Only use implied bounds hack if bevy, and use deeply normalize in implied bounds hack
Consolidates the implied bounds computation mode into a single function, which deeply normalizes, and if it's in **compat** mode (for bevy), it extracts outlives bounds from the infcx.
Previously, we were using the implied bounds compat mode in two cases:
1. During WF, if it detects `ParamSet`
2. EVERYWHERE ELSE (lol) -- e.g. borrowck, predicate entailment, etc.
While I think this is fine, and the net effect was just that we emitted fewer diagnostics, it makes me uncomfortable that all crates were using the supposed "compat" code.
Fixes#137767
mgca: Lower all const paths as `ConstArgKind::Path`
When `#![feature(min_generic_const_args)]` is enabled, we now lower all
const paths in generic arg position to `hir::ConstArgKind::Path`. We
then lower assoc const paths to `ty::ConstKind::Unevaluated` since we
can no longer use the anon const expression lowering machinery. In the
process of implementing this, I factored out `hir_ty_lowering` code that
is now shared between lowering assoc types and assoc consts.
This PR also introduces a `#[type_const]` attribute for trait assoc
consts that are allowed as const args. However, we still need to
implement code to check that assoc const definitions satisfy
`#[type_const]` if present (basically is it a const path or a
monomorphic anon const).
r? `@BoxyUwU`
When `#![feature(min_generic_const_args)]` is enabled, we now lower all
const paths in generic arg position to `hir::ConstArgKind::Path`. We
then lower assoc const paths to `ty::ConstKind::Unevaluated` since we
can no longer use the anon const expression lowering machinery. In the
process of implementing this, I factored out `hir_ty_lowering` code that
is now shared between lowering assoc types and assoc consts.
This PR also introduces a `#[type_const]` attribute for trait assoc
consts that are allowed as const args. However, we still need to
implement code to check that assoc const definitions satisfy
`#[type_const]` if present (basically is it a const path or a
monomorphic anon const).
Update query normalizer docs to not position it as the greatest pioneer in the space of normalization
I don't think its true that we intend to replace all normalization with the query normalizer- its more likely that once the new solver is stable we can replace the query normalizer with normal normalization calls as the new solver caches much more than the old solver
r? ``@compiler-errors``
Remove `ParamEnv::without_caller_bounds`
This doesn't really do anything that `ParamEnv::empty` doesn't do nowadays as `ParamEnv` *only* stores caller bounds since other information has been moved out into `TypingMode`
r? ```@compiler-errors``` ```@lcnr```
Introduce `feature(generic_const_parameter_types)`
Allows to define const generic parameters whose type depends on other generic parameters, e.g. `Foo<const N: usize, const ARR: [u8; N]>;`
Wasn't going to implement for this for a while until we could implement it with `bad_inference.rs` resolved but apparently the project simd folks would like to be able to use this for some intrinsics and the inference issue isn't really a huge problem there aiui. (cc ``@workingjubilee`` )
Use `Binder<Vec<Ty>>` instead of `Vec<Binder<Ty>>` in both solvers for sized/auto traits/etc.
It's more conceptually justified IMO, especially when binders get implications.
r? lcnr
Don't suggest constraining unstable associated types
Fixes#137624
This could be made a bit more specific, considering the local crate's stability or nightly status or something, but I think in general we should not be suggesting associated type bounds on unstable associated items.
Teach structured errors to display short `Ty<'_>`
Make it so that in every structured error annotated with `#[derive(Diagnostic)]` that has a field of type `Ty<'_>`, the printing of that value into a `String` will look at the thread-local storage `TyCtxt` in order to shorten to a length appropriate with the terminal width. When this happen, the resulting error will have a note with the file where the full type name was written to.
```
error[E0618]: expected function, found `((..., ..., ..., ...), ..., ..., ...)``
--> long.rs:7:5
|
6 | fn foo(x: D) { //~ `x` has type `(...
| - `x` has type `((..., ..., ..., ...), ..., ..., ...)`
7 | x(); //~ ERROR expected function, found `(...
| ^--
| |
| call expression requires function
|
= note: the full name for the type has been written to 'long.long-type-14182675702747116984.txt'
= note: consider using `--verbose` to print the full type name to the console
```
Follow up to and response to the comments on #136898.
r? ``@oli-obk``
Make it so that every structured error annotated with `#[derive(Diagnostic)]` that has a field of type `Ty<'_>`, the printing of that value into a `String` will look at the thread-local storage `TyCtxt` in order to shorten to a length appropriate with the terminal width. When this happen, the resulting error will have a note with the file where the full type name was written to.
```
error[E0618]: expected function, found `((..., ..., ..., ...), ..., ..., ...)``
--> long.rs:7:5
|
6 | fn foo(x: D) { //~ `x` has type `(...
| - `x` has type `((..., ..., ..., ...), ..., ..., ...)`
7 | x(); //~ ERROR expected function, found `(...
| ^--
| |
| call expression requires function
|
= note: the full name for the type has been written to 'long.long-type-14182675702747116984.txt'
= note: consider using `--verbose` to print the full type name to the console
```
In the standard library, the `Extend` impl for `Iterator` (specialised
with `TrustedLen`) has a parameter which is constrained by a projection
predicate. This projection predicate provides a value for an inference
variable but host effect evaluation wasn't resolving variables first.
Adding the extra resolve can the number of errors in some tests when they
gain host effect predicates, but this is not unexpected as calls to
`resolve_vars_if_possible` can cause more error tainting to happen.
Co-authored-by: Boxy <rust@boxyuwu.dev>
Use `edition = "2024"` in the compiler (redux)
Most of this is binding mode changes, which I fixed by running `x.py fix`.
Also adds some miscellaneous `unsafe` blocks for new unsafe standard library functions (the setenv ones), and a missing `unsafe extern` block in some enzyme codegen code, and fixes some precise capturing lifetime changes (but only when they led to errors).
cc ``@ehuss`` ``@traviscross``
Prune dead regionck code
We never encounter `ObligationCauseCode`s that correspond to region obligations that originate from "within" a body, since we don't do HIR regionck anymore on bodies. So prune some dead code.
Tweak E0277 when predicate comes indirectly from ?
When a `?` operation requires an `Into` conversion with additional bounds (like having a concrete error but wanting to convert to a trait object), we handle it speficically and provide the same kind of information we give other `?` related errors.
```
error[E0277]: `?` couldn't convert the error: `E: std::error::Error` is not satisfied
--> $DIR/bad-question-mark-on-trait-object.rs:7:13
|
LL | fn foo() -> Result<(), Box<dyn std::error::Error>> {
| -------------------------------------- required `E: std::error::Error` because of this
LL | Ok(bar()?)
| -----^ the trait `std::error::Error` is not implemented for `E`
| |
| this has type `Result<_, E>`
|
note: `E` needs to implement `std::error::Error`
--> $DIR/bad-question-mark-on-trait-object.rs:1:1
|
LL | struct E;
| ^^^^^^^^
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= note: required for `Box<dyn std::error::Error>` to implement `From<E>`
```
Avoid talking about `FromResidual` when other more relevant information is being given, particularly from `rust_on_unimplemented`.
Fix#137238.
-----
CC #137232, which was a smaller step related to this.
```
error[E0277]: `?` couldn't convert the error: `E: std::error::Error` is not satisfied
--> $DIR/bad-question-mark-on-trait-object.rs:7:13
|
LL | fn foo() -> Result<(), Box<dyn std::error::Error>> {
| -------------------------------------- required `E: std::error::Error` because of this
LL | Ok(bar()?)
| -----^ the trait `std::error::Error` is not implemented for `E`
| |
| this has type `Result<_, E>`
|
note: `E` needs to implement `std::error::Error`
--> $DIR/bad-question-mark-on-trait-object.rs:1:1
|
LL | struct E;
| ^^^^^^^^
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= note: required for `Box<dyn std::error::Error>` to implement `From<E>`
error[E0277]: `?` couldn't convert the error to `X`
--> $DIR/bad-question-mark-on-trait-object.rs:18:13
|
LL | fn bat() -> Result<(), X> {
| ------------- expected `X` because of this
LL | Ok(bar()?)
| -----^ the trait `From<E>` is not implemented for `X`
| |
| this can't be annotated with `?` because it has type `Result<_, E>`
|
note: `X` needs to implement `From<E>`
--> $DIR/bad-question-mark-on-trait-object.rs:4:1
|
LL | struct X;
| ^^^^^^^^
note: alternatively, `E` needs to implement `Into<X>`
--> $DIR/bad-question-mark-on-trait-object.rs:1:1
|
LL | struct E;
| ^^^^^^^^
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
```
When a `?` operation requires an `Into` conversion with additional bounds (like having a concrete error but wanting to convert to a trait object), we handle it speficically and provide the same kind of information we give other `?` related errors.
```
error[E0277]: `?` couldn't convert the error: `E: std::error::Error` is not satisfied
--> $DIR/bad-question-mark-on-trait-object.rs:5:13
|
LL | fn foo() -> Result<(), Box<dyn std::error::Error>> {
| -------------------------------------- required `E: std::error::Error` because of this
LL | Ok(bar()?)
| ^ the trait `std::error::Error` is not implemented for `E`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= note: required for `Box<dyn std::error::Error>` to implement `From<E>`
```
Avoid talking about `FromResidual` when other more relevant information is being given, particularly from `rust_on_unimplemented`.
Register `USAGE_OF_TYPE_IR_INHERENT`, remove inherent usages
I implemented a lint to discourage the usage of `rustc_type_ir::inherent` but never actually enabled it. People started using `rustc_type_ir::inherent` methods through globs, lol.
r? fmease or reassign as you please
Make fewer crates depend on `rustc_ast_ir`
I think it simplifies the crate graph and also exposes people less to confusion if downstream crates don't interact with `rustc_ast_ir` directly and instead just use its functionality reexported through more familiar paths.
r? oli-obk since you introduced ast-ir
Don't mention `FromResidual` on bad `?`
Unless `try_trait_v2` is enabled, don't mention that `FromResidual` isn't implemented for a specific type when the implicit `From` conversion of a `?` fails. For the end user on stable, `?` might as well be a compiler intrinsic, so we remove that note to avoid further confusion and allowing other parts of the error to be more prominent.
```
error[E0277]: `?` couldn't convert the error to `u8`
--> $DIR/bad-interconversion.rs:4:20
|
LL | fn result_to_result() -> Result<u64, u8> {
| --------------- expected `u8` because of this
LL | Ok(Err(123_i32)?)
| ------------^ the trait `From<i32>` is not implemented for `u8`
| |
| this can't be annotated with `?` because it has type `Result<_, i32>`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= help: the following other types implement trait `From<T>`:
`u8` implements `From<Char>`
`u8` implements `From<bool>`
```
Emit dropck normalization errors in borrowck
Borrowck generally assumes that any queries it runs for type checking will succeed, thinking that HIR typeck will have errored first if there was a problem. However as of #98641, dropck isn't run on HIR, so there's no direct guarantee that it doesn't error. While a type being well-formed might be expected to ensure that its fields are well-formed, this is not the case for types containing a type projection:
```rust
pub trait AuthUser {
type Id;
}
pub trait AuthnBackend {
type User: AuthUser;
}
pub struct AuthSession<Backend: AuthnBackend> {
data: Option<<<Backend as AuthnBackend>::User as AuthUser>::Id>,
}
pub trait Authz: Sized {
type AuthnBackend: AuthnBackend<User = Self>;
}
pub fn run_query<User: Authz>(auth: AuthSession<User::AuthnBackend>) {}
// ^ No User: AuthUser bound is required or inferred.
```
While improvements to trait solving might fix this in the future, for now we go for a pragmatic solution of emitting an error from borrowck (by rerunning dropck outside of a query) and making drop elaboration check if an error has been emitted previously before panicking for a failed normalization.
Closes#103899Closes#135039
r? `@compiler-errors` (feel free to re-assign)
Unless `try_trait_v2` is enabled, don't mention that `FromResidual` isn't implemented for a specific type when the implicit `From` conversion of a `?` fails. For the end user on stable, `?` might as well be a compiler intrinsic, so we remove that note to avoid further confusion and allowing other parts of the error to be more prominent.
```
error[E0277]: `?` couldn't convert the error to `u8`
--> $DIR/bad-interconversion.rs:4:20
|
LL | fn result_to_result() -> Result<u64, u8> {
| --------------- expected `u8` because of this
LL | Ok(Err(123_i32)?)
| ------------^ the trait `From<i32>` is not implemented for `u8`
| |
| this can't be annotated with `?` because it has type `Result<_, i32>`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= help: the following other types implement trait `From<T>`:
`u8` implements `From<Char>`
`u8` implements `From<bool>`
```
Continuing the work started in #136466.
Every method gains a `hir_` prefix, though for the ones that already
have a `par_` or `try_par_` prefix I added the `hir_` after that.
HIR type checking no longer runs dropck, so we may get new errors when
we run it in borrowck. If this happens then rerun the query in a local
infcx and report errors for it.
First of all, note that `Map` has three different relevant meanings.
- The `intravisit::Map` trait.
- The `map::Map` struct.
- The `NestedFilter::Map` associated type.
The `intravisit::Map` trait is impl'd twice.
- For `!`, where the methods are all unreachable.
- For `map::Map`, which gets HIR stuff from the `TyCtxt`.
As part of getting rid of `map::Map`, this commit changes `impl
intravisit::Map for map::Map` to `impl intravisit::Map for TyCtxt`. It's
fairly straightforward except various things are renamed, because the
existing names would no longer have made sense.
- `trait intravisit::Map` becomes `trait intravisit::HirTyCtxt`, so named
because it gets some HIR stuff from a `TyCtxt`.
- `NestedFilter::Map` assoc type becomes `NestedFilter::MaybeTyCtxt`,
because it's always `!` or `TyCtxt`.
- `Visitor::nested_visit_map` becomes `Visitor::maybe_tcx`.
I deliberately made the new trait and associated type names different to
avoid the old `type Map: Map` situation, which I found confusing. We now
have `type MaybeTyCtxt: HirTyCtxt`.
The end goal is to eliminate `Map` altogether.
I added a `hir_` prefix to all of them, that seemed simplest. The
exceptions are `module_items` which became `hir_module_free_items` because
there was already a `hir_module_items`, and `items` which became
`hir_free_items` for consistency with `hir_module_free_items`.
Rollup of 8 pull requests
Successful merges:
- #135549 (Document some safety constraints and use more safe wrappers)
- #135965 (In "specify type" suggestion, skip type params that are already known)
- #136193 (Implement pattern type ffi checks)
- #136646 (Add a TyPat in the AST to reuse the generic arg lowering logic)
- #136874 (Change the issue number for `likely_unlikely` and `cold_path`)
- #136884 (Lower fn items as ZST valtrees and delay a bug)
- #136885 (i686-linux-android: increase CPU baseline to Pentium 4 (without an actual change)
- #136891 (Check sig for errors before checking for unconstrained anonymous lifetime)
r? `@ghost`
`@rustbot` modify labels: rollup
In "specify type" suggestion, skip type params that are already known
When we suggest specifying a type for an expression or pattern, like in a `let` binding, we previously would print the entire type as the type system knew it. We now look at the params that have *no* inference variables, so they are fully known to the type system which means that they don't need to be specified.
This helps in suggestions for types that are really long, because we can usually skip most of the type params and make the annotation as short as possible:
```
error[E0282]: type annotations needed for `Result<_, ((..., ..., ..., ...), ..., ..., ...)>`
--> $DIR/really-long-type-in-let-binding-without-sufficient-type-info.rs:7:9
|
LL | let y = Err(x);
| ^ ------ type must be known at this point
|
help: consider giving `y` an explicit type, where the type for type parameter `T` is specified
|
LL | let y: Result<T, _> = Err(x);
| ++++++++++++++
```
Fix#135919.
Prevent generic pattern types from being used in libstd
Pattern types should follow the same rules that patterns follow. So a pattern type range must not wrap and not be empty. While we reject such invalid ranges at layout computation time, that only happens during monomorphization in the case of const generics. This is the exact same issue as other const generic math has, and since there's no solution there yet, I put these pattern types behind a separate incomplete feature.
These are not necessary for the pattern types MVP (replacing the layout range attributes in libcore and rustc).
cc #136574 (new tracking issue for the `generic_pattern_types` feature gate)
r? ``@lcnr``
cc ``@scottmcm`` ``@joshtriplett``
Ensure that we never try to monomorphize the upcasting or vtable calls of impossible dyn types
Check for impossible obligations in the `dyn Trait` type we're trying to compute its the vtable upcasting and method call slots.
r? lcnr
Remove unnecessary layout assertions for object-safe receivers
The soundness of `DispatchFromDyn` relies on the fact that, like all other built-in marker-like layout traits (e.g. `Sized`, `CoerceUnsized`), the guarantees that they enforce in *generic* code via traits will result in assumptions that we can rely on in codegen.
Specifically, `DispatchFromDyn` ensures that we end up with a receiver that is a valid pointer type, and its implementation validity recursively ensures that the ABI of that pointer type upholds the `Scalar` or `ScalarPair` representation for sized and unsized pointees, respectively.
The check that this layout guarantee holds for arbitrary, possibly generic receiver types that also may exist in possibly impossible-to-instantiate where clauses is overkill IMO, and leads to several ICEs due to the fact that computing layouts before monomorphization is going to be fallible at best.
This PR removes the check altogether, since it just exists as a sanity check from very long ago, 6f2a161b1b.
Fixes#125810Fixes#90110
This PR is an alternative to #136195. cc `@adetaylor.` I didn't realize in that PR that the layout checks that were being modified were simply *sanity checks*, rather than being actually necessary for soundness.
When we suggest specifying a type for an expression or pattern, like in a `let` binding, we previously would print the entire type as the type system knew it. We now look at the params that have *no* inference variables, so they are fully known to the type system which means that they don't need to be specified.
This helps in suggestions for types that are really long, because we can usually skip most of the type params and make the annotation as short as possible:
```
error[E0282]: type annotations needed for `Result<_, ((..., ..., ..., ...), ..., ..., ...)>`
--> $DIR/really-long-type-in-let-binding-without-sufficient-type-info.rs:7:9
|
LL | let y = Err(x);
| ^ ------ type must be known at this point
|
help: consider giving `y` an explicit type, where the type for type parameter `T` is specified
|
LL | let y: Result<T, _> = Err(x);
| ++++++++++++++
```
Shorten error message for callable with wrong return type
```
error: expected `{closure@...}` to return `Ret`, but it returns `Other`
```
instead of
```
error: expected `{closure@...}` to be a closure that returns `Ret`, but it returns `Other`
```
Highlight clarifying information in "expected/found" error
When the expected and found types have the same textual representation, we add clarifying in parentheses. We now visually highlight it in the output.
Detect a corner case where the clarifying information would be the same for both types and skip it, as it doesn't add anything useful.

Tweak fn pointer suggestion span
Use a more targeted span when suggesting casting an `fn` item to an `fn` pointer.
```
error[E0308]: cannot coerce functions which must be inlined to function pointers
--> $DIR/cast.rs:10:33
|
LL | let _: fn(isize) -> usize = callee;
| ------------------ ^^^^^^ cannot coerce functions which must be inlined to function pointers
| |
| expected due to this
|
= note: expected fn pointer `fn(_) -> _`
found fn item `fn(_) -> _ {callee}`
= note: fn items are distinct from fn pointers
help: consider casting to a fn pointer
|
LL | let _: fn(isize) -> usize = callee as fn(isize) -> usize;
| +++++++++++++++++++++
```
```
error[E0308]: mismatched types
--> $DIR/fn-pointer-mismatch.rs:42:30
|
LL | let d: &fn(u32) -> u32 = foo;
| --------------- ^^^ expected `&fn(u32) -> u32`, found fn item
| |
| expected due to this
|
= note: expected reference `&fn(_) -> _`
found fn item `fn(_) -> _ {foo}`
help: consider using a reference
|
LL | let d: &fn(u32) -> u32 = &foo;
| +
```
Previously we'd point at the whole expression for replacement, instead of marking what was being added.
We could also modify the suggestions for `&(name as fn())`, but for that we require storing more accurate spans than we have now.