Commit Graph

4556 Commits

Author SHA1 Message Date
bors
75eff9a574 Auto merge of #132377 - matthiaskrgr:rollup-3p1c6hs, r=matthiaskrgr
Rollup of 3 pull requests

Successful merges:

 - #132368 (Remove `do_not_const_check` from `Iterator` methods)
 - #132373 (Make sure `type_param_predicates` resolves correctly for RPITIT)
 - #132374 (Remove dead code stemming from the old effects desugaring)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-31 00:46:22 +00:00
León Orell Valerian Liehr
a6bbdf0fd4
Remove dead code stemming from the old effects desugaring 2024-10-30 23:55:13 +01:00
Jubilee
7b19508abe
Rollup merge of #132344 - compiler-errors:same-thing, r=lcnr
Merge `HostPolarity` and `BoundConstness`

They're basically the same thing, and I think `BoundConstness` is easier to use.

r? fee1-dead or reassign
2024-10-30 14:01:38 -07:00
Jubilee
847b6fe6b0
Rollup merge of #132246 - workingjubilee:campaign-on-irform, r=compiler-errors
Rename `rustc_abi::Abi` to `BackendRepr`

Remove the confabulation of `rustc_abi::Abi` with what "ABI" actually means by renaming it to `BackendRepr`, and rename `Abi::Aggregate` to `BackendRepr::Memory`. The type never actually represented how things are passed, as that has to have `PassMode` considered, at minimum, but rather it just is how we represented some things to the backend. This conflation arose because LLVM, the primary backend at the time, would lower certain IR forms using certain ABIs. Even that only somewhat was true, as it broke down when one ventured significantly afield of what is described by the System V AMD64 ABI either by using different architectures, ABI-modifying IR annotations, the same architecture **with different ISA extensions enabled**, or other... unexpected delights.

Unfortunately both names are still somewhat of a misnomer right now, as people have written code for years based on this misunderstanding. Still, their original names are even moreso, and for better or worse, this backend code hasn't received as much maintenance as the rest of the compiler, lately. Actually arriving at a correct end-state will simply require us to disentangle a lot of code in order to fix, much of it pointlessly repeated in several places. Thus this is not an "actual fix", just a way to deflect further misunderstandings.
2024-10-30 14:01:37 -07:00
Michael Goulet
802f3a78a6 Merge HostPolarity and BoundConstness 2024-10-30 16:23:16 +00:00
Camille GILLOT
b6e1214ac0 Remap impl-trait lifetimes on HIR instead of AST lowering. 2024-10-30 16:18:50 +00:00
Matthias Krüger
305508f969
Rollup merge of #131856 - lcnr:typing-mode, r=compiler-errors
TypingMode: merge intercrate, reveal, and defining_opaque_types

This adds `TypingMode` and uses it in most places. We do not yet remove `Reveal` from `param_env`s. This and other future work as tracked in #132279 and via `FIXME`s.

Fetching the `TypingMode` of the `InferCtxt` asserts that the `TypingMode` agrees with `ParamEnv::reveal` to make sure we don't introduce any subtle bugs here. This will be unnecessary once `ParamEnv::reveal` no longer exists.

As the `TypingMode` is now a part of the query input, I've merged the coherence and non-coherence caches for the new solver. I've also enabled the local `infcx` cache during coherence by clearing the cache when forking it with a different `TypingMode`.

#### `TypingMode::from_param_env`

I am using this even in cases where I know that the `param_env` will always be `Reveal::UserFacing`. This is to make it easier to correctly refactor this code in the future, any time we use `Reveal::UserFacing` in a body while not defining its opaque types is incorrect and should use a `TypingMode` which only reveals opaques defined by that body instead, cc #124598

r? ``@compiler-errors``
2024-10-30 06:40:34 +01:00
Jubilee Young
7086dd83cc compiler: rustc_abi::Abi => BackendRepr
The initial naming of "Abi" was an awful mistake, conveying wrong ideas
about how psABIs worked and even more about what the enum meant.
It was only meant to represent the way the value would be described to
a codegen backend as it was lowered to that intermediate representation.
It was never meant to mean anything about the actual psABI handling!
The conflation is because LLVM typically will associate a certain form
with a certain ABI, but even that does not hold when the special cases
that actually exist arise, plus the IR annotations that modify the ABI.

Reframe `rustc_abi::Abi` as the `BackendRepr` of the type, and rename
`BackendRepr::Aggregate` as `BackendRepr::Memory`. Unfortunately, due to
the persistent misunderstandings, this too is now incorrect:
- Scattered ABI-relevant code is entangled with BackendRepr
- We do not always pre-compute a correct BackendRepr that reflects how
  we "actually" want this value to be handled, so we leave the backend
  interface to also inject various special-cases here
- In some cases `BackendRepr::Memory` is a "real" aggregate, but in
  others it is in fact using memory, and in some cases it is a scalar!

Our rustc-to-backend lowering code handles this sort of thing right now.
That will eventually be addressed by lifting duplicated lowering code
to either rustc_codegen_ssa or rustc_target as appropriate.
2024-10-29 14:56:00 -07:00
Esteban Küber
5b54286640 Remove detail from label/note that is already available in other note
Remove the "which is required by `{root_obligation}`" post-script in
"the trait `X` is not implemented for `Y`" explanation in E0277. This
information is already conveyed in the notes explaining requirements,
making it redundant while making the text (particularly in labels)
harder to read.

```
error[E0277]: the trait bound `NotCopy: Copy` is not satisfied
  --> $DIR/wf-static-type.rs:10:13
   |
LL | static FOO: IsCopy<Option<NotCopy>> = IsCopy { t: None };
   |             ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`
   |
   = note: required for `Option<NotCopy>` to implement `Copy`
note: required by a bound in `IsCopy`
  --> $DIR/wf-static-type.rs:7:17
   |
LL | struct IsCopy<T:Copy> { t: T }
   |                 ^^^^ required by this bound in `IsCopy`
```
vs the prior

```
error[E0277]: the trait bound `NotCopy: Copy` is not satisfied
  --> $DIR/wf-static-type.rs:10:13
   |
LL | static FOO: IsCopy<Option<NotCopy>> = IsCopy { t: None };
   |             ^^^^^^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `NotCopy`, which is required by `Option<NotCopy>: Copy`
   |
   = note: required for `Option<NotCopy>` to implement `Copy`
note: required by a bound in `IsCopy`
  --> $DIR/wf-static-type.rs:7:17
   |
LL | struct IsCopy<T:Copy> { t: T }
   |                 ^^^^ required by this bound in `IsCopy`
```
2024-10-29 16:26:57 +00:00
lcnr
524a22e790 rebase 2024-10-29 17:07:32 +01:00
lcnr
f51ec110a7 TypingMode 🤔 2024-10-29 17:01:24 +01:00
Michael Goulet
599ffab6cd Remove region from adjustments 2024-10-29 01:34:06 +00:00
Michael Goulet
8b7b8e5f56 Hack out effects support for old solver 2024-10-28 21:42:14 +00:00
许杰友 Jieyou Xu (Joe)
3e3feac7c3
Rollup merge of #132243 - compiler-errors:no-span, r=jieyouxu
Remove `ObligationCause::span()` method

I think it's an incredibly confusing footgun to expose both `obligation_cause.span` and `obligation_cause.span()`. Especially because `ObligationCause::span()` (the method) seems to just be hacking around a single quirk in the way we set up obligation causes for match arms.

First commit removes the need for that hack, with only one diagnostic span changing (but IMO not really getting worse -- I'd argue that it was already confusing).
2024-10-28 13:36:21 +08:00
许杰友 Jieyou Xu (Joe)
20d2a546fa
Rollup merge of #132086 - estebank:long-types, r=jieyouxu
Tweak E0277 highlighting and "long type" path printing

Partially address #132013.

![Output from this PR for the repro case in #132013](https://github.com/user-attachments/assets/a073ba37-4adc-411e-81f7-6cb9a945ce3d)
2024-10-28 13:36:18 +08:00
Michael Goulet
7f54b9ecef Remove ObligationCause::span() method 2024-10-27 23:54:06 +00:00
Michael Goulet
2507e83d7b Stop using the whole match expr span for an arm's obligation span 2024-10-27 22:48:03 +00:00
Ralf Jung
8849ac6042 tcx.is_const_fn doesn't work the way it is described, remove it
Then we can rename the _raw functions to drop their suffix, and instead
explicitly use is_stable_const_fn for the few cases where that is really what
you want.
2024-10-25 20:52:39 +02:00
Esteban Küber
5980a32ef1 Pass long type path into note_obligation_cause_code to avoid printing same path multiple times
Because `note_obligation_cause_code` is recursive, if multiple types are too
long to print to the terminal, a `long_ty_file` will be created. Before, one was
created *per recursion*. Now, it is passed in so it gets printed only once.

Part of #132013.
2024-10-25 18:06:39 +00:00
Esteban Küber
aa82fd6d1d Tweak highlighting when trait is available for different type
When printing

```
  = help: the trait `chumsky::private::ParserSealed<'_, &'a str, ((), ()), chumsky::extra::Full<EmptyErr, (), ()>>` is implemented for `Then<Ignored<chumsky::combinator::Filter<chumsky::primitive::Any<&str, chumsky::extra::Full<EmptyErr, (), ()>>, {closure@src/main.rs:9:17: 9:27}>, char>, chumsky::combinator::Map<impl CSTParser<'a, O>, O, {closure@src/main.rs:11:24: 11:27}>, (), (), chumsky::extra::Full<EmptyErr, (), ()>>`
  = help: for that trait implementation, expected `((), ())`, found `()`
```

Highlight only the `expected` and `found` types, instead of the full type in the first `help`.
2024-10-25 18:06:39 +00:00
bors
1d4a7670d4 Auto merge of #131985 - compiler-errors:const-pred, r=fee1-dead
Represent trait constness as a distinct predicate

cc `@rust-lang/project-const-traits`
r? `@ghost` for now

Also mirrored everything that is written below on this hackmd here: https://hackmd.io/`@compiler-errors/r12zoixg1l`

# Tl;dr:

* This PR removes the bulk of the old effect desugaring.
* This PR reimplements most of the effect desugaring as a new predicate and set of a couple queries. I believe it majorly simplifies the implementation and allows us to move forward more easily on its implementation.

I'm putting this up both as a request for comments and a vibe-check, but also as a legitimate implementation that I'd like to see land (though no rush of course on that last part).

## Background

### Early days

Once upon a time, we represented trait constness in the param-env and in `TraitPredicate`. This was very difficult to implement correctly; it had bugs and was also incomplete; I don't think this was anyone's fault though, it was just the limit of experimental knowledge we had at that point.

Dealing with `~const` within predicates themselves meant dealing with constness all throughout the trait solver. This was difficult to keep track of, and afaict was not handled well with all the corners of candidate assembly.

Specifically, we had to (in various places) remap constness according to the param-env constness:

574b64a97f/compiler/rustc_trait_selection/src/traits/select/mod.rs (L1498)

This was annoying and manual and also error prone.

### Beginning of the effects desugaring

Later on, #113210 reimplemented a new desugaring for const traits via a `<const HOST: bool>` predicate. This essentially "reified" the const checking and separated it from any of the remapping or separate tracking in param-envs. For example, if I was in a const-if-const environment, but I wanted to call a trait that was non-const, this reification would turn the constness mismatch into a simple *type* mismatch of the effect parameter.

While this was a monumental step towards straightening out const trait checking in the trait system, it had its own issues, since that meant that the constness of a trait (or any item within it, like an associated type) was *early-bound*. This essentially meant that `<T as Trait>::Assoc` was *distinct* from `<T as ~const Trait>::Assoc`, which was bad.

### Associated-type bound based effects desugaring

After this, #120639 implemented a new effects desugaring. This used an associated type to more clearly represent the fact that the constness is not an input parameter of a trait, but a property that could be computed of a impl. The write-up linked in that PR explains it better than I could.

However, I feel like it really reached the limits of what can comfortably be expressed in terms of associated type and trait calculus. Also, `<const HOST: bool>` remains a synthetic const parameter, which is observable in nested items like RPITs and closures, and comes with tons of its own hacks in the astconv and middle layer.

For example, there are pieces of unintuitive code that are needed to represent semantics like elaboration, and eventually will be needed to make error reporting intuitive, and hopefully in the future assist us in implementing built-in traits (eventually we'll want something like `~const Fn` trait bounds!).

elaboration hack: 8069f8d17a/compiler/rustc_type_ir/src/elaborate.rs (L133-L195)

trait bound remapping hack for diagnostics: 8069f8d17a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs (L2370-L2413)

I want to be clear that I don't think this is a issue of implementation quality or anything like that; I think it's simply a very clear sign that we're using types and traits in a way that they're not fundamentally supposed to be used, especially given that constness deserves to be represented as a first-class concept.

### What now?

This PR implements a new desugaring for const traits. Specifically, it introduces a `HostEffect` predicate to represent the obligation an impl is const, rather than using associated type bounds and the compat trait that exists for effects today.

### `HostEffect` predicate

A `HostEffect` clause has two parts -- the `TraitRef` we're trying to prove, and a `HostPolarity::{Maybe, Const}`.

`HostPolarity::Const` corresponds to `T: const Trait` bounds, which must *always* be proven as const, and which can be written in any context. These are lowered directly into the predicates of an item, since they're not "context-specific".

On the other hand, `HostPolarity::Maybe` corresponds to `T: ~const Trait` bounds which must only exist in a conditionally-const context like a method in a `#[const_trait]`, or a `const fn` free function. We do not lower these immediately into the predicates of an item; instead, we collect them into a new query called the **`const_conditions`**. These are the set of trait refs that we need to prove have const implementations for an item to be const.

Notably, they're represented as bare (poly) trait refs because they are meant to be paired back together with a `HostPolarity` when they're being registered in typeck (see next section).

For example, given:

```rust
const fn foo<T: ~const A + const B>() {}
```

`foo`'s const conditions would contain `T: A`, but not `T: B`. On the flip side, foo's predicates (`predicates_of`) query would contain `HostEffect(T: B, HostPolarity::Const)` but not `HostEffect(T: A, HostPolarity::Maybe)` since we don't need to prove that predicate in a non-const environment (and it's not even the right predicate to prove in an unconditionally const environment).

### Type checking const bodies

When type checking bodies in HIR, when we encounter a call expression, we additionally register the callee item's const conditions with the `HostPolarity` from the body we're typechecking (`Const` for unconditionally const things like `const`/`static` items, and `Maybe` for conditionally const things like const fns; and we don't register `HostPolarity` predicates for non-const bodies).

When type-checking a conditionally const body, we augment its param-env with `HostEffect(..., Maybe)` predicates.

### Checking that const impls are WF

We extend the logic in `compare_method_predicate_entailment` to also check the const-conditions of the impl method, to make sure that we error for:

```rust
#[const_trait] Bar {}
#[const_trait] trait Foo {
    fn method<T: Bar>();
}

impl Foo for () {
    fn method<T: ~const Bar>() {} // stronger assumption!
}
```

We also extend the WF check for impls to register the const conditions of the trait that is being implemented. This is to make sure we error for:

```rust
#[const_trait] trait Bar {}
#[const_trait] trait Foo<T> where T: ~const Bar {}

impl<T> const Foo<T> for () {}
//~^ `T: ~const Bar` is missing!
```

### Proving a `HostEffect` predicate

We have several ways of proving a `HostEffect` predicate:

1. Matching a `HostEffect` predicate from the param-env
2. From an impl - we do impl selection very similar to confirming a trait goal, except we filter for only const impls, and we additionally register the impl's const conditions (i.e. the impl's `~const` where clauses).

Later I expect that we will add more built-in implementations for things like `Fn`.

## What next?

After this PR, I'd like to split out the work more so it can proceed in parallel and probably amongst others that are not me.

* Register `HostEffect` goal for places in HIR typeck that correspond to call terminators, like autoderef.
* Make traits in libstd const again.
    * Probably need to impl host effect preds in old solver.
* Implement built-in `HostEffect` rules for traits like `Fn`.
* Rip out const checking from MIR altogether.

## So what?

This ends up being super convenient basically everywhere in the compiler. Due to the design of the new trait solver, we end up having an almost parallel structure to the existing trait and projection predicates for assembling `HostEffect` predicates; adding new candidates and especially new built-in implementations is now basically trivial, and it's quite straightforward to understand the confirmation logic for these predicates.

Same with diagnostics reporting; since we have predicates which represent the obligation to prove an impl is const, we can simplify and make these diagnostics richer without having to write a ton of logic to intercept and rewrite the existing `Compat` trait errors.

Finally, it gives us a much more straightforward path for supporting the const effect on the old trait solver. I'm personally quite passionate about getting const trait support into the hands of users without having to wait until the new solver lands[^1], so I think after this PR lands we can begin to gauge how difficult it would be to implement constness in the old trait solver too. This PR will not do this yet.

[^1]: Though this is not a prerequisite or by any means the only justification for this PR.
2024-10-24 17:33:42 +00:00
Michael Goulet
cde29b9ec9 Implement const effect predicate in new solver 2024-10-24 09:46:36 +00:00
Michael Goulet
a16d491054 Remove associated type based effects logic 2024-10-24 09:46:36 +00:00
Matthias Krüger
0470728e94
Rollup merge of #132084 - compiler-errors:param-env-with-err, r=lcnr,estebank
Consider param-env candidates even if they have errors

I added this logic in https://github.com/rust-lang/rust/pull/106309, but frankly I don't know why -- the logic was a very large hammer. It seems like recent changes to error tainting has made that no longer necessary.

Ideally we'd rework the way we handle error reporting in all of candidate assembly to be a bit more responsible; we're just suppressing candidates all willy-nilly and it leads to mysterious *other* errors cropping up, like the one that #132082 originally wanted to fix.

**N.B.** This has the side-effect of turning a failed resolution like `where Missing: Sized` into a trivial where clause that matches all types, but also I don't think it really matters?

I'm putting this up as an alternative to #132082, since that PR doesn't address the case when one desugars the APIT into a regular type param.

r? lcnr vibeck
2024-10-24 10:35:40 +02:00
Michael Goulet
4217b8702d Deeply normalize type trace in type error reporting 2024-10-24 02:48:28 +00:00
Michael Goulet
1920c66a8d Plumb through param_env to note_type_err 2024-10-24 02:48:08 +00:00
Michael Goulet
d8dc31fd3d Consider param-env candidates even if they have errors 2024-10-24 01:48:44 +00:00
bors
be01dabfef Auto merge of #132027 - RalfJung:lang-feature-bool-fields, r=nnethercote
nightly feature tracking: get rid of the per-feature bool fields

The `struct Features` that tracks which features are enabled has a ton of public `bool`-typed fields that are basically caching the result of looking up the corresponding feature in `enabled_lang_features`. Having public fields with an invariant is not great, so at least they should be made private. However, it turns out caching these lookups is actually [not worth it](https://github.com/rust-lang/rust/pull/131321#issuecomment-2402068336), so this PR just entirely gets rid of these fields. (The alternative would be to make them private and have a method for each of them to expose them in a read-only way. Most of the diff of this PR would be the same in that case.)

r? `@nnethercote`
2024-10-23 12:16:41 +00:00
Ralf Jung
ad3991d303 nightly feature tracking: get rid of the per-feature bool fields 2024-10-23 09:14:41 +01:00
bors
9abfcb4900 Auto merge of #132053 - matthiaskrgr:rollup-u5ds6i3, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #131707 (Run most `core::num` tests in const context too)
 - #132002 (abi/compatibility: also test Option-like types)
 - #132026 (analyse: remove unused uncanonicalized field)
 - #132031 (Optimize `Rc<T>::default`)
 - #132040 (relnotes: fix stabilizations of `assume_init`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-23 05:57:00 +00:00
Matthias Krüger
5b602201ed
Rollup merge of #132026 - lcnr:stabilize-coherence-again, r=compiler-errors
analyse: remove unused uncanonicalized field

This field is unused and was only relevant when actually printing proof trees. Right now this simply causes proof tree building to leak a bunch of inference vars 😁

r? ``@compiler-errors``
2024-10-23 06:51:24 +02:00
Michael Goulet
febb3f7c88 Represent TraitBoundModifiers as distinct parts in HIR 2024-10-22 19:48:44 +00:00
Matthias Krüger
457087ed29
Rollup merge of #131549 - compiler-errors:try-in-sync, r=spastorino
Add a note for `?` on a `impl Future<Output = Result<..>>` in sync function

It's confusing to `?` a future of a result in a sync function. We have a suggestion to `.await` it if we're in an async function, but not a sync function. Note that this is the case for sync functions, at least.

Let's be a bit more vague about a fix, since it's somewhat context dependent. For example, you could block on it, or you could make your function asynchronous. 🤷
2024-10-22 15:28:41 +02:00
lcnr
d6ce2bd1de remove unused field 2024-10-22 08:30:09 +02:00
bors
814df6e50e Auto merge of #131840 - compiler-errors:impossible-maybe, r=lcnr
Dont consider predicates that may hold as impossible in `is_impossible_associated_item`

Use infer vars to account for ambiguities when considering if methods are impossible to instantiate for a given self type. Also while we're at it, let's use the new trait solver instead of `evaluate` since this is used in rustdoc.

r? lcnr
Fixes #131839
2024-10-21 22:58:44 +00:00
lcnr
b64b25b99e normalizes-to disable infer var check 2024-10-21 16:25:42 +02:00
bors
93742bd782 Auto merge of #131988 - matthiaskrgr:rollup-tx173wn, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #126588 (Added more scenarios where comma to be removed in the function arg)
 - #131728 (bootstrap: extract builder cargo to its own module)
 - #131968 (Rip out old effects var handling code from traits)
 - #131981 (Remove the `BoundConstness::NotConst` variant)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-21 06:13:34 +00:00
Matthias Krüger
62b7293a90
Rollup merge of #131981 - compiler-errors:bound-constness, r=cjgillot
Remove the `BoundConstness::NotConst` variant

I find it easier to represent `BoundConstness::NotConst` as just `None` for some refactorings I'm doing.
2024-10-21 07:01:37 +02:00
bors
f2ba41113d Auto merge of #130950 - compiler-errors:yeet-eval, r=BoxyUwU
Continue to get rid of `ty::Const::{try_}eval*`

This PR mostly does:

* Removes all of the `try_eval_*` and `eval_*` helpers from `ty::Const`, and replace their usages with `try_to_*`.
* Remove `ty::Const::eval`.
* Rename `ty::Const::normalize` to `ty::Const::normalize_internal`. This function is still used in the normalization code itself.
* Fix some weirdness around the `TransmuteFrom` goal.

I'm happy to split it out further; for example, I could probably land the first part which removes the helpers, or the changes to codegen which are more obvious than the changes to tools.

r? BoxyUwU

Part of https://github.com/rust-lang/rust/issues/130704
2024-10-21 03:46:28 +00:00
Michael Goulet
61ed4cb5b4 Remove the BoundConstness::NotConst variant 2024-10-20 18:33:59 +00:00
Michael Goulet
6f6f91ab82 Rip out old effects var handling code from traits 2024-10-20 13:40:22 +00:00
Matthias Krüger
559f8ce726
Rollup merge of #131795 - compiler-errors:expectation, r=Nadrieril
Stop inverting expectation in normalization errors

We have some funky special case logic to invert the expectation and actual type for normalization errors depending on their cause code. IMO most of the error messages get better, except for `try {}` blocks' type expectations. I think that these need to be special cased in some other way, rather than via this hack.

Fixes #131763
2024-10-19 22:00:57 +02:00
Michael Goulet
9453d2cfeb Fix transmute goal 2024-10-19 18:07:35 +00:00
Michael Goulet
38bbcc001e Rename normalize to normalize_internal, remove unnecessary usages 2024-10-19 18:07:35 +00:00
Michael Goulet
e83e4e8112 Get rid of const eval_* and try_eval_* helpers 2024-10-19 18:07:35 +00:00
许杰友 Jieyou Xu (Joe)
765e8c75b0
Rollup merge of #131864 - lrh2000:upcast_reorder, r=WaffleLapkin
Never emit `vptr` for empty/auto traits

Emiting `vptr`s for empty/auto traits is unnecessary (#114942) and causes unsoundness in `trait_upcasting` (#131813). This PR should ensure that we never emit vtables for such traits. See the linked issues for more details.

I'm not sure if I can add tests for the vtable layout. So this PR only adds tests for the soundness hole (i.e., the segmentation fault will disappear after this PR).

Fixes #114942
Fixes #131813

Cc #65991 (tracking issue for `trait_upcasting`)

r? `@WaffleLapkin`  (per https://github.com/rust-lang/rust/issues/131813#issuecomment-2419969745)
2024-10-18 14:52:25 +01:00
Matthias Krüger
13b398401f
Rollup merge of #131857 - WaffleLapkin:dyn-drop-principal-3, r=compiler-errors
Allow dropping dyn principal

Revival of #126660, which was a revival of #114679. Fixes #126313.

Allows dropping principal when coercing trait objects, e.g. `dyn Debug + Send` -> `dyn Send`.

cc `@compiler-errors` `@Jules-Bertholet`
r? `@lcnr`
2024-10-18 06:59:07 +02:00
Ruihan Li
781bff0499 Never emit vptr for empty/auto traits 2024-10-18 12:34:56 +08:00
Matthias Krüger
405eb4178e
Rollup merge of #131825 - lcnr:probe-no-more-leak-2, r=compiler-errors
SolverDelegate add assoc type for Infcx

makes writing trait bounds on it a lot nicer going forward.

r? `@compiler-errors`
2024-10-17 20:47:31 +02:00
Michael Goulet
e3800a1a04 Allow dropping dyn principal 2024-10-17 20:43:31 +02:00
Michael Goulet
8ff8f78e4c Dont consider predicates that may hold as impossible in is_impossible_associated_item 2024-10-17 12:32:31 -04:00
lcnr
c45073ec3e SolverDelegate add assoc type for Infcx 2024-10-17 11:38:40 +02:00
lcnr
3360c1773a move defining_opaque_types out of Canonical 2024-10-17 10:22:52 +02:00
lcnr
f3ce557fcd DropckOutlives to rustc_middle 2024-10-17 09:53:27 +02:00
lcnr
401f9b4e0a ImpliedOutlivesBounds to rustc_middle 2024-10-17 09:53:27 +02:00
bors
798fb83f7d Auto merge of #131797 - matthiaskrgr:rollup-lzpze2k, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #130989 (Don't check unsize goal in MIR validation when opaques remain)
 - #131657 (Rustfmt `for<'a> async` correctly)
 - #131691 (Delay ambiguous intra-doc link resolution after `Cache` has been populated)
 - #131730 (Refactor some `core::fmt` macros)
 - #131751 (Rename `can_coerce` to `may_coerce`, and then structurally resolve correctly in the probe)
 - #131753 (Unify `secondary_span` and `swap_secondary_and_primary` args in `note_type_err`)
 - #131776 (Emscripten: Xfail backtrace ui tests)
 - #131777 (Fix trivially_copy_pass_by_ref in stable_mir)
 - #131778 (Fix needless_lifetimes in stable_mir)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-16 20:50:53 +00:00
Matthias Krüger
80cbc6d40d
Rollup merge of #131753 - compiler-errors:swap-secondary, r=jieyouxu
Unify `secondary_span` and `swap_secondary_and_primary` args in `note_type_err`

Tiny tweak b/c working w `note_type_err` is kinda a mess.
2024-10-16 20:15:55 +02:00
Michael Goulet
99d5f3b280 Stop inverting expectation in normalization errors 2024-10-16 13:44:56 -04:00
Matthias Krüger
aac91f75e3
Rollup merge of #131699 - compiler-errors:better-errors-for-projections, r=lcnr
Try to improve error messages involving aliases in the solver

1. Treat aliases as rigid only if it may not be defined and it's well formed (i.e. for projections, its trait goal is satisfied).
2. Record goals that are related to alias normalization under a new `GoalKind`, so we can look into them in the `BestObligation` visitor.
3. Try to deduplicate errors due to self types of goals that are un-normalizable aliases.

r? lcnr
2024-10-16 19:18:32 +02:00
bors
9618da7c99 Auto merge of #131422 - GnomedDev:smallvec-predicate-obligations, r=compiler-errors
Use `ThinVec` for PredicateObligation storage

~~I noticed while profiling clippy on a project that a large amount of time is being spent allocating `Vec`s for `PredicateObligation`, and the `Vec`s are often quite small. This is an attempt to optimise this by using SmallVec to avoid heap allocations for these common small Vecs.~~

This PR turns all the `Vec<PredicateObligation>` into a single type alias while avoiding referring to `Vec` around it, then swaps the type over to `ThinVec<PredicateObligation>` and fixes the fallout. This also contains an implementation of `ThinVec::extract_if`, copied from `Vec::extract_if` and currently being upstreamed to https://github.com/Gankra/thin-vec/pull/66.

This leads to a small (0.2-0.7%) performance gain in the latest perf run.
2024-10-16 04:06:14 +00:00
Michael Goulet
8528387743 Be better at reporting alias errors 2024-10-15 20:42:17 -04:00
Michael Goulet
50b8029ce1 Always recurse on predicates in BestObligation 2024-10-15 20:36:51 -04:00
bors
e7c0d27507 Auto merge of #131747 - compiler-errors:rollup-0fnymws, r=compiler-errors
Rollup of 7 pull requests

Successful merges:

 - #129794 (uefi: Implement getcwd and chdir)
 - #130568 (Make some float methods unstable `const fn`)
 - #131521 (rename RcBox to RcInner for consistency)
 - #131701 (Don't report `on_unimplemented` message for negative traits)
 - #131705 (Fix most ui tests on emscripten target)
 - #131733 (Fix uninlined_format_args in stable_mir)
 - #131734 (Update `arm64e-apple-tvos` maintainer)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-15 19:55:10 +00:00
Michael Goulet
4886e9a134 Unify secondary_span and swap_secondary_and_primary 2024-10-15 14:39:49 -04:00
Michael Goulet
6558e3470b
Rollup merge of #131701 - compiler-errors:negative-bounds-on-unimplemented, r=lcnr
Don't report `on_unimplemented` message for negative traits

Kinda useless change but it was affecting my ability to read error messages when experimenting with negative bounds.
2024-10-15 12:33:36 -04:00
bors
a0c2aba29a Auto merge of #130654 - lcnr:stabilize-coherence-again, r=compiler-errors
stabilize `-Znext-solver=coherence` again

r? `@compiler-errors`

---

This PR stabilizes the use of the next generation trait solver in coherence checking by enabling `-Znext-solver=coherence` by default. More specifically its use in the *implicit negative overlap check*. The tracking issue for this is https://github.com/rust-lang/rust/issues/114862. Closes #114862.

This is a direct copy of #121848 which has been reverted due to a hang in `nalgebra`: #130056. This hang should have been fixed by #130617 and #130821. See the added section in the stabilization report containing user facing changes merged since the original FCP.

## Background

### The next generation trait solver

The new solver lives in [`rustc_trait_selection::solve`](https://github.com/rust-lang/rust/blob/master/compiler/rustc_trait_selection/src/solve/mod.rs) and is intended to replace the existing *evaluate*, *fulfill*, and *project* implementation. It also has a wider impact on the rest of the type system, for example by changing our approach to handling associated types.

For a more detailed explanation of the new trait solver, see the [rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/solve/trait-solving.html). This does not stabilize the current behavior of the new trait solver, only the behavior impacting the implicit negative overlap check. There are many areas in the new solver which are not yet finalized. We are confident that their final design will not conflict with the user-facing behavior observable via coherence. More on that further down.

Please check out [the chapter](https://rustc-dev-guide.rust-lang.org/solve/significant-changes.html) summarizing the most significant changes between the existing and new implementations.

### Coherence and the implicit negative overlap check

Coherence checking detects any overlapping impls. Overlapping trait impls always error while overlapping inherent impls result in an error if they have methods with the same name. Coherence also results in an error if any other impls could exist, even if they are currently unknown. This affects impls which may get added to upstream crates in a backwards compatible way and impls from downstream crates.

Coherence failing to detect overlap is generally considered to be unsound, even if it is difficult to actually get runtime UB this way. It is quite easy to get ICEs due to bugs in coherence.

It currently consists of two checks:

The [orphan check] validates that impls do not overlap with other impls we do not know about: either because they may be defined in a sibling crate, or because an upstream crate is allowed to add it without being considered a breaking change.

The [overlap check] validates that impls do not overlap with other impls we know about. This is done as follows:
- Instantiate the generic parameters of both impls with inference variables
- Equate the `TraitRef`s of both impls. If it fails there is no overlap.
- [implicit negative]: Check whether any of the instantiated `where`-bounds of one of the impls definitely do not hold when using the constraints from the previous step. If a `where`-bound does not hold, there is no overlap.
- *explicit negative (still unstable, ignored going forward)*: Check whether the any negated `where`-bounds can be proven, e.g. a `&mut u32: Clone` bound definitely does not hold as an explicit `impl<T> !Clone for &mut T` exists.

The overlap check has to *prove that unifying the impls does not succeed*. This means that **incorrectly getting a type error during coherence is unsound** as it would allow impls to overlap: coherence has to be *complete*.

Completeness means that we never incorrectly error. This means that during coherence we must only add inference constraints if they are definitely necessary. During ordinary type checking [this does not hold](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=01d93b592bd9036ac96071cbf1d624a9), so the trait solver has to behave differently, depending on whether we're in coherence or not.

The implicit negative check only considers goals to "definitely not hold" if they could not be implemented downstream, by a sibling, or upstream in a backwards compatible way. If the goal is is "unknowable" as it may get added in another crate, we add an ambiguous candidate: [source](bea5bebf3d/compiler/rustc_trait_selection/src/solve/assembly/mod.rs (L858-L883)).

[orphan check]: fd80c02c16/compiler/rustc_trait_selection/src/traits/coherence.rs (L566-L579)
[overlap check]: fd80c02c16/compiler/rustc_trait_selection/src/traits/coherence.rs (L92-L98)
[implicit negative]: fd80c02c16/compiler/rustc_trait_selection/src/traits/coherence.rs (L223-L281)

## Motivation

Replacing the existing solver in coherence fixes soundness bugs by removing sources of incompleteness in the type system. The new solver separately strengthens coherence, resulting in more impls being disjoint and passing the coherence check. The concrete changes will be elaborated further down. We believe the stabilization to reduce the likelihood of future bugs in coherence as the new implementation is easier to understand and reason about.

It allows us to remove the support for coherence and implicit-negative reasoning in the old solver, allowing us to remove some code and simplifying the old trait solver. We will only remove the old solver support once this stabilization has reached stable to make sure we're able to quickly revert in case any unexpected issues are detected before then.

Stabilizing the use of the next-generation trait solver expresses our confidence that its current behavior is intended and our work towards enabling its use everywhere will not require any breaking changes to the areas used by coherence checking. We are also confident that we will be able to replace the existing solver everywhere, as maintaining two separate systems adds a significant maintainance burden.

## User-facing impact and reasoning

### Breakage due to improved handling of associated types

The new solver fixes multiple issues related to associated types. As these issues caused coherence to consider more types distinct, fixing them results in more overlap errors. This is therefore a breaking change.

#### Structurally relating aliases containing bound vars

Fixes https://github.com/rust-lang/rust/issues/102048. In the existing solver relating ambiguous projections containing bound variables is structural. This is *incomplete* and allows overlapping impls. These was mostly not exploitable as the same issue also caused impls to not apply when trying to use them. The new solver defers alias-relating to a nested goal, fixing this issue:
```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
trait Trait {}

trait Project {
    type Assoc<'a>;
}

impl Project for u32 {
    type Assoc<'a> = &'a u32;
}

// Eagerly normalizing `<?infer as Project>::Assoc<'a>` is ambiguous,
// so the old solver ended up structurally relating
//
//     (?infer, for<'a> fn(<?infer as Project>::Assoc<'a>))
//
// with
//
//     ((u32, fn(&'a u32)))
//
// Equating `&'a u32` with `<u32 as Project>::Assoc<'a>` failed, even
// though these types are equal modulo normalization.
impl<T: Project> Trait for (T, for<'a> fn(<T as Project>::Assoc<'a>)) {}

impl<'a> Trait for (u32, fn(&'a u32)) {}
//[next]~^ ERROR conflicting implementations of trait `Trait` for type `(u32, for<'a> fn(&'a u32))`
```

A crater run did not discover any breakage due to this change.

#### Unknowable candidates for higher ranked trait goals

This avoids an unsoundness by attempting to normalize in `trait_ref_is_knowable`, fixing https://github.com/rust-lang/rust/issues/114061. This is a side-effect of supporting lazy normalization, as that forces us to attempt to normalize when checking whether a `TraitRef` is knowable: [source](47dd709bed/compiler/rustc_trait_selection/src/solve/assembly/mod.rs (L754-L764)).

```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
trait IsUnit {}
impl IsUnit for () {}

pub trait WithAssoc<'a> {
    type Assoc;
}

// We considered `for<'a> <T as WithAssoc<'a>>::Assoc: IsUnit`
// to be knowable, even though the projection is ambiguous.
pub trait Trait {}
impl<T> Trait for T
where
    T: 'static,
    for<'a> T: WithAssoc<'a>,
    for<'a> <T as WithAssoc<'a>>::Assoc: IsUnit,
{
}
impl<T> Trait for Box<T> {}
//[next]~^ ERROR conflicting implementations of trait `Trait`
```
The two impls of `Trait` overlap given the following downstream crate:
```rust
use dep::*;
struct Local;
impl WithAssoc<'_> for Box<Local> {
    type Assoc = ();
}
```

There a similar coherence unsoundness caused by our handling of aliases which is fixed separately in https://github.com/rust-lang/rust/pull/117164.

This change breaks the [`derive-visitor`](https://crates.io/crates/derive-visitor) crate. I have opened an issue in that repo: nikis05/derive-visitor#16.

### Evaluating goals to a fixpoint and applying inference constraints

In the old implementation of the implicit-negative check, each obligation is [checked separately without applying its inference constraints](bea5bebf3d/compiler/rustc_trait_selection/src/traits/coherence.rs (L323-L338)). The new solver instead [uses a `FulfillmentCtxt`](bea5bebf3d/compiler/rustc_trait_selection/src/traits/coherence.rs (L315-L321)) for this, which evaluates all obligations in a loop until there's no further inference progress.

This is necessary for backwards compatibility as we do not eagerly normalize with the new solver, resulting in constraints from normalization to only get applied by evaluating a separate obligation. This also allows more code to compile:
```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
trait Mirror {
    type Assoc;
}
impl<T> Mirror for T {
    type Assoc = T;
}

trait Foo {}
trait Bar {}

// The self type starts out as `?0` but is constrained to `()`
// due to the where-clause below. Because `(): Bar` is known to
// not hold, we can prove the impls disjoint.
impl<T> Foo for T where (): Mirror<Assoc = T> {}
//[current]~^ ERROR conflicting implementations of trait `Foo` for type `()`
impl<T> Foo for T where T: Bar {}

fn main() {}
```
The old solver does not run nested goals to a fixpoint in evaluation. The new solver does do so, strengthening inference and improving the overlap check:
```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
trait Foo {}
impl<T> Foo for (u8, T, T) {}
trait NotU8 {}
trait Bar {}
impl<T, U: NotU8> Bar for (T, T, U) {}

trait NeedsFixpoint {}
impl<T: Foo + Bar> NeedsFixpoint for T {}
impl NeedsFixpoint for (u8, u8, u8) {}

trait Overlap {}
impl<T: NeedsFixpoint> Overlap for T {}
impl<T, U: NotU8, V> Overlap for (T, U, V) {}
//[current]~^ ERROR conflicting implementations of trait `Foo`
```

### Breakage due to removal of incomplete candidate preference

Fixes #107887. In the old solver we incompletely prefer the builtin trait object impl over user defined impls. This can break inference guidance, inferring `?x` in `dyn Trait<u32>: Trait<?x>` to `u32`, even if an explicit impl of `Trait<u64>` also exists.

This caused coherence to incorrectly allow overlapping impls, resulting in ICEs and a theoretical unsoundness. See https://github.com/rust-lang/rust/issues/107887#issuecomment-1997261676. This compiles on stable but results in an overlap error with `-Znext-solver=coherence`:

```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
struct W<T: ?Sized>(*const T);

trait Trait<T: ?Sized> {
    type Assoc;
}

// This would trigger the check for overlap between automatic and custom impl.
// They actually don't overlap so an impl like this should remain possible
// forever.
//
// impl Trait<u64> for dyn Trait<u32> {}
trait Indirect {}
impl Indirect for dyn Trait<u32, Assoc = ()> {}
impl<T: Indirect + ?Sized> Trait<u64> for T {
    type Assoc = ();
}

// Incomplete impl where `dyn Trait<u32>: Trait<_>` does not hold, but
// `dyn Trait<u32>: Trait<u64>` does.
trait EvaluateHack<U: ?Sized> {}
impl<T: ?Sized, U: ?Sized> EvaluateHack<W<U>> for T
where
    T: Trait<U, Assoc = ()>, // incompletely constrains `_` to `u32`
    U: IsU64,
    T: Trait<U, Assoc = ()>, // incompletely constrains `_` to `u32`
{
}

trait IsU64 {}
impl IsU64 for u64 {}

trait Overlap<U: ?Sized> {
    type Assoc: Default;
}
impl<T: ?Sized + EvaluateHack<W<U>>, U: ?Sized> Overlap<U> for T {
    type Assoc = Box<u32>;
}
impl<U: ?Sized> Overlap<U> for dyn Trait<u32, Assoc = ()> {
//[next]~^ ERROR conflicting implementations of trait `Overlap<_>`
    type Assoc = usize;
}
```

### Considering region outlives bounds in the `leak_check`

For details on the `leak_check`, see the FCP proposal #119820.[^leak_check]

[^leak_check]: which should get moved to the dev-guide :3

In both coherence and during candidate selection, the `leak_check` relies on the region constraints added in `evaluate`. It therefore currently does not register outlives obligations: [source](ccb1415eac/compiler/rustc_trait_selection/src/traits/select/mod.rs (L792-L810)). This was likely done as a performance optimization without considering its impact on the `leak_check`. This is the case as in the old solver, *evaluatation* and *fulfillment* are split, with evaluation being responsible for candidate selection and fulfillment actually registering all the constraints.

This split does not exist with the new solver. The `leak_check` can therefore eagerly detect errors caused by region outlives obligations. This improves both coherence itself and candidate selection:

```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
trait LeakErr<'a, 'b> {}
// Using this impl adds an `'b: 'a` bound which results
// in a higher-ranked region error. This bound has been
// previously ignored but is now considered.
impl<'a, 'b: 'a> LeakErr<'a, 'b> for () {}

trait NoOverlapDir<'a> {}
impl<'a, T: for<'b> LeakErr<'a, 'b>> NoOverlapDir<'a> for T {}
impl<'a> NoOverlapDir<'a> for () {}
//[current]~^ ERROR conflicting implementations of trait `NoOverlapDir<'_>`

// --------------------------------------

// necessary to avoid coherence unknowable candidates
struct W<T>(T);

trait GuidesSelection<'a, U> {}
impl<'a, T: for<'b> LeakErr<'a, 'b>> GuidesSelection<'a, W<u32>> for T {}
impl<'a, T> GuidesSelection<'a, W<u8>> for T {}

trait NotImplementedByU8 {}
trait NoOverlapInd<'a, U> {}
impl<'a, T: GuidesSelection<'a, W<U>>, U> NoOverlapInd<'a, U> for T {}
impl<'a, U: NotImplementedByU8> NoOverlapInd<'a, U> for () {}
//[current]~^ conflicting implementations of trait `NoOverlapInd<'_, _>`
```

### Removal of `fn match_fresh_trait_refs`

The old solver tries to [eagerly detect unbounded recursion](b14fd2359f/compiler/rustc_trait_selection/src/traits/select/mod.rs (L1196-L1211)), forcing the affected goals to be ambiguous. This check is only an approximation and has not been added to the new solver.

The check is not necessary in the new solver and it would be problematic for caching. As it depends on all goals currently on the stack, using a global cache entry would have to always make sure that doing so does not circumvent this check.

This changes some goals to error - or succeed - instead of failing with ambiguity. This allows more code to compile:

```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence

// Need to use this local wrapper for the impls to be fully
// knowable as unknowable candidate result in ambiguity.
struct Local<T>(T);

trait Trait<U> {}
// This impl does not hold, but is ambiguous in the old
// solver due to its overflow approximation.
impl<U> Trait<U> for Local<u32> where Local<u16>: Trait<U> {}
// This impl holds.
impl Trait<Local<()>> for Local<u8> {}

// In the old solver, `Local<?t>: Trait<Local<?u>>` is ambiguous,
// resulting in `Local<?u>: NoImpl`, also being ambiguous.
//
// In the new solver the first impl does not apply, constraining
// `?u` to `Local<()>`, causing `Local<()>: NoImpl` to error.
trait Indirect<T> {}
impl<T, U> Indirect<U> for T
where
    T: Trait<U>,
    U: NoImpl
{}

// Not implemented for `Local<()>`
trait NoImpl {}
impl NoImpl for Local<u8> {}
impl NoImpl for Local<u16> {}

// `Local<?t>: Indirect<Local<?u>>` cannot hold, so
// these impls do not overlap.
trait NoOverlap<U> {}
impl<T: Indirect<U>, U> NoOverlap<U> for T {}
impl<T, U> NoOverlap<Local<U>> for Local<T> {}
//~^ ERROR conflicting implementations of trait `NoOverlap<Local<_>>`
```

### Non-fatal overflow

The old solver immediately emits a fatal error when hitting the recursion limit. The new solver instead returns overflow. This both allows more code to compile and is results in performance and potential future compatability issues.

Non-fatal overflow is generally desirable. With fatal overflow, changing the order in which we evaluate nested goals easily causes breakage if we have goal which errors and one which overflows. It is also required to prevent breakage due to the removal of `fn match_fresh_trait_refs`, e.g. [in `typenum`](https://github.com/rust-lang/trait-system-refactor-initiative/issues/73).

#### Enabling more code to compile

In the below example, the old solver first tried to prove an overflowing goal, resulting in a fatal error. The new solver instead returns ambiguity due to overflow for that goal, causing the implicit negative overlap check to succeed as `Box<u32>: NotImplemented` does not hold.
```rust
// revisions: current next
//[next] compile-flags: -Znext-solver=coherence
//[current] ERROR overflow evaluating the requirement

trait Indirect<T> {}
impl<T: Overflow<()>> Indirect<T> for () {}

trait Overflow<U> {}
impl<T, U> Overflow<U> for Box<T>
where
    U: Indirect<Box<Box<T>>>,
{}

trait NotImplemented {}

trait Trait<U> {}
impl<T, U> Trait<U> for T
where
    // T: NotImplemented, // causes old solver to succeed
    U: Indirect<T>,
    T: NotImplemented,
{}

impl Trait<()> for Box<u32> {}
```

#### Avoiding hangs with non-fatal overflow

Simply returning ambiguity when reaching the recursion limit can very easily result in hangs, e.g.
```rust
trait Recur {}
impl<T, U> Recur for ((T, U), (U, T))
where
    (T, U): Recur,
    (U, T): Recur,
{}

trait NotImplemented {}
impl<T: NotImplemented> Recur for T {}
```
This can happen quite frequently as it's easy to have exponential blowup due to multiple nested goals at each step. As the trait solver is depth-first, this immediately caused a fatal overflow error in the old solver. In the new solver we have to handle the whole proof tree instead, which can very easily hang.

To avoid this we restrict the recursion depth after hitting the recursion limit for the first time. We also **ignore all inference constraints from goals resulting in overflow**. This is mostly backwards compatible as any overflow in the old solver resulted in a fatal error.

### sidenote about normalization

We return ambiguous nested goals of `NormalizesTo` goals to the caller and ignore their impact when computing the `Certainty` of the current goal. See the [normalization chapter](https://rustc-dev-guide.rust-lang.org/solve/normalization.html) for more details.This means we apply constraints resulting from other nested goals and from equating the impl header when normalizing, even if a nested goal results in overflow. This is necessary to avoid breaking the following example:
```rust
trait Trait {
    type Assoc;
}

struct W<T: ?Sized>(*mut T);
impl<T: ?Sized> Trait for W<W<T>>
where
    W<T>: Trait,
{
    type Assoc = ();
}

// `W<?t>: Trait<Assoc = u32>` does not hold as
// `Assoc` gets normalized to `()`. However, proving
// the where-bounds of the impl results in overflow.
//
// For this to continue to compile we must not discard
// constraints from normalizing associated types.
trait NoOverlap {}
impl<T: Trait<Assoc = u32>> NoOverlap for T {}
impl<T: ?Sized> NoOverlap for W<T> {}
```

#### Future compatability concerns

Non-fatal overflow results in some unfortunate future compatability concerns. Changing the approach to avoid more hangs by more strongly penalizing overflow can cause breakage as we either drop constraints or ignore candidates necessary to successfully compile. Weakening the overflow penalities instead allows more code to compile and strengthens inference while potentially causing more code to hang.

While the current approach is not perfect, we believe it to be good enough. We believe it to apply the necessary inference constraints to avoid breakage and expect there to not be any desirable patterns broken by our current penalities. Similarly we believe the current constraints to avoid most accidental hangs. Ignoring constraints of overflowing goals is especially useful, as it may allow major future optimizations to our overflow handling. See [this summary](https://hackmd.io/ATf4hN0NRY-w2LIVgeFsVg) and the linked documents in case you want to know more.

### changes to performance

In general, trait solving during coherence checking is not significant for performance. Enabling the next-generation trait solver in coherence does not impact our compile time benchmarks. We are still unable to compile the benchmark suite when fully enabling the new trait solver.

There are rare cases where the new solver has significantly worse performance due to non-fatal overflow, its reliance on fixpoint algorithms and the removal of the `fn match_fresh_trait_refs` approximation. We encountered such issues in [`typenum`](https://crates.io/crates/typenum) and believe it should be [pretty much as bad as it can get](https://github.com/rust-lang/trait-system-refactor-initiative/issues/73).

Due to an improved structure and far better caching, we believe that there is a lot of room for improvement and that the new solver will outperform the existing implementation in nearly all cases, sometimes significantly. We have not yet spent any time micro-optimizing the implementation and have many unimplemented major improvements, such as fast-paths for trivial goals.

### Unstable features

#### Unsupported unstable features

The new solver currently does not support all unstable features, most notably `#![feature(generic_const_exprs)]`, `#![feature(associated_const_equality)]` and `#![feature(adt_const_params)]` are not yet fully supported in the new solver. We are confident that supporting them is possible, but did not consider this to be a priority. This stabilization introduces new ICE when using these features in impl headers.

#### fixes to `#![feature(specialization)]`

- fixes #105782
- fixes #118987

#### fixes to `#![feature(type_alias_impl_trait)]`

- fixes #119272
- https://github.com/rust-lang/rust/issues/105787#issuecomment-1750112388
- fixes #124207

### Important changes since the original FCP

https://github.com/rust-lang/rust/pull/127574 changes the coherence unknowable candidate to only apply if all the super trait bounds may hold. This allows more code to compile and fixes a regression in `pyella`

https://github.com/rust-lang/rust/pull/130617 bails with ambiguity if the query response would contain too many non-region inference variables. This should only be triggered in case the result contains a lot of ambiguous aliases in which case further constraining the goal should resolve this.

https://github.com/rust-lang/rust/pull/130821 adds caching to a lot of type folders, which is necessary to handle exponentially large types and handles the hang in `nalgebra` together with #130617.

## This does not stabilize the whole solver

While this stabilizes the use of the new solver in coherence checking, there are many parts of the solver which will remain fully unstable. We may still adapt these areas while working towards stabilizing the new solver everywhere. We are confident that we are able to do so without negatively impacting coherence.

### goals with a non-empty `ParamEnv`

Coherence always uses an empty environment. We therefore do not depend on the behavior of `AliasBound` and `ParamEnv` candidates. We only stabilizes the behavior of user-defined and builtin implementations of traits. There are still many open questions there.

### opaque types in the defining scope

The handling of opaque types - `impl Trait` - in both the new and old solver is still not fully figured out. Luckily this can be ignored for now. While opaque types are reachable during coherence checking by using `impl_trait_in_associated_types`, the behavior during coherence is separate and self-contained. The old and new solver fully agree here.

### normalization is hard

This stabilizes that we equate associated types involving bound variables using deferred-alias-equality. We also stop eagerly normalizing in coherence, which should not have any user-facing impact.

We do not stabilize the normalization behavior outside of coherence, e.g. we currently deeply normalize all types during writeback with the new solver. This may change going forward

### how to replace `select` from the old solver

We sometimes depend on getting a single `impl` for a given trait bound, e.g. when resolving a concrete method for codegen/CTFE. We do not depend on this during coherence, so the exact approach here can still be freely changed going forward.

## Acknowledgements

This work would not have been possible without `@compiler-errors.` He implemented large chunks of the solver himself but also and did a lot of testing and experimentation, eagerly discovering multiple issues which had a significant impact on our approach. `@BoxyUwU` has also done some amazing work on the solver. Thank you for the endless hours of discussion resulting in the current approach. Especially the way aliases are handled has gone through multiple revisions to get to its current state.

There were also many contributions from - and discussions with - other members of the community and the rest of `@rust-lang/types.` This solver builds upon previous improvements to the compiler, as well as lessons learned from `chalk` and `a-mir-formality`. Getting to this point  would not have been possible without that and I am incredibly thankful to everyone involved. See the [list of relevant PRs](https://github.com/rust-lang/rust/pulls?q=is%3Apr+is%3Amerged+label%3AWG-trait-system-refactor+-label%3Arollup+closed%3A%3C2024-03-22+).
2024-10-15 14:21:34 +00:00
lcnr
1a9d2d82a5 stabilize -Znext-solver=coherence 2024-10-15 13:11:00 +02:00
Michael Goulet
5a8405a5fa Don't report on_unimplemented for negative traits 2024-10-14 14:18:25 -04:00
Michael Goulet
7500e09b8b Move trait bound modifiers into hir::PolyTraitRef 2024-10-14 09:20:38 -04:00
GnomedDev
8de8f46f78 Swap PredicateObligation to ThinVec 2024-10-12 15:17:16 +01:00
GnomedDev
7ec06b0d1d Swap Vec<PredicateObligation> to type alias 2024-10-12 15:17:08 +01:00
Michael Goulet
5e8820caaa Add a note for ? on future in sync function 2024-10-12 06:14:45 -04:00
lcnr
5fd7be97e9 remove outdated FIXMEs 2024-10-11 10:41:10 +00:00
Matthias Krüger
fa3dff3e24
Rollup merge of #131475 - fmease:compiler-mv-obj-safe-dyn-compat-2, r=jieyouxu
Compiler & its UI tests: Rename remaining occurrences of "object safe" to "dyn compatible"

Follow-up to #130826.
Part of #130852.

1. 1st commit: Fix stupid oversights. Should've been part of #130826.
2. 2nd commit: Rename the unstable feature `object_safe_for_dispatch` to `dyn_compatible_for_dispatch`. Might not be worth the churn, you decide.
3. 3rd commit: Apply the renaming to all UI tests (contents and paths).
2024-10-10 22:00:50 +02:00
bors
8d94e06ec9 Auto merge of #131263 - compiler-errors:solver-relating, r=lcnr
Introduce SolverRelating type relation to the new solver

Redux of #128744.

Splits out relate for the new solver so that implementors don't need to implement it themselves.

r? lcnr
2024-10-10 14:59:40 +00:00
lcnr
d6fd45c2e3 impossible obligations check fast path 2024-10-10 06:09:50 -04:00
Michael Goulet
3da257a98d Use SolverRelating in new solver 2024-10-10 06:07:52 -04:00
León Orell Valerian Liehr
2e7a52b22f
Rename feature object_safe_for_dispatch to dyn_compatible_for_dispatch 2024-10-10 00:57:59 +02:00
León Orell Valerian Liehr
62b24ea7c5
Compiler: Replace remaining occurrences of "object safe" with "dyn compatible" 2024-10-10 00:57:52 +02:00
codemountains
6dfc4a0473 Rename NestedMetaItem to MetaItemInner 2024-10-06 23:28:30 +09:00
bors
5a4ee43c38 Auto merge of #129244 - cjgillot:opaque-hir, r=compiler-errors
Make opaque types regular HIR nodes

Having opaque types as HIR owner introduces all sorts of complications. This PR proposes to make them regular HIR nodes instead.

I haven't gone through all the test changes yet, so there may be a few surprises.

Many thanks to `@camelid` for the first draft.
Fixes https://github.com/rust-lang/rust/issues/129023

Fixes #129099
Fixes #125843
Fixes #119716
Fixes #121422
2024-10-05 06:19:35 +00:00
Jubilee
08689af7b4
Rollup merge of #131273 - estebank:issue-131051, r=compiler-errors
Account for `impl Trait {` when `impl Trait for Type {` was intended

On editions where bare traits are never allowed, detect if the user has written `impl Trait` with no type, silence any dyn-compatibility errors, and provide a structured suggestion for the potentially missing type:

```
error[E0782]: trait objects must include the `dyn` keyword
  --> $DIR/missing-for-type-in-impl.rs:8:6
   |
LL | impl Foo<i64> {
   |      ^^^^^^^^
   |
help: add `dyn` keyword before this trait
   |
LL | impl dyn Foo<i64> {
   |      +++
help: you might have intended to implement this trait for a given type
   |
LL | impl Foo<i64> for /* Type */ {
   |               ++++++++++++++
```

CC #131051.
2024-10-04 19:19:27 -07:00
Noah Lev
d6f247f3d5 rm ItemKind::OpaqueTy
This introduce an additional collection of opaques on HIR, as they can no
longer be listed using the free item list.
2024-10-04 23:28:22 +00:00
Esteban Küber
e057c43382 Account for impl Trait { when impl Trait for Type { was intended
On editions where bare traits are never allowed, detect if the user has
written `impl Trait` with no type, silence any dyn-compatibility errors,
and provide a structured suggestion for the potentially missing type:

```
error[E0782]: trait objects must include the `dyn` keyword
  --> $DIR/missing-for-type-in-impl.rs:8:6
   |
LL | impl Foo<i64> {
   |      ^^^^^^^^
   |
help: add `dyn` keyword before this trait
   |
LL | impl dyn Foo<i64> {
   |      +++
help: you might have intended to implement this trait for a given type
   |
LL | impl Foo<i64> for /* Type */ {
   |               ++++++++++++++
```
2024-10-04 22:59:03 +00:00
Jubilee
5a8fcab713
Rollup merge of #130518 - scottmcm:stabilize-controlflow-extra, r=dtolnay
Stabilize the `map`/`value` methods on `ControlFlow`

And fix the stability attribute on the `pub use` in `core::ops`.

libs-api in https://github.com/rust-lang/rust/issues/75744#issuecomment-2231214910 seemed reasonably happy with naming for these, so let's try for an FCP.

Summary:
```rust
impl<B, C> ControlFlow<B, C> {
    pub fn break_value(self) -> Option<B>;
    pub fn map_break<T>(self, f: impl FnOnce(B) -> T) -> ControlFlow<T, C>;
    pub fn continue_value(self) -> Option<C>;
    pub fn map_continue<T>(self, f: impl FnOnce(C) -> T) -> ControlFlow<B, T>;
}
```

Resolves #75744

``@rustbot`` label +needs-fcp +t-libs-api -t-libs

---

Aside, in case it keeps someone else from going down the same dead end: I looked at the `{break,continue}_value` methods and tried to make them `const` as part of this, but that's disallowed because of not having `const Drop`, so put it back to not even unstably-const.
2024-10-04 14:11:34 -07:00
Guillaume Gomez
2ceeeb159d
Rollup merge of #131034 - Urgau:cfg-true-false, r=nnethercote
Implement RFC3695 Allow boolean literals as cfg predicates

This PR implements https://github.com/rust-lang/rfcs/pull/3695: allow boolean literals as cfg predicates, i.e. `cfg(true)` and `cfg(false)`.

r? `@nnethercote` *(or anyone with parser knowledge)*
cc `@clubby789`
2024-10-04 15:42:53 +02:00
Matthias Krüger
da81f64d84
Rollup merge of #131183 - compiler-errors:opaque-ty-origin, r=estebank
Refactoring to `OpaqueTyOrigin`

Pulled out of a larger PR that uses these changes to do cross-crate encoding of opaque origin, so we can use them for edition 2024 migrations. These changes should be self-explanatory on their own, tho 😄
2024-10-03 21:52:46 +02:00
Matthias Krüger
33b4947554
Rollup merge of #131112 - jswrenn:fix-130413, r=compiler-errors
TransmuteFrom: Gracefully handle unnormalized types and normalization errors

~~Refactor to share code between `TransmuteFrom`'s trait selection and error reporting code paths. Additionally normalizes the source and destination types, and gracefully handles normalization errors.~~

Fixes #130413

r​? `@compiler-errors`
2024-10-03 21:52:45 +02:00
Michael Goulet
bc5f9520c1 Remove crashes, add comment 2024-10-03 15:19:23 -04:00
Michael Goulet
7cd466a036 Move in_trait into OpaqueTyOrigin 2024-10-02 22:48:26 -04:00
Michael Goulet
cb7e3695e8 Use named fields for OpaqueTyOrigin 2024-10-02 22:04:18 -04:00
Michael Goulet
f95bdf453e Remove redundant in_trait from hir::TyKind::OpaqueDef 2024-10-02 21:59:55 -04:00
Deadbeef
7f6150b577 Improve const traits diagnostics for new desugaring 2024-10-02 19:45:17 +08:00
Jack Wrenn
5b1a2b8712 TransmuteFrom: Gracefully handle unnormalized types and normalization errors
Fixes #130413
2024-10-01 20:52:17 +00:00
Urgau
c99f29b29f Implement boolean lit support in cfg predicates 2024-10-01 10:01:33 +02:00
Urgau
57b9b1f974 Use ast::NestedMetaItem when evaluating cfg predicate 2024-10-01 10:01:09 +02:00
Michael Goulet
7c552d56b2 Also fix first_method_vtable_slot 2024-09-30 13:17:33 -04:00
Michael Goulet
d87e0ca497 Extract trait_refs_are_compatible, make it instantiate binders 2024-09-30 13:17:33 -04:00
Michael Goulet
af3f212453 Instantiate binders in supertrait_vtable_slot 2024-09-30 13:17:33 -04:00
Matthias Krüger
4e510daed7
Rollup merge of #130866 - compiler-errors:dyn-instantiate-binder, r=lcnr
Allow instantiating object trait binder when upcasting

This PR fixes two bugs (that probably need an FCP).

### We use equality rather than subtyping for upcasting dyn conversions

This code should be valid:

```rust
#![feature(trait_upcasting)]

trait Foo: for<'h> Bar<'h> {}
trait Bar<'a> {}

fn foo(x: &dyn Foo) {
    let y: &dyn Bar<'static> = x;
}
```
But instead:

```
error[E0308]: mismatched types
 --> src/lib.rs:7:32
  |
7 |     let y: &dyn Bar<'static> = x;
  |                                ^ one type is more general than the other
  |
  = note: expected existential trait ref `for<'h> Bar<'h>`
             found existential trait ref `Bar<'_>`
```

And so should this:

```rust
#![feature(trait_upcasting)]

fn foo(x: &dyn for<'h> Fn(&'h ())) {
    let y: &dyn FnOnce(&'static ()) = x;
}
```

But instead:

```
error[E0308]: mismatched types
 --> src/lib.rs:4:39
  |
4 |     let y: &dyn FnOnce(&'static ()) = x;
  |                                       ^ one type is more general than the other
  |
  = note: expected existential trait ref `for<'h> FnOnce<(&'h (),)>`
             found existential trait ref `FnOnce<(&(),)>`
```

Specifically, both of these fail because we use *equality* when comparing the supertrait to the *target* of the unsize goal. For the first example, since our supertrait is `for<'h> Bar<'h>` but our target is `Bar<'static>`, there's a higher-ranked type mismatch even though we *should* be able to instantiate that supertrait binder when upcasting. Similarly for the second example.

### New solver uses equality rather than subtyping for no-op (i.e. non-upcasting) dyn conversions

This code should be valid in the new solver, like it is with the old solver:

```rust
// -Znext-solver

fn foo<'a>(x: &mut for<'h> dyn Fn(&'h ())) {
   let _: &mut dyn Fn(&'a ()) = x;
}
```

But instead:

```
error: lifetime may not live long enough
 --> <source>:2:11
  |
1 | fn foo<'a>(x: &mut dyn for<'h> Fn(&'h ())) {
  |        -- lifetime `'a` defined here
2 |    let _: &mut dyn Fn(&'a ()) = x;
  |           ^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static`
  |
  = note: requirement occurs because of a mutable reference to `dyn Fn(&())`
```

Specifically, this fails because we try to coerce `&mut dyn for<'h> Fn(&'h ())` to `&mut dyn Fn(&'a ())`, which registers an `dyn for<'h> Fn(&'h ()): dyn Fn(&'a ())` goal. This fails because the new solver uses *equating* rather than *subtyping* in `Unsize` goals.

This is *mostly* not a problem... You may wonder why the same code passes on the new solver for immutable references:

```
// -Znext-solver

fn foo<'a>(x: &dyn Fn(&())) {
   let _: &dyn Fn(&'a ()) = x; // works
}
```

That's because in this case, we first try to coerce via `Unsize`, but due to the leak check the goal fails. Then, later in coercion, we fall back to a simple subtyping operation, which *does* work.

Since `&T` is covariant over `T`, but `&mut T` is invariant, that's where the discrepancy between these two examples crops up.

---

r? lcnr or reassign :D
2024-09-28 09:35:09 +02:00