Normalize the result of `Fields::ty_with_args`
We were only instantiating before, which would leak an AliasTy. I added a test case that reproduce the issue seen here:
https://github.com/model-checking/kani/issues/3113
r? ``@oli-obk``
Simplify trim-paths feature by merging all debuginfo options together
This PR simplifies the trim-paths feature by merging all debuginfo options together, as described in https://github.com/rust-lang/rust/issues/111540#issuecomment-1994010274.
And also do some correctness fixes found during the review.
cc `@weihanglo`
r? `@michaelwoerister`
Match ergonomics 2024: implement mutable by-reference bindings
Implements the mutable by-reference bindings portion of match ergonomics 2024 (#123076), with the `mut ref`/`mut ref mut` syntax, under feature gate `mut_ref`.
r? `@Nadrieril`
`@rustbot` label A-patterns A-edition-2024
CFI: Fix methods as function pointer cast
Fix casting between methods and function pointers by assigning a secondary type id to methods with their concrete self so they can be used as function pointers.
This was split off from #116404.
cc `@compiler-errors` `@workingjubilee`
Eliminate `UbChecks` for non-standard libraries
The purpose of this PR is to allow other passes to treat `UbChecks` as constants in MIR for optimization after #122629.
r? RalfJung
Codegen const panic messages as function calls
This skips emitting extra arguments at every callsite (of which there
can be many). For a librustc_driver build with overflow checks enabled,
this cuts 0.7MB from the resulting shared library (see [perf]).
A sample improvement from nightly:
```
leaq str.0(%rip), %rdi
leaq .Lalloc_d6aeb8e2aa19de39a7f0e861c998af13(%rip), %rdx
movl $25, %esi
callq *_ZN4core9panicking5panic17h17cabb89c5bcc999E@GOTPCREL(%rip)
```
to this PR:
```
leaq .Lalloc_d6aeb8e2aa19de39a7f0e861c998af13(%rip), %rdi
callq *_RNvNtNtCsduqIKoij8JB_4core9panicking11panic_const23panic_const_div_by_zero@GOTPCREL(%rip)
```
[perf]: https://perf.rust-lang.org/compare.html?start=a7e4de13c1785819f4d61da41f6704ed69d5f203&end=64fbb4f0b2d621ff46d559d1e9f5ad89a8d7789b&stat=instructions:u
Rollup of 6 pull requests
Successful merges:
- #123063 (Function ABI is irrelevant for reachability)
- #123096 (Don't check match scrutinee of postfix match for unused parens)
- #123146 (Use compiletest directives instead of manually checking TARGET / tools)
- #123160 (remove `def_id_to_node_id` in ast lowering)
- #123162 (Correctly get complete intra-doc link data)
- #123164 (Bump Unicode printables to version 15.1, align to unicode_data)
r? `@ghost`
`@rustbot` modify labels: rollup
Correctly get complete intra-doc link data
Fixes https://github.com/rust-lang/rust/issues/123158.
The problem was that we didn't take into account cases where there would be content other than backticks into the intra doc link definition.
r? `@notriddle`
Use compiletest directives instead of manually checking TARGET / tools
Changes:
- Accept `ignore-wasm32-wasip1` and `needs-wasmtime` directives.
- Add support for needing `wasmtime` as a runner.
- Update wasm/compiler_builtin tests to use compiletest directives over manual checks.
Don't check match scrutinee of postfix match for unused parens
We only check the scrutinees of block-like constructs and a few others (return/index/assign/method calls). Just don't do it for postfix match at all.
Fixes#123064
r? fmease
Suggest correct path in include_bytes!
`include_bytes!` paths are relative, and I'm often not sure how nested is the `.rs` file that I'm editing, so I have to guess the number of `"../.."`. This change searches `..` and `../..` for the given file and offers corrected path as a suggestion.
I wasn't sure how to get the right span, and how to properly escape it.
```text
error: couldn't read src/file.txt: No such file or directory (os error 2)
--> src/main.rs:2:13
|
2 | let x = include_bytes!("file.txt");
| ^^^^^^^^^^^^^^^----------^
| |
| help: it's in a parent directory: `"../../file.txt"`
```
Fix casting between methods and function pointers by assigning a
secondary type id to methods with their concrete self so they can be
used as function pointers.
Delegation: fix ICE on wrong `Self` instantiation
fixes https://github.com/rust-lang/rust/issues/119921
fixes https://github.com/rust-lang/rust/issues/119919
There is no way to instantiate `Self` param for caller in delegation item if
1. callee is a trait method && callee contains `Self` param
2. delegation item isn't an associative item
In general, we can consider `Self` param as independent type param in these cases:
```rust
trait Trait {
fn foo(_: Option<&Self>) {...}
}
reuse Trait::foo;
// will be desugared to:
fn foo<T: Trait>(x: Option<&T>) { Trait::foo(x) }
```
But this requires early bound parameters support. For now, I suggest banning such cases to avoid ICE's.
r? ``@petrochenkov``
CFI: Fix drop and drop_in_place
Fix drop and drop_in_place by transforming self of drop and drop_in_place methods into a Drop trait objects.
This was split off from https://github.com/rust-lang/rust/pull/116404.
cc `@compiler-errors` `@workingjubilee`
Rework rmake support library API
### Take 1: Strongly-typed API
Context: https://github.com/rust-lang/rust/pull/122448#discussion_r1523774427
> My 2 cents: from my experience with writing similar "test DSLs", I would suggest to create these helpers as soon as possible in the process (basically the first time someone needs them, not only after N similar usages), and basically treat any imperative code in these high-level tests as a maintenance burden, basically making them as declarative as possible. Otherwise it might be a bit annoying to keep refactoring the tests later once such helpers are available.
>
> I would even discourage the arg method and create explicit methods for setting things like unpretty, the output file etc., but this might be more controversial, as it will make the invoked command-line arguments more opaque.
cc `@Kobzol` for the testing DSL suggestion.
Example:
```rs
let output = Rustc::new()
.input_file("main.rs")
.emit(&[EmitKind::Metadata])
.extern_("stable", &stable_path)
.output();
```
### Take 2: xshell-based macro API
Example:
```rs
let sh = Shell::new()?;
let stable_path = stable_path.to_string_lossy();
let output = cmd!(sh, "rustc main.rs --emit=metadata --extern stable={stable_path}").output()?;
```
### Take 3: Weakly-typed API with a few helper methods
```rs
let output = Rustc::new()
.input("main.rs")
.emit("metadata")
.extern_("stable", &stable_path)
.output();
```
CFI: Enable KCFI testing of run-pass tests
This enables KCFI-based testing for all the CFI run-pass tests in the suite today. We can add the test header on top of in-flight CFI tests once they land. This is becoming more important as we get closer to leveraging CFI's multiple type attachment feature, as that is where the implementations will have a divergence.
It also enables KCFI as a sanitizer for x86_64 and aarch64 Linux to make this possible. The sanitizer should likely be available for all aarch64, x86_64, and riscv targets, but that isn't critical for initial testing.
coverage: Re-enable `UnreachablePropagation` for coverage builds
This is a sequence of 3 related changes:
- Clean up the existing code that scans for unused functions
- Detect functions that were instrumented for coverage, but have had all their coverage statements removed by later MIR transforms (e.g. `UnreachablePropagation`)
- Re-enable `UnreachablePropagation` in coverage builds
Because we now detect functions that have lost their coverage statements, and treat them as unused, we don't need to worry about `UnreachablePropagation` removing all of those statements. This is demonstrated by `tests/coverage/unreachable.rs`.
Fixes#116171.
Soft-destabilize `RustcEncodable` & `RustcDecodable`, remove from prelude in next edition
cc rust-lang/libs-team#272
Any use of `RustcEncodable` and `RustcDecodable` now triggers a deny-by-default lint. The derives have been removed from the 2024 prelude. I specifically chose **not** to document this in the module-level documentation, as the presence in existing preludes is not documented (which I presume is intentional).
This does not implement the proposed change for `rustfix`, which I will be looking into shortly.
With regard to the items in the preludes being stable, this should not be an issue because #15702 has been resolved.
r? libs-api
Rollup of 9 pull requests
Successful merges:
- #108675 (Document `adt_const_params` feature in Unstable Book)
- #122120 (Suggest associated type bounds on problematic associated equality bounds)
- #122589 (Fix diagnostics for async block cloning)
- #122835 (Require `DerefMut` and `DerefPure` on `deref!()` patterns when appropriate)
- #123049 (In `ConstructCoroutineInClosureShim`, pass receiver by mut ref, not mut pointer)
- #123055 (enable cargo miri test doctests)
- #123057 (unix fs: Make hurd using explicit new rather than From)
- #123087 (Change `f16` and `f128` clippy stubs to be nonpanicking)
- #123103 (Rename `Inherited` -> `TypeckRootCtxt`)
r? `@ghost`
`@rustbot` modify labels: rollup
In `ConstructCoroutineInClosureShim`, pass receiver by mut ref, not mut pointer
The receivers were compatible at codegen time, but did not necessarily have the same layouts due to niches, which was caught by miri.
Fixesrust-lang/miri#3400
r? oli-obk
Suggest associated type bounds on problematic associated equality bounds
Fixes#105056. TL;DR: Suggest `Trait<Ty: Bound>` on `Trait<Ty = Bound>` in Rust >=2021.
~~Blocked on #122055 (stabilization of `associated_type_bounds`), I'd say.~~ (merged)
Delegation: fix ICE on wrong `self` resolution
fixes https://github.com/rust-lang/rust/issues/122874
Delegation item should be wrapped in a `rib` to behave like a regular function during name resolution.
r? `@petrochenkov`
match lowering: consistently merge simple or-patterns
There are two places where we expand or-patterns in match lowering: the main one is `test_candidates_with_or`, and there's one in `match_candidates` that's an optimization for the simple case where the whole pattern is just one or-pattern.
To reduce duplication, we merge or-pattern alternatives into a single block when possible, but we only to that in `test_candidates_with_or`. This PR fixes this oversight and merges them in `match_candidates` too.
This is a part of splitting up https://github.com/rust-lang/rust/pull/122046 into smaller bits.
CFI: (actually) check that methods are object-safe before projecting their receivers to `dyn Trait` in CFI
`trait_object_ty` assumed that associated types would be fully determined by the trait. This is *almost* true - const parameters and type parameters are no longer allowed, but lifetime parameters are. Since we erase all lifetime parameters anyways, instantiate it with as many erased regions as it needs.
Fixes: #123053
r? `@compiler-errors`
Avoid some unnecessary query invocations.
Specifically this inlines `const_eval_poly` and avoids computing the generic params, the param env, normalizing the param env and erasing lifetimes on everything.
should fix the perf regression from https://github.com/rust-lang/rust/pull/121087
This enables KCFI-based testing for all the CFI run-pass tests in the
suite today. We can add the test header on top of in-flight CFI tests
once they land.
It also enables KCFI as a sanitizer for x86_64 and aarch64 Linux to make
this possible. The sanitizer should likely be available for all aarch64,
x86_64, and riscv targets, but that isn't critical for initial testing.
Rollup of 10 pull requests
Successful merges:
- #122707 (Fix a typo in the alloc::string::String docs)
- #122769 (extend comments for reachability set computation)
- #122892 (fix(bootstrap/dist): use versioned dirs when vendoring)
- #122896 (Update stdarch submodule)
- #122923 (In `pretty_print_type()`, print `async fn` futures' paths instead of spans.)
- #122950 (Add regression tests for #101903)
- #123039 (Update books)
- #123042 (Import the 2021 prelude in the core crate)
- #123044 (`Instance` is `Copy`)
- #123051 (did I mention that tests are super cool? )
r? `@ghost`
`@rustbot` modify labels: rollup
Print a backtrace in const eval if interrupted
Demo:
```rust
#![feature(const_eval_limit)]
#![const_eval_limit = "0"]
const OW: u64 = {
let mut res: u64 = 0;
let mut i = 0;
while i < u64::MAX {
res = res.wrapping_add(i);
i += 1;
}
res
};
fn main() {
println!("{}", OW);
}
```
```
╭ ➜ ben@archlinux:~/rust
╰ ➤ rustc +stage1 spin.rs
^Cerror[E0080]: evaluation of constant value failed
--> spin.rs:8:33
|
8 | res = res.wrapping_add(i);
| ^ Compilation was interrupted
note: erroneous constant used
--> spin.rs:15:20
|
15 | println!("{}", OW);
| ^^
note: erroneous constant used
--> spin.rs:15:20
|
15 | println!("{}", OW);
| ^^
|
= note: this note originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error
For more information about this error, try `rustc --explain E0080`.
```
`trait_object_ty` assumed that associated types would be fully
determined by the trait. This is *almost* true - const parameters and
type parameters are no longer allowed, but lifetime parameters are.
Since we erase all lifetime parameters anyways, instantiate it with as
many erased regions as it needs.
Fixes: #123053
In `pretty_print_type()`, print `async fn` futures' paths instead of spans.
This makes `-Zprint-type-sizes`'s output easier to read, because the name of an `async fn` is more immediately recognizable than its span. This change will also synergize with my other `-Zprint-type-sizes` PR #122922 which prints the type of child futures being awaited.
I also deleted the comment "FIXME(eddyb) should use `def_span`." because it appears to have already been fixed by commit 67727aa7c3.
Validate that we're only matching on unit struct for path pattern
Resolution doesn't validate that we only really take `CtorKind::Unit` in path patterns, since all it sees is `Res::SelfCtor(def_id)`. Check this instead during pattern typeck.
r? petrochenkov
Fixes#122809
Delegation: fix ICE on `bound_vars` divergence
Fixes https://github.com/rust-lang/rust/issues/122550.
Bug was caused by divergence between lowered type and corresponding `bound_vars` in `late_bound_vars_map`. In this patch `bound_vars` calculation for delegation item is moved from `lower_fn_ty` to `resolve_bound_vars` query.
r? `@petrochenkov`
Don't emit an error about failing to produce a file with a specific name if user never gave an explicit name
Fixes#122509
You can ask `rustc` to produce some intermediate results with `--emit foo`, this operation comes in two flavors: `--emit asm` and `--emit asm=foo.s`. First one produces one or more `.s` files without any name guarantees, second one renames it into `foo.s`. Second version only works when compiler produces a single file - for asm files this means using a single compilation unit for example.
In case compilation produced more than a single file `rustc` runs following check to emit some warnings:
```rust
if crate_output.outputs.contains_key(&output_type) {
// 2) Multiple codegen units, with `--emit foo=some_name`. We have
// no good solution for this case, so warn the user.
sess.dcx().emit_warn(errors::IgnoringEmitPath { extension });
} else if crate_output.single_output_file.is_some() {
// 3) Multiple codegen units, with `-o some_name`. We have
// no good solution for this case, so warn the user.
sess.dcx().emit_warn(errors::IgnoringOutput { extension });
} else {
// 4) Multiple codegen units, but no explicit name. We
// just leave the `foo.0.x` files in place.
// (We don't have to do any work in this case.)
}
```
Comment in the final `else` branch implies that if user didn't ask for a specific name - there's no need to emit warnings. However because of the internal representation of `crate_output.outputs` - this doesn't work as expected: if user asked to produce an asm file without giving it an implicit name it will contain `Some(None)`.
To fix the problem new code actually checks if user gave an explicit name. I think this was an original intentional behavior, at least comments imply that.
This makes `-Zprint-type-sizes`'s output easier to read, because the
name of an `async fn` is more immediately recognizable than its span.
I also deleted the comment "FIXME(eddyb) should use `def_span`." because
it appears to have already been fixed by commit 67727aa7c3.
CFI: Support complex receivers
Right now, we only support rewriting `&self` and `&mut self` into `&dyn MyTrait` and `&mut dyn MyTrait`. This expands it to handle the full gamut of receivers by calculating the receiver based on *substitution* rather than based on a rewrite. This means that, for example, `Arc<Self>` will become `Arc<dyn MyTrait>` appropriately with this change.
This approach also allows us to support associated type constraints as well, so we will correctly rewrite `&self` into `&dyn MyTrait<T=i32>`, for example.
r? ```@workingjubilee```
CFI: Handle dyn with no principal
In user-facing Rust, `dyn` always has at least one predicate following it. Unfortunately, because we filter out marker traits from receivers at callsites and `dyn Sync` is, for example, legal, this results in us having `dyn` types with no predicates on occasion in our alias set encoding. This patch handles cases where there are no predicates in a `dyn` type which are relevant to its alias set.
Fixes#122998
r? workingjubilee
Clean up unnecessary headers/flags in coverage mir-opt tests
During #122542, I noticed that some of the headers and flags I had copied over from `tests/mir-opt/instrument_coverage.rs` were unnecessary. And while working to remove those, I noticed even more that could be removed or replaced.
Replace `mir_built` query with a hook and use mir_const everywhere instead
A small perf improvement due to less dep graph handling.
Mostly just a cleanup to get rid of one of our many mir queries
Previously, we only rewrote `&self` and `&mut self` receivers. By
instantiating the method from the trait definition, we can make this
work work with arbitrary legal receivers instead.
This saves some debug and scope metadata in every single function that calls it.
Normally wouldn't be worth it, but with the derives there's *so* many of these.
In user-facing Rust, `dyn` always has at least one predicate following
it. Unfortunately, because we filter out marker traits from receivers at
callsites and `dyn Sync` is, for example, legal, this results in us
having `dyn` types with no predicates on occasion in our alias set
encoding. This patch handles cases where there are no predicates in a
`dyn` type which are relevant to its alias set.
Fixes#122998
panic-in-panic-hook: formatting a message that's just a string is risk-free
This slightly improves the output in the 'panic while processing panic' case if the panic message does not involve any formatting. Follow-up to https://github.com/rust-lang/rust/pull/122930.
r? ``@Amanieu``
Add a regression test for #117310Closes#117310
It seems to have been fixed in `rustc 1.79.0-nightly (1388d7a06 2024-03-20)` or before, so just adding a regression test for it.
Fixed the `private-dependency` bug
Fixed the private-dependency bug: If the directly dependent crate is loaded last and is not configured with `--extern`, it may be incorrectly set to `private-dependency`
Fixes#122756
Encode implied predicates for traits
In #112629, we decided to make associated type bounds in the "supertrait" AST position *implied* even though they're not supertraits themselves.
This means that the `super_predicates` and `implied_predicates` queries now differ for regular traits. The assumption that they didn't differ was hard-coded in #107614, so in cross-crate positions this means that we forget the implied predicates from associated type bounds.
This isn't unsound, just kind of annoying. This should be backported since associated type bounds are slated to stabilize for 1.78 -- either that, or associated type bounds can be reverted on beta and re-shipped in 1.79 with this patch.
Fixes#122859
CFI: Strip auto traits off Virtual calls
We already use `Instance` at declaration sites when available to glean additional information about possible abstractions of the type in use. This does the same when possible at callsites as well.
The primary purpose of this change is to allow CFI to alter how it generates type information for indirect calls through `Virtual` instances.
This is needed for the "separate machinery" version of my approach to the vtable issues (#122573), because we need to respond differently to a `Virtual` call to the same type as a non-virtual call, specifically [stripping auto traits off the receiver's `Self`](54b15b0c36) because there isn't a separate vtable for `Foo` vs `Foo + Send`.
This would also make a more general underlying mechanism that could be used by rcvalle's [proposed drop detection / encoding](edcd1e20a1) if we end up using his approach, as we could condition out on the `def_id` in the CFI code rather than requiring the generating code to explicitly note whether it was calling drop.
CFI: Support self_cell-like recursion
Current `transform_ty` attempts to avoid cycles when normalizing `#[repr(transparent)]` types to their interior, but runs afoul of this pattern used in `self_cell`:
```
struct X<T> {
x: u8,
p: PhantomData<T>,
}
#[repr(transparent)]
struct Y(X<Y>);
```
When attempting to normalize Y, it will still cycle indefinitely. By using a types-visited list, this will instead get expanded exactly one layer deep to X<Y>, and then stop, not attempting to normalize `Y` any further.
This PR was split off from #121962 as part of fixing the larger vtable compatibility issues.
r? ``````@workingjubilee``````
Mention Register Size in `#[warn(asm_sub_register)]`
Fixes#121593
Displays the register size information obtained from `suggest_modifier()` and `default_modifier()`.
Add test in higher ranked subtype
I'm a beginner in this repository, and there are some things I'm not sure about:
- Is it okay that there is a warning:
```
rustc_infer::infer::relate::generalize may incompletely handle alias type: AliasTy { args: [?1t, '^0.Named(DefId(0:15 ~ structually_relate_aliases[de75]::{impl#1}::'a), "'a")], def_id: DefId(0:5 ~ structually_relate_aliases[de75]::ToUnit::Unit) }
```
- Is it okay that there are two duplicate errors in the same line?
- Did I put the test in the right place?
Any suggestions would be appreciated.
Fixes#121649
`rustdoc --test`: Prevent reaching the maximum size of command-line by using files for arguments if there are too many
Fixes#122722.
Thanks to this I discovered that rust was using ``@`` to add arguments from a file, quite convenient.
If there are too many `cfg` arguments given to `rustdoc --test`, it'll now put them into a temporary file and passing it as argument to the rustc command.
I added a test with 100_000 `cfg` arguments to ensure it'll not break again.
r? `@notrid`
Handle str literals written with `'` lexed as lifetime
Given `'hello world'` and `'1 str', provide a structured suggestion for a valid string literal:
```
error[E0762]: unterminated character literal
--> $DIR/lex-bad-str-literal-as-char-3.rs:2:26
|
LL | println!('hello world');
| ^^^^
|
help: if you meant to write a `str` literal, use double quotes
|
LL | println!("hello world");
| ~ ~
```
```
error[E0762]: unterminated character literal
--> $DIR/lex-bad-str-literal-as-char-1.rs:2:20
|
LL | println!('1 + 1');
| ^^^^
|
help: if you meant to write a `str` literal, use double quotes
|
LL | println!("1 + 1");
| ~ ~
```
Fix#119685.
Fix validation on substituted callee bodies in MIR inliner
When inlining a coroutine, we will substitute the MIR body with the args of the call. There is code in the MIR validator that attempts to prevent query cycles, and will use the coroutine body directly when it detects that's the body that's being validated. That means that when inlining a coroutine body that has been substituted, it may no longer be parameterized over the original args of the coroutine, which will lead to substitution ICEs.
Fixes#119064