ast: Standardize visiting order for attributes and node IDs
This should only affect `macro_rules` scopes and order of diagnostics.
Also add a deprecation lint for `macro_rules` called outside of their scope, like in https://github.com/rust-lang/rust/issues/124535.
Various refactorings to rustc_interface
This should make it easier to move the driver interface away from queries in the future. Many custom drivers call queries like `queries.global_ctxt()` before they are supposed to be called, breaking some things like certain `--print` and `-Zunpretty` options, `-Zparse-only` and emitting the dep info at the wrong point in time. They are also not actually necessary at all. Passing around the query output manually would avoid recomputation too and would be just as easy. Removing driver queries would also reduce the amount of global mutable state of the compiler. I'm not removing driver queries in this PR to avoid breaking the aforementioned custom drivers.
It was somewhat confusing that the old constructor would create a `FlatPat` in
a (possibly) non-simplified state, and then simplify its contents in-place.
So instead we now create its fields as local variables, perform simplification,
and then create the struct afterwards.
This doesn't affect correctness, but is less confusing.
transmute size check: properly account for alignment
Fixes another place where ZST alignment was ignored when checking whether something is a newtype. I wonder how many more of these there are...
Fixes https://github.com/rust-lang/rust/issues/101084
Allow constraining opaque types during various unsizing casts
allows unsizing of tuples, arrays and Adts to constraint opaque types in their generic parameters to concrete types on either side of the unsizing cast.
Also allows constraining opaque types during trait object casts that only differ in auto traits or lifetimes.
cc #116652
Just some extra sanity checking, making explicit some values not
possible in code working with token trees -- we shouldn't be seeing
explicit delimiter tokens, because they should be represented as
`TokenTree::Delimited`.
Add `SliceLike` to `rustc_type_ir`, use it in the generic solver code (+ some other changes)
First, we split out `TraitRef::new_from_args` which takes *just* `ty::GenericArgsRef` from `TraitRef::new` which takes `impl IntoIterator<Item: Into<GenericArg>>`. I will explain in a minute why.
Second, we introduce `SliceLike`, which allows us to be generic over `List<T>` and `[T]`. This trait has an `as_slice()` and `into_iter()` method, and some other convenience functions. However, importantly, since types like `I::GenericArgs` now implement `SliceLike` rather than `IntoIter<Item = I::GenericArg>`, we can't use `TraitRef::new` on this directly. That's where `new_from_args` comes in.
Finally, we adjust all the code to use these slice operators. Some things get simpler, some things get a bit more annoying since we need to use `as_slice()` in a few places. 🤷
r? lcnr
Rollup of 11 pull requests
Successful merges:
- #124460 (Show notice about "never used" of Debug for enum)
- #124712 (Deprecate no-op codegen option `-Cinline-threshold=...`)
- #125082 (Remove `MaybeUninit::uninit_array()` and replace it with inline const blocks.)
- #125575 (SmartPointer derive-macro)
- #126413 (compiletest: make the crash test error message abit more informative)
- #126673 (Ensure we don't accidentally succeed when we want to report an error)
- #126682 (coverage: Overhaul validation of the `#[coverage(..)]` attribute)
- #126899 (Suggest inline const blocks for array initialization)
- #126904 (Small fixme in core now that NonZero is generic)
- #126909 (add `@kobzol` to bootstrap team for triagebot)
- #126911 (Split the lifetimes of `MirBorrowckCtxt`)
r? `@ghost`
`@rustbot` modify labels: rollup
Split the lifetimes of `MirBorrowckCtxt`
These lifetimes are sometimes too general and will link things together that are independent. These are a blocker for actually finishing tracking more state (e.g. error tainting) in the diagnostic context handle, and I'd rather land it in its own PR instead of together with functional changes.
Also changes a bunch of named lifetimes to `'_` where they were irrelevant
follow-up to https://github.com/rust-lang/rust/pull/126623
coverage: Overhaul validation of the `#[coverage(..)]` attribute
This PR makes sweeping changes to how the (currently-unstable) coverage attribute is validated:
- Multiple coverage attributes on the same item/expression are now treated as an error.
- The attribute must always be `#[coverage(off)]` or `#[coverage(on)]`, and the error messages for this are more consistent.
- A trailing comma is still allowed after off/on, since that's part of the normal attribute syntax.
- Some places that silently ignored a coverage attribute now produce an error instead.
- These cases were all clearly bugs.
- Some places that ignored a coverage attribute (with a warning) now produce an error instead.
- These were originally added as lints, but I don't think it makes much sense to knowingly allow new attributes to be used in meaningless places.
- Some of these errors might soon disappear, if it's easy to extend recursive coverage attributes to things like modules and impl blocks.
---
One of the goals of this PR is to lay a more solid foundation for making the coverage attribute recursive, so that it applies to all nested functions/closures instead of just the one it is directly attached to.
Fixes#126658.
This PR incorporates #126659, which adds more tests for validation of the coverage attribute.
`@rustbot` label +A-code-coverage
Ensure we don't accidentally succeed when we want to report an error
This also changes the `DefiningOpaqueTypes::No` to `Yes` without adding tests, as it is solely run on the error path to improve diagnostics. I was unable to provide a test that changes diagnostics, as all the tests I came up with ended up successfully constraining the opaque type and thus succeeding the coercion.
r? ```@compiler-errors```
cc https://github.com/rust-lang/rust/issues/116652
SmartPointer derive-macro
<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.
This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using
r? <reviewer name>
-->
Possibly replacing #123472 for continued upkeep of the proposal rust-lang/rfcs#3621 and implementation of the tracking issue #123430.
cc `@Darksonn` `@wedsonaf`
Remove `MaybeUninit::uninit_array()` and replace it with inline const blocks.
\[This PR originally contained the changes in #125995 too. See edit history for the original PR description.]
The documentation of `MaybeUninit::uninit_array()` says:
> Note: in a future Rust version this method may become unnecessary when Rust allows [inline const expressions](https://github.com/rust-lang/rust/issues/76001). The example below could then use `let mut buf = [const { MaybeUninit::<u8>::uninit() }; 32];`.
The PR adding it also said: <https://github.com/rust-lang/rust/pull/65580#issuecomment-544200681>
> if it’s stabilized soon enough maybe it’s not worth having a standard library method that will be replaceable with `let buffer = [MaybeUninit::<T>::uninit(); $N];`
That time has come to pass — inline const expressions are stable — so `MaybeUninit::uninit_array()` is now unnecessary. The only remaining question is whether it is an important enough *convenience* to keep it around.
I believe it is net good to remove this function, on the principle that it is better to compose two orthogonal features (`MaybeUninit` and array construction) than to have a specific function for the specific combination, now that that is possible.
Deprecate no-op codegen option `-Cinline-threshold=...`
This deprecates `-Cinline-threshold` since using it has no effect. This has been the case since the new LLVM pass manager started being used, more than 2 years ago.
Recommend using `-Cllvm-args=--inline-threshold=...` instead.
Closes#89742 which is E-help-wanted.
Show notice about "never used" of Debug for enum
Close#123068
If an ADT implements `Debug` trait and it is not used, the compiler says a note that indicates intentionally ignored during dead code analysis as [this note](2207179a59/tests/ui/lint/dead-code/unused-variant.stderr (L9)).
However this node is not shown for variants that have fields in enum. This PR fixes to show the note.
Save 2 pointers in `TerminatorKind` (96 → 80 bytes)
These things don't need to be `Vec`s; boxed slices are enough.
The frequent one here is call arguments, but MIR building knows the number of arguments from the THIR, so the collect is always getting the allocation right in the first place, and thus this shouldn't ever add the shrink-in-place overhead.
This is possible now that inline const blocks are stable; the idea was
even mentioned as an alternative when `uninit_array()` was added:
<https://github.com/rust-lang/rust/pull/65580#issuecomment-544200681>
> if it’s stabilized soon enough maybe it’s not worth having a
> standard library method that will be replaceable with
> `let buffer = [MaybeUninit::<T>::uninit(); $N];`
Const array repetition and inline const blocks are now stable (in the
next release), so that circumstance has come to pass, and we no longer
have reason to want `uninit_array()` other than convenience. Therefore,
let’s evaluate the inconvenience by not using `uninit_array()` in
the standard library, before potentially deleting it entirely.
Special case when a code line only has multiline span starts
Minimize multline span overlap when there are multiple of them starting on the same line:
```
3 | X0 Y0 Z0
| _____^ - -
| | _______| |
| || _________|
4 | ||| X1 Y1 Z1
5 | ||| X2 Y2 Z2
| |||____^__-__- `Z` label
| ||_____|__|
| |______| `Y` is a good letter too
| `X` is a good letter
```
It might make sense to allow this in the future, if we add values that aren't
mutually exclusive, but for now having multiple coverage attributes on one item
is useless.
Fix 32-bit Arm reg classes by hierarchically sorting them
We were rejecting legal `asm!` because we were asking for the "greatest" feature that includes a register class, instead of the "least" feature that includes a register class. This was only revealed on certain 32-bit Arm targets because not all have the same register limitations.
This is a somewhat hacky solution, but other solutions would require potentially rearchitecting how the internals of parsing or rejecting register classes work for all targets.
Fixes#126797
r? ``@Amanieu``
For [E0308]: mismatched types, when expr is in an arm's body, not add semicolon ';' at the end of it.
For [E0308]: mismatched types, when expr is in an arm's body, and it is the end expr without a semicolon of the block, not add semicolon ';' at the end of it.
fixes#126222
<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.
This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using
r? <reviewer name>
-->
Add hard error and migration lint for unsafe attrs
More implementation work for https://github.com/rust-lang/rust/issues/123757
This adds the migration lint for unsafe attributes, as well as making it a hard error in Rust 2024.
Remove confusing `use_polonius` flag and do less cloning
The `use_polonius` flag is both redundant and confusing since every function it's propagated to also checks if `all_facts` is `Some`, the true test of whether to generate Polonius facts for Polonius or for external consumers. This PR makes that path clearer by simply doing away with the argument and handling the logic in precisely two places: where facts are populated (check for `Some`), and where `all_facts` are initialised. It also delays some statements until after that check to avoid the miniscule performance penalty of executing them when Polonius is disabled.
This also addresses `@lqd's` concern in #125652 by reducing the size of what is cloned out of Polonius facts to just the facts being added, as opposed to the entire vector of potential inputs, and added descriptive comments.
*Reviewer note*: the comments in `add_extra_drop_facts` should be inspected by a reviewer, in particular the one on [L#259](https://github.com/rust-lang/rust/compare/master...amandasystems:you-dropped-this-again?expand=1#diff-aa727290e6670264df2face84f012897878e11a70e9c8b156543cfcd9619bac3R259) in this PR, which should be trivial for someone with the right background knowledge to address.
I also included some lints I found on the way there that I couldn't help myself from addressing.
Rework pattern and expression nonterminal kinds.
Some tweaks to `NonterminalKind` that will assist with #124141. Details in the individual commits.
r? compiler-errors
cc ```@eholk```
Replace `f16` and `f128` pattern matching stubs with real implementations
This section of code depends on `rustc_apfloat` rather than our internal types, so this is one potential ICE that we should be able to melt now.
r? `@Nadrieril`
This section of code depends on `rustc_apfloat` rather than our internal
types, so this is one potential ICE that we should be able to melt now.
This also fixes some missing range and match handling in `rustc_middle`.
Merge `PatParam`/`PatWithOr`, and `Expr`/`Expr2021`, for a few reasons.
- It's conceptually nice, because the two pattern kinds and the two
expression kinds are very similar.
- With expressions in particular, there are several places where both
expression kinds get the same treatment.
- It removes one unreachable match arm.
- Most importantly, for #124141 I will need to introduce a new type
`MetaVarKind` that is very similar to `NonterminalKind`, but records a
couple of extra fields for expression metavars. It's nicer to have a
single `MetaVarKind::Expr` expression variant to hold those extra
fields instead of duplicating them across two variants
`MetaVarKind::{Expr,Expr2021}`. And then it makes sense for patterns
to be treated the same way, and for `NonterminalKind` to also be
treated the same way.
I also clarified the comments, because I have long found them a little
hard to understand.
Remove use of const traits (and `feature(effects)`) from stdlib
The current uses are already unsound because they are using non-const impls in const contexts. We can reintroduce them by reverting the commit in this PR, after #120639 lands.
Also, make `effects` an incomplete feature.
cc `@rust-lang/project-const-traits`
r? `@compiler-errors`
Before if the closure passed to run_compiler emitted an error without
calling abort_if_errors and no diagnostics have been stashed,
run_compiler would return normally as if no error had occured.
Fix `...` in multline code-skips in suggestions
When we have long code skips, we write `...` in the line number gutter.
For suggestions, we were "centering" the `...` with the line, but that was inconsistent with what we do in every other case *and* off-center.
Add `f16` inline ASM support for 32-bit ARM
Adds `f16` inline ASM support for 32-bit ARM. SIMD vector types are taken from [here](https://developer.arm.com/architectures/instruction-sets/intrinsics/#f:`@navigationhierarchiesreturnbasetype=[float]&f:@navigationhierarchieselementbitsize=[16]&f:@navigationhierarchiesarchitectures=[A32]).`
Relevant issue: #125398
Tracking issue: #116909
`@rustbot` label +F-f16_and_f128
Added an associated `const THIS_IMPLEMENTATION_HAS_BEEN_TRIPLE_CHECKED`
to the `StableOrd` trait to ensure that implementors carefully consider
whether the trait's contract is upheld, as incorrect implementations can
cause miscompilations.
Add a tidy rule to check that fluent messages and attrs don't end in `.`
This adds a new dependency on `fluent-parse` to `tidy` -- we already rely on it in rustc so I feel like it's not that big of a deal.
This PR also adjusts many error messages that currently end in `.`; not all of them since I added an `ALLOWLIST`, excluded `rustc_codegen_*` ftl files, and `.teach_note` attributes.
r? ``@estebank`` ``@oli-obk``
Add `f16` inline ASM support for RISC-V
This PR adds `f16` inline ASM support for RISC-V. A `FIXME` is left for `f128` support as LLVM does not support the required `Q` (Quad-Precision Floating-Point) extension yet.
Relevant issue: #125398
Tracking issue: #116909
`@rustbot` label +F-f16_and_f128
These things don't need to be `Vec`s; boxed slices are enough.
The frequent one here is call arguments, but MIR building knows the number of arguments from the THIR, so the collect is always getting the allocation right in the first place, and thus this shouldn't ever add the shrink-in-place overhead.
Rename a bunch of things in the new solver and `rustc_type_ir`
* Renames `interner()` to `cx()` in the solver and `TypeFolder`.
* Renames `Infcx` generic param to `D`
* Moves `infcx.rs` to `delegate.rs`
r? lcnr
Stop sorting `Span`s' `SyntaxContext`, as that is incompatible with incremental
work towards https://github.com/rust-lang/rust/issues/90317
Luckily no one actually needed these to be sorted, so it didn't even affect diagnostics. I'm guessing they'd have been sorted by creation time anyway, so it wouldn't really have mattered.
r? `@cjgillot`
Rollup of 8 pull requests
Successful merges:
- #126125 (Improve conflict marker recovery)
- #126481 (Add `powerpc-unknown-openbsd` maintenance status)
- #126613 (Print the tested value in int_log tests)
- #126617 (Expand `avx512_target_feature` to include VEX variants)
- #126700 (Make edition dependent `:expr` macro fragment act like the edition-dependent `:pat` fragment does)
- #126707 (Pass target to inaccessible-temp-dir rmake test)
- #126767 (`StaticForeignItem` and `StaticItem` are the same)
- #126774 (Fix another assertion failure for some Expect diagnostics.)
r? `@ghost`
`@rustbot` modify labels: rollup
More ptr metadata gvn
There's basically 3 parts to this PR.
1. Allow references as arguments to `UnOp::PtrMetadata`
This is a MIR semantics addition, so
r? mir
Rather than just raw pointers, also allow references to be passed to `PtrMetadata`. That means the length of a slice can be just `PtrMetadata(_1)` instead of also needing a ref-to-pointer statement (`_2 = &raw *_1` + `PtrMetadata(_2)`).
AFAIK there should be no provenance or tagging implications of looking at the *metadata* of a pointer, and the code in the backends actually already supported it (other than a debug assert, given that they don't care about ptr vs reference, really), so we might as well allow it.
2. Simplify the argument to `PtrMetadata` in GVN
Because the specific kind of pointer-like thing isn't that important, GVN can simplify all those details away. Things like `*const`-to-`*mut` casts and `&mut`-to-`&` reborrows are irrelevant, and skipping them lets it see more interesting things.
cc `@cjgillot`
Notably, unsizing casts for arrays. GVN supported that for `Len`, and now it sees it for `PtrMetadata` as well, allowing `PtrMetadata(pointer)` to become a constant if that pointer came from an array-to-slice unsizing, even through a bunch of other possible steps.
3. Replace `NormalizeArrayLen` with GVN
The `NormalizeArrayLen` pass hasn't been running even in optimized builds for well over a year, and it turns out that GVN -- which *is* on in optimized builds -- can do everything it was trying to do.
So the code for the pass is deleted, but the tests are kept, just changed to the different pass.
As part of this, `LowerSliceLen` was changed to emit `PtrMetadata(_1)` instead of `Len(*_1)`, a small step on the road to eventually eliminating `Rvalue::Len`.
Fix another assertion failure for some Expect diagnostics.
Very similar to #126719. So much so that I added a new case to the test from that PR rather than creating a new one.
r? `@oli-obk`
`StaticForeignItem` and `StaticItem` are the same
The struct `StaticItem` and `StaticForeignItem` are the same, so remove `StaticForeignItem`. Having them be separate is unique to `static` items -- unlike `ForeignItemKind::{Fn,TyAlias}`, which use the normal AST item.
r? ``@spastorino`` or ``@oli-obk``
Make edition dependent `:expr` macro fragment act like the edition-dependent `:pat` fragment does
Parse the `:expr` fragment as `:expr_2021` in editions <=2021, and as `:expr` in edition 2024. This is similar to how we parse `:pat` as `:pat_param` in edition <=2018 and `:pat_with_or` in >=2021, and means we can get rid of a span dependency from `nonterminal_may_begin_with`.
Specifically, this fixes a theoretical regression since the `expr_2021` macro fragment previously would allow `const {}` if the *caller* is edition 2024. This is inconsistent with the way that the `pat` macro fragment was upgraded, and also leads to surprising behavior when a macro *caller* crate upgrades to edtion 2024, since they may have parsing changes that they never asked for (with no way of opting out of it).
This PR also allows using `expr_2021` in all editions. Why was this was disallowed in the first place? It's purely additive, and also it's still feature gated?
r? ```@fmease``` ```@eholk``` cc ```@vincenzopalazzo```
cc #123865
Tracking:
- https://github.com/rust-lang/rust/issues/123742
Expand `avx512_target_feature` to include VEX variants
Added 5 new target features for x86:
- `AVX-IFMA`
- `AVX-NE-CONVERT`
- `AVX-VNNI`
- `AVX-VNNI_INT8`
- `AVX-VNNI_INT16`
Both LLVM and GCC already have support for these.
See also the [stdarch PR](https://github.com/rust-lang/stdarch/pull/1586)
Improve conflict marker recovery
<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.
This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using
r? <reviewer name>
-->
closes#113826
r? ```@estebank``` since you reviewed #115413
cc: ```@rben01``` since you opened up the issue in the first place
`PtrMetadata` doesn't care about `*const`/`*mut`/`&`/`&mut`, so GVN away those casts in its argument.
This includes updating MIR to allow calling PtrMetadata on references too, not just raw pointers. That means that `[T]::len` can be just `_0 = PtrMetadata(_1)`, for example.
# Conflicts:
# tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-abort.mir
# tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-unwind.mir
Properly gate `safe` keyword in pre-expansion
This PR gates `safe` keyword in pre-expansion contexts. Should mitigate the fallout of https://github.com/rust-lang/rust/issues/126755, which is that `safe` is now usable on beta lol.
r? `@spastorino` or `@oli-obk`
cc #124482 tracking #123743
Account for things that optimize out in inlining costs
This updates the MIR inlining `CostChecker` to have both bonuses and penalties, rather than just penalties.
That lets us add bonuses for some things where we want to encourage inlining without risking wrapping into a gigantic cost. For example, `switchInt(const …)` we give an inlining bonus because codegen will actually eliminate the branch (and associated dead blocks) once it's monomorphized, so measuring both sides of the branch gives an unrealistically-high cost to it. Similarly, an `unreachable` terminator gets a small bonus, because whatever branch leads there doesn't actually exist post-codegen.