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`
Implement selection for `Unsize` for better coercion behavior
In order for much of coercion to succeed, we need to be able to deal with partial ambiguity of `Unsize` traits during selection. However, I pessimistically implemented selection in the new trait solver to just bail out with ambiguity if it was a built-in impl:
9227ff28af/compiler/rustc_trait_selection/src/solve/eval_ctxt/select.rs (L126)
This implements a proper "rematch" procedure for dealing with built-in `Unsize` goals, so that even if the goal is ambiguous, we are able to get nested obligations which are used in the coercion selection-like loop:
9227ff28af/compiler/rustc_hir_typeck/src/coercion.rs (L702)
Second commit just moves a `resolve_vars_if_possible` call to fix a bug where we weren't detecting a trait upcasting to occur.
r? ``@lcnr``
Structurally resolve in pattern matching when peeling refs in new solver
Let me know if you want me to commit the minimized test:
```rust
fn test() {}
fn test2() {}
fn main() {
let tests: &[(_, fn())] = &[
("test", test),
("test2", test2),
];
for (a, b) in tests {
todo!();
}
}
```
In that test above, the match scrutinee is `<std::vec::Iter<(&'static str, fn())> as Iterator>::Item`, which we cannot peel the refs from.
We also need to structurally resolve in the loop, since structural resolve is inherently shallow. I haven't come up with a test where this matters, but I can if you care.
Also, I removed two other calls to `resolve_vars_with_obligations` in diagnostics code that I'm pretty convinced are not useful.
r? `@lcnr`
Replace RPITIT current impl with new strategy that lowers as a GAT
This PR replaces the current implementation of RPITITs with the new implementation that we had under -Zlower-impl-trait-in-trait-to-assoc-ty flag that lowers the RPIT as a GAT on the trait and on the impls that implement that trait.
Opening this PR as a draft because this goes after #112682, ~#112981~ and ~#112983~.
As soon as those are merged, I can rebase and we should run perf, crater and test a lot.
r? `@compiler-errors`
Don't call `query_normalize` when reporting similar impls
Firstly, It's sketchy to be using `query_normalize` at all during HIR typeck -- it's asking for an ICE 😅. Secondly, we're normalizing an impl trait ref that potentially has parameter types in `ty::ParamEnv::empty()`, which is kinda sketchy as well.
The only UI test change from removing this normalization is that we don't evaluate anonymous constants in impls, which end up giving us really ugly suggestions:
```
error[E0277]: the trait bound `[X; 35]: Default` is not satisfied
--> /home/gh-compiler-errors/test.rs:4:5
|
4 | <[X; 35] as Default>::default();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Default` is not implemented for `[X; 35]`
|
= help: the following other types implement trait `Default`:
&[T]
&mut [T]
[T; 32]
[T; core::::array::{impl#30}::{constant#0}]
[T; core::::array::{impl#31}::{constant#0}]
[T; core::::array::{impl#32}::{constant#0}]
[T; core::::array::{impl#33}::{constant#0}]
[T; core::::array::{impl#34}::{constant#0}]
and 27 others
```
So just fold the impls with a `BottomUpFolder` that calls `ty::Const::eval`. This doesn't work totally correctly with generic-const-exprs, but it's fine for stable code, and this is error reporting after all.
Reveal opaques in new solver
We were testing against the wrong reveal mode 😨
Also a couple of misc commits that I don't want to really put in separate prs
r? ``@lcnr``
Rollup of 8 pull requests
Successful merges:
- #113413 (Add needs-triage to all new issues)
- #113426 (Don't ICE in `resolve_bound_vars` when associated return-type bounds are in bad positions)
- #113427 (Remove `variances_of` on RPITIT GATs, remove its one use-case)
- #113441 (miri: check that assignments do not self-overlap)
- #113453 (Remove unused from_method from rustc_on_unimplemented)
- #113456 (Avoid calling report_forbidden_specialization for RPITITs)
- #113466 (Update cargo)
- #113467 (Fix comment of `fn_can_unwind`)
r? `@ghost`
`@rustbot` modify labels: rollup
Remove unused from_method from rustc_on_unimplemented
Fixes#113439
`on_unimplemented_note` was calling `item_name` for RPITITs and that produced ICEs. I've added a regression test for that but also have removed `from_method` symbol entirely because it wasn't even used and by doing that the `item_name` call was also removed.
r? ``@compiler-errors``
Split `SelectionContext::select` into fns that take a binder and don't
*most* usages of `SelectionContext::select` don't need to use a binder, but wrap them in a dummy because of the signature. Let's split this out into `SelectionContext::{select,poly_select}` and limit the usages of the latter.
Right now, we only have 3 places where we're calling `poly_select` -- fulfillment, internally within the old solver, and the auto-trait finder.
r? `@lcnr`
Prefer object candidates in new selection
`dyn Any` shouldn't be using [this implementation](https://doc.rust-lang.org/std/any/trait.Any.html#impl-Any-for-T) during codegen.
Prefer object candidates over other candidates, except for other object candidates.
Winnow specialized impls during selection in new solver
We need to be able to winnow impls that are specialized by more specific impls in order for codegen to be able to proceed.
r? ``@lcnr``
Move `ty::ConstKind` to `rustc_type_ir`
Needed this in another PR for custom debug impls, and this will also be required to move the new solver into a separate crate that does not use `TyCtxt` so that r-a and friends can depend on the trait solver.
Rebased on top of #113325, only the second and third commits needs reviewing
Add some extra information to opaque type cycle errors
Plus a bunch of cleanups.
This should help users debug query cycles due to auto trait checking. We'll probably want to fix cycle errors in most (or all?) cases by looking at the current item's hidden types (new solver does this), and by delaying the auto trait checks to after typeck.
`TypeParameterDefinition` always require a `DefId`
the `None` case never actually reaches diagnostics so it feels better for diagnostics to be able to rely on the `DefId` being there, cc #113310
add `ecx.probe_candidate`
Not yet changing the candidate source to an enum because that would be more involved, but this by itself should already be a significant improvement imo
r? `@BoxyUwU`
Rollup of 5 pull requests
Successful merges:
- #113192 (`assemble_candidates_after_normalizing_self_ty` docs)
- #113251 (Use scoped-tls for SMIR to map between TyCtxt and SMIR datastructures)
- #113282 (Update platform-support.md to improve ARM target descriptions)
- #113296 (add flag for enabling global cache usage for proof trees and printing proof trees on error)
- #113324 (implement `ConstEvaluatable` goals in new solver)
r? `@ghost`
`@rustbot` modify labels: rollup
implement `ConstEvaluatable` goals in new solver
this only supports stable const generics. `feature(generic_const_exprs)` needs to extend that function is non-trivial ways. Leaving this for someone else or some later date.
r? `@BoxyUwU`
add flag for enabling global cache usage for proof trees and printing proof trees on error
This adds a few new things:
- `-Zdump-solver-proof-tree=always/never/on-error`
- `always`/`never` were previosuly specifiable by whether the flag exists or not, th new flag is `on_error` which reruns obligations of fulfillment and selection errors with proof tree generation enabled and prints them out
- `-Zdump-solver-proof-tree-uses-cache`
- allows forcing global cache to be used or unused for all generated proof trees, global cache is enabled by default for `always` so that it accurately represents what happend. This flag currently would affect misc uses of `GenerateProofTree::Yes` which will be added in the future for things like diagnostics logic and rustdoc's auto_trait file. We can fix this when we start using proof tree generation for those use cases if it's desirable.
I also changed the output to go straight to stdout instead of going through `debug!` so that `-Zdump-solver-proof-tree` can be adequately used on `nightly` not just a locally built toolchain.
The idea for `on-error` is that it should hopefully make it easier to quickly figure out "why doesnt this code compile"- you just pass in `-Zdump-solver-proof-tree=on-error` and you'll only get proof trees you care about.
---
r? `@lcnr` `@compiler-errors`
`assemble_candidates_after_normalizing_self_ty` docs
I already explained that in different places a few times, should have added that explanation as a doc comment the first time I did so :3
r? `@BoxyUwU`
Normalize opaques with late-bound vars again
We have a hack in the compiler where if an opaque has escaping late-bound vars, we skip revealing it even though we *could* reveal it from a technical perspective. First of all, this is weird, since we really should be revealing all opaques in `Reveal::All` mode. Second of all, it causes subtle bugs (linked below).
I attempted to fix this in #100980, which was unfortunately reverted due to perf regressions on codebases that used really deeply nested futures in some interesting ways. The worst of which was #103423, which caused the project to hang on build. Another one was #104842, which was just a slow-down, but not a hang. I took some time afterwards to investigate how to rework `normalize_erasing_regions` to take advantage of better caching, but that effort kinda fizzled out (#104133).
However, recently, I was made aware of more bugs whose root cause is not revealing opaques during codegen. That made me want to fix this again -- in the process, interestingly, I took the the minimized example from https://github.com/rust-lang/rust/issues/103423#issuecomment-1292947043, and it doesn't seem to hang any more...
Thinking about this harder, there have been some changes to the way we lower and typecheck async futures that may have reduced the pathologically large number of outlives obligations (see description of #103423) that we were encountering when normalizing opaques with bound vars the last time around:
* #104321 (lower `async { .. }` directly as a generator that implements `Future`, removing the `from_generator` shim)
* #104833 (removing an `identity_future` fn that was wrapping desugared future generators)
... so given that I can see:
* No significant regression on rust perf bot (https://github.com/rust-lang/rust/pull/107620#issuecomment-1600070317)
* No timeouts in crater run I did (https://github.com/rust-lang/rust/pull/107620#issuecomment-1605428952, rechecked failing crates in https://github.com/rust-lang/rust/pull/107620#issuecomment-1605973434)
... and given that this PR:
* Fixes#104601
* Fixes#107557
* Fixes#109464
* Allows us to remove a `DefiningAnchor::Bubble` from codegen (75a8f68183)
I'm inclined to give this another shot at landing this. Best case, it just works -- worst case, we get more examples to study how we need to improve the compiler to make this work.
r? types
Don't emit same goal as input during `wf::unnormalized_obligations`
r? `@aliemjay` cc `@lcnr`
I accidentally pruned the logic to handle `WF(?0)` when writing `wf::unnormalized_obligations`.
idk if you wanted to construct a test first, but this is an obvious fix. Copied the comment from above.
Fixesrust-lang/trait-system-refactor-initiative#36
Migrate `item_bounds` to `ty::Clause`
Should be simpler than the next PR that's coming up. Last three commits are the relevant ones.
r? ``@oli-obk`` or ``@lcnr``
When a trait is used without specifying the implementation (e.g. calling
a non-member associated function without fully-qualified syntax) and
there are multiple implementations available, use a placeholder comment
for the implementation type in the suggestion instead of picking a
random implementation.
Example:
```
fn main() {
let _ = Default::default();
}
```
Previous output:
```
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
--> test.rs:2:13
|
2 | let _ = Default::default();
| ^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
help: use a fully-qualified path to a specific available implementation (273 found)
|
2 | let _ = <FileTimes as Default>::default();
| +++++++++++++ +
```
New output:
```
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
--> test.rs:2:13
|
2 | let _ = Default::default();
| ^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
help: use a fully-qualified path to a specific available implementation (273 found)
|
2 | let _ = </* self type */ as Default>::default();
| +++++++++++++++++++ +
```
Account for sealed traits in privacy and trait bound errors
On trait bound errors caused by super-traits, identify if the super-trait is publicly accessibly and if not, explain "sealed traits".
```
error[E0277]: the trait bound `S: Hidden` is not satisfied
--> $DIR/sealed-trait-local.rs:17:20
|
LL | impl a::Sealed for S {}
| ^ the trait `Hidden` is not implemented for `S`
|
note: required by a bound in `Sealed`
--> $DIR/sealed-trait-local.rs:3:23
|
LL | pub trait Sealed: self:🅱️:Hidden {
| ^^^^^^^^^^^^^^^ required by this bound in `Sealed`
= note: `Sealed` is a "sealed trait", because to implement it you also need to implelement `a:🅱️:Hidden`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
```
Deduplicate privacy errors that point to the same path segment even if their deduplication span are different.
When encountering a path that is not reachable due to privacy constraints path segments other than the last, keep metadata for the last path segment's `Res` in order to look for alternative import paths for that item to suggest. If there are none, be explicit that the item is not accessible.
```
error[E0603]: module `b` is private
--> $DIR/re-exported-trait.rs:11:9
|
LL | impl a:🅱️:Trait for S {}
| ^ private module
|
note: the module `b` is defined here
--> $DIR/re-exported-trait.rs:5:5
|
LL | mod b {
| ^^^^^
help: consider importing this trait through its public re-export instead
|
LL | impl a::Trait for S {}
| ~~~~~~~~
```
```
error[E0603]: module `b` is private
--> $DIR/private-trait.rs:8:9
|
LL | impl a:🅱️:Hidden for S {}
| ^ ------ trait `b` is not publicly reachable
| |
| private module
|
note: the module `b` is defined here
--> $DIR/private-trait.rs:2:5
|
LL | mod b {
| ^^^^^
```
When implementing a public trait with a private super-trait, we now emit
a note that the missing bound is not going to be able to be satisfied,
and we explain the concept of a sealed trait.
Add a fully fledged `Clause` type, rename old `Clause` to `ClauseKind`
Does two basic things before I put up a more delicate set of PRs (along the lines of #112714, but hopefully much cleaner) that migrate existing usages of `ty::Predicate` to `ty::Clause` (`predicates_of`/`item_bounds`/`ParamEnv::caller_bounds`).
1. Rename `Clause` to `ClauseKind`, so it's parallel with `PredicateKind`.
2. Add a new `Clause` type which is parallel to `Predicate`.
* This type exposes `Clause::kind(self) -> Binder<'tcx, ClauseKind<'tcx>>` which is parallel to `Predicate::kind` 😸
The new `Clause` type essentially acts as a newtype wrapper around `Predicate` that asserts that it is specifically a `PredicateKind::Clause`. Turns out from experimentation[^1] that this is not negative performance-wise, which is wonderful, since this a much simpler design than something that requires encoding the discriminant into the alignment bits of a predicate kind, or something else like that...
r? ``@lcnr`` or ``@oli-obk``
[^1]: https://github.com/rust-lang/rust/pull/112714#issuecomment-1595653910
The only regression is one ambiguity in the new trait solver, having to
do with two param-env candidates that may apply. I think this is fine,
since the error message already kinda sucks.
Add `implement_via_object` to `rustc_deny_explicit_impl` to control object candidate assembly
Some built-in traits are special, since they are used to prove facts about the program that are important for later phases of compilation such as codegen and CTFE. For example, the `Unsize` trait is used to assert to the compiler that we are able to unsize a type into another type. It doesn't have any methods because it doesn't actually *instruct* the compiler how to do this unsizing, but this is later used (alongside an exhaustive match of combinations of unsizeable types) during codegen to generate unsize coercion code.
Due to this, these built-in traits are incompatible with the type erasure provided by object types. For example, the existence of `dyn Unsize<T>` does not mean that the compiler is able to unsize `Box<dyn Unsize<T>>` into `Box<T>`, since `Unsize` is a *witness* to the fact that a type can be unsized, and it doesn't actually encode that unsizing operation in its vtable as mentioned above.
The old trait solver gets around this fact by having complex control flow that never considers object bounds for certain built-in traits:
2f896da247/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs (L61-L132)
However, candidate assembly in the new solver is much more lovely, and I'd hate to add this list of opt-out cases into the new solver. Instead of maintaining this complex and hard-coded control flow, instead we can make this a property of the trait via a built-in attribute. We already have such a build attribute that's applied to every single trait that we care about: `rustc_deny_explicit_impl`. This PR adds `implement_via_object` as a meta-item to that attribute that allows us to opt a trait out of object-bound candidate assembly as well.
r? `@lcnr`
Don't consider TAIT normalizable to hidden ty if it would result in impossible item bounds
See test for example where we shouldn't consider it possible to alias-relate a TAIT and hidden type.
r? `@lcnr`
Don't ICE on bound var in `reject_fn_ptr_impls`
We may try to use an impl like `impl<T: FnPtr> PartialEq {}` to satisfy a predicate like `for<T> T: PartialEq` -- don't ICE in that case.
Fixes#112735
Continue folding in query normalizer on weak aliases
Fixes#112752Fixes#112731 (same root cause, so didn't make a test for it)
fixes#112776
r? ```@oli-obk```
Add `AliasKind::Weak` for type aliases.
`type Foo<T: Debug> = Bar<T>;` does not check `T: Debug` at use sites of `Foo<NotDebug>`, because in contrast to a
```rust
trait Identity {
type Identity;
}
impl<T: Debug> Identity for T {
type Identity = T;
}
<NotDebug as Identity>::Identity
```
type aliases do not exist in the type system, but are expanded to their aliased type immediately when going from HIR to the type layer.
Similarly:
* a private type alias for a public type is a completely fine thing, even though it makes it a bit hard to write out complex times sometimes
* rustdoc expands the type alias, even though often times users use them for documentation purposes
* diagnostics show the expanded type, which is confusing if the user wrote a type alias and the diagnostic talks about another type that they don't know about.
For type alias impl trait, these issues do not actually apply in most cases, but sometimes you have a type alias impl trait like `type Foo<T: Debug> = (impl Debug, Bar<T>);`, which only really checks it for `impl Debug`, but by accident prevents `Bar<T>` from only being instantiated after proving `T: Debug`. This PR makes sure that we always check these bounds explicitly and don't rely on an implementation accident.
To not break all the type aliases out there, we only use it when the type alias contains an opaque type. We can decide to do this for all type aliases over an edition.
Or we can later extend this to more types if we figure out the back-compat concerns with suddenly checking such bounds.
As a side effect, easily allows fixing https://github.com/rust-lang/rust/issues/108617, which I did.
fixes https://github.com/rust-lang/rust/issues/108617
Make assumption functions in new solver take `Binder<'tcx, Clause<'tcx>>`
We just use an if-let to match on an optional clause at all the places where we transition from `Predicate` -> `Clause`, but I assume that when things like item-bounds and param-env start to only store `Clause`s then those can just be trivially dropped.
r? ``@lcnr``
Opportunistically resolve regions in new solver
Use `opportunistic_resolve_var` during canonicalization to collapse some regions.
We have to start using `CanonicalVarValues::is_identity_modulo_regions`. We also have to modify that function to consider responses like `['static, ^0, '^1, ^2]` to be an "identity" response, since because we opportunistically resolve regions, there's no longer a 1:1 mapping between canonical var values and bound var indices in the response...
There's one nasty side-effect -- one test (`tests/ui/dyn-star/param-env-infer.rs`) starts to ICE because the certainty goes from `Yes` to `Maybe(Overflow)`... Not exactly sure why, though? Putting this up for discussion/investigation.
r? ```@lcnr```
Improve docs/clean up negative overlap functions
Clean up some functions in ways that should not affect behavior, change some names to be clearer (`negative_impl` and `implicit_negative` are not really clear imo), and add some documentation examples.
r? `@spastorino`
Collect VTable stats & add `-Zprint-vtable-sizes`
This is a bit hacky/buggy, but I'm not entirely sure how to fix it, so I want to ask reviewers for help...
To try this, use either of those:
- `cargo clean && RUSTFLAGS="-Zprint-vtable-sizes" cargo +toolchain b`
- `cargo clean && cargo rustc +toolchain -Zprint-vtable-sizes`
- `rustc +toolchain -Zprint-vtable-sizes ./file.rs`
Safe Transmute: Enable handling references
This patch enables support for references in Safe Transmute, by generating nested obligations during trait selection. Specifically, when we call `confirm_transmutability_candidate(...)`, we now recursively traverse the `rustc_transmute::Answer` tree and create obligations for all the `Answer` variants, some of which include multiple nested `Answer`s.
- Create `Answer` type that is not just a type alias of `Result`
- Remove a usage of `map_layouts` to make the code easier to read
- Don't hide errors related to Unknown Layout when computing transmutability
Add `-Ztrait-solver=next-coherence`
Flag that conditionally uses the trait solver *only* during coherence, for more testing and/or eventual partial-migration onto the trait solver (in the medium- to long-term).
* This still uses the selection context in some of the coherence methods I think, so it's not "complete". Putting this up for review and/or for further work in-tree.
* I probably need to spend a bit more time making sure that we don't sneakily create any other infcx's during coherence that also need the new solver enabled.
r? `@lcnr`
Fall back to bidirectional normalizes-to if no subst-relate candidate in alias-relate goal
Sometimes we get into the case where the choice of normalizes-to branch in alias-relate are both valid, but we cannot make a choice of which one to take because they are different -- either returning equivalent but permuted region constraints, or equivalent opaque type definitions but differing modulo normalization.
In this case, we can make progress by considering a fourth candidate where we compute both normalizes-to branches together and canonicalize that as a response. This is essentially the AND intersection of both normalizes-to branches. In an ideal world, we'd be returning something more like the OR intersection of both branches, but we have no way of representing that either for regions (maybe eventually) or opaques (don't see that happening ever).
This is incomplete, so like the subst-relate fallback it's only considered outside of coherence. But it doesn't seem like a dramatic strengthening of inference or anything, and is useful for helping opaque type inference succeed when the hidden type is a projection.
## Example
Consider the goal - `AliasRelate(Tait, <[i32; 32] as IntoIterator>::IntoIter)`.
We have three ways of currently solving this goal:
1. SubstRelate - fails because we can't directly equate the substs of different alias kinds.
2. NormalizesToRhs - `Tait normalizes-to <[i32; 32] as IntoIterator>::IntoIter`
* Ends up infering opaque definition - `Tait := <[i32; 32] as IntoIterator>::IntoIter`
3. NormalizesToLhs - `<[i32; 32] as IntoIterator>::IntoIter normalizes-to Tait`
* Find impl candidate, substitute the associated type - `std::array::IntoIter<i32, 32>`
* Equate `std::array::IntoIter<i32, 32>` and `Tait`
* Ends up infering opaque definition - `Tait := std::array::IntoIter<i32, 32>`
The problem here is that 2 and 3 are essentially both valid, since we have aliases that normalize on both sides, but due to lazy norm, they end up inferring different opaque type definitions that are only equal *after* normalizing them further.
---
r? `@lcnr`
Merge method, type and const object safety checks
cc `@spastorino` and `@compiler-errors` on the first commit. I believe it to be correct, as the field is only `Some` for assoc types, so just checking the field without checking the assoc kind to be `Type` is fine.
The second commit avoids going through all associated items thrice and just goes over all of them once, running the object safety checks per assoc item kind.
Normalize in infcx instead of globally for `Option::as_deref` suggestion
fixes#112293
The projection may contain inference variables. These inference variables are local to the local inference context. Using `tcx.normalize_erasing_regions` doesn't work here because this method is global and does not have access to the inference context. It's therefore unable to deal with the inference variables. We normalize in the local inference context instead, which knowns about the inference variables.
The test looks a little different than the issue example, I made it more minimal and verified that it still ICEs on nightly.
Also contains a drive-by fix to properly compare the types.
r? `@compiler-errors`
The projection may contain inference variables. These inference
variables are local to the local inference context. Using
`tcx.normalize_erasing_regions` doesn't work here because this method is
global and does not have access to the inference context. It's therefore
unable to deal with the inference variables. We normalize in the local
inference context instead, which knowns about the inference variables.
suggest `Option::as_deref(_mut)` on type mismatch in option combinator if it passes typeck
Fixes#106342.
This adds a suggestion to call `.as_deref()` (or `.as_deref_mut()` resp.) if typeck fails due to a type mismatch in the function passed to an `Option` combinator such as `.map()` or `.and_then()`.
For example:
```rs
fn foo(_: &str) {}
Some(String::new()).map(foo);
```
The `.map()` method requires its argument to satisfy `F: FnOnce(String)`, but it received `fn(&str)`, which won't pass. However, placing a `.as_deref()` before the `.map()` call fixes this since `&str == &<String as Deref>::Target`
refactor and cleanup the leak check, add it to new solver
ended up being a bit more involved than I wanted but is hopefully still easy enough to review as a single PR, can split it into separate ones otherwise.
this can be reviewed commit by commit:
a473d55cdb9284aa2b01282d1b529a2a4d26547b 31a686646534ca006d906ec757ece4e771d6f973 949039c107852a5e36361c08b62821a0613656f5 242917bf5170d9a723c6c8e23e9d9d0c2fa8dc9d ed2b25a7aa28be3184be9e3022c2796a30eaad87 are all pretty straightforward.
03dd83b4c3f4ff27558f5c8ab859bd9f83db1d04 makes it easier to refactor coherence in a later commit, see the commit description, cc `@oli-obk`
4fe311d807a77b6270f384e41689bf5d58f46aec I don't quite remember what we wanted to test here, this definitely doesn't test that the occurs check doesn't cause incorrect errors in coherence, also cc `@oli-obk` here. I may end up writing a new test for this myself later.
5c200d88a91b75bd0875b973150655bd581ef97a is the main refactor of the leak check, changing it to take the `outer_universe` instead of getting it from a snapshot. Using a snapshot requires us to be in a probe which we aren't in the new solver, it also just feels dirty as snapshots don't really have anything to do with universes.
with all of this cfc230d54188d9c7ed867a9a0d1f51be77b485f9 is now kind of trivial.
r? `@nikomatsakis`
`EarlyBinder::new` -> `EarlyBinder::bind`
for consistency with `Binder::bind`. it may make sense to also add `EarlyBinder::dummy` in places where we know that no parameters exist, but I left that out of this PR.
r? `@jackh726` `@kylematsuda`
Each of `{D,Subd}iagnosticMessage::{Str,Eager}` has a comment:
```
// FIXME(davidtwco): can a `Cow<'static, str>` be used here?
```
This commit answers that question in the affirmative. It's not the most
compelling change ever, but it might be worth merging.
This requires changing the `impl<'a> From<&'a str>` impls to `impl
From<&'static str>`, which involves a bunch of knock-on changes that
require/result in call sites being a little more precise about exactly
what kind of string they use to create errors, and not just `&str`. This
will result in fewer unnecessary allocations, though this will not have
any notable perf effects given that these are error paths.
Note that I was lazy within Clippy, using `to_string` in a few places to
preserve the existing string imprecision. I could have used `impl
Into<{D,Subd}iagnosticMessage>` in various places as is done in the
compiler, but that would have required changes to *many* call sites
(mostly changing `&format("...")` to `format!("...")`) which didn't seem
worthwhile.
Enable MatchBranchSimplification
This pass is one of the small number of benefits from `-Zmir-opt-level=3` that has motivated rustc_codegen_cranelift to use it:
19ed0aade6/compiler/rustc_codegen_cranelift/build_system/build_sysroot.rs (L244-L246)
Cranelift's motivation for this is _runtime_ performance improvements in debug builds. Lifting this pass all the way to `-Zmir-opt-level=1` seems to come without significant perf overhead, so that's what I'm suggesting here.
Add warn-by-default lint when local binding shadows exported glob re-export item
This PR introduces a warn-by-default rustc lint for when a local binding (a use statement, or a type declaration) produces a name which shadows an exported glob re-export item, causing the name from the exported glob re-export to be hidden (see #111336).
### Unresolved Questions
- [x] ~~Is this approach correct? While it passes the UI tests, I'm not entirely convinced it is correct.~~ Seems to be ok now.
- [x] ~~What should the lint be called / how should it be worded? I don't like calling `use x::*;` or `struct Foo;` a "local binding" but they are `NameBinding`s internally if I'm not mistaken.~~ ~~The lint is called `local_binding_shadows_glob_reexport` for now, unless a better name is suggested.~~ `hidden_glob_reexports`.
Fixes#111336.