Originally, there has been a dedicated pass for renumbering
AST NodeIds to have actual values. This pass had been added by
commit a5ad4c3794.
Then, later, this step was moved to where it resides now,
macro expansion. See commit c86c8d41a2
or PR #36438.
The comment snippet, added by the original commit, has
survived the times without any change, becoming outdated
at removal of the dedicated pass.
Nowadays, grepping for the next_node_id function will show up
multiple places in the compiler that call it, but the main
rewriting that the comment talks about is still done in the
expansion step, inside an innocious looking visit_id function
that's called during macro invocation collection.
Changes from 68965 extended the kind of instances that are being
inlined. For some of those, the `instance_mir` returns a MIR body that
is already expressed in terms of the types found in substitution array,
and doesn't need further substitution.
Use `substs_for_mir_body` to take that into account.
Previously, trying to allow this would give another error!
```
warning: unknown lint: `private_intra_doc_links`
--> private.rs:1:10
|
1 | #![allow(private_intra_doc_links)]
| ^^^^^^^^^^^^^^^^^^^^^^^ help: did you mean: `broken_intra_doc_links`
|
= note: `#[warn(unknown_lints)]` on by default
warning: public documentation for `DocMe` links to private item `DontDocMe`
--> private.rs:2:11
|
2 | /// docs [DontDocMe]
| ^^^^^^^^^ this item is private
|
= note: `#[warn(private_intra_doc_links)]` on by default
= note: this link will resolve properly if you pass `--document-private-items`
```
reverse binding order in matches to allow the subbinding of copyable fields in bindings after @
Fixes#69971
### TODO
- [x] Regression tests
r? `@oli-obk`
Inliner copies the unevaluated constants from the callee body to the
caller at the point where decision to inline is yet to be made. The
constants will be unnecessary if inlining were to fail.
Organize the code moving items from callee to the caller together in one
place to avoid the issue.
Provide diagnostic suggestion in ExprUseVisitor Delegate
The [Delegate trait](981346fc07/compiler/rustc_typeck/src/expr_use_visitor.rs (L28-L38)) currently use `PlaceWithHirId` which is composed of Hir `Place` and the
corresponding expression id.
Even though this is an accurate way of expressing how a Place is used,
it can cause confusion during diagnostics.
Eg:
```
let arr : [String; 5];
let [a, ...] = arr;
^^^ E1 ^^^ = ^^E2^^
```
Here `arr` is moved because of the binding created E1. However, when we
point to E1 in diagnostics with the message `arr` was moved, it can be
confusing. Rather we would like to report E2 to the user.
Closes: https://github.com/rust-lang/project-rfc-2229/issues/20
r? `@ghost`
Refactorings in preparation for const value trees
cc #72396
This PR changes the `Scalar::Bits { data: u128, size: u8 }` variant to `Scalar::Bits(ScalarInt)` where `ScalarInt` contains the same information, but is `repr(packed)`. The reason for using a packed struct is to allow enum variant packing to keep the original size of `Scalar` instead of adding another word to its size due to padding.
Other than that the PR just gets rid of all the inspection of the internal fields of `Scalar::Bits` which were frankly scary. These fields have invariants that we need to uphold and we can't do that without making the fields private.
r? `@ghost`
Use reparsed `TokenStream` if we captured any inner attributes
Fixes#78675
We now bail out of `prepend_attrs` if we ended up capturing any inner
attributes (which can happen in several places, due to token capturing
for `macro_rules!` arguments.
Hash both the length and the end location (line/column) of a span. If we
hash only the length, for example, then two otherwise equal spans with
different end locations will have the same hash. This can cause a
problem during incremental compilation wherein a previous result for a
query that depends on the end location of a span will be incorrectly
reused when the end location of the span it depends on has changed. A
similar analysis applies if some query depends specifically on the
length of the span, but we only hash the end location. So hash both.
Fix#46744, fix#59954, fix#63161, fix#73640, fix#73967, fix#74890, fix#75900
Corrected suggestion for generic parameters in `function_item_references` lint
This commit handles functions with generic type parameters like you pointed out as well as const generics. Also this is probably a minor thing, but the type alias you used in the example doesn't show up so the suggestion right now would be `size_of::<[u8; 16]> as fn() ->`. This is because the lint checker works with MIR instead of HIR. I don't think we can get the alias at that point, but let me know if I'm wrong and there's a way to fix this. Also I put you as the reviewer, but I'm not sure if you want to review it or if it makes more sense to ask one of the original reviewers of this lint.
closes#78571
Improve errors about #[deprecated] attribute
This change:
1. Turns `#[deprecated]` on a trait impl block into an error, which fixes#78625;
2. Changes these and other errors about `#[deprecated]` to use the span of the attribute instead of the item; and
3. Turns this error into a lint, to make sure it can be capped with `--cap-lints` and doesn't break any existing dependencies.
Can be reviewed per commit.
---
Example:
```rust
struct X;
#[deprecated = "a"]
impl Default for X {
#[deprecated = "b"]
fn default() -> Self {
X
}
}
```
Before:
```
error: This deprecation annotation is useless
--> src/main.rs:6:5
|
6 | / fn default() -> Self {
7 | | X
8 | | }
| |_____^
```
After:
```
error: this `#[deprecated]' annotation has no effect
--> src/main.rs:3:1
|
3 | #[deprecated = "a"]
| ^^^^^^^^^^^^^^^^^^^ help: try removing the deprecation attribute
|
= note: `#[deny(useless_deprecated)]` on by default
error: this `#[deprecated]' annotation has no effect
--> src/main.rs:5:5
|
5 | #[deprecated = "b"]
| ^^^^^^^^^^^^^^^^^^^ help: try removing the deprecation attribute
```
Add support for SHA256 source file hashing
Adds support for `-Z src-hash-algorithm sha256`, which became available in LLVM 11.
Using an older version of LLVM will cause an error `invalid checksum kind` if the hash algorithm is set to sha256.
r? `@eddyb`
cc #70401 `@est31`
Properly handle lint spans after MIR inlining
The first commit shows what happens when we apply mir inlining and then cause lints on the inlined MIR.
The second commit fixes that.
r? `@wesleywiser`
Retagging: do not retag 'raw reborrows'
When doing `&raw const (*raw_ptr).field`, we do not want any retagging; the original provenance should be fully preserved.
Fixes https://github.com/rust-lang/miri/issues/1608
Test added by https://github.com/rust-lang/miri/pull/1614
Not sure whom to ask for review on this... `@oli-obk` can you have a look? Or maybe highfive makes a good choice.^^
This is helpful when looking for CGUs where the size estimate isn't a
good indicator of compilation time.
I verified that moving the profiling timer call doesn't affect the
results.
add mipsel-unknown-none target
This adds a target for bare MIPS32r2, little endian, softfloat. This target can be used for PIC32 microcontrollers (or possibly for other devices that have a MIPS MCU core such as the M4K core).
Tried to find a name for the target that is in line with the naming scheme apparently used for the other MIPS targets.
r? `@jonas-schievink`
Fix ICE when a future-incompat-report has its command-line level capped
Fixes#78660
With PR https://github.com/rust-lang/rust/pull/75534 merged, we now run
more lint-related code for future-incompat-report, even when their final
level is Allow. Some lint-related code was not expecting `Level::Allow`,
and had an explicit panic.
This PR explicitly tracks the lint level set on the command line before
`--cap-lints` is applied. This is used to emit a more precise error
note (e.g. we don't say that `-W lint-name` was specified on the
command line just because a lint was capped to Warn). As a result, we
can now correctly emit a note that `-A` was used if we got
`Level::Allow` from the command line (before the cap is applied).
Treat trailing semicolon as a statement in macro call
See #61733 (comment)
We now preserve the trailing semicolon in a macro invocation, even if
the macro expands to nothing. As a result, the following code no longer
compiles:
```rust
macro_rules! empty {
() => { }
}
fn foo() -> bool { //~ ERROR mismatched
{ true } //~ ERROR mismatched
empty!();
}
```
Previously, `{ true }` would be considered the trailing expression, even
though there's a semicolon in `empty!();`
This makes macro expansion more token-based.
foreign_modules query hash table lookups
When compiling a large monolithic crate we're seeing huge times in the `foreign_modules` query due to repeated iteration over foreign modules (in order to find a module by its id). This implements hash table lookups so that which massively reduces time spent in that query in this particular case. We'll need to see if the overhead of creating the hash table has a negative impact on performance in more normal compilation scenarios.
I'm working with `@wesleywiser` on this.
Fixes#78675
We now bail out of `prepend_attrs` if we ended up capturing any inner
attributes (which can happen in several places, due to token capturing
for `macro_rules!` arguments.
See https://github.com/rust-lang/rust/issues/61733#issuecomment-716188981
We now preserve the trailing semicolon in a macro invocation, even if
the macro expands to nothing. As a result, the following code no longer
compiles:
```rust
macro_rules! empty {
() => { }
}
fn foo() -> bool { //~ ERROR mismatched
{ true } //~ ERROR mismatched
empty!();
}
```
Previously, `{ true }` would be considered the trailing expression, even
though there's a semicolon in `empty!();`
This makes macro expansion more token-based.
Transform post order walk to an iterative approach
The previous recursive approach might overflow the stack when walking a
particularly deep, list-like, graph. In particular, dominator
calculation for borrow checking does such a traversal and very long
functions might lead to a region dependency graph with in this
problematic structure.
This addresses what appears to be the cause of #78567 (`@SunHao-0` thanks for the stack trace).
Rollup of 5 pull requests
Successful merges:
- #78606 (Clarify handling of final line ending in str::lines())
- #78610 (Do not remove tokens before AST json serialization)
- #78620 (Trivial fixes to bitwise operator documentation)
- #78627 (Point out that total_cmp is no strict superset of partial comparison)
- #78637 (Add fetch_update methods to AtomicBool and AtomicPtr)
Failed merges:
r? `@ghost`
Fixes#78660
With PR https://github.com/rust-lang/rust/pull/75534 merged, we now run
more lint-related code for future-incompat-report, even when their final
level is Allow. Some lint-related code was not expecting `Level::Allow`,
and had an explicit panic.
This PR explicitly tracks the lint level set on the command line before
`--cap-lints` is applied. This is used to emit a more precise error
note (e.g. we don't say that `-W lint-name` was specified on the
command line just because a lint was capped to Warn). As a result, we
can now correctly emit a note that `-A` was used if we got
`Level::Allow` from the command line (before the cap is applied).
The [Delegate
trait](981346fc07/compiler/rustc_typeck/src/expr_use_visitor.rs (L28-L38))
currently use `PlaceWithHirId` which is composed of Hir `Place` and the
corresponding expression id.
Even though this is an accurate way of expressing how a Place is used,
it can cause confusion during diagnostics.
Eg:
```
let arr : [String; 5];
let [a, ...] = arr;
^^^ E1 ^^^ = ^^E2^^
```
Here `arr` is moved because of the binding created E1. However, when we
point to E1 in diagnostics with the message `arr` was moved, it can be
confusing. Rather we would like to report E2 to the user.
Closes: https://github.com/rust-lang/project-rfc-2229/issues/20
Do not remove tokens before AST json serialization
`TokenStripper` is error-prone and introduces one more use of `MutVisitor`.
It's much simpler to treat serialization as just one more place that wants lazy token stream to turn into a real token stream.
Also, no code is better than more code, in general.
r? @Aaron1011
(I also merged tests for `TokenStripper` ICEs into one.)
Add option to customize the nll-facts' folder location
This PR adds a `nll-facts-dir` option to specify the location of the directory in which NLL facts are dumped into. It works the same way `dump-mir-dir` controls the location used by the `dump-mir` option.
This lint was incorrectly suggesting casting a function to a pointer without
specifying generic type parameters or const generics. This would cause a
compiler error since the missing parameters couldn't be inferred. This commit
fixed the suggestion and added a few tests with generics.
Implement -Z relax-elf-relocations=yes|no
This lets rustc users tweak whether the linker should relax ELF relocations without recompiling a whole new target with its own libcore etc.
Implement rustc side of report-future-incompat
cc https://github.com/rust-lang/rust/issues/71249
This is an alternative to `@pnkfelix's` initial implementation in https://github.com/pnkfelix/rust/commits/prototype-rustc-side-of-report-future-incompat (mainly because I started working before seeing that branch 😄 ).
My approach outputs the entire original `Diagnostic`, in a way that is compatible with incremental compilation. This is not yet integrated with compiletest, but can be used manually by passing `-Z emit-future-incompat-report` to `rustc`.
Several changes are made to support this feature:
* The `librustc_session/lint` module is moved to a new crate `librustc_lint_defs` (name bikesheddable). This allows accessing lint definitions from `librustc_errors`.
* The `Lint` struct is extended with an `Option<FutureBreakage>`. When present, it indicates that we should display a lint in the future-compat report. `FutureBreakage` contains additional information that we may want to display in the report (currently, a `date` field indicating when the crate will stop compiling).
* A new variant `rustc_error::Level::Allow` is added. This is used when constructing a diagnostic for a future-breakage lint that is marked as allowed (via `#[allow]` or `--cap-lints`). This allows us to capture any future-breakage diagnostics in one place, while still discarding them before they are passed to the `Emitter`.
* `DiagnosticId::Lint` is extended with a `has_future_breakage` field, indicating whether or not the `Lint` has future breakage information (and should therefore show up in the report).
* `Session` is given access to the `LintStore` via a new `SessionLintStore` trait (since `librustc_session` cannot directly reference `LintStore` without a cyclic dependency). We use this to turn a string `DiagnosticId::Lint` back into a `Lint`, to retrieve the `FutureBreakage` data.
Currently, `FutureBreakage.date` is always set to `None`. However, this could potentially be interpreted by Cargo in the future.
I've enabled the future-breakage report for the `ARRAY_INTO_ITER` lint, which can be used to test out this PR. The intent is to use the field to allow Cargo to determine the date of future breakage (as described in [RFC 2834](https://github.com/rust-lang/rfcs/blob/master/text/2834-cargo-report-future-incompat.md)) without needing to parse the diagnostic itself.
cc `@pnkfelix`
Fix#78549
Before #78430, this worked because `specialize_constructor` didn't actually care too much which constructor was passed to it unless needed. That PR however handles `&str` as a special case, and I did not anticipate patterns for the `&str` type other than string literals.
I am not very confident there are not other similar oversights left, but hopefully only `&str` was different enough to break my assumptions.
Fixes https://github.com/rust-lang/rust/issues/78549
Rollup of 6 pull requests
Successful merges:
- #78073 (Add #[inline] to some functions in core::str.)
- #78596 (Fix doc links to std::fmt)
- #78599 (Add note to process::arg[s] that args shouldn't be escaped or quoted)
- #78602 (fix various aliasing issues in the standard library)
- #78603 (expand: Tweak a comment in implementation of `macro_rules`)
- #78621 (Inline Default::default() for atomics)
Failed merges:
r? `@ghost`
expand: Tweak a comment in implementation of `macro_rules`
The answer to the removed FIXME is that we don't apply mark to the span `sp` just because that span is no longer used. We could apply it, but that would just be unnecessary extra work.
The comments in code tell why the span is unused, it's a span of `$var` literally, which is lost for `tt` variables because their tokens are outputted directly, but kept for other variables which are outputted as [groups](https://doc.rust-lang.org/nightly/proc_macro/struct.Group.html) and `sp` is kept as the group's span.
Closes https://github.com/rust-lang/rust/issues/2887
rustc_llvm: unwrap LLVMMetadataRef before casting
Directly casting the opaque pointer was [reported] to cause an
"incomplete type" error with GCC 9.3:
```
llvm-wrapper/RustWrapper.cpp:939:31: required from here
/usr/include/c++/9.3/type_traits:1301:12: error: invalid use of incomplete type 'struct LLVMOpaqueMetadata'
1301 | struct is_base_of
| ^~~~~~~~~~
In file included from [...]/rust/src/llvm-project/llvm/include/llvm-c/BitReader.h:23,
from llvm-wrapper/LLVMWrapper.h:1,
from llvm-wrapper/RustWrapper.cpp:1:
[...]/rust/src/llvm-project/llvm/include/llvm-c/Types.h:89:16: note: forward declaration of 'struct LLVMOpaqueMetadata'
89 | typedef struct LLVMOpaqueMetadata *LLVMMetadataRef;
| ^~~~~~~~~~~~~~~~~~
```
[reported]: https://zulip-archive.rust-lang.org/182449tcompilerhelp/12215halprustcllvmbuildfail.html#214915124
A simple `unwrap` fixes the issue.
r? `@eddyb`
Suggest calling associated `fn` inside `trait`s
When calling a function that doesn't exist inside of a trait's
associated `fn`, and another associated `fn` in that trait has that
name, suggest calling it with the appropriate fully-qualified path.
Expand the label to be more descriptive.
Prompted by the following user experience:
https://users.rust-lang.org/t/cannot-find-function/50663
Before #78430, string literals worked because `specialize_constructor`
didn't actually care too much which constructor was passed to it unless
needed. Since then, string literals are special cased and a bit hacky. I
did not anticipate patterns for the `&str` type other than string
literals, hence this bug. This makes string literals less hacky.
The validator in visit_local asserts that local has a stroage when used,
but visit_local is never called so validation is ineffective.
Use super_statement and super_terminator to ensure that locals are visited.
The previous recursive approach might overflow the stack when walking a
particularly deep, list-like, graph. In particular, dominator
calculation for borrow checking does such a traversal and very long
functions might lead to a region dependency graph with in this
problematic structure.
This lets rustc users tweak whether the linker should relax ELF relocations,
namely whether it should emit R_X86_64_GOTPCRELX relocations instead of
R_X86_64_GOTPCREL, as the former is allowed by the ABI to be further
optimised. The default value is whatever the target defines.
- Add more well-known traits
- Use the correct binders when lowering trait objects
- Use correct substs when lowering trait objects
- Use the correct binders for opaque_ty_data
- Lower negative impls with the correct polarity
- Supply associated type values
- Use `predicates_defined_on` for where clauses
Avoid BorrowMutError with RUSTC_LOG=debug
```console
$ touch empty.rs
$ env RUSTC_LOG=debug rustc +stage1 --crate-type=lib empty.rs
```
Fails with a `BorrowMutError` because source map files are already
borrowed while `features_query` attempts to format a log message
containing a span.
Release the borrow before the query to avoid the issue.
Simplify a nested bool match
Logically this first eliminates the innermost match by merging the patterns.
Then, in a second step, turns the newly innermost match into a `matches!` call.
Always record reference to binding in match if guards
When encountering a binding from a `match` pattern in its `if` guard when computing a generator's interior types, we must always record the type of a reference to the binding because of how `if` guards are lowered to MIR. This was missed in #75213 because the binding in that test case was autorefed and we recorded that adjusted type anyway.
Fixes#78366
[resolve] Use `unwrap_or_else` instead of `unwrap_or` in a hot path
This improves the performance of the `resolve_crate` function by 30% for
a very large single file crate with auto-generated C bindings.
cc `@rylev`
Directly casting the opaque pointer was [reported] to cause an
"incomplete type" error with GCC 9.3:
```
llvm-wrapper/RustWrapper.cpp:939:31: required from here
/usr/include/c++/9.3/type_traits:1301:12: error: invalid use of incomplete type 'struct LLVMOpaqueMetadata'
1301 | struct is_base_of
| ^~~~~~~~~~
In file included from [...]/rust/src/llvm-project/llvm/include/llvm-c/BitReader.h:23,
from llvm-wrapper/LLVMWrapper.h:1,
from llvm-wrapper/RustWrapper.cpp:1:
[...]/rust/src/llvm-project/llvm/include/llvm-c/Types.h:89:16: note: forward declaration of 'struct LLVMOpaqueMetadata'
89 | typedef struct LLVMOpaqueMetadata *LLVMMetadataRef;
| ^~~~~~~~~~~~~~~~~~
```
[reported]: https://zulip-archive.rust-lang.org/182449tcompilerhelp/12215halprustcllvmbuildfail.html#214915124
A simple `unwrap` fixes the issue.
Use unwrapDIPtr because the Scope may be null.
I ran into an assertion when using debug information on Windows with LLVM assertions enabled.
It seems like we are using unwrap here (which in turn calls isa and requires the pointer to be non-null) but we expect the value to be null because that is what we are passing from rustc.
This change uses unwrapDIPtr which explicitly allows nullptr.
The FFI prototype for this method on the rust side has the `LLVMMetadataRef` parameter as `Scope: Option<&'a DIScope>`, and we always pass `None` when `msvc_like_names` is true.
rustc_span: improve bounds checks in byte_pos_to_line_and_col
The effect of this change is to consider edge-case spans that start or
end at the position one past the end of a file to be valid during span
hashing and encoding. This change means that these spans will be
preserved across incremental compilation sessions when they are part of
a serialized query result, instead of causing the dummy span to be used.
Dogfood {exclusive,half-open} ranges in compiler (nfc)
In particular, this allows us to write more explicit matches that
avoid the pitfalls of using a fully general fall-through case, yet
remain fairly ergonomic. Less logic is in guard cases, more is in
the actual exhaustive case analysis.
No functional changes.
In particular, this allows us to write more explicit matches that
avoid the pitfalls of using a fully general fall-through case, yet
remain fairly ergonomic. Less logic is in guard cases, more is in
the actual exhaustive case analysis.
No functional changes.
Adjust turbofish help message for const generics
Types are no longer special. (This message arguably only makes sense with `min_const_generics` or more, but we'll be there soon.)
r? @lcnr
min_const_generics: allow ty param in repeat expr
implements https://rust-lang.zulipchat.com/#narrow/stream/260443-project-const-generics/topic/repeat.20expressions
Even with `min_const_generics` active, now keeps resulting in future compat warnings instead of hard errors.
Const parameters, for example `[0; N + 1]`, still result in hard errors during resolve.
```rust
#![allow(dead_code)]
fn foo<T>() {
[0; std::mem::size_of::<*mut T>()];
}
struct Foo<T>(T);
impl<T> Foo<T> {
const ASSOC: usize = 4;
fn test() {
[0; Self::ASSOC];
}
}
```
r? @varkor cc @petrochenkov
Clarify main code paths in exhaustiveness checking
This PR massively clarifies the main code paths of exhaustiveness checking, by using the `Constructor` enum to a fuller extent. I've been itching to write it for more than a year, but the complexity of matching consts had prevented me. Behold a massive simplification :D.
This in particular removes a fair amount of duplication between various parts, localizes code into methods of relevant types when applicable, makes some implicit assumptions explicit, and overall improves legibility a lot (or so I hope). Additionally, after my changes undoing #76918 turned out to be a noticeable perf gain.
As usual I tried my best to make the commits self-contained and easy to follow. I've also tried to keep the code well-commented, but I tend to forget how complex this file is; I'm happy to clarify things as needed.
My measurements show good perf improvements on the two match-heavy benchmarks (-18.0% on `unicode_normalization-check`! :D); I'd like a perf run to check the overall impact.
r? `@varkor`
`@rustbot` modify labels: +A-exhaustiveness-checking
$ touch empty.rs
$ env RUSTC_LOG=debug rustc +stage1 --crate-type=lib empty.rs
Fails with a `BorrowMutError` because source map files are already
borrowed while `features_query` attempts to format a log message
containing a span.
Release the borrow before the query to avoid the issue.
Implement -Z function-sections=yes|no
This lets rustc users tweak whether all functions should be put in their own TEXT section, using whatever default value the target defines if the flag is missing.
I'm having fun experimenting with musl libc and trying to implement the start symbol in Rust, that means avoiding code that requires relocations, and AFAIK putting everything in its own section makes the toolchain generate `GOTPCREL` relocations for symbols that could use plain old PC-relative addressing (at least on `x86_64`) if they were all in the same section.
Iterate over the smaller list
If there are two lists of different sizes,
iterating over the smaller list and then
looking up in the larger list is cheaper
than vice versa, because lookups scale
sublinearly.
resolve: private fields in tuple struct ctor diag
Fixes#75906.
This PR improves the diagnostic emitted when a tuple struct is being constructed which has private fields so that private fields are labelled and the message is improved.
r? @estebank
Tweak invalid `fn` header and body parsing
* Rely on regular "expected"/"found" parser error for `fn`, fix#77115
* Recover empty `fn` bodies when encountering `}`
* Recover trailing `>` in return types
* Recover from non-type in array type `[<BAD TOKEN>; LEN]`
check object safety of generic constants
As `Self` can only be effectively used in constants with `const_evaluatable_checked` this should not matter outside of it.
Implements the first item of #72219
> Object safety interactions with constants
r? @oli-obk for now cc @nikomatsakis
Move "mutable thing in const" check from interning to validity
This moves the check for mutable things (such as `UnsafeCell` or `&mut`) in a`const` from interning to validity. That means we can give more targeted error messages (pointing out *where* the problem lies), and we can simplify interning a bit.
Also fix the interning mode used for promoteds in statics.
r? @oli-obk
Suggest calling await on method call and field access
When encountering a failing method or field resolution on a `Future`,
look at the `Output` and try the same operation on it. If successful,
suggest calling `.await` on the `Future`.
This had already been introduced in #72784, but at some point they
stopped working.
Built on top of #78214, only last commit is relevant.
r? @oli-obk
Separate unsized locals
Closes#71694
Takes over again #72029 and #74971
cc @RalfJung @oli-obk @pnkfelix @eddyb as they've participated in previous reviews of this PR.
Uplift `temporary-cstring-as-ptr` lint from `clippy` into rustc
The general consensus seems to be that this lint covers a common enough mistake to warrant inclusion in rustc.
The diagnostic message might need some tweaking, as I'm not sure the use of second-person perspective matches the rest of rustc, but I'd like to hear others' thoughts on that.
(cc #53224).
r? `@oli-obk`
When a function argument bound by `Pointer` is an associated type, we only
perform substitutions using the parameters from the callsite but don't attempt
to normalize since it may not succeed. A simplified version of the scenario that
triggered this error was added as a test case. Also fixed `Pointer::fmt` which
was being double-counted when called outside of macros and added a test case for
this.
Removed test for the unhandled case of calls to `fn f<T>(x: &T)` where `x` is a
function reference and is formatted as a pointer in `f`. This compiles since
`&T` implements `Pointer`, but is unlikely to occur in practice. Also tweaked
the lint's wording and modified tests accordingly.
The lint checks arguments in calls to `transmute` or functions that have
`Pointer` as a trait bound and displays a warning if the argument is a function
reference. Also checks for `std::fmt::Pointer::fmt` to handle formatting macros
although it doesn't depend on the exact expansion of the macro or formatting
internals. `std::fmt::Pointer` and `std::fmt::Pointer::fmt` were also added as
diagnostic items and symbols.
Working with MIR let's us exclude expressions like `&fn_name as &dyn Something`
and `(&fn_name)()`. Also added ABI, unsafety and whether a function is variadic
in the lint suggestion, included the `&` in the span of the lint and updated the
test.
Capture output from threads spawned in tests
This is revival of #75172.
Original text:
> Fixes#42474.
>
> r? `@dtolnay` since you expressed interest in this, but feel free to redirect if you aren't the right person anymore.
---
Closes#75172.
Suggest that expressions that look like const generic arguments should be enclosed in brackets
I pulled out the changes for const expressions from https://github.com/rust-lang/rust/pull/71592 (without the trait object diagnostic changes) and made some small changes; the implementation is `@estebank's.`
We're also going to want to make some changes separately to account for trait objects (they result in poor diagnostics, as is evident from one of the test cases here), such as an adaption of https://github.com/rust-lang/rust/pull/72273.
Fixes https://github.com/rust-lang/rust/issues/70753.
r? `@petrochenkov`
The test change is because we used to treat `&str` like other `&T`s, ie
as having a single constructor. That's not quite true though since we
consider `&str` constants as atomic instead of refs to `str` constants.
Also removes the ugly caching that was introduced in #76918. It was
bolted on without deeper knowledge of the workings of the algorithm.
This commit manages to be more performant without any of the complexity.
It should be better on representative workloads too.
Add compiler support for LLVM's x86_64 ERMSB feature
This change is needed for compiler-builtins to check for this feature
when implementing memcpy/memset. See:
https://github.com/rust-lang/compiler-builtins/pull/365
Without this change, the following code compiles, but does nothing:
```rust
#[cfg(target_feature = "ermsb")]
pub unsafe fn ermsb_memcpy() { ... }
```
The change just does compile-time detection. I think that runtime
detection will have to come in a follow-up CL to std-detect.
Like all the CPU feature flags, this just references #44839
Signed-off-by: Joe Richey <joerichey@google.com>
The effect of this change is to consider edge-case spans that start or
end at the position one past the end of a file to be valid during span
hashing and encoding. This change means that these spans will be
preserved across incremental compilation sessions when they are part of
a serialized query result, instead of causing the dummy span to be used.
When calling a function that doesn't exist inside of a trait's
associated `fn`, and another associated `fn` in that trait has that
name, suggest calling it with the appropriate fully-qualified path.
Expand the label to be more descriptive.
Prompted by the following user experience:
https://users.rust-lang.org/t/cannot-find-function/50663
Remove unused set-discriminant statements and assignments regardless of rvalue
* Represent use counts with u32
* Unify use count visitors
* Change RemoveStatements visitor into a function
* Remove unused set-discriminant statements
* Use exhaustive match to clarify what is being optimized
* Remove unused assignments regardless of rvalue kind
This lets rustc users tweak whether all functions should be put in their own
TEXT section, using whatever default value the target defines if the flag
is missing.
rustc_mir: track inlined callees in SourceScopeData.
We now record which MIR scopes are the roots of *other* (inlined) functions's scope trees, which allows us to generate the correct debuginfo in codegen, similar to what LLVM inlining generates.
This PR makes the `ui` test `backtrace-debuginfo` pass, if the MIR inliner is turned on by default.
Also, `#[track_caller]` is now correct in the face of MIR inlining (cc `@anp).`
Fixes#76997.
r? `@rust-lang/wg-mir-opt`
Add cg_clif as optional codegen backend
Rustc_codegen_cranelift is an alternative codegen backend for rustc based on Cranelift. It has the potential to improve compilation times in debug mode. In my experience the compile time improvements over debug mode LLVM for a clean build are about 20-30% in most cases.
This PR adds cg_clif as optional codegen backend. By default it is only enabled for `./x.py check`. It can be enabled for `./x.py build` too by adding `cranelift` to the `rust.codegen-backends` array in `config.toml`.
MCP: https://github.com/rust-lang/compiler-team/issues/270
r? `@Mark-Simulacrum`
When encountering a failing method or field resolution on a `Future`,
look at the `Output` and try the same operation on it. If successful,
suggest calling `.await` on the `Future`.
This had already been introduced in #72784, but at some point they
stopped working.
This commit improves the diagnostic emitted when a tuple struct is being
constructed which has private fields so that private fields are
labelled and the message is improved.
Signed-off-by: David Wood <david@davidtw.co>
This change is needed for compiler-builtins to check for this feature
when implementing memcpy/memset. See:
https://github.com/rust-lang/compiler-builtins/pull/365
The change just does compile-time detection. I think that runtime
detection will have to come in a follow-up CL to std-detect.
Like all the CPU feature flags, this just references #44839
Signed-off-by: Joe Richey <joerichey@google.com>
Update affected ui & incremental tests to use a user declared variable
bindings instead of temporaries. The former are preserved because of
debuginfo, the latter are not.
The simplify locals implementation uses two different visitors to update
the locals use counts. The DeclMarker calculates the initial use counts.
The StatementDeclMarker updates the use counts as statements are being
removed from the block.
Replace them with a single visitor that can operate in either mode,
ensuring consistency of behaviour.
Additionally use exhaustive match to clarify what is being optimized.
No functional changes intended.