const_generics: correctly deal with bound variables
removes the hack in `resolve` which was needed because we evaluated constants without caring about their bound variables.
Each commit should be fairly self-contained, even if they build on each other
r? `@jackh726`
Migrate another part of rustc_infer to session diagnostic
Probably will migrate another file before marking this one as ready-to-merge.
`@rustbot` label +A-translation
r? rust-lang/diagnostics
cc https://github.com/rust-lang/rust/issues/100717
Update `SessionDiagnostic::into_diagnostic` to take `Handler` instead of `ParseSess`
Suggested by the team in [this Zulip Topic](https://rust-lang.zulipchat.com/#narrow/stream/336883-i18n/topic/.23100717.20SessionDiagnostic.20on.20Handler).
`Handler` already has almost all the capabilities of `ParseSess` when it comes to diagnostic emission, in this migration we only needed to add the ability to access `source_map` from the emitter in order to get a `Snippet` and the `start_point`. Not sure if adding these two methods [`span_to_snippet_from_emitter` and `span_start_point_from_emitter`] is the best way to address this gap.
P.S. If this goes in the right direction, then we probably may want to move `SessionDiagnostic` to `rustc_errors` and rename it to `DiagnosticHandler` or something similar.
r? `@davidtwco`
r? `@compiler-errors`
Suggested by the team in this Zulip Topic https://rust-lang.zulipchat.com/#narrow/stream/336883-i18n/topic/.23100717.20SessionDiagnostic.20on.20Handler
Handler already has almost all the capabilities of ParseSess when it comes to diagnostic emission, in this migration we only needed to add the ability to access source_map from the emitter in order to get a Snippet and the start_point. Not sure if this is the best way to address this gap
This PR will fix some typos detected by [typos].
I only picked the ones I was sure were spelling errors to fix, mostly in
the comments.
[typos]: https://github.com/crate-ci/typos
Attempt to normalize `FnDef` signature in `InferCtxt::cmp`
Stashes a normalization callback in `InferCtxt` so that the signature we get from `tcx.fn_sig(..).subst(..)` in `InferCtxt::cmp` can be properly normalized, since we cannot expect for it to have normalized types since it comes straight from astconv.
This is kind of a hack, but I will say that `@jyn514` found the fact that we present unnormalized types to be very confusing in real life code, and I agree with that feeling. Though altogether I am still a bit unsure about whether this PR is worth the effort, so I'm open to alternatives and/or just closing it outright.
On the other hand, this isn't a ridiculously heavy implementation anyways -- it's less than a hundred lines of changes, and half of that is just miscellaneous cleanup.
This is stacked onto #100471 which is basically unrelated, and it can be rebased off of that when that lands or if needed.
---
The code:
```rust
trait Foo { type Bar; }
impl<T> Foo for T {
type Bar = i32;
}
fn foo<T>(_: <T as Foo>::Bar) {}
fn needs_i32_ref_fn(f: fn(&'static i32)) {}
fn main() {
needs_i32_ref_fn(foo::<()>);
}
```
Before:
```
= note: expected fn pointer `fn(&'static i32)`
found fn item `fn(<() as Foo>::Bar) {foo::<()>}`
```
After:
```
= note: expected fn pointer `fn(&'static i32)`
found fn item `fn(i32) {foo::<()>}`
```
Do not leak type variables from opaque type relation
The "root cause" is that we call `InferCtxt::resolve_vars_if_possible` (3d9dd681f5) on the types we get back in `TypeError::Sorts` since I added a call to it in `InferCtxt::same_type_modulo_infer`. However if this `TypeError` comes from a `InferCtxt::commit_if_ok`, then it may reference type variables that do not exist anymore, which is problematic.
We avoid this by substituting the `TypeError` with the types we had before being generalized while handling opaques.
This is kinda gross, and I feel like we can get the same issue from other places where we generalize type/const inference variables. Maybe not? I don't know.
Fixes#99914Fixes#99970Fixes#100463
Rollup of 9 pull requests
Successful merges:
- #95376 (Add `vec::Drain{,Filter}::keep_rest`)
- #100092 (Fall back when relating two opaques by substs in MIR typeck)
- #101019 (Suggest returning closure as `impl Fn`)
- #101022 (Erase late bound regions before comparing types in `suggest_dereferences`)
- #101101 (interpret: make read-pointer-as-bytes a CTFE-only error with extra information)
- #101123 (Remove `register_attr` feature)
- #101175 (Don't --bless in pre-push hook)
- #101176 (rustdoc: remove unused CSS selectors for `.table-display`)
- #101180 (Add another MaybeUninit array test with const)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Fall back when relating two opaques by substs in MIR typeck
This is certainly _one_ way to fix#100075. Not really confident it's the _best_ way to do it, though.
The root cause of this issue is that during MIR type-check, we end up trying to equate an opaque against the same opaque def-id but with different substs. Because of the way that we replace RPITs during (HIR) typeck with an inference variable, we don't end up emitting a type-checking error, so the delayed MIR bug causes an ICE.
See the `src/test/ui/impl-trait/issue-100075-2.rs` test below to make that clear -- in that example, we try to equate `{impl Sized} substs=[T]` and `{impl Sized} substs=[Option<T>]`, which causes an ICE. This new logic will instead cause us to infer `{impl Sized} substs=[Option<T>]` as the hidden type for `{impl Sized} substs=[T]`, which causes a proper error to be emitted later on when we check that an opaque isn't recursive.
I'm open to closing this in favor of something else. Ideally we'd fix this in typeck, but the thing we do to ensure backwards compatibility with weird RPIT cases makes that difficult. Also open to discussing this further.
Revert let_chains stabilization
This is the revert against master, the beta revert was already done in #100538.
Bumps the stage0 compiler which already has it reverted.
Rollup of 7 pull requests
Successful merges:
- #100898 (Do not report too many expr field candidates)
- #101056 (Add the syntax of references to their documentation summary.)
- #101106 (Rustdoc-Json: Retain Stripped Modules when they are imported, not when they have items)
- #101131 (CTFE: exposing pointers and calling extern fn is just impossible)
- #101141 (Simplify `get_trait_ref` fn used for `virtual_function_elimination`)
- #101146 (Various changes to logging of borrowck-related code)
- #101156 (Remove `Sync` requirement from lint pass objects)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Remove separate indexing of early-bound regions
~Based on https://github.com/rust-lang/rust/pull/99728.~
This PR copies some modifications from https://github.com/rust-lang/rust/pull/97839 around object lifetime defaults.
These modifications allow to stop counting generic parameters during lifetime resolution, and rely on the indexing given by `rustc_typeck::collect`.
InferCtxt tainted_by_errors_flag should be Option<ErrorGuaranteed>
Fixes#100321.
Use Cell<Option<ErrorGuaranteed>> to guarantee that we emit an error when that flag is set.
Make `same_type_modulo_infer` a proper `TypeRelation`
Specifically, this fixes#100690 because we no longer consider a `ReLateBound` and a `ReVar` to be equal. `ReVar` can only be equal to free regions or static.
Revert "Rollup merge of #97346 - JohnTitor:remove-back-compat-hacks, …
…r=oli-obk"
This reverts commit c703d11dcc, reversing
changes made to 64eb9ab869.
it didn't apply cleanly, so now it works the same for RPIT and for TAIT instead of just working for RPIT, but we should keep those in sync anyway. It also exposed a TAIT bug (see the feature gated test that now ICEs).
r? `@pnkfelix`
fixes#99536
remove `commit_unconditionally`
`commit_unconditionally` is a noop unless we somehow inspect the current state of our snapshot. The only thing which does that is the leak check which was only used in one place where `commit_if_ok` is probably at least as, or even more, correct.
r? rust-lang/types
make `PlaceholderConst` not store the type of the const
Currently the `Placeholder` variant on `ConstKind` is 28 bytes when with this PR its 8 bytes, i am not sure this is really useful at all rn since `Unevaluated` and `Value` variants are huge still but eventually it should be possible to get both down to 16 bytes 🤔. Mostly opening this to see if this change has any perf impact when done before it can make `ConstKind`/`ConstS` smaller
`codegen_fulfill_obligation` expect erased regions
it's a query, so by erasing regions before calling it, we get better caching.
This doesn't actually change anything as its already the status quo.
use `check_region_obligations_and_report_errors` to avoid ICEs
If we don't call `process_registered_region_obligations` before `resolve_regions_and_report_errors` then we'll ICE if we have any region obligations, and `check_region_obligations_and_report_errors` just does both of these for us in a nice convenient function.
Fixes#53475
r? types
Previously, `infcx.instantiate_canonical_*` maps the root universe in `canonical` into `ty::UniverseIndex::Root`, I think because it assumes it works with a fresh `infcx` but this is not true for the use cases in mir typeck. Now the root universe is mapped into `infcx.universe()`.
I catched this accidentally while reviewing the code. I'm not sure if this is the right fix or if it is really a bug!
Check that RPITs constrained by a recursive call in a closure are compatible
Fixes#99073
Adapts a similar visitor pattern to `find_opaque_ty_constraints` (that we use to check TAITs), but with some changes:
0. Only walk the "OnlyBody" children, instead of all items in the RPIT's defining scope
1. Only walk through the body's children if we found a constraining usage
2. Don't actually do any inference, just do a comparison and error if they're mismatched
----
r? `@oli-obk` -- you know all this impl-trait stuff best... is this the right approach? I can explain the underlying issue better if you'd like, in case that might reveal a better solution. Not sure if it's possible to gather up the closure's defining usages of the RPIT while borrowck'ing the outer function, that might be a better place to put this check...
Use full type name instead of just saying `impl Trait` in "captures lifetime" error
I think this is very useful, especially when there's >1 `impl Trait`, and it just means passing around a bit more info that we already have access to.
handle consts with param/infer in `const_eval_resolve` better
This PR addresses [this thread here](https://github.com/rust-lang/rust/pull/99449#discussion_r924141230). Was this the change you were looking for ``@lcnr?``
Interestingly, one test has begun to pass. Was that expected?
r? ``@lcnr``
Improve suggestions for returning binding
Fixes#99525
Also reworks the cause codes for match and if a bit, I think cleaning them up in a positive way.
We no longer need to call `could_remove_semicolon` in successful code, which might save a few cycles?
Remove the unused StableSet and StableMap types from rustc_data_structures.
The current implementation is not "stable" in the same sense that `HashStable` and `StableHasher` are stable, i.e. across compilation sessions. So, in my opinion, it's better to remove those types (which are basically unused anyway) than to give the wrong impression that these are safe for incr. comp.
I plan to provide new "stable" collection types soon that can be used to replace `FxHashMap` and `FxHashSet` in query results (see [draft](69d03ac7a7)). It's unsound that `HashMap` and `HashSet` implement `HashStable` (see https://github.com/rust-lang/rust/issues/98890 for a recent P-critical bug caused by this) -- so we should make some progress there.
Formalize defining_use_anchor
This tackles issue #57961
Introduces new enum called `DefiningAnchor` that replaces `Option<LocalDefId>` of `defining_use_anchor`. Now every use of it is explicit and exhaustively matched, catching errors like one in the linked issue. This is not a perfect fix but it's a step in the right direction.
r? `@oli-obk`
Do not allow typeck children items to constrain outer RPITs
Fixes#99073 in a simpler and more conservative way than #99079. Simply raise a mismatched types error if we try to constrain an RPIT in an item that isn't the RPIT's parent.
r? `@oli-obk`
Remove some usages of `guess_head_span`
No need to pass things through `guess_head_span` if they already point to the head span.
Only major change is that we point to the head span of `enum`s on some errors now, which I prefer.
r? `@cjgillot`
Move abstract const to middle
Moves AbstractConst (and all associated methods) to rustc middle for use in `rustc_infer`.
This allows for const resolution in infer to use abstract consts to walk consts and check if
they are resolvable.
This attempts to resolve the issue where `Foo<{ concrete const }, generic T>` is incorrectly marked as conflicting, and is independent from the other issue where nested abstract consts must be resolved.
r? `@lcnr`
Implement `for<>` lifetime binder for closures
This PR implements RFC 3216 ([TI](https://github.com/rust-lang/rust/issues/97362)) and allows code like the following:
```rust
let _f = for<'a, 'b> |a: &'a A, b: &'b B| -> &'b C { b.c(a) };
// ^^^^^^^^^^^--- new!
```
cc ``@Aaron1011`` ``@cjgillot``
don't use `commit_if_ok` during `higher_ranked_sub`
This snapshot doesn't really do anything useful for us, especially once we deal with placeholder outlive bounds during trait solving.
I guess that currently the idea is that `higher_ranked_sub` could cause a later `leak_check` to fail even if the combine operation isn't actually relevant. But really, using combine outside of snapshot and ignoring its result is wrong anyways, as it can constrain inference variables.
r? rust-lang/types
don't succeed `evaluate_obligation` query if new opaque types were registered
fixes#98608fixes#98604
The root cause of all this is that in type flag computation we entirely ignore nongeneric things like struct fields and the signature of function items. So if a flag had to be set for a struct if it is set for a field, that will only happen if the field is generic, as only the generic parameters are checked.
I now believe we cannot use type flags to handle opaque types. They seem like the wrong tool for this.
Instead, this PR replaces the previous logic by adding a new variant of `EvaluatedToOk`: `EvaluatedToOkModuloOpaqueTypes`, which says that there were some opaque types that got hidden types bound, but that binding may not have been legal (because we don't know if the opaque type was in its defining scope or not).
Make TAIT behave exactly like RPIT
fixes https://github.com/rust-lang/rust/issues/96552
This makes type-alias-impl-trait behave like return-position-impl-trait. Unfortunately it also causes some cases to stop compiling due to "needing type annotations" and makes panicking cause fallback for the hidden type to `()`.
All of these are addressable, but we should probably address them for RPIT and TAIT together
r? ``@lcnr``
Avoid some `&str` to `String` conversions with `MultiSpan::push_span_label`
This patch removes some`&str` to `String` conversions with `MultiSpan::push_span_label`.
Clean up arg mismatch diagnostic, generalize tuple wrap suggestion
This is based on top of #97542, so just look at the last commit which contains the relevant changes.
1. Remove `final_arg_types` which was one of the last places we were using raw (`usize`) indices instead of typed indices in the arg mismatch suggestion code.
2. Improve the tuple wrap suggestion, now we suggest things like `call(a, b, c, d)` -> `call(a, (b, c), d)` 😺
3. Folded in fix#98645
Reverse folder hierarchy
#91318 introduced a trait for infallible folders distinct from the fallible version. For some reason (completely unfathomable to me now that I look at it with fresh eyes), the infallible trait was a supertrait of the fallible one: that is, all fallible folders were required to also be infallible. Moreover the `Error` associated type was defined on the infallible trait! It's so absurd that it has me questioning whether I was entirely sane.
This trait reverses the hierarchy, so that the fallible trait is a supertrait of the infallible one: all infallible folders are required to also be fallible (which is a trivial blanket implementation). This of course makes much more sense! It also enables the `Error` associated type to sit on the fallible trait, where it sensibly belongs.
There is one downside however: folders expose a `tcx` accessor method. Since the blanket fallible implementation for infallible folders only has access to a generic `F: TypeFolder`, we need that trait to expose such an accessor to which we can delegate. Alternatively it's possible to extract that accessor into a separate `HasTcx` trait (or similar) that would then be a supertrait of both the fallible and infallible folder traits: this would ensure that there's only one unambiguous `tcx` method, at the cost of a little additional boilerplate. If desired, I can submit that as a separate PR.
r? ````@jackh726````
fix universes in the NLL type tests
In the NLL code, we were not accommodating universes in the
`type_test` logic.
Fixes#98095.
r? `@compiler-errors`
This breaks some tests, however, so the purpose of this branch is more explanatory and perhaps to do a crater run.
Point at return expression for RPIT-related error
Certainly this needs some diagnostic refining, but I wanted to show that it was possible first and foremost. Not sure if this is the right approach. Open to feedback.
Fixes#80583
lub: don't bail out due to empty binders
allows for the following to compile. The equivalent code using `struct Wrapper<'upper>(fn(&'upper ());` already compiles on stable.
```rust
let _: fn(&'upper ()) = match v {
true => lt_in_fn::<'a>(),
false => lt_in_fn::<'b>(),
};
```
see https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7034a677190110941223cafac6632f70 for a complete example
r? ```@rust-lang/types```
#91318 introduced a trait for infallible folders distinct from the fallible version. For some reason (completely unfathomable to me now that I look at it with fresh eyes), the infallible trait was a supertrait of the fallible one: that is, all fallible folders were required to also be infallible. Moreover the `Error` associated type was defined on the infallible trait! It's so absurd that it has me questioning whether I was entirely sane.
This trait reverses the hierarchy, so that the fallible trait is a supertrait of the infallible one: all infallible folders are required to also be fallible (which is a trivial blanket implementation). This of course makes much more sense! It also enables the `Error` associated type to sit on the fallible trait, where it sensibly belongs.
There is one downside however: folders expose a `tcx` accessor method. Since the blanket fallible implementation for infallible folders only has access to a generic `F: TypeFolder`, we need that trait to expose such an accessor to which we can delegate. Alternatively it's possible to extract that accessor into a separate `HasTcx` trait (or similar) that would then be a supertrait of both the fallible and infallible folder traits: this would ensure that there's only one unambiguous `tcx` method, at the cost of a little additional boilerplate. If desired, I can submit that as a separate PR.
r? @jackh726
The code now accepts `Binder<OutlivesPredicate>`
instead of just `OutlivesPredicate` and thus exercises
the new, generalized `IfEqBound` codepaths. Note though
that we never *produce* Binder<OutlivesPredicate>, so we
are only testing a subset of those codepaths that excludes
actual higher-ranked outlives bounds.
Make `ExprKind::Closure` a struct variant.
Simple refactor since we both need it to introduce additional fields in `ExprKind::Closure`.
r? ``@Aaron1011``
Rename the `ConstS::val` field as `kind`.
And likewise for the `Const::val` method.
Because its type is called `ConstKind`. Also `val` is a confusing name
because `ConstKind` is an enum with seven variants, one of which is
called `Value`. Also, this gives consistency with `TyS` and `PredicateS`
which have `kind` fields.
The commit also renames a few `Const` variables from `val` to `c`, to
avoid confusion with the `ConstKind::Value` variant.
r? `@BoxyUwU`
Remove RegionckMode in favor of calling new skip_region_resolution
Simple cleanup. We can skip a bunch of stuff for places where NLL does the region checking, so skip earlier.
r? rust-lang/types
And likewise for the `Const::val` method.
Because its type is called `ConstKind`. Also `val` is a confusing name
because `ConstKind` is an enum with seven variants, one of which is
called `Value`. Also, this gives consistency with `TyS` and `PredicateS`
which have `kind` fields.
The commit also renames a few `Const` variables from `val` to `c`, to
avoid confusion with the `ConstKind::Value` variant.
Mention `infer::Trace` methods on `infer::At` methods' docs
I missed that you could do `infcx.at(...).trace(...).eq(a, b)` when `a` and `b` dont implement `ToTrace` but does implement `Relate` these docs would have helped see that 😅
This commit makes type folding more like the way chalk does it.
Currently, `TypeFoldable` has `fold_with` and `super_fold_with` methods.
- `fold_with` is the standard entry point, and defaults to calling
`super_fold_with`.
- `super_fold_with` does the actual work of traversing a type.
- For a few types of interest (`Ty`, `Region`, etc.) `fold_with` instead
calls into a `TypeFolder`, which can then call back into
`super_fold_with`.
With the new approach, `TypeFoldable` has `fold_with` and
`TypeSuperFoldable` has `super_fold_with`.
- `fold_with` is still the standard entry point, *and* it does the
actual work of traversing a type, for all types except types of
interest.
- `super_fold_with` is only implemented for the types of interest.
Benefits of the new model.
- I find it easier to understand. The distinction between types of
interest and other types is clearer, and `super_fold_with` doesn't
exist for most types.
- With the current model is easy to get confused and implement a
`super_fold_with` method that should be left defaulted. (Some of the
precursor commits fixed such cases.)
- With the current model it's easy to call `super_fold_with` within
`TypeFolder` impls where `fold_with` should be called. The new
approach makes this mistake impossible, and this commit fixes a number
of such cases.
- It's potentially faster, because it avoids the `fold_with` ->
`super_fold_with` call in all cases except types of interest. A lot of
the time the compile would inline those away, but not necessarily
always.