Implement negative bounds for internal testing purposes
Implements partial support the `!` negative polarity on trait bounds. This is incomplete, but should allow us to at least be able to play with the feature.
Not even gonna consider them as a public-facing feature, but I'm implementing them because would've been nice to have in UI tests, for example in #110671.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.
This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.
As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
Add `ConstParamTy` trait
This is a bit sketch, but idk.
r? `@BoxyUwU`
Yet to be done:
- [x] ~~Figure out if it's okay to implement `StructuralEq` for primitives / possibly remove their special casing~~ (it should be okay, but maybe not in this PR...)
- [ ] Maybe refactor the code a little bit
- [x] Use a macro to make impls a bit nicer
Future work:
- [ ] Actually™ use the trait when checking if a `const` generic type is allowed
- [ ] _Really_ refactor the surrounding code
- [ ] Refactor `marker.rs` into multiple modules for each "theme" of markers
Tweak await span to not contain dot
Fixes a discrepancy between method calls and await expressions where the latter are desugared to have a span that *contains* the dot (i.e. `.await`) but method call identifiers don't contain the dot. This leads to weird suggestions suggestions in borrowck -- see linked issue.
Fixes#110761
This mostly touches a bunch of tests to tighten their `await` span.
Clear response values for overflow in new solver
When we have an overflow, return a trivial query response. This fixes an ICE with the code described in #110544:
```rust
trait Trait {}
struct W<T>(T);
impl<T, U> Trait for W<(W<T>, W<U>)>
where
W<T>: Trait,
W<U>: Trait,
{}
fn impls<T: Trait>() {}
fn main() {
impls::<W<_>>()
}
```
Where, while proving `W<?0>: Trait`, we overflow but still apply the query response of `?0 = (W<?1>, W<?2>)`. Then while re-processing the query to validate that our evaluation result was stable, we get a different query response that looks like `?1 = (W<?3>, W<?4>), ?2 = (W<?5>, W<?6>)`, and so we trigger the ICE.
Also, by returning a trivial query response we also avoid the infinite-loop/OOM behavior of the old solver.
r? ``@lcnr``
Consider polarity in new solver
It's kinda ugly to have a polarity check in all of the builtin impls -- I guess I could consider the polarity at the top of assemble-builtin but that would require adding a polarity fn to `GoalKind`...
🤷 putting this up just so i dont forget, since it's needed to bootstrap core during coherence (this alone does not allow core to bootstrap though, additional work is needed!)
r? ``@lcnr``
Switch to `EarlyBinder` for `explicit_item_bounds`
Part of the work to finish https://github.com/rust-lang/rust/issues/105779.
This PR adds `EarlyBinder` to the return type of the `explicit_item_bounds` query and removes `bound_explicit_item_bounds`.
r? `@compiler-errors` (hope it's okay to request you, since you reviewed #110299 and #110498😃)
Break up long function in trait selection error reporting + clean up nearby code
- Move blocks of code into their own functions
- Replace a few function argument types with their type aliases
- Create "AppendConstMessage" enum to replace a nested `Option`.
Allow to feed a value in another query's cache and remove `WithOptConstParam`
I used it to remove `WithOptConstParam` queries, as an example.
The idea is that a query (here `typeck(function)`) can write into another query's cache (here `type_of(anon const)`). The dependency node for `type_of` would depend on all the current dependencies of `typeck`.
There is still an issue with cycles: if `type_of(anon const)` is accessed before `typeck(function)`, we will still have the usual cycle. The way around this issue is to `ensure` that `typeck(function)` is called before accessing `type_of(anon const)`.
When replayed, we may the following cases:
- `typeck` is green, in that case `type_of` is green too, and all is right;
- `type_of` is green, `typeck` may still be marked as red (it depends on strictly more things than `type_of`) -> we verify that the saved value and the re-computed value of `type_of` have the same hash;
- `type_of` is red, then `typeck` is red -> it's the caller responsibility to ensure `typeck` is recomputed *before* `type_of`.
As `anon consts` have their own `DefPathData`, it's not possible to have the def-id of the anon-const point to something outside the original function, but the general case may have to be resolved before using this device more broadly.
There is an open question about loading from the on-disk cache. If `typeck` is loaded from the on-disk cache, the side-effect does not happen. The regular `type_of` implementation can go and fetch the correct value from the decoded `typeck` results, and the dep-graph will check that the hashes match, but I'm not sure we want to rely on this behaviour.
I specifically allowed to feed the value to `type_of` from inside a call to `type_of`. In that case, the dep-graph will check that the fingerprints of both values match.
This implementation is still very sensitive to cycles, and requires that we call `typeck(function)` before `typeck(anon const)`. The reason is that `typeck(anon const)` calls `type_of(anon const)`, which calls `typeck(function)`, which feeds `type_of(anon const)`, and needs to build the MIR so needs `typeck(anon const)`. The latter call would not cycle, since `type_of(anon const)` has been set, but I'd rather not remove the cycle check.
Add `rustc_fluent_macro` to decouple fluent from `rustc_macros`
Fluent, with all the icu4x it brings in, takes quite some time to compile. `fluent_messages!` is only needed in further downstream rustc crates, but is blocking more upstream crates like `rustc_index`. By splitting it out, we allow `rustc_macros` to be compiled earlier, which speeds up `x check compiler` by about 5 seconds (and even more after the needless dependency on `serde_json` is removed from `rustc_data_structures`).
Switch to `EarlyBinder` for `collect_return_position_impl_trait_in_trait_tys`
Part of the work to finish https://github.com/rust-lang/rust/issues/105779.
This PR adds `EarlyBinder` to the return type of the `collect_return_position_impl_trait_in_trait_tys` query and removes `bound_return_position_impl_trait_in_trait_tys`.
r? `@lcnr`
Fluent, with all the icu4x it brings in, takes quite some time to
compile. `fluent_messages!` is only needed in further downstream rustc
crates, but is blocking more upstream crates like `rustc_index`. By
splitting it out, we allow `rustc_macros` to be compiled earlier, which
speeds up `x check compiler` by about 5 seconds (and even more after the
needless dependency on `serde_json` is removed from
`rustc_data_structures`).
Various minor Idx-related tweaks
Nothing particularly exciting here, but a couple of things I noticed as I was looking for more index conversions to simplify.
cc https://github.com/rust-lang/compiler-team/issues/606
r? `@WaffleLapkin`
Remove `TypeSuper{Foldable,Visitable}` impls for `Region`.
These traits exist so that folders/visitors can recurse into types of interest: binders, types, regions, predicates, and consts. But `Region` is non-recursive and cannot contain other types of interest, so its methods in these traits are trivial.
This commit inlines and removes those trivial methods.
r? `@compiler-errors`
Remove `remap_env_constness` in queries
This removes some of the complexities with const traits. #88119 used to be caused by this but was fixed by `param_env = param_env.without_const()`.
These traits exist so that folders/visitors can recurse into types of
interest: binders, types, regions, predicates, and consts. But `Region`
is non-recursive and cannot contain other types of interest, so its
methods in these traits are trivial.
This commit inlines and removes those trivial methods.
Switch to `EarlyBinder` for `impl_subject` query
Part of the work to finish https://github.com/rust-lang/rust/issues/105779.
Several queries `X` have a `bound_X` variant that wraps the output in `EarlyBinder`. This adds `EarlyBinder` to the return type of the `impl_subject` query and removes `bound_impl_subject`.
r? ```@lcnr```
don't uniquify regions when canonicalizing
uniquifying causes a bunch of issues, most notably it causes `AliasEq(<?x as Trait<'a>>::Assoc, <?x as Trait<'a>>::Assoc)` to result in ambiguity because both `normalizes-to` paths result in ambiguity and substs equate should trivially succeed but doesn't because we uniquified `'a` to two different regions.
I originally added uniquification to make it easier to deal with requirement 6 from the dev-guide: https://rustc-dev-guide.rust-lang.org/solve/trait-solving.html#requirements
> ### 6. Trait solving must be (free) lifetime agnostic
>
> Trait solving during codegen should have the same result as during typeck. As we erase
> all free regions during codegen we must not rely on them during typeck. A noteworthy example
> is special behavior for `'static`.
cc https://github.com/rust-lang/rustc-dev-guide/pull/1671
Relying on regions being identical may cause ICE during MIR typeck, but even without this PR we can end up relying on that as type inference vars can resolve to types which contain an identical region. Let's land this and deal with any ICE that crop up as we go. Will look at this issue again before stabilization.
r? ```@compiler-errors```
Improve safe transmute error reporting
This patch updates the error reporting when Safe Transmute is not possible between 2 types by including the reason.
Also, fix some small bugs that occur when computing the `Answer` for transmutability.
This patch updates the error reporting when Safe Transmute is not
possible between 2 types by including the reason.
Also, fix some small bugs that occur when computing the `Answer` for
transmutability.
Check for body owner fallibly in error reporting
Sometimes the "body id" we use for an obligation cause is not actually a body owner, like when we're doing WF checking on items.
Fixes#110157
cleanup our region error API
- require `TypeErrCtxt` to always result in an error, closing #108810
- move `resolve_regions_and_report_errors` to the `ObligationCtxt`
- call `process_registered_region_obligations` in `resolve_regions`
- move `resolve_regions` into the `outlives` submodule
- add `#[must_use]` to functions returning lists of errors
r? types
I'm surprised the compiler doesn't warn about these. It appears having
an `impl` on a struct is enough to avoid a warning about it never being
constructed.
Split implied and super predicate queries, then allow elaborator to filter only supertraits
Split the `super_predicates_of` query into a new `implied_predicates_of` query. The former now only returns the *real* supertraits of a trait alias, and the latter now returns the implied predicates (which include all of the `where` clauses of the trait alias). The behavior of these queries is identical for regular traits.
Now that the two queries are split, we can add a new filter method to the elaborator, `filter_only_self()`, which can be used in instances that we need only the *supertrait* predicates, such as during the elaboration used in closure signature deduction. This toggles the usage of `super_predicates_of` instead of `implied_predicates_of` during elaboration of a trait predicate.
This supersedes #104745, and fixes the four independent bugs identified in that PR.
Fixes#104719Fixes#106238Fixes#110023Fixes#109514
r? types
- require `TypeErrCtxt` to always result in an error
- move `resolve_regions_and_report_errors` to the `ObligationCtxt`
- merge `process_registered_region_obligations` into `resolve_regions`
Support safe transmute in new solver
Basically copies the same implementation as the old solver, but instead of looking for param types, we look for type or const placeholders.
Enforce that `PointerLike` requires a pointer-like ABI
At least temporarily, let's ban coercing things that are pointer-sized and pointer-aligned but *not* `Abi::Scalar(..)` into `dyn*`. See: https://github.com/rust-lang/rust/pull/104694#discussion_r1142522073
This can be lifted in the future if we decie that we *want* to be able to coerce something `repr(C)` into a `dyn*`, but we'll have to figure out what to do with Miri and codegen...
r? compiler
Make elaboration generic over input
Combines all the `elaborate_*` family of functions into just one, which is an iterator over the same type that you pass in (e.g. elaborating `Predicate` gives `Predicate`s, elaborating `Obligation`s gives `Obligation`s, etc.)
Implement support for `GeneratorWitnessMIR` in new solver
r? ```@cjgillot```
I mostly want this to cut down the number of failing UI tests when running the UI test suite with `--compare-mode=next-solver`, but there doesn't seem like much reason to block implementing this since it adds minimal complexity to the existing structural traits impl in the new solver.
If others are against adding this for some reason, then maybe we should just make `GeneratorWitnessMIR` return `NoSolution` for these traits. Anything but an ICE please 😸🧊
Tweak debug outputs to make debugging new solver easier
1. Move the fields that are "most important" (I know this is subjective) to the beginning of the structs.
For goals, I typically care more about the predicate than the param-env (which is significantly longer in debug output).
For canonicalized things, I typically care more about what is *being* canonicalized.
For a canonical response, I typically care about the response -- or at least, it's typically useful to put it first since it's short and affects the whether the solver recurses or not...
2. Add some more debug and instrument calls to functions to add more structure to tracing lines.
r? `@oli-obk` or `@BoxyUwU` (since I think `@lcnr` is on holiday)
Remove `intercrate` and `mark_ambiguous` from `TypeRelation`
Fixes#109863
Pulls this logic into `super_combine_tys`, which has access to `InferCtxt` and takes a `ObligationEmittingRelation` -- both of which simplify the logic here.
r? `@oli-obk` `@aliemjay`
This solves a regression where `0.0.cmp()` was ambiguous when a custom
trait with a `cmp` method was in scope.
FOr integers it shouldn't be a problem in practice so I wasn't able to
add a test.
Update `ty::VariantDef` to use `IndexVec<FieldIdx, FieldDef>`
And while doing the updates for that, also uses `FieldIdx` in `ProjectionKind::Field` and `TypeckResults::field_indices`.
There's more places that could use it (like `rustc_const_eval` and `LayoutS`), but I tried to keep this PR from exploding to *even more* places.
Part 2/? of https://github.com/rust-lang/compiler-team/issues/606
Closures always implement `FnOnce` in new solver
We should process `[closure]: FnOnce(Tys...) -> Ty` obligations *before* fallback and closure analysis. We can do this by taking advantage of the fact that `FnOnce` is always implemented by closures, even before we definitely know the closure kind.
Fixescompiler-errors/next-solver-hir-issues#15
r? ``@oli-obk`` (trying to spread the reviewer load for new trait solver prs, and this one is pretty self-contained, though feel free to reassign 😸)
Freshen normalizes-to hack goal RHS in the evaluate loop
Ensure that we repeatedly equate the unconstrained RHS of the normalizes-to hack goal with the *actual* RHS of the goal, even if the normalizes-to goal loops several times and thus we replace the unconstrained RHS var repeatedly.
Alternative to #109583.
And while doing the updates for that, also uses `FieldIdx` in `ProjectionKind::Field` and `TypeckResults::field_indices`.
There's more places that could use it (like `rustc_const_eval` and `LayoutS`), but I tried to keep this PR from exploding to *even more* places.
Part 2/? of https://github.com/rust-lang/compiler-team/issues/606
Canonicalize float var as float in new solver
Typo in new canonicalizer -- we should be canonicalizing float vars as `CanonicalTyVarKind::Float`, not `CanonicalTyVarKind::Int`.
Fixescompiler-errors/next-solver-hir-issues#9
Don't ICE on `DiscriminantKind` projection in new solver
As title says, since we now actually call `Ty::discriminant_kind` on placeholder types 😃
Also drive-by simplify `Pointee::Metadata` projection logic, and fix the UI test because the `<T as Pointee>::Metadata` tests weren't actually exercising the new projection logic, since we still eagerly normalize (which hits `project.rs` in the old solver) in HIR typeck.
r? `@lcnr` tho feel free to re-roll, this pr is very low-priority and not super specific to the new trait solver.
Fixescompiler-errors/next-solver-hir-issues#14
Do not consider elaborated projection predicates for objects in new solver
Object types have projection bounds which are elaborated during astconv. There's no need to do it again for projection goals, since that'll give us duplicate projection candidatesd that are distinct up to regions due to the fact that we canonicalize every region to a separate variable. See quick example below the break for a better explanation.
Discussed this with lcnr, and adding a stop-gap until we get something like intersection region constraints (or modify canonicalization to canonicalize identical regions to the same canonical regions) -- after which, this will hopefully not matter and may be removed.
r? `@lcnr`
---
See `tests/ui/traits/new-solver/more-object-bound.rs`:
Consider a goal: `<dyn Iter<'a, ()> as Iterator>::Item = &'a ()`.
After canonicalization: `<dyn Iter<'!0r, (), Item = '!1r ()> as Iterator>::Item == &!'2r ()`
* First object candidate comes from the item bound in the dyn's bounds itself, giving us `<dyn Iter<'!0r, (), Item = '?!r ()> as Iterator>::Item == &!'1r ()`. This gives us one region constraint: `!'1r == !'2r`.
* Second object candidate comes from elaborating the principal trait ref, gives us `<dyn Iter<'!0r, (), Item = '!1r ()> as Iterator>::Item == &!'0r ()`. This gives us one region constraint: `!'0r == !'2r`.
* Oops! Ambiguity!
Rename `IndexVec::last` → `last_index`
As I've been trying to replace a `Vec` with an `IndexVec`, having `last` exist on both but returning very different types makes the transition a bit awkward -- the errors are later, where you get things like "there's no `ty` method on `mir::Field`" rather than a more localized error like "hey, there's no `last` on `IndexVec`".
So I propose renaming `last` to `last_index` to help distinguish `Vec::last`, which returns an element, and `IndexVec::last_index`, which returns an index.
(Similarly, `Iterator::last` also returns an element, not an index.)
Check for overflow in `assemble_candidates_after_normalizing_self_ty`
Prevents a stack overflow (⚠️❗) in the new solver when we have param-env candidates that look like: `T: Trait<Assoc = <T as Trait>::Assoc>`
The current error message looks bad, but that's because we don't distinguish overflow and other ambiguity errors. I'll break that out into a separate PR since the fix may be controversial.
r? `@lcnr`
As I've been trying to replace a `Vec` with an `IndexVec`, having `last` exist on both but returning very different types makes the transition a bit awkward -- the errors are later, where you get things like "there's no `ty` method on `mir::Field`" rather than a more localized error like "hey, there's no `last` on `IndexVec`".
So I propose renaming `last` to `last_index` to help distinguish `Vec::last`, which returns an element, and `IndexVec::last_index`, which returns an index.
(Similarly, `Iterator::last` also returns an element, not an index.)
Rollup of 8 pull requests
Successful merges:
- #91793 (socket ancillary data implementation for FreeBSD (from 13 and above).)
- #92284 (Change advance(_back)_by to return the remainder instead of the number of processed elements)
- #102472 (stop special-casing `'static` in evaluation)
- #108480 (Use Rayon's TLV directly)
- #109321 (Erase impl regions when checking for impossible to eagerly monomorphize items)
- #109470 (Correctly substitute GAT's type used in `normalize_param_env` in `check_type_bounds`)
- #109562 (Update ar_archive_writer to 0.1.3)
- #109629 (remove obsolete `givens` from regionck)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup