Commit Graph

7785 Commits

Author SHA1 Message Date
Ralf Jung
ffad9aac27 mark some target features as 'forbidden' so they cannot be (un)set
For now, this is just a warning, but should become a hard error in the future
2024-11-04 22:56:47 +01:00
Matthias Krüger
b9db639ea5
Rollup merge of #132544 - dianne:unstable-library-feature-backticks, r=compiler-errors
Use backticks instead of single quotes for library feature names in diagnostics

This PR changes the text of library feature errors for using unstable or body-unstable items. Displaying library feature names in backticks is consistent with other diagnostics (e.g. those from `rustc_passes`) and with the `reason`s on unstable attributes in the library. Additionally, this simplifies diagnostics when supporting multiple unstable attributes on items (see #131824) since `DiagSymbolList` also displays symbols using backticks.
2024-11-04 18:12:46 +01:00
Michael Goulet
e03e9abe3c Register const preds for Deref adjustments in HIR typeck 2024-11-04 04:51:31 +00:00
Michael Goulet
d458f850aa ty::BrK -> ty::BoundRegionKind::K 2024-11-04 04:45:52 +00:00
Michael Goulet
883f8705d4 Remove BorrowKind glob, make names longer 2024-11-04 04:45:52 +00:00
Michael Goulet
be4b0261c2 ty::KContainer -> ty::AssocItemContainer::K 2024-11-04 04:45:52 +00:00
Michael Goulet
8e6af16192 Remove the trivial constkind imports 2024-11-04 04:45:51 +00:00
Jubilee
72df7780dd
Rollup merge of #132574 - workingjubilee:abi-in-compiler, r=compiler-errors
compiler: Directly use rustc_abi almost everywhere

Use rustc_abi instead of rustc_target where applicable. This is mostly described by the following substitutions:
```rust
match path_substring {
    rustc_target::spec::abi::Abi => rustc_abi::ExternAbi,
    rustc_target::abi::call => rustc_target::callconv,
    rustc_target::abi => rustc_abi,
}
```

A number of spot-fixes make that not quite the whole story.

The main exception is in 33edc68 where I get a lot more persnickety about how things are imported, especially in `rustc_middle::ty::layout`, not just from where. This includes putting an end to a reexport of `rustc_middle::ty::ReprOptions`, for the same reason that the rest of this change is happening: reexports mostly confound things.

This notably omits rustc_passes and the ast crates, as I'm still examining a question I have about how they do stability checking of `extern "Abi"` strings and if I can simplify their logic. The rustc_abi and rustc_target crates also go untouched because they will be entangled in that cleanup.

r? compiler-errors
2024-11-03 15:25:00 -08:00
dianne
d7d6238b23 use backticks instead of single quotes when reporting "use of unstable library feature"
This is consistent with all other diagnostics I could find containing
features and enables the use of `DiagSymbolList` for generalizing
diagnostics for unstable library features to multiple features.
2024-11-03 13:55:52 -08:00
Jubilee Young
236fe33345 compiler: Directly use rustc_abi in metadata and middle
Stop reexporting ReprOptions from middle::ty
2024-11-03 13:38:47 -08:00
Michael Goulet
6b96103bf3 Rename the FIXMEs, remove a few that dont matter anymore 2024-11-03 18:59:41 +00:00
Esteban Küber
c6017badb4 Fix type shortening writing to file
Make sure that we append to the file for long ty paths. Do not write the same type more than once. Shorten the calculated width a bit.
2024-11-02 03:08:04 +00:00
Luca Versari
c8b76bcf58 Emit warning when calling/declaring functions with unavailable vectors.
On some architectures, vector types may have a different ABI depending
on whether the relevant target features are enabled. (The ABI when the
feature is disabled is often not specified, but LLVM implements some
de-facto ABI.)

As discussed in rust-lang/lang-team#235, this turns out to very easily
lead to unsound code.

This commit makes it a post-monomorphization future-incompat warning to
declare or call functions using those vector types in a context in which
the corresponding target features are disabled, if using an ABI for
which the difference is relevant. This ensures that these functions are
always called with a consistent ABI.

See the [nomination comment](https://github.com/rust-lang/rust/pull/127731#issuecomment-2288558187)
for more discussion.

Part of #116558
2024-11-01 22:24:35 +01:00
bjorn3
760338526f Show actual MIR when MIR building forgot to terminate block
This makes it significantly easier to debug bugs of this kind.
2024-11-01 11:24:14 +01:00
Jubilee
c57b351d38
Rollup merge of #132403 - lcnr:typing-mode, r=compiler-errors
continue `TypingMode` refactor

There are still quite a few places which (indirectly) rely on the `Reveal` of a `ParamEnv`, but we're slowly getting there

r? `@compiler-errors`
2024-10-31 17:50:43 -07:00
lcnr
2cde638ac0 stop using ParamEnv::reveal while handling MIR 2024-10-31 14:55:53 +01:00
lcnr
aab149b58c ConstCx stop using ParamEnv::reveal 2024-10-31 12:43:22 +01:00
bors
9ccfedf186 Auto merge of #132301 - compiler-errors:adjust, r=lcnr
Remove region from adjustments

It's not necessary to store this region, because it's only used in THIR and MemCat/ExprUse, both of which already basically only deal with erased regions anyways.
2024-10-31 10:17:49 +00:00
bors
c8b83785dc Auto merge of #131186 - compiler-errors:precise-capturing-borrowck, r=estebank
Try to point out when edition 2024 lifetime capture rules cause borrowck issues

Lifetime capture rules in 2024 are modified to capture more lifetimes, which sometimes lead to some non-local borrowck errors. This PR attempts to link these back together with a useful note pointing out the capture rule changes.

This is not a blocking concern, but I'd appreciate feedback (though, again, I'd like to stress that I don't want to block this PR on this): I'm worried about this note drowning in the sea of other diagnostics that borrowck emits. I was tempted to change the level of the note to `.span_warn` just so it would show up in a different color. Thoughts?

Fixes #130545

Opening as a draft first since it's stacked on #131183.
r? `@ghost`
2024-10-31 03:36:06 +00:00
Michael Goulet
c1457798db Try to point out when edition 2024 lifetime capture rules cause borrowck issues 2024-10-31 01:35:14 +00:00
Michael Goulet
e093b82a41 Encode cross-crate opaque type origin 2024-10-31 01:35:13 +00:00
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
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
lcnr
f51ec110a7 TypingMode 🤔 2024-10-29 17:01:24 +01:00
Jubilee
5d0f52efa4
Rollup merge of #131375 - klensy:clone_on_ref_ptr, r=cjgillot
compiler: apply clippy::clone_on_ref_ptr for CI

Apply lint https://rust-lang.github.io/rust-clippy/master/index.html#/clone_on_ref_ptr for compiler, also see https://github.com/rust-lang/rust/pull/131225#discussion_r1790109443.

Some Arc's can be misplaced with Lrc's, sorry.

https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/enable.20more.20clippy.20lints.20for.20compiler.20.28and.5Cor.20std.29
2024-10-29 03:11:39 -07:00
Michael Goulet
599ffab6cd Remove region from adjustments 2024-10-29 01:34:06 +00:00
Jubilee
259ddf9b50
Rollup merge of #132255 - workingjubilee:layout-is-🏚️, r=compiler-errors
Add `LayoutS::is_uninhabited` and use it

Use accessors for the things that accessors are good at: reducing everyone's need to be nosy and peek at the internals of every data structure.
2024-10-28 10:18:50 -07:00
Jubilee Young
88a9edc091 compiler: Add is_uninhabited and use LayoutS accessors
This reduces the need of the compiler to peek on the fields of LayoutS.
2024-10-28 09:58:30 -07:00
klensy
746b675c5a fix clippy::clone_on_ref_ptr for compiler 2024-10-28 18:05:08 +03:00
Matthias Krüger
a4acbd561b
Rollup merge of #132252 - workingjubilee:rename-layouts-to-layoutdata, r=jieyouxu
compiler: rename LayoutS to LayoutData

Bid `LayoutS` goodbye because it looks like a typo.

`LayoutS` is the last of the types that use the "`{TypeName}` is the interned type, `{TypeName}S` is the backing data that is interned" convention. This is pretty confusing to those not intimately familiar with the history of rustc's names for its types over time, and doubly so now that there are no other examples in the tree. Abolish this convention.
2024-10-28 12:14:59 +01:00
Jubilee Young
e1781297f3 compiler: Rename LayoutS to LayoutData
The last {UninternedType}S is in captivity. The galaxy is at peace.
2024-10-27 22:31:14 -07: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
bors
4d88de2acd Auto merge of #125116 - blyxyas:ignore-allowed-lints-final, r=cjgillot
(Big performance change) Do not run lints that cannot emit

Before this change, adding a lint was a difficult matter because it always had some overhead involved. This was because all lints would run, no matter their default level, or if the user had `#![allow]`ed them. This PR changes that. This change would improve both the Rust lint infrastructure and Clippy, but Clippy will see the most benefit, as it has about 900 registered lints (and growing!)

So yeah, with this little patch we filter all lints pre-linting, and remove any lint that is either:
- Manually `#![allow]`ed in the whole crate,
- Allowed in the command line, or
- Not manually enabled with `#[warn]` or similar, and its default level is `Allow`

As some lints **need** to run, this PR also adds **loadbearing lints**. On a lint declaration, you can use the ``@eval_always` = true` marker to label it as loadbearing. A loadbearing lint will never be filtered (it will always run)

Fixes #106983
2024-10-26 16:37:43 +00:00
Matthias Krüger
56463df1be
Rollup merge of #132168 - fee1-dead-contrib:fxclean, r=compiler-errors
Effects cleanup

- removed extra bits from predicates queries that are no longer needed in the new system
- removed the need for `non_erasable_generics` to take in tcx and DefId, removed unused arguments in callers

r? compiler-errors
2024-10-26 06:29:48 +02:00
Deadbeef
f6fea83342 Effects cleanup
- removed extra bits from predicates queries that are no longer needed in the new system
- removed the need for `non_erasable_generics` to take in tcx and DefId, removed unused arguments in callers
2024-10-26 10:19:07 +08: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
Ralf Jung
a0215d8e46 Re-do recursive const stability checks
Fundamentally, we have *three* disjoint categories of functions:
1. const-stable functions
2. private/unstable functions that are meant to be callable from const-stable functions
3. functions that can make use of unstable const features

This PR implements the following system:
- `#[rustc_const_stable]` puts functions in the first category. It may only be applied to `#[stable]` functions.
- `#[rustc_const_unstable]` by default puts functions in the third category. The new attribute `#[rustc_const_stable_indirect]` can be added to such a function to move it into the second category.
- `const fn` without a const stability marker are in the second category if they are still unstable. They automatically inherit the feature gate for regular calls, it can now also be used for const-calls.

Also, several holes in recursive const stability checking are being closed.
There's still one potential hole that is hard to avoid, which is when MIR
building automatically inserts calls to a particular function in stable
functions -- which happens in the panic machinery. Those need to *not* be
`rustc_const_unstable` (or manually get a `rustc_const_stable_indirect`) to be
sure they follow recursive const stability. But that's a fairly rare and special
case so IMO it's fine.

The net effect of this is that a `#[unstable]` or unmarked function can be
constified simply by marking it as `const fn`, and it will then be
const-callable from stable `const fn` and subject to recursive const stability
requirements. If it is publicly reachable (which implies it cannot be unmarked),
it will be const-unstable under the same feature gate. Only if the function ever
becomes `#[stable]` does it need a `#[rustc_const_unstable]` or
`#[rustc_const_stable]` marker to decide if this should also imply
const-stability.

Adding `#[rustc_const_unstable]` is only needed for (a) functions that need to
use unstable const lang features (including intrinsics), or (b) `#[stable]`
functions that are not yet intended to be const-stable. Adding
`#[rustc_const_stable]` is only needed for functions that are actually meant to
be directly callable from stable const code. `#[rustc_const_stable_indirect]` is
used to mark intrinsics as const-callable and for `#[rustc_const_unstable]`
functions that are actually called from other, exposed-on-stable `const fn`. No
other attributes are required.
2024-10-25 20:31:40 +02:00
Michael Goulet
0f5a47d088 Be better at enforcing that const_conditions is only called on const items 2024-10-24 09:46:36 +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
Stuart Cook
77f2c57b3f
Rollup merge of #131623 - matthiaskrgr:clippy_sat, r=Nadrieril
misc cleanups
2024-10-24 14:19:54 +11:00
Matthias Krüger
dab76eccdf fix a couple clippy:complexitys
double_parens
 filter_map_identity
 needless_question_mark
 redundant_guards
2024-10-23 22:15:59 +02:00
León Orell Valerian Liehr
6b70ff44bc
Rollup merge of #131979 - compiler-errors:compare-pred-entail, r=fmease
Minor tweaks to `compare_impl_item.rs`

1. Stop using the `InstantiatedPredicates` struct for `hybrid_preds` in `compare_impl_item.rs`, since we never actually push anything into the `spans` part of it.
2. Remove redundant impl args and don't do useless identity substitution, prefer calling `instantiate_identity`.
2024-10-23 22:11:04 +02:00
Michael Goulet
21d95fb7b2 More compare_impl_item simplifications 2024-10-23 14:33: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
bors
ffd978b7bf Auto merge of #132044 - lcnr:no-relate-abi, r=compiler-errors
do not implement `Relate`  for "boring" types

and update some macros while we're at it. This means we don't have to implement `TypeVisitable` for them.

r? `@compiler-errors`
2024-10-23 08:41:24 +00:00
Ralf Jung
ad3991d303 nightly feature tracking: get rid of the per-feature bool fields 2024-10-23 09:14:41 +01:00
lcnr
00266eeaa5 remove PredicatePolarity and BoundConstness relate impls
Also removes `TypeError::ConstnessMismatch`. It is unused.
2024-10-23 00:52:37 +02:00
lcnr
196fdf144f do not relate Abi and Safety
and update some macros while we're at it
2024-10-22 23:13:04 +02:00
Michael Goulet
febb3f7c88 Represent TraitBoundModifiers as distinct parts in HIR 2024-10-22 19:48:44 +00:00
bors
86d69c705a Auto merge of #132035 - matthiaskrgr:rollup-ty1e4q0, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #125205 (Fixup Windows verbatim paths when used with the `include!` macro)
 - #131049 (Validate args are correct for `UnevaluatedConst`, `ExistentialTraitRef`/`ExistentialProjection`)
 - #131549 (Add a note for `?` on a `impl Future<Output = Result<..>>` in sync function)
 - #131731 (add `TestFloatParse` to `tools.rs` for bootstrap)
 - #131732 (Add doc(plugins), doc(passes), etc. to INVALID_DOC_ATTRIBUTES)
 - #132006 (don't stage-off to previous compiler when CI rustc is available)
 - #132022 (Move `cmp_in_dominator_order` out of graph dominator computation)
 - #132033 (compiletest: Make `line_directive` return a `DirectiveLine`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-10-22 14:16:37 +00:00
Matthias Krüger
3f15d296f4
Rollup merge of #131049 - compiler-errors:more-validation, r=spastorino
Validate args are correct for `UnevaluatedConst`, `ExistentialTraitRef`/`ExistentialProjection`

For the `Existential*` ones, we have to do some adjustment to the args list to deal with the missing `Self` type, so we introduce a `debug_assert_existential_args_compatible` function to the interner as well.
2024-10-22 15:28:38 +02:00
bors
bca5fdebe0 Auto merge of #131321 - RalfJung:feature-activation, r=nnethercote
terminology: #[feature] *enables* a feature (instead of "declaring" or "activating" it)

Mostly, we currently call a feature that has a corresponding `#[feature(name)]` attribute in the current crate a "declared" feature. I think that is confusing as it does not align with what "declaring" usually means. Furthermore, we *also* refer to `#[stable]`/`#[unstable]` as *declaring* a feature (e.g. in [these diagnostics](f25e5abea2/compiler/rustc_passes/messages.ftl (L297-L301))), which aligns better with what "declaring" usually means. To make things worse, the functions  `tcx.features().active(...)` and  `tcx.features().declared(...)` both exist and they are doing almost the same thing (testing whether a corresponding `#[feature(name)]`  exists) except that `active` would ICE if the feature is not an unstable lang feature. On top of this, the callback when a feature is activated/declared is called `set_enabled`, and many comments also talk about "enabling" a feature.

So really, our terminology is just a mess.

I would suggest we use "declaring a feature" for saying that something is/was guarded by a feature (e.g. `#[stable]`/`#[unstable]`), and "enabling a feature" for  `#[feature(name)]`. This PR implements that.
2024-10-22 11:02:35 +00:00
Ralf Jung
46ce5cbf33 terminology: #[feature] *enables* a feature (instead of "declaring" or "activating" it) 2024-10-22 07:37:54 +01:00
Jubilee
fe2cbbd2d5
Rollup merge of #130432 - azhogin:azhogin/regparm, r=workingjubilee,pnkfelix
rust_for_linux: -Zregparm=<N> commandline flag for X86 (#116972)

Command line flag `-Zregparm=<N>` for X86 (32-bit) for rust-for-linux: https://github.com/rust-lang/rust/issues/116972
Implemented in the similar way as fastcall/vectorcall support (args are marked InReg if fit).
2024-10-21 20:32:00 -07:00
Matthias Krüger
20b1dadf92
Rollup merge of #130350 - RalfJung:strict-provenance, r=dtolnay
stabilize Strict Provenance and Exposed Provenance APIs

Given that [RFC 3559](https://rust-lang.github.io/rfcs/3559-rust-has-provenance.html) has been accepted, t-lang has approved the concept of provenance to exist in the language. So I think it's time that we stabilize the strict provenance and exposed provenance APIs, and discuss provenance explicitly in the docs:
```rust
// core::ptr
pub const fn without_provenance<T>(addr: usize) -> *const T;
pub const fn dangling<T>() -> *const T;
pub const fn without_provenance_mut<T>(addr: usize) -> *mut T;
pub const fn dangling_mut<T>() -> *mut T;
pub fn with_exposed_provenance<T>(addr: usize) -> *const T;
pub fn with_exposed_provenance_mut<T>(addr: usize) -> *mut T;

impl<T: ?Sized> *const T {
    pub fn addr(self) -> usize;
    pub fn expose_provenance(self) -> usize;
    pub fn with_addr(self, addr: usize) -> Self;
    pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self;
}

impl<T: ?Sized> *mut T {
    pub fn addr(self) -> usize;
    pub fn expose_provenance(self) -> usize;
    pub fn with_addr(self, addr: usize) -> Self;
    pub fn map_addr(self, f: impl FnOnce(usize) -> usize) -> Self;
}

impl<T: ?Sized> NonNull<T> {
    pub fn addr(self) -> NonZero<usize>;
    pub fn with_addr(self, addr: NonZero<usize>) -> Self;
    pub fn map_addr(self, f: impl FnOnce(NonZero<usize>) -> NonZero<usize>) -> Self;
}
```

I also did a pass over the docs to adjust them, because this is no longer an "experiment". The `ptr` docs now discuss the concept of provenance in general, and then they go into the two families of APIs for dealing with provenance: Strict Provenance and Exposed Provenance. I removed the discussion of how pointers also have an associated "address space" -- that is not actually tracked in the pointer value, it is tracked in the type, so IMO it just distracts from the core point of provenance. I also adjusted the docs for `with_exposed_provenance` to make it clear that we cannot guarantee much about this function, it's all best-effort.

There are two unstable lints associated with the strict_provenance feature gate; I moved them to a new [strict_provenance_lints](https://github.com/rust-lang/rust/issues/130351) feature since I didn't want this PR to have an even bigger FCP. ;)

`@rust-lang/opsem` Would be great to get some feedback on the docs here. :)
Nominating for `@rust-lang/libs-api.`

Part of https://github.com/rust-lang/rust/issues/95228.

[FCP comment](https://github.com/rust-lang/rust/pull/130350#issuecomment-2395114536)
2024-10-21 18:11:19 +02:00
Ralf Jung
56ee492a6e move strict provenance lints to new feature gate, remove old feature gates 2024-10-21 15:22:17 +01: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
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
blyxyas
637d5cc56f Remove module passes filtering 2024-10-19 16:20:51 +02:00
blyxyas
71b4d108c7 Follow review comments (optimize the filtering) 2024-10-19 16:20:33 +02:00
blyxyas
edc6577627 Change lints_to_emit to lints_that_actually_run 2024-10-19 16:19:44 +02:00
blyxyas
b4da058595 Do not run lints that cannot emit
Before this change, adding a lint was a difficult matter
because it always had some overhead involved. This was
because all lints would run, no matter their default level,
or if the user had #![allow]ed them. This PR changes that
2024-10-19 16:19:44 +02:00
Ralf Jung
eea74be5c1 interpret errors: add map_err_kind, rename InterpError -> InterpErrorKind 2024-10-19 09:22:38 +02:00
许杰友 Jieyou Xu (Joe)
aae4730c78
Rollup merge of #131802 - compiler-errors:fnonce-coverage, r=Zalathar
Dont ICE when computing coverage of synthetic async closure body

I'm not totally certain if this is *right*, but at least it doesn't ICE.

The issue is that we end up generating two MIR bodies for each async closure, since the `FnOnce` and `Fn`/`FnMut` implementations have different borrowing behavior of their captured variables. They should ideally both contribute to the coverage, since those MIR bodies are (*to the user*) the same code and should have no behavioral differences.

This PR at least suppresses the ICEs, and then I guess worst case we can fix this the right way later.

r? Zalathar or re-roll

Fixes #131190
2024-10-18 12:00:51 +01:00
Michael Goulet
cdbf28af76 Dont ICE when computing coverage of synthetic async closure body 2024-10-18 20:14:02 +11:00
Andrew Zhogin
b3ae64d24f rust_for_linux: -Zregparm=<N> commandline flag for X86 (#116972) 2024-10-18 00:29:31 +07: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
9334d85e69 remove type_op constructors 2024-10-17 09:53:27 +02:00
lcnr
401f9b4e0a ImpliedOutlivesBounds to rustc_middle 2024-10-17 09:53:27 +02:00
Matthias Krüger
c1ed1f133e
Rollup merge of #131381 - Nadrieril:min-match-ergonomics, r=pnkfelix
Implement edition 2024 match ergonomics restrictions

This implements the minimalest version of [match ergonomics for edition 2024](https://rust-lang.github.io/rfcs/3627-match-ergonomics-2024.html). This minimal version makes it an error to ever reset the default binding mode. The implemented proposal is described precisely [here](https://hackmd.io/zUqs2ISNQ0Wrnxsa9nhD0Q#RFC-3627-nano), where it is called "RFC 3627-nano".

Rules:
- Rule 1C: When the DBM (default binding mode) is not `move` (whether or not behind a reference), writing `mut`, `ref`, or `ref mut` on a binding is an error.
- Rule 2C: Reference patterns can only match against references in the scrutinee when the DBM is `move`.

This minimal version is forward-compatible with the main proposals for match ergonomics 2024: [RFC3627](https://rust-lang.github.io/rfcs/3627-match-ergonomics-2024.html) itself, the alternative [rule 4-early variant](https://rust-lang.github.io/rfcs/3627-match-ergonomics-2024.html), and [others](https://hackmd.io/zUqs2ISNQ0Wrnxsa9nhD0Q). The idea is to give us more time to iron out a final proposal.

This includes a migration lint that desugars any offending pattern into one that doesn't make use of match ergonomics. Such patterns have identical meaning across editions.

This PR insta-stabilizes the proposed behavior onto edition 2024.

r? `@ghost`

Tracking:

- https://github.com/rust-lang/rust/issues/123076
2024-10-16 19:18:30 +02:00
bors
d829780c4e Auto merge of #131481 - nnethercote:rm-GenKillSet, r=cjgillot
Remove `GenKillAnalysis`

There are two kinds of dataflow analysis in the compiler: `Analysis`, which is the basic kind, and `GenKillAnalysis`, which is a more specialized kind for gen/kill analyses that is intended as an optimization. However, it turns out that `GenKillAnalysis` is actually a  pessimization! It's faster (and much simpler) to do all the gen/kill analyses via `Analysis`. This lets us remove `GenKillAnalysis`, and `GenKillSet`, and a few other things, and also merge `AnalysisDomain` into `Analysis`. The PR removes 500 lines of code and improves performance.

r? `@tmiasko`
2024-10-16 09:45:05 +00: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
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
Matthias Krüger
4d53a28cac
Rollup merge of #131652 - compiler-errors:modifiers, r=Nadrieril,jieyouxu
Move polarity into `PolyTraitRef` rather than storing it on the side

Arguably we could move these modifiers into `TraitRef` instead of `PolyTraitRef`, but I see `TraitRef` as simply the *path* part of the trait ref. It doesn't really matter -- refactoring this further is much easier now.
2024-10-15 05:11:37 +02:00
Michael Goulet
7500e09b8b Move trait bound modifiers into hir::PolyTraitRef 2024-10-14 09:20:38 -04:00
Nicholas Nethercote
e0b83c34c3 Remove Engine::new_gen_kill.
This is an alternative to `Engine::new_generic` for gen/kill analyses.
It's supposed to be an optimization, but it has negligible effect.
The commit merges `Engine::new_generic` into `Engine::new`.

This allows the removal of various other things: `GenKillSet`,
`gen_kill_statement_effects_in_block`, `is_cfg_cyclic`.
2024-10-14 16:35:28 +11:00
Matthias Krüger
cb140dcb00
Rollup merge of #131473 - workingjubilee:move-that-abi-up, r=saethlin
compiler: `{TyAnd,}Layout` comes home

The `Layout` and `TyAndLayout` types are heavily abstract and have no particular target-specific qualities, though we do use them to answer questions particular to targets. We can keep it that way if we simply move them out of `rustc_target` and into `rustc_abi`. They bring a small entourage of connected types with them, but that's fine.

This will allow us to strengthen a few abstraction barriers over time and thus make the notoriously gnarly layout code easier to refactor. For now, we don't need to worry about that and deliberately use reexports to minimize this particular diff.
2024-10-14 06:04:28 +02:00
Trevor Gross
39071fdc58
Rollup merge of #131626 - matthiaskrgr:dont_string, r=lqd
remove a couple of redundant String to String conversion
2024-10-12 21:38:38 -05:00
Trevor Gross
19f6c17df4 Stabilize const_option
This makes the following API stable in const contexts:

    impl<T> Option<T> {
        pub const fn as_mut(&mut self) -> Option<&mut T>;
        pub const fn expect(self, msg: &str) -> T;
        pub const fn unwrap(self) -> T;
        pub const unsafe fn unwrap_unchecked(self) -> T;
        pub const fn take(&mut self) -> Option<T>;
        pub const fn replace(&mut self, value: T) -> Option<T>;
    }

    impl<T> Option<&T> {
        pub const fn copied(self) -> Option<T>
        where T: Copy;
    }

    impl<T> Option<&mut T> {
        pub const fn copied(self) -> Option<T>
        where T: Copy;
    }

    impl<T, E> Option<Result<T, E>> {
        pub const fn transpose(self) -> Result<Option<T>, E>
    }

    impl<T> Option<Option<T>> {
        pub const fn flatten(self) -> Option<T>;
    }

The following functions make use of the unstable
`const_precise_live_drops` feature:

- `expect`
- `unwrap`
- `unwrap_unchecked`
- `transpose`
- `flatten`

Fixes: <https://github.com/rust-lang/rust/issues/67441>
2024-10-12 17:07:13 -04:00
Matthias Krüger
4bc21e318c remove a couple of redundant String to String conversion 2024-10-12 22:07:46 +02:00
GnomedDev
8de8f46f78 Swap PredicateObligation to ThinVec 2024-10-12 15:17:16 +01:00
Ralf Jung
89623439f7 mark InterpResult as must_use 2024-10-12 13:13:50 +02:00
Jubilee Young
10721909f2 compiler: Wire {TyAnd,}Layout into rustc_abi
This finally unites TyAndLayout, Layout, and LayoutS into the same crate,
as one might imagine they would be placed. No functional changes.
2024-10-11 17:41:52 -07:00
bors
f4966590d8 Auto merge of #131045 - compiler-errors:remove-unnamed_fields, r=wesleywiser
Retire the `unnamed_fields` feature for now

`#![feature(unnamed_fields)]` was implemented in part in #115131 and #115367, however work on that feature has (afaict) stalled and in the mean time there have been some concerns raised (e.g.[^1][^2]) about whether `unnamed_fields` is worthwhile to have in the language, especially in its current desugaring. Because it represents a compiler implementation burden including a new kind of anonymous ADT and additional complication to field selection, and is quite prone to bugs today, I'm choosing to remove the feature.

However, since I'm not one to really write a bunch of words, I'm specifically *not* going to de-RFC this feature. This PR essentially *rolls back* the state of this feature to "RFC accepted but not yet implemented"; however if anyone wants to formally unapprove the RFC from the t-lang side, then please be my guest. I'm just not totally willing to summarize the various language-facing reasons for why this feature is or is not worthwhile, since I'm coming from the compiler side mostly.

Fixes #117942
Fixes #121161
Fixes #121263
Fixes #121299
Fixes #121722
Fixes #121799
Fixes #126969
Fixes #131041

Tracking:
* https://github.com/rust-lang/rust/issues/49804

[^1]: https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Unnamed.20struct.2Funion.20fields
[^2]: https://github.com/rust-lang/rust/issues/49804#issuecomment-1972619108
2024-10-11 13:11:13 +00:00
Michael Goulet
a7dc98733d Add variances to RPITITs 2024-10-10 11:46:48 -07:00
Michael Goulet
efb1c23ff6 Introduce SolverRelating 2024-10-10 06:07:51 -04:00