Delegation: support coercion for target expression
(solves https://github.com/rust-lang/rust/issues/118212#issuecomment-2160723092)
The implementation consist of 2 parts. Firstly, method call is generated instead of fully qualified call in AST->HIR lowering if there were no generic arguments or `Qpath` were provided. These restrictions are imposed due to the loss of information after desugaring. For example in
```rust
trait Trait {
fn foo(&self) {}
}
reuse <u8 as Trait>::foo;
```
We would like to generate such a code:
```rust
fn foo<u8: Trait>(x: &u8) {
x.foo(x)
}
```
however, the signature is inherited during HIR analysis where `u8` was discarded.
Then, we probe the single pre-resolved method.
P.S In the future, we would like to avoid restrictions on the callee path by `Self` autoref/autoderef in fully qualified calls, but at the moment it didn't work out.
r? `@petrochenkov`
Sync ar_archive_writer to LLVM 18.1.3
From LLVM 15.0.0-rc3. This adds support for COFF archives containing Arm64EC object files and has various fixes for AIX big archive files.
Various ast validation simplifications
Changes pulled out of https://github.com/rust-lang/rust/pull/127524
These are needed to make ast validation a mutable visitor, as we can't keep immutable references to the AST around in that case. But I think they are simplifying things in general and can stand on their own
Fix a bunch of sites that were walking instead of visiting, making it impossible for visitor impls to look at these values
This doesn't affects anything right now, but a `MutVisitor` impl could be surprised by this.
The reason this doesn't affect anything is that no one overrrides `visit_lifetime` or `visit_param_bounds` currently.
Make ErrorGuaranteed discoverable outside types, consts, and lifetimes
types like `PatKind` could contain `ErrorGuaranteed`, but not return them via `tainted_by_errors` or `error_reported` (see https://github.com/rust-lang/rust/pull/127687#discussion_r1679027883). Now this happens, but it's a bit fragile as you can see with the `TypeSuperVisitable for Ty` impl.
We will catch any problems around Ty, Region or Const at runtime with an assert, and everything using derives will not have such issues, as it will just invoke the `TypeVisitable for ErrorGuaranteed` impl
Fix and enforce `unsafe_op_in_unsafe_fn` in compiler
In preparation for edition 2024, this PR previews the fallout of enabling the `unsafe_op_in_unsafe_fn` lint in the compiler, since it's defaulting to warn in the new edition (#112038).
The major annoyance comes primarily from the `rustc_codegen_llvm` module, where there's a ton of unsafe calls. I tended to wrap individual calls to unsafe fns in `unsafe {}`, but there a handful of places I chose to just wrap several calls in an `unsafe {}` block just because it would've been excessive to wrap each call individually.
This doesn't enable the lint for the standard library, since I'm not totally certain what T-libs prefers w/ this lint.
match lowering: Use an iterator to find `expand_until`
A small cleanup that I noticed while looking at #127164.
This makes it easier to see that the split point is always the index after the found item, or the whole list if no stopping point was found.
r? `@Nadrieril`
when the `C-cmse-nonsecure-call` ABI is used, arguments and return values must be passed via registers. Failing to do so (i.e. spilling to the stack) causes an LLVM error down the line, but now rustc will properly emit an error a bit earlier in the chain
Make sure trait def ids match before zipping args in `note_function_argument_obligation`
Fixes#126416Fixes#127745
Didn't add both tests b/c I felt like it was unnecessary.
match lowering: Move `MatchPair` tree creation to its own module
This makes it easier to see that `MatchPair::new` has only one non-recursive caller, because the recursive callers are all in this module. No functional changes.
---
I have used `git diff --color-moved` to verify that the moved code is identical to the old code, except for reduced visibility on the helper methods.
It only has two call sites, and it extremely similar to
`Parser::parse_expr_dot_or_call_with`, in both name and behaviour. The
only difference is the latter has an `attrs` argument and an
`ensure_sufficient_stack` call. We can pass in an empty `attrs` as
necessary, as is already done at some `parse_expr_dot_or_call_with` call
sites.
coverage: Restrict `ExpressionUsed` simplification to `Code` mappings
In the future, branch and MC/DC mappings might have expressions that don't correspond to any single point in the control-flow graph. That makes it trickier to keep track of which expressions should expect an `ExpressionUsed` node.
We therefore sidestep that complexity by only performing `ExpressionUsed` simplification for expressions associated directly with ordinary `Code` mappings.
(This simplification step is inherited from the original coverage implementation, which only supported `Code` mappings anyway, so there's no particular reason to extend it to other kinds of mappings unless we specifically choose to.)
Relevant to:
- #124154
- #126677
- #124278
```@rustbot``` label +A-code-coverage
Stop using the `gen` identifier in the compiler
In preparation for edition 2024, this PR previews the fallout of removing usages of `gen` since it's being reserved as a keyword.
There are two notable changes here:
1. Had to rename `fn gen(..)` in gen/kill analysis to `gen_`. Not certain there's a better name than that.
2. There are (false?[^1]) positives in `rustc_macros` when using synstructure, which uses `gen impl` to mark an implementation. We could suppress this in a one-off way, or perhaps just ignore `gen` in macros altogether, since if an identifier ends up in expanded code then it'll get properly denied anyways.
Not relevant to the compiler, but it's gonna be really annoying to change `rand`'s `gen` fn in the library and miri...
[^1]: I haven't looked at the synstructure proc macro code itself so I'm not certain if it'll start to fail when converted to ed2024 (or, e.g., when syn starts parsing `gen` as a kw).
Make parse error suggestions verbose and fix spans
Go over all structured parser suggestions and make them verbose style.
When suggesting to add or remove delimiters, turn them into multiple suggestion parts.
offset_from: always allow pointers to point to the same address
This PR implements the last remaining part of the t-opsem consensus in https://github.com/rust-lang/unsafe-code-guidelines/issues/472: always permits offset_from when both pointers have the same address, no matter how they are computed. This is required to achieve *provenance monotonicity*.
Tracking issue: https://github.com/rust-lang/rust/issues/117945
### What is provenance monotonicity and why does it matter?
Provenance monotonicity is the property that adding arbitrary provenance to any no-provenance pointer must never make the program UB. More specifically, in the program state, data in memory is stored as a sequence of [abstract bytes](https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#abstract-byte), where each byte can optionally carry provenance. When a pointer is stored in memory, all of the bytes it is stored in carry that provenance. Provenance monotonicity means: if we take some byte that does not have provenance, and give it some arbitrary provenance, then that cannot change program behavior or introduce UB into a UB-free program.
We care about provenance monotonicity because we want to allow the optimizer to remove provenance-stripping operations. Removing a provenance-stripping operation effectively means the program after the optimization has provenance where the program before the optimization did not -- since the provenance removal does not happen in the optimized program. IOW, the compiler transformation added provenance to previously provenance-free bytes. This is exactly what provenance monotonicity lets us do.
We care about removing provenance-stripping operations because `*ptr = *ptr` is, in general, (likely) a provenance-stripping operation. Specifically, consider `ptr: *mut usize` (or any integer type), and imagine the data at `*ptr` is actually a pointer (i.e., we are type-punning between pointers and integers). Then `*ptr` on the right-hand side evaluates to the data in memory *without* any provenance (because [integers do not have provenance](https://rust-lang.github.io/rfcs/3559-rust-has-provenance.html#integers-do-not-have-provenance)). Storing that back to `*ptr` means that the abstract bytes `ptr` points to are the same as before, except their provenance is now gone. This makes `*ptr = *ptr` a provenance-stripping operation (Here we assume `*ptr` is fully initialized. If it is not initialized, evaluating `*ptr` to a value is UB, so removing `*ptr = *ptr` is trivially correct.)
### What does `offset_from` have to do with provenance monotonicity?
With `ptr = without_provenance(N)`, `ptr.offset_from(ptr)` is always well-defined and returns 0. By provenance monotonicity, I can now add provenance to the two arguments of `offset_from` and it must still be well-defined. Crucially, I can add *different* provenance to the two arguments, and it must still be well-defined. In other words, this must always be allowed: `ptr1.with_addr(N).offset_from(ptr2.with_addr(N))` (and it returns 0). But the current spec for `offset_from` says that the two pointers must either both be derived from an integer or both be derived from the same allocation, which is not in general true for arbitrary `ptr1`, `ptr2`.
To obtain provenance monotonicity, this PR hence changes the spec for offset_from to say that if both pointers have the same address, the function is always well-defined.
### What further consequences does this have?
It means the compiler can no longer transform `end2 = begin.offset(end.offset_from(begin))` into `end2 = end`. However, it can still be transformed into `end2 = begin.with_addr(end.addr())`, which later parts of the backend (when provenance has been erased) can trivially turn into `end2 = end`.
The only alternative I am aware of is a fundamentally different handling of zero-sized accesses, where a "no provenance" pointer is not allowed to do zero-sized accesses and instead we have a special provenance that indicates "may be used for zero-sized accesses (and nothing else)". `offset` and `offset_from` would then always be UB on a "no provenance" pointer, and permit zero-sized offsets on a "zero-sized provenance" pointer. This achieves provenance monotonicity. That is, however, a breaking change as it contradicts what we landed in https://github.com/rust-lang/rust/pull/117329. It's also a whole bunch of extra UB, which doesn't seem worth it just to achieve that transformation.
### What about the backend?
LLVM currently doesn't have an intrinsic for pointer difference, so we anyway cast to integer and subtract there. That's never UB so it is compatible with any relaxation we may want to apply.
If LLVM gets a `ptrsub` in the future, then plausibly it will be consistent with `ptradd` and [consider two equal pointers to be inbounds](https://github.com/rust-lang/rust/pull/124921#issuecomment-2205795829).
In the future, branch and MC/DC mappings might have expressions that don't
correspond to any single point in the control-flow graph. That makes it
trickier to keep track of which expressions should expect an `ExpressionUsed`
node.
We therefore sidestep that complexity by only performing `ExpressionUsed`
simplification for expressions associated directly with ordinary `Code`
mappings.
Fill out target-spec metadata for all targets
**What does this PR try to resolve?**
This PR completes the target-spec metadata fields for all targets. This is required for a corresponding Cargo PR which adds a check for whether a target supports building the standard library when the `-Zbuild-std=std` flag is passed ([see this issue](https://github.com/rust-lang/wg-cargo-std-aware/issues/87). This functionality in Cargo is reliant on the output of `--print=target-spec-json`.
**How should we test and review this PR?**
Check that a given target-spec metadata has been updated with:
```
$ ./x.py build library/std
$ build/host/stage1/bin/rustc --print=target-spec-json --target <target_name> -Zunstable-options
```
**Additional Information**
A few things to note:
* Where a targets 'std' or 'host tools' support is listed as '?' in the rust docs, these are left as 'None' with this PR. The corresponding changes in cargo will only reject an attempt to build std if the 'std' field is 'Some(false)'. In the case it is 'None', cargo will continue trying to build
* There's no rush for this to be merged. I understand that the format for this is not finalised yet.
* Related: #120745
Remove lang feature for type ascription (since it's a lib feature now)
It's not necessary since it's a library feature now, via the type ascription macro. We can't (and shouldn't) register it as a removed feature since I think that would give "this feature has been removed" errors even for people using the macro (well, I'm pretty sure, though I didn't check).
r? `@Nilstrieb`
Report usage of lib features in ast validation
No idea why it was split between ast validation for lang features and a later pass for lang features.
r? `@Nilstrieb`
Fix `DebugParser`.
I tried using this and it didn't work at all. `prev_token` is never eof, so the accumulator is always false, which means the `then_some` always returns `None`, which means `scan` always returns `None`, and `tokens` always ends up an empty vec. I'm not sure how this code was supposed to work.
(An aside: I find `Iterator::scan` to be a pretty wretched function, that produces code which is very hard to understand. Probably why this is just one of two uses of it in the entire compiler.)
This commit changes it to a simpler imperative style that produces a valid `tokens` vec.
r? `@workingjubilee`
Gate the type length limit check behind a nightly flag
Effectively disables the type length limit by introducing a `-Zenforce-type-length-limit` which defaults to **`false`**, since making the length limit actually be enforced ended up having a worse fallout than expected. We still keep the code around, but the type length limit attr is now a noop (except for its usage in some diagnostics code?).
r? `@lcnr` -- up to you to decide what team consensus we need here since this reverses an FCP decision.
Reopens#125460 (if we decide to reopen it or keep it closed)
Effectively reverses the decision FCP'd in #125507Closes#127346
Rollup of 5 pull requests
Successful merges:
- #127083 (Add release notes for 1.80)
- #127322 (handle ci-rustc incompatible options during config parse)
- #127697 (use std for file mtime and atime modifications)
- #127704 (Fix minor typos in std::process doc on Win argv)
- #127710 (clarify the meaning of the version number for accepted/removed features)
r? `@ghost`
`@rustbot` modify labels: rollup
Only track mentioned places for jump threading
This PR aims to reduce the state space size in jump threading and dataflow const-prop opts.
The current implementation walks the types of all locals, and creates a place for each possible projection. This can easily lead to a large number of places and tracked values, most being useless to the actual pass.
With this PR, we instead collect places that appear syntactically in the MIR (first commit). However, this is not sufficient (second commit), and we miss places that we could track in aggregate assignments. The third commit tracks such assignments to mirror place projections, see the inline comment.
This is complementary to https://github.com/rust-lang/rust/pull/127036
r? `@oli-obk`
Clear `inner_attr_ranges` regularly.
There's a comment saying we don't do it for performance reasons, but it doesn't actually affect performance.
The commit also tweaks the control flow, to make clearer that two code paths are mutually exclusive.
r? ````@petrochenkov````
use "bootstrap" instead of "rustbuild" in comments and docs
Let's stick with the single name "bootstrap" to refer to the bootstrap project to avoid confusion. This should make it clearer, especially for new contributors.
It currently doesn't work at all. This commit changes it to a simpler
imperative style that produces a valid `tokens` vec.
(An aside: I find `Iterator::scan` to be a pretty wretched function,
that produces code which is very hard to understand. Probably why this
is just one of two uses of it in the entire compiler.)
That method is currently badly broken, and the test output reflects
this. The obtained tokens list is always empty, except in the case where
we go two `bump`s past the final token, whereupon it will produce as
many `Eof` tokens as asked for.
Fix incorrect NDEBUG handling in LLVM bindings
We currently compile our LLVM bindings using `-DNDEBUG` if debuginfo for LLVM is disabled. However, `NDEBUG` doesn't have any relation to debuginfo, it controls whether assertions are enabled.
Split the LLVM_NDEBUG environment variable into two, so that assertions and debuginfo are controlled independently.
After this change, `LLVMRustDIBuilderInsertDeclareAtEnd` triggers an assertion failure on LLVM 19 due to an incorrect cast. Fix it by removing the unused return value entirely.
r? `@cuviper`
Rollup of 11 pull requests
Successful merges:
- #126502 (Ignore allocation bytes in some mir-opt tests)
- #126922 (add lint for inline asm labels that look like binary)
- #127209 (Added the `xop` target-feature and the `xop_target_feature` feature gate)
- #127310 (Fix import suggestion ice)
- #127338 (Migrate `extra-filename-with-temp-outputs` and `issue-85019-moved-src-dir` `run-make` tests to rmake)
- #127381 (Migrate `issue-83045`, `rustc-macro-dep-files` and `env-dep-info` `run-make` tests to rmake)
- #127535 (Fire unsafe_code lint on unsafe extern blocks)
- #127619 (Suggest using precise capturing for hidden type that captures region)
- #127631 (Remove `fully_normalize`)
- #127632 (Implement `precise_capturing` support for rustdoc)
- #127660 (Rename the internal `const_strlen` to just `strlen`)
r? `@ghost`
`@rustbot` modify labels: rollup
Implement `precise_capturing` support for rustdoc
Implements rustdoc (+json) support for local (i.e. non-cross-crate-inlined) RPITs with `use<...>` precise capturing syntax.
Tests kinda suck. They're really hard to write 😰
r? `@fmease` or re-roll if you're too busy!
also cc `@aDotInTheVoid` for the json side
Tracking:
* https://github.com/rust-lang/rust/issues/127228#issuecomment-2201443216 (not fully fixed for cross-crate-inlined opaques)
* https://github.com/rust-lang/rust/issues/123432
Suggest using precise capturing for hidden type that captures region
Adjusts the "add `+ '_`" suggestion for opaques to instead suggest adding or reusing the `+ use<>` in the opaque.
r? oli-obk or please re-roll if you're busy!
Fix import suggestion ice
Fixes#127302#127302 only crash in edition 2015
#120074 can only reproduced in edition 2021
so I added revisions in test file.
Added the `xop` target-feature and the `xop_target_feature` feature gate
This is an effort towards #127208. This adds the `xop` target feature gated by `xop_target_feature`.
add lint for inline asm labels that look like binary
fixes#94426
Due to a bug/feature in LLVM, labels composed of only the digits `0` and `1` can sometimes be confused with binary literals, even if a binary literal would not be valid in that position.
This PR adds detection for such labels and also as a drive-by change, adds a note to cases such as `asm!(include_str!("file"))` that the label that it found came from an expansion of a macro, it wasn't found in the source code.
I expect this PR to upset some people that were using labels `0:` or `1:` without issue because they never hit the case where LLVM got it wrong, but adding a heuristic to the lint to prevent this is not feasible - it would involve writing a whole assembly parser for every target that we have assembly support for.
[zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/238009-t-compiler.2Fmeetings/topic/.5Bweekly.5D.202024-06-20/near/445870628)
r? ``@estebank``
Ignore allocation bytes in some mir-opt tests
This adds `rustc -Zdump-mir-exclude-alloc-bytes` to skip writing allocation bytes in MIR dumps, and applies it to tests that were failing on s390x due to its big-endian byte order.
Fixes#126261
Ensure floats are returned losslessly by the Rust ABI on 32-bit x86
Solves #115567 for the (default) `"Rust"` ABI. When compiling for 32-bit x86, this PR changes the `"Rust"` ABI to return floats indirectly instead of in x87 registers (with the exception of single `f32`s, which this PR returns in general purpose registers as they are small enough to fit in one). No change is made to the `"C"` ABI as that ABI requires x87 register usage and therefore will need a different solution.
The return value changed from an Instruction to a DbgRecord in
LLVM 19. As we don't actually use the result, drop the return
value entirely to support both.
We currently compile our LLVM bindings using `-DNDEBUG` if
debuginfo for LLVM is disabled. However, `NDEBUG` doesn't have
any relation to debuginfo, it controls whether assertions are
enabled.
Rename the environment variable to `LLVM_ASSERTIONS` and drive
it using the `llvm_assertions` option. Also drop the explicit
`debug(false)` call, as cc already sets this up using the
cargo `DEBUG` environment variable.
Previously we would only mention that the item was gated out, and opportunisitically mention the feature flag name when possible. We now point to the place where the item was gated, which can be behind layers of macro indirection, or in different modules.
```
error[E0433]: failed to resolve: could not find `doesnt_exist` in `inner`
--> $DIR/diagnostics-cross-crate.rs:18:23
|
LL | cfged_out::inner::doesnt_exist::hello();
| ^^^^^^^^^^^^ could not find `doesnt_exist` in `inner`
|
note: found an item that was configured out
--> $DIR/auxiliary/cfged_out.rs:6:13
|
LL | pub mod doesnt_exist {
| ^^^^^^^^^^^^
note: the item is gated here
--> $DIR/auxiliary/cfged_out.rs:5:5
|
LL | #[cfg(FALSE)]
| ^^^^^^^^^^^^^
```
Fix `Parser::look_ahead`
`Parser::look_ahead` has a slow but simple general case, and a fast special case that is hit most of the time. But the special case is buggy and behaves differently to the general case. There are also no unit tests. This PR fixes all of this, resulting in a `Parser::look_ahead` that is equally fast, slightly simpler, more correct, and better tested.
r? `@davidtwco`
generalize search graph to enable fuzzing
I do not believe it to be feasible to correctly implement the search graph without fuzzing. This PR enables this by requiring a fuzzer to only implement three new traits:
- `Cx`: implemented by all `I: Interner`
- `ProofTreeBuilder`: implemented by `struct ProofTreeBuilder<D>` for all `D: SolverDelegate`
- `Delegate`: implemented for a new `struct SearchGraphDelegate<D>` for all `D: SolverDelegate`
It also moves the evaluation cache implementation into `rustc_type_ir`, requiring `Interner` to provide methods to create and access arbitrary `WithDepNode<T>` and to provide mutable access to a given `GlobalCache`. It otherwise does not change the API surface for users of the shared library.
This change should not impact behavior in any way.
r? ``@compiler-errors``
Add AMX target-features and `x86_amx_intrinsics` feature flag
This is an effort towards #126622. This adds support for all 5 target-features for `AMX`, and introduces the feature flag `x86_amx_intrinsics`, which would gate these target-features and the yet-to-be-implemented amx intrinsics in stdarch.
Use rustc-stable-hash in the compiler
Following https://github.com/rust-lang/compiler-team/issues/755 and the release of the crate on crates.io, let's now use it in the compiler and remove the old implementation.
cc `@michaelwoerister`
r? ghost
Rollup of 6 pull requests
Successful merges:
- #127164 (match lowering: Clarify the main loop of the algorithm)
- #127422 (as_simd: fix doc comment to be in line with align_to)
- #127596 (More suggestion for converting `Option<&Vec<T>>` to `Option<&[T]>`)
- #127607 (compiletest: Better error message for bad `normalize-*` headers)
- #127622 (Mark `builtin_syntax` as internal)
- #127625 (Revert accidental comment deletion)
r? `@ghost`
`@rustbot` modify labels: rollup
This new special case is simpler than the old special case because it
only is used when `dist == 1`. But that's still enough to cover ~98% of
cases. This results in equivalent performance to the old special case,
and identical behaviour as the general case.
The general case at the bottom of `look_ahead` is slow, because it
clones the token cursor. Above it there is a special case for
performance that is hit most of the time and avoids the cloning.
Unfortunately, its behaviour differs from the general case in two ways.
- When within a pair of delimiters, if you look any distance past the
closing delimiter you get the closing delimiter instead of what comes
after the closing delimiter.
- It uses `tree_cursor.look_ahead(dist - 1)` which totally confuses
tokens with token trees. This means that only the first token in a
token tree will be seen. E.g. in a sequence like `{ a }` the `a` and
`}` will be skipped over. Bad!
It's likely that these differences weren't noticed before now because
the use of `look_ahead` in the parser is limited to small distances and
relatively few contexts.
Removing the special case causes slowdowns up of to 2% on a range of
benchmarks. The next commit will add a new, correct special case to
regain that lost performance.
Go over all structured parser suggestions and make them verbose style.
When suggesting to add or remove delimiters, turn them into multiple suggestion parts.
match lowering: Clarify the main loop of the algorithm
Now that we expand or-patterns in a single place in the algorithm, we can move it (back) to the main part of the loop. This makes the call-graph of the main loop rather simple: `match_candidates` has three branches that each call back to `match_candidates`. The remaining tricky part is `finalize_or_candidate`.
I also factored out the whole "process a prefix of the candidates then process the rest" thing which I think helps legibility.
The first two commits are a fix for an indexing mistake I introduced in https://github.com/rust-lang/rust/pull/126553, already sumitted in https://github.com/rust-lang/rust/pull/127028 but feel free to merge this first.
r? `@matthewjasper`
Rollup of 8 pull requests
Successful merges:
- #124599 (Suggest borrowing on fn argument that is `impl AsRef`)
- #127572 (Don't mark `DEBUG_EVENT` struct as `repr(packed)`)
- #127588 (core: Limit remaining f16 doctests to x86_64 linux)
- #127591 (Make sure that labels are defined after the primary span in diagnostics)
- #127598 (Allows `#[diagnostic::do_not_recommend]` to supress trait impls in suggestions as well)
- #127599 (Rename `lazy_cell_consume` to `lazy_cell_into_inner`)
- #127601 (check is_ident before parse_ident)
- #127605 (Remove extern "wasm" ABI)
r? `@ghost`
`@rustbot` modify labels: rollup
Remove extern "wasm" ABI
Remove the unstable `extern "wasm"` ABI (`wasm_abi` feature tracked in #83788).
As discussed in https://github.com/rust-lang/rust/pull/127513#issuecomment-2220410679 and following, this ABI is a failed experiment that did not end up being used for anything. Keeping support for this ABI in LLVM 19 would require us to switch wasm targets to the `experimental-mv` ABI, which we do not want to do.
It should be noted that `Abi::Wasm` was internally used for two things: The `-Z wasm-c-abi=legacy` ABI that is still used by default on some wasm targets, and the `extern "wasm"` ABI. Despite both being `Abi::Wasm` internally, they were not the same. An explicit `extern "wasm"` additionally enabled the `+multivalue` feature.
I've opted to remove `Abi::Wasm` in this patch entirely, instead of keeping it as an ABI with only internal usage. Both `-Z wasm-c-abi` variants are now treated as part of the normal C ABI, just with different different treatment in
adjust_for_foreign_abi.
Allows `#[diagnostic::do_not_recommend]` to supress trait impls in suggestions as well
This commit changes the error reporting mechanism for not implemented traits to skip impl marked as `#[diagnostic::do_not_recommend]` in the help part of the error message ("the following other types implement trait `Foo`:"). The main use case here is to allow crate authors to skip non-meaningful confusing suggestions. A common example for this are fully generic impls on tuples.
Related to https://github.com/rust-lang/rust/issues/51992
r? `@compiler-errors`
Make sure that labels are defined after the primary span in diagnostics
Putting a `#[label]` before a `#[primary_span]` results in that label being overwritten, due to the semantics of `Diagnostic::span` and the fact that labels are stored in the `MultiSpan` of the diagnostic.
This isn't possible to fix in general, since a lot of code actually *relies* in this overwriting behavior (e.g. `rustc_on_unimplemented`). However, it's useful to enforce this for derive-diagnostics, since this is certainly never what you intend to do in a derived diagnostic, where all the fields are meaningful parts of the diagnostic being rendered.
This only matters for `#[label]`, since those are the ones stored in the `MultiSpan` of the error.
We could also make this "just work" by sorting the attrs or processing the primary span attr first, however I think it's kinda pointless to do.
There was 1 case where this mattered, but we literally didn't have a test exercising that diagnostic 🙃
Suggest borrowing on fn argument that is `impl AsRef`
When encountering a move conflict, on an expression that is `!Copy` passed as an argument to an `fn` that is `impl AsRef`, suggest borrowing the expression.
```
error[E0382]: use of moved value: `bar`
--> f204.rs:14:15
|
12 | let bar = Bar;
| --- move occurs because `bar` has type `Bar`, which does not implement the `Copy` trait
13 | foo(bar);
| --- value moved here
14 | let baa = bar;
| ^^^ value used here after move
|
help: borrow the value to avoid moving it
|
13 | foo(&bar);
| +
```
Fix#41708
Add `f16` and `f128` as simd types in LLVM
`@sayantn` is working on adding SIMD for `f16` and hitting the `FloatingPointVector` error. This should fix it and unblock adding support for `simd_fma` and `simd_fabs` in stdarch.
Avoid follow-up errors and ICEs after missing lifetime errors on data structures
Tuple struct constructors are functions, so when we call them typeck will use the signature tuple struct constructor function to provide type hints. Since typeck mostly ignores and erases lifetimes, we end up never seeing the error lifetime in writeback, thus not tainting the typeck result.
Now, we eagerly taint typeck results by tainting from `resolve_vars_if_possible`, which is called all over the place.
I did not carry over all the `crashes` test suite tests, as they are really all the same cause (missing or unknown lifetime names in tuple struct definitions or generic arg lists).
fixes#124262fixes#124083fixes#125155fixes#125888fixes#125992fixes#126666fixes#126648fixes#127268fixes#127266fixes#127304
Remove the unstable `extern "wasm"` ABI (`wasm_abi` feature tracked
in #83788).
As discussed in https://github.com/rust-lang/rust/pull/127513#issuecomment-2220410679
and following, this ABI is a failed experiment that did not end
up being used for anything. Keeping support for this ABI in LLVM 19
would require us to switch wasm targets to the `experimental-mv`
ABI, which we do not want to do.
It should be noted that `Abi::Wasm` was internally used for two
things: The `-Z wasm-c-abi=legacy` ABI that is still used by
default on some wasm targets, and the `extern "wasm"` ABI. Despite
both being `Abi::Wasm` internally, they were not the same. An
explicit `extern "wasm"` additionally enabled the `+multivalue`
feature.
I've opted to remove `Abi::Wasm` in this patch entirely, instead
of keeping it as an ABI with only internal usage. Both
`-Z wasm-c-abi` variants are now treated as part of the normal
C ABI, just with different different treatment in
adjust_for_foreign_abi.
Implement simple, unstable lint to suggest turning closure-of-async-block into async-closure
We want to eventually suggest people to turn `|| async {}` to `async || {}`. This begins doing that. It's a pretty rudimentary lint, but I wanted to get something down so I wouldn't lose the code.
Tracking:
* #62290
This commit changes the error reporting mechanism for not implemented
traits to skip impl marked as `#[diagnostic::do_not_recommend]` in the
help part of the error message ("the following other types implement
trait `Foo`:"). The main use case here is to allow crate authors to skip
non-meaningful confusing suggestions. A common example for this are
fully generic impls on tuples.
Make `visit_clobber`'s impl safe
This was originally introduced in #58061 but I didn't see any perf discussion about it, so let's see what perf says.
r? `@nnethercote`
instantiate higher ranked goals in candidate selection again
This reverts #119820 as that PR has a significant impact and breaks code which *feels like it should work*. The impact ended up being larger than we expected during the FCP and we've ended up with some ideas for how we can work around this issue in the next solver. This has been discussed in the previous high bandwidth t-types meeting: https://rust-lang.zulipchat.com/#narrow/stream/326132-t-types.2Fmeetings/topic/2024-07-09.20high.20bandwidth.20meeting.
We'll therefore keep this inconsistency between the two solvers for now and will have to deal with it before stabilizating the use of the new solver outside of coherence: https://github.com/rust-lang/trait-system-refactor-initiative/issues/120.
fixes#125194 after a beta-backport.
The pattern which is more widely used than expected and feels like it should work, especially without deep knowledge of the type system is
```rust
trait Trait<'a> {}
impl<'a, T> Trait<'a> for T {}
fn trait_bound<T: for<'a> Trait<'a>>() {}
// A function with a where-bound which is more restrictive than the impl.
fn function1<T: Trait<'static>>() {
// stable: ok
// with #119820: error as we prefer the where-bound over the impl
// with this PR: back to ok
trait_bound::<T>();
}
```
r? `@rust-lang/types`
This comment has two problems:
- It is very long, making the flow of the enclosing method hard to follow.
- It starts by talking about an `autoref` flag that hasn't existed since #59114.
This PR therefore replaces the long inline comment with a revised doc comment
on `bind_matched_candidate_for_guard`, and some shorter inline comments.
For readers who want more historical context, we also link to the PR that added
the old comment, and the PR that removed the `autoref` flag.
This commit does the following.
- Pulls the code out of `AttrTokenStream::to_token_trees` into a new
function `attrs_and_tokens_to_token_trees`.
- Simplifies `TokenStream::from_ast` by calling the new function. This
is nicer than the old way, which created a temporary
`AttrTokenStream` containing a single `AttrsTarget` (which required
some cloning) just to call `to_token_trees` on it. (It is good to
remove this use of `AttrsTarget` which isn't related to `cfg_attr`
expansion.)
The new condition is equivalent in practice, but it's much more obvious
that it would result in an empty range, because the condition lines up
with the contents of the iterator.
Update `f16`/`f128` FIXMEs that needed `(NEG_)INFINITY`
Just a small fix to the pattern matching tests now that we can. Also contains a small unrelated comment tweak.
More trait error reworking
More work on #127492, specifically those sub-bullets under "Move trait error reporting to `error_reporting::traits`". Stacked on top of #127493.
This does introduce new `TypeErrCtxt.*Ext` traits, but those will be deleted soon. Splitting this work into bite-sized pieces is the only way that it's gonna be feasible to both author and review ❤️
r? lcnr
Automatically taint when reporting errors from ItemCtxt
This isn't very robust yet, as you need to use `itemctxt.dcx()` instead of `tcx.dcx()` for it to take effect, but it's at least more convenient than sprinkling `set_tainted_by_errors` calls in individual places.
based on https://github.com/rust-lang/rust/pull/127357
r? `@fmease`
[Coverage][MCDC] Group mcdc tests and fix panic when generating mcdc code for inlined expressions.
### Changes
1. Group all mcdc tests to one directory.
2. Since mcdc instruments different mappings for boolean expressions with normal branch coverage as #125766 introduces, it would be better also trace branch coverage results in mcdc tests.
3. So far rustc does not call `CoverageInfoBuilderMethods::init_coverage` for inlined functions. As a result, it could panic if it tries to instrument mcdc statements for inlined functions due to uninitialized cond bitmaps. We can reproduce this issue by current nightly rustc and [the test](https://github.com/rust-lang/rust/pull/127234/files#diff-c81af6bf4869aa42f5c7334e3e86344475de362f673f54ce439ec75fcb5ac3e5) with flag `--release`. This patch fixes it.
This is adding a migration lint for the current (in the 2021 edition and previous)
to move expr to expr_2021 from expr
Co-Developed-by: Eric Holk
Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
Fix regression in the MIR lowering of or-patterns
In https://github.com/rust-lang/rust/pull/126553 I made a silly indexing mistake and regressed the MIR lowering of or-patterns. This fixes it.
r? `@compiler-errors` because I'd like this to be merged quickly 🙏
Consolidate region error reporting in `rustc_infer`
More work on https://github.com/rust-lang/rust/issues/127492. Separate but important step, since I'm gonna likely pull everything else here into another module.
I don't think I'm confident whether `nice_region_error` should be a submodule of the new `rustc_infer::infer::error_reporting::region` module, so I left it alone for now.
r? lcnr
Move trait selection error reporting to its own top-level module
This effectively moves `rustc_trait_selection::traits::error_reporting` to `rustc_trait_selection::error_reporting::traits`. There are only a couple of actual changes to the code, like moving the `pretty_impl_header` fn out of the specialization module for privacy reasons.
This is quite pointless on its own, but having `error_reporting` as a top-level module in `rustc_trait_selection` is very important to make sure we have a meaningful file structure for when we move **type** error reporting (and region error reporting, with which it's incredibly entangled currently) into `rustc_trait_selection`. I've opened a tracking issue here: #127492
r? lcnr
Add Natvis visualiser and debuginfo tests for `f16`
To render `f16`s in debuggers on MSVC targets, this PR changes the compiler to output `f16`s as `struct f16 { bits: u16 }`, and includes a Natvis visualiser that manually converts the `f16`'s bits to a `float` which is can then be displayed by debuggers. `gdb`, `lldb` and `cdb` tests are also included for `f16` .
`f16`/`f128` MSVC debug info issue: #121837
Tracking issue: #116909
Infer async closure signature from (old-style) two-part `Fn` + `Future` bounds
When an async closure is passed to a function that has a "two-part" `Fn` and `Future` trait bound, like:
```rust
use std::future::Future;
fn not_exactly_an_async_closure(_f: F)
where
F: FnOnce(String) -> Fut,
Fut: Future<Output = ()>,
{}
```
The we want to be able to extract the signature to guide inference in the async closure, like:
```rust
not_exactly_an_async_closure(async |string| {
for x in string.split('\n') { ... }
//~^ We need to know that the type of `string` is `String` to call methods on it.
})
```
Closure signature inference will see two bounds: `<?F as FnOnce<Args>>::Output = ?Fut`, `<?Fut as Future>::Output = String`. We need to extract the signature by looking through both projections.
### Why?
I expect the ecosystem's move onto `async Fn` trait bounds (which are not affected by this PR, and already do signature inference fine) to be slow. In the mean time, I don't see major overhead to supporting this "old–style" of trait bounds that were used to model async closures.
r? oli-obk
Fixes#127468Fixes#127425
Make casts of pointers to trait objects stricter
This is an attempt to `fix` https://github.com/rust-lang/rust/issues/120222 and https://github.com/rust-lang/rust/issues/120217.
This is done by adding restrictions on casting pointers to trait objects.
Before this PR the rules were as follows:
> When casting `*const X<dyn A>` -> `*const Y<dyn B>`, principal traits in `A` and `B` must refer to the same trait definition (or no trait).
With this PR the rules are changed to
> When casting `*const X<dyn Src>` -> `*const Y<dyn Dst>`
> - if `Dst` has a principal trait `DstP`,
> - `Src` must have a principal trait `SrcP`
> - `dyn SrcP` and `dyn DstP` must be the same type (modulo the trait object lifetime, `dyn T+'a` -> `dyn T+'b` is allowed)
> - Auto traits in `Dst` must be a subset of auto traits in `Src`
> - Not adhering to this is currently a FCW (warn-by-default + `FutureReleaseErrorReportInDeps`), instead of an error
> - if `Src` has a principal trait `Dst` must as well
> - this restriction will be removed in a follow up PR
This ensures that
1. Principal trait's generic arguments match (no `*const dyn Tr<A>` -> `*const dyn Tr<B>` casts, which are a problem for [#120222](https://github.com/rust-lang/rust/issues/120222))
2. Principal trait's lifetime arguments match (no `*const dyn Tr<'a>` -> `*const dyn Tr<'b>` casts, which are a problem for [#120217](https://github.com/rust-lang/rust/issues/120217))
3. No auto traits can be _added_ (this is a problem for arbitrary self types, see [this comment](https://github.com/rust-lang/rust/pull/120248#discussion_r1463835350))
Some notes:
- We only care about the metadata/last field, so you can still cast `*const dyn T` to `*const WithHeader<dyn T>`, etc
- The lifetime of the trait object itself (`dyn A + 'lt`) is not checked, so you can still cast `*mut FnOnce() + '_` to `*mut FnOnce() + 'static`, etc
- This feels fishy, but I couldn't come up with a reason it must be checked
The diagnostics are currently not great, to say the least, but as far as I can tell this correctly fixes the issues.
cc `@oli-obk` `@compiler-errors` `@lcnr`
coverage: Extract hole spans from HIR instead of MIR
This makes it possible to treat more kinds of nested item/code as holes, instead of being restricted to closures.
(It also potentially opens up the possibility of using HIR holes to modify branch or MC/DC spans, though we currently don't actually do this.)
Thus, this new implementation treats the following as holes:
- Closures (as before, including `async` and coroutines)
- All nested items
- Inline `const` (because why not)
This gives more accurate coverage reports, because lines occupied by holes don't show the execution count from the enclosing function.
Fixes#126626.
Make `push_outlives_components` into a `TypeVisitor`
This involves removing the `visited: &mut SsoHashSet<GenericArg<'tcx>>` that is being passed around the `VerifyBoundCx`. The fact that we were using it when decomposing different type tests seems sketchy, so I don't think, though it may technically result in us registering more redundant outlives components 🤷
I did end up deleting some of the comments that referred back to RFC 1214 during this refactor. I can add them back if you think they were useful.
r? lcnr
There's a comment saying we don't do it for performance reasons, but it
doesn't actually affect performance.
The commit also tweaks the control flow, to make clearer that two code
paths are mutually exclusive.
Rollup of 10 pull requests
Successful merges:
- #126841 ([`macro_metavar_expr_concat`] Add support for literals)
- #126881 (Make `NEVER_TYPE_FALLBACK_FLOWING_INTO_UNSAFE` a deny-by-default lint in edition 2024)
- #126921 (Give VaList its own home)
- #127367 (Run alloc sync tests)
- #127431 (Use field ident spans directly instead of the full field span in diagnostics on local fields)
- #127437 (Uplift trait ref is knowable into `rustc_next_trait_solver`)
- #127439 (Uplift elaboration into `rustc_type_ir`)
- #127451 (Improve `run-make/output-type-permutations` code and improve `filename_not_in_denylist` API)
- #127452 (Fix intrinsic const parameter counting with `effects`)
- #127459 (rustdoc-json: add type/trait alias tests)
r? `@ghost`
`@rustbot` modify labels: rollup
Uplift elaboration into `rustc_type_ir`
Allows us to deduplicate and consolidate elaboration (including these stupid elaboration duplicate fns i added for pretty printing like 3 years ago) so I'm pretty hyped about this change :3
r? lcnr
Use field ident spans directly instead of the full field span in diagnostics on local fields
This improves diagnostics and avoids having to store the `DefId`s of fields
Make `NEVER_TYPE_FALLBACK_FLOWING_INTO_UNSAFE` a deny-by-default lint in edition 2024
I don't actually really care about this, but ``@traviscross`` asked me to do this, because lang team briefly discussed this before.
(TC here:)
Specifically, our original FCPed plan included this step:
- Add a lint against fallback affecting a generic that is passed to an `unsafe` function.
- Perhaps make this lint `deny-by-default` or a hard error in Rust 2024.
That is, we had left as an open question strengthening this in Rust 2024, and had marked it as an open question on the tracking issue. We're nominating here to address the open question. (Closing the remaining open question helps us to fully mark this off for Rust 2024.)
r? ``@compiler-errors``
Tracking:
- https://github.com/rust-lang/rust/issues/123748
[`macro_metavar_expr_concat`] Add support for literals
Adds support for things like `${concat($variable, 123)}` or `${concat("hello", "_world")}` .
cc #124225
Support tail calls in mir via `TerminatorKind::TailCall`
This is one of the interesting bits in tail call implementation — MIR support.
This adds a new `TerminatorKind` which represents a tail call:
```rust
TailCall {
func: Operand<'tcx>,
args: Vec<Operand<'tcx>>,
fn_span: Span,
},
```
*Structurally* this is very similar to a normal `Call` but is missing a few fields:
- `destination` — tail calls don't write to destination, instead they pass caller's destination to the callee (such that eventual `return` will write to the caller of the function that used tail call)
- `target` — similarly to `destination` tail calls pass the caller's return address to the callee, so there is nothing to do
- `unwind` — I _think_ this is applicable too, although it's a bit confusing
- `call_source` — `become` forbids operators and is not created as a lowering of something else; tail calls always come from HIR (at least for now)
It might be helpful to read the interpreter implementation to understand what `TailCall` means exactly, although I've tried documenting it too.
-----
There are a few `FIXME`-questions still left, ideally we'd be able to answer them during review ':)
-----
r? `@oli-obk`
cc `@scottmcm` `@DrMeepster` `@JakobDegen`
Cache hir_owner_nodes in ParentHirIterator.
Lint level computation may traverse deep HIR trees using that iterator. This calls `hir_owner_nodes` many times for the same HIR owner, which is wasterful.
This PR caches the value to allow a more efficient iteration scheme.
r? ghost for perf
Make `can_eq` process obligations (almost) everywhere
Move `can_eq` to an extension trait on `InferCtxt` in `rustc_trait_selection`, and change it so that it processes obligations. This should strengthen it to be more accurate in some cases, but is most important for the new trait solver which delays relating aliases to `AliasRelate` goals. Without this, we always basically just return true when passing aliases to `can_eq`, which can lead to weird errors, for example #127149.
I'm not actually certain if we should *have* `can_eq` be called on the good path. In cases where we need `can_eq`, we probably should just be using a regular probe.
Fixes#127149
r? lcnr
Emit a wrap expr span_bug only if context is not tainted
Fixes#127332
The ICE occurs because of this `span_bug`: 51917e2e69/compiler/rustc_hir_typeck/src/expr_use_visitor.rs (L732-L738)
which is triggered by the fact that we're trying to use an `enum` in a `with` expression instead of a `struct`.
The issue originates in commit 814bfe9335 from PR #127202. As per the title of that commit the ICEing code should not be reachable any more, but looks like it still is.
This PR changes the code so that the `span_bug` will be emitted only if the context is not tainted by a previous error.
Currently the second element is a `Vec<(FlatToken, Spacing)>`. But the
vector always has zero or one elements, and the `FlatToken` is always
`FlatToken::AttrTarget` (which contains an `AttributesData`), and the
spacing is always `Alone`. So we can simplify it to
`Option<AttributesData>`.
An assertion in `to_attr_token_stream` can can also be removed, because
`new_tokens.len()` was always 0 or 1, which means than `range.len()`
is always greater than or equal to it, because `range.is_empty()` is
always false (as per the earlier assertion).
The only place it is meaningfully used is in a panic message in
`TokenStream::from_ast`. But `node.span()` doesn't need to be printed
because `node` is also printed and it must contain the span.
Don't try to label `ObligationCauseCode::CompareImplItem` for an RPITIT, since it has no name
The old (current) trait solver has a limitation that when a where clause in param-env must be normalized using the same where clause, then we get spurious errors in `normalize_param_env_or_error`. I don't think there's an issue tracking it, but it's the root cause for many of the "fixed-by-next-solver" labeled issues.
Specifically, these errors may occur when checking predicate entailment of the GAT that comes out of desugaring RPITITs. Since we use `ObligationCauseCode::CompareImplItem` for these predicates, we try calling `item_name` on an RPITIT which fails, since the RPITIT has no name.
We simply suppress this logic when we're reporting a predicate entailment error for an RPITIT. RPITITs should never have predicate entailment errors, *by construction*, but they may due to this bug in the old solver.
Addresses the ICE in #127331, though doesn't fix the underlying issue (which is fundamental to the old solver).
r? types
Uplift outlives components to `rustc_type_ir`
We need this to uplift `push_outlives_components`, since the elaborator uses `push_outlives_components` to elaborate type outlives obligations and I want to uplift elaboration.
This ends up reworking and inlining a fair portion of the `GenericArg::walk_shallow` function, whose only callsite was this one. I believe I got the logic correct, but may be worthwhile to look at it closely just in case. Unfortunately github was too dumb to understand that this is a rename + change -- I could also rework the git history to split the "copy the file over" part from the actual logical changes if that makes this easier to review.
r? lcnr
Elaboration tweaks
Removes `Filter::OnlySelfThatDefines` and reimplements `transitive_bounds_that_define_assoc_item` as a separate function, since I don't want to have to uplift that mode since it's both an implementation detail (only exists to avoid cycles in astconv) and requires exposing `Ident` as an associated type on `Interner`.
r? lcnr
offset_from, offset: clearly separate safety requirements the user needs to prove from corollaries that automatically follow
By landing https://github.com/rust-lang/rust/pull/116675 we decided that objects larger than `isize::MAX` cannot exist in the address space of a Rust program, which lets us simplify these rules.
For `offset_from`, we can even state that the *absolute* distance fits into an `isize`, and therefore exclude `isize::MIN`. This PR also changes Miri to treat an `isize::MIN` difference like the other isize-overflowing cases.
Match ergonomics 2024: align with RFC again
- `&` matches `&mut` on old editions
- Add some more tests
r? ``@Nadrieril``
cc https://github.com/rust-lang/rust/issues/123076
``@rustbot`` label A-edition-2024 A-patterns
Added dots at the sentence ends of rustc AST doc
Just a tiny improvement for the AST documentation by bringing consistency to sentence ends. I intentionally didn't terminate every sentence, there are still some members not having them, but at least there's no mixing style on the type level.
Use `ControlFlow` results for visitors that are only looking for a single value
These visitors all had a `Option<Value>` or `bool` field, that, once set, was never unset or modified again. They have been refactored by removing the field and returning `ControlFlow` directly from the visitor
Split `SolverDelegate` back out from `InferCtxtLike`
This is because in order to uplift things like the `Generalizer` and other `TypeRelation`s, we want to be able to interface with `InferCtxtLike` (and `InferCtxt` as its implementation), rather that `SolverDelegate`, which only really exists as a hack to be able to define some downstream methods in `rustc_type_ir`.
r? lcnr
Improve well known value check-cfg diagnostic for the standard library
This PR adjust the current logic for hidding the rustc/Cargo suggestion to add a value to a well-known name to exclude the standard library and rustc crates.
This is done in order to improve the contributor experience, in particular when adding a new target, which often requires adding some cfgs like `target_os` which may not be available yet in stage0.
<details>
The diagnostic code would look like this.
```text
error: unexpected `cfg` condition value: `blable`
--> library/core/src/lib.rs:369:7
|
369 | #[cfg(target_os = "blable")]
| ^^^^^^^^^^^^^^^^^^^^
|
= note: expected values for `target_os` are: `aix`, `android`, `cuda`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `openbsd`, `psp`, `redox`, `solaris`, `solid_asp3`, `teeos`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, and `windows` and 2 more
= help: consider using a Cargo feature instead
= help: or consider adding in `Cargo.toml` the `check-cfg` lint config for the lint:
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(target_os, values("blable"))'] }
= help: or consider adding `println!("cargo::rustc-check-cfg=cfg(target_os, values(\"blable\"))");` to the top of the `build.rs`
= note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg/cargo-specifics.html> for more information about checking conditional configuration
= note: `-D unexpected-cfgs` implied by `-D warnings`
= help: to override `-D warnings` add `#[allow(unexpected_cfgs)]`
```
</details>
Improve dead code analysis
Fixes#120770
1. check impl items later if self ty is private although the trait method is public, cause we must use the ty firstly if it's private
2. mark the adt live if it appears in pattern, like generic argument, this implies the use of the adt
3. based on the above, we can handle the case that private adts impl Default, so that we don't need adding rustc_trivial_field_reads on Default, and the logic in should_ignore_item
r? ``@pnkfelix``
coverage: Rename `mir::coverage::BranchInfo` to `CoverageInfoHi`
This opens the door to collecting and storing coverage information that is unrelated to branch coverage or MC/DC, during MIR building.
There is no change to the output of coverage instrumentation, but one deliberate change is that functions now *always* have an attached `CoverageInfoHi` (if coverage is enabled and they are eligible), even if they didn't collect any interesting branch information.
---
`@rustbot` label +A-code-coverage
DependencyList: removed outdated comment
Comment was outdated. Didn't updated description, as `Linkage` enum have descriptive names.
Also added fixme about moving this file to rustc_metadata.
Match ergonomics 2024: Implement TC's match ergonomics proposal
Under gate `ref_pat_eat_one_layer_2024_structural`. Enabling `ref_pat_eat_one_layer_2024` at the same time allows the union of what the individual gates allow. `@traviscross`
r? `@Nadrieril`
cc https://github.com/rust-lang/rust/issues/123076
`@rustbot` label A-edition-2024 A-patterns
Miri function identity hack: account for possible inlining
Having a non-lifetime generic is not the only reason a function can be duplicated. Another possibility is that the function may be eligible for cross-crate inlining. So also take into account the inlining attribute in this Miri hack for function pointer identity.
That said, `cross_crate_inlinable` will still sometimes return true even for `inline(never)` functions:
- when they are `DefKind::Ctor(..) | DefKind::Closure` -- I assume those cannot be `InlineAttr::Never` anyway?
- when `cross_crate_inline_threshold == InliningThreshold::Always`
so maybe this is still not quite the right criterion to use for function pointer identity.
cache type sizes in type-size limit visitor
This is basically https://github.com/rust-lang/rust/pull/125507#issuecomment-2206813779 as lcnr can't open the PR now.
Locally it reduces the `itertools` regression by quite a bit, to "only +50%" compared to nightly (that includes overhead from the local lack of artifact post-processing, and is just a data point to compare to the 10-20x timings without the cache).
```console
Benchmark 1: cargo +stage1 build --release
Time (mean ± σ): 2.721 s ± 0.009 s [User: 2.446 s, System: 0.325 s]
Range (min … max): 2.710 s … 2.738 s 10 runs
Benchmark 2: cargo +nightly build --release
Time (mean ± σ): 1.784 s ± 0.005 s [User: 1.540 s, System: 0.279 s]
Range (min … max): 1.778 s … 1.792 s 10 runs
Summary
cargo +nightly build --release ran
1.52 ± 0.01 times faster than cargo +stage1 build --release
```
On master, it's from 34s to the 2.7s above.
r? compiler-errors
Rollup of 9 pull requests
Successful merges:
- #123043 (Disable dead variant removal for `#[repr(C)]` enums.)
- #126405 (Migrate some rustc_builtin_macros to SessionDiagnostic)
- #127037 (Remove some duplicated tests)
- #127283 (Reject SmartPointer constructions not serving the purpose)
- #127301 (Tweak some structured suggestions to be more verbose and accurate)
- #127307 (Allow to have different types for arguments of `Rustc::remap_path_prefix`)
- #127309 (jsondocck: add `$FILE` built-in variable)
- #127314 (Trivial update on tidy bless note)
- #127319 (Remove a use of `StructuredDiag`, which is incompatible with automatic error tainting and error translations)
r? `@ghost`
`@rustbot` modify labels: rollup
Remove a use of `StructuredDiag`, which is incompatible with automatic error tainting and error translations
fixes#127219
I want to remove all of `StructuredDiag`, but it's a bit more involved as it is also used from the `ItemCtxt`, which doesn't support tainting yet.
Tweak some structured suggestions to be more verbose and accurate
Addressing some issues I found while working on #127282.
```
error: this URL is not a hyperlink
--> $DIR/auxiliary/include-str-bare-urls.md:1:11
|
LL | HEADS UP! https://example.com MUST SHOW UP IN THE STDERR FILE!
| ^^^^^^^^^^^^^^^^^^^
|
= note: bare URLs are not automatically turned into clickable links
note: the lint level is defined here
--> $DIR/include-str-bare-urls.rs:14:9
|
LL | #![deny(rustdoc::bare_urls)]
| ^^^^^^^^^^^^^^^^^^
help: use an automatic link instead
|
LL | HEADS UP! <https://example.com> MUST SHOW UP IN THE STDERR FILE!
| + +
```
```
error[E0384]: cannot assign twice to immutable variable `v`
--> $DIR/assign-imm-local-twice.rs:7:5
|
LL | v = 1;
| ----- first assignment to `v`
LL | println!("v={}", v);
LL | v = 2;
| ^^^^^ cannot assign twice to immutable variable
|
help: consider making this binding mutable
|
LL | let mut v: isize;
| +++
```
```
error[E0393]: the type parameter `Rhs` must be explicitly specified
--> $DIR/issue-22560.rs:9:23
|
LL | trait Sub<Rhs=Self> {
| ------------------- type parameter `Rhs` must be specified for this
...
LL | type Test = dyn Add + Sub;
| ^^^
|
= note: because of the default `Self` reference, type parameters must be specified on object types
help: set the type parameter to the desired type
|
LL | type Test = dyn Add + Sub<Rhs>;
| +++++
```
```
error[E0596]: cannot borrow `v` as mutable, as it is not declared as mutable
--> $DIR/issue-33819.rs:4:34
|
LL | Some(ref v) => { let a = &mut v; },
| ^^^^^^ cannot borrow as mutable
|
help: try removing `&mut` here
|
LL - Some(ref v) => { let a = &mut v; },
LL + Some(ref v) => { let a = v; },
|
```
```
help: remove the invocation before committing it to a version control system
|
LL - dbg!();
|
```
```
error[E0308]: mismatched types
--> $DIR/issue-39974.rs:1:21
|
LL | const LENGTH: f64 = 2;
| ^ expected `f64`, found integer
|
help: use a float literal
|
LL | const LENGTH: f64 = 2.0;
| ++
```
```
error[E0529]: expected an array or slice, found `Vec<i32>`
--> $DIR/match-ergonomics.rs:8:9
|
LL | [&v] => {},
| ^^^^ pattern cannot match with input type `Vec<i32>`
|
help: consider slicing here
|
LL | match x[..] {
| ++++
```
```
error[E0609]: no field `0` on type `[u32; 1]`
--> $DIR/parenthesized-deref-suggestion.rs:10:21
|
LL | (x as [u32; 1]).0;
| ^ unknown field
|
help: instead of using tuple indexing, use array indexing
|
LL | (x as [u32; 1])[0];
| ~ +
```