Separate `consider_unsize_to_dyn_candidate` from other unsize candidates
Move the unsize candidate assembly *just for* `T -> dyn Trait` out of `assemble_candidates_via_self_ty` so that we only consider it once, instead of for every normalization step of the self ty. This makes sure that we don't assemble several candidates that are equal modulo normalization when we really don't care about normalizing the self type of an `T: Unsize<dyn Trait>` goal anyways.
Fixesrust-lang/trait-system-refactor-initiative#57
r? lcnr
Probe when assembling upcast candidates so they don't step on eachother's toes in new solver
Lack of a probe causes one candidate to disqualify the other due to inference side-effects.
r? lcnr
When encountering code like
```rust
fn foo() -> i32 {
match 0 {
1 => return 0,
2 => "",
_ => 1,
}
}
```
Point at the return type and not at the prior arm, as that arm has type
`!` which isn't influencing the arm corresponding to arm `2`.
Fix#78124.
normalize in `trait_ref_is_knowable` in new solver
fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/51
Alternatively we could avoid normalizing the self type and do this at the end of the `assemble_candidates_via_self_ty` stack by splitting candidates into:
- applicable without normalizing self type
- applicable for aliases, even if they can be normalized
- applicable for stuff which cannot get normalized further
I don't think this would have any significant benefits and it also seems non-trivial to avoid normalizing only the self type in `trait_ref_is_knowable`.
r? `@compiler-errors`
Fix a couple of bad comments
A couple of nits I saw. Sorry, this really should be folded into some other PR of mine, but I will literally forget if I don't put these up now.
Structurally normalize weak and inherent in new solver
It seems pretty obvious to me that we should be normalizing weak and inherent aliases too, since they can always be normalized. This PR still leaves open the question of what to do with opaques, though 💀
**Also**, we need to structurally resolve the target of a coercion, for the UI test to work.
r? `@lcnr`
Store the laziness of type aliases in their `DefKind`
Previously, we would treat paths referring to type aliases as *lazy* type aliases if the current crate had lazy type aliases enabled independently of whether the crate which the alias was defined in had the feature enabled or not.
With this PR, the laziness of a type alias depends on the crate it is defined in. This generally makes more sense to me especially if / once lazy type aliases become the default in a new edition and we need to think about *edition interoperability*:
Consider the hypothetical case where the dependency crate has an older edition (and thus eager type aliases), it exports a type alias with bounds & a where-clause (which are void but technically valid), the dependent crate has the latest edition (and thus lazy type aliases) and it uses that type alias. Arguably, the bounds should *not* be checked since at any time, the dependency crate should be allowed to change the bounds at will with a *non*-major version bump & without negatively affecting downstream crates.
As for the reverse case (dependency: lazy type aliases, dependent: eager type aliases), I guess it rules out anything from slight confusion to mild annoyance from upstream crate authors that would be caused by the compiler ignoring the bounds of their type aliases in downstream crates with older editions.
---
This fixes#114468 since before, my assumption that the type alias associated with a given weak projection was lazy (and therefore had its variances computed) did not necessarily hold in cross-crate scenarios (which [I kinda had a hunch about](https://github.com/rust-lang/rust/pull/114253#discussion_r1278608099)) as outlined above. Now it does hold.
`@rustbot` label F-lazy_type_alias
r? `@oli-obk`
Bubble up nested goals from equation in `predicates_for_object_candidate`
This used to be needed for https://github.com/rust-lang/rust/pull/114036#discussion_r1273987510, but since it's no longer, I'm opening this as a separate PR. This also fixes one ICEing UI test: (`tests/ui/unboxed-closures/issue-53448.rs`)
r? `@lcnr`
update overflow handling in the new trait solver
implements https://hackmd.io/QY0dfEOgSNWwU4oiGnVRLw?view. I want to clean up this doc and add it to the rustc-dev-guide, but I think this PR is ready for merge as is, even without the dev-guide entry.
r? `@compiler-errors`
Improve spans for indexing expressions
fixes#114388
Indexing is similar to method calls in having an arbitrary left-hand-side and then something on the right, which is the main part of the expression. Method calls already have a span for that right part, but indexing does not. This means that long method chains that use indexing have really bad spans, especially when the indexing panics and that span in coverted into a panic location.
This does the same thing as method calls for the AST and HIR, storing an extra span which is then put into the `fn_span` field in THIR.
r? compiler-errors
Indexing is similar to method calls in having an arbitrary
left-hand-side and then something on the right, which is the main part
of the expression. Method calls already have a span for that right part,
but indexing does not. This means that long method chains that use
indexing have really bad spans, especially when the indexing panics and
that span in coverted into a panic location.
This does the same thing as method calls for the AST and HIR, storing an
extra span which is then put into the `fn_span` field in THIR.
Rework upcasting confirmation to support upcasting to fewer projections in target bounds
This PR implements a modified trait upcasting algorithm that is resilient to changes in the number of associated types in the bounds of the source and target trait objects.
It does this by equating each bound of the target trait ref individually against the bounds of the source trait ref, rather than doing them all together by constructing a new trait object.
#### The new way we do trait upcasting confirmation
1. Equate the target trait object's principal trait ref with one of the supertraits of the source trait object's principal.
fdcab310b2/compiler/rustc_trait_selection/src/traits/select/mod.rs (L2509-L2525)
2. Make sure that every auto trait in the *target* trait object is present in the source trait ref's bounds.
fdcab310b2/compiler/rustc_trait_selection/src/traits/select/mod.rs (L2559-L2562)
3. For each projection in the *target* trait object, make sure there is exactly one projection that equates with it in the source trait ref's bound. If there is more than one, bail with ambiguity.
fdcab310b2/compiler/rustc_trait_selection/src/traits/select/mod.rs (L2526-L2557)
* Since there may be more than one that applies, we probe first to check that there is exactly one, then we equate it outside of a probe once we know that it's unique.
4. Make sure the lifetime of the source trait object outlives the lifetime of the target.
<details>
<summary>Meanwhile, this is how we used to do upcasting:</summary>
1. For each supertrait of the source trait object, take that supertrait, append the source object's projection bounds, and the *target* trait object's auto trait bounds, and make this into a new object type:
d12c6e947c/compiler/rustc_trait_selection/src/traits/select/confirmation.rs (L915-L929)
2. Then equate it with the target trait object:
d12c6e947c/compiler/rustc_trait_selection/src/traits/select/confirmation.rs (L936)
This will be a type mismatch if the target trait object has fewer projection bounds, since we compare the bounds structurally in relate:
d12c6e947c/compiler/rustc_middle/src/ty/relate.rs (L696-L698)
</details>
Fixes#114035
Also fixes#114113, because I added a normalize call in the old solver.
r? types
resolve before canonicalization in new solver, ICE if unresolved
Fold the values with a resolver before canonicalization instead of making it happen within canonicalization.
This allows us to filter trivial region constraints from the external constraints.
r? ``@lcnr``
Rollup of 6 pull requests
Successful merges:
- #114178 (Account for macros when suggesting a new let binding)
- #114199 (Don't unsize coerce infer vars in select in new solver)
- #114301 (Don't check unnecessarily that impl trait is RPIT)
- #114314 (Tweaks to `adt_sized_constraint`)
- #114322 (Fix invalid slice coercion suggestion reported in turbofish)
- #114340 ([rustc_attr][nit] Replace `filter` + `is_some` with `map_or`.)
r? `@ghost`
`@rustbot` modify labels: rollup
Fix invalid slice coercion suggestion reported in turbofish
This PR fixes the invalid slice coercion suggestion reported in turbofish and inferred generics by not emitting them.
Fixes https://github.com/rust-lang/rust/issues/110063
Detect trait upcasting through struct tail unsizing in new solver select
Oops, we were able to hide trait upcasting behind a parent unsize goal that evaluated to `Certainty::Yes`. Let's do rematching for `Certainty::Yes` unsize goals with `BuiltinImplSource::Misc` sources (corresponding to all of the other unsize rules) to make sure we end up selecting any nested goals which may be satisfied via `BuiltinImplSource::TraitUpcasting` or `::TupleUnsizing`.
r? ``@lcnr``
Restore region uniquification in the new solver 🎉
All of the bugs that were "due" to uniquification have been settled via other means (e.g. bidirectional alias-relate, param-env incompleteness, etc).
Firstly, revert the functional changes in #110180. 😸
Secondly, we need to ignore regions when considering if a goal has changed (the "has_changed" boolean returned from `evaluate_goal`) -- otherwise, because we're doing region uniquification, we may perpetually consider a goal to be changed. See the UI test I committed for an explanation.
Don't treat negative trait predicates as always knowable
We don't need this. It was added in #90104 but I don't really know why. It's not sound afaict -- negative trait predicates need the same coherence-ambiguity/orphan check rules as positive ones.
r? `@lcnr`
cc `@spastorino,` do you remember why?
Double check that hidden types match the expected hidden type
Fixes https://github.com/rust-lang/rust/issues/113278 specifically, but I left a TODO for where we should also add some hardening.
It feels a bit like papering over the issue, but at least this way we don't get unsoundness, but just surprising errors. Errors will be improved and given spans before this PR lands.
r? `@compiler-errors` `@lcnr`
rustdoc: handle cross-crate RPITITs correctly
Filter out the internal associated types synthesized during the desugaring of RPITITs, they really shouldn't show up in the docs.
This also fixes#113929 since we're no longer invoking `is_impossible_associated_item` (renamed from `is_impossible_method`) which cannot handle them (leading to an ICE). I don't think it makes sense to try to make `is_impossible_associated_item` handle this exotic kind of associated type (CC original author `@compiler-errors).`
@ T-rustdoc reviewers, currently I'm throwing out ITIT assoc tys before cleaning assoc tys at each usage-site. I'm thinking about making `clean_middle_assoc_item` return an `Option<_>` instead and doing the check inside of it to prevent any call sites from forgetting the check for ITITs. Since I wasn't sure if you would like that approach, I didn't go through with it. Let me know what you think.
<details><summary>Explanation on why <code>is_impossible_associated_item(itit_assoc_ty)</code> leads to an ICE</summary>
Given the following code:
```rs
pub trait Trait { fn def<T>() -> impl Default {} }
impl Trait for () {}
```
The generated associated type looks something like (simplified):
```rs
type {opaque#0}<T>: Default = impl Default; // the name is actually `kw::Empty` but this is the `def_path_str` repr
```
The query `is_impossible_associated_item` goes through all predicates of the associated item – in this case `<T as Sized>` – to check if they contain any generic parameters from the (generic) associated type itself. For predicates that don't contain any *own* generics, it does further processing, part of which is instantiating the predicate with the generic arguments of the impl block (which is only correct if they truly don't contain any own generics since they wouldn't get instantiated this way leading to an ICE).
It checks if `parent_def_id(T) == assoc_ty_def_id` to get to know if `T` is owned by the assoc ty. Unfortunately this doesn't work for ITIT assoc tys. In this case, the parent of `T` is `Trait::def` (!) which is the associated function (I'm pretty sure this is very intentional) which is of course not equal to the assoc ty `Trait::{opaque#0}`.
</details>
`@rustbot` label A-cross-crate-reexports
Get rid of subst-relate incompleteness in new solver
We shouldn't need subst-relate if we have bidirectional-normalizes-to in the new solver.
The only potential issue may happen if we have an unconstrained projection like `<Wrapper<?0> as Trait>::Assoc == <Wrapper<T> as Trait>::Assoc` where they both normalize to something that doesn't mention any substs, which would possibly prefer `?0 = T` if we fall back to subst-relate. But I'd prefer if we remove incompleteness until we can determine some case where we need them, and the bidirectional-normalizes-to seems better to have in general.
I can update https://github.com/rust-lang/trait-system-refactor-initiative/issues/26 and https://github.com/rust-lang/trait-system-refactor-initiative/issues/25 once this lands.
r? `@lcnr`
Tweak spans for self arg, fix borrow suggestion for signature mismatch
1. Adjust a suggestion message that was annoying me
2. Fix#112503 by recording the right spans for the `self` part of the `&self` 0th argument
3. Remove the suggestion for adjusting a trait signature on type mismatch, bc that's gonna probably break all the other impls of the trait even if it fixes its one usage 😅
Rollup of 4 pull requests
Successful merges:
- #113887 (new solver: add a separate cache for coherence)
- #113910 (Add FnPtr ty to SMIR)
- #113913 (error/E0691: include alignment in error message)
- #113914 (rustc_target: drop duplicate code)
r? `@ghost`
`@rustbot` modify labels: rollup
THis significantly complicates `NaiveLayout` logic, but is necessary to
ensure that bounds like `NonNull<T>: PointerLike` hold in generic
contexts.
Also implement exact layout computation for structs.
Refactor vtable encoding and optimize it for the case of multiple marker traits
This PR does two things
- Refactor `prepare_vtable_segments` (this was motivated by the other change, `prepare_vtable_segments` was quite hard to understand and while trying to edit it I've refactored it)
- Mostly remove `loop`s labeled `break`s/`continue`s whenever there is a simpler solution
- Also use `?`
- Make vtable format a bit more efficient wrt to marker traits
- See the tests for an example
Fixes https://github.com/rust-lang/rust/issues/113840
cc `@crlf0710`
----
Review wise it's probably best to review each commit individually, as then it's more clear why the refactoring is correct.
I can split the last two commits (which change behavior) into a separate PR if it makes reviewing easier
Reasoning: if the stack is empty, the loop will be infinite,
so the assumption is that the stack can't be non empty. Unwrap
makes the assumption more clear (and removes an indentation level)
allow opaques to be defined by trait queries, again
This basically reverts #112963.
Moreover, all call-sites of `enter_canonical_trait_query` can now define opaque types, see the ui test `defined-by-user-annotation.rs`.
Fixes#113689
r? `@compiler-errors` `@oli-obk`
Add support for inherent projections in new solver
Not hard to support these, and it cuts out a really big chunk of failing UI tests with `--compare-mode=next-solver`
r? `@lcnr` (feel free to reassign, anyone can review this)
Don't call `predicate_must_hold`-esque functions during fulfillment in intercrate
Fixes#113415
Given that this only happens in `translate_substs`, I don't actually think that this is something that you can weaponize, but it's still sketchy regardless.
r? `@lcnr`
Structurally normalize in selection
We need to do this because of the fact that we're checking the `Ty::kind` on a type during selection, but goals passed into select are not necessarily normalized.
Right now, we're (kinda) unnecessarily normalizing the RHS of a trait upcasting goal, which is broken for different reasons (#113393). But I'm waiting for this PR to land before discussing that one.
r? `@lcnr`
Allow escaping bound vars during `normalize_erasing_regions` in new solver
Add `AllowEscapingBoundVars` to `deeply_normalize`, and use it in the new solver in the `query_normalize` routine.
Ideally, we'd make all `query_normalize` calls handle pass in `AllowEscapingBoundVars` individually, because really the only `query_normalize` call that needs `AllowEscapingBoundVars::Yes` is the one in `try_normalize_generic_arg_after_erasing_regions`, but I think that's kind of overkill. I am happy to be convinced otherwise, though.
r? `@lcnr`
Make it clearer that we're just checking for an RPITIT
Tiny nit to use `is_impl_trait_in_trait` more, to make it clearer that we're just checking whether a def-id is an RPITIT, rather than doing something meaningful with the `opt_rpitit_info`.
r? `@spastorino`