Couple of small changes
These are unrelated to each other, but they are each small enough that opening separate PR's doesn't make sense to me either.
* Remove a place where the parse driver query is stolen.
* Update an outdated doc comment
* Use correct crate name in `-Zprint-vtable-sizes` when using `#![crate_name = "..."]`.
Add FileCheck annotations to a few MIR opt tests
const_debuginfo did not specify which passes were running.
const_prop_miscompile is renamed and moved to const_prop directory.
while_storage was broken.
Stabilize `const_maybe_uninit_zeroed` and `const_mem_zeroed`
Make `MaybeUninit::zeroed` and `mem::zeroed` const stable. Newly stable API:
```rust
// core::mem
pub const unsafe fn zeroed<T>() ->;
impl<T> MaybeUninit<T> {
pub const fn zeroed() -> MaybeUninit<T>;
}
```
This relies on features based around `const_mut_refs`. Per `@RalfJung,` this should be OK since we do not leak any `&mut` to the user.
For this to be possible, intrinsics `assert_zero_valid` and `assert_mem_uninitialized_valid` were made const stable.
Tracking issue: #91850
Zulip discussion: https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/.60const_mut_refs.60.20dependents
r? libs-api
`@rustbot` label -T-libs +T-libs-api +A-const-eval
cc `@RalfJung` `@oli-obk` `@rust-lang/wg-const-eval`
Make sure that predicates with unmentioned bound vars are still considered global in the old solver
In the old solver, we consider predicates with late-bound vars to not be "global":
9c8a2694fa/compiler/rustc_trait_selection/src/traits/select/mod.rs (L1840-L1844)
The implementation of `has_late_bound_vars` was modified in #115834 so that we'd properly anonymize binders that had late-bound vars but didn't reference them. This fixed an ICE.
However, this also led to a behavioral change in https://github.com/rust-lang/rust/issues/117056#issuecomment-1775014545 for a couple of crates, which now consider `for<'a> GL33: Shader` (note the binder var that is *not* used in the predicate) to not be "global". This forces associated types to not be normalizable due to the old trait solver being dumb.
This PR distinguishes types which *reference* late-bound vars and binders which *have* late-bound vars. The latter is represented with the new type flag `TypeFlags::HAS_BINDER_VARS`, which is used when we only care about knowing whether binders have vars in their bound var list (even if they're not used, like for binder anonymization).
This should fix (after beta backport) the `luminance-gl` and `luminance-webgl` crates in #117056.
r? types
**(priority is kinda high on a review here given beta becomes stable on November 16.)**
Hint optimizer about try-reserved capacity
This is #116568, but limited only to the less-common `try_reserve` functions to reduce bloat in debug binaries from debug info, while still addressing the main use-case #116570
Rollup of 6 pull requests
Successful merges:
- #110340 (Deref docs: expand and remove "smart pointer" qualifier)
- #116894 (Guarantee that `char` has the same size and alignment as `u32`)
- #117534 (clarify that the str invariant is a safety, not validity, invariant)
- #117562 (triagebot no-merges: exclude different case)
- #117570 (fallback for `construct_generic_bound_failure`)
- #117583 (Remove `'tcx` lifetime on `PlaceholderConst`)
r? `@ghost`
`@rustbot` modify labels: rollup
fallback for `construct_generic_bound_failure`
Fixes#117547
This case regressed at #115882.
In this context, `generic_param_scope` is produced by `RPITVisitor` and not included by `hir_owner`. Therefore, I've added a fallback to address this.
Make `core::mem::zeroed` const stable. Newly stable API:
// core::mem
pub const unsafe fn zeroed<T>() -> T;
This is stabilized with `const_maybe_uninit_zeroed` since it is a simple
wrapper.
In order to make this possible, intrinsics `assert_zero_valid` was made
const stable under `const_assert_type2`.
`assert_mem_uninitialized_valid` was also made const stable since it is
under the same gate.
Update the alignment checks to match rust-lang/reference#1387
Previously, we had a special case to not check `Rvalue::AddressOf` in this pass because we weren't quite sure if pointers needed to be aligned in the Place passed to it: https://github.com/rust-lang/rust/pull/112026
Since https://github.com/rust-lang/reference/pull/1387 merged, this PR updates this pass to match. The behavior of the check is nearly unchanged, except we also avoid inserting a check for creating references. Most of the changes in this PR are cleanup and new tests.
Cleanup `rustc_mir_build/../check_match.rs`
The file had become pretty unwieldy, with a fair amount of duplication. As a bonus, I discovered that we weren't running some pattern checks in if-let chains.
I recommend looking commit-by-commit. The last commit is a whim, I think it makes more sense that way but I don't hold this opinion strongly.
They've been deprecated for four years.
This commit includes the following changes.
- It eliminates the `rustc_plugin_impl` crate.
- It changes the language used for lints in
`compiler/rustc_driver_impl/src/lib.rs` and
`compiler/rustc_lint/src/context.rs`. External lints are now called
"loaded" lints, rather than "plugins" to avoid confusion with the old
plugins. This only has a tiny effect on the output of `-W help`.
- E0457 and E0498 are no longer used.
- E0463 is narrowed, now only relating to unfound crates, not plugins.
- The `plugin` feature was moved from "active" to "removed".
- It removes the entire plugins chapter from the unstable book.
- It removes quite a few tests, mostly all of those in
`tests/ui-fulldeps/plugin/`.
Closes#29597.
Fix incorrect trait bound restriction suggestion
Suggest
```
error[E0308]: mismatched types
--> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
|
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
| - - expected `B` because of return type
| |
| expected this type parameter
LL | return a.bar();
| ^^^^^^^ expected type parameter `B`, found associated type
|
= note: expected type parameter `B`
found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
|
LL | pub fn foo<A: MyTrait<T = B>, B>(a: A) -> B {
| +++++++
```
instead of
```
error[E0308]: mismatched types
--> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
|
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
| - - expected `B` because of return type
| |
| expected this type parameter
LL | return a.bar();
| ^^^^^^^ expected type parameter `B`, found associated type
|
= note: expected type parameter `B`
found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
|
LL | pub fn foo<A: MyTrait + <T = B>, B>(a: A) -> B {
| +++++++++
```
Fix#117501.
Pretty print `Fn` traits in `rustc_on_unimplemented`
I don't think that users really ever should need to think about `Fn*` traits' tupled args for a simple trait error.
r? diagnostics
Derive expansions for packed structs cause move errors because
they prefer copying over borrowing since borrowing the fields of a
packed struct can result in unaligned access and therefore undefined
behaviour.
This underlying cause of the errors, however, is not apparent
to the user. We add a diagnostic note here to remedy that.
Add all RPITITs when augmenting param-env with GAT bounds in `check_type_bounds`
When checking that associated type definitions actually satisfy their associated type bounds in `check_type_bounds`, we construct a "`normalize_param_env`" which adds a projection predicate that allows us to assume that we can project the GAT to the definition we're checking. For example, in:
```rust
type Foo {
type Bar: Display = i32;
}
```
We would add `<Self as Foo>::Bar = i32` as a projection predicate when checking that `i32: Display` holds.
That `normalize_param_env` was, for some reason, only being used to normalize the predicate before it was registered. This is sketchy, because a nested obligation may require the GAT bound to hold, and also the projection cache is broken and doesn't differentiate projection cache keys that differ by param-envs 😿.
This `normalize_param_env` is also not sufficient when we have nested RPITITs and default trait methods, since we need to be able to assume we can normalize both the RPITIT and all of its child RPITITs to sufficiently prove all of its bounds. This is the cause of #117104, which only starts to fail for RPITITs that are nested 3 and above due to the projection-cache bug above.[^1]
## First fix
Use the `normalize_param_env` everywhere in `check_type_bounds`. This is reflected in a test I've constructed that fixes a GAT-only failure.
## Second fix
For RPITITs, install projection predicates for each RPITIT in the same function in `check_type_bounds`. This fixes#117104.
not sure who to request, so...
r? `@lcnr` hehe feel free to reassign :3
[^1]: The projection cache bug specifically occurs because we try normalizing the `assumed_wf_types` with the non-normalization param-env. This causes us to insert a projection cache entry that keeps the outermost RPITIT rigid, and it trivially satisifes all its own bounds. Super sketchy![^2]
[^2]: I haven't actually gone and fixed the projection cache bug because it's only marginally related, but I could, and it should no longer be triggered here.
Suggest
```
error[E0308]: mismatched types
--> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
|
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
| - - expected `B` because of return type
| |
| expected this type parameter
LL | return a.bar();
| ^^^^^^^ expected type parameter `B`, found associated type
|
= note: expected type parameter `B`
found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
|
LL | pub fn foo<A: MyTrait<T = B>, B>(a: A) -> B {
| +++++++
```
instead of
```
error[E0308]: mismatched types
--> $DIR/restrict-assoc-type-of-generic-bound.rs:9:12
|
LL | pub fn foo<A: MyTrait, B>(a: A) -> B {
| - - expected `B` because of return type
| |
| expected this type parameter
LL | return a.bar();
| ^^^^^^^ expected type parameter `B`, found associated type
|
= note: expected type parameter `B`
found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
|
LL | pub fn foo<A: MyTrait + <T = B>, B>(a: A) -> B {
| +++++++++
```
Fix#117501.
Fix order of implementations in the "implementations on foreign types" section
Fixes#117391.
We forgot to run the `sort_by_cached_key` on this section. This fixes it.
r? `@notriddle`
Remove support for alias `-Z symbol-mangling-version`
(This is very similar to the removal of `-Z instrument-coverage` in #117111.)
`-C symbol-mangling-version` was stabilized back in rustc 1.59.0 (2022-02-24) via #90128, with the old unstable flag kept around (with a warning) as an alias to ease migration.
Clarify `Unsize` documentation
The documentation erroneously says that:
```rust
/// - Types implementing a trait `Trait` also implement `Unsize<dyn Trait>`.
/// - Structs `Foo<..., T, ...>` implement `Unsize<Foo<..., U, ...>>` if all of these conditions
/// are met:
/// - `T: Unsize<U>`.
/// - Only the last field of `Foo` has a type involving `T`.
/// - `Bar<T>: Unsize<Bar<U>>`, where `Bar<T>` stands for the actual type of that last field.
```
Specifically, `T: Unsize<U>` is not required to hold -- only the final field must implement `FinalField<T>: Unsize<FinalField<U>>`. This can be demonstrated by the test I added.
---
Second commit fleshes out the documentation a lot more.
Don't check for alias bounds in liveness when aliases have escaping bound vars
I actually have no idea how we *should* be treating aliases with escaping bound vars here... but the simplest behavior is just doing what we used to do before.
r? aliemjay
Fixes#117455
Most notably, this commit changes the `pub use crate::*;` in that file
to `use crate::*;`. This requires a lot of `use` items in other crates
to be adjusted, because everything defined within `rustc_span::*` was
also available via `rustc_span::source_map::*`, which is bizarre.
The commit also removes `SourceMap::span_to_relative_line_string`, which
is unused.
Rollup of 4 pull requests
Successful merges:
- #117298 (Recover from missing param list in function definitions)
- #117373 (Avoid the path trimming ICE lint in error reporting)
- #117441 (Do not assert in op_to_const.)
- #117488 (Update minifier-rs version to 0.3.0)
r? `@ghost`
`@rustbot` modify labels: rollup
Do not assert in op_to_const.
`op_to_const` is used in `try_destructure_mir_constant_for_diagnostics`, which may encounter invalid constants created by optimizations and debugging.
r? ``@oli-obk``
Fixes https://github.com/rust-lang/rust/issues/117368
Add FileCheck annotations to MIR-opt inlining tests
Part of #116971, adds FileCheck annotations to MIR-opt tests in `tests/mir-opt/inline`.
I left out a few (such as `inline_cycle`) where it mentioned that the particular outcome of inlining isn't important, just that the inliner doesn't get stuck in an infinite loop.
r? cjgillot
Account for `ref` and `mut` in the wrong place for pattern ident renaming
If the user writes `S { ref field: name }` instead of `S { field: ref name }`, we suggest the correct code.
Fix#72298.
Support enum variants in offset_of!
This MR implements support for navigating through enum variants in `offset_of!`, placing the enum variant name in the second argument to `offset_of!`. The RFC placed it in the first argument, but I think it interacts better with nested field access in the second, as you can then write things like
```rust
offset_of!(Type, field.Variant.field)
```
Alternatively, a syntactic distinction could be made between variants and fields (e.g. `field::Variant.field`) but I'm not convinced this would be helpful.
[RFC 3308 # Enum Support](https://rust-lang.github.io/rfcs/3308-offset_of.html#enum-support-offset_ofsomeenumstructvariant-field_on_variant)
Tracking Issue #106655.
Clean up unchecked_math, separate out unchecked_shifts
Tracking issue: #85122
Changes:
1. Remove `const_inherent_unchecked_arith` flag and make const-stability flags the same as the method feature flags. Given the number of other unsafe const fns already stabilised, it makes sense to just stabilise these in const context when they're stabilised.
2. Move `unchecked_shl` and `unchecked_shr` into a separate `unchecked_shifts` flag, since the semantics for them are unclear and they'll likely be stabilised separately as a result.
3. Add an `unchecked_neg` method exclusively to signed integers, under the `unchecked_neg` flag. This is because it's a new API and probably needs some time to marinate before it's stabilised, and while it *would* make sense to have a similar version for unsigned integers since `checked_neg` also exists for those there is absolutely no case where that would be a good idea, IMQHO.
The longer-term goal here is to prepare the `unchecked_math` methods for an FCP and stabilisation since they've existed for a while, their semantics are clear, and people seem in favour of stabilising them.
Match usize/isize exhaustively with half-open ranges
The long-awaited finale to the saga of [exhaustiveness checking for integers](https://github.com/rust-lang/rust/pull/50912)!
```rust
match 0usize {
0.. => {} // exhaustive!
}
match 0usize {
0..usize::MAX => {} // helpful error message!
}
```
Features:
- Half-open ranges behave as expected for `usize`/`isize`;
- Trying to use `0..usize::MAX` will tell you that `usize::MAX..` is missing and explain why. No more unhelpful "`_` is missing";
- Everything else stays the same.
This should unblock https://github.com/rust-lang/rust/issues/37854.
Review-wise:
- I recommend looking commit-by-commit;
- This regresses perf because of the added complexity in `IntRange`; hopefully not too much;
- I measured each `#[inline]`, they all help a bit with the perf regression (tho I don't get why);
- I did not touch MIR building; I expect there's an easy PR there that would skip unnecessary comparisons when the range is half-open.
Replace switch to unreachable by assume statements
`UnreachablePropagation` currently keeps some switch terminators alive in order to ensure codegen can infer the inequalities on the discriminants.
This PR proposes to encode those inequalities as `Assume` statements.
This allows to simplify MIR further by removing some useless terminators.
Rollup of 5 pull requests
Successful merges:
- #113241 (rustdoc: Document lack of object safety on affected traits)
- #117388 (Turn const_caller_location from a query to a hook)
- #117417 (Add a stable MIR visitor)
- #117439 (prepopulate opaque ty storage before using it)
- #117451 (Add support for pre-unix-epoch file dates on Apple platforms (#108277))
r? `@ghost`
`@rustbot` modify labels: rollup
rustdoc: Document lack of object safety on affected traits
Closes#85138
I saw the issue didn't have any recent activity, if there is another MR for it I missed it.
I want the issue to move forward so here is my proposition.
It takes some space just before the "Implementors" section and only if the trait is **not** object
safe since it is the only case where special care must be taken in some cases and this has the
benefit of avoiding generation of HTML in (I hope) the common case.
Accept less invalid Rust in rustdoc
pulled out of https://github.com/rust-lang/rust/pull/117213 where this change was already approved
This only affects rustdoc, and has up to [20% perf regressions in rustdoc](https://github.com/rust-lang/rust/pull/117213#issuecomment-1785776288). These are unavoidable, as we are simply doing more checks now, but it's part of the longer term plan of making rustdoc more resistant to ICEs by only accepting valid Rust code.
Rollup of 5 pull requests
Successful merges:
- #116267 (Some codegen cleanups around SIMD checks)
- #116712 (When encountering unclosed delimiters during lexing, check for diff markers)
- #117416 (Also consider TAIT to be uncomputable if the MIR body is tainted)
- #117421 (coverage: Replace impossible `coverage::Error` with assertions)
- #117438 (Do not ICE on constant evaluation failure in GVN.)
r? `@ghost`
`@rustbot` modify labels: rollup
Also consider TAIT to be uncomputable if the MIR body is tainted
Not totally sure if this is the best solution. We could, alternatively, look at the hir typeck results and try to take a type from there instead of just falling back to type error, inferring `u8` instead of `{type error}`. Not certain it really matters, though.
Happy to iterate on this.
Fixes#117413
r? ``@oli-obk`` cc ``@Nadrieril``
Store #[deprecated] attribute's `since` value in parsed form
This PR implements the first followup bullet listed in https://github.com/rust-lang/rust/pull/117148#issue-1960240108.
We centralize error handling to the attribute parsing code in `compiler/rustc_attr/src/builtin.rs`, and thereby remove some awkward error codepaths from later phases of compilation that had to make sense of these #\[deprecated\] attributes, namely `compiler/rustc_passes/src/stability.rs` and `compiler/rustc_middle/src/middle/stability.rs`.
Detect object safety errors when assoc type is missing
When an associated type with GATs isn't specified in a `dyn Trait`, emit an object safety error instead of only complaining about the missing associated type, as it will lead the user down a path of three different errors before letting them know that what they were trying to do is impossible to begin with.
Fix#103155.
When an associated type with GATs isn't specified in a `dyn Trait`, emit
an object safety error instead of only complaining about the missing
associated type, as it will lead the user down a path of three different
errors before letting them know that what they were trying to do is
impossible to begin with.
Fix#103155.
Rollup of 7 pull requests
Successful merges:
- #116862 (Detect when trait is implemented for type and suggest importing it)
- #117389 (Some diagnostics improvements of `gen` blocks)
- #117396 (Don't treat closures/coroutine types as part of the public API)
- #117398 (Correctly handle nested or-patterns in exhaustiveness)
- #117403 (Poison check_well_formed if method receivers are invalid to prevent typeck from running on it)
- #117411 (Improve some diagnostics around `?Trait` bounds)
- #117414 (Don't normalize to an un-revealed opaque when we hit the recursion limit)
r? `@ghost`
`@rustbot` modify labels: rollup
Don't normalize to an un-revealed opaque when we hit the recursion limit
Currently, we will normalize `Opaque := Option<&Opaque>` to something like `Option<&Option<&Option<&...Opaque>>>`, hitting a limit and bottoming out in an unnormalized opaque after the recursion limit gets hit.
Unfortunately, during `layout_of`, we'll simply recurse and try again if the type normalizes to something different than the type:
e6e931dda5/compiler/rustc_ty_utils/src/layout.rs (L58-L60)
That means then we'll try to normalize `Option<&Option<&Option<&...Opaque>>>` again, substituting `Opaque` into itself even deeper. Eventually this will get to the point that we're just stack-overflowing on a really deep type before even hitting an opaque again.
To fix this, we just bottom out into `ty::Error` instead of the unrevealed opaque type.
Fixes#117412
r? `@oli-obk`
Improve some diagnostics around `?Trait` bounds
* uses better spans
* clarifies a message that was only talking about generic params, but applies to `dyn ?Trait` and `impl ?Trait` as well
Poison check_well_formed if method receivers are invalid to prevent typeck from running on it
fixes#117379
Though if some code invokes typeck without having first invoked `check_well_formed` then we'll encounter this ICE again. This can happen in const and const fn bodies if they are evaluated due to other `check_well_formed` checks or similar
Correctly handle nested or-patterns in exhaustiveness
I had assumed nested or-patterns were flattened, and they mostly are but not always.
Fixes https://github.com/rust-lang/rust/issues/117378
Fix missing leading space in suggestion
For a local pattern with no space between `let` and `(` e.g.:
```rust
let(_a) = 3;
```
we were previously suggesting this illegal code:
```rust
let_a = 3;
```
After this change the suggestion will instead be:
```rust
let _a = 3;
```
Fixes#117380
C-variadic error improvements
A couple improvements for c-variadic errors:
1. Fix the bad-c-variadic error being emitted multiple times. If a function incorrectly contains multiple `...` args, and is also not foreign or `unsafe extern "C"`, only emit the latter error once rather than once per `...`.
2. Explicitly reject `const` C-variadic functions. Trying to use C-variadics in a const function would previously fail with an error like "destructor of `VaListImpl<'_>` cannot be evaluated at compile-time". Add an explicit check for const C-variadics to provide a clearer error: "functions cannot be both `const` and C-variadic". This also addresses one of the concerns in https://github.com/rust-lang/rust/issues/44930: "Ensure that even when this gets stabilized for regular functions, it is still rejected on const fn."
On object safety error, mention new enum as alternative
When we encounter a `dyn Trait` that isn't object safe, look for its implementors. If there's one, mention using it directly If there are less than 9, mention the possibility of creating a new enum and using that instead.
Fix#80194.
rustdoc: elide cross-crate default generic arguments
Elide cross-crate generic arguments if they coincide with their default.
TL;DR: Most notably, no more `Box<…, Global>` in `std`'s docs, just `Box<…>` from now on.
Fixes#80379.
Also helps with #44306. Follow-up to #103885, #107637.
r? ``@ghost``
Trying to use C-variadics in a const function would previously fail with
an error like "destructor of `VaListImpl<'_>` cannot be evaluated at
compile-time".
Add an explicit check for const C-variadics to provide a clearer error:
"functions cannot be both `const` and C-variadic".
For a local pattern with no space between `let` and `(` e.g.:
let(_a) = 3;
we were previously suggesting this illegal code:
let_a =3;
After this change the suggestion will instead be:
let _a =3;
(Note the space after `let`)
Fail typeck for illegal break-with-value
This is fixes the issue wherein typeck was succeeding for break-with-value exprs at illegal locations such as inside `while`, `while let` and `for` loops which eventually caused an ICE during MIR interpretation for const eval.
Now we fail typeck for such code which prevents faulty MIR from being generated and interpreted, thus fixing the ICE.
Fixes#114529
Ignore RPIT duplicated lifetimes in `opaque_types_defined_by`
An RPIT's or TAIT's own generics are kinda useless -- so just ignore them. For TAITs, they will always be empty, and for RPITs, they're always duplicated lifetimes.
Fixes#115013.
Allows `#[diagnostic::on_unimplemented]` attributes to have multiple
notes
This commit extends the `#[diagnostic::on_unimplemented]` (and `#[rustc_on_unimplemented]`) attributes to allow multiple `note` options. This enables emitting multiple notes for custom error messages. For now I've opted to not change any of the existing usages of `#[rustc_on_unimplemented]` and just updated the relevant compile tests.
r? `@compiler-errors`
I'm happy to adjust any of the existing changed location to emit the old error message if that's desired.
Print variadic argument pattern in HIR pretty printer
Variadic argument name/pattern was ignored during HIR pretty printing.
Could not figure out why it only works on normal functions (`va2`) and not in foreign ones (`va1`).
This is fixes the issue wherein typeck was succeeding for break-with-value
at illegal locations such as inside `while`, `while let` and `for` loops which
eventually caused an ICE during MIR interpetation for const eval.
Now we fail typeck for such code which prevents faulty MIR from being generated
and interpreted, thus fixing the ICE.
When we encounter a `dyn Trait` that isn't object safe, look for its
implementors. If there's one, mention using it directly If there are
less than 9, mention the possibility of creating a new enum and using
that instead.
Account for object unsafe `impl Trait on dyn Trait {}`. Make a
distinction between public and sealed traits.
Fix#80194.
Consider alias bounds when computing liveness in NLL (but this time sound hopefully)
This is a revival of #116040, except removing the changes to opaque lifetime captures check to make sure that we're not triggering any unsoundness due to the lack of general existential regions and the currently-existing `ReErased` hack we use instead.
r? `@aliemjay` -- I appreciate you pointing out the unsoundenss in the previous iteration of this PR, and I'd like to hear that you're happy with this iteration of this PR before this goes back into FCP :>
Fixes#116794 as well
---
(mostly copied from #116040 and reworked slightly)
# Background
Right now, liveness analysis in NLL is a bit simplistic. It simply walks through all of the regions of a type and marks them as being live at points. This is problematic in the case of aliases, since it requires that we mark **all** of the regions in their args[^1] as live, leading to bugs like #42940.
In reality, we may be able to deduce that fewer regions are allowed to be present in the projected type (or "hidden type" for opaques) via item bounds or where clauses, and therefore ideally, we should be able to soundly require fewer regions to be live in the alias.
For example:
```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}
fn capture<'o>(_: &'o mut ()) -> impl Sized + Captures<'o> + 'static {}
fn test_two_mut(mut x: ()) {
let _f1 = capture(&mut x);
let _f2 = capture(&mut x);
//~^ ERROR cannot borrow `x` as mutable more than once at a time
}
```
In the example above, we should be able to deduce from the `'static` bound on `capture`'s opaque that even though `'o` is a captured region, it *can never* show up in the opaque's hidden type, and can soundly be ignored for liveness purposes.
# The Fix
We apply a simple version of RFC 1214's `OutlivesProjectionEnv` and `OutlivesProjectionTraitDef` rules to NLL's `make_all_regions_live` computation.
Specifically, when we encounter an alias type, we:
1. Look for a unique outlives bound in the param-env or item bounds for that alias. If there is more than one unique region, bail, unless any of the outlives bound's regions is `'static`, and in that case, prefer `'static`. If we find such a unique region, we can mark that outlives region as live and skip walking through the args of the opaque.
2. Otherwise, walk through the alias's args recursively, as we do today.
## Limitation: Multiple choices
This approach has some limitations. Firstly, since liveness doesn't use the same type-test logic as outlives bounds do, we can't really try several options when we're faced with a choice.
If we encounter two unique outlives regions in the param-env or bounds, we simply fall back to walking the opaque via its args. I expect this to be mostly mitigated by the special treatment of `'static`, and can be fixed in a forwards-compatible by a more sophisticated analysis in the future.
## Limitation: Opaque hidden types
Secondly, we do not employ any of these rules when considering whether the regions captured by a hidden type are valid. That causes this code (cc #42940) to fail:
```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}
fn a() -> impl Sized + 'static {
b(&vec![])
}
fn b<'o>(_: &'o Vec<i32>) -> impl Sized + Captures<'o> + 'static {}
```
We need to have existential regions to avoid [unsoundness](https://github.com/rust-lang/rust/pull/116040#issuecomment-1751628189) when an opaque captures a region which is not represented in its own substs but which outlives a region that does.
## Read more
Context: https://github.com/rust-lang/rust/pull/115822#issuecomment-1731153952 (for the liveness case)
More context: https://github.com/rust-lang/rust/issues/42940#issuecomment-455198309 (for the opaque capture case, which this does not fix)
[^1]: except for bivariant region args in opaques, which will become less relevant when we move onto edition 2024 capture semantics for opaques.
See through aggregates in GVN
This PR is extracted from https://github.com/rust-lang/rust/pull/111344
The first 2 commit are cleanups to avoid repeated work. I propose to stop removing useless assignments as part of this pass, and let a later `SimplifyLocals` do it. This makes tests easier to read (among others).
The next 3 commits add a constant folding mechanism to the GVN pass, presented in https://github.com/rust-lang/rust/pull/116012. ~This pass is designed to only use global allocations, to avoid any risk of accidental modification of the stored state.~
The following commits implement opportunistic simplifications, in particular:
- projections of aggregates: `MyStruct { x: a }.x` gets replaced by `a`, works with enums too;
- projections of arrays: `[a, b][0]` becomes `a`;
- projections of repeat expressions: `[a; N][x]` becomes `a`;
- transform arrays of equal operands into a repeat rvalue.
Fixes https://github.com/rust-lang/miri/issues/3090
r? `@oli-obk`
Fix closure-inherit-target-feature test for SGX platform
PR #116078 adds the `closure-inherit-target-feature.rs` test that checks the generated assembly code for closures. These checks explicitly check the presence of `ret` instructions. This is incompatible with the SGX target as it explicitly rewrites all `ret` instructions to mitigate LVI vulnerabilities of certain processors. This PR simply ignores these tests for the SGX platform.
cc: ```@jethrogb```
Implement `gen` blocks in the 2024 edition
Coroutines tracking issue https://github.com/rust-lang/rust/issues/43122
`gen` block tracking issue https://github.com/rust-lang/rust/issues/117078
This PR implements `gen` blocks that implement `Iterator`. Most of the logic with `async` blocks is shared, and thus I renamed various types that were referring to `async` specifically.
An example usage of `gen` blocks is
```rust
fn foo() -> impl Iterator<Item = i32> {
gen {
yield 42;
for i in 5..18 {
if i.is_even() { continue }
yield i * 2;
}
}
}
```
The limitations (to be resolved) of the implementation are listed in the tracking issue
coverage: Consistently remove unused counter IDs from expressions/mappings
If some coverage counters were removed by MIR optimizations, we need to take care not to refer to those counter IDs in coverage mappings, and instead replace them with a constant zero value. If we don't, `llvm-cov` might see a too-large counter ID and silently discard the entire function from its coverage reports.
Fixes#117012.
Cleanup and improve `--check-cfg` implementation
This PR removes some indentation in the code, as well as preventing some bugs/misusages and fix a nit in the doc.
r? ```@petrochenkov``` (maybe)
When encountering sealed traits, point types that implement it
```
error[E0277]: the trait bound `S: d::Hidden` is not satisfied
--> $DIR/sealed-trait-local.rs:53:20
|
LL | impl c::Sealed for S {}
| ^ the trait `d::Hidden` is not implemented for `S`
|
note: required by a bound in `c::Sealed`
--> $DIR/sealed-trait-local.rs:17:23
|
LL | pub trait Sealed: self::d::Hidden {
| ^^^^^^^^^^^^^^^ required by this bound in `Sealed`
= note: `Sealed` is a "sealed trait", because to implement it you also need to implement `c::d::Hidden`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
= help: the following types implement the trait:
- c::X
- c::Y
```
The last `help` is new.
rustdoc: use JS to inline target type impl docs into alias
Preview docs:
- https://notriddle.com/rustdoc-html-demo-5/js-trait-alias/std/io/type.Result.html
- https://notriddle.com/rustdoc-html-demo-5/js-trait-alias-compiler/rustc_middle/ty/type.PolyTraitRef.html
This pull request also includes a bug fix for trait alias inlining across crates. This means more documentation is generated, and is why ripgrep runs slower (it's a thin wrapper on top of the `grep` crate, so 5% of its docs are now the Result type).
- Before, built with rustdoc 1.75.0-nightly (aa1a71e9e 2023-10-26), Result type alias method docs are missing: http://notriddle.com/rustdoc-html-demo-5/ripgrep-js-nightly/rg/type.Result.html
- After, built with this branch, all the methods on Result are shown: http://notriddle.com/rustdoc-html-demo-5/ripgrep-js-trait-alias/rg/type.Result.html
*Review note: This is mostly just reverting https://github.com/rust-lang/rust/pull/115201. The last commit has the new work in it.*
Fixes#115718
This is an attempt to balance three problems, each of which would
be violated by a simpler implementation:
- A type alias should show all the `impl` blocks for the target
type, and vice versa, if they're applicable. If nothing was
done, and rustdoc continues to match them up in HIR, this
would not work.
- Copying the target type's docs into its aliases' HTML pages
directly causes far too much redundant HTML text to be generated
when a crate has large numbers of methods and large numbers
of type aliases.
- Using JavaScript exclusively for type alias impl docs would
be a functional regression, and could make some docs very hard
to find for non-JS readers.
- Making sure that only applicable docs are show in the
resulting page requires a type checkers. Do not reimplement
the type checker in JavaScript.
So, to make it work, rustdoc stashes these type-alias-inlined docs
in a JSONP "database-lite". The file is generated in `write_shared.rs`,
included in a `<script>` tag added in `print_item.rs`, and `main.js`
takes care of patching the additional docs into the DOM.
The format of `trait.impl` and `type.impl` JS files are superficially
similar. Each line, except the JSONP wrapper itself, belongs to a crate,
and they are otherwise separate (rustdoc should be idempotent). The
"meat" of the file is HTML strings, so the frontend code is very simple.
Links are relative to the doc root, though, so the frontend needs to fix
that up, and inlined docs can reuse these files.
However, there are a few differences, caused by the sophisticated
features that type aliases have. Consider this crate graph:
```text
---------------------------------
| crate A: struct Foo<T> |
| type Bar = Foo<i32> |
| impl X for Foo<i8> |
| impl Y for Foo<i32> |
---------------------------------
|
----------------------------------
| crate B: type Baz = A::Foo<i8> |
| type Xyy = A::Foo<i8> |
| impl Z for Xyy |
----------------------------------
```
The type.impl/A/struct.Foo.js JS file has a structure kinda like this:
```js
JSONP({
"A": [["impl Y for Foo<i32>", "Y", "A::Bar"]],
"B": [["impl X for Foo<i8>", "X", "B::Baz", "B::Xyy"], ["impl Z for Xyy", "Z", "B::Baz"]],
});
```
When the type.impl file is loaded, only the current crate's docs are
actually used. The main reason to bundle them together is that there's
enough duplication in them for DEFLATE to remove the redundancy.
The contents of a crate are a list of impl blocks, themselves
represented as lists. The first item in the sublist is the HTML block,
the second item is the name of the trait (which goes in the sidebar),
and all others are the names of type aliases that successfully match.
This way:
- There's no need to generate these files for types that have no aliases
in the current crate. If a dependent crate makes a type alias, it'll
take care of generating its own docs.
- There's no need to reimplement parts of the type checker in
JavaScript. The Rust backend does the checking, and includes its
results in the file.
- Docs defined directly on the type alias are dropped directly in the
HTML by `render_assoc_items`, and are accessible without JavaScript.
The JSONP file will not list impl items that are known to be part
of the main HTML file already.
[JSONP]: https://en.wikipedia.org/wiki/JSONP
Allow partially moved values in match
This PR attempts to unify the behaviour between `let _ = PLACE`, `let _: TY = PLACE;` and `match PLACE { _ => {} }`.
The logical conclusion is that the `match` version should not check for uninitialised places nor check that borrows are still live.
The `match PLACE {}` case is handled by keeping a `FakeRead` in the unreachable fallback case to verify that `PLACE` has a legal value.
Schematically, `match PLACE { arms }` in surface rust becomes in MIR:
```rust
PlaceMention(PLACE)
match PLACE {
// Decision tree for the explicit arms
arms,
// An extra fallback arm
_ => {
FakeRead(ForMatchedPlace, PLACE);
unreachable
}
}
```
`match *borrow { _ => {} }` continues to check that `*borrow` is live, but does not read the value.
`match *borrow {}` both checks that `*borrow` is live, and fake-reads the value.
Continuation of ~https://github.com/rust-lang/rust/pull/102256~ ~https://github.com/rust-lang/rust/pull/104844~
Fixes https://github.com/rust-lang/rust/issues/99180https://github.com/rust-lang/rust/issues/53114
Fix ICE: Restrict param constraint suggestion
When encountering an associated item with a type param that could be constrained, do not look at the parent item if the type param comes from the associated item.
Fix#117209, fix#89868.
Properly restore snapshot when failing to recover parsing ternary
If the recovery parsed an expression, then failed to eat a `:`, it would return `false` without restoring the snapshot. Fix this by always restoring the snapshot when returning `false`.
Draft for now because I'd like to try and improve this recovery further.
Fixes#117208
```
error[E0277]: the trait bound `S: d::Hidden` is not satisfied
--> $DIR/sealed-trait-local.rs:53:20
|
LL | impl c::Sealed for S {}
| ^ the trait `d::Hidden` is not implemented for `S`
|
note: required by a bound in `c::Sealed`
--> $DIR/sealed-trait-local.rs:17:23
|
LL | pub trait Sealed: self::d::Hidden {
| ^^^^^^^^^^^^^^^ required by this bound in `Sealed`
= note: `Sealed` is a "sealed trait", because to implement it you also need to implement `c::d::Hidden`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
= help: the following types implement the trait:
- c::X
- c::Y
```
The last `help` is new.
When encountering
```rust
foo()
*bar = baz;
```
We currently emit potentially two errors, one for the return type of
`foo` not being multiplyiable by the type of `bar`, and another for
`foo() * bar` not being assignable.
We now check for this case and suggest adding a semicolon in the right
place.
Fix#80446.
Lint overlapping ranges as a separate pass
This reworks the [`overlapping_range_endpoints`](https://doc.rust-lang.org/beta/nightly-rustc/rustc_lint_defs/builtin/static.OVERLAPPING_RANGE_ENDPOINTS.html) lint. My motivations are:
- It was annoying to have this lint entangled with the exhaustiveness algorithm, especially wrt librarification;
- This makes the lint behave consistently.
Here's the consistency story. Take the following matches:
```rust
match (0u8, true) {
(0..=10, true) => {}
(10..20, true) => {}
(10..20, false) => {}
_ => {}
}
match (true, 0u8) {
(true, 0..=10) => {}
(true, 10..20) => {}
(false, 10..20) => {}
_ => {}
}
```
There are two semantically consistent options: option 1 we lint all overlaps between the ranges, option 2 we only lint the overlaps that could actually occur (i.e. the ones with `true`). Option 1 is what this PR does. Option 2 is possible but would require the exhaustiveness algorithm to track more things for the sake of the lint. The status quo is that we're inconsistent between the two.
Option 1 generates more false postives, but I prefer it from a maintainer's perspective. I do think the difference is minimal; cases where the difference is observable seem rare.
This PR adds a separate pass, so this will have a perf impact. Let's see how bad, it looked ok locally.
notes
This commit extends the `#[diagnostic::on_unimplemented]` (and
`#[rustc_on_unimplemented]`) attributes to allow multiple `note`
options. This enables emitting multiple notes for custom error messages.
For now I've opted to not change any of the existing usages of
`#[rustc_on_unimplemented]` and just updated the relevant compile tests.
Rollup of 6 pull requests
Successful merges:
- #114998 (feat(docs): add cargo-pgo to PGO documentation 📝)
- #116868 (Tweak suggestion span for outer attr and point at item following invalid inner attr)
- #117240 (Fix documentation typo in std::iter::Iterator::collect_into)
- #117241 (Stash and cancel cycle errors for auto trait leakage in opaques)
- #117262 (Create a new ConstantKind variant (ZeroSized) for StableMIR)
- #117266 (replace transmute by raw pointer cast)
r? `@ghost`
`@rustbot` modify labels: rollup
Stash and cancel cycle errors for auto trait leakage in opaques
We don't need to emit a traditional cycle error when we have a selection error that explains what's going on but in more detail.
We may want to augment this error to actually point out the cycle, now that the cycle error is not being emitted. We could do that by storing the set of opaques that was in the `CyclePlaceholder` that gets returned from `type_of_opaque`.
r? `@oli-obk` cc `@estebank` #117235
Refactor some `char`, `u8` ASCII functions to be branchless
Extract conditions in singular `matches!` with or-patterns to individual `matches!` statements which enables branchless code output. The following functions were changed:
- `is_ascii_alphanumeric`
- `is_ascii_hexdigit`
- `is_ascii_punctuation`
Added codegen tests
---
Continued from https://github.com/rust-lang/rust/pull/103024.
Based on the comment from `@scottmcm` https://github.com/rust-lang/rust/pull/103024#pullrequestreview-1248697206.
The unmodified `is_ascii_*` functions didn't seem to benefit from extracting the conditions.
I've never written a codegen test before, but I tried to check that no branches were emitted.
Allow target specs to use an LLD flavor, and self-contained linking components
This PR allows:
- target specs to use an LLD linker-flavor: this is needed to switch `x86_64-unknown-linux-gnu` to using LLD, and is currently not possible because the current flavor json serialization fails to roundtrip on the modern linker-flavors. This can e.g. be seen in https://github.com/rust-lang/rust/pull/115622#discussion_r1321312880 which explains where an `Lld::Yes` is ultimately deserialized into an `Lld::No`.
- target specs to declare self-contained linking components: this is needed to switch `x86_64-unknown-linux-gnu` to using `rust-lld`
- adds an end-to-end test of a custom target json simulating `x86_64-unknown-linux-gnu` being switched to using `rust-lld`
- disables codegen backends from participating because they don't support `-Zgcc-ld=lld` which is the basis of mcp510.
r? `@petrochenkov:` if the approach discussed https://github.com/rust-lang/rust/pull/115622#discussion_r1329403467 and on zulip would work for you: basically, see if we can emit only modern linker flavors in the json specs, but accept both old and new flavors while reading them, to fix the roundtrip issue.
The backwards compatible `LinkSelfContainedDefault` variants are still serialized and deserialized in `crt-objects-fallback`, while the spec equivalent of e.g. `-Clink-self-contained=+linker` is serialized into a different json object (with future-proofing to incorporate `crt-objects-fallback` in the future).
---
I've been test-driving this in https://github.com/rust-lang/rust/pull/113382 to test actually switching `x86_64-unknown-linux-gnu` to `rust-lld` (and fix what needs to be fixed in CI, bootstrap, etc), and it seems to work fine.
Decompose singular `matches!` with or-patterns to individual `matches!`
statements to enable branchless code output. The following functions
were changed:
- `is_ascii_alphanumeric`
- `is_ascii_hexdigit`
- `is_ascii_punctuation`
Add codegen tests
Co-authored-by: George Bateman <george.bateman16@gmail.com>
Co-authored-by: scottmcm <scottmcm@users.noreply.github.com>
When expecting closure argument but finding block provide suggestion
Detect if there is a potential typo where the `{` meant to open the closure body was written before the body.
```
error[E0277]: expected a `FnOnce<({integer},)>` closure, found `Option<usize>`
--> $DIR/ruby_style_closure_successful_parse.rs:3:31
|
LL | let p = Some(45).and_then({|x|
| ______________________--------_^
| | |
| | required by a bound introduced by this call
LL | | 1 + 1;
LL | | Some(x * 2)
| | ----------- this tail expression is of type `Option<usize>`
LL | | });
| |_____^ expected an `FnOnce<({integer},)>` closure, found `Option<usize>`
|
= help: the trait `FnOnce<({integer},)>` is not implemented for `Option<usize>`
note: required by a bound in `Option::<T>::and_then`
--> $SRC_DIR/core/src/option.rs:LL:COL
help: you might have meant to open the closure body instead of placing a closure within a block
|
LL - let p = Some(45).and_then({|x|
LL + let p = Some(45).and_then(|x| {
|
```
Detect the potential typo where the closure header is missing.
```
error[E0277]: expected a `FnOnce<(&bool,)>` closure, found `bool`
--> $DIR/block_instead_of_closure_in_arg.rs:3:23
|
LL | Some(true).filter({
| _________________------_^
| | |
| | required by a bound introduced by this call
LL | |/ if number % 2 == 0 {
LL | || number == 0
LL | || } else {
LL | || number != 0
LL | || }
| ||_________- this tail expression is of type `bool`
LL | | });
| |______^ expected an `FnOnce<(&bool,)>` closure, found `bool`
|
= help: the trait `for<'a> FnOnce<(&'a bool,)>` is not implemented for `bool`
note: required by a bound in `Option::<T>::filter`
--> $SRC_DIR/core/src/option.rs:LL:COL
help: you might have meant to create the closure instead of a block
|
LL | Some(true).filter(|_| {
| +++
```
Partially address #27300. Fix#104690.
When encountering an associated item with a type param that could be
constrained, do not look at the parent item if the type param comes from
the associated item.
Fix#117209.
Rollup of 8 pull requests
Successful merges:
- #116905 (refactor(compiler/resolve): simplify some code)
- #117095 (Add way to differentiate argument locals from other locals in Stable MIR)
- #117143 (Avoid unbounded O(n^2) when parsing nested type args)
- #117194 (Minor improvements to `rustc_incremental`)
- #117202 (Revert "Remove TaKO8Ki from reviewers")
- #117207 (The value of `-Cinstrument-coverage=` doesn't need to be `Option`)
- #117214 (Quietly fail if an error has already occurred)
- #117221 (Rename type flag `HAS_TY_GENERATOR` to `HAS_TY_COROUTINE`)
r? `@ghost`
`@rustbot` modify labels: rollup
Add way to differentiate argument locals from other locals in Stable MIR
This PR resolvesrust-lang/project-stable-mir#47 which request a way to differentiate argument locals in a SMIR `Body` from other locals.
Specifically, this PR exposes the `arg_count` field from the MIR `Body`. However, I'm opening this as a draft PR because I think there are a few outstanding questions on how this information should be exposed and described. Namely:
- Is exposing `arg_count` the best way to surface this information to SMIR users? Would it be better to leave `arg_count` as a private field and add public methods (e.g. `fn arguments(&self) -> Iter<'_, LocalDecls>`) that may use the underlying `arg_count` info from the MIR body, but expose this information to users in a more convenient form? Or is it best to stick close to the current MIR convention?
- If the answer to the above point is to stick with the current MIR convention (`arg_count`), is it reasonable to also commit to sticking to the current MIR convention that the first local is always the return local, while the next `arg_count` locals are always the (in-order) argument locals?
- Should `Body` in SMIR only represent function bodies (as implied by the comment I added)? That seems to be the current case in MIR, but should this restriction always be the case for SMIR?
r? `@celinval`
r? `@oli-obk`
Never consider raw pointer casts to be trival
HIR typeck tries to figure out which casts are trivial by doing them as
coercions and seeing whether this works. Since HIR typeck is oblivious
of lifetimes, this doesn't work for pointer casts that only change the
lifetime of the pointee, which are, as borrowck will tell you, not
trivial.
This change makes it so that raw pointer casts are never considered
trivial.
This also incidentally fixes the "trivial cast" lint false positive on
the same code. Unfortunately, "trivial cast" lints are now never emitted
on raw pointer casts, even if they truly are trivial. This could be
fixed by also doing the lint in borrowck for raw pointers specifically.
fixes#113257
Rework negative coherence to properly consider impls that only partly overlap
This PR implements a modified negative coherence that handles impls that only have partial overlap.
It does this by:
1. taking both impl trait refs, instantiating them with infer vars
2. equating both trait refs
3. taking the equated trait ref (which represents the two impls' intersection), and resolving any vars
4. plugging all remaining infer vars with placeholder types
these placeholder-plugged trait refs can then be used normally with the new trait solver, since we no longer have to worry about the issue with infer vars in param-envs.
We use the **new trait solver** to reason correctly about unnormalized trait refs (due to deferred projection equality), since this avoid having to normalize anything under param-envs with infer vars in them.
This PR then additionally:
* removes the `FnPtr` knowable hack by implementing proper negative `FnPtr` trait bounds for rigid types.
---
An example:
Consider these two partially overlapping impls:
```
impl<T, U> PartialEq<&U> for &T where T: PartialEq<U> {}
impl<F> PartialEq<F> for F where F: FnPtr {}
```
Under the old algorithm, we would take one of these impls and replace it with infer vars, then try unifying it with the other impl under identity substitutions. This is not possible in either direction, since it either sets `T = U`, or tries to equate `F = &?0`.
Under the new algorithm, we try to unify `?0: PartialEq<?0>` with `&?1: PartialEq<&?2>`. This gives us `?0 = &?1 = &?2` and thus `?1 = ?2`. The intersection of these two trait refs therefore looks like: `&?1: PartialEq<&?1>`. After plugging this with placeholders, we get a trait ref that looks like `&!0: PartialEq<&!0>`, with the first impl having substs `?T = ?U = !0` and the second having substs `?F = &!0`[^1].
Then we can take the param-env from the first impl, and try to prove the negated where clause of the second.
We know that `&!0: !FnPtr` never holds, since it's a rigid type that is also not a fn ptr, we successfully detect that these impls may never overlap.
[^1]: For the purposes of this example, I just ignored lifetimes, since it doesn't really matter.
Store #[stable] attribute's `since` value in structured form
Followup to https://github.com/rust-lang/rust/pull/116773#pullrequestreview-1680913901.
Prior to this PR, if you wrote an improper `since` version in a `stable` attribute, such as `#[stable(feature = "foo", since = "wat.0")]`, rustc would emit a diagnostic saying **_'since' must be a Rust version number, such as "1.31.0"_** and then throw out the whole `stable` attribute as if it weren't there. This strategy had 2 problems, both fixed in this PR:
1. If there was also a `#[deprecated]` attribute on the same item, rustc would want to enforce that the stabilization version is older than the deprecation version. This involved reparsing the `stable` attribute's `since` version, with a diagnostic **_invalid stability version found_** if it failed to parse. Of course this diagnostic was unreachable because an invalid `since` version would have already caused the `stable` attribute to be thrown out. This PR deletes that unreachable diagnostic.
2. By throwing out the `stable` attribute when `since` is invalid, you'd end up with a second diagnostic saying **_function has missing stability attribute_** even though your function is not missing a stability attribute. This PR preserves the `stable` attribute even when `since` cannot be parsed, avoiding the misleading second diagnostic.
Followups I plan to try next:
- Do the same for the `since` value of `#[deprecated]`.
- See whether it makes sense to also preserve `stable` and/or `unstable` attributes when they contain an invalid `feature`. What redundant/misleading diagnostics can this eliminate? What problems arise from not having a usable feature name for some API, in the situation that we're already failing compilation, so not concerned about anything that happens in downstream code?
Mark .rmeta files as /SAFESEH on x86 Windows.
Chrome links .rlibs with /WHOLEARCHIVE or -Wl,--whole-archive to prevent the linker from discarding static initializers. This works well, except on Windows x86, where lld complains:
error: /safeseh: lib.rmeta is not compatible with SEH
The fix is simply to mark the .rmeta as SAFESEH aware. This is trivially true, since the metadata file does not contain any executable code.
Stop telling people to submit bugs for internal feature ICEs
This keeps track of usage of internal features, and changes the message to instead tell them that using internal features is not supported.
I thought about several ways to do this but now used the explicit threading of an `Arc<AtomicBool>` through `Session`. This is not exactly incremental-safe, but this is fine, as this is set during macro expansion, which is pre-incremental, and also only affects the output of ICEs, at which point incremental correctness doesn't matter much anyways.
See [MCP 620.](https://github.com/rust-lang/compiler-team/issues/596)
![image](https://github.com/rust-lang/rust/assets/48135649/be661f05-b78a-40a9-b01d-81ad2dbdb690)
The latest locals() method in stable MIR returns slices instead of vecs.
This commit also includes fixes to the existing tests that previously
referenced the private locals field.