Test cross-crate usage of `feature(const_trait_impl)`
This PR does two things:
- Fixes metadata not encoded properly for functions in const trait impls.
- Adds tests for using const trait impls cross-crate with the feature gate on the user crate either enabled or disabled.
AFAIK, this means we can now constify some trait impls in the standard library 🎉
See #67792 for the tracking issue, cc `@oli-obk`
Check node kind to avoid ICE in `check_expr_return()`
This PR fixes#86721. The ICE described there is apparently due to a misunderstanding:
e98897e5dc/compiler/rustc_typeck/src/check/expr.rs (L684-L685)
Intuitively, one would think that calling `expect_item()` after `get_parent_item()` should succeed, but as it turns out, `get_parent_item()` can also return foreign, trait, and impl items as well as crates, whereas `expect_item()` specifically expects a `Node::Item`. I have therefore added an extra check to prevent this ICE.
There are several cases where names of types and functions in the debug info are either ambiguous, or not helpful, such as including ambiguous placeholders (e.g., `{{impl}}`, `{{closure}}` or `dyn _'`) or dropping qualifications (e.g., for dynamic types).
Instead, each debug symbol name should be unique and useful:
* Include disambiguators for anonymous `DefPathDataName` (closures and generators), and unify their formatting when used as a path-qualifier vs item being qualified.
* Qualify the principal trait for dynamic types.
* If there is no principal trait for a dynamic type, emit all other traits instead.
* Respect the `qualified` argument when emitting ref and pointer types.
* For implementations, emit the disambiguator.
* Print const generics when emitting generic parameters or arguments.
Additionally, when targeting MSVC, its debugger treats many command arguments as C++ expressions, even when the argument is defined to be a symbol name. As such names in the debug info need to be more C++-like to be parsed correctly:
* Avoid characters with special meaning (`#`, `[`, `"`, `+`).
* Never start a name with `<` or `{` as this is treated as an operator.
* `>>` is always treated as a right-shift, even when parsing generic arguments (so add a space to avoid this).
* Emit function declarations using C/C++ style syntax (e.g., leading return type).
* Emit arrays as a synthetic `array$<type, size>` type.
* Include a `$` in all synthetic types as this is a legal character for C++, but not Rust (thus we avoid collisions with user types).
This PR adds ability for the target specifications to specify frame
pointer emission type that's not just “always” or “whatever cg decides”.
In particular there's a new mode that allows omission of the frame
pointer for leaf functions (those that don't call any other functions).
We then set this new mode for Aarch64-based Apple targets.
Fixes#86196
Introduce -Zprofile-closures to evaluate the impact of 2229
This creates a CSV with name "closure_profile_XXXXX.csv", where the
variable part is the process id of the compiler.
To profile a cargo project you can run one of the following depending on
if you're compiling a library or a binary:
```
cargo +nightly rustc --lib -- -Zprofile-closures
cargo +nightly rustc --bin {binary_name} -- -Zprofile-closures
```
r? `@nikomatsakis`
Only include lint in future_incompatible lint group if not an edition lint
A follow up to #86330 - this only includes lints annotated with `FutureIncompatibleInfo` in the `future_incompatibile` lint group if the future compatibility is not tied to an edition.
We probably want to rename `FutureIncompatibleInfo` to something else since this type is now used to indicate future breakages of all kinds (even those that happen in editions). I'd prefer to do that in a separate PR though.
r? `@nikomatsakis`
Change vtable memory representation to use tcx allocated allocations.
This fixes https://github.com/rust-lang/rust/issues/86324. However i suspect there's more to change before it can land.
r? `@bjorn3`
cc `@rust-lang/miri`
One key observation while going over the closure size profile of rustc
was that we are disjointly capturing one or more fields starting at an
immutable reference.
Disjoint capture over immutable reference doesn't add too much value
because the fields can either be borrowed immutably or copied.
One possible edge case of the optimization is when a fields of a struct
have a longer lifetime than the structure, therefore we can't completely
get rid of all the accesses on top of sharef refs, only the rightmost
one. Here is a possible example:
```rust
struct MyStruct<'a> {
a: &'static A,
b: B,
c: C<'a>,
}
fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
let c = || drop(&*m.a.field_of_a);
// Here we really do want to capture `*m.a` because that outlives `'static`
// If we capture `m`, then the closure no longer outlives `'static'
// it is constrained to `'a`
}
```
Don't make `rustc_insignificant_dtor` feature gate
This isn't a feature gate, it's an attribute that is feature gated behind the `rustc_attrs` attribute. Closes#85680.
Fix garbled suggestion for missing lifetime specifier
This PR fixes#86667. The suggestion code currently checks whether there is a generic parameter that is not a synthetic `impl Trait` parameter and, if so, suggests to insert a new lifetime `'a` before that generic parameter. However, it does not make sense to insert `'a` in front of an elided lifetime parameter, since these are synthetic as well, which leads to the garbled suggestion in #86667.
Turn non_fmt_panic into a future_incompatible edition lint.
This turns the `non_fmt_panic` lint into a future_incompatible edition lint, so it becomes part of the `rust_2021_compatibility` group. See https://github.com/rust-lang/rust/issues/85894.
This lint produces both warnings about semantical changes (e.g. `panic!("{{")`) and things that will become hard errors (e.g. `panic!("{")`). So I added a `explain_reason: false` that supresses the default "this will become a hard error" or "the semantics will change" message, and instead added a note depending on the situation. (cc `@rylev)`
r? `@nikomatsakis`
Fix `future_prelude_collision` false positive
Fixes#86633
The lint for checking if method resolution of methods named `try_into` will fail in 2021 edition previously would fire on all inherent methods, however for inherent methods that consume `self`, this takes priority over `TryInto::try_into` due to being inherent, while trait method and methods that take `&self` or `&mut self` don't take priority, and thus aren't affected by this false positive.
This fix is rather simple: simply checking if the inherent method doesn't auto-deref or auto-ref (and thus takes `self`) and if so, prevents the lint from firing.
This prevents mistakes where the feature is in the list of incomplete
features but not actually a feature by making the incompleteness a part
of the declaration.
This creates a CSV with name "closure_profile_XXXXX.csv", where the
variable part is the process id of the compiler.
To profile a cargo project you can run one of the following depending on
if you're compiling a library or a binary:
```
cargo +stage1 rustc --lib -- -Zprofile-closures
cargo +stage1 rustc --bin -- -Zprofile-closures
```
Fix type checking of return expressions outside of function bodies
This pull request fixes#86188. The problem is that the current code for type-checking `return` expressions stops if the `return` occurs outside of a function body, while the correct behavior is to continue type-checking the return value expression (otherwise an ICE happens later on because variables declared in the return value expression don't have a type).
Also, I have noticed that it is sometimes not obvious why a `return` is outside of a function body; for instance, in the example from #86188 (which currently causes an ICE):
```rust
fn main() {
[(); return || {
let tx;
}]
}
```
I have changed the error message to also explain why the `return` is considered outside of the function body:
```
error[E0572]: return statement outside of function body
--> ice0.rs:2:10
|
1 | / fn main() {
2 | | [(); return || {
| |__________^
3 | || let tx;
4 | || }]
| ||_____^ the return is part of this body...
5 | | }
| |_- ...not the enclosing function body
```
Reserve prefixed identifiers and literals (RFC 3101)
This PR denies any identifiers immediately followed by one of three tokens `"`, `'` or `#`, which is stricter than the requirements of RFC 3101 but may be necessary according to the discussion at [Zulip].
[Zulip]: https://rust-lang.zulipchat.com/#narrow/stream/268952-edition-2021/topic/reserved.20prefixes/near/238470099
The tracking issue #84599 says we'll add a feature gate named `reserved_prefixes`, but I don't think I can do this because it is impossible for the lexer to know whether a feature is enabled or not. I guess determining the behavior by the edition information should be enough.
Fixes#84599
2229: Capture box completely in move closures
Even if the content from box is used in a sharef-ref context,
we capture the box entirerly.
This is motivated by:
1) We only capture data that is on the stack.
2) Capturing data from within the box might end up moving more data than
the user anticipated.
Closes https://github.com/rust-lang/project-rfc-2229/issues/50
r? `@nikomatsakis`
Fix ICE with `-Zunpretty=hir,typed`
This PR fixes#82328. The `-Zunpretty=hir,typed` pretty-printer maintains an `Option` with type-checking results and sets the `Option` to `Some` when entering a body. However, this leads to an ICE if an expression occurs in a function signature (i.e. outside of a body), such as `128` in
```rust
fn foo(-128..=127: i8) {}
```
This PR fixes the ICE by checking (if necessary) whether the expression's owner has a body, and retrieving type-checking results for that on the fly.
Allow loading of llvm plugins on nightly
Based on a discussion in #82734 / with `@wsmoses.`
Mainly moves [this](0149bc4e7e) behind a -Z flag, so it can only be used on nightly,
as requested by `@nagisa` in https://github.com/rust-lang/rust/issues/82734#issuecomment-835863940
This change allows loading of llvm plugins like Enzyme.
Right now it also requires a shared library LLVM build of rustc for symbol resolution.
```rust
// test.rs
extern { fn __enzyme_autodiff(_: usize, ...) -> f64; }
fn square(x : f64) -> f64 {
return x * x;
}
fn main() {
unsafe {
println!("Hello, world {} {}!", square(3.0), __enzyme_autodiff(square as usize, 3.0));
}
}
```
```
./rustc test.rs -Z llvm-plugins="./LLVMEnzyme-12.so" -C passes="enzyme"
./test
Hello, world 9 6!
```
I will try to figure out how to simplify the usage and get this into stable in a later iteration,
but having this on nightly will already help testing further steps.
Use HTTPS links where possible
While looking at #86583, I wondered how many other (insecure) HTTP links were in `rustc`. This changes most other `http` links to `https`. While most of the links are in comments or documentation, there are a few other HTTP links that are used by CI that are changed to HTTPS.
Notes:
- I didn't change any to or in licences
- Some links don't support HTTPS :(
- Some `http` links were dead, in those cases I upgraded them to their new places (all of which used HTTPS)
Check that `#[cmse_nonsecure_entry]` is applied to a function definition
This PR fixes#83475. The compiler currently neglects to check whether `#[cmse_nonsecure_entry]` is applied to a function (and not, say, a struct) definition, leading to an ICE later on when the type checker attempts to retrieve the function signature. I have fixed this problem by adding an appropriate check to the `check_attr` pass, so that an error is reported instead of an ICE.
Rollup of 5 pull requests
Successful merges:
- #86330 (Change how edition based future compatibility warnings are handled)
- #86513 (Rustdoc: Do not list impl when trait has doc(hidden))
- #86592 (Use `#[non_exhaustive]` where appropriate)
- #86608 (chore(rustdoc): remove unused members of RenderType)
- #86624 (Update compiler-builtins)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Use `#[non_exhaustive]` where appropriate
Due to the std/alloc split, it is not possible to make `alloc::collections::TryReserveError::AllocError` non-exhaustive without having an unstable, doc-hidden method to construct (which negates the benefits from `#[non_exhaustive]`).
`@rustbot` label +C-cleanup +T-libs +S-waiting-on-review
rustc_data_structures has a dependency on crossbeam-utils but never uses
it. It appears to have originally had this dependency in order to set
the "nightly" feature; however, its other dependencies use a different
version of crossbeam-utils, so this doesn't actually affect anything.
Furthermore, in current crossbeam-utils, the "nightly" feature has
become a no-op.
The sha-1 and md-5 packages contain crates named sha1 and md5,
respectively. This discrepancy makes it somewhat more challenging to
automate detection of unused crates. Explicitly rename the packages to
the names of the crates they contain, to simplify such detection.
Don't lint :pat when re-parsing a macro from another crate.
`compile_macro` is used both when compiling the original definition in the crate that defines it, and to compile the macro when loading it when compiling a crate that uses it. We should only emit lints in the first case.
This adds a `is_definition: bool` to pass this information in, so we don't warn about things that only concern the definition site.
Fixes#86567
Even if the content from box is used in a sharef-ref context,
we capture the box entirerly.
This is motivated by:
1) We only capture data that is on the stack.
2) Capturing data from within the box might end up moving more data than
the user anticipated.
Fix use placement for suggestions near main.
This fixes an edge case for the suggestion to add a `use`. When running with `--test`, the `main` function will be annotated with an `#[allow(dead_code)]` attribute. The `UsePlacementFinder` would end up using the dummy span of that synthetic attribute. If there are top-level inner attributes, this would place the `use` in the wrong position. The solution here is to ignore attributes with dummy spans.
In the process of working on this, I discovered that the `use_suggestion_placement` test was broken. `UsePlacementFinder` is unaware of active attributes. Attributes like `#[derive]` don't exist in the AST since they are removed. Fixing that is difficult, since the AST does not retain enough information. I considered trying to place the `use` towards the top of the module after any `extern crate` items, but I couldn't find a way to get a span for the start of a module block (the `mod` span starts at the `mod` keyword, and it seems tricky to find the spot just after the opening bracket and past inner attributes). For now, I just put some comments about the issue. This appears to have been a known issue in #44215 where the test for it was introduced, and the fix seemed to be deferred to later.
Due to the std/alloc split, it is not possible to make
`alloc::collections::TryReserveError::AllocError` non-exhaustive without
having an unstable, doc-hidden method to construct (which negates the
benefits from `#[non_exhaustive]`.
Permit zero non-zero-field on transparent types
Fixes#77841
This makes the transparent fields meet the below:
> * A `repr(transparent)` type `T` must meet the following rules:
> * It may have any number of 1-ZST fields
> * In addition, it may have at most one other field of type U
r? `@nikomatsakis`
Support lowercase error codes in `--explain`
This enables `rustc --explain` to accept a lowercase error code. Thus, for instance, `rustc --explain e0573` would be valid after this change, where before a user would have needed to do `rustc --explain E0573`. Although the upper case form of an error code is canonical, the user may prefer the easier-to-type lowercase form, and there's nothing to be gained by forcing them to type the upper case version.
Resolves#86518.
Error code cleanup and enforce checks
Fixes#86097.
It now checks if an error code is unused, and if so, will report an error if the error code wasn't commented out in the `error_codes.rs` file. It also checks that the constant used in the tidy check is up-to-date.
r? `@Mark-Simulacrum`
Check whether the closure's owner is an ADT in thir-unsafeck
This pull request fixes#85871. The code in `rustc_mir_build/src/check_unsafety.rs` incorrectly assumes that a closure's owner always has a body, but only functions, closures, and constants have bodies, whereas a closure can also appear inside a struct or enum:
```rust
struct S {
arr: [(); match || 1 { _ => 42 }]
}
enum E {
A([(); { || 1; 42 }])
}
```
This pull request fixes the resulting ICE by checking whether the closure's owner is an ADT and only deferring to `thir_check_unsafety(owner)` if it isn't.
Better errors for Debug and Display traits
Currently, if someone tries to pass value that does not implement `Debug` or `Display` to a formatting macro, they get a very verbose and confusing error message. This PR changes the error messages for missing `Debug` and `Display` impls to be less overwhelming in this case, as suggested by #85844. I was a little less aggressive in changing the error message than that issue proposed. Still, this implementation would be enough to reduce the number of messages to be much more manageable.
After this PR, information on the cause of an error involving a `Debug` or `Display` implementation would suppressed if the requirement originated within a standard library macro. My reasoning was that errors originating from within a macro are confusing when they mention details that the programmer can't see, and this is particularly problematic for `Debug` and `Display`, which are most often used via macros. It is possible that either a broader or a narrower criterion would be better. I'm quite open to any feedback.
Fixes#85844.
Rollup of 6 pull requests
Successful merges:
- #86223 (Specify the kind of the item for E0121)
- #86521 (Add comments around code where ordering is important due for panic-safety)
- #86523 (Improvements to intra-doc link macro disambiguators)
- #86542 (Line numbers aligned with content)
- #86549 (Add destructuring example of E0508)
- #86557 (Update books)
Failed merges:
- #86548 (Fix crate filter search reset)
r? `@ghost`
`@rustbot` modify labels: rollup
Re-add support for parsing (and pretty-printing) inner-attributes in match body
Re-add support for parsing (and pretty-printing) inner-attributes within body of a `match`.
In other words, we can do `match EXPR { #![inner_attr] ARM_1 ARM_2 ... }` again.
I believe this unbreaks the only four crates that crater flagged as broken by PR #83312.
(I am putting this up so that the lang-team can check it out and decide whether it changes their mind about what to do regarding PR #83312.)
Fix emit path hashing
With `--emit KIND=PATH`, the PATH should not affect hashes used for dependency tracking. It does not with other ways of specifying output paths (`-o` or `--out-dir`).
Also updates `rustc -Zls` to print more info about crates, which is used here to implement a `run-make` test.
It seems there was already a test explicitly checking that `OutputTypes` hash *is* affected by the path. I think this behaviour is wrong, so I updated the test.
Disambiguate between SourceFiles from different crates even if they have the same path
This PR fixes an ICE that can occur when the compiler encounters a source file that is part of both the local crate and an upstream crate:
1. While importing source files from an upstream crate the compiler creates a `SourceFile` entry for `foo.rs` in the `SourceMap`. Since this is an imported source file its `src` field is `None`.
2. At a later point the parser encounters `foo.rs` again. It tells the `SourceMap` to load the file but because we already have an entry for `foo.rs` the `SourceMap` will return the existing version with `src == None`.
3. The parser proceeds under the assumption that `src.is_some()` and panics when actually trying to use the file's contents.
This PR fixes the issue by adding the source file's associated `CrateNum` to the `SourceMap`'s interning key. As a consequence the two instances of the file will each have a separate entry in the `SourceMap`. They just happen to share the same file path. This approach seemed less problematic to me than trying to mutate the `SourceFile` after it had already been created.
Another, more involved, approach might be to merge the `src` and the `external_src` field.
Fixes#85955
Fix `unused_unsafe` around `await`
Enables `unused_unsafe` lint for `unsafe { future.await }`.
The existing test for this is `unsafe { println!() }`, so I assume that `println!` used to contain compiler-generated unsafe but this is no longer true, and so the existing test is broken. I replaced the test with `unsafe { ...await }`. I believe `await` is currently the only instance of compiler-generated unsafe.
Reverts some parts of #85421, but the issue predates that PR.
Add `future_prelude_collision` lint
Implements #84594. (RFC rust-lang/rfcs#3114 ([rendered](https://github.com/rust-lang/rfcs/blob/master/text/3114-prelude-2021.md))) Not entirely complete but wanted to have my progress decently available while I finish off the last little bits.
Things left to implement:
* [x] UI tests for lints
* [x] Only emit lint for 2015 and 2018 editions
* [ ] Lint name/message bikeshedding
* [x] Implement for `FromIterator` (from best I can tell, the current approach as mentioned from [this comment](https://github.com/rust-lang/rust/issues/84594#issuecomment-847288288) won't work due to `FromIterator` instances not using dot-call syntax, but if I'm correct about this then that would also need to be fixed for `TryFrom`/`TryInto`)*
* [x] Add to `rust-2021-migration` group? (See #85512) (added to `rust-2021-compatibility` group)
* [ ] Link to edition guide in lint docs
*edit: looked into it, `lookup_method` will also not be hit for `TryFrom`/`TryInto` for non-dotcall syntax. If anyone who is more familiar with typecheck knows the equivalent for looking up associated functions, feel free to chime in.
Rollup of 11 pull requests
Successful merges:
- #85054 (Revert SGX inline asm syntax)
- #85182 (Move `available_concurrency` implementation to `sys`)
- #86037 (Add `io::Cursor::{remaining, remaining_slice, is_empty}`)
- #86114 (Reopen#79692 (Format symbols under shared frames))
- #86297 (Allow to pass arguments to rustdoc-gui tool)
- #86334 (Resolve type aliases to the type they point to in intra-doc links)
- #86367 (Fix comment about rustc_inherit_overflow_checks in abs().)
- #86381 (Add regression test for issue #39161)
- #86387 (Remove `#[allow(unused_lifetimes)]` which is now unnecessary)
- #86398 (Add regression test for issue #54685)
- #86493 (Say "this enum variant takes"/"this struct takes" instead of "this function takes")
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Say "this enum variant takes"/"this struct takes" instead of "this function takes"
This makes error messages for functions with incorrect argument counts adapt if they refer to a struct or enum variant:
```
error[E0061]: this enum variant takes 1 argument but 0 arguments were supplied
--> $DIR/struct-enum-wrong-args.rs:7:13
|
LL | let _ = Ok();
| ^^-- supplied 0 arguments
| |
| expected 1 argument
error[E0061]: this struct takes 1 argument but 0 arguments were supplied
--> $DIR/struct-enum-wrong-args.rs:8:13
|
LL | let _ = Wrapper();
| ^^^^^^^-- supplied 0 arguments
| |
| expected 1 argument
```
Fixes#86481.
Add MIR pass to lower call to `core::slice::len` into `Len` operand
During some larger experiment with range analysis I've found that code like `let l = slice.len()` produces different MIR then one found in bound checks. This optimization pass replaces terminators that are calls to `core::slice::len` with just a MIR operand and Goto terminator.
It uses some heuristics to remove the outer borrow that is made to call `core::slice::len`, but I assume it can be eliminated, just didn't find how.
Would like to express my gratitude to `@oli-obk` who helped me a lot on Zullip
Emit warnings for unused fields in custom targets.
Add a warning which lists any fields in a custom target `json` file that aren't used. Currently unrecognized fields are ignored so, for example, a typo in the `json` will silently produce a target which isn't the one intended.
Do not emit alloca for ZST locals with multiple assignments
This extends 35566bfd7d to additionally stop emitting unnecessary allocas for zero sized locals that are assigned multiple times.
When rebuilding the standard library with `-Zbuild-std` this reduces the number of locals that require an allocation from 62315 to 61767.
Replace some `std::iter::repeat` with `str::repeat`
I noticed that there were some instances where `std::iter::repeat` would be used to repeat a string or a char to take a specific count of it and then collect it into a `String` when `str::repeat` is actually much faster and better for that.
See also: https://github.com/rust-lang/rust-clippy/issues/7260.