Commit Graph

2959 Commits

Author SHA1 Message Date
许杰友 Jieyou Xu (Joe)
6c60abf51a
Rollup merge of #137633 - compiler-errors:no-implied-bounds-hack-unless-bevy, r=lcnr
Only use implied bounds hack if bevy, and use deeply normalize in implied bounds hack

Consolidates the implied bounds computation mode into a single function, which deeply normalizes, and if it's in **compat** mode (for bevy), it extracts outlives bounds from the infcx.

Previously, we were using the implied bounds compat mode in two cases:
1. During WF, if it detects `ParamSet`
2. EVERYWHERE ELSE (lol) -- e.g. borrowck, predicate entailment, etc.

While I think this is fine, and the net effect was just that we emitted fewer diagnostics, it makes me uncomfortable that all crates were using the supposed "compat" code.

Fixes #137767
2025-03-05 21:46:42 +08:00
许杰友 Jieyou Xu (Joe)
5df9a9f45c
Rollup merge of #137298 - compiler-errors:mir-wf, r=lcnr
Check signature WF when lowering MIR body

Alternative to #137233.

https://github.com/rust-lang/rust/pull/137233#issuecomment-2667879143

Fixes https://github.com/rust-lang/rust/issues/137186

We do this check in `mir_drops_elaborated_and_const_checked` and not during `mir_promoted` because that may result in borrowck cycles if WF requires looking into an opaque hidden type. This causes some TAIT tests to fail unnecessarily.

r? lcnr

try-job: test-various
2025-03-05 21:46:39 +08:00
xizheyin
d7ed32b0c0
Suggest struct or union to add generic that impls trait
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-03-05 16:03:56 +08:00
Jubilee
b3d7c1483d
Rollup merge of #137913 - compiler-errors:struct-field-default-generic, r=BoxyUwU
Allow struct field default values to reference struct's generics

Right now, the default field value feature (https://github.com/rust-lang/rust/issues/132162) lowers anon consts whose types may reference ADT params that the const doesn't inherit.

This PR fixes this, so that these defaults can reference ADTs' generics, and sets the `generics_of` parenting up correctly.

There doesn't seem to be a good reason not to support this, since the anon const has a well-defined type from the field, and the anon const doesn't interact with the type system like generic parameter defaults do.

r? `````@boxyuwu````` or reassign

I could also make this into an error if this seems problematic (https://github.com/rust-lang/rust/compare/master...compiler-errors:rust:default-field-value-implicit-param?expand=1)...... but I'd rather make this work and register an open question on the tracking issue about validating that this is well-vetted.

Fixes #137896
2025-03-04 19:37:01 -08:00
Michael Goulet
d759958131 Only use implied bounds hack if bevy, and use deeply normalize in implied bounds hack 2025-03-04 18:18:48 +00:00
Michael Goulet
05a80608b3 Make rustdoc tests use always applicable negative auto impls 2025-03-04 18:04:07 +00:00
Michael Goulet
3d62b279dd Ensure that negative auto impls are always applicable 2025-03-04 17:45:18 +00:00
Noah Lev
177e7ff548 mgca: Lower all const paths as ConstArgKind::Path
When `#![feature(min_generic_const_args)]` is enabled, we now lower all
const paths in generic arg position to `hir::ConstArgKind::Path`. We
then lower assoc const paths to `ty::ConstKind::Unevaluated` since we
can no longer use the anon const expression lowering machinery. In the
process of implementing this, I factored out `hir_ty_lowering` code that
is now shared between lowering assoc types and assoc consts.

This PR also introduces a `#[type_const]` attribute for trait assoc
consts that are allowed as const args. However, we still need to
implement code to check that assoc const definitions satisfy
`#[type_const]` if present (basically is it a const path or a
monomorphic anon const).
2025-03-04 10:11:13 -05:00
Michael Goulet
3e5fddc95e Allow struct field default values to reference struct's generics 2025-03-04 01:00:55 +00:00
Michael Goulet
09e584671b Also note struct access, and fix macro expansion from foreign crates 2025-03-04 00:04:01 +00:00
Michael Goulet
06072468fe Fix associated type errors too 2025-03-03 23:53:42 +00:00
Michael Goulet
0baee2432a Don't typeck during WF, instead check outside of WF in check_crate 2025-03-03 23:09:42 +00:00
Michael Goulet
9d3d5a7fbb Check signature WF when lowering MIR body 2025-03-03 23:09:42 +00:00
Michael Goulet
c566318a78 Tweak error code for sized checks of const/static 2025-03-03 23:09:42 +00:00
Mu001999
4508f5f862 update outdated doc with new example 2025-03-02 23:21:43 +08:00
Matthias Krüger
935535d14f
Rollup merge of #137837 - fee1-dead-contrib:push-pvqvwuvrnwsy, r=compiler-errors
Update `const_conditions` and `explicit_implied_const_bounds` docs

Move documentation to query definitions, and add docs to `explicit_implied_const_bounds`.

r? project-const-traits
2025-03-01 16:03:20 +01:00
Matthias Krüger
415b207b7f
Rollup merge of #137617 - BoxyUwU:generic_const_parameter_types, r=lcnr
Introduce `feature(generic_const_parameter_types)`

Allows to define const generic parameters whose type depends on other generic parameters, e.g. `Foo<const N: usize, const ARR: [u8; N]>;`

Wasn't going to implement for this for a while until we could implement it with `bad_inference.rs` resolved but apparently the project simd folks would like to be able to use this for some intrinsics and the inference issue isn't really a huge problem there aiui. (cc ``@workingjubilee`` )
2025-03-01 11:33:58 +01:00
Deadbeef
2f4b9ddf89 Update const_conditions and explicit_implied_const_bounds docs
Move documentation to query definitions, and add docs to
`explicit_implied_const_bounds`.
2025-03-01 12:58:14 +08:00
Matthias Krüger
174bbfb369
Rollup merge of #137686 - nbdd0121:asm_const, r=compiler-errors
Handle asm const similar to inline const

Previously, asm consts are handled similar to anon consts rather than inline consts. Anon consts are not good at dealing with lifetimes, because `type_of` has lifetimes erased already. Inline consts can deal with lifetimes because they live in an outer typeck context. And since `global_asm!` lacks an outer typeck context, we have implemented asm consts with anon consts while they're in fact more similar to inline consts.

This was changed in #137180, and this means that handling asm consts as inline consts are possible. While as `@compiler-errors` pointed out, `const` currently can't be used with any types with lifetime, this is about to change if #128464 is implemented. This PR is a preparatory PR for that feature.

As an unintentional side effect, fix #117877.

cc `@Amanieu`
r? `@compiler-errors`
2025-03-01 05:49:52 +01:00
Boxy
df5b279ca9 Introduce feature(generic_const_parameter_types) 2025-02-28 20:43:15 +00:00
Jack Wrenn
91034adf30 Do not require that unsafe fields lack drop glue
Instead, we adopt the position that introducing an `unsafe` field
itself carries a safety invariant: that if you assign an invariant
to that field weaker than what the field's destructor requires,
you must ensure that field is in a droppable state in your
destructor.

See:
- https://github.com/rust-lang/rfcs/pull/3458#discussion_r1971676100
- https://rust-lang.zulipchat.com/#narrow/channel/213817-t-lang/topic/unsafe.20fields.20RFC/near/502113897
2025-02-28 16:32:06 +00:00
Gary Guo
f482460f92 Handle asm const similar to inline const 2025-02-26 19:27:19 +00:00
León Orell Valerian Liehr
2fc88233cd
Rollup merge of #137631 - TaKO8Ki:issue-137508, r=compiler-errors
Avoid collecting associated types for undefined trait

Fixes #137508
Fixes #137554
2025-02-26 19:03:56 +01:00
León Orell Valerian Liehr
cf8498d36a
Rollup merge of #137613 - davidtwco:const-traits-variances, r=compiler-errors
hir_analysis: skip self type of host effect preds in variances_of

Discovered as part of an implementation of rust-lang/rfcs#3729 - w/out this then when introducing const trait bounds: many more interesting tests change with different output, missing errors, new errors, etc related to this but they all depend on feature flags and are much more complex than this test.

r? ``@oli-obk``
2025-02-26 04:15:08 +01:00
León Orell Valerian Liehr
292c003ce7
Rollup merge of #137529 - klensy:unused3, r=lcnr
remove few unused args
2025-02-26 04:15:04 +01:00
Takayuki Maeda
b7a549725c fix #137508
rename ui tests

check if res is trait def

fix typo

regression test for #137554
2025-02-26 05:11:18 +09:00
bors
85abb27636 Auto merge of #137608 - fmease:rollup-h4siso6, r=fmease
Rollup of 8 pull requests

Successful merges:

 - #137370 (adjust_abi: make fallback logic for ABIs a bit easier to read)
 - #137444 (Improve behavior of `IF_LET_RESCOPE` around temporaries and place expressions)
 - #137464 (Fix invalid suggestion from type error for derive macro)
 - #137539 ( Add rustdoc-gui regression test for #137082 )
 - #137576 (Don't doc-comment BTreeMap<K, SetValZST, A>)
 - #137595 (remove `simd_fpow` and `simd_fpowi`)
 - #137600 (type_ir: remove redundant part of comment)
 - #137602 (feature: fix typo in attribute description)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-25 19:36:17 +00:00
León Orell Valerian Liehr
1511ccd6f8
Rollup merge of #137595 - folkertdev:remove-simd-pow-powi, r=RalfJung
remove `simd_fpow` and `simd_fpowi`

Discussed in https://github.com/rust-lang/rust/issues/137555

These functions are not exposed from `std::intrinsics::simd`, and not used anywhere outside of the compiler. They also don't lower to particularly good code at least on the major ISAs (I checked x86_64, aarch64, s390x, powerpc), where the vector is just spilled to the stack and scalar functions are used for the actual logic.

r? `@RalfJung`
2025-02-25 13:07:40 +01:00
klensy
8467a76581 remove unused field from VariantDef::new and convert debug to instrument 2025-02-25 14:43:58 +03:00
Folkert de Vries
60a268998c
remove simd_fpow and simd_fpowi 2025-02-25 09:20:10 +01:00
Oli Scherer
ffc955bcfb Don't require method impls for methods with Self:Sized bounds for impls for unsized types 2025-02-25 08:06:30 +00:00
bors
f5729cfed3 Auto merge of #137573 - compiler-errors:rollup-noq9yhp, r=compiler-errors
Rollup of 11 pull requests

Successful merges:

 - #136522 (Remove `feature(dyn_compatible_for_dispatch)` from the compiler)
 - #137289 (Consolidate and improve error messaging for `CoerceUnsized` and `DispatchFromDyn`)
 - #137321 (Correct doc about `temp_dir()` behavior on Android)
 - #137417 (rustc_target: Add more RISC-V atomic-related features)
 - #137489 (remove `#[rustc_intrinsic_must_be_overridde]`)
 - #137530 (DWARF mixed versions with LTO on MIPS)
 - #137543 (std: Fix another new symlink test on Windows)
 - #137548 (Pass correct `TypingEnv` to `InlineAsmCtxt`)
 - #137550 (Don't immediately panic if dropck fails without returning errors)
 - #137552 (Update books)
 - #137556 (rename simd_shuffle_generic → simd_shuffle_const_generic)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-25 02:24:40 +00:00
Michael Goulet
6c1f959288
Rollup merge of #137556 - RalfJung:simd_shuffle_const_generic, r=oli-obk
rename simd_shuffle_generic → simd_shuffle_const_generic

I've been confused by this name one time too often. ;)

r? `@oli-obk`
2025-02-24 19:21:51 -05:00
Michael Goulet
87f3908066
Rollup merge of #137548 - compiler-errors:asm-ty, r=oli-obk
Pass correct `TypingEnv` to `InlineAsmCtxt`

Fixes #137512

r? oli-obk
2025-02-24 19:21:49 -05:00
Michael Goulet
0bb00e2085
Rollup merge of #137289 - compiler-errors:coerce-unsized-errors, r=oli-obk
Consolidate and improve error messaging for `CoerceUnsized` and `DispatchFromDyn`

Firstly, this PR consolidates and reworks the error diagnostics for `CoercePointee` and `DispatchFromDyn`. There was a ton of duplication for no reason -- this reworks both the errors and also the error codes, since they can be shared between both traits since they report the same thing.

Secondly, when encountering a struct with multiple fields that must be coerced, point out the field spans, rather than mentioning the fields by name. This makes the error message clearer, but also means that we don't mention the `__S` dummy parameter for `derive(CoercePointee)`.

Thirdly, emit a custom error message when we encounter a trait error that comes from the recursive field `CoerceUnsized`/`DispatchFromDyn` trait check. **Note:** This is the only one I'm not too satisfied with -- I think it could use some more refinement, but ideally it explains that the field must be an unsize-able pointer... Feedback welcome.

Finally, don't emit `DispatchFromDyn` validity errors if we detect `CoerceUnsized` validity errors from an impl of the same ADT.

This is best reviewed per commit.

r? `@oli-obk` perhaps?

cc `@dingxiangfei2009` -- sorry for making my own attempt at this PR, but I wanted to see if I could implement a fix for #136796 in a less complicated way, since communicating over github review comments can be a bit slow. I'll leave comments inline to explain my thinking about the diagnostics changes.
2025-02-24 19:21:45 -05:00
Michael Goulet
b46acc0191 Deduplicate CoerceUnsized and DispatchFromDyn impl errors 2025-02-24 19:34:54 +00:00
Michael Goulet
5c5ed92c37 Simplify trait error message for CoercePointee validation 2025-02-24 19:34:54 +00:00
Michael Goulet
96d966b07a Consolidate and rework CoercePointee and DispatchFromDyn errors 2025-02-24 19:34:54 +00:00
Michael Goulet
b6899ab921 More eagerly bail in DispatchFromDyn validation 2025-02-24 19:34:54 +00:00
Michael Goulet
f3d31f77e4 Remove dyn_compatible_for_dispatch 2025-02-24 18:48:40 +00:00
Ralf Jung
0362775fb5 rename simd_shuffle_generic → simd_shuffle_const_generic 2025-02-24 19:13:23 +01:00
Michael Goulet
b2dee4226d Better error message for unsized pointers 2025-02-24 16:20:50 +00:00
Michael Goulet
04c00585c3 Properly support thin ptrs that are only thin due to their param-env in asm macro 2025-02-24 16:20:35 +00:00
Jana Dönszelmann
7e0f5b5016
Introduce new-style attribute parsers for several attributes
note: compiler compiles but librustdoc and clippy don't
2025-02-24 14:31:17 +01:00
Jana Dönszelmann
dbd3b7928e
Introduce new parsing infrastructure and types for parsed attributes
fixup docs in parser
2025-02-24 14:26:06 +01:00
Jana Dönszelmann
115b3b03b0
Change span field accesses to method calls 2025-02-24 14:22:31 +01:00
David Wood
0bed12e02d
hir_analysis: skip self type of host effect preds
Like trait predicates, the self type ought to be skipped here.
2025-02-24 10:19:16 +00:00
Trevor Gross
a2bb4d748d
Rollup merge of #136543 - RalfJung:round-ties-even, r=tgross35
intrinsics: unify rint, roundeven, nearbyint in a single round_ties_even intrinsic

LLVM has three intrinsics here that all do the same thing (when used in the default FP environment). There's no reason Rust needs to copy that historically-grown mess -- let's just have one intrinsic and leave it up to the LLVM backend to decide how to lower that.

Suggested by `@hanna-kruppe` in https://github.com/rust-lang/rust/issues/136459; Cc `@tgross35`

try-job: test-various
2025-02-23 14:30:25 -05:00
Jacob Pratt
7f14d2eba4
Rollup merge of #137334 - compiler-errors:edition-2024-fresh-2, r=saethlin,traviscross
Greatly simplify lifetime captures in edition 2024

Remove most of the `+ Captures` and `+ '_` from the compiler, since they are now unnecessary with the new edition 2021 lifetime capture rules. Use some `+ 'tcx` and `+ 'static` rather than being overly verbose with precise capturing syntax.
2025-02-23 02:44:18 -05:00
Matthias Krüger
4115f51d15
Rollup merge of #137180 - compiler-errors:sym-regions, r=oli-obk
Give `global_asm` a fake body to store typeck results, represent `sym fn` as a hir expr to fix `sym fn` operands with lifetimes

There are a few intertwined problems with `sym fn` operands in both inline and global asm macros.

Specifically, unlike other anon consts, they may evaluate to a type with free regions in them without actually having an item-level type annotation to give them a "proper" type. This is in contrast to named constants, which always have an item-level type annotation, or unnamed constants which are constrained by their position (e.g. a const arg in a turbofish, or a const array length).

Today, we infer the type of the operand by looking at the HIR typeck results; however, those results are region-erased, so during borrowck we ICE since we don't expect to encounter erased regions. We can't just fill this type with something like `'static`, since we may want to use real (free) regions:

```rust
fn foo<'a>() {
  asm!("/* ... */", sym bar::<&'a ()>);
}
```

The first idea may be to represent `sym fn` operands using *inline* consts instead of anon consts. This makes sense, since inline consts can reference regions from the parent body (like the `'a` in the example above). However, this introduces a problem with `global_asm!`, which doesn't *have* a parent body; inline consts *must* be associated with a parent body since they are not a body owner of their own. In #116087, I attempted to fix this by using two separate `sym` operands for global and inline asm. However, this led to a lot of confusion and also some unattractive code duplication.

In this PR, I adjust the lowering of `global_asm!` so that it's lowered in a "fake" HIR body. This body contains a single expression which is `ExprKind::InlineAsm`; we don't *use* this HIR body, but it's used in typeck and borrowck so that we can properly infer and validate the the lifetimes of `sym fn` operands.

I then adjust the lowering of `sym fn` to instead be represented with a HIR expression. This is both because it's no longer necessary to represent this operand as an anon const, since it's *just* a path expression, and also more importantly to sidestep yet another ICE (https://github.com/rust-lang/rust/issues/137179), which has to do with the existing code breaking an invariant of def-id creation and anon consts. Specifically, we are not allowed to synthesize a def-id for an anon const when that anon const contains expressions with def-ids whose parent is *not* that anon const. This is somewhat related to https://github.com/rust-lang/rust/pull/130443#issuecomment-2445678945, which is also a place in the compiler where synthesizing anon consts leads to def-id parenting issue.

As a side-effect, this consolidates the type checking for inline and global asm, so it allows us to simplify `InlineAsmCtxt` a bit. It also allows us to delete a bit of hacky code from anon const `type_of` which was there to detect `sym fn` operands specifically. This also could be generalized to support `const` asm operands with types with lifetimes in them. Since we specifically reject these consts today, I'm not going to change the representation of those consts (but they'd just be turned into inline consts).

r? oli-obk -- mostly b/c you're patient and also understand the breadth of the code that this touches, please reassign if you don't want to review this.

Fixes #111709
Fixes #96304
Fixes #137179
2025-02-23 00:16:19 +01:00
Michael Goulet
12e3911d81 Greatly simplify lifetime captures in edition 2024 2025-02-22 22:24:52 +00:00
Ralf Jung
d1b34acb3b make the new intrinsics safe 2025-02-22 14:12:55 +01:00
Matthias Krüger
37e0d138cf
Rollup merge of #137333 - compiler-errors:edition-2024-fresh, r=Nadrieril
Use `edition = "2024"` in the compiler (redux)

Most of this is binding mode changes, which I fixed by running `x.py fix`.

Also adds some miscellaneous `unsafe` blocks for new unsafe standard library functions (the setenv ones), and a missing `unsafe extern` block in some enzyme codegen code, and fixes some precise capturing lifetime changes (but only when they led to errors).

cc ``@ehuss`` ``@traviscross``
2025-02-22 11:36:43 +01:00
Michael Goulet
3d5438accd Fix binding mode problems 2025-02-22 00:13:19 +00:00
Michael Goulet
6ba39f7dc7 Make a fake body to store typeck results for global_asm 2025-02-22 00:12:07 +00:00
Michael Goulet
37060aae13 Initial cleanups of InlineAsmCtxt 2025-02-22 00:05:09 +00:00
Michael Goulet
2a6daaf89a Make asm a named field 2025-02-22 00:05:09 +00:00
Michael Goulet
76d341fa09 Upgrade the compiler to edition 2024 2025-02-22 00:01:48 +00:00
Matthias Krüger
085adfda3c
Rollup merge of #136787 - compiler-errors:lt2024feat, r=oli-obk
Remove `lifetime_capture_rules_2024` feature

Just use edition 2024 instead
2025-02-22 01:01:40 +01:00
Matthias Krüger
326072ac20
Rollup merge of #136458 - compiler-errors:fix-3, r=lcnr
Do not deduplicate list of associated types provided by dyn principal

## Background

The way that we handle a dyn trait type's projection bounds is very *structural* today. A dyn trait is represented as a list of `PolyExistentialPredicate`s, which in most cases will be a principal trait (like `Iterator`) and a list of projections (like `Item = u32`). Importantly, the list of projections comes from user-written associated type bounds on the type *and* from elaborating the projections from the principal's supertraits.

For example, given a set of traits like:

```rust
trait Foo<T> {
    type Assoc;
}

trait Bar<A, B>: Foo<A, Assoc = A> + Foo<B, Assoc = B> {}
```

For the type `dyn Bar<i32, u32>`, the list of projections will be something like `[Foo<i32>::Assoc = i32, Foo<u32>::Assoc = u32]`. We deduplicate these projections when they're identical, so for `dyn Bar<(), ()>` would be something like `[Foo<()>::Assoc = ()]`.

## Shortcomings 1: inference

We face problems when we begin to mix this structural notion of projection bounds with inference and associated type normalization. For example, let's try calling a generic function that takes `dyn Bar<A, B>` with a value of type `dyn Bar<(), ()>`:

```rust
trait Foo<T> {
    type Assoc;
}

trait Bar<A, B>: Foo<A, Assoc = A> + Foo<B, Assoc = B> {}

fn call_bar<A, B>(_: &dyn Bar<A, B>) {}

fn test(x: &dyn Bar<(), ()>) {
    call_bar(x);
    // ^ ERROR mismatched types
}
```

```
error[E0308]: mismatched types
  --> /home/mgx/test.rs:10:14
   |
10 |     call_bar(x);
   |     -------- ^ expected trait `Bar<_, _>`, found trait `Bar<(), ()>`
```

What's going on here? Well, when calling `call_bar`, the generic signature `&dyn Bar<?A, ?B>` does not unify with `&dyn Bar<(), ()>` because the list of projections differ -- `[Foo<?A>::Assoc = ?A, Foo<?B>::Assoc = ?B]` vs `[Foo<()>::Assoc = ()]`.

A simple solution to this may be to unify the principal traits first, then attempt to deduplicate them after inference. In this case, if we constrain `?A = ?B = ()`, then we would be able to deduplicate those projections in the first list.

However, this idea is still pretty fragile, and it's not a complete solution.

## Shortcomings 2: normalization

Consider a slightly modified example:

```rust
//@ compile-flags: -Znext-solver

trait Mirror {
    type Assoc;
}
impl<T> Mirror for T {
    type Assoc = T;
}

fn call_bar(_: &dyn Bar<(), <() as Mirror>::Assoc>) {}

fn test(x: &dyn Bar<(), ()>) {
    call_bar(x);
}
```

This fails in the new solver. In this example, we try to unify `dyn Bar<(), ()>` and `dyn Bar<(), <() as Mirror>::Assoc>`. We are faced with the same problem even though there are no inference variables, and making this work relies on eagerly and deeply normalizing all projections so that they can be structurally deduplicated.

This is incompatible with how we handle associated types in the new trait solver, and while we could perhaps support it with some major gymnastics in the new solver, it suggests more fundamental shortcomings with how we deal with projection bounds in the new solver.

## Shortcomings 3: redundant projections

Consider a final example:

```rust
trait Foo {
    type Assoc;
}

trait Bar: Foo<Assoc = ()> {}

fn call_bar1(_: &dyn Bar) {}

fn call_bar2(_: &dyn Bar<Assoc = ()>) {}

fn main() {
    let x: &dyn Bar<Assoc = _> = todo!();
    call_bar1(x);
    //~^ ERROR mismatched types
    call_bar2(x);
    //~^ ERROR mismatched types
}
```

In this case, we have a user-written associated type bound (`Assoc = _`) which overlaps the bound that comes from the supertrait projection of `Bar` (namely, `Foo<Assoc = ()>`). In a similar way to the two examples above, this causes us to have a projection list mismatch that the compiler is not able to deduplicate.

## Solution

### Do not deduplicate after elaborating projections when lowering `dyn` types

The root cause of this issue has to do with mismatches of the deduplicated projection list before and after substitution or inference. This PR aims to avoid these issues by *never* deduplicating the projection list after elaborating the list of projections from the *identity* substituted principal trait ref.

For example,

```rust
trait Foo<T> {
    type Assoc;
}

trait Bar<A, B>: Foo<A, Assoc = A> + Foo<B, Assoc = B> {}
```

When computing the projections for `dyn Bar<(), ()>`, before this PR we'd elaborate `Bar<(), ()>` to find a (deduplicated) projection list of `[Foo<()>::Assoc = ()]`.

After this PR, we take the principal trait and use its *identity* substitutions `Bar<A, B>` during elaboration, giving us projections `[Foo<A>::Assoc = A, Foo<B>::Assoc = B]`. Only after this elaboration do we substitute `A = (), B = ()` to get `[Foo<()>::Assoc = (), Foo<()>::Assoc = ()]`. This allows the type to be unified with the projections for `dyn Bar<?A, ?B>`, which are `[Foo<?A>::Assoc = ?A, Foo<?B>::Assoc = ?B]`.

This helps us avoid shorcomings 1 noted above.

### Do not deduplicate projections when relating `dyn` types

Similarly, we also do not call deduplicate when relating dyn types. This means that the list of projections does not differ depending on if the type has been normalized or not, which should avoid shortcomings 2 noted above.

Following from the example above, when relating projection lists like `[Foo<()>::Assoc = (), Foo<()>::Assoc = ()]` and `[Foo<?A>::Assoc = ?A, Foo<?B>::Assoc = ?B]`, the latter won't be deduplicated to a list of length 1 which would immediately fail to relate to the latter which is a list of length 2.

### Implement proper precedence between supertrait and user-written projection bounds when lowering `dyn` types

```rust
trait Foo {
    type Assoc;
}

trait Bar: Foo<Assoc = ()> {}
```

Given a type like `dyn Foo<Assoc = _>`, we used to previously include *both* the supertrait and user-written associated type bounds in the projection list, giving us `[Foo::Assoc = (), Foo::Assoc = _]`. This would never unify with `dyn Foo`. However, this PR implements a strategy which overwrites the supertrait associated type bound with the one provided by the user, giving us a projection list of `[Foo::Assoc = _]`.

Why is this OK? Well, if a user wrote an associated type bound that is unsatisfiable (e.g. `dyn Bar<Assoc = i32>`) then the dyn type would never implement `Bar` or `Foo` anyways. If the user wrote something that is either structurally equal or equal modulo normalization to the supertrait bound, then it should be unaffected. And if the user wrote something that needs inference guidance (e.g. `dyn Bar<Assoc = _>`), then it'll be constrained when proving `dyn Bar<Assoc = _>: Bar`.

Importantly, this differs from the strategy in https://github.com/rust-lang/rust/pull/133397, which preferred the *supertrait* bound and ignored the user-written bound. While that's also theoretically justifiable in its own way, it does lead to code which does not (and probably should not) compile either today or after this PR, like:

```rust
trait IteratorOfUnit: Iterator<Item = ()> {}
impl<T> IteratorOfUnit for T where T: Iterator<Item = ()> {}

fn main() {
    let iter = [()].into_iter();
    let iter: &dyn IteratorOfUnit<Item = i32> = &iter;
}
```

### Conclusion

This is a far less invasive change compared to #133397, and doesn't necessarily necessitate the addition of new lints or any breakage of existing code. While we could (and possibly should) eventually introduce lints to warn users of redundant or mismatched associated type bounds, we don't *need* to do so as part of fixing this unsoundness, which leads me to believe this is a much safer solution.
2025-02-22 01:01:38 +01:00
Michael Goulet
72bd174c43 Do not deduplicate list of associated types provided by dyn principal 2025-02-21 19:32:45 +00:00
Nicholas Nethercote
806be25fc9 Move methods from Map to TyCtxt, part 3.
Continuing the work from #137162.

Every method gains a `hir_` prefix.
2025-02-21 14:31:09 +11:00
Michael Goulet
b02eac37ff Restrict bevy hack 2025-02-19 03:58:31 +00:00
Matthias Krüger
a66ef2f40e
Rollup merge of #137206 - estebank:e0599-structured, r=jieyouxu
Make E0599 a structured error
2025-02-18 18:40:54 +01:00
Matthias Krüger
c8d904125e
Rollup merge of #137000 - compiler-errors:deeply-normalize-item-bounds, r=lcnr
Deeply normalize item bounds in new solver

Built on #136863.

Fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/142.
Fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/151.

cc https://github.com/rust-lang/trait-system-refactor-initiative/issues/116

First commit reworks candidate preference for projection bounds to prefer param-env projection clauses even if the corresponding trait ref doesn't come from the param-env.

Second commit adjusts the associated type item bounds check to deeply normalize in the new solver. This causes some test fallout which I will point out.

r? lcnr
2025-02-18 18:40:51 +01:00
Esteban Küber
693f7035f1 Make E0599 a structured error 2025-02-18 04:50:33 +00:00
Nicholas Nethercote
fd7b4bf4e1 Move methods from Map to TyCtxt, part 2.
Continuing the work started in #136466.

Every method gains a `hir_` prefix, though for the ones that already
have a `par_` or `try_par_` prefix I added the `hir_` after that.
2025-02-18 10:17:44 +11:00
Michael Goulet
b002b5cc82 Deeply normalize associated type bounds before proving them 2025-02-17 17:21:24 +00:00
bors
2162e9d4b1 Auto merge of #137164 - matthiaskrgr:rollup-dj5826k, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #137095 (Replace some u64 hashes with Hash64)
 - #137100 (HIR analysis: Remove unnecessary abstraction over list of clauses)
 - #137105 (Restrict DerefPure for Cow<T> impl to T = impl Clone, [impl Clone], str.)
 - #137120 (Enable `relative-path-include-bytes-132203` rustdoc-ui test on Windows)
 - #137125 (Re-add missing empty lines in the releases notes)
 - #137145 (use add-core-stubs / minicore for a few more tests)
 - #137149 (Remove SSE ABI from i586-pc-windows-msvc)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-17 11:18:33 +00:00
Nicholas Nethercote
661f99ba03 Overhaul the intravisit::Map trait.
First of all, note that `Map` has three different relevant meanings.
- The `intravisit::Map` trait.
- The `map::Map` struct.
- The `NestedFilter::Map` associated type.

The `intravisit::Map` trait is impl'd twice.
- For `!`, where the methods are all unreachable.
- For `map::Map`, which gets HIR stuff from the `TyCtxt`.

As part of getting rid of `map::Map`, this commit changes `impl
intravisit::Map for map::Map` to `impl intravisit::Map for TyCtxt`. It's
fairly straightforward except various things are renamed, because the
existing names would no longer have made sense.

- `trait intravisit::Map` becomes `trait intravisit::HirTyCtxt`, so named
  because it gets some HIR stuff from a `TyCtxt`.
- `NestedFilter::Map` assoc type becomes `NestedFilter::MaybeTyCtxt`,
  because it's always `!` or `TyCtxt`.
- `Visitor::nested_visit_map` becomes `Visitor::maybe_tcx`.

I deliberately made the new trait and associated type names different to
avoid the old `type Map: Map` situation, which I found confusing. We now
have `type MaybeTyCtxt: HirTyCtxt`.
2025-02-17 13:21:35 +11:00
Nicholas Nethercote
f86f7ad5f2 Move some Map methods onto TyCtxt.
The end goal is to eliminate `Map` altogether.

I added a `hir_` prefix to all of them, that seemed simplest. The
exceptions are `module_items` which became `hir_module_free_items` because
there was already a `hir_module_items`, and `items` which became
`hir_free_items` for consistency with `hir_module_free_items`.
2025-02-17 13:21:02 +11:00
León Orell Valerian Liehr
84bdc5de6e
HIR analysis: Remove unnecessary abstraction over list of clauses 2025-02-15 23:54:53 +01:00
bors
c241e14650 Auto merge of #136593 - lukas-code:ty-value-perf, r=oli-obk
valtree performance tuning

Summary: This PR makes type checking of code with many type-level constants faster.

After https://github.com/rust-lang/rust/pull/136180 was merged, we observed a small perf regression (https://github.com/rust-lang/rust/pull/136318#issuecomment-2635562821). This happened because that PR introduced additional copies in the fast reject code path for consts, which is very hot for certain crates: 6c1d960d88/compiler/rustc_type_ir/src/fast_reject.rs (L486-L487)

This PR improves the performance again by properly interning the valtrees so that copying and comparing them becomes faster. This will become especially useful with `feature(adt_const_params)`, so the fast reject code doesn't have to do a deep compare of the valtrees.

Note that we can't just compare the interned consts themselves in the fast reject, because sometimes `'static` lifetimes in the type are be replaced with inference variables (due to canonicalization) on one side but not the other.

A less invasive alternative that I considered is simply avoiding copies introduced by https://github.com/rust-lang/rust/pull/136180 and comparing the valtrees it in-place (see commit: 9e91e50ac5 / perf results: https://github.com/rust-lang/rust/pull/136593#issuecomment-2642303245), however that was still measurably slower than interning.

There are some minor regressions in secondary benchmarks: These happen due to changes in memory allocations and seem acceptable to me. The crates that make heavy use of valtrees show no significant changes in memory usage.
2025-02-13 15:27:30 +00:00
bors
54cdc751df Auto merge of #136965 - jhpratt:rollup-bsnqvmf, r=jhpratt
Rollup of 8 pull requests

Successful merges:

 - #134999 (Add cygwin target.)
 - #136559 (Resolve named regions when reporting type test failures in NLL)
 - #136660 (Use a trait to enforce field validity for union fields + `unsafe` fields + `unsafe<>` binder types)
 - #136858 (Parallel-compiler-related cleanup)
 - #136881 (cg_llvm: Reduce visibility of all functions in the llvm module)
 - #136888 (Always perform discr read for never pattern in EUV)
 - #136948 (Split out the `extern_system_varargs` feature)
 - #136949 (Fix import in bench for wasm)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-13 11:45:11 +00:00
Jacob Pratt
36d37966df
Rollup merge of #136948 - workingjubilee:split-off-extern-system-varargs, r=compiler-errors
Split out the `extern_system_varargs` feature

After the stabilization PR was opened, `extern "system"` functions were added to `extended_varargs_abi_support`. This has a number of questions regarding it that were not discussed and were somewhat surprising. It deserves to be considered as its own feature, separate from `extended_varargs_abi_support`.

Tracking issue:
- https://github.com/rust-lang/rust/issues/136946
2025-02-13 03:53:32 -05:00
Jacob Pratt
4ea261018a
Rollup merge of #136660 - compiler-errors:BikeshedGuaranteedNoDrop, r=lcnr
Use a trait to enforce field validity for union fields + `unsafe` fields + `unsafe<>` binder types

This PR introduces a new, internal-only trait called `BikeshedGuaranteedNoDrop`[^1] to faithfully model the field check that used to be implemented manually by `allowed_union_or_unsafe_field`.

942db6782f/compiler/rustc_hir_analysis/src/check/check.rs (L84-L115)

Copying over the doc comment from the trait:

```rust
/// Marker trait for the types that are allowed in union fields, unsafe fields,
/// and unsafe binder types.
///
/// Implemented for:
/// * `&T`, `&mut T` for all `T`,
/// * `ManuallyDrop<T>` for all `T`,
/// * tuples and arrays whose elements implement `BikeshedGuaranteedNoDrop`,
/// * or otherwise, all types that are `Copy`.
///
/// Notably, this doesn't include all trivially-destructible types for semver
/// reasons.
///
/// Bikeshed name for now.
```

As far as I am aware, there's no new behavior being guaranteed by this trait, since it operates the same as the manually implemented check. We could easily rip out this trait and go back to using the manually implemented check for union fields, however using a trait means that this code can be shared by WF for `unsafe<>` binders too. See the last commit.

The only diagnostic changes are that this now fires false-negatives for fields that are ill-formed. I don't consider that to be much of a problem though.

r? oli-obk

[^1]: Please let's not bikeshed this name lol. There's no good name for `ValidForUnsafeFieldsUnsafeBindersAndUnionFields`.
2025-02-13 03:53:30 -05:00
Michael Goulet
72b4df3772 Implement lint for definition site item shadowing too 2025-02-13 05:45:53 +00:00
Jubilee Young
4bb0c3da2c Split out the extern_system_varargs feature
After the stabilization PR was opened, `extern "system"` functions were
added to `extended_varargs_abi_support`. This has a number of questions
regarding it that were not discussed and were somewhat surprising.
It deserves to be considered as its own feature, separate from
`extended_varargs_abi_support`.
2025-02-12 19:57:45 -08:00
Michael Goulet
516afd557c Implement and use BikeshedGuaranteedNoDrop for union/unsafe field validity 2025-02-13 03:45:04 +00:00
Jacob Pratt
03e2d7ebc5
Rollup merge of #136806 - adwinwhite:cycle-in-pretty-print-rpitit, r=compiler-errors
Fix cycle when debug-printing opaque types from RPITIT

Extend #66594 to opaque types from RPITIT.

Before this PR, enabling debug logging like `RUSTC_LOG="[check_type_bounds]"` for code containing RPITIT produces a query cycle of `explicit_item_bounds`, as pretty printing for opaque type calls [it](d9a4a47b8b/compiler/rustc_middle/src/ty/print/pretty.rs (L1001)).
2025-02-12 20:09:59 -05:00
Jacob Pratt
6b9b0a0ce8
Rollup merge of #135841 - oli-obk:push-qxlnokwrkkym, r=compiler-errors
Reject `?Trait` bounds in various places where we unconditionally warned since 1.0

fixes #135730
fixes #135809

Also a breaking change, so let's see what crater says.

This has been an unconditional warning since *before* 1.0
2025-02-12 20:09:57 -05:00
Lukas Markeffsky
885e0f1b96 intern valtrees 2025-02-13 00:38:17 +01:00
bors
552a959051 Auto merge of #136918 - GuillaumeGomez:rollup-f6h21gg, r=GuillaumeGomez
Rollup of 8 pull requests

Successful merges:

 - #134981 ( Explain that in paths generics can't be set on both the enum and the variant)
 - #136698 (Replace i686-unknown-redox target with i586-unknown-redox)
 - #136767 (improve host/cross target checking)
 - #136829 ([rustdoc] Move line numbers into the `<code>` directly)
 - #136875 (Rustc dev guide subtree update)
 - #136900 (compiler: replace `ExternAbi::name` calls with formatters)
 - #136913 (Put kobzol back on review rotation)
 - #136915 (documentation fix: `f16` and `f128` are not double-precision)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-12 12:42:25 +00:00
Guillaume Gomez
30bd1b53b3
Rollup merge of #136900 - workingjubilee:format-externabi-directly, r=oli-obk
compiler: replace `ExternAbi::name` calls with formatters

Most of these just format the ABI string, so... just format ExternAbi? This makes it more consistent and less jank when we can do it.
2025-02-12 10:46:40 +01:00
Guillaume Gomez
262079b52a
Rollup merge of #134981 - estebank:issue-93993, r=BoxyUwU
Explain that in paths generics can't be set on both the enum and the variant

```
error[E0109]: type arguments are not allowed on tuple variant `TSVariant`
  --> $DIR/enum-variant-generic-args.rs:54:29
   |
LL |     Enum::<()>::TSVariant::<()>(());
   |                 ---------   ^^ type argument not allowed
   |                 |
   |                 not allowed on tuple variant `TSVariant`
   |
   = note: generic arguments are not allowed on both an enum and its variant's path segments simultaneously; they are only valid in one place or the other
help: remove the generics arguments from one of the path segments
   |
LL -     Enum::<()>::TSVariant::<()>(());
LL +     Enum::TSVariant::<()>(());
   |
LL -     Enum::<()>::TSVariant::<()>(());
LL +     Enum::<()>::TSVariant(());
   |
```

Fix #93993.
2025-02-12 10:46:36 +01:00
bors
021fb9c09a Auto merge of #136897 - workingjubilee:revert-unfcped-stab, r=WaffleLapkin
Revert "Stabilize `extended_varargs_abi_support`"

I cannot find an FCP for this, despite it being a stabilization PR which normally means we do an FCP of some kind? It would seem reasonable for _either_ compiler or lang to have FCPed it? I am thus opening a revert PR, which mostly-cleanly applies, so that we can later actually land this properly with a stability report and FCP.

- https://github.com/rust-lang/rust/issues/136896
- https://github.com/rust-lang/rust/pull/116161
- https://github.com/rust-lang/rust/issues/100189
2025-02-12 09:44:30 +00:00
Matthias Krüger
77a1d6b266
Rollup merge of #136891 - compiler-errors:unconstrained-anon-lt, r=lqd
Check sig for errors before checking for unconstrained anonymous lifetime

Fixes #136841
2025-02-12 06:07:40 +01:00
Jubilee Young
32fd1a7b72 compiler: replace ExternAbi::name calls with formatters
Most of these just format the ABI string, so... just format ExternAbi?
This makes it more consistent and less jank when we can do it.
2025-02-11 19:42:47 -08:00
Jubilee Young
d97bde059a Revert "Stabilize extended_varargs_abi_support"
This reverts commit 685f189b43.
2025-02-11 17:22:27 -08:00
Esteban Küber
23daa8c724 Remove some the spans pointing at the enum in the path and its generic args
```
error[E0109]: type arguments are not allowed on tuple variant `TSVariant`
  --> $DIR/enum-variant-generic-args.rs:54:29
   |
LL |     Enum::<()>::TSVariant::<()>(());
   |                 ---------   ^^ type argument not allowed
   |                 |
   |                 not allowed on tuple variant `TSVariant`
   |
   = note: generic arguments are not allowed on both an enum and its variant's path segments simultaneously; they are only valid in one place or the other
help: remove the generics arguments from one of the path segments
   |
LL -     Enum::<()>::TSVariant::<()>(());
LL +     Enum::<()>::TSVariant(());
   |
```
2025-02-11 23:47:56 +00:00
Esteban Küber
1b98d0ed13 Explain that in paths generics can't be set on both the enum and the variant
```
error[E0109]: type arguments are not allowed on enum `Enum` and tuple variant `TSVariant`
  --> $DIR/enum-variant-generic-args.rs:54:12
   |
LL |     Enum::<()>::TSVariant::<()>(());
   |     ----   ^^   ---------   ^^ type argument not allowed
   |     |           |
   |     |           not allowed on tuple variant `TSVariant`
   |     not allowed on enum `Enum`
   |
   = note: generic arguments are not allowed on both an enum and its variant's path segments simultaneously; they are only valid in one place or the other
help: remove the generics arguments from one of the path segments
   |
LL -     Enum::<()>::TSVariant::<()>(());
LL +     Enum::<()>::TSVariant(());
   |
```

Fix #93993.
2025-02-11 23:30:07 +00:00
Michael Goulet
6ffe6dd826 Check sig for errors before checking for unconstrained anonymous lifetime 2025-02-11 22:59:57 +00:00
Michael Goulet
f0cb746480 Lower fn items as ZST valtrees and delay a bug 2025-02-11 19:16:12 +00:00
Oli Scherer
c294da3310 Reject impl Trait bounds in various places where we unconditionally warned since 1.0 2025-02-11 09:19:37 +00:00
Adwin White
a634246b66 reduce query calls in pretty printing when finding bounds of
associated types
2025-02-11 12:30:16 +08:00
Matthias Krüger
af3c51d849
Rollup merge of #136107 - dingxiangfei2009:coerce-pointee-wellformed, r=compiler-errors
Introduce CoercePointeeWellformed for coherence checks at typeck stage

Fix #135206

This is the first PR to introduce the "wellformedness" check for `derive(CoercePointee)`.

This patch introduces a new error code to cover all the prerequisites of the said macro. The checks that is enforced with this patch is whether the data is indeed `struct` and whether the layout is set to `repr(transparent)`.

A following series of patch will arrive later to address the following concern.
1. #135217 so that we would only admit one single coercion on one type parameter, and leave the rest for future consideration in tandem of development of other coercion rules.
1. Enforcement of data field requirements.

**An open question** is whether there is a good schema to encode the `#[pointee]` as well, so that we could also check if the `#[pointee]` type parameter is indeed `?Sized`.

``@rustbot`` label F-derive_coerce_pointee
2025-02-11 02:53:42 +01:00
Michael Goulet
6fe8b8d4a0 Remove lifetime_capture_rules_2024 feature 2025-02-09 19:09:45 +00:00
Ding Xiang Fei
b9435056a7
move repr(transparent) checks to coherence 2025-02-09 20:40:43 +08:00
Ding Xiang Fei
c067324637
rename the trait to validity and place a feature gate afront 2025-02-09 20:40:42 +08:00
Ding Xiang Fei
de405dcb8f
introduce CoercePointeeWellformed for coherence checks at typeck stage 2025-02-09 20:40:41 +08:00
bjorn3
1fcae03369 Rustfmt 2025-02-08 22:12:13 +00:00
Matthias Krüger
7ca29360a7
Rollup merge of #136073 - compiler-errors:recursive-coro-always, r=oli-obk
Always compute coroutine layout for eagerly emitting recursive layout errors

Detect recursive coroutine layouts even if we don't detect opaque type recursion in the new solver. This is for two reasons:
1. It helps us detect (bad) recursive async function calls in the new solver, which due to its approach to normalization causes us to not detect this via a recursive RPIT (since the opaques are more eagerly revealed in the opaque body).
    * Fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/137.
2. It helps us detect (bad) recursive async functions behind AFITs. See the AFIT test that changed for the old solver too.
3. It also greatly simplifies the recursive impl trait check, since I can remove some jankness around how it handles coroutines.
2025-02-06 13:09:57 +01:00
Jubilee
1361ef37ff
Rollup merge of #136550 - compiler-errors:rpitit-empty-body, r=oli-obk
Fix `rustc_hidden_type_of_opaques` for RPITITs with no default body

Needed this when debugging something
2025-02-05 19:53:47 -08:00
Michael Goulet
d0b0b028a6 Eagerly detect coroutine recursion pre-mono when possible 2025-02-05 18:36:17 +00:00
León Orell Valerian Liehr
d81701b610
Rollup merge of #128045 - pnkfelix:rustc-contracts, r=oli-obk
#[contracts::requires(...)]  + #[contracts::ensures(...)]

cc https://github.com/rust-lang/rust/issues/128044

Updated contract support: attribute syntax for preconditions and postconditions, implemented via a series of desugarings  that culminates in:
1. a compile-time flag (`-Z contract-checks`) that, similar to `-Z ub-checks`, attempts to ensure that the decision of enabling/disabling contract checks is delayed until the end user program is compiled,
2. invocations of lang-items that handle invoking the precondition,  building a checker for the post-condition, and invoking that post-condition checker at the return sites for the function, and
3. intrinsics for the actual evaluation of pre- and post-condition predicates that third-party verification tools can intercept and reinterpret for their own purposes (e.g. creating shims of behavior that abstract away the function body and replace it solely with the pre- and post-conditions).

Known issues:

 * My original intent, as described in the MCP (https://github.com/rust-lang/compiler-team/issues/759) was   to have a rustc-prefixed attribute namespace (like   rustc_contracts::requires). But I could not get things working when I tried   to do rewriting via a rustc-prefixed builtin attribute-macro. So for now it  is called `contracts::requires`.

 * Our attribute macro machinery does not provide direct support for attribute arguments that are parsed like rust expressions. I spent some time trying to add that (e.g. something that would parse the attribute arguments as an AST while treating the remainder of the items as a token-tree), but its too big a lift for me to undertake. So instead I hacked in something approximating that goal, by semi-trivially desugaring the token-tree attribute contents into internal AST constucts. This may be too fragile for the long-term.
   * (In particular, it *definitely* breaks when you try to add a contract to a function like this: `fn foo1(x: i32) -> S<{ 23 }> { ... }`, because its token-tree based search for where to inject the internal AST constructs cannot immediately see that the `{ 23 }` is within a generics list. I think we can live for this for the short-term, i.e. land the work, and continue working on it while in parallel adding a new attribute variant that takes a token-tree attribute alongside an AST annotation, which would completely resolve the issue here.)

* the *intent* of `-Z contract-checks` is that it behaves like `-Z ub-checks`, in that we do not prematurely commit to including or excluding the contract evaluation in upstream crates (most notably, `core` and `std`). But the current test suite does not actually *check* that this is the case. Ideally the test suite would be extended with a multi-crate test that explores the matrix of enabling/disabling contracts on both the upstream lib and final ("leaf") bin crates.
2025-02-05 05:03:01 +01:00
bors
bef3c3b01f Auto merge of #136549 - matthiaskrgr:rollup-sqbpgtd, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #136242 (Remove `LateContext::match_def_path()`)
 - #136274 (Check Sizedness of return type in WF)
 - #136284 (Allow using named consts in pattern types)
 - #136477 (Fix a couple NLL TLS spans )
 - #136497 (Report generic mismatches when calling bodyless trait functions)
 - #136520 (Remove unnecessary layout assertions for object-safe receivers)
 - #136526 (mir_build: Rename `thir::cx::Cx` to `ThirBuildCx` and remove `UserAnnotatedTyHelpers`)

Failed merges:

 - #136304 (Reject negative literals for unsigned or char types in pattern ranges and literals)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-04 20:55:34 +00:00
Michael Goulet
009feeb83e Fix rustc_hidden_type_of_opaques for RPITITs with no default body 2025-02-04 17:56:47 +00:00
Matthias Krüger
b07fa7696b
Rollup merge of #136284 - oli-obk:push-zsxuwnzmonnl, r=lcnr
Allow using named consts in pattern types

This required a refactoring first: I had to stop using `hir::Pat`in `hir::TyKind::Pat` and instead create a separate `TyPat` that has `ConstArg` for range ends instead of `PatExpr`. Within the type system we should be using `ConstArg` for all constants, as otherwise we'd be maintaining two separate const systems that could diverge. The big advantage of this PR is that we now inherit all the rules from const generics and don't have a separate system. While this makes things harder for users (const generic rules wrt what is allowed in those consts), it also means we don't accidentally allow some things like referring to assoc consts or doing math on generic consts.
2025-02-04 18:49:37 +01:00
Matthias Krüger
a8ecb79d19
Rollup merge of #136274 - compiler-errors:sized-wf, r=lcnr
Check Sizedness of return type in WF

Still need to clean this up a bit. This should fix https://github.com/rust-lang/trait-system-refactor-initiative/issues/150.

r? lcnr
2025-02-04 18:49:37 +01:00
bors
3f33b30e19 Auto merge of #135760 - scottmcm:disjoint-bitor, r=WaffleLapkin
Add `unchecked_disjoint_bitor` per ACP373

Following the names from libs-api in https://github.com/rust-lang/libs-team/issues/373#issuecomment-2085686057

Includes a fallback implementation so this doesn't have to update cg_clif or cg_gcc, and overrides it in cg_llvm to use `or disjoint`, which [is available in LLVM 18](https://releases.llvm.org/18.1.0/docs/LangRef.html#or-instruction) so hopefully we don't need any version checks.
2025-02-04 17:46:06 +00:00
Ralf Jung
04e7a10af6 intrinsics: unify rint, roundeven, nearbyint in a single round_ties_even intrinsic 2025-02-04 16:27:29 +01:00
Oli Scherer
fbcaa9b0a1 Allow using named consts in pattern types 2025-02-04 15:17:31 +00:00
Celina G. Val
2bb1464cb6 Improve contracts intrisics and remove wrapper function
1. Document the new intrinsics.
2. Make the intrinsics actually check the contract if enabled, and
   remove `contract::check_requires` function.
3. Use panic with no unwind in case contract is using to check for
   safety, we probably don't want to unwind. Following the same
   reasoning as UB checks.
2025-02-03 13:55:15 -08:00
Felix S. Klock II
bcb8565f30 Contracts core intrinsics.
These are hooks to:

  1. control whether contract checks are run
  2. allow 3rd party tools to intercept and reintepret the results of running contracts.
2025-02-03 12:53:57 -08:00
Michael Goulet
23ab0f2cdc Check Sizedness of return type in WF 2025-02-03 19:00:22 +00:00
许杰友 Jieyou Xu (Joe)
1df7b30926
Rollup merge of #136432 - fmease:lta-fix-def-site-checks, r=compiler-errors
LTA: Actually check where-clauses for well-formedness at the def site

All of the added tests used to wrongfully pass.

r? oli-obk or types/compiler or reassign
2025-02-03 19:13:27 +08:00
Oli Scherer
f0308938ba Use a different hir type for patterns in pattern types than we use in match patterns 2025-02-03 08:18:30 +00:00
León Orell Valerian Liehr
c371363650
LTA: Check where-clauses for well-formedness at the def site 2025-02-03 03:43:14 +01:00
Oli Scherer
7e4ccc2f12 Maintain a list of types permitted per pattern 2025-02-02 19:30:53 +00:00
Matthias Krüger
3559a48b8e
Rollup merge of #136368 - estebank:listify, r=fee1-dead
Make comma separated lists of anything easier to make for errors

Provide a new function `listify`, meant to be used in cases similar to `pluralize!`. When you have a slice of arbitrary elements that need to be presented to the user, `listify` allows you to turn that into a list of comma separated strings.

This reduces a lot of redundant logic that happens often in diagnostics.
2025-02-02 12:31:57 +01:00
Scott McMurray
f23025305f Add unchecked_disjoint_bitor with fallback intrinsic implementation 2025-01-31 22:29:08 -08:00
Zalathar
3581512fb8 Use an explicit type when discarding the result of tcx.ensure_ok() 2025-02-01 12:42:41 +11:00
Zalathar
24cdaa146a Rename tcx.ensure() to tcx.ensure_ok() 2025-02-01 12:38:54 +11:00
Esteban Küber
8e9422f94e Make comma separated lists of anything easier to make for errors
Provide a new function `listify`, meant to be used in cases similar to `pluralize!`. When you have a slice of arbitrary elements that need to be presented to the user, `listify` allows you to turn that into a list of comma separated strings.

This reduces a lot of redundant logic that happens often in diagnostics.
2025-01-31 20:36:44 +00:00
bors
854f22563c Auto merge of #136350 - matthiaskrgr:rollup-6eqfyvh, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #134531 ([rustdoc] Add `--extract-doctests` command-line flag)
 - #135860 (Compiler: Finalize dyn compatibility renaming)
 - #135992 (Improve documentation when adding a new target)
 - #136194 (Support clobber_abi in BPF inline assembly)
 - #136325 (Delay a bug when indexing unsized slices)
 - #136326 (Replace our `LLVMRustDIBuilderRef` with LLVM-C's `LLVMDIBuilderRef`)
 - #136330 (Remove unnecessary hooks)
 - #136336 (Overhaul `rustc_middle::util`)
 - #136341 (Remove myself from vacation)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-31 20:16:46 +00:00
Matthias Krüger
308ea7120b
Rollup merge of #135860 - fmease:compiler-mv-obj-save-dyn-compat-ii, r=jieyouxu
Compiler: Finalize dyn compatibility renaming

Update the Reference link to use the new URL fragment from https://github.com/rust-lang/reference/pull/1666 (this change has finally hit stable). Fixes a FIXME.

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

~~Blocking it on #133372.~~ (merged)

r? ghost
2025-01-31 12:28:15 +01:00
bors
7f36543a48 Auto merge of #136332 - jhpratt:rollup-aa69d0e, r=jhpratt
Rollup of 9 pull requests

Successful merges:

 - #132156 (When encountering unexpected closure return type, point at return type/expression)
 - #133429 (Autodiff Upstreaming - rustc_codegen_ssa, rustc_middle)
 - #136281 (`rustc_hir_analysis` cleanups)
 - #136297 (Fix a typo in profile-guided-optimization.md)
 - #136300 (atomic: extend compare_and_swap migration docs)
 - #136310 (normalize `*.long-type.txt` paths for compare-mode tests)
 - #136312 (Disable `overflow_delimited_expr` in edition 2024)
 - #136313 (Filter out RPITITs when suggesting unconstrained assoc type on too many generics)
 - #136323 (Fix a typo in conventions.md)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-31 09:42:28 +00:00
bors
25a16572a3 Auto merge of #136331 - jhpratt:rollup-curo1f4, r=jhpratt
Rollup of 8 pull requests

Successful merges:

 - #135414 (Stabilize `const_black_box`)
 - #136150 (ci: use windows 2025 for i686-mingw)
 - #136258 (rustdoc: rename `issue-\d+.rs` tests to have meaningful names (part 11))
 - #136270 (Remove `NamedVarMap`.)
 - #136278 (add constraint graph to polonius MIR dump)
 - #136287 (LLVM changed the nocapture attribute to captures(none))
 - #136291 (some test suite cleanups)
 - #136296 (float::min/max: mention the non-determinism around signed 0)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-31 06:55:04 +00:00
Jacob Pratt
e6285b8ff1
Rollup merge of #136313 - compiler-errors:too-many-args, r=lqd
Filter out RPITITs when suggesting unconstrained assoc type on too many generics

Fixes #136233
2025-01-31 00:26:34 -05:00
Jacob Pratt
940b45f27c
Rollup merge of #136281 - nnethercote:rustc_hir_analysis, r=lcnr
`rustc_hir_analysis` cleanups

Just some improvements I found while looking through this code.

r? `@lcnr`
2025-01-31 00:26:31 -05:00
Jacob Pratt
dcf1134386
Rollup merge of #136270 - nnethercote:rm-NamedVarMap, r=jackh726
Remove `NamedVarMap`.

`NamedVarMap` is extremely similar to `ResolveBoundVars`. The former contains two `UnordMap<ItemLocalId, T>` fields (obscured behind `ItemLocalMap` typedefs). The latter contains two
`SortedMap<ItemLocalId, T>` fields. We construct a `NamedVarMap` and then convert it into a `ResolveBoundVars` by sorting the `UnordMap`s, which is unnecessary busywork.

This commit removes `NamedVarMap` and constructs a `ResolveBoundVars` directly. `SortedMap` and `NamedVarMap` have slightly different perf characteristics during construction (e.g. speed of insertion) but this code isn't hot enough for that to matter.

A few details to note.
- A `FIXME` comment is removed.
- The detailed comments on the fields of `NamedVarMap` are copied to `ResolveBoundVars` (which has a single, incorrect comment).
- `BoundVarContext::map` is renamed.
- `ResolveBoundVars` gets a derived `Default` impl.

r? `@jackh726`
2025-01-31 00:25:36 -05:00
Nicholas Nethercote
483307f127 Don't export rustc_hir_analysis::collect.
Instead re-export `rustc_hir_analysis::collect::suggest_impl_trait`,
which is the only thing from the module used in another crate. This
fixes a `FIXME` comment. Also adjust some visibilities to satisfy the
`unreachable_pub` lint.

This changes requires downgrading a link in a comment on `FnCtxt`
because `collect` is no longer public and rustdoc complains otherwise.
This is annoying but I can't see how to avoid it.
2025-01-31 08:36:30 +11:00
Nicholas Nethercote
29317604d1 Remove xform submodule.
It used to be bigger, with an `Xform` trait, but now it has just a
single function.
2025-01-31 08:28:28 +11:00
Nicholas Nethercote
4e2ef694f3 Remove an unnecessary loop label. 2025-01-31 08:28:28 +11:00
Nicholas Nethercote
d8be00fd44 Fix a comment typo. 2025-01-31 08:28:14 +11:00
Nicholas Nethercote
40db88979d Use .and chaining to improve readability. 2025-01-31 08:27:16 +11:00
Nicholas Nethercote
ceb09de256 Remove an unnecessary lifetime from RemapLateParam. 2025-01-31 08:27:15 +11:00
Nicholas Nethercote
c2e37d32d5 Remove an unused arg from the trait method provided_kind. 2025-01-31 08:27:15 +11:00
Nicholas Nethercote
969d9336ca Remove unnecessary builders.
`delegation.rs` has three builders: `GenericsBuilder`,
`PredicatesBuilder`, and `GenericArgsBuilder`. The first two builders
have just two optional parameters, and the third one has zero. Each
builder is used within a single function. The code is over-engineered.

This commit removes the builders, replacing each with with a single
`build_*` function. This makes the code shorter and simpler.
2025-01-31 08:27:15 +11:00
Nicholas Nethercote
7be593e379 Format delegation.rs better.
There is a comment `Delegation to inherent methods is not yet
supported.` that appears three times mid-pattern and somehow inhibits
rustfmt from formatting the enclosing `match` statement. This commit
moves them to the top of the pattern, which enables more formatting.
2025-01-31 08:27:15 +11:00
Nicholas Nethercote
cab629fbd2 Merge two identical match arms.
Note: `inherit_predicates_for_delegation_item` already has these cases
merged.
2025-01-31 08:27:15 +11:00
Nicholas Nethercote
2dbe9fd8a6 Remove an out-of-date FIXME comment.
This comment made sense when this crate was called `rustc_typeck`, but
makes less sense now that it's called `rustc_hir_analysis`. Especially
given that `check_drop_impl` is only called within the crate.
2025-01-31 08:27:15 +11:00
Nicholas Nethercote
f453f930ab Merge two match arms that are identical.
Also rewrite the merged arm slightly to more closely match the arm above
it.
2025-01-31 08:27:15 +11:00
Nicholas Nethercote
b546334f6c Avoid a duplicated error case in fn_sig_suggestion. 2025-01-31 08:27:15 +11:00
Nicholas Nethercote
97d1b0cbcd Clarify a comment.
I was confused here for a bit.
2025-01-31 08:27:15 +11:00
Michael Goulet
88d7ea36e9 Filter out RPITITs when suggesting unconstrained assoc type on too many generics 2025-01-30 18:51:49 +00:00
Esteban Küber
d116767113 review comment: change span argument 2025-01-30 18:38:42 +00:00
Esteban Küber
d3a148fe07 When encountering unexpected closure return type, point at return type/expression
```
error[E0271]: expected `{closure@fallback-closure-wrap.rs:18:40}` to be a closure that returns `()`, but it returns `!`
  --> $DIR/fallback-closure-wrap.rs:19:9
   |
LL |     let error = Closure::wrap(Box::new(move || {
   |                                        -------
LL |         panic!("Can't connect to server.");
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found `!`
   |
   = note: expected unit type `()`
                   found type `!`
   = note: required for the cast from `Box<{closure@$DIR/fallback-closure-wrap.rs:18:40: 18:47}>` to `Box<dyn FnMut()>`
```

```
error[E0271]: expected `{closure@dont-ice-for-type-mismatch-in-closure-in-async.rs:6:10}` to be a closure that returns `bool`, but it returns `Option<()>`
  --> $DIR/dont-ice-for-type-mismatch-in-closure-in-async.rs:6:16
   |
LL |     call(|| -> Option<()> {
   |     ---- ------^^^^^^^^^^
   |     |          |
   |     |          expected `bool`, found `Option<()>`
   |     required by a bound introduced by this call
   |
   = note: expected type `bool`
              found enum `Option<()>`
note: required by a bound in `call`
  --> $DIR/dont-ice-for-type-mismatch-in-closure-in-async.rs:3:25
   |
LL | fn call(_: impl Fn() -> bool) {}
   |                         ^^^^ required by this bound in `call`
```

```
error[E0271]: expected `{closure@f670.rs:28:13}` to be a closure that returns `Result<(), _>`, but it returns `!`
    --> f670.rs:28:20
     |
28   |     let c = |e| -> ! {
     |             -------^
     |                    |
     |                    expected `Result<(), _>`, found `!`
...
32   |     f().or_else(c);
     |         ------- required by a bound introduced by this call
-Ztrack-diagnostics: created at compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs:1433:28
     |
     = note: expected enum `Result<(), _>`
                found type `!`
note: required by a bound in `Result::<T, E>::or_else`
    --> /home/gh-estebank/rust/library/core/src/result.rs:1406:39
     |
1406 |     pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
     |                                       ^^^^^^^^^^^^ required by this bound in `Result::<T, E>::or_else`
```
2025-01-30 18:38:37 +00:00
Michael Goulet
fdc4bd22b7 Do not treat vtable supertraits as distinct when bound with different bound vars 2025-01-30 15:33:58 +00:00
Michael Goulet
08d7e9dfe5 Rework rustc_dump_vtable 2025-01-30 15:30:04 +00:00
bors
5a45ab9738 Auto merge of #136038 - compiler-errors:outlives, r=lcnr
Simplify and consolidate the way we handle construct `OutlivesEnvironment` for lexical region resolution

This is best reviewed commit-by-commit. I tried to consolidate the API for lexical region resolution *first*, then change the API when it was finally behind a single surface.

r? lcnr or reassign
2025-01-30 11:40:32 +00:00
Nicholas Nethercote
022c0ce947 Remove NamedVarMap.
`NamedVarMap` is extremely similar to `ResolveBoundVars`. The former
contains two `UnordMap<ItemLocalId, T>` fields (obscured behind
`ItemLocalMap` typedefs). The latter contains two
`SortedMap<ItemLocalId, T>` fields. We construct a `NamedVarMap` and
then convert it into a `ResolveBoundVars` by sorting the `UnordMap`s,
which is unnecessary busywork.

This commit removes `NamedVarMap` and constructs a `ResolveBoundVars`
directly. `SortedMap` and `NamedVarMap` have slightly different
perf characteristics during construction (e.g. speed of insertion) but
this code isn't hot enough for that to matter.

A few details to note.
- A `FIXME` comment is removed.
- The detailed comments on the fields of `NamedVarMap` are copied to
  `ResolveBoundVars` (which has a single, incorrect comment).
- `BoundVarContext::map` is renamed.
- `ResolveBoundVars` gets a derived `Default` impl.
2025-01-30 09:39:52 +11:00
Oli Scherer
f47ad71059 Eliminate PatKind::Path 2025-01-29 15:45:13 +00:00
Michael Goulet
009d68740f Make item self/non-self bound naming less whack 2025-01-28 19:08:50 +00:00
Michael Goulet
48b7e38c06 Move outlives env computation into methods 2025-01-28 18:55:03 +00:00
Michael Goulet
2b8930c71c Consolidate OutlivesEnv construction with resolve_regions 2025-01-28 18:55:03 +00:00
Guillaume Gomez
03fdcffa1e
Rollup merge of #136114 - compiler-errors:more-idents, r=jieyouxu
Use identifiers more in diagnostics code

This should make the diagnostics code slightly more correct when rendering idents in mixed crate edition situations. Kinda a no-op, but a cleanup regardless.

r? oli-obk or reassign
2025-01-27 15:38:30 +01:00
Michael Goulet
c08624d8d2 Remove redundant to_ident_string calls 2025-01-27 01:23:34 +00:00
Michael Goulet
ac1c6c50f4 Use identifiers in diagnostics more often 2025-01-27 01:23:34 +00:00
FedericoBruzzone
cef97bce7b Add TooGeneric variant to LayoutError and emit Unknown one
- `check-pass` test for a MRE of #135020
- fail test for #135138
- switch to `TooGeneric` for checking CMSE fn signatures
- switch to `TooGeneric` for compute `SizeSkeleton` (for transmute)
- fix broken tests
2025-01-27 00:37:34 +01:00
León Orell Valerian Liehr
57b5d3af62
Compiler: Finalize dyn compatibility renaming 2025-01-26 21:20:31 +01:00
Jacob Pratt
6cf4204790
Rollup merge of #135951 - yotamofek:use-debug-helpers, r=SparrowLii
Use `fmt::from_fn` in more places in the compiler

Use the unstable functions from #117729 in more places in the compiler, follow up to #135494
2025-01-25 23:27:00 -05:00
Matthias Krüger
9ffe558455
Rollup merge of #135971 - compiler-errors:self-projection, r=fmease
Properly report error when object type param default references self

I accidentally broke this error for cases where a type parameter references `Self` via a projection (i.e. `trait Foo<Arg = Self::Bar> {}`). This PR fixes that, and also makes the error a bit easier to understand.

Fixes #135918
2025-01-25 08:03:33 +01:00
Yotam Ofek
8b57fd9e43 use fmt::from_fn in more places, instead of using structs that impl formatting traits 2025-01-24 14:45:56 +00:00
bors
8231e8599e Auto merge of #135272 - BoxyUwU:generic_arg_infer_reliability_2, r=compiler-errors
Forbid usage of `hir` `Infer` const/ty variants in ambiguous contexts

The feature `generic_arg_infer` allows providing `_` as an argument to const generics in order to infer them. This introduces a syntactic ambiguity as to whether generic arguments are type or const arguments. In order to get around this we introduced a fourth `GenericArg` variant, `Infer` used to represent `_` as an argument to generic parameters when we don't know if its a type or a const argument.

This made hir visitors that care about `TyKind::Infer` or `ConstArgKind::Infer` very error prone as checking for `TyKind::Infer`s in  `visit_ty` would find *some* type infer arguments but not *all* of them as they would sometimes be lowered to `GenericArg::Infer` instead.

Additionally the `visit_infer` method would previously only visit `GenericArg::Infer` not *all* infers (e.g. `TyKind::Infer`), this made it very easy to override `visit_infer` and expect it to visit all infers when in reality it would only visit *some* infers.

---

This PR aims to fix those issues by making the `TyKind` and `ConstArgKind` types generic over whether the infer types/consts are represented by `Ty/ConstArgKind::Infer` or out of line (e.g. by a `GenericArg::Infer` or accessible by overiding `visit_infer`). We then make HIR Visitors convert all const args and types to the versions where infer vars are stored out of line and call `visit_infer` in cases where a `Ty`/`Const` would previously have had a `Ty/ConstArgKind::Infer` variant:

API Summary
```rust
enum AmbigArg {}

enum Ty/ConstArgKind<Unambig = ()> {
   ...
   Infer(Unambig),
}

impl Ty/ConstArg {
  fn try_as_ambig_ty/ct(self) -> Option<Ty/ConstArg<AmbigArg>>;
}
impl Ty/ConstArg<AmbigArg> {
  fn as_unambig_ty/ct(self) -> Ty/ConstArg;
}

enum InferKind {
  Ty(Ty),
  Const(ConstArg),
  Ambig(InferArg),
}

trait Visitor {
  ...
  fn visit_ty/const_arg(&mut self, Ty/ConstArg<AmbigArg>) -> Self::Result;
  fn visit_infer(&mut self, id: HirId, sp: Span, kind: InferKind) -> Self::Result;
}

// blanket impl'd, not meant to be overriden
trait VisitorExt {
  fn visit_ty/const_arg_unambig(&mut self, Ty/ConstArg) -> Self::Result;
}

fn walk_unambig_ty/const_arg(&mut V, Ty/ConstArg) -> Self::Result;
fn walk_ty/const_arg(&mut V, Ty/ConstArg<AmbigArg>) -> Self::Result;
```

The end result is that `visit_infer` visits *all* infer args and is also the *only* way to visit an infer arg, `visit_ty` and `visit_const_arg` can now no longer encounter a `Ty/ConstArgKind::Infer`. Representing this in the type system means that it is now very difficult to mess things up, either accessing `TyKind::Infer` "just works" and you won't miss *some* type infers- or it doesn't work and you have to look at `visit_infer` or some `GenericArg::Infer` which forces you to think about the full complexity involved.

Unfortunately there is no lint right now about explicitly matching on uninhabited variants, I can't find the context for why this is the case 🤷‍♀️

I'm not convinced the framing of un/ambig ty/consts is necessarily the right one but I'm not sure what would be better. I somewhat like calling them full/partial types based on the fact that `Ty<Partial>`/`Ty<Full>` directly specifies how many of the type kinds are actually represented compared to `Ty<Ambig>` which which leaves that to the reader to figure out based on the logical consequences of it the type being in an ambiguous position.

---

tool changes have been modified in their own commits for easier reviewing by anyone getting cc'd from subtree changes. I also attempted to split out "bug fixes arising from the refactoring" into their own commit so they arent lumped in with a big general refactor commit

Fixes #112110
2025-01-24 11:12:01 +00:00
Matthias Krüger
efb8084672
Rollup merge of #135865 - zachs18:maybe_report_similar_assoc_fn_more, r=compiler-errors
For E0223, suggest associated functions that are similar to the path, even if the base type has multiple inherent impl blocks.

Currently, the "help: there is an associated function with a similar name `from_utf8`" suggestion for `String::from::utf8` is only given if `String` has exactly one inherent `impl` item. This PR makes the suggestion be emitted even if the base type has multiple inherent `impl` items.

Example:

```rust
struct Foo;
impl Foo {
    fn bar_baz() {}
}
impl Foo {} // load-bearing
fn main() {
    Foo::bar::baz;
}
```

Nightly/stable output:

```rust
error[E0223]: ambiguous associated type
 --> f.rs:7:5
  |
7 |     Foo::bar::baz;
  |     ^^^^^^^^
  |
help: if there were a trait named `Example` with associated type `bar` implemented for `Foo`, you could use the fully-qualified path
  |
7 |     <Foo as Example>::bar::baz;
  |     ~~~~~~~~~~~~~~~~~~~~~

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0223`.
```

Output with this PR, or without the load-bearing empty impl on nightly/stable:

```rust
error[E0223]: ambiguous associated type
 --> f.rs:7:5
  |
7 |     Foo::bar::baz;
  |     ^^^^^^^^
  |
help: there is an associated function with a similar name: `bar_baz`
  |
7 |     Foo::bar_baz;
  |          ~~~~~~~

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0223`.
```

Ideally, this suggestion would also work for non-ADT types like ~~`str::char::indices`~~ (edit: latest commit makes this work with primitives)  or `<dyn Any>::downcast::mut_unchecked`, but that seemed to be a harder change.

`@rustbot` label +A-diagnostics
2025-01-24 08:08:08 +01:00
Michael Goulet
ea9a253ff1 Properly report error when object type param default references self 2025-01-24 04:07:10 +00:00
Boxy
2bdeff2fb8 visit_x_unambig 2025-01-23 06:01:36 +00:00
Boxy
7c8c6d2497 Semantic changes from new hir representation
Always lower to `GenericArg::Infer`
Update `PlaceholderCollector`
Update closure lifetime binder infer var visitor
Fallback visitor handle ambig infer args
Ensure type infer args have their type recorded
2025-01-23 06:01:36 +00:00
Boxy
98d80e22d0 Split hir TyKind and ConstArgKind in two and update hir::Visitor 2025-01-23 06:01:36 +00:00
Boxy
0f10ba60ff Make hir::TyKind::TraitObject use tagged ptr 2025-01-23 06:01:36 +00:00
Matthias Krüger
ef0e6863c6
Rollup merge of #135816 - BoxyUwU:root_normalizes_to_goal_ice, r=lcnr
Use `structurally_normalize` instead of manual `normalizes-to` goals in alias relate errors

r? `@lcnr`

I added `structurally_normalize_term` so that code that is generic over ty or const can use the structurally normalize helpers. See `tests/ui/traits/next-solver/diagnostics/alias_relate_error_uses_structurally_normalize.rs` for a description of the reason for the (now fixed) ICEs
2025-01-22 19:29:39 +01:00
Taylor Cramer
d00d4dfe0d Refactor dyn-compatibility error and suggestions
This CL makes a number of small changes to dyn compatibility errors:
- "object safety" has been renamed to "dyn-compatibility" throughout
- "Convert to enum" suggestions are no longer generated when there
  exists a type-generic impl of the trait or an impl for `dyn OtherTrait`
- Several error messages are reorganized for user readability

Additionally, the dyn compatibility error creation code has been
split out into functions.

cc #132713
cc #133267
2025-01-22 09:20:57 -08:00
Zachary S
7e1a8bd633 Also check for associated fns on primitives in E0223 similar-path check. 2025-01-22 02:13:10 -06:00
Zachary S
6702df109e For E0223, suggest associated functions that are similar to the path, even if there are multiple inherent impls to check. 2025-01-22 02:13:10 -06:00
Boxy
b99f59bbd6 Rename structurally_normalize to structurally_normalize_ty 2025-01-22 07:04:53 +00:00
Matthias Krüger
4af3ff8cd1
Rollup merge of #135706 - compiler-errors:elaborate, r=lcnr
Move `supertrait_def_ids` into the elaborate module like all other fns

It's strange that this is the only elaborate-like fn on tcx.

r? lcnr
2025-01-21 23:30:18 +01:00
bors
ed43cbcb88 Auto merge of #134299 - RalfJung:remove-start, r=compiler-errors
remove support for the (unstable) #[start] attribute

As explained by `@Noratrieb:`
`#[start]` should be deleted. It's nothing but an accidentally leaked implementation detail that's a not very useful mix between "portable" entrypoint logic and bad abstraction.

I think the way the stable user-facing entrypoint should work (and works today on stable) is pretty simple:
- `std`-using cross-platform programs should use `fn main()`. the compiler, together with `std`, will then ensure that code ends up at `main` (by having a platform-specific entrypoint that gets directed through `lang_start` in `std` to `main` - but that's just an implementation detail)
- `no_std` platform-specific programs should use `#![no_main]` and define their own platform-specific entrypoint symbol with `#[no_mangle]`, like `main`, `_start`, `WinMain` or `my_embedded_platform_wants_to_start_here`. most of them only support a single platform anyways, and need cfg for the different platform's ways of passing arguments or other things *anyways*

`#[start]` is in a super weird position of being neither of those two. It tries to pretend that it's cross-platform, but its signature is  a total lie. Those arguments are just stubbed out to zero on ~~Windows~~ wasm, for example. It also only handles the platform-specific entrypoints for a few platforms that are supported by `std`, like Windows or Unix-likes. `my_embedded_platform_wants_to_start_here` can't use it, and neither could a libc-less Linux program.
So we have an attribute that only works in some cases anyways, that has a signature that's a total lie (and a signature that, as I might want to add, has changed recently, and that I definitely would not be comfortable giving *any* stability guarantees on), and where there's a pretty easy way to get things working without it in the first place.

Note that this feature has **not** been RFCed in the first place.

*This comment was posted [in May](https://github.com/rust-lang/rust/issues/29633#issuecomment-2088596042) and so far nobody spoke up in that issue with a usecase that would require keeping the attribute.*

Closes https://github.com/rust-lang/rust/issues/29633

try-job: x86_64-gnu-nopt
try-job: x86_64-msvc-1
try-job: x86_64-msvc-2
try-job: test-various
2025-01-21 19:46:20 +00:00
Michael Goulet
45929a8f46 Move supertrait_def_ids into the elaborate module like all other fns 2025-01-21 17:36:57 +00:00
Ralf Jung
56c90dc31e remove support for the #[start] attribute 2025-01-21 06:59:15 -07:00
bors
cd805f09ff Auto merge of #133830 - compiler-errors:span-key, r=lcnr
Rework dyn trait lowering to stop being so intertwined with trait alias expansion

This PR reworks the trait object lowering code to stop handling trait aliases so funky, and removes the `TraitAliasExpander` in favor of a much simpler design. This refactoring is important for making the code that I'm writing in https://github.com/rust-lang/rust/pull/133397 understandable and easy to maintain, so the diagnostics regressions are IMO inevitable.

In the old trait object lowering code, we used to be a bit sloppy with the lists of traits in their unexpanded and expanded forms. This PR largely rewrites this logic to expand the trait aliases *once* and handle them more responsibly throughout afterwards.

Please review this with whitespace disabled.

r? lcnr
2025-01-21 12:33:33 +00:00
yukang
865a09d50a remove unnecessary assertion for reference error 2025-01-17 15:41:05 +08:00
bors
99db2737c9 Auto merge of #134504 - oli-obk:push-rltsvnyttwll, r=compiler-errors
Use trait definition cycle detection for trait alias definitions, too

fixes #133901

In general doing this for `All` is not right, but this code path is specifically for traits and trait aliases, and there we only ever use `All` for trait aliases.
2025-01-16 18:46:28 +00:00
bors
341f60327f Auto merge of #134353 - oli-obk:safe-target-feature-unsafe-by-default, r=wesleywiser
Treat safe target_feature functions as unsafe by default [less invasive variant]

This unblocks
* #134090

As I stated in https://github.com/rust-lang/rust/pull/134090#issuecomment-2541332415 I think the previous impl was too easy to get wrong, as by default it treated safe target feature functions as safe and had to add additional checks for when they weren't. Now the logic is inverted. By default they are unsafe and you have to explicitly handle safe target feature functions.

This is the less (imo) invasive variant of #134317, as it doesn't require changing the Safety enum, so it only affects FnDefs and nothing else, as it should.
2025-01-15 12:06:56 +00:00
Jubilee
f256f9ef22
Rollup merge of #135228 - compiler-errors:normalizes-ur-dispatch, r=BoxyUwU
Improve `DispatchFromDyn` and `CoerceUnsized` impl validation

* Disallow arbitrary 1-ZST fields in `DispatchFromDyn` -- only `PhantomData`, and 1-ZSTs that mention no params (which is needed to support, e.g., the `Global` alloctor in `Box<T, U = Global>`).
* Don't allow coercing between non-ZSTs to ZSTs (since the previous check wasn't actually checking the field tys were the same before checking the layout...)
* Normalize the field before checking it's `PhantomData`.

Fixes #135215
Fixes #135214
Fixes #135220

r? ```@BoxyUwU``` or reassign
2025-01-14 19:56:30 -08:00
Michael Goulet
824a867e82 Rework trait expansion to happen once explicitly 2025-01-15 01:26:24 +00:00
Michael Goulet
3cd75812c8 Normalize field before checking PhantomData in coerce/dispatch impl validation 2025-01-14 18:47:23 +00:00
bors
8c39ce5b4f Auto merge of #135278 - tgross35:ignore-std-dep-crates, r=SparrowLii
Exclude dependencies of `std` for diagnostics

Currently crates in the sysroot can show up in diagnostic suggestions, such as in https://github.com/rust-lang/rust/issues/135232. To prevent this, duplicate `all_traits` into `visible_traits` which only shows traits in non-private crates.

Setting `#![feature(rustc_private)]` overrides this and makes items in private crates visible as well, since `rustc_private` enables use of `std`'s private dependencies.

This may be reviewed per-commit.

Fixes: https://github.com/rust-lang/rust/issues/135232
2025-01-14 14:15:39 +00:00
Oli Scherer
a907c56a77 Add hir::HeaderSafety to make follow up commits simpler 2025-01-14 10:54:11 +00:00
Trevor Gross
2da9accab9 Add tcx.visible_traits() and use it for producing diagnostics
Add an alternative to `tcx.all_traits()` that only shows traits that the
user might be able to use, for diagnostic purposes. With this available,
make use of it for diagnostics including associated type errors, which
is part of the problem with [1].

Includes a few comment updates for related API.

[1]: https://github.com/rust-lang/rust/issues/135232
2025-01-14 08:51:19 +00:00
lcnr
87f03a4238 rm unnecessary OpaqueTypeDecl wrapper 2025-01-13 14:33:18 +01:00
Matthias Krüger
b53239668a
Rollup merge of #135378 - compiler-errors:unnecessary-stashing, r=chenyukang
Remove a bunch of diagnostic stashing that doesn't do anything

#121669 removed a bunch of conditional diagnostic stashing/canceling, but left around the `steal` calls which just emitted the error eagerly instead of canceling the diagnostic. I think that these no-op `steal` calls don't do much and are confusing to encounter, so let's remove them.

The net effect is:
1. We emit more duplicated errors, since stashing has the side effect of duplicating diagnostics. This is not a big deal, since outside of `-Zdeduplicate-diagnostics=no`, the errors are already being deduplicated by the compiler.
2. It changes the order of diagnostics, since we're no longer stashing and then later stealing the errors. I don't think this matters much for the changes that the UI test suite manifests, and it makes these errors less order dependent.
2025-01-12 12:07:58 +01:00
Matthias Krüger
55503a1d0e
Rollup merge of #135374 - compiler-errors:typo-trait-method, r=fee1-dead
Suggest typo fix when trait path expression is typo'ed

When users write something like `Default::defualt()` (notice the typo), failure to resolve the erroneous `defualt` item will cause resolution + lowering to interpret this as a type-dependent path whose self type is `Default` which is a trait object without `dyn`, rather than a trait function like `<_ as Default>::default()`.

Try to provide a bit of guidance in this situation when we can detect the typo.

Fixes https://github.com/rust-lang/rust/issues/135349
2025-01-12 12:07:57 +01:00
Michael Goulet
85c9ce6d79 Remove a bunch of diagnostic stashing that doesn't do anything 2025-01-11 19:22:06 +00:00
Michael Goulet
4486a19007 Suggest typos when trait path expression is typod 2025-01-11 18:44:12 +00:00
Rémy Rakic
a13354bea0 rename BitSet to DenseBitSet
This should make it clearer that this bitset is dense, with the
advantages and disadvantages that it entails.
2025-01-11 11:34:01 +00:00
Jacob Pratt
b557f1baa7
Rollup merge of #135321 - matthiaskrgr:out_of_into, r=lqd
remove more redundant into() conversions
2025-01-10 03:55:23 -05:00
Matthias Krüger
1c619373f9 remove more redundant into() conversions 2025-01-10 07:08:28 +01:00
Michael Goulet
9585f36678 Rename RegionResolutionVisitor to ScopeResolutionVisitor 2025-01-09 22:17:10 +00:00
Michael Goulet
9d2e1ed6bd Make sure to walk into nested const blocks in RegionResolutionVisitor 2025-01-09 22:16:51 +00:00