rust/compiler
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
..
rustc disable size asserts in the compiler when randomizing layouts 2024-08-31 23:56:45 +02:00
rustc_abi Make rustc_abi compile on stable again 2024-10-21 15:11:20 +02:00
rustc_arena move strict provenance lints to new feature gate, remove old feature gates 2024-10-21 15:22:17 +01:00
rustc_ast Represent TraitBoundModifiers as distinct parts in HIR 2024-10-22 19:48:44 +00:00
rustc_ast_ir Add sugar for &pin (const|mut) types 2024-10-07 11:15:04 -07:00
rustc_ast_lowering Remove associated type based effects logic 2024-10-24 09:46:36 +00:00
rustc_ast_passes nightly feature tracking: get rid of the per-feature bool fields 2024-10-23 09:14:41 +01:00
rustc_ast_pretty Print safety correctly in extern static items 2024-10-24 00:41:27 +00:00
rustc_attr fix a couple clippy:complexitys 2024-10-23 22:15:59 +02:00
rustc_baked_icu_data Don't add warn(unreachable_pub) to rustc_baked_icu. 2024-08-16 08:46:52 +10:00
rustc_borrowck Rollup merge of #131756 - compiler-errors:deeply-normalize-type-err, r=lcnr 2024-10-24 14:19:55 +11:00
rustc_builtin_macros nightly feature tracking: get rid of the per-feature bool fields 2024-10-23 09:14:41 +01:00
rustc_codegen_cranelift Rename Receiver -> LegacyReceiver 2024-10-22 12:55:16 +00:00
rustc_codegen_gcc Rollup merge of #130225 - adetaylor:rename-old-receiver, r=wesleywiser 2024-10-24 14:19:53 +11:00
rustc_codegen_llvm Rollup merge of #131956 - Zalathar:llvm-counters, r=compiler-errors,Swatinem 2024-10-24 14:19:57 +11:00
rustc_codegen_ssa Rollup merge of #132060 - joshtriplett:innermost-outermost, r=jieyouxu 2024-10-23 22:11:05 +02:00
rustc_const_eval nightly feature tracking: get rid of the per-feature bool fields 2024-10-23 09:14:41 +01:00
rustc_data_structures Replace an FTP link in comments with an equivalent HTTPS link 2024-10-24 17:02:11 +11:00
rustc_driver
rustc_driver_impl Rollup merge of #130899 - bjorn3:wasi_bootstrap_fixes, r=davidtwco 2024-10-07 11:10:53 -07:00
rustc_error_codes terminology: #[feature] *enables* a feature (instead of "declaring" or "activating" it) 2024-10-22 07:37:54 +01:00
rustc_error_messages Reformat using the new identifier sorting from rustfmt 2024-09-22 19:11:29 -04:00
rustc_errors "innermost", "outermost", "leftmost", and "rightmost" don't need hyphens 2024-10-23 02:45:24 -07:00
rustc_expand Rollup merge of #132060 - joshtriplett:innermost-outermost, r=jieyouxu 2024-10-23 22:11:05 +02:00
rustc_feature Auto merge of #131985 - compiler-errors:const-pred, r=fee1-dead 2024-10-24 17:33:42 +00:00
rustc_fluent_macro use tracked_path in rustc_fluent_macro 2024-10-19 22:32:38 +08:00
rustc_fs_util Couple of changes to make it easier to compile rustc for wasm 2024-09-26 19:51:14 +00:00
rustc_graphviz Reformat using the new identifier sorting from rustfmt 2024-09-22 19:11:29 -04:00
rustc_hir Remove associated type based effects logic 2024-10-24 09:46:36 +00:00
rustc_hir_analysis Be better at enforcing that const_conditions is only called on const items 2024-10-24 09:46:36 +00:00
rustc_hir_pretty Remove associated type based effects logic 2024-10-24 09:46:36 +00:00
rustc_hir_typeck Be better at enforcing that const_conditions is only called on const items 2024-10-24 09:46:36 +00:00
rustc_incremental nightly feature tracking: get rid of the per-feature bool fields 2024-10-23 09:14:41 +01:00
rustc_index Rollup merge of #130625 - heiseish:issue-124028-fix, r=jieyouxu 2024-10-10 12:49:18 +02:00
rustc_index_macros Remove 'apostrophes' from rustc_parse_format 2024-10-14 23:22:51 +02:00
rustc_infer Implement const effect predicate in new solver 2024-10-24 09:46:36 +00:00
rustc_interface rust_for_linux: -Zregparm=<N> commandline flag for X86 (#116972) 2024-10-18 00:29:31 +07:00
rustc_lexer Reserve guarded string literals (RFC 3593) 2024-10-08 18:21:16 -06:00
rustc_lint Auto merge of #131985 - compiler-errors:const-pred, r=fee1-dead 2024-10-24 17:33:42 +00:00
rustc_lint_defs Auto merge of #129935 - RalfJung:unsupported_calling_conventions, r=compiler-errors 2024-10-22 03:24:40 +00:00
rustc_llvm Rollup merge of #131956 - Zalathar:llvm-counters, r=compiler-errors,Swatinem 2024-10-24 14:19:57 +11:00
rustc_log Reformat using the new identifier sorting from rustfmt 2024-09-22 19:11:29 -04:00
rustc_macros Reformat using the new identifier sorting from rustfmt 2024-09-22 19:11:29 -04:00
rustc_metadata Be better at enforcing that const_conditions is only called on const items 2024-10-24 09:46:36 +00:00
rustc_middle Be better at enforcing that const_conditions is only called on const items 2024-10-24 09:46:36 +00:00
rustc_mir_build Rollup merge of #129248 - compiler-errors:raw-ref-deref, r=nnethercote 2024-10-24 10:35:39 +02:00
rustc_mir_dataflow "innermost", "outermost", "leftmost", and "rightmost" don't need hyphens 2024-10-23 02:45:24 -07:00
rustc_mir_transform fix a couple clippy:complexitys 2024-10-23 22:15:59 +02:00
rustc_monomorphize Remove associated type based effects logic 2024-10-24 09:46:36 +00:00
rustc_next_trait_solver Implement const effect predicate in new solver 2024-10-24 09:46:36 +00:00
rustc_parse "innermost", "outermost", "leftmost", and "rightmost" don't need hyphens 2024-10-23 02:45:24 -07:00
rustc_parse_format Remove 'apostrophes' from rustc_parse_format 2024-10-14 23:22:51 +02:00
rustc_passes Plumb through param_env to note_type_err 2024-10-24 02:48:08 +00:00
rustc_pattern_analysis nightly feature tracking: get rid of the per-feature bool fields 2024-10-23 09:14:41 +01:00
rustc_privacy Implement const effect predicate in new solver 2024-10-24 09:46:36 +00:00
rustc_query_impl Handle rustc_query_impl cases of rustc::potential_query_instability lint 2024-10-03 12:47:08 +03:00
rustc_query_system stop hashing compile-time constant 2024-10-23 19:46:52 +02:00
rustc_resolve nightly feature tracking: get rid of the per-feature bool fields 2024-10-23 09:14:41 +01:00
rustc_sanitizers Rollup merge of #131049 - compiler-errors:more-validation, r=spastorino 2024-10-22 15:28:38 +02:00
rustc_serialize Fix explicit_iter_loop in rustc_serialize 2024-10-16 15:44:16 +02:00
rustc_session Limited -Zregparm support (no Rust calling conv) descriptions 2024-10-20 18:18:01 +07:00
rustc_smir Implement const effect predicate in new solver 2024-10-24 09:46:36 +00:00
rustc_span Remove associated type based effects logic 2024-10-24 09:46:36 +00:00
rustc_symbol_mangling nightly feature tracking: get rid of the per-feature bool fields 2024-10-23 09:14:41 +01:00
rustc_target Rollup merge of #131169 - madsmtm:target-info-nto-vendor, r=wesleywiser 2024-10-24 14:19:53 +11:00
rustc_trait_selection Auto merge of #131985 - compiler-errors:const-pred, r=fee1-dead 2024-10-24 17:33:42 +00:00
rustc_traits Implement const effect predicate in new solver 2024-10-24 09:46:36 +00:00
rustc_transmute Fix transmute goal 2024-10-19 18:07:35 +00:00
rustc_ty_utils Be better at enforcing that const_conditions is only called on const items 2024-10-24 09:46:36 +00:00
rustc_type_ir Implement const effect predicate in new solver 2024-10-24 09:46:36 +00:00
rustc_type_ir_macros do not relate Abi and Safety 2024-10-22 23:13:04 +02:00
stable_mir Remove associated type based effects logic 2024-10-24 09:46:36 +00:00