Question: <ins> // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // RFC 736 (and Issue 21407): functional struct update should respect privacy. // The `foo` module attempts to maintains an invariant that each `S` // has a unique `u64` id. use self::foo::S; mod foo { use std::cell::{UnsafeCell}; static mut count : UnsafeCell<u64> = UnsafeCell { value: 1 }; pub struct S { pub a: u8, pub b: String, secret_uid: u64 } pub fn make_secrets(a: u8, b: String) -> S { let val = unsafe { let p = count.get(); let val = *p; *p = val + 1; val }; println!("creating {}, uid {}", b, val); S { a: a, b: b, secret_uid: val } } impl Drop for S { fn drop(&mut self) { println!("dropping {}, uid {}", self.b, self.secret_uid); } } } fn main() { let s_1 = foo::make_secrets(3, format!("ess one")); let s_2 = foo::S { b: format!("ess two"), ..s_1 }; // FRU ... //~^ ERROR field `secret_uid` of struct `foo::S` is private println!("main forged an S named: {}", s_2.b); // at end of scope, ... both s_1 *and* s_2 get dropped.  Boom! } </ins>

That out of the way, an additional possibility, let's call it 6., for list: We could just make the "abstract type" vs. "data type" distinction based on "does or doesn't the type have a private field". This doesn't entirely fill me with satisfaction (as with "worse is better" solutions in general), with specific drawbacks being that it doesn't extend cleanly to the nullary case (no fields at all), and that in terms of UX a change of semantics based on the presence or absence of a private field may be unexpected, but on the plus side, it's simpler, and would, I think, work.
Sure, hypothetical show-stopper issues could cause us to revisit our self-imposed schedule. I personally don't think that this issue, on its own at least, provides sufficient motivation for schedule revision. I admit that your draft RFC seems like it addresses a host of issues, so maybe all of them taken in unison would be a different story. (But then again, that's not even my call to make.)
There were a couple more options that I should have put on the list, for completeness, but overlooked. 6 note, the "has any private fields ==abstract-type; all public fields ==data-type", is one of them. This would (probably) be less work than adopting the draft RFC in full, but I am not sure what the other Advantages/Disadvantages are. I invite others to write an Advantages/Drawbacks for this approach (perhaps in an RFC PR). 7 We could add a way for a struct to opt-out of FRU support entirely. So in this approach, one would attach the appropriate attribute to , , etc. Advantages: won't break any existing code Drawbacks: Seems quite fragile; we may be good about auditing our own stdlib, but clients who are not aware of the attribute may inadvertently expose themselves to the same bug that currently plagues .
Also, I just wanted to mention: when I wrote my comment 6 hours ago, I came to the keyboard thinking that the FRU support for adding new private fields to and having still work was an important use case. But after some reflection in the hours since, supporting that use case does not seem as important to me.


Question: <ins> // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // RFC 736 (and Issue 21407): functional struct update should respect privacy. // The `foo` module attempts to maintains an invariant that each `S` // has a unique `u64` id. use self::foo::S; mod foo { use std::cell::{UnsafeCell}; static mut count : UnsafeCell<u64> = UnsafeCell { value: 1 }; pub struct S { pub a: u8, pub b: String, secret_uid: u64 } pub fn make_secrets(a: u8, b: String) -> S { let val = unsafe { let p = count.get(); let val = *p; *p = val + 1; val }; println!("creating {}, uid {}", b, val); S { a: a, b: b, secret_uid: val } } impl Drop for S { fn drop(&mut self) { println!("dropping {}, uid {}", self.b, self.secret_uid); } } } fn main() { let s_1 = foo::make_secrets(3, format!("ess one")); let s_2 = foo::S { b: format!("ess two"), ..s_1 }; // FRU ... //~^ ERROR field `secret_uid` of struct `foo::S` is private println!("main forged an S named: {}", s_2.b); // at end of scope, ... both s_1 *and* s_2 get dropped.  Boom! } </ins>

Here is why: It is relatively easy for a developer who wants to provide that sort of extensible abstraction can still do it, by factoring the type into a all-public front-end with a single public field that holds the all-private back-end, like so: So, given that there exists a reasonable pattern to bring back usable FRU even under the option "(3.) change FRU into a non-hygienic expansion into the record construction form with all fields listed, in the sense that is synonymous with and subject to privacy checks.", I would not object to us adopting (3.) aka solution.
I think that "has any private field" is a decent way to handle abstractness (you can always add a private unit field). On the other hand, Rust supports trait bounds of types – these should handle roles just fine – you shouldn't be able to coerce past a trait bound. By the way, this is somewhat subtle, because coercing to is wrong (as it leaks memory – it coerces past the implicit bound), but coercing to is fine (as the bound isn't used by ). However, this isn't a property of – you still can't coerce to – so we probably want a relatively-sophisticated way to occasionally ignore roles.
I mean, Rust already has a mechanism for ensuring representation-abstraction – private fields – which are semantic (they are handled after type-checking, we probably want to handle them during it, but they definitely aren't handled syntactically or during resolution). It is just that FRU currently accesses them improperly. Also, it doesn't have much to do with e.g. roles – is an abstract type, but it doesn't use any bound on . only uses the implicit bound. A for data-only types would be nice, through.
Another alternative came to me while I was drafting an RFC about this. (But its an alternative that I do not particularly like.) 8a Instead of making "has any private fields" the thing that makes FRU unavailable, instead make the rule be "has all private fields." Thus types like and will not be subject to the vulnerability outlined here. Adding a single field to an otherwise private struct is what changes the nature of a struct with respect to abstraction and FRU, rather than adding a single non- field to an otherwise public struct.


Question: <ins> // Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // RFC 736 (and Issue 21407): functional struct update should respect privacy. // The `foo` module attempts to maintains an invariant that each `S` // has a unique `u64` id. use self::foo::S; mod foo { use std::cell::{UnsafeCell}; static mut count : UnsafeCell<u64> = UnsafeCell { value: 1 }; pub struct S { pub a: u8, pub b: String, secret_uid: u64 } pub fn make_secrets(a: u8, b: String) -> S { let val = unsafe { let p = count.get(); let val = *p; *p = val + 1; val }; println!("creating {}, uid {}", b, val); S { a: a, b: b, secret_uid: val } } impl Drop for S { fn drop(&mut self) { println!("dropping {}, uid {}", self.b, self.secret_uid); } } } fn main() { let s_1 = foo::make_secrets(3, format!("ess one")); let s_2 = foo::S { b: format!("ess two"), ..s_1 }; // FRU ... //~^ ERROR field `secret_uid` of struct `foo::S` is private println!("main forged an S named: {}", s_2.b); // at end of scope, ... both s_1 *and* s_2 get dropped.  Boom! } </ins>

8b, which is so similar to 8a that I gave them both the same numeral: Outlaw the trivial FRU form . That is, to use FRU, you have to use at least one field in the constructing expression. Again, this implies that types like and will not be subject to the vulnerability outlined here. (This may be a decent change to make to the language regardless of whatever else happens on this ticket; the only argument in favor of keeping support for such a trivial form is maybe for supporting certain macro-expansions. But fully-general macro-authors already have to tread very carefully around corner cases on structs, due to issues like the empty braces problem (see )
That would leave the vulnerability intact in the case where the type has both public fields and private fields, the fact that no such type currently exists in the standard library notwithstanding (just as a very artificial demonstration, consider a with ).
yep. Library authors would have to factor their structures very carefully. (I described the drawback you mention in the RFC I posted shortly after you wrote your comment, though I did not include the detail of having the private fields be , which does seem like it could make the situation all the more subtle. Not insurmountable, but a definite drawback.) Just to be clear, I'm not saying I prefer (8a) or (8b); I'm just trying to be complete in my exploration of the solution space.
Repurposed as the tracking issue for rust-lang/rfcs
I'll just go snag


Question: /// # Examples /// /// ```no_run <del> /// #![feature(buffered_io_capacity)] </del> /// use std::io::BufWriter; /// use std::net::TcpStream; ///

adds methods to and . Unresolved questions:
Can I nominate this for stabilization? It's a straightforward API with no real alternatives possible, and I had a real-world use case for it recently.
CC --^?
fcp merge
Team member has proposed to merge this. The next step is review by the rest of the tagged team members: [x] [ ] [x] [x] [ ] No concerns currently listed. Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up! See for info about what commands tagged team members can give me.
:bell: This is now entering its final comment period, as per the . :bell:
The final comment period, with a disposition to merge, as per the , is now complete. As the automated representative of the governance process, I would like to thank the author for their work and everyone else who contributed. The RFC will be merged soon.


Question: <ins> error: unused pinned `MustUsePtr` that must be used --> $DIR/must_use-pin.rs:42:5 | LL |     pin_must_use_ptr(); |     ^^^^^^^^^^^^^^^^^^ | note: the lint level is defined here --> $DIR/must_use-pin.rs:1:9 | LL | #![deny(unused_must_use)] |         ^^^^^^^^^^^^^^^ error: unused pinned boxed `MustUse` that must be used --> $DIR/must_use-pin.rs:44:5 | LL |     pin_box_must_use(); |     ^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors </ins>

<!-- Thank you for filing a bug report! Please provide a short summary of the bug, along with any information you feel relevant to replicating the bug. --Defining traits that contain methods that return such a type: The compiler should probably have warned me about not using the of the , consistent with the behaviour of async functions in Rust 1.67.0. This will also work without the need for traits but async traits is one of the most common use cases for such a type. <!-- If you're using the stable version of the compiler, you should also check if the bug also exists in the beta or nightly versions. --: <!-- Include a backtrace in the code block by setting in your environment. E.g. . --<details<summaryBacktrace</summary<p</p</details<!-- TRIAGEBOTSTART --<!-- TRIAGEBOTASSIGNSTART --<!-- TRIAGEBOTASSIGNDATASTARTTRIAGEBOTASSIGNDATAEND --<!-- TRIAGEBOTASSIGNEND --<!-- TRIAGEBOTEND --
We looked at this as the wg-async triage meeting today. We agree this is a bug and that the behavior should be consistent with on and/or . This is also likely a good first issue for someone wanting to contribute to async.
Would you say this is also a good issue for a first-time contributor to Rust? I'm not super familiar with the language, but I want to contribute to open source compilers, so I'm hoping to potentially take on this task.
Can I take this ?
Either one of you ( or are welcome to work on this! If it's your first time contributing to Rust, it might take a while to ramp up on it, but I find the best way to do that is to just do it. If you decided to have a go at it, feel free to ask any questions you have either here or in . I tend to watch #wg-async closer than GitHub issues, so you'll probably get a more prompt reply there.
this issue wasn't claimed so you are free to claim and work on it if you still are interested. Kindly comment with to claim the issue.
claim
This is also a very special case of


Question: without modifying the original"] #[inline] #[track_caller] <del> #[rustc_inherit_overflow_checks] #[allow(arithmetic_overflow)] </del> pub const fn ilog10(self) -> u32 { <del> match self.checked_ilog10() { Some(n) => n, None => { // In debug builds, trigger a panic on None. // This should optimize completely out in release builds. let _ = Self::MAX + 1; 0 }, } </del> <ins> self.checked_ilog10().expect("argument of integer logarithm must be positive") </ins> } /// Returns the logarithm of the number with respect to an arbitrary base,

Filing since it's in pFCP over at , and I don't think we can reasonably change it after stabilization (especially since it's documented). Currently, in release mode evaluates to . (And same for the other bases.) It's not obvious to me that that's necessarily the best option. For example, the implementation is slightly nicer on CPUs from the past or so (and I think would be just as nice on older ones ), but gives <subas u32</subin the wrapping case. It also might be nice to have the wrapping case give something clearly different from any of the successful cases, rather than having and give the same thing. For example returns in release mode, which isn't a power of two (according to ), so it's distinguishable from all the non-wrapping cases. This only affects // on . (The checked versions don't have an issue, nor do the ones on .)
I couldn't find any previous discussion of what the exact wrapping value ought to be, just that there ought to be one, as opposed to a . There was this note: For which I think the implementation I mention above is a counter-example, albeit only for the base-2 case. Also, currently in release mode is essentially , so we can pick any value we want to return for those cases. FWIW, the implementation in gives as the result for .
In Rust we try to do the right thing. Not even Python gives -1. Let's avoid in-band error values in Rust.
What's your proposal for what the "right" thing is, then? That panic in release too? Arguably the most-correct value is −∞ (like ), but that doesn't fit in any of our integer types. So would make sense, but release mode for the other un-prefixed things is wrapping, not saturating.
Python has some functions that return in-band values: "xy".find("y") 1 "xy".find("z") -1 From Rust I expect something better. In Rust if a function isn't naturally total and you can't restrict its input, then I expect it to return Option (or Result), or when that's isn't ergonomic enough, a panic (in release too). Returning -1 is dangerous as that Python find function, returning 0 is not math.


Question: without modifying the original"] #[inline] #[track_caller] <del> #[rustc_inherit_overflow_checks] #[allow(arithmetic_overflow)] </del> pub const fn ilog10(self) -> u32 { <del> match self.checked_ilog10() { Some(n) => n, None => { // In debug builds, trigger a panic on None. // This should optimize completely out in release builds. let _ = Self::MAX + 1; 0 }, } </del> <ins> self.checked_ilog10().expect("argument of integer logarithm must be positive") </ins> } /// Returns the logarithm of the number with respect to an arbitrary base,

I think returning (wrapped if necessary) is a clear distinguish between normal and error result. Returning an is not ideal currently because it will makes the function practically unusable in const context (before const unwrap is stabilized) If getting closest to the "correct" math answer, how about choosing ? However it seems weird and still seems better to me
Perhaps in other languages. Rust is known for being better than that. I have chosen to use Rust because it's a bit better than Python (see above). Let's return Option and and wait for const unwrap to be stabilized before making ilog const, then.
That's what does already. Is your proposal, then, that the version of just shouldn't exist on ? How do you square that with precedent of other things -- like or -- that have the version return , but the un-prefixed one wrap in release mode?
what about treating it like division by zero and just panicking?
I'd be fine with -1. The point of these methods is to get fast code (otherwise many won't use them and will prefer to do to keep the code branchless and avoid the ugly ) and a defined value outside of the usual input range. (from above) is a good example. If you want stricter guarantees than that, you can use .
A minor point: being 0 is actually a reasonable choice - even though 0 is not a power of two, it is congruent to the correct power of two modulo 2^32 (which is 2^32 itself), so exactly what is expected in wrapping arithmetic. But unfortunately there's no "−∞ mod 2^32" that could be used for .
Modular arithmetic is confusing in the context of logarithm, if you want to return the discrete logarithm of 0 in the release mode, then there are a lot of candidates, because (in case of ) therefore in the sense of modular arithmetic, could be any multiple of . If you really want to achieve something close to , then I guess the best value is as I mentioned above. (Interestingly though, = , which is a multiple of 8, 16, 32, 64, 128)
That's certainly a possibility. suggested not doing that back in the original PR, though:
Doesn't implicitly include a check for zero in the code generated?


Question: without modifying the original"] #[inline] #[track_caller] <del> #[rustc_inherit_overflow_checks] #[allow(arithmetic_overflow)] </del> pub const fn ilog10(self) -> u32 { <del> match self.checked_ilog10() { Some(n) => n, None => { // In debug builds, trigger a panic on None. // This should optimize completely out in release builds. let _ = Self::MAX + 1; 0 }, } </del> <ins> self.checked_ilog10().expect("argument of integer logarithm must be positive") </ins> } /// Returns the logarithm of the number with respect to an arbitrary base,

]
Also, since the methods are implemented for signed integers as well, another issue would be the log of negative values. For example for floating-point, would return −∞, but would return NaN. So if would return some value for −∞, would panic anyway, or return some value?
I don't think it makes sense to do anything other than panic in the case of negative values, which in turn is probably an argument for panicking on zero as well. I guess one could argue that "wrapping" could be interpreted as wrapping the preimage to fit in the function's domain (rather than just wrapping the image to fit in the range) but IMO that would be entirely unintuitive and unhelpful as well. After thinking about it a bit, it seems to me that simply cannot have a meaningful variant, because semantics (as reasonably interpreted) cannot answer the question "what should the result be for values for which the original function is undefined?" There are no elements in 's domain for which the function underflows or overflows.
That's only the case on old chips. As I linked in the OP (), that happens in the instruction generation very-last-phase of LLVM on old chips, and on newer chips it knows to emit a different instruction instead of the branching code: The good news is that it looks like newer LLVM has gotten smarter here. It used to be that, because of how the intrinsic gets translated, it would emit obviously-redundant assembly on old chips in some code patterns, as you could see in Rust 1.16:
is supposed to find the largest so that . Since computers use wrapping arithmetic, the equation is better put as . The largest satisfying this equation in the case is (aka ). So if we consider a wrapping to be the inverse of , makes perfect sense (and is very efficient on modern CPUs, as others have pointed out). I would also advocate for to be as a method which always has this behaviour. [Edit: it already behaves that way]
Note that's already how works . It's just that it wraps to in release right now -- this issue doesn't propose removing the panic in debug behaviour, just to figure out what the best value for release would be.


Question: without modifying the original"] #[inline] #[track_caller] <del> #[rustc_inherit_overflow_checks] #[allow(arithmetic_overflow)] </del> pub const fn ilog10(self) -> u32 { <del> match self.checked_ilog10() { Some(n) => n, None => { // In debug builds, trigger a panic on None. // This should optimize completely out in release builds. let _ = Self::MAX + 1; 0 }, } </del> <ins> self.checked_ilog10().expect("argument of integer logarithm must be positive") </ins> } /// Returns the logarithm of the number with respect to an arbitrary base,

Since, from the notes, it seems like the libs-api meeting today said "how about we panic instead of wrap", I'll try to answer my own question from above: I would propose the following rule: Conceptually, the result is first calculated in true ℤ (aka to infinite precision). Then for the non-prefixed versions If that result is undefined (, , etc), then it panics (regardless of compilation mode) If that result is defined and fits in the result type, it's returned. If that result is defined but not in-range for the result type, it panics if overflow checking is enabled, and wraps (mod 2<supN</supfor uN) if overflow checking is disabled. I think that's consistent with all the current precedent. ( also is good reading about the distinction I'm drawing here.)
I would redefine that to include cases where the result is defined but you can't wrap that to the result type, e.g. or . that would cover and
I agree, but was considering that implied by "in ℤ", as that set includes neither −∞ nor ⅈ. (Like how is , not a complex number.)
I'm not necessarily against panicking in that case. I just pointed out how it's a bit inconsistent with the other operations we have on integers. (Whether it makes sense for the other operations to have this difference in behavior between debug and release mode is an interesting discussion too, but I'm afraid that ship has sailed.) The reason we don't always panic on overflow for and etc. is performance. It's simply too costly to do. (We always panic on division by zero because that's both mathematically undefined (even modulo 2<supBITS</sup) and because on some platforms, the native division instruction will signal/abort/trap the program when the right hand side is zero.) We applied the same reasoning to things like and , although one might reasonably argue that for those it might be fine to always panic, since these are not as common as and . (You could then still use if you really want to make sure there's no check, if you're sure it's unnecessary.) That seems reasonable. It'd be nice if it'd still be easy to get the efficient calculation through some usage of or though.


Question: without modifying the original"] #[inline] #[track_caller] <del> #[rustc_inherit_overflow_checks] #[allow(arithmetic_overflow)] </del> pub const fn ilog10(self) -> u32 { <del> match self.checked_ilog10() { Some(n) => n, None => { // In debug builds, trigger a panic on None. // This should optimize completely out in release builds. let _ = Self::MAX + 1; 0 }, } </del> <ins> self.checked_ilog10().expect("argument of integer logarithm must be positive") </ins> } /// Returns the logarithm of the number with respect to an arbitrary base,

It looks like llvm isn't smart enough today to turn into simply a count-leading-zeros and a subtract instruction. :(
We discussed this again in the libs-api meeting, and we concluded pretty much the same as rule, meaning that these functions should panic on zero in all compilation modes, since there's not a modulo-2<supN</sup-correct result.


Question: <ins> // https://github.com/rust-lang/rust/issues/69228 // Used to give bogus suggestion about T not being Sized. use std::mem::size_of; fn foo<T>() { let _arr: [u8; size_of::<T>()]; //~^ ERROR generic parameters may not be used in const operations //~| NOTE cannot perform const operation //~| NOTE type parameters may not be used in const expressions } fn main() {} </ins>

Example: Results in the following error: of course, is by default unless you say , so the error and the suggestion are clearly wrong. And if you do say explicitly, you get Note being suggested, which is ~not even valid syntax~ apparently valid syntax, but not something you would write. I expected to see this happen: Either this compiles cleanly Or the compiler emits a different error that makes sense <!-- If you're using the stable version of the compiler, you should also check if the bug also exists in the beta or nightly versions. --: (Seems to happen on nightly too.) </details
Duplicate of
Reopening to track the error message, which is not tracked by . is just wrong.


Question: <ins> // run-pass #![feature(const_mut_refs)] static mut TEST: i32 = { // We must not promote this, as CTFE needs to be able to mutate it later. let x = &mut [1,2,3]; x[0] += 1; x[0] }; // This still works -- it's not done via promotion. #[allow(unused)] static mut TEST2: &'static mut [i32] = &mut [0,1,2]; fn main() { assert_eq!(unsafe { TEST }, 2); } </ins>

Consider the following code: This should just work. But instead it throws an error: The reason for this is that gets lifetime extended via promotion, so this reference now points to a separate mutable static -- but mutable statics cannot be mutated during CTFE. I see no way to fix this, other than stopping to promote mutable references -- which we should IMO do anyway, they are a very strange and unprincipled special case. Just imagine doing this in a loop, suddenly all these different and mutable allocations share the same address... Cc
Ugh, that's an ancient rule (believe it or not, it's a workaround for not being able to write and have the length be inferred!) and it was never meant to get this far, I guess I didn't think it through properly when adding the "outermost scope" rule, which is the only position where allowing it makes sense. In the current implementation, it should've never been promoted, only allowed, my bad!


Question: pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str = "attributes of the form `#[derive_*]` are reserved for the compiler"; <del> pub const EXPLAIN_LITERAL_MATCHER: &'static str = ":literal fragment specifier is experimental and subject to change"; </del> pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str = "unsized tuple coercion is not stable enough for use and is subject to change";

Tracking issue for rust-lang/rfcs.
Is anyone working on implementation already? If not I can take a crack at it.
I'll probably do it.
Huh oh, we have an issue already: do we mean to include potentially minus-prefixed literals? If yes, we have a problem because 1. it means we have to return an Expr instead of a Lit, which means I'm not sure one will be able to use the bound fragment in a non-expr context (for example in a static array type?) and 2. it's no longer always a single-TT, so the benefits in terms of future-proofing are a bit less good. If we don't... well, we loose expressivity. I have no idea what is more intuitive though... Would you, as a Rust user, expect to parse ? I certainly can think of use cases for this...
good point. I think I would have expected it, I also agree with the complications.
Can't we upgrade Lit to support negative literals?
I'd expect "literal" (or a future integer-literal specifier) to include (negative 5), but not (the negation of positive 5). Perhaps that expectation doesn't match reality, though. For instance, based on parsing rules for non-literals, I'd expect to act like . So, if handling both and as literals makes this easier, that works. But "literal" definitely needs to include negative numbers, or we'd have a weird user trap to explain.
I'd expect "literal" (or a future integer-literal specifier) to include -5 (negative 5), but not - 5 (the negation of positive 5). Unary operators, including minus, are processed purely by the parser at the moment, no lexer involved. So their treatment is whitespace agnostic. (I personally think this is a good thing.)
I agree with is not syntactically different from and has no reason to be. But I also agree with the fact that the user will probably expect negative numbers to work as literals (even it – syntactically – they're not).
is also supported in literal patterns while arbitrary expressions are not. It'd be reasonable to support it in fragments as well.
Another thing that won't match is a macro call, like , or any of the other macros that I think of as expanding to a literal (, ...).


Question: pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str = "attributes of the form `#[derive_*]` are reserved for the compiler"; <del> pub const EXPLAIN_LITERAL_MATCHER: &'static str = ":literal fragment specifier is experimental and subject to change"; </del> pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str = "unsized tuple coercion is not stable enough for use and is subject to change";

I dunno, maybe this is not such a good idea after all. Re-reading the RFC in a more skeptical light, I felt like the "Motivation" section could use some more concrete use cases. Maybe this is just failure of imagination on my part, though! I think the likelihood of this feature attracting people who really want constant expressions should be acknowledged as a drawback, too.
That's fine IMO. Personally I'd like it to match only explicit literals in code to distinguish, for example, between literal and identifier and produce different code for them. Right now this is not possible because all of , , are too broad and conflict with each other.
Hi All, I have implemented this feature in my fork of Rust over 1.25.0, under this branch: Following a quick review by a rustc mentor I may have the free time to provide a full pull request for this.
BTW label has the tooltip "implemented in nightly and unstable" but I did not see it there, i.e. commits & pull requests referencing this. Did I miss it?
The implementation that I worked on was merged, yay!
Is there anything stopping an FCP for this?
It's currently merged in unstable; do you mean an FCP to declare it stable?
Yes, an FCP to stabilise. Should have clarified.
Currently, it is not possible to pass a literal from a macro to another macro. . I think this is a bug.
Interesting! That is a bug. I opened to track it.
Agreed, this should be allowed just like passing any other node types.
Is there anything else preventing this from being stabilized? The issue above has been fixed.
This has baked for some time now and I believe it should be ready for stabilization. So let's start the review. merge The feature gate test is here: Unstable book: Tests defined here:
Team member has proposed to merge this. The next step is review by the rest of the tagged teams: [x] [x] [x] [x] [x] [ ] [x] [x] [x] [ ] No concerns currently listed. Once a majority of reviewers approve (and none object), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up!


Question: pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str = "attributes of the form `#[derive_*]` are reserved for the compiler"; <del> pub const EXPLAIN_LITERAL_MATCHER: &'static str = ":literal fragment specifier is experimental and subject to change"; </del> pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str = "unsized tuple coercion is not stable enough for use and is subject to change";

See for info about what commands tagged team members can give me.
Reading through the tests, I see that is a literal. While that makes sense to me, I remember hearing that it wasn't, but was instead a negation operator and a literal. Am I misremembering?
cc on
I agree that it makes sense. I would say that even if is interpreted as negation + a literal, I would probably still want the macro matcher to accept since that behavior seems more intuitive. In other words, I would see being more as an implementation detail than what a literal is in the mental model.
I think that the nuance with causes a bit of a problem, because I don't think it should be treated as a literal, but I also don't think that the current implementation of would allow detecting it either. You could naïvely allow but that would allow which is clearly wrong.
there are tests currently implemented that verify that is detected as a literal.
I worded that wrong; I meant that only having a matcher and not being able to distinguish strings and numbers means that you can't easily make not a literal.
for procedural macros the input as lexed by the compiler is (two tokens) but procedural macros can create tokens that are negatives (like ). In that sense matching for makes sense to me.
Are literals generated by the compiler counted as true literals? A quick example would be something like: This fails to match, as the expansion, I guess, happens after the selection. I just naively assumed that would have worked.
is not a literal generated by the compiler, it is an identifier followed by an exclamation mark followed by a set of parentheses containing some tokens. See for example: If you were to use it in expression position, it would be interpreted as an invocation of which expands to a string literal. In this case and in your macro though, it is never in a syntactic position where it would be treated as an expression.
I can understand semantically why it doesn't make sense, I just thought it would have, but that being said, I already changed it to , so there's no issue. It just made more sense to me as a literal, because according to the compiler, it could generate a literal from it. I guess it was more a question than an actual issue.
This is true, but there's more to it!


Question: pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str = "attributes of the form `#[derive_*]` are reserved for the compiler"; <del> pub const EXPLAIN_LITERAL_MATCHER: &'static str = ":literal fragment specifier is experimental and subject to change"; </del> pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str = "unsized tuple coercion is not stable enough for use and is subject to change";

A few built-in macros can expand their arguments eagerly through ~m a g i c~, so they accept and likes even if they expect string literals: Fortunately (or not), this currently cannot be done in user-defined macros.
I actually just realised that I can't change it to , as it's used in . So, I've just had to manually unroll the macro. ! It doesn't look pretty. :( Ninja edit: I just tested what actually happens if you try to pass in a non-literal with . It rejects it the exact same way. Does the already make use of this feature? If not, the seems to propagate the required token. Oh, unless the compiler steps in... That's actually probably the case... I've reverted it back to the type.
:bell: This is now entering its final comment period, as per the . :bell:
The final comment period, with a disposition to merge, as per the , is now complete.
Since you implemented this, would you be willing to write up the stabilization PR?
sure
This appears to be missing from the Rust reference


Question: exit_success_if_unwind::bar(do_panic); } } <del> let s = Command::new(env::args_os().next().unwrap()).arg("foo").status(); </del> <ins> let mut cmd = Command::new(env::args_os().next().unwrap()); cmd.arg("foo"); // ARMv6 hanges while printing the backtrace, see #41004 if cfg!(target_arch = "arm") && cfg!(target_env = "gnu") { cmd.env("RUST_BACKTRACE", "0"); } let s = cmd.status(); </ins> assert!(s.unwrap().code() != Some(0)); }

The AVR-Rust post continues to track AVR-LLVM, which is tracking upstream LLVM. That means we are running into changes from the future LLVM 4.0. I figured we could open up this issue now to track the changes required to stay compatible. This is the current list of upgrade hazards. Note that some of the text may be nonsensical as I don't truly grok all the internals of LLVM so some changes are wild stabs in the dark. It's also possible that some failed fix for earlier problems actually caused later problems: [x] DIDescriptorFlags became a real C++ enum and not a bitset () [x] An EH personality is required for every function that can unwind () [x] pass changed header and constructor name () [x] changed API () [x] Bitcode/ReaderWriter.h has been renamed / API changed () () [x] changed API () [x] changed API () [x] prefers over () [x] string type changes () [x] is not guaranteed to be null terminated () [x] changed return types () [x] Archive support changed error handling types () [x] Teach Rust about an LLVM 4.0 API change for creating debug info for global variables () [x] Check all errors in LLVMRustArchiveIterator API () [x] Upgrade emscripten (kripken/emscripten-fastcomp, kripken/emscripten-fastcomp-clang) [x] Alignment now represented with 32 bits instead of 64 () [x] API changed again () [x] now takes an instead of a and () [x] Symbol lookup error when linking dylibs () [x] Undefined behavior in tests () [x] Unoptimised builds of compilerbuiltins on ARM have references to () A WIP PR that performs the upgrade! Some issues whose resolution is believed to be blocked on LLVM 4.0: [ ]
Next time we do this upgrade we'll need emscripten to do it to. It would be good if we could pull in a working llvm wasm backend in the same upgrade, but that may not be ready before the end of the year.
For the record, I am also working with a fork of LLVM that is tracking upstream (not AVR-LLVM but similar in spirit) and am starting to work on this now.


Question: exit_success_if_unwind::bar(do_panic); } } <del> let s = Command::new(env::args_os().next().unwrap()).arg("foo").status(); </del> <ins> let mut cmd = Command::new(env::args_os().next().unwrap()); cmd.arg("foo"); // ARMv6 hanges while printing the backtrace, see #41004 if cfg!(target_arch = "arm") && cfg!(target_env = "gnu") { cmd.env("RUST_BACKTRACE", "0"); } let s = cmd.status(); </ins> assert!(s.unwrap().code() != Some(0)); }

I'm looking through the AVR-Rust commits and I'd love to coordinate --- feel free to ping me on IRC () or via mail!
Note that there is a regression reported against llvm 4.0 regarding the powi intrinsic on armhf targets: I'm explicitly mentioning this here, because there were previously problems with it, see and related issues. Also cc rust-lang-nursery/compiler-builtins, an issue about the same problem in the compiler-rt rust port.
To clarify what I think the is referring to (correct me if I'm wrong) In LLVM 3.9 and before, the calling convention LLVM used with the powidf2 and powisf2 intrinsics was basically the C calling convention In LLVM 4.0, the backend was corrected to expect these intrinsics to have the aapcs calling convention One person that aapcs is expected for powis2f and powid2f, while another a claiming that the normal C calling convention should be used. So it seems that if the LLVM change is not reverted (expected powisf2 to be aapcs) then we need to update our definition. This is going to be a huge PITA for supporting multiple LLVM versions as well. We need to select the calling convention depending on the LLVM version as well...
Any objections to doing that coordination here on GitHub, or on one of our forks?
I don't have strong preferences for the communication channel.
should address what is listed as API changes" above (the core of the change is in how attributes are represented).
I would prefer to upstream LLVM 4.0 compatibility patches sooner rather than later. That includes my own work obviously, but I'm also looking at the commits I cherry-picked from AVR-Rust. In particular, looks like a reasonable simplification even independent of LLVM 4.0 compatibility, and looks like a nice little self-contained fix. Could you create PRs for those? (If you don't have the time but are otherwise fine with upstreaming, I'd be happy to manage that, giving proper credit of course.)
Absolutely! I wasn't really sure how much we could expect LLVM 4 to change as it goes towards stable / how much churn the Rust maintainers would want to put up with. I'll get those pulled out and submitted soon. I think I'm also starting to understand some of the silly error handling that the new LLVM does.


Question: exit_success_if_unwind::bar(do_panic); } } <del> let s = Command::new(env::args_os().next().unwrap()).arg("foo").status(); </del> <ins> let mut cmd = Command::new(env::args_os().next().unwrap()); cmd.arg("foo"); // ARMv6 hanges while printing the backtrace, see #41004 if cfg!(target_arch = "arm") && cfg!(target_env = "gnu") { cmd.env("RUST_BACKTRACE", "0"); } let s = cmd.status(); </ins> assert!(s.unwrap().code() != Some(0)); }

Awesome, thanks in advance!
BTW the PR reference for "llvm::AttrBuilder changed API" is wrong, it points at this issue instead of
Does anyone have ETA? I'd like to know when I can use AVR. :)
You should follow along at avr-rust/rust for the AVR-specific issues. Upgrading to LLVM 4 will not magically yield AVR support.
Ok, thank you!
I've created for the API change.
I've also created for another debug info API change.
After putting all of those patches on top of master, was successfully built. I got several undefined references, most likely due to my local LLVM setup.
I think the next step after all those patches land is to allow LLVM 4.0 in the configure/rustbuild scripts and then actually update the submodule.
We'll also need to fix that AAPCS bug first, I just noticed it
Don't forget : I think that means that the Rust fork of LLVM is following the Emscripten fork of LLVM, thus Emscripten needs to upgrade to LLVM 4.0 / master before Rust can.
And I'm hoping to supersede it with
I just ran into which changed the alignment from u64 to u32. Will think about a proper fix later, unless someone beats me to it (but should merge first to avoid further conflicts).
And it says So, that will be "exciting".
Is there much left blocking an upgrade?
This: Has to be done too but I don't know if it's currently being worked on. Any info on that ^?
No nobody is actively working on an emscripten upgrade. Since even when that is done it will probably take a lot of work to land an LLVM upgrade, there's probably more we can do to prepare. Once we decide we want to do it, somebody can prepare a patch to throw at the bots. It seems likely stuff will not work and it will be a slog to fix it all, which will give us time. We don't need emcc to generate wasm stds, just a fairly small patch on our LLVM branch that will hopefully port without much difficulty. So if somebody feels motivated, it's not too soon to start going after it. As to the emscripten upgrade, we should at least let know that we're starting to think seriously about doing the upgrade, and need emscripten to upgrade LLVM too.


Question: exit_success_if_unwind::bar(do_panic); } } <del> let s = Command::new(env::args_os().next().unwrap()).arg("foo").status(); </del> <ins> let mut cmd = Command::new(env::args_os().next().unwrap()); cmd.arg("foo"); // ARMv6 hanges while printing the backtrace, see #41004 if cfg!(target_arch = "arm") && cfg!(target_env = "gnu") { cmd.env("RUST_BACKTRACE", "0"); } let s = cmd.status(); </ins> assert!(s.unwrap().code() != Some(0)); }

It seems like that could be a big effort. Another alternative is to use the LLVM wasm backend, but I still have not heard that it is generally usable yet. cc
I can look into the effort needed to update emscripten's fastcomp LLVM version, but I need to know a commit to aim for. Sounds like the goal here is 4.0, which hasn't released yet, so I guess I have to wait on that?
So far as AVR is concerned, any commit within the last month will do. There will likely be a few more months until 4.0 is actually tagged (every ~6 months a new release is made). It is quite common for projects to track LLVM master, which I'm personally a fan of.
But is it common to release snapshots from LLVM master? When LLVM itself only releases every 6 months, it seems incongruous for Rust to pick arbitrary snapshots in its 6-week release cycle.
LLVM 4.0 will branch in a week and the final release will happen in late feburary (schedule says 21st for final tag, but this is flexible IIRC).
From the llvm-dev mailing list:
branch has happened
An update on the "powidf2 / powisf2 calling convention changed" situation: The regression has been fixed on llvm master () however from what I can tell the fixes are not yet in the 4.0 branch, although the fix may be backported ().
I've started working on updating emscripten kripken/emscripten-fastcomp kripken/emscripten-fastcomp-clang I've also created a new bug requesting that the regression fix be merged into 4.0 .
says the emcc LLVM upgrade is ready to go. or are we prepared to begin the Rust LLVM upgrade? I think what needs to happen is to submit the Rust PR and start throwing it against the bots. Once it looks like that is close to landing then we'll have to coordinate both project's upgrades to minimize the breakage window where rustc and emcc have different backends. I'm not sure how best to do that - we might just try to upgrade as simultaneously as possible and accept up to a few days of breakage, or we might ask emscripten to stage their build such that they can swap their incoming branch right after we land to master.


Question: exit_success_if_unwind::bar(do_panic); } } <del> let s = Command::new(env::args_os().next().unwrap()).arg("foo").status(); </del> <ins> let mut cmd = Command::new(env::args_os().next().unwrap()); cmd.arg("foo"); // ARMv6 hanges while printing the backtrace, see #41004 if cfg!(target_arch = "arm") && cfg!(target_env = "gnu") { cmd.env("RUST_BACKTRACE", "0"); } let s = cmd.status(); </ins> assert!(s.unwrap().code() != Some(0)); }

needs to know the exact LLVM commit we're moving to as well, and that will become clear once the PR starts working through the queue. The stars are aligning. Let's make this happen. Thanks for doing the fastcomp upgrade.
We are not fully compatible with LLVM 4.0. I have heard from at least one person (on IRC) that building against stock LLVM 4.0 (RC) does not work. I haven't personally inspected all failures, but there's at least two things still missing: (and possibly ). It shouldn't be a conceptually difficult patch to apply the equivalent changes to rustc, but possibly a big diff. I haven't digested the implications yet, but it might be a relatively simple change localized to the function in that currently calls .
The fix has been merged into the 4.0 release (). I'm going to try and build Rust against stock LLVM 4.0 and figure out what needs modifying.
On top of what mentioned: now takes an instead of a and ()
I've got a half-baked patch to use the new signature for I'm not familiar enough with Rust internals to finish it off. I ran into a problem in as it is given a but in order to use we need a . We need to call in order to build an instance of .
I've opened for the change that mentioned. I've also opened for the 32-bit alignment change. I believe that is the only thing we need to update aside from these two PRs in order to get the compiler to successfully be built with LLVM 4.0.
So to summarize where we are with LLVM 4 (correct me if I'm wrong): 4.0 will be released in about 1 week (2/21). are no known issues with supporting LLVM 4.0, but there are probably issues that will be discovered once we try to use it in nightlies. runs on in-tree LLVM + LLVM 3.7 (so PRs haven't actually been tested on LLVM 4.0 yet). support LLVM back to ~3.6(?


Question: exit_success_if_unwind::bar(do_panic); } } <del> let s = Command::new(env::args_os().next().unwrap()).arg("foo").status(); </del> <ins> let mut cmd = Command::new(env::args_os().next().unwrap()); cmd.arg("foo"); // ARMv6 hanges while printing the backtrace, see #41004 if cfg!(target_arch = "arm") && cfg!(target_env = "gnu") { cmd.env("RUST_BACKTRACE", "0"); } let s = cmd.status(); </ins> assert!(s.unwrap().code() != Some(0)); }

)~ 3.7 and will continue to support it until either: a. It's so old that it can be removed without bothering package maintainers b. We need at least version X in order to fix an important bug c. The API is so different from version Y that it's a huge pain to support will open a PR to update the submodule shortly after release but it will take a month to land due to: a. Waiting for emscripten ( -) b. Bugs in upstream c. Missed LLVM API changes d. Making bors happy e. All of the above
Thanks for the summary The only correction I'd make is that in your point (4) you can s/3.6/3.7/, but otherwise it's accurate :) If you'd like to start preparing a PR to update to LLVM 4.0 I don't think we need to block waiting for LLVM itself to release 4.0. Currently only one Travis builder runs on each PR but we could temporarily allow more builders running on an LLVM 4.0 PR to start weeding out bugs before it hits
I gave it a go but I don't think my git-fu (or patience) is strong enough to handle a big merge like this. What I can do is try to run rustc with upstream LLVM and file/fix issues as I find them. There is at least one issue remaining as of (details to come).
Whoever ends up doing the LLVM upgrade, please also upgrade the compiler-rt submodule so that the sanitizer related LLVM passes don't diverge from what the sanitizer runtimes expect.
In fact, if you upgrade before the release, they usually mention your project in the release notes. :)
So whats the next issue(s) to subscribe to in the race-to-AVR? :)
As says on , we can integrate the latest Rust master into the avr-rust compiler. After that, we can spend some time getting compiling for AVR. Once that is working, we could then start looking into upstreaming the AVR target to Rust.
AVR-specific issues can be raised / tracked in For example, there are two that I'm aware of right now:
has been closed, so that can be checked off in the top post.


Question: <ins> // This tests the parser recovery in `recover_intersection_pat` // and serves as a regression test for the diagnostics issue #65400. // // The general idea is that for `$pat_lhs @ $pat_rhs` where // `$pat_lhs` is not generated by `ref? mut? $ident` we want // to suggest either switching the order or note that intersection // patterns are not allowed. fn main() { let s: Option<u8> = None; match s { Some(x) @ y => {} //~^ ERROR pattern on wrong side of `@` //~| pattern on the left, should be on the right //~| binding on the right, should be on the left //~| HELP switch the order //~| SUGGESTION y @ Some(x) _ => {} } match s { Some(x) @ Some(y) => {} //~^ ERROR left-hand side of `@` must be a binding //~| interpreted as a pattern, not a binding //~| also a pattern //~| NOTE bindings are `x`, `mut x`, `ref x`, and `ref mut x` _ => {} } match 2 { 1 ..= 5 @ e => {} //~^ ERROR pattern on wrong side of `@` //~| pattern on the left, should be on the right //~| binding on the right, should be on the left //~| HELP switch the order //~| SUGGESTION e @ 1 ..=5 _ => {} } } </ins>

The compiler could suggest that identifier must precede the pattern in the following code: playpen link: Current error message: It could be improved as:
modify labels: A-diagnostics C-feature-request T-compiler
So what happens after is that we've parsed a and then follows which is not a valid token after a parsed . To fix this we can, after having parsed in , check if follows and then emit appropriate suggestions. We will need to use some heuristics to figure out what the user wants based on the structure of . Some of the suggestions would be and some not. cc


Question: /// [`NonNull::dangling()`]: ptr::NonNull::dangling #[inline] #[stable(feature = "rust1", since = "1.0.0")] <del> pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] { debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice"); debug_assert!( mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize, "attempt to create slice covering at least half the address space" ); </del> <ins> #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")] pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] { debug_check_data_len(data as _, len); </ins> // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`. unsafe { &mut *ptr::slice_from_raw_parts_mut(data, len) } } <ins> // In debug builds checks that `data` pointer is aligned and non-null and that slice with given `len` would cover less than half the address space #[cfg(all(not(bootstrap), debug_assertions))] #[unstable(feature = "const_slice_from_raw_parts", issue = "67456")] #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")] const fn debug_check_data_len<T>(data: *const T, len: usize) { fn rt_check<T>(data: *const T) { use crate::intrinsics::is_aligned_and_not_null; assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice"); } const fn noop<T>(_: *const T) {} // SAFETY: // // `rt_check` is just a debug assert to hint users that they are causing UB, // it is not required for safety (the safety must be guatanteed by // the `from_raw_parts[_mut]` caller). // // Since the checks are not required, we ignore them in CTFE as they can't // be done there (alignment does not make much sense there). unsafe { crate::intrinsics::const_eval_select((data,), noop, rt_check); } assert!( crate::mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize, "attempt to create slice covering at least half the address space" ); } #[cfg(not(all(not(bootstrap), debug_assertions)))] const fn debug_check_data_len<T>(_data: *const T, _len: usize) {} </ins> /// Converts a reference to T into a slice of length 1 (without copying). #[stable(feature = "from_ref", since = "1.28.0")] #[rustc_const_unstable(feature = "const_slice_from_ref", issue = "90206")]

Currently,  is not , since it uses with a non- check: can't be made , since it involves ptr-int cast to check the alignment: Recently intrinsic , it allows to run different code in CTFE and runtime. This, in turn, allows us to only make the alignment check in runtime and ignore it in the CTFE where it doesn't make much sense. See also: cc and (it seems like use of requires approval of all of the above teams) label +T-lang +T-libs +A-const-eval +A-const-fn
Another approach to make const would be to disable the checks altogether, but since we already have , that seems unreasonable.
cc opinions before we escalate to lang and libs?
If a new intrinsic was in the spirit of and , this could possibly provide a solution without . Something like:
It seems useless to be able to perform any align checks in constants. The CTFE catches invalid pointer dereferences anyways.
Yes, but we also want to catch invalid pointer dereferences when we are not in CTFE, hence the idea of the function/intrinsic.
So why not use ?
It doesn't catch insufficiently aligned pointers though.


Question: /// N.B., while `f` is running, the thread-local state /// is `BridgeState::InUse`. fn with<R>(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R { <del> BRIDGE_STATE.with(|state| { state.replace(BridgeState::InUse, |mut state| { // FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone f(&mut *state) }) }) </del> <ins> BRIDGE_STATE.with(|state| state.replace(BridgeState::InUse, f)) </ins> } }

() As you can see, calling directly doesn't instantiate the HRTB (even though it needs to AFAIK) or if it does it doesn't normalize the resulting bound, whereas going through normalizes the instantiated argument types of , while 's definition can be type-checked as-is. EDIT: you can also get an ICE by uncommenting the use in : cc (this might be a duplicate)
Duplicate of (at least the ICE case)? A lot of analysis wad did in the other issue. Maybe it would help. I doubt that, in such cases the associate type do normalize at all. My assumption is: In the case that you marked as "working", it is just delayed the normalization to the later stage. So if the later stage consider this is dead code it is passed and compile, otherwise, when it really need to normalize it, run into ICE. So when called explicitly like , the compiler have no choice but to normalize with . If you instead though, the compiler checked that the requirement to match the argument can in theory fullfill, but the lifetime parameter was not free in the function body so it can consider this is a late bound. So the normalization is not happen right away. Later on, when you add the code in to call , the compiler have to do normalization again, but it is already in codegen (see the backtrace messages) phase, so normalization is unexpected and ICE occurs. Given all that, I guess a proper solution is to add a "late normalization" pass to normalize any postponed normalization like this.
This is a probably a duplicate of and/or ?
closing as duplicate of , which is where I will try to track future instances of this field of ICE.


Question: let tcx = self.tcx(); let mut pred = cache_fresh_trait_pred.skip_binder(); <del> param_env = param_env.with_constness(pred.constness.and(param_env.constness())); </del> <ins> pred.remap_constness(tcx, &mut param_env); </ins> if !self.can_cache_candidate(&candidate) { debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable");

<!-- Thank you for filing a regression report! A regression is something that changed between versions of Rust but was not supposed to. Please provide a short summary of the regression, along with any information you feel is relevant to replicate it. --I tried this code: I expected to see this happen: print (from Debug impl) Instead, this happened: E0277, trait impl not found This was found by CI in the Ruffle Project: The issue is caused by the effective anti-bound of Drop, introduced by the manual impl of the trait, as well as the PR which introduced bounds for a number of functions in . It most recently worked on: rustc 1.59.0-nightly ( 2021-12-18) : modify labels: +regression-from-stable-to-nightly -regression-untriaged
cc


Question: // one: if self.emitted_diagnostics.borrow_mut().insert(diagnostic_hash) { self.emitter.borrow_mut().emit(db); <ins> if db.is_error() { self.bump_err_count(); } </ins> } } }

Minimal example: Error message (ran in playground): Tested on nightly as well ()
Related:
twice without checking the return value. Modify it to return and check where it is being called ether both calls have returned an (cancel one, emit the other, return ), wether only one was created (emit it, return ) or none has (return ).
I'll fix this, thanks for the instruction!
I would happily have a go at this, if that's ok with
Sure go for it!
have you had time to work on this? If not could I give it a go? :)
I totally thought I was going to have time, but I had a crazy week at work this week. Go ahead and give it a go :) I'll find another bug to work on when I definitely have time
It looks like the PR to fix this was merged but has a few dangling threads. There seems to be some confusion about short-circuiting functionality and the necessity of the patch and also the error count still reads 2 rather than 1. Should a new issue be opened with those issues and this issue closed?


Question: <del> //@ known-bug: #121574 #![feature(generic_const_exprs)] impl<const Z: usize> X<Z> { pub fn y<'a, U: 'a>(&'a self) -> impl Iterator<Item = impl Iterator<Item = [u8; Z]> + '_> {} } </del>

<!-- ICE: Rustc '' 'error: internal compiler error: cannot convert to a region vid', 'error: internal compiler error: cannot convert to a region vid' File: --auto-reduced (treereduce-rust): original: Version information ` Command: <!-- Include a backtrace in the code block by setting in your environment. E.g. . --<details<summary<strongProgram output</strong</summary<p</p</details<!-- query stack: [mirborrowck] borrow-checking [analysis] running analysis passes on this crate --
cc


Question: <del> //@ known-bug: #121574 #![feature(generic_const_exprs)] impl<const Z: usize> X<Z> { pub fn y<'a, U: 'a>(&'a self) -> impl Iterator<Item = impl Iterator<Item = [u8; Z]> + '_> {} } </del>

<!-- Thank you for finding an Internal Compiler Error! If possible, try to provide a minimal verifiable example. You can read "Rust Bug Minimization Patterns" for how to create smaller examples. --<!-- If you're using the stable version of the compiler, you should also check if the bug also exists in the beta or nightly versions. --: <!-- Include a backtrace in the code block by setting in your environment. E.g. . --<details<summary<strongBacktrace</strong</summary<p</p</details
Is this a duplicate of
i think so
I wish there were a "close as duplidate" for this. Ah well.
there is actually, if you click the drop down on the close button
Hunh, they mean to include that in "not planned". Strange.
the "duplicate" issue is closed but this is still failing.
Also ive found that even if you do this without nesting the impl trait it still ICE's.
And if you do it succeeds.


Question: <ins> #[derive(Clone)] pub struct Struct; pub mod dep_mod1 { pub struct Fields { /// [crate::Struct::clone] pub field: u8, } } pub mod dep_mod2 { pub enum Fields { V { /// [crate::Struct::clone] field: u8, }, } } </ins>

Here is a complete (minimized) reproducer: It can be reproduced with a workspace with two crates "a" and "b" where: The crate "a" depends on the public () crate and its code is: . The crate "b" depends on the workspace crate and its code is: With that setup, the command rightfully succeeds using the stable toolchain. But fails when using the latest (2022-04-25) nightly toolchain. The bug is observable on nightly only (works fine on stable, and beta) : <details<summary<strongBacktrace</strong</summary<p</p</details
Fixed in


Question: have happily compiled. If we forget in the `match`, it will not. Rust helps us make sure to cover all of our bases. <ins> `match` expressions also allow us to get the values contained in an `enum` (also known as destructuring) as follows: ```{rust} enum OptionalInt { Value(int), Missing, } fn main() { let x = Value(5); let y = Missing; match x { Value(n) => println!("x is {}", n), Missing  => println!("x is missing!"), } match y { Value(n) => println!("y is {}", n), Missing  => println!("y is missing!"), } } ``` That is how you can get and use the values contained in `enum`s. It can also allow us to treat errors or unexpected computations, for example, a function that is not guaranteed to be able to compute a result (an `int` here), could return an `OptionalInt`, and we would handle that value with a `match`. As you can see, `enum` and `match` used together are quite useful! </ins> `match` is also an expression, which means we can use it on the right hand side of a `let` binding or directly where an expression is used. We could also implement the previous line like this:

See: The keyword hasn't been introduced until that point but it's used in the code example which is confusing. I believe an if/else solution would be more explanatory, especially because the reader probably wants to see how to unpack the variant of . The same enum could then be used with the keyword in the beginning of the next chapter ().
You are correct. Nice catch!
Are you ok with simply reordering them ? Because introducing sum type without precedent knowledge of pattern matching is a bit pointles (or at least misses the fact that they are juste AWESOME for pattern matching). If you're ok with this I'll PR in a few hours :)
Maybe, if it flows okay, yeah. I do want to put SOME kind of mention of it first.
It's probably easy to find out what is doing by simply looking at it. This part of the tutorial is just a bit confusing and should be fixed. However, my main concern here is that the reader is left clueless on how to solve this problem with if/else: In fact, I really don't know how the equivalent code without would look like. I've briefly tried to figure it out and gave up.
With an Option you coul unwrap I guess. By the way why did you write a fake option enum ? Because that's basically what is done with this, it might be better to give out the real name
Because we haven't talked about generics yet.
Nicely done. However, my other concern, how this example could be done without , remains unresolved. I'm certain that I'm not the only one who wants to know how it works with before continue reading about . Should I open another issue for that matter?
I'm honestly not sure that it is possible with an arbitrary enum... You can test for some arbitrary values but i guess but that's it. Bt it's more an issue of sum types in general rather than a Rust issue (I can't find ways to do that in haskell nor in scala)
Alright, I expected something like this as I was unable to figure out how to write it without . I don't have much experience with statically typed languages, therefore the concept was new to me. If you are right, could we mention in the tutorial that it is actually not possible to write an equivalent solution with ? Certainly, I can't be the only one who was a bit puzzled.


Question: have happily compiled. If we forget in the `match`, it will not. Rust helps us make sure to cover all of our bases. <ins> `match` expressions also allow us to get the values contained in an `enum` (also known as destructuring) as follows: ```{rust} enum OptionalInt { Value(int), Missing, } fn main() { let x = Value(5); let y = Missing; match x { Value(n) => println!("x is {}", n), Missing  => println!("x is missing!"), } match y { Value(n) => println!("y is {}", n), Missing  => println!("y is missing!"), } } ``` That is how you can get and use the values contained in `enum`s. It can also allow us to treat errors or unexpected computations, for example, a function that is not guaranteed to be able to compute a result (an `int` here), could return an `OptionalInt`, and we would handle that value with a `match`. As you can see, `enum` and `match` used together are quite useful! </ins> `match` is also an expression, which means we can use it on the right hand side of a `let` binding or directly where an expression is used. We could also implement the previous line like this:

Cheers.
Thanks a lot for the remark, it's exactly the kind of comment needed, if you see others don't hesitate to open new issues :) I'll try to add this tonight or tomorrow.


Question: // Functions cannot both be `const async` or `const gen` if let Some(&FnHeader { <del> constness: Const::Yes(cspan), </del> <ins> constness: Const::Yes(const_span), </ins> coroutine_kind: Some(coroutine_kind), .. }) = fk.header() { <del> let aspan = match coroutine_kind { CoroutineKind::Async { span: aspan, .. } | CoroutineKind::Gen { span: aspan, .. } | CoroutineKind::AsyncGen { span: aspan, .. } => aspan, }; // FIXME(gen_blocks): Report a different error for `const gen` self.dcx().emit_err(errors::ConstAndAsync { spans: vec![cspan, aspan], cspan, aspan, </del> <ins> self.dcx().emit_err(errors::ConstAndCoroutine { spans: vec![coroutine_kind.span(), const_span], const_span, coroutine_span: coroutine_kind.span(), coroutine_kind: coroutine_kind.as_str(), </ins> span, }); }

() Reproduces on the playground using . label +D-incorrect +F-gen_blocks +requires-nightly


Question: <ins> // test for https://github.com/rust-lang/rust/issues/86940 // run-rustfix // edition:2018 // check-pass #![warn(rust_2021_prelude_collisions)] #![allow(dead_code)] #![allow(unused_imports)] struct Generic<T, U>(T, U); trait MyFromIter { fn from_iter(_: i32) -> Self; } impl MyFromIter for Generic<i32, i32> { fn from_iter(x: i32) -> Self { Self(x, x) } } impl std::iter::FromIterator<i32> for Generic<i32, i32> { fn from_iter<T: IntoIterator<Item = i32>>(_: T) -> Self { todo!() } } fn main() { Generic::from_iter(1); //~^ WARNING trait-associated function `from_iter` will become ambiguous in Rust 2021 //~| this is accepted in the current edition (Rust 2018) Generic::<i32, i32>::from_iter(1); //~^ WARNING trait-associated function `from_iter` will become ambiguous in Rust 2021 //~| this is accepted in the current edition (Rust 2018) Generic::<_, _>::from_iter(1); //~^ WARNING trait-associated function `from_iter` will become ambiguous in Rust 2021 //~| this is accepted in the current edition (Rust 2018) } </ins>

For generic types, the prelude collision lint can produce suggestions that do not compile: Code: Suggestion from the prelude collision lint: Error after applying the suggestion: <!-- TRIAGEBOTSTART --<!-- TRIAGEBOTASSIGNSTART --<!-- TRIAGEBOTASSIGNDATASTARTTRIAGEBOTASSIGNDATAEND --<!-- TRIAGEBOTASSIGNEND --<!-- TRIAGEBOTEND --
cc
My guess is this should be a simple fix, just copying the code the lint already uses for adding unspecified generics (). Will try implementing a fix soon.
assign
release-assignment
The code related to this lint lives in the . The relevant suggestion is generated here: The "self type" string comes from here: The code for traits is here: This is actually just a touch tricky, because currently we are getting the "self type" just by copying the text the user wrote. Probably the most correct thing for us to do would be to examine the 'self expression' HIR and, if it is a plain path, then to append the and otherwise skip it. Specifically, the other case that I am thinking about is code like this: Currently , meaning that it offers the suggestion "disambiguate the associated function: ".
claim
great! Let us know if you need anything or make progress. This issue is fairly time sensitive.
release-assignment
claim


Question: use rustc_infer::infer; use rustc_infer::traits::{self, StatementAsExpression}; use rustc_middle::lint::in_external_macro; <del> use rustc_middle::ty::{self, Binder, DefIdTree, IsSuggestable, Ty}; </del> <ins> use rustc_middle::ty::{ self, suggest_constraining_type_params, Binder, DefIdTree, IsSuggestable, ToPredicate, Ty, }; </ins> use rustc_session::errors::ExprParenthesesNeeded; use rustc_span::symbol::sym; use rustc_span::Span;

This gives the very unintuitive error: You expect to return , i.e. a . It mysteriously returns an instead. Because has a clone impl, it too, can be cloned (really, copied), returning a reference of the same lifetime. This is an operation you rarely want to do explicitly, except when dealing with generics. This error can crop up when you've forgotten to implement on , and have a reference (which could have been silently inserted using , as in the code above). However, it's not very obvious what's happening here. It can also crop up We should hint that itself isn't cloneable and thus we fell back to cloning here. This could be a lint on hitting the clone impl for references, but lints run too late. I'm not sure how this can be implemented, since we need to see the source of a value and that's a bit tricky.
cc
Interesting. This does seem like it would require some pretty special-case code to achieve, but I agree it'd be a nice case to capture.
A relatively easy way to catch most instances of this is to Pick up the expression which has a type error like this If it is a method call, check if that method call is a clone() call resolving to If it is a variable, find the variable's def If the def is a local def, look at the init expr, check if it's a bad clone This will miss things, but I think the majority of such bugs will be due to this. As it stands this feels like an incredibly easy case to hit (we've all forgotten to decorate structs).
cc
CC
As reported in : This reports:
Current output is even worse for the original report: The last comment's code is marginally different:
Current output: The last case should suggest constraining . Edit: that was easier than I thought (we already had the suggestion machinery): <img width="511" alt="Screen Shot 2022-12-13 at 6 41 23 PM" src="https://user-"


Question: } _ => intravisit::walk_expr(self, expr), }, <del> ExprKind::Path(qpath) => { let res = self.fcx.tables.borrow().qpath_res(qpath, expr.hir_id); if let Res::Def(DefKind::Static, def_id) = res { // Statics are lowered to temporary references or // pointers in MIR, so record that type. let ptr_ty = self.fcx.tcx.static_ptr_ty(def_id); self.record(ptr_ty, scope, Some(expr), expr.span); } } </del> _ => intravisit::walk_expr(self, expr), } self.expr_count += 1; <ins> let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); </ins> // If there are adjustments, then record the final type -- // this is the actual value that is being produced. if let Some(adjusted_ty) = self.fcx.tables.borrow().expr_ty_adjusted_opt(expr) {

root: updns-0.0.6: v.
triage: P-high. Nominating for discussion.
self-assigned for investigation in short term (as in, next two or three days). However I suspect someone from will be a better choice to investigate this.
We should try to bisect this
used . Determined: searched nightlies: from nightly-2019-11-26 to nightly-2020-01-03 regressed nightly: nightly-2019-12-01 searched commits: from to  regressed commit:
is a rollup commit of the following PR's: I'm guessing this is due to PR
I'm still working on reducing this down to something that I could put into the playpen. However, one interesting thing I've found locally during my reduction: This version of the will signal an analogous compilation error: but if I lift the first argument out to a separate -binding (i.e. change it to use above, or the sub-expression out to a separate -binding (i.e. change the argument expression to use above), then the error goes away. I'll admit that I don't know all the details of how the fn-transformation works to support , but I strongly suspect that if this kind of local code change can make an error go away, then that represents a weakness somewhere (either in the fn-transformation, or in the borrowck).
Okay in the details block is a standalone version suitable for the : <details</detailsand the error it generates:
So this does seem like somewhat clear (expected?) fallout from PR : a use of a in a generator witness will be recorded as a unsafe pointer , and then is never , but the method requires that the task you give it is . I believe we can readily update the crate in question to avoid using the in the expression under the RHS of . But I do wonder whether we can/should improve the diagnostics here to try to guide the user towards such a solution ...?
I might have worded this too strongly, and/or over-reduced my example. In particular, its easy to move around the access to . But the borrow of may be trickier to deal with.
I'll have a look at addressing this with another approach I considered for . If that doesn't work out then I'll have a look at the error message.


Question: } _ => intravisit::walk_expr(self, expr), }, <del> ExprKind::Path(qpath) => { let res = self.fcx.tables.borrow().qpath_res(qpath, expr.hir_id); if let Res::Def(DefKind::Static, def_id) = res { // Statics are lowered to temporary references or // pointers in MIR, so record that type. let ptr_ty = self.fcx.tcx.static_ptr_ty(def_id); self.record(ptr_ty, scope, Some(expr), expr.span); } } </del> _ => intravisit::walk_expr(self, expr), } self.expr_count += 1; <ins> let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); </ins> // If there are adjustments, then record the final type -- // this is the actual value that is being produced. if let Some(adjusted_ty) = self.fcx.tables.borrow().expr_ty_adjusted_opt(expr) {

The patch linked is enough to fix the crate in question, but I'm all for finding an in-compiler solution if we can do it soundly.
OK. I'm going to write some things up because I've changed my mind a bunch of times about how/if this can be fixed in MIR building and I don't want to keep forgetting things. Generators store values that if their value needs to be preserved across a yield. These values need to be visible for auto-traits, for example a generator may be resumed on a different thread after it yields, and so cannot be if any of theses values isn't . There are two passes that determine which values can be included in the generator: A pass that runs as part of typeck that walks the HIR to find the types of expressions and then checks for yields in the values scope (as determined by the RegionScopeTree). The types recorded here are stored in the GeneratorWitnesss type contained in the generator, which is then used for auto trait checking. This notably uses the types of expressions that HIR sees. The MIR transform that lowers the generator to a state machine. This determines the values that the generator actually stores. As a check for the compiler, we assert that any types that we capture here are included in the witness type (we don't know all auto traits, so can't check only for them). After statics no longer have a special representation in MIR. They are instead lowered to a dereference of a pointer to the given static: is lowered as if it were: Which becomes: The example above is somewhat deceptive in that the temporary that holds the pointer is used immediately after it's assigned. In this case it cannot end up in the generator since it's not live across any user code. However this isn't true in all cases, index and match expressions allow running user code while the pointer is live: In these cases MIR has to put the temporary pointer into the generator state and promptly ICEs. The obvious solution now is make type checking record the new pointer types in the generator witness in these cases. Unfortunately HIR is not a great tool for specifying "these cases". The methods that the region scope tree provides in HIR are either usually far too large (the "temporary scope") or occasionally too small (the "enclosing scope"). went for the sound but rather approximate approach, leaving us here.


Question: } _ => intravisit::walk_expr(self, expr), }, <del> ExprKind::Path(qpath) => { let res = self.fcx.tables.borrow().qpath_res(qpath, expr.hir_id); if let Res::Def(DefKind::Static, def_id) = res { // Statics are lowered to temporary references or // pointers in MIR, so record that type. let ptr_ty = self.fcx.tcx.static_ptr_ty(def_id); self.record(ptr_ty, scope, Some(expr), expr.span); } } </del> _ => intravisit::walk_expr(self, expr), } self.expr_count += 1; <ins> let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); </ins> // If there are adjustments, then record the final type -- // this is the actual value that is being produced. if let Some(adjusted_ty) = self.fcx.tables.borrow().expr_ty_adjusted_opt(expr) {

One idea might be to try changing MIR building so that the temporary is never live across user code. For example, one might change the lowering as follows However working out how to do this for in a reasonable to implement way is harder. MIR actually already contains an escape hatch for values that are in the MIR but aren't in the HIR in the form of a flag (called ) on the variable. We currently use it for drop flags and boxes created by expressions. It's unclear what exactly the difference is between is. I guess one could argue that auto traits are for layout introspection and this would be further breaking that. I think that's everything for now.
Visiting from triage. were you planning to work on this further?
It's definitely tempting to take advantage of the constraints around statics to just declare these equivalent, and use the flag to get out of this. While I don't see any soundness issues around that, I also don't quite trust myself to get this right :) Can you expand on this? I'm not sure I follow.
Another solution that comes to mind relies on the fact that these pointers never need to be stored in a generator. They are consts, and the temporaries containing them shouldn't ever be mutated. We could add semantics for "const temporaries" to MIR, and never store them inside generators. The semantics would (hopefully) be simple: defined once and assigned a value that doesn't depend on any other temporaries; never mutated or borrowed mutably. We can move the statements defining them to the top of the function inside the generator transform. But that would be adding more semantics and special casing to MIR to fix a change which removed extra semantics and special casing, so I'm not sure if that's what we want :)
The argument is that the given the following auto trait we guarantee that if then there are no raw pointers directly stored in an instance of . If we make that guarantee then using internal in generators would not be OK. I would argue that we're not making such (or really any) guarantees with user defined auto traits.
Yeah, I don't think auto traits should expose layout implementation details of generators. And this really does seem like a pure implementation detail -- it doesn't have any bearing on what kinds of (unsafe) operations are allowed on a generator, like a self-reference would.


Question: } _ => intravisit::walk_expr(self, expr), }, <del> ExprKind::Path(qpath) => { let res = self.fcx.tables.borrow().qpath_res(qpath, expr.hir_id); if let Res::Def(DefKind::Static, def_id) = res { // Statics are lowered to temporary references or // pointers in MIR, so record that type. let ptr_ty = self.fcx.tcx.static_ptr_ty(def_id); self.record(ptr_ty, scope, Some(expr), expr.span); } } </del> _ => intravisit::walk_expr(self, expr), } self.expr_count += 1; <ins> let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); </ins> // If there are adjustments, then record the final type -- // this is the actual value that is being produced. if let Some(adjusted_ty) = self.fcx.tables.borrow().expr_ty_adjusted_opt(expr) {

cc
So, I've been putting off commenting here to let these ideas sit, but let me leave a comment. I think I've reached a conclusion. TL;DR. I think we should mark these types as internal, but I think there are some better options for fixing this in the medium term, and this interaction should be taken into account as part of the "MIR 2.0" effort to rework places. Auto traits weren't really intended as a tool for probing layout, but rather semantic considerations. This is why traits like can be implemented by users. So I don't really think that auto traits give any sort of guarantee about their layout. Rather, this question is about is simply "what are the constituent types exposed by a generator", and this should correspond to the types that user code can directly access. The raw pointers here are not directly accessible. The values that are accessible are the "live values" that the user's code may later use -- and of course the code currently makes the constituent types be a superset of those, based on the AST structure. Of course, the real root cause of this error is a simplifying change to the definition of in MIR. It used to be that a Place had this grammar: but now we changed to just , which is why we are required to introduce the new temporary (and that holds the address of the ). As we've been talking about this change, I've been saying that we should be considering the older definition of as the one that is used by various analyses (and in particular by borrow check). This particular transformation of removing statics doesn't affect borrow check, but we failed to take into account the fact that the set of live variables can effect the definition of what is live in a generator. In particular, compiling for some expression requires a temporary unless corresponds to a place -- those places used to include statics like , but they no longer do. But I think that for analysis purposes, it should appear as if they do. We could fix this in two ways. We could write some code motion / duplication that takes temporaries like that are live across a yield and creates a fresh variable after the yield. The idea would be to make them never* live across a yield.


Question: } _ => intravisit::walk_expr(self, expr), }, <del> ExprKind::Path(qpath) => { let res = self.fcx.tables.borrow().qpath_res(qpath, expr.hir_id); if let Res::Def(DefKind::Static, def_id) = res { // Statics are lowered to temporary references or // pointers in MIR, so record that type. let ptr_ty = self.fcx.tcx.static_ptr_ty(def_id); self.record(ptr_ty, scope, Some(expr), expr.span); } } </del> _ => intravisit::walk_expr(self, expr), } self.expr_count += 1; <ins> let scope = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); </ins> // If there are adjustments, then record the final type -- // this is the actual value that is being produced. if let Some(adjusted_ty) = self.fcx.tables.borrow().expr_ty_adjusted_opt(expr) {

We can do this because that operation is a compile-time constant, really, and thus the value doesn't need to be live across a yield. This might be worth doing as a size optimization regardless. Secondly, some of the proposals we've been kicking around for going further with simplifying include the idea of a distinct sort of temporaries that explicitly represent a "partially constructed that hasn't been used by the user". The idea was to allow borrowck (and other analyses) to trivially reconstruct the . We might want to add this interaction with auto-traits into the consideration for that design, and maybe it takes us some place (e.g., these special temporaries are not considered live for the purposes of auto traits). Having written out both of those options, though, I sort of lean towards the first, at least for this specific issue.
I think these references and raw pointers created by MIR construction should be marked as . They are not visible at the language level. They can be viewed as just prefetching the address of a static, so the compiler could pick any type it likes for it (, , , some compiler internal type) so it must not affect auto trait inference. Drop flags are ignored for similar reasons. You cannot use an auto trait like this to detect them: So I think that should be reverted and the temporary static references should be marked as .
Note: opened instituting this change and I r+'d it, since fixing the regression seems pretty important and time is of the essence; there is general consensus here on the thread; this is only restoring older behavior. In particular, there were some suggestions that this might be a lang team issue; I think there is some 'intersection' and I don't want the perception that I'm trying to shortcircuit discussion. That said, I also think this is primarily a compiler team matter, since it's a deviation from the old behavior, and further this deviation was caused by altering the MIR away from the "natural, Rust-based" definition and towards a lower-level definition.


Question: <ins> error[E0310]: the parameter type `T` may not live long enough --> $DIR/issue_74400.rs:12:5 | LL |     f(data, identity) |     ^^^^^^^^^^^^^^^^^ | = help: consider adding an explicit lifetime bound `T: 'static`... error[E0308]: mismatched types --> $DIR/issue_74400.rs:12:5 | LL |     f(data, identity) |     ^^^^^^^^^^^^^^^^^ one type is more general than the other | = note: expected type `for<'r> Fn<(&'r T,)>` found type `Fn<(&T,)>` error: implementation of `FnOnce` is not general enough --> $DIR/issue_74400.rs:12:5 | LL |     f(data, identity) |     ^^^^^^^^^^^^^^^^^ implementation of `FnOnce` is not general enough | = note: `fn(&'2 T) -> &'2 T {identity::<&'2 T>}` must implement `FnOnce<(&'1 T,)>`, for any lifetime `'1`... = note: ...but it actually implements `FnOnce<(&'2 T,)>`, for some specific lifetime `'2` error: aborting due to 3 previous errors Some errors have detailed explanations: E0308, E0310. For more information about an error, try `rustc --explain E0308`. </ins>

Regression from to . The following code yields an incorrect error: On beta, this gives: On nightly, this:
would you be so kind to label this issue? It's sliding down the list while being hard to search.
Regression occurred between nightly-2020-06-23 and nightly-2020-06-24, I suspect is related (it's ?).
It would be great to find the culprit PR. ping cleanup
Hey Cleanup Crew ICE-breakers! This bug has been identified as a good "Cleanup ICE-breaking candidate". In case it's useful, here are some [instructions] for tackling these sorts of bugs. Maybe take a look? Thanks! <3 [instructions]: https://rustc-dev- cc
searched nightlies: from nightly-2020-06-23 to nightly-2020-06-24 regressed nightly: nightly-2020-06-24 searched commits: from to regressed commit: <details<summarybisected with <a href=''cargo-bisect-rustc</av0.5.1</summaryHost triple: x86_64-unknown-linux-gnu Reproduce with: </detailsIf we rule out document changes then we have
Bisection seems to confirm this, cc
With a little more git bisect it seems is the first bad commit And I guess the change to the test case also shows that
Assigning as and removing .
Well, I can certainly imagine how this could come about as a result of the leak-check moving, since the same error can now be detected at a different point during type-checking. What's happening in that confusing error, I imagine, is that we are now winding up with a "universe error" that comes out from region checking. The identity function was inferred to take an argument for some ... Well, in short, I imagine that the solution here is to improve the error reporting for the new point where the error occurs, but it'll take a bit more digging to give good mentoring instructions into how to go about doing that.
This is now a stable regression.
Discussed in T-compiler meeting. Seems related to (or potential duplicate of) ?
On today's nightly, the error is now: That seems correct, and with the extra lifetime, the snippet compiles:


Question: return false; }; <del> // FIXME(with_negative_coherence): the infcx has region contraints from equating // the impl headers as requirements. Given that the only region constraints we // get are involving inference regions in the root, it shouldn't matter, but // still sus. // // We probably should just throw away the region obligations registered up until // now, or ideally use them as assumptions when proving the region obligations // that we get from proving the negative predicate below. </del> let ref infcx = root_infcx.fork(); let ocx = ObligationCtxt::new(infcx);

<!-- Thank you for filing a bug report! Please provide a short summary of the bug, along with any information you feel relevant to replicating the bug. -- I expected to see this happen: Compiles successfully Instead, this happened: <!-- If you're using the stable version of the compiler, you should also check if the bug also exists in the beta or nightly versions. --: label A-coherence F-negative_impls requires-nightly T-compiler
I'll look into it


Question: # Only commits merged by bors will have CI artifacts. merge_base = [ "git", "rev-list", "--author=bors@rust-lang.org", "-n1", <del> "--merges", "--first-parent", "HEAD" </del> <ins> "--first-parent", "HEAD" </ins> ] commit = subprocess.check_output(merge_base, universal_newlines=True).strip() <ins> if not commit: print("error: could not find commit hash for downloading rustc") print("help: maybe your repository history is too shallow?") print("help: consider disabling `download-rustc`") print("help: or fetch enough history to include one upstream commit") exit(1) </ins> # Warn if there were changes to the compiler or standard library since the ancestor commit. status = subprocess.call(["git", "diff-index", "--quiet", commit, "--", compiler, library])

An error message indicating that a full (or at least longer) git history is required. The correct link would include a commit hash inbetween the . But the required commit hash is not available because there is no full history. <!-- TRIAGEBOTSTART --<!-- TRIAGEBOTASSIGNSTART --<!-- TRIAGEBOTASSIGNDATASTARTTRIAGEBOTASSIGNDATAEND --<!-- TRIAGEBOTASSIGNEND --<!-- TRIAGEBOTEND --
Hm, can I do this? label +A-rustbuild
Mentoring instructions: find what this command outputs when the repository is shallow: If it's an error, see if you can check for a shallow repository somehow and give a hard error instead of continuing onward just to fail.
Note that this shouldn't need to the full history of the repo, just the past few days, since PRs are constantly being merged.
We should only need one (bors merge) commit, I believe - each bors merge has the full set of artifacts.
The command prints nothing in my shallow clone. There is a bors merge commit in my shallow clone though: The command before used to work for me -- I was able to enable in my shallow clone. I tried to fetch more commits, and then started to work: But still prints nothing.
cc I would have expected the git log and git rev-list to be 'identical', in some sense, so perhaps that's something worth filing upstream as well. But regardless, I am inclined to revert to fix this issue; it was primarily a 'hopefully more robust' solution and to my knowledge wasn't actually fixing any known bugs, so since it caused a bug seems good to revert it for now...
I think it's possible that the shallow clone is causing the predicate to fail. Note the decoration in The git documentation implies that shallow clones use something akin to the (fake parentage for commits) facility for shallow clones. Maybe removing is sufficient? I'm a bit wary because bors seems to create non-merge commits on occasion (for squashes), but maybe it never does so on the first-parent history. I haven't had a chance to poke at a shallow clone in detail yet.
I'm seeing a similar problem for git worktrees, not just shallow clones. EDIT: this may have been a separate reason, it just had the right timing
Would love to see movement on this.


Question: # Only commits merged by bors will have CI artifacts. merge_base = [ "git", "rev-list", "--author=bors@rust-lang.org", "-n1", <del> "--merges", "--first-parent", "HEAD" </del> <ins> "--first-parent", "HEAD" </ins> ] commit = subprocess.check_output(merge_base, universal_newlines=True).strip() <ins> if not commit: print("error: could not find commit hash for downloading rustc") print("help: maybe your repository history is too shallow?") print("help: consider disabling `download-rustc`") print("help: or fetch enough history to include one upstream commit") exit(1) </ins> # Warn if there were changes to the compiler or standard library since the ancestor commit. status = subprocess.call(["git", "diff-index", "--quiet", commit, "--", compiler, library])

I don't want to allocate ~20GB of laptop space to a deep clone of the repository in order to simply be able to build the compiler. When i was messing around, removing "--merges" as suggested did the trick.
feel free to make a PR with that change :)
I wasn't sure if there was some reason not to do that: I'm a bit wary because bors seems to create non-merge commits on occasion (for squashes), but maybe it never does so on the first-parent history. I don't really grok most of what said there, but if you think that's a safe change, then sure thing!
As long as we keep first parent, dropping merges should be ok, any commit in the first parent chain should have artifacts (if it's recent enough).
I would appreciate knowing details of what behavior you're seeing with git worktrees, if you're willing to provide them.
Sorry, I'm not seeing any related problem when trying to do a simple test with worktrees. I do see a problem with shallow clones. Could you please describe what you're seeing? Does it still happen if you delete the options from the command lines in ?
I don't think we need to exhaustively catalogue the issues - even if removing --merges doesn't fix all the issues it will fix some of them, and we can make more improvements in follow-ups.
claim
Someone should probably file a bug about failing to see merge commits in shallow clones. I don't feel like I understand the issue well enough to do so.


Question: <ins> error[E0609]: no field `f` on type `Foo` --> $DIR/non-existent-field-present-in-subfield-recursion-limit.rs:41:22 | LL |     let test = fooer.f; |                      ^ unknown field | = note: available fields are: `first`, `second`, `third` error: aborting due to previous error For more information about this error, try `rustc --explain E0609`. </ins>

I just encountered this output: We currently mention available fields when the field used isn't found. It would be nice if we peeked at the types for the available fields to see if any of them has any fields (including through deref) of the name we originally wanted. In this case, I would love to see the following output: <!-- TRIAGEBOTSTART --<!-- TRIAGEBOTASSIGNSTART --<!-- TRIAGEBOTASSIGNDATASTARTTRIAGEBOTASSIGNDATAEND --<!-- TRIAGEBOTASSIGNEND --<!-- TRIAGEBOTEND --
I'll work on this. claim
I was just about to open a PR when I saw that you claimed the issue. It's my fault for not claiming this issue myself obviously, so if you've already been investing time into this the issue its still yours, but if you haven't can I open a PR for this?
I've done nothing yet as I planned to work on this tomorrow morning, so this is yours :)
release-assignment
if you're still interested in contributing, it seems to me that might be similar in scope and section of the codebase you could work in.
Thank you.