rustc_interface: Add a new query `pre_configure`
It partially expands crate attributes before the main expansion pass (without modifying the crate), and the produced preliminary crate attribute list is used for querying a few attributes that are required very early.
Crate-level cfg attributes on the crate itself are then expanded normally during the main expansion pass, like attributes on any other nodes.
This is a continuation of https://github.com/rust-lang/rust/pull/92473 and one more step to very unstable crate-level proc macro attributes maybe actually working.
Previously crate attributes were pre-configured simultaneously with feature extraction, and then written directly into `ast::Crate`.
Rollup of 7 pull requests
Successful merges:
- #108541 (Suppress `opaque_hidden_inferred_bound` for nested RPITs)
- #109137 (resolve: Querify most cstore access methods (subset 2))
- #109380 (add `known-bug` test for unsoundness issue)
- #109462 (Make alias-eq have a relation direction (and rename it to alias-relate))
- #109475 (Simpler checked shifts in MIR building)
- #109504 (Stabilize `arc_into_inner` and `rc_into_inner`.)
- #109506 (make param bound vars visibly bound vars with -Zverbose)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
It partially expands crate attributes before the main expansion pass (without modifying the crate), and the produced preliminary crate attribute list is used for querying a few attributes that are required very early.
Crate-level cfg attributes are then expanded normally during the main expansion pass, like attributes on any other nodes.
Fix cross-compiling with dlltool for raw-dylib
Fix for #103939
Issue Details:
When attempting to cross-compile using the `raw-dylib` feature and the GNU toolchain, rustc would attempt to find a cross-compiling version of dlltool (e.g., `i686-w64-mingw32-dlltool`). The has two issues 1) on Windows dlltool is always `dlltool` (no cross-compiling named versions exist) and 2) it only supported compiling to i686 and x86_64 resulting in ARM 32 and 64 compiling as x86_64.
Fix Details:
* On Windows always use the normal `dlltool` binary.
* Add the ARM64 cross-compiling dlltool name (support for this is coming: https://sourceware.org/bugzilla/show_bug.cgi?id=29964)
* Provide the `-m` argument to dlltool to indicate the target machine type.
(This is the first of two PRs to fix the remaining issues for the `raw-dylib` feature (#58713) that is blocking stabilization (#104218))
make param bound vars visibly bound vars with -Zverbose
I was trying to debug some type/const bound var stuff and it was shockingly tricky due to the fact that even with `-Zverbose` enabled the `T` in `for<T> T: Trait` prints as `T` making it seem like its `TyKind::Param` when it is infact `TyKind::Bound`. This PR "fixes" this when `-Zverbose` is set to allow rendering it as `^T` or `^1_T` depending on binder depth.
r? ```@compiler-errors```
Simpler checked shifts in MIR building
Doing masking to check unsigned shift amounts is overcomplicated; just comparing the shift directly saves a statement and a temporary, as well as is much easier to read as a human. And shifting by unsigned is the canonical case -- notably, all the library shifting methods (that don't support every type) take shift RHSs as `u32` -- so we might as well make that simpler since it's easy to do so.
This PR also changes *signed* shift amounts to `IntToInt` casts and then uses the same check as for unsigned. The bit-masking is a nice trick, but for example LLVM actually canonicalizes it to an unsigned comparison anyway <https://rust.godbolt.org/z/8h59fMGT4> so I don't think it's worth the effort and the extra `Constant`. (If MIR's `assert` was `assert_nz` then the masking might make sense, but when the `!=` uses another statement I think the comparison is better.)
To review, I suggest looking at 2ee0468c49 first -- that's the interesting code change and has a MIR diff.
My favourite part of the diff:
```diff
- _20 = BitAnd(_19, const 340282366920938463463374607431768211448_u128); // scope 0 at $DIR/shifts.rs:+2:34: +2:44
- _21 = Ne(move _20, const 0_u128); // scope 0 at $DIR/shifts.rs:+2:34: +2:44
- assert(!move _21, "attempt to shift right by `{}`, which would overflow", _19) -> [success: bb3, unwind: bb7]; // scope 0 at $DIR/shifts.rs:+2:34: +2:44
+ _18 = Lt(_17, const 8_u128); // scope 0 at $DIR/shifts.rs:+2:34: +2:44
+ assert(move _18, "attempt to shift right by `{}`, which would overflow", _17) -> [success: bb3, unwind: bb7]; // scope 0 at $DIR/shifts.rs:+2:34: +2:44
```
Make alias-eq have a relation direction (and rename it to alias-relate)
Emitting an "alias-eq" is too strict in some situations, since we don't always want strict equality between a projection and rigid ty. Adds a relation direction.
* I could probably just reuse this [`RelationDir`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_infer/infer/combine/enum.RelationDir.html) -- happy to uplift that struct into middle and use that instead, but I didn't feel compelled to... 🤷
* Some of the matching in `compute_alias_relate_goal` is a bit verbose -- I guess I could simplify it by using [`At::relate`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_infer/infer/at/struct.At.html#method.relate) and mapping the relation-dir to a variance.
* Alternatively, I coulld simplify things by making more helper functions on `EvalCtxt` (e.g. `EvalCtxt::relate_with_direction(T, T)` that also does the nested goal registration). No preference.
r? ```@lcnr``` cc ```@BoxyUwU``` though boxy can claim it if she wants
NOTE: first commit is all the changes, the second is just renaming stuff
Make NLL Type Relating Eager
We previously instantiated bound regions in nll type relating lazily. Making this eager is more consistent with how we handle type relating in [`higher_ranked_sub`](0a3b557d52/compiler/rustc_infer/src/infer/higher_ranked/mod.rs (L28)) and should allow us to short circuit in case there's structural equality.
Updates `interpret`, `codegen_ssa`, and `codegen_cranelift` to consume the new cast instead of the intrinsic.
Includes `CastTransmute` for custom MIR building, to be able to test the extra UB.
new solver cleanup + implement coherence
the cleanup:
- change `Certainty::unify_and` to consider ambig + overflow to be ambig
- rename `trait_candidate_should_be_dropped_in_favor_of` to `candidate_should_be_dropped_in_favor_of`
- remove outdated fixme
For coherence I mostly just add an ambiguous candidate if the current trait ref is unknowable. I am doing the same for reservation impl where I also just add an ambiguous candidate.
Use region-erased self type during IAT selection
Split off from #109410 as discussed.
Fixes#109299.
Re UI test: I use a reproducer of #109299 that contains a name resolution error instead of reproducer [`regionck-2.rs`](fc7ed4af16/tests/ui/associated-inherent-types/regionck-2.rs) (as found in the `AliasKind::Inherent` PR) since it would (incorrectly) pass typeck in this PR due to the lack of regionck and I'd rather not make *that* a regression test (with or without `known-bug`).
``@rustbot`` label F-inherent_associated_types
r? ``@compiler-errors``
rustc: Remove unused `Session` argument from some attribute functions
(One auxiliary test file containing one of these functions was unused, so I removed it instead of updating.)
Eagerly intern and check CrateNum/StableCrateId collisions
r? ``@cjgillot``
It seems better to check things ahead of time than checking them afterwards.
The [previous version](https://github.com/rust-lang/rust/pull/108390) was a bit nonsensical, so this addresses the feedback
Do not feed param_env for RPITITs impl side
r? `@compiler-errors`
I don't think this needs more comments or things that we already have but please let me know if you want some comments or something else in this PR.
Detect uninhabited types early in const eval
r? `@RalfJung`
implements https://github.com/rust-lang/rust/pull/108442#discussion_r1143003840
this is a breaking change, as some UB during const eval is now detected instead of silently being ignored. Users can see this and other UB that may cause future breakage with `-Zextra-const-ub-checks` or just by running miri on their code, which sets that flag by default.
Do not consider synthesized RPITITs on missing items checks
Without this patch for `tests/ui/impl-trait/in-trait/dont-project-to-rpitit-with-no-value.rs` we get ...
```
warning: the feature `return_position_impl_trait_in_trait` is incomplete and may not be safe to use and/or cause compiler crashes
--> tests/ui/impl-trait/in-trait/dont-project-to-rpitit-with-no-value.rs:4:12
|
4 | #![feature(return_position_impl_trait_in_trait)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: see issue #91611 <https://github.com/rust-lang/rust/issues/91611> for more information
= note: `#[warn(incomplete_features)]` on by default
error[E0046]: not all trait items implemented, missing: `foo`, ``
--> tests/ui/impl-trait/in-trait/dont-project-to-rpitit-with-no-value.rs:12:1
|
8 | fn foo(&self) -> impl Sized;
| ----------------------------
| | |
| | `` from trait
| `foo` from trait
...
12 | impl MyTrait for i32 {
| ^^^^^^^^^^^^^^^^^^^^ missing `foo`, `` in implementation
error: aborting due to previous error; 1 warning emitted
For more information about this error, try `rustc --explain E0046`.
```
instead of ...
```
warning: the feature `return_position_impl_trait_in_trait` is incomplete and may not be safe to use and/or cause compiler crashes
--> $DIR/dont-project-to-rpitit-with-no-value.rs:4:12
|
LL | #![feature(return_position_impl_trait_in_trait)]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: see issue #91611 <https://github.com/rust-lang/rust/issues/91611> for more information
= note: `#[warn(incomplete_features)]` on by default
error[E0046]: not all trait items implemented, missing: `foo`
--> $DIR/dont-project-to-rpitit-with-no-value.rs:12:1
|
LL | fn foo(&self) -> impl Sized;
| ---------------------------- `foo` from trait
...
LL | impl MyTrait for i32 {
| ^^^^^^^^^^^^^^^^^^^^ missing `foo` in implementation
error: aborting due to previous error; 1 warning emitted
For more information about this error, try `rustc --explain E0046`.
```
r? `@compiler-errors`
Update links for custom discriminants.
The discriminant documentation was updated in https://github.com/rust-lang/reference/pull/1055 which changed the layout a bit. This updates the links to the updated locations.
rustdoc: Cleanup parent module tracking for doc links
Keep ids of the documented items themselves, not their parent modules. Parent modules can be retreived from those ids when necessary.
Fixes https://github.com/rust-lang/rust/issues/108501.
That issue could be fixed in a more local way, but this refactoring is something that I wanted to do since https://github.com/rust-lang/rust/pull/93805 anyway.
move Option::as_slice to intrinsic
````@scottmcm```` suggested on #109095 I use a direct approach of unpacking the operation in MIR lowering, so here's the implementation.
cc ````@nikic```` as this should hopefully unblock #107224 (though perhaps other changes to the prior implementation, which I left for bootstrapping, are needed).
a general type system cleanup
removes the helper functions `traits::fully_solve_X` as they add more complexity then they are worth. It's confusing which of these helpers should be used in which context.
changes the way we deal with overflow to always add depth in `evaluate_predicates_recursively`. It may make sense to actually fully transition to not have `recursion_depth` on obligations but that's probably a bit too much for this PR.
also removes some other small - and imo unnecessary - helpers.
r? types
Only clear written-to locals in ConstProp
This aims to revert the regression in https://github.com/rust-lang/rust/pull/108872
Clearing all locals at the end of each bb is very costly.
This PR goes back to the original implementation of recording which locals are modified.
Rollup of 8 pull requests
Successful merges:
- #96391 (Windows: make `Command` prefer non-verbatim paths)
- #108164 (Drop all messages in bounded channel when destroying the last receiver)
- #108729 (fix: modify the condition that `resolve_imports` stops)
- #109336 (Constrain const vars to error if const types are mismatched)
- #109403 (Avoid ICE of attempt to add with overflow in emitter)
- #109415 (Refactor `handle_missing_lit`.)
- #109441 (Only implement Fn* traits for extern "Rust" safe function pointers and items)
- #109446 (Do not suggest bounds restrictions for synthesized RPITITs)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Do not suggest bounds restrictions for synthesized RPITITs
Before this PR we were getting ...
```
warning: the feature `async_fn_in_trait` is incomplete and may not be safe to use and/or cause compiler crashes
--> tests/ui/async-await/in-trait/missing-send-bound.rs:5:12
|
5 | #![feature(async_fn_in_trait)]
| ^^^^^^^^^^^^^^^^^
|
= note: see issue #91611 <https://github.com/rust-lang/rust/issues/91611> for more information
= note: `#[warn(incomplete_features)]` on by default
error: future cannot be sent between threads safely
--> tests/ui/async-await/in-trait/missing-send-bound.rs:17:20
|
17 | assert_is_send(test::<T>());
| ^^^^^^^^^^^ future returned by `test` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `impl Future<Output = ()>`
note: future is not `Send` as it awaits another future which is not `Send`
--> tests/ui/async-await/in-trait/missing-send-bound.rs:13:5
|
13 | T::bar().await;
| ^^^^^^^^ await occurs here on type `impl Future<Output = ()>`, which is not `Send`
note: required by a bound in `assert_is_send`
--> tests/ui/async-await/in-trait/missing-send-bound.rs:21:27
|
21 | fn assert_is_send(_: impl Send) {}
| ^^^^ required by this bound in `assert_is_send`
help: consider further restricting the associated type
|
16 | fn test2<T: Foo>() where impl Future<Output = ()>: Send {
| ++++++++++++++++++++++++++++++++++++
error: aborting due to previous error; 1 warning emitted
```
and we want this output ...
```
warning: the feature `async_fn_in_trait` is incomplete and may not be safe to use and/or cause compiler crashes
--> $DIR/missing-send-bound.rs:5:12
|
LL | #![feature(async_fn_in_trait)]
| ^^^^^^^^^^^^^^^^^
|
= note: see issue #91611 <https://github.com/rust-lang/rust/issues/91611> for more information
= note: `#[warn(incomplete_features)]` on by default
error: future cannot be sent between threads safely
--> $DIR/missing-send-bound.rs:17:20
|
LL | assert_is_send(test::<T>());
| ^^^^^^^^^^^ future returned by `test` is not `Send`
|
= help: within `impl Future<Output = ()>`, the trait `Send` is not implemented for `impl Future<Output = ()>`
note: future is not `Send` as it awaits another future which is not `Send`
--> $DIR/missing-send-bound.rs:13:5
|
LL | T::bar().await;
| ^^^^^^^^ await occurs here on type `impl Future<Output = ()>`, which is not `Send`
note: required by a bound in `assert_is_send`
--> $DIR/missing-send-bound.rs:21:27
|
LL | fn assert_is_send(_: impl Send) {}
| ^^^^ required by this bound in `assert_is_send`
error: aborting due to previous error; 1 warning emitted
```
r? `@compiler-errors`
Only implement Fn* traits for extern "Rust" safe function pointers and items
Since calling the function via an `Fn` trait will assume `extern "Rust"` ABI and not do any safety checks, only safe `extern "Rust"` function can implement the `Fn` traits. This syncs the logic between the old solver and the new solver.
r? `@compiler-errors`
Constrain const vars to error if const types are mismatched
When equating two consts of different types, if either are const variables, constrain them to the correct const error kind.
This helps us avoid "successfully" matching a const against an impl signature but leaving unconstrained const vars, which will lead to incremental ICEs when we call const-eval queries during const projection.
Fixes#109296
The second commit in the stack fixes a regression in the first commit where we end up mentioning `[const error]` in an impl overlap error message. I think the error message changes for the better, but I could implement alternative strategies to avoid this without delaying the overlap error message...
r? `@BoxyUwU`
not *all* retags might be explicit in Runtime MIR
In https://github.com/rust-lang/rust/pull/105317 I made Miri treat `Rvalue::Ref/AddrOf` as implicit retagging sites. This updates the MIR docs accordingly.
For `Rvalue::Ref` I think this makes a lot more sense: creating a new reference is their entire point, so we can avoid bloating the MIR with retags. Also this seems to be the best way to handle cases like `*ptr = &[mut] ...`, where doing a retag is somewhat questionable since maybe `*ptr` points to another place now?
For `Rvalue::AddrOf`, Stacked Borrows needs this because even raw ptrs need some retagging, but Tree Borrows doesn't do ant retagging here and I hope we'll end up with a model where raw pointers don't get retagged.
Custom MIR: Support aggregate expressions
Add support for tuple, array and ADT expressions in custom mir
r? `````@oli-obk````` or `````@tmiasko````` or `````@JakobDegen`````
Walk un-shifted nested `impl Trait` in trait when setting up default trait method assumptions
Fixes a double subtraction in some binder math in return-position `impl Trait` in trait handling code.
Fixes#109239
new solver: make all goal evaluation able to be automatically rerun
It is generally wrong to call `evaluate_goal` multiple times or `evaluate_goal` and `evaluate_all` for the same `QueryResult` without correctly handling rerunning the goals when inference makes progress. Not doing so will result in the assertion in `evaluate_goal` firing because rerunning the goal will lead to a more accurate `QueryResult`.
Currently there are lots of places that get this wrong and generally it is complex and error prone to handle correctly everywhere. This PR introduces a way to add goals to the `EvalCtxt` and then run all the added goals in a loop so that `evaluate_goal`/`evaluate_all` is not necessary to call manually.
There are a few complications for making everything work "right":
1. the `normalizes-to` hack that replaces the rhs with an unconstrained infer var requires special casing in the new `try_evaluate_added_goals` function similar to how `evaluate_goal`'s assertion special cases that hack.
2. `assemble_candidates_after_normalizing_self_ty`'s normalization step needs to be reran for each candidate otherwise the found candidates will potentially get a more accurate `QueryResult` when rerunning the projection/trait goal which can effect the `QueryResult` of the projection/trait goal.
This is implemented via `EvalCtxt::probe`'s closure's `EvalCtxt` inheriting the added goals of the `EvalCtxt` that `probe` is called on, allowing us to add goals in a probe, and then enter a nested probe for each candidate and evaluate added goals which include the normalization step's goals.
I made `make_canonical_response` evaluate added goals so that it will be hard to mess up the impl of the solver by forgetting to evaluate added goals. Right now the only way to mess this up would be to call `response_no_constraints` (which from the name is obviously weird).
The visibility of `evaluate_goal` means that it can be called from various `compute_x_goal` or candidate assembly functions, this is generally wrong and we should never call `evaluate_goal` manually, instead we should be calling `add_goal`/`add_goals`. This is solved by moving `evaluate_goal` `evaluate_canonical_goal` and `compute_goal` into `eval_ctxt`'s module and making them private so they cannot be called from elsewhere, forcing people to call `add_goal/s` and `evaluate_added_goals_and_make_canonical_resposne`/`try_evaluate_added_goals`
---
Other changes:
- removed the `&& false` that was introduced to the assertion in `evaluate_goal` in #108839
- remove a `!self.did_overflow()` requirement in `search_graph.is_empty()` which causes goals that overflow to ICE
- made `EvalCtxt::eq` take `&mut self` and add all the nested goals via `add_goals` instead of returning them as 99% of call sites just immediately called `EvalCtxt::add_goals` manually.
r? `````@lcnr`````
Split `execute_job` into `execute_job_incr` and `execute_job_non_incr`
`execute_job` was a bit large, so this splits it in 2. Performance was neutral locally, but this may affect bootstrap times.
migrate compiler, bootstrap and compiletest to windows-rs
This PR migrates the compiler, bootstrap, and compiletest to use [windows-rs](https://github.com/microsoft/windows-rs) instead of winapi-rs. windows-rs is the bindings crate provided by Microsoft, and is actively maintained compared to winapi-rs. Not all ecosystem crates have migrated over yet, so there will be a period of time where both crates are used.
windows-rs also provides some nice ergonomics over winapi-rs to convert return values to `Result`s (which found a case where we forgot to check the return value of `CreateFileW`).
Optimize dep node backtrace and ignore fatal errors
This attempts to optimize https://github.com/rust-lang/rust/pull/91742 while also passing through fatal errors.
r? `@cjgillot`
Only expect a GAT const param for `type_of` of GAT const arg
IDK why we were account for both `is_ty_or_const` instead of just for a const param, since we're computing the `type_of` a const param specifically.
Fixes#109300
Fix generics_of for impl's RPITIT synthesized associated type
The only useful commit is the last one.
This makes `generics_of` for the impl side RPITIT copy from the trait's associated type and avoid the fn on the impl side which was previously wrongly used.
This solution is better but we still need to fix resolution of the generated generics.
r? ``@compiler-errors``
fix ClashingExternDeclarations lint ICE
Fixes#109334
First "real" contribution, please let me know if I did something wrong.
As I understand it, it's OK if a `#[repr(transparent)]` type has no non-zero sized types (aka is a ZST itself) and the function should just return the type normally instead of panicking
r? `@Nilstrieb`
fix: fix ICE in `custom-test-frameworks` feature
Fixes#107454
Simple fix to emit error instead of ICEing. At some point, all the code in `tests.rs` should be refactored, there is a bit of duplication (this PR's code is repeated five times over lol).
r? `@Nilstrieb` (active on the linked issue?)
The name of NativeLib will be presented
Fixes#109144
I was working on a quick fix, but found change the name from `Option<Symbol>` to `Symbol` make life a little bit easier.
fix: don't suggest similar method when unstable
Fixes#109177
Don't display typo suggestions for unstable things, unless the feature flag is enabled.
AFAIK, there are two places this occurs:
- `rustc_resolve`: before type checking, effectively just `FnCtxt::Free`.
- `rustc_hir_typck`: during type checking, for `FnCtxt::Assoc(..)`s.
The linked issue is about the latter, obviously the issue is applicable to both.
r? `@estebank`
Add `useless_anonymous_reexport` lint
This is a follow-up of https://github.com/rust-lang/rust/pull/108936. We once again show all anonymous re-exports in rustdoc, however we also wanted to add a lint to let users know that it very likely doesn't have the effect they think it has.
Add note for mismatched types because of circular dependencies
If you have crate A with a dependency on crate B, and crate B with a dev-dependency on A, then you might see "mismatched types" errors on types that seem to be equal. This PR adds a note that explains that the types are different, because crate B is compiled twice, one time with `cfg(test)` and one time without.
I haven't found a good way to create circular dependencies in UI tests, so I abused the incremental tests instead. As a bonus, incremental tests support "cpass" now.
related to https://github.com/rust-lang/rust/issues/22750
Use `size_of_val` instead of manual calculation
Very minor thing that I happened to notice in passing, but it's both shorter and [means it gets `mul nsw`](https://rust.godbolt.org/z/Y9KxYETv5), so why not.
Fix generics mismatch errors for RPITITs on -Zlower-impl-trait-in-trait-to-assoc-ty
This PR stops reporting errors due to different count of generics on the new synthesized associated types for RPITITs. Those were already reported when we compare the function on the triat with the function on the impl.
r? ``@compiler-errors``
Tweak implementation of overflow checking assertions
Extract and reuse logic controlling behaviour of overflow checking assertions instead of duplicating it three times.
r? `@cjgillot`
resolve: Improve debug impls for `NameBinding`
Print at least the Some/None/Ok/Err status of the nested bindings if not the bindings themselves.
Noticed while reviewing https://github.com/rust-lang/rust/pull/108729.
Pass the right HIR back from `get_fn_decl`
Fixes#109232
Makes sure that the `fn_id: HirId` that we pass to `suggest_missing_return_type` matches up with the `fn_decl: hir::FnDecl` that we pass to it, so the late-bound vars that we fetch from the former match up with the types in the latter...
This HIR suggestion code really needs a big refactor. I've tried to do it in the past (a couple of attempts), but it's a super tangled mess. It really shouldn't be passing around things like `hir::Node` and just deal with `LocalDefId`s everywhere... Anyways, I'd rather fix this ICE, now.
Do not ICE for unexpected lifetime with ConstGeneric rib
Fixes#109143
r? ````@petrochenkov````
Combining this test with the previous test will affect the previous diagnostics, so I added a separate test case.
- only borrow the refcell once per loop
- avoid complex matches to reduce branch paths in the hot loop
- use a by-ref fast path that avoids mutations at the expense of having false negatives
Use index based drop loop for slices and arrays
Instead of building two kinds of drop pair loops, of which only one will be eventually used at runtime in a given monomorphization, always use index based loop.
Install projection from RPITIT to default trait method opaque correctly
1. For new lowering strategy `-Zlower-impl-trait-in-trait-to-assoc-ty`, install the correct default trait method projection predicates (RPITIT -> opaque). This makes default trait body tests pass!
2. Fix two WF-checking bugs -- first, we want to make sure that we're always looking for an opaque type in `check_return_position_impl_trait_in_trait_bounds`. That's because the RPITIT projections are normalized to opaques during wfcheck. Second, fix RPITIT's param-envs by not adding the projection predicates that we install on trait methods to make default RPITITs work -- I left a comment why.
3. Also, just a small drive-by for `rustc_on_unimplemented`. Not sure if it affects any tests, but can't hurt.
r? ````@spastorino,```` based off of #109140
Fix riscv64 fuchsia LLVM target name
Currently, riscv64gc-unknown-fuchsia (added in #108722) sets riscv64*gc*-unknown-fuchsia as the LLVM target.
1716932743/compiler/rustc_target/src/spec/riscv64gc_unknown_fuchsia.rs (L5)
However, riscv64*gc*-\* is not a valid LLVM target and causes the following error.
```console
$ rustc --print cfg --target riscv64gc-unknown-fuchsia
error: could not create LLVM TargetMachine for triple: riscv64gc-unknown-fuchsia: No available targets are compatible with triple "riscv64gc-unknown-fuchsia"
```
As with other RISC-V targets, the LLVM target should use riscv64-\*, not riscv64*gc*-\*.
1716932743/compiler/rustc_target/src/spec/riscv64gc_unknown_freebsd.rs (L5)1716932743/compiler/rustc_target/src/spec/riscv64gc_unknown_linux_gnu.rs (L5)
I confirmed that riscv64-unknown-fuchsia is recognized as a valid LLVM target by using custom targets.
```console
# create a custom target with `"llvm-target": "riscv64-unknown-fuchsia" from no-std riscv64gc target.
$ rustc --print target-spec-json -Z unstable-options --target riscv64gc-unknown-none-elf | grep -v is-builtin | sed 's/"llvm-target".*/"llvm-target": "riscv64-unknown-fuchsia",/' > riscv64gc-unknown-fuchsia.json
$ rustc --print cfg --target riscv64gc-unknown-fuchsia.json
debug_assertions
panic="abort"
target_abi=""
target_arch="riscv64"
target_endian="little"
target_env=""
target_feature="a"
target_feature="c"
target_feature="d"
target_feature="f"
target_feature="m"
...
$ cat riscv64gc-unknown-fuchsia.json
{
"arch": "riscv64",
"code-model": "medium",
"cpu": "generic-rv64",
"data-layout": "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128",
"eh-frame-header": false,
"emit-debug-gdb-scripts": false,
"features": "+m,+a,+f,+d,+c",
"linker": "rust-lld",
"linker-flavor": "ld.lld",
"llvm-abiname": "lp64d",
"llvm-target": "riscv64-unknown-fuchsia",
"max-atomic-width": 64,
"panic-strategy": "abort",
"relocation-model": "static",
"supported-sanitizers": [
"kernel-address"
],
"target-pointer-width": "64"
}
# Check the current master's LLVM target name causes an error
$ sed -i 's/riscv64-unknown-fuchsia/riscv64gc-unknown-fuchsia/' riscv64gc-unknown-fuchsia.json
$ rustc --print cfg --target riscv64gc-unknown-fuchsia.json
error: could not create LLVM TargetMachine for triple: riscv64gc-unknown-fuchsia: No available targets are compatible with triple "riscv64gc-unknown-fuchsia"
```
r? ````@tmandry````
Remove box expressions from HIR
After #108516, `#[rustc_box]` is used at HIR->THIR lowering and this is no longer emitted, so it can be removed.
This is based on top of #108471 to help with conflicts, so 43490488ccacd1a822e9c621f5ed6fca99959a0b is the only relevant commit (sorry for all the duplicated pings!)
````@rustbot```` label +S-blocked
Wrap the whole LocalInfo in ClearCrossCrate.
MIR contains a lot of information about locals. The primary purpose of this information is the quality of borrowck diagnostics.
This PR aims to drop this information after MIR analyses are finished, ie. starting from post-cleanup runtime MIR.
In cases where it is legal, we should prefer poison values over
undef values.
This replaces undef with poison for aggregate construction and
for uninhabited types. There are more places where we can likely
use poison, but I wanted to stay conservative to start with.
In particular the aggregate case is important for newer LLVM
versions, which are not able to handle an undef base value during
early optimization due to poison-propagation concerns.
Flatten/inline format_args!() and (string and int) literal arguments into format_args!()
Implements https://github.com/rust-lang/rust/issues/78356
Gated behind `-Zflatten-format-args=yes`.
Part of #99012
This change inlines string literals, integer literals and nested format_args!() into format_args!() during ast lowering, making all of the following pairs result in equivalent hir:
```rust
println!("Hello, {}!", "World");
println!("Hello, World!");
```
```rust
println!("[info] {}", format_args!("error"));
println!("[info] error");
```
```rust
println!("[{}] {}", status, format_args!("error: {}", msg));
println!("[{}] error: {}", status, msg);
```
```rust
println!("{} + {} = {}", 1, 2, 1 + 2);
println!("1 + 2 = {}", 1 + 2);
```
And so on.
This is useful for macros. E.g. a `log::info!()` macro could just pass the tokens from the user directly into a `format_args!()` that gets efficiently flattened/inlined into a `format_args!("info: {}")`.
It also means that `dbg!(x)` will have its file, line, and expression name inlined:
```rust
eprintln!("[{}:{}] {} = {:#?}", file!(), line!(), stringify!(x), x); // before
eprintln!("[example.rs:1] x = {:#?}", x); // after
```
Which can be nice in some cases, but also means a lot more unique static strings than before if dbg!() is used a lot.
Some cleanups in our normalization logic
Changed a match to be exhaustive and deduplicated some code.
r? ```@compiler-errors```
this pulls out the uncontroversial part of https://github.com/rust-lang/rust/pull/108860
make `define_opaque_types` fully explicit
based on the idea of #108389. Moved `define_opaque_types` into the actual operations, e.g. `eq`, instead of `infcx.at` because normalization doesn't use `define_opaque_types` and even creates it's own `At` with a different `define_opaque_types` internally.
Somewhat surprisingly, coherence actually relies on `DefineOpaqueTypes::Yes` for soundness which was revealed because I've incorrectly used `DefineOpaqueTypes::No` in `equate_impl_headers`. It feels concerning that even though this is the case, we still sometimes use `DefineOpaqueTypes::No` in coherence. I did not look into this as part of this PR as it is purely changing the structure of the code without changing behavior in any way.
r? ```@oli-obk```
error-msg: impl better suggestion for `E0532`
Fixes#106862
No test as there is already a test which is nearly identical to the example in the linked issue.
Revert #107376 to fix potential `bincode` breakage and `rustc-perf` benchmark.
#107376 caused `rustc-perf`'s `webrender` benchmark to break, by regressing on the `bincode-1.3.3` crate.
~~This PR is a draft revert in case we can't land a fix soon enough, and we'd like to land the revert instead~~
(Though I myself think it'd be safer to do the revert, and run crater when relanding #107376.)
cc `@aliemjay`
Implement checked Shl/Shr at MIR building.
This does not require any special handling by codegen backends,
as the overflow behaviour is entirely determined by the rhs (shift amount).
This allows MIR ConstProp to remove the overflow check for constant shifts.
~There is an existing different behaviour between cg_llvm and cg_clif (cc `@bjorn3).`
I took cg_llvm's one as reference: overflow if `rhs < 0 || rhs > number_of_bits_in_lhs_ty`.~
EDIT: `cg_llvm` and `cg_clif` implement the overflow check differently. This PR uses `cg_llvm`'s implementation based on a `BitAnd` instead of `cg_clif`'s one based on an unsigned comparison.
Sync rustc_codegen_cranelift
Bunch of bug fixes this time. Also an update to Cranelift 0.93 which adds a brand new optimization pass which cg_clif exposes when using `--release`. And various improvements to cg_clif's test suite, making it faster to run. And finally two small perf improvements.
r? `@ghost`
`@rustbot` label +A-codegen +A-cranelift +T-compiler
Rollup of 7 pull requests
Successful merges:
- #108991 (add `enable-warnings` flag for llvm, and disable it by default.)
- #109109 (Use `unused_generic_params` from crate metadata)
- #109111 (Create dirs for build_triple)
- #109136 (Simplify proc macro signature validity check)
- #109150 (Update cargo)
- #109154 (Fix MappingToUnit to support no span of arg_ty)
- #109157 (Remove mw from review rotation for a while)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Simplify proc macro signature validity check
Use an `ObligationCtxt` instead of `normalize_erasing_regions` + `DeepRejectCtxt`. This should both give us a more accurate error message, and also avoid issues like not-well-formed proc macro signatures. Also, let's fall back on the regular type mismatch error reporting for making these diagnostic notes, instead of hard-coding a bunch of specific diagnostics.
Fixes#109129
Use `unused_generic_params` from crate metadata
Due to the way that `separate_provide_extern` interacted with the implementation of `<ty::InstanceDef<'tcx> as Key>::query_crate_is_local`, we actually never hit the foreign provider for `unused_generic_params`.
Additionally, since the *local* provider of `unused_generic_params` calls `should_polymorphize`, which always returns false if the def-id is foreign, this means that we never actually polymorphize monomorphic instances originating from foreign crates.
We don't actually encode `unused_generic_params` for items where all generics are used, so I had to tweak the foreign provider to fall back to `ty::UnusedGenericParams::new_all_used()` to avoid more ICEs when the above bugs were fixed.
Ensure `ptr::read` gets all the same LLVM `load` metadata that dereferencing does
I was looking into `array::IntoIter` optimization, and noticed that it wasn't annotating the loads with `noundef` for simple things like `array::IntoIter<i32, N>`. Trying to narrow it down, it seems that was because `MaybeUninit::assume_init_read` isn't marking the load as initialized (<https://rust.godbolt.org/z/Mxd8TPTnv>), which is unfortunate since that's basically its reason to exist.
The root cause is that `ptr::read` is currently implemented via the *untyped* `copy_nonoverlapping`, and thus the `load` doesn't get any type-aware metadata: no `noundef`, no `!range`. This PR solves that by lowering `ptr::read(p)` to `copy *p` in MIR, for which the backends already do the right thing.
Fortuitiously, this also improves the IR we give to LLVM for things like `mem::replace`, and fixes a couple of long-standing bugs where `ptr::read` on `Copy` types was worse than `*`ing them.
Zulip conversation: <https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Move.20array.3A.3AIntoIter.20to.20ManuallyDrop/near/341189936>
cc `@erikdesjardins` `@JakobDegen` `@workingjubilee` `@the8472`
Fixes#106369Fixes#73258
Instead of building two kinds of drop pair loops, of which only one will
be eventually used at runtime in a given monomorphization, always use
index based loop.
Rollup of 9 pull requests
Successful merges:
- #108722 (Support for Fuchsia RISC-V target)
- #108880 (Remove tests/ui/impl-trait/in-trait/new-lowering-strategy in favor of using revisions on existing tests)
- #108909 (Fix object safety checks for new RPITITs)
- #108915 (Remove some direct calls to local_def_id_to_hir_id on diagnostics)
- #108923 (Make fns from other crates with RPITIT work for -Zlower-impl-trait-in-trait-to-assoc-ty)
- #109101 (Fall back to old metadata computation when type references errors)
- #109105 (Don't ICE for late-bound consts across `AnonConstBoundary`)
- #109110 (Don't codegen impossible to satisfy impls)
- #109116 (Emit diagnostic when calling methods on the unit type in method chains)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Emit diagnostic when calling methods on the unit type in method chains
Fixes#104204.
What this PR does: If a method is not found somewhere in a call chain, we check if we called earlier a method with signature `(&mut T, ...) -> ()`. If this is the case then we emit a diagnostic message.
For example given input:
```
vec![1, 2, 3].into_iter().collect::<Vec<i32>>().sort_by_key(|i| i).sort();
```
the current output is:
```
error[E0599]: no method named `sort` found for unit type `()` in the current scope
--> hello.rs:3:72
|
3 | vec![1, 2, 3].into_iter().collect::<Vec<i32>>().sort_by_key(|i| i).sort();
| ^^^^ method not found in `()`
```
after this PR it will be:
```
error[E0599]: no method named `sort` found for unit type `()` in the current scope
--> ./hello.rs:3:72
|
3 | vec![1, 2, 3].into_iter().collect::<Vec<i32>>().sort_by_key(|i| i).sort();
| ^^^^ method not found in `()`
|
note: method `sort_by_key` modifies its receiver in-place, it is not meant to be used in method chains.
--> ./hello.rs:3:53
|
3 | vec![1, 2, 3].into_iter().collect::<Vec<i32>>().sort_by_key(|i| i).sort();
| ^^^^^^^^^^^ this call modifies its receiver in-place
```
Fall back to old metadata computation when type references errors
Projection is a bit too aggressive normalizing `<dyn Trait<[type error]> as Pointee>::Metadata` to `[type error]`, rather than to `DynMetadata<..>`. Side-step that by just falling back to the old structural metadata computation.
Fixes#109078
Make fns from other crates with RPITIT work for -Zlower-impl-trait-in-trait-to-assoc-ty
Only the last two commits are meaningful.
r? `@compiler-errors`
Remove some direct calls to local_def_id_to_hir_id on diagnostics
Was playing with `tests/ui/impl-trait/in-trait/default-body-with-rpit.rs` and was able to remove some ICEs. Still getting ...
```
error[E0277]: `impl Future<Output = Foo::{opaque#0}>` is not a future
--> tests/ui/impl-trait/in-trait/default-body-with-rpit.rs:10:28
|
10 | async fn baz(&self) -> impl Debug {
| ^^^^^^^^^^ `impl Future<Output = Foo::{opaque#0}>` is not a future
|
= help: the trait `Future` is not implemented for `impl Future<Output = Foo::{opaque#0}>`
= note: impl Future<Output = Foo::{opaque#0}> must be a future or must implement `IntoFuture` to be awaited
note: required by a bound in `Foo::{opaque#1}`
--> tests/ui/impl-trait/in-trait/default-body-with-rpit.rs:10:28
|
10 | async fn baz(&self) -> impl Debug {
| ^^^^^^^^^^ required by this bound in `Foo::{opaque#1}`
error[E0277]: the size for values of type `impl Future<Output = Foo::{opaque#0}>` cannot be known at compilation time
--> tests/ui/impl-trait/in-trait/default-body-with-rpit.rs:10:28
|
10 | async fn baz(&self) -> impl Debug {
| ^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `impl Future<Output = Foo::{opaque#0}>`
note: required by a bound in `Foo::{opaque#1}`
--> tests/ui/impl-trait/in-trait/default-body-with-rpit.rs:10:28
|
10 | async fn baz(&self) -> impl Debug {
| ^^^^^^^^^^ required by this bound in `Foo::{opaque#1}`
error: internal compiler error: compiler/rustc_hir_typeck/src/closure.rs:724:18: async fn generator return type not an inference variable: Foo::{opaque#1}<'_>
--> tests/ui/impl-trait/in-trait/default-body-with-rpit.rs:10:39
|
10 | async fn baz(&self) -> impl Debug {
| _______________________________________^
11 | | ""
12 | | }
| |_____^
```
But I guess this is a little bit of progress anyway.
This one goes on top of #108700 and #108945
r? `@compiler-errors`
Support for Fuchsia RISC-V target
Fuchsia is in the process of implementing the RISC-V support. This change implements the minimal Rust compiler support. The support for building runtime libraries will be implemented in follow up changes once Fuchsia SDK has the RISC-V support.
If no method is found when checking method call, we check if we called a method with signature (&mut T, ...) -> (). If this is the case then we emit a diagnostic message
Properly allow macro expanded `format_args` invocations to uses captures
Originally, this was kinda half-allowed. There were some primitive checks in place that looked at the span to see whether the input was likely a literal. These "source literal" checks are needed because the spans created during `format_args` parsing only make sense when it is indeed a literal that was written in the source code directly.
This is orthogonal to the restriction that the first argument must be a "direct literal", not being exanpanded from macros. This restriction was imposed by [RFC 2795] on the basis of being too confusing. But this was only concerned with the argument of the invocation being a literal, not whether it was a source literal (maybe in spirit it meant it being a source literal, this is not clear to me).
Since the original check only really cared about source literals (which is good enough to deny the `format_args!(concat!())` example), macros expanding to `format_args` invocations were able to use implicit captures if they spanned the string in a way that lead back to a source string.
The "source literal" checks were not strict enough and caused ICEs in certain cases (see #106191). So I tightened it up in #106195 to really only work if it's a direct source literal.
This caused the `indoc` crate to break. `indoc` transformed the source literal by removing whitespace, which made it not a "source literal" anymore (which is required to fix the ICE). But since `indoc` spanned the literal in ways that made the old check think that it's a literal, it was able to use implicit captures (which is useful and nice for the users of `indoc`).
This commit properly seperates the previously introduced concepts of "source literal" and "direct literal" and therefore allows `indoc` invocations, which don't create "source literals" to use implicit captures again.
Fixes#106191
[RFC 2795]: https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html#macro-hygiene
Sometimes, we want to create subspans and point at code in the literal
if possible. But this doesn't always make sense, sometimes the literal
may come from macro expanded code and isn't actually there in the
source. Then, we can't really make these suggestions.
This now makes sure that the literal is actually there as we see it so
that we will not run into ICEs on weird literal transformations.
Originally, this was kinda half-allowed. There were some primitive
checks in place that looked at the span to see whether the input was
likely a literal. These "source literal" checks are needed because the
spans created during `format_args` parsing only make sense when it is
indeed a literal that was written in the source code directly.
This is orthogonal to the restriction that the first argument must be a
"direct literal", not being exanpanded from macros. This restriction was
imposed by [RFC 2795] on the basis of being too confusing. But this was
only concerned with the argument of the invocation being a literal, not
whether it was a source literal (maybe in spirit it meant it being a
source literal, this is not clear to me).
Since the original check only really cared about source literals (which
is good enough to deny the `format_args!(concat!())` example), macros
expanding to `format_args` invocations were able to use implicit
captures if they spanned the string in a way that lead back to a source
string.
The "source literal" checks were not strict enough and caused ICEs in
certain cases (see # 106191 (the space is intended to avoid spammy
backreferences)). So I tightened it up in # 106195 to really only work
if it's a direct source literal.
This caused the `indoc` crate to break. `indoc` transformed the source
literal by removing whitespace, which made it not a "source literal"
anymore (which is required to fix the ICE). But since `indoc` spanned
the literal in ways that made the old check think that it's a literal,
it was able to use implicit captures (which is useful and nice for the
users of `indoc`).
This commit properly seperates the previously introduced concepts of
"source literal" and "direct literal" and therefore allows `indoc`
invocations, which don't create "source literals" to use implicit
captures again.
[RFC 2795]: https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html#macro-hygiene
Remove `identity_future` indirection
This was previously needed because the indirection used to hide some unexplained lifetime errors, which it turned out were related to the `min_choice` algorithm.
Removing the indirection also solves a couple of cycle errors, large moves and makes async blocks support the `#[track_caller]`annotation.
Fixes https://github.com/rust-lang/rust/issues/104826.
Gracefully handle `#[target_feature]` on statics
The was careful around not calling `fn_sig` on not-functions but well, it wasn't careful enough. This commit makes it a little more careful and also adds tests for a bunch more item kinds.
I was sadly not able to fully bless the test locally because I'm on an aarch64 machine but I hope some manual editing made it work 😅Fix#109079
The was careful around not calling `fn_sig` on not-functions but well,
it wasn't careful enough. This commit makes it a little more careful and
also adds tests for a bunch more item kinds.
Remove `box_syntax`
r? `@Nilstrieb`
This removes the feature `box_syntax`, which allows the use of `box <expr>` to create a Box, and finalises removing use of the feature from the compiler. `box_patterns` (allowing the use of `box <pat>` in a pattern) is unaffected.
It also removes `ast::ExprKind::Box` - the only way to create a 'box' expression now is with the rustc-internal `#[rustc_box]` attribute.
As a temporary measure to help users move away, `box <expr>` now parses the inner expression, and emits a `MachineApplicable` lint to replace it with `Box::new`
Closes#49733
Strengthen state tracking in const-prop
Some/many of the changes are replicated between both the const-prop lint and the const-prop optimization.
Behaviour changes:
- const-prop opt does not give a span to propagated values. This was useless as that span's primary purpose is to diagnose evaluation failure in codegen.
- we remove the `OnlyPropagateInto` mode. It was only used for function arguments, which are better modeled by a write before entry.
- the tracking of assignments and discriminants make clearer that we do nothing in `NoPropagation` mode or on indirect places.
Rollup of 8 pull requests
Successful merges:
- #108651 (Forbid the use of `#[target_feature]` on `main`)
- #109009 (rustdoc: use restricted Damerau-Levenshtein distance for search)
- #109026 (Introduce `Rc::into_inner`, as a parallel to `Arc::into_inner`)
- #109029 (Gate usages of `dyn*` and const closures in macros)
- #109031 (Rename `config.toml.example` to `config.example.toml`)
- #109032 (Use `TyCtxt::trait_solver_next` in some places)
- #109047 (typo)
- #109052 (Add eslint check for rustdoc-gui tester)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Gate usages of `dyn*` and const closures in macros
We silently accepted `dyn*` and const closures in macros as long as they didn't expand to anything containing these experimental features, unlike other gated features such as `for<'a>` binders on closures, etc. Let's not do that, to make sure nobody begins relying on this.
Check that a query has not completed and is not executing before starting it
This fixes a race in the query system where we only checked if the query was currently executing, but not if it was already completed, causing queries to re-execute.
r? `@cjgillot`
Ensure value is on the on-disk cache before returning from `ensure()`.
The current logic for `ensure()` a query just checks that the node is green in the dependency graph.
However, a lot of places use `ensure()` to prevent the query from being called later. This is the case before stealing a query result.
If the query is actually green but the value is not available in the on-disk cache, `ensure` would return, but a subsequent call to the full query would run the code, and attempt to read from a stolen value.
This PR conforms the query system to the usage by checking whether the queried value is loadable from disk before returning.
Sadly, I can't manage to craft a proper test...
Should fix all instances of "attempted to read from stolen value".