Commit Graph

2959 Commits

Author SHA1 Message Date
Skgland
5eb535c568
remove compiler support for extern "rust-intrinsic" blocks 2025-04-06 21:32:58 +02:00
bors
bad13a970a Auto merge of #139390 - matthiaskrgr:rollup-l64euwx, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #139041 (Remove `rustc_middle::ty::util::ExplicitSelf`.)
 - #139328 (Fix 2024 edition doctest panic output)
 - #139339 (unstable book: document tait)
 - #139348 (AsyncDestructor: replace fields with impl_did)
 - #139353 (Fix `Debug` impl for `LateParamRegionKind`.)
 - #139366 (ToSocketAddrs: fix typo)
 - #139374 (Use the span of the whole bound when the diagnostic talks about a bound)
 - #139378 (Use target-agnostic LLD flags in bootstrap for `use-lld`)
 - #139384 (Add `compiletest` adhoc_group for `r? compiletest`)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-04-04 23:03:57 +00:00
Michael Goulet
f343b9d1fd Don't construct preds w escaping bound vars in diagnostic_hir_wf_check 2025-04-04 21:09:32 +00:00
Matthias Krüger
f074bbff7a
Rollup merge of #139374 - oli-obk:const-trait-bound, r=compiler-errors
Use the span of the whole bound when the diagnostic talks about a bound

While it makes sense that the host predicate only points to the `~const` part, as whether the actual trait bound is satisfied is checked separately, the user facing diagnostic is talking about the entire trait bound, at which point it makes more sense to just highlight the entire bound

r? `@compiler-errors` or `@fee1-dead`
2025-04-04 21:55:00 +02:00
Matthias Krüger
00f608af18
Rollup merge of #139041 - nnethercote:rm-rustc_middle-ty-util-ExplicitSelf, r=BoxyUwU
Remove `rustc_middle::ty::util::ExplicitSelf`.

It's an old (2017 or earlier) type that describes a `self` receiver. It's only used in `rustc_hir_analysis` for two error messages, and much of the complexity isn't used. I suspect it used to be used for more things.

This commit removes it, and moves a greatly simplified version of the `determine` method into `rustc_hir_analysis`, renamed as `get_self_string`. The big comment on the method is removed because it no longer seems relevant.

r? `@BoxyUwU`
2025-04-04 21:54:56 +02:00
bors
17ffbc81a3 Auto merge of #138785 - lcnr:typing-mode-borrowck, r=compiler-errors,oli-obk
add `TypingMode::Borrowck`

Shares the first commit with #138499, doesn't really matter which PR to land first 😊 😁

Introduces `TypingMode::Borrowck` which unlike `TypingMode::Analysis`, uses the hidden type computed by HIR typeck as the initial value of opaques instead of an unconstrained infer var. This is a part of https://github.com/rust-lang/types-team/issues/129.

Using this new `TypingMode` is unfortunately a breaking change for now, see tests/ui/impl-trait/non-defining-uses/as-projection-term.rs. Using an inference variable as the initial value results in non-defining uses in the defining scope. We therefore only enable it if with `-Znext-solver=globally` or `-Ztyping-mode-borrowck`

To do that the PR contains the following changes:
- `TypeckResults::concrete_opaque_type` are already mapped to the definition of the opaque type
  - writeback now checks that the non-lifetime parameters of the opaque are universal
  - for this, `fn check_opaque_type_parameter_valid` is moved from `rustc_borrowck` to `rustc_trait_selection`
- we add a new `query type_of_opaque_hir_typeck` which, using the same visitors as MIR typeck, attempts to merge the hidden types from HIR typeck from all defining scopes
  - done by adding a `DefiningScopeKind` flag to toggle between using borrowck and HIR typeck
  - the visitors stop checking that the MIR type matches the HIR type. This is trivial as the HIR type are now used as the initial hidden types of the opaque. This check is useful as a safeguard when not using `TypingMode::Borrowck`, but adding it to the new structure is annoying and it's not soundness critical, so I intend to not add it back.
- add a `TypingMode::Borrowck`  which behaves just like `TypingMode::Analysis` except when normalizing opaque types
   - it uses `type_of_opaque_hir_typeck(opaque)` as the initial value after replacing its regions with new inference vars
   - it uses structural lookup in the new solver

fixes #112201, fixes #132335, fixes #137751

r? `@compiler-errors` `@oli-obk`
2025-04-04 19:54:42 +00:00
Oli Scherer
a69a219f96 Use the span of the whole bound when the diagnostic talks about a bound 2025-04-04 13:39:50 +00:00
Bryanskiy
0522ed059d Default auto traits: fix perf 2025-04-04 15:32:00 +03:00
Mara Bos
3e6cc7689d Boolean hate. 2025-04-04 09:44:22 +02:00
Mara Bos
3123df8ef0 Implement super let. 2025-04-04 09:44:19 +02:00
bors
9e14530c7c Auto merge of #120706 - Bryanskiy:leak, r=lcnr
Initial support for auto traits with default bounds

This PR is part of ["MCP: Low level components for async drop"](https://github.com/rust-lang/compiler-team/issues/727)
Tracking issue: #138781
Summary: https://github.com/rust-lang/rust/pull/120706#issuecomment-1934006762

### Intro

Sometimes we want to use type system to express specific behavior and provide safety guarantees. This behavior can be specified by various "marker" traits. For example, we use `Send` and `Sync` to keep track of which types are thread safe. As the language develops, there are more problems that could be solved by adding new marker traits:

- to forbid types with an async destructor to be dropped in a synchronous context a trait like `SyncDrop` could be used [Async destructors, async genericity and completion futures](https://sabrinajewson.org/blog/async-drop).
- to support [scoped tasks](https://without.boats/blog/the-scoped-task-trilemma/) or in a more general sense to provide a [destruction guarantee](https://zetanumbers.github.io/book/myosotis.html) there is a desire among some users to see a `Leak` (or `Forget`) trait.
- Withoutboats in his [post](https://without.boats/blog/changing-the-rules-of-rust/) reflected on the use of `Move` trait instead of a `Pin`.

All the traits proposed above are supposed to be auto traits implemented for most types, and usually implemented automatically by compiler.

For backward compatibility these traits have to be added implicitly to all bound lists in old code (see below). Adding new default bounds involves many difficulties: many standard library interfaces may need to opt out of those default bounds, and therefore be infected with confusing `?Trait` syntax, migration to a new edition may contain backward compatibility holes, supporting new traits in the compiler can be quite difficult and so forth. Anyway, it's hard to evaluate the complexity until we try the system on a practice.

In this PR we introduce new optional lang items for traits that are added to all bound lists by default, similarly to existing `Sized`. The examples of such traits could be `Leak`, `Move`, `SyncDrop` or something else, it doesn't matter much right now (further I will call them `DefaultAutoTrait`'s). We want to land this change into rustc under an option, so it becomes available in bootstrap compiler. Then we'll be able to do standard library experiments with the aforementioned traits without adding hundreds of `#[cfg(not(bootstrap))]`s. Based on the experiments, we can come up with some scheme for the next edition, in which such bounds are added in a more targeted way, and not just everywhere.

Most of the implementation is basically a refactoring that replaces hardcoded uses of `Sized` with iterating over a list of traits including both `Sized` and the new traits when `-Zexperimental-default-bounds` is enabled (or just `Sized` as before, if the option is not enabled).

### Default bounds for old editions

All existing types, including generic parameters, are considered `Leak`/`Move`/`SyncDrop` and can be forgotten, moved or destroyed in generic contexts without specifying any bounds. New types that cannot be, for example, forgotten and do not implement `Leak` can be added at some point, and they should not be usable in such generic contexts in existing code.

To both maintain this property and keep backward compatibility with existing code, the new traits should be added as default bounds _everywhere_ in previous editions. Besides the implicit `Sized` bound contexts that includes supertrait lists and trait lists in trait objects (`dyn Trait1 + ... + TraitN`). Compiler should also generate implicit `DefaultAutoTrait` implementations for foreign types (`extern { type Foo; }`) because they are also currently usable in generic contexts without any bounds.

#### Supertraits

Adding the new traits as supertraits to all existing traits is potentially necessary, because, for example, using a `Self` param in a trait's associated item may be a breaking change otherwise:

```rust
trait Foo: Sized {
    fn new() -> Option<Self>; // ERROR: `Option` requires `DefaultAutoTrait`, but `Self` is not `DefaultAutoTrait`
}

// desugared `Option`
enum Option<T: DefaultAutoTrait + Sized> {
    Some(T),
    None,
}
```

However, default supertraits can significantly affect compiler performance. For example, if we know that `T: Trait`, the compiler would deduce that `T: DefaultAutoTrait`. It also implies proving `F: DefaultAutoTrait` for each field `F` of type `T` until an explicit impl is be provided.

If the standard library is not modified, then even traits like `Copy` or `Send` would get these supertraits.

In this PR for optimization purposes instead of adding default supertraits, bounds are added to the associated items:

```rust
// Default bounds are generated in the following way:
trait Trait {
   fn foo(&self) where Self: DefaultAutoTrait {}
}

// instead of this:
trait Trait: DefaultAutoTrait {
   fn foo(&self) {}
}
```

It is not always possible to do this optimization because of backward compatibility:

```rust
pub trait Trait<Rhs = Self> {}
pub trait Trait1 : Trait {} // ERROR: `Rhs` requires `DefaultAutoTrait`, but `Self` is not `DefaultAutoTrait`
```

or

```rust
trait Trait {
   type Type where Self: Sized;
}
trait Trait2<T> : Trait<Type = T> {} // ERROR: `???` requires `DefaultAutoTrait`, but `Self` is not `DefaultAutoTrait`
```

Therefore, `DefaultAutoTrait`'s are still being added to supertraits if the `Self` params or type bindings were found in the trait header.

#### Trait objects

Trait objects requires explicit `+ Trait` bound to implement corresponding trait which is not backward compatible:

```rust
fn use_trait_object(x: Box<dyn Trait>) {
   foo(x) // ERROR: `foo` requires `DefaultAutoTrait`, but `dyn Trait` is not `DefaultAutoTrait`
}

// implicit T: DefaultAutoTrait here
fn foo<T>(_: T) {}
```

So, for a trait object `dyn Trait` we should add an implicit bound `dyn Trait + DefaultAutoTrait` to make it usable, and allow relaxing it with a question mark syntax `dyn Trait + ?DefaultAutoTrait` when it's not necessary.

#### Foreign types

If compiler doesn't generate auto trait implementations for a foreign type, then it's a breaking change if the default bounds are added everywhere else:

```rust
// implicit T: DefaultAutoTrait here
fn foo<T: ?Sized>(_: &T) {}

extern "C" {
    type ExternTy;
}

fn forward_extern_ty(x: &ExternTy) {
    foo(x); // ERROR: `foo` requires `DefaultAutoTrait`, but `ExternTy` is not `DefaultAutoTrait`
}
```

We'll have to enable implicit `DefaultAutoTrait` implementations for foreign types at least for previous editions:

```rust
// implicit T: DefaultAutoTrait here
fn foo<T: ?Sized>(_: &T) {}

extern "C" {
    type ExternTy;
}

impl DefaultAutoTrait for ExternTy {} // implicit impl

fn forward_extern_ty(x: &ExternTy) {
    foo(x); // OK
}
```

### Unresolved questions

New default bounds affect all existing Rust code complicating an already complex type system.

- Proving an auto trait predicate requires recursively traversing the type and proving the predicate for it's fields. This leads to a significant performance regression. Measurements for the stage 2 compiler build show up to 3x regression.
    - We hope that fast path optimizations for well known traits could mitigate such regressions at least partially.
- New default bounds trigger some compiler bugs in both old and new trait solver.
- With new default bounds we encounter some trait solver cycle errors that break existing code.
    - We hope that these cases are bugs that can be addressed in the new trait solver.

Also migration to a new edition could be quite ugly and enormous, but that's actually what we want to solve. For other issues there's a chance that they could be solved by a new solver.
2025-04-04 01:35:52 +00:00
Bryanskiy
581c5fbc40 Initial support for auto traits with default bounds 2025-04-03 14:59:39 +03:00
xtex
fdefffecb2
compiler: report error when trait object type param reference self
Fixes #139082.

Emits an error when `Self` is found in the projection bounds of a trait
object. In type aliases, `Self` has no meaning, so `type A = &'static
dyn B` where `trait B = Fn() -> Self` will expands to `type A = &'static
Fn() -> Self` which is illegal, causing the region solver to bail out
when hitting the uninferred Self.

Bug: #139082
Signed-off-by: xtex <xtexchooser@duck.com>
2025-04-03 17:35:51 +08:00
lcnr
509a144eed add TypingMode::Borrowck 2025-04-03 11:13:10 +02:00
lcnr
abc838be13 rm RpitConstraintChecker
we already collect opaque types from nested items
during `mir_borrowck` of the root, checking that they
are consistent this way.
2025-04-03 11:13:10 +02:00
Takayuki Maeda
bda2ea4d01
Rollup merge of #139232 - nnethercote:remove-Map-5, r=Zalathar
Move methods from `Map` to `TyCtxt`, part 5.

This eliminates all methods on `Map`. Actually removing `Map` will occur in a follow-up PR.

A follow-up to #137504.

r? `@Zalathar`
2025-04-02 22:52:46 +09:00
bors
ae9173d7dd Auto merge of #139018 - oli-obk:incremental-trait-impls, r=compiler-errors
Various local trait item iteration cleanups

Adding a trait impl for `Foo` unconditionally affected all queries that are interested in a completely independent trait `Bar`. Perf has no effect on this. We probably don't have a good perf test for this tho.

r? `@compiler-errors`

I am unsure about 9d05efb66f as it doesn't improve anything wrt incremental, because we still do all the checks for valid `Drop` impls, which subsequently will still invoke many queries and basically keep the depgraph the same.

I want to do

9549077a47/compiler/rustc_middle/src/ty/trait_def.rs (L141)

but would leave that to a follow-up PR, this one changes enough things as it is
2025-04-02 10:10:50 +00:00
Oli Scherer
49c74d29fd Only walk local items instead of filtering for them later 2025-04-02 07:30:11 +00:00
Oli Scherer
7192a0643d Directly fetch the impl self type 2025-04-02 07:30:11 +00:00
Oli Scherer
ca32447c0c Only look at trait impls in the current crate when looking for Drop impls 2025-04-02 07:30:11 +00:00
Nicholas Nethercote
1830245a22 Remove recursion_limit increases.
These are no longer needed now that `Nonterminal` is gone.
2025-04-02 16:25:27 +11:00
Stuart Cook
2d43a8b20d
Rollup merge of #139200 - xizheyin:issue-139174, r=compiler-errors
Skip suggest impl or dyn when poly trait is not a real trait

Fixes #139174
When `poly_trait_ref` is not a real trait, we should stop suggesting `impl` and `dyn` to avoid false positives. 3 cases were added to the ui test.
0b45675cfc/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs (L88-L93)

In the first commit, I submitted the test and passed it. In the second commit, I modified the code and we can see the changes in the test.

r? compiler
2025-04-02 13:10:40 +11:00
Stuart Cook
bae53a7c3c
Rollup merge of #135295 - eyraudh:master, r=compiler-errors
Check empty SIMD vector in inline asm

fixes [#134334](https://github.com/rust-lang/rust/issues/134334)
2025-04-02 13:10:36 +11:00
Nicholas Nethercote
6713f34ee4 Move methods from Map to TyCtxt, part 5.
This eliminates all methods on `Map`. Actually removing `Map` will occur
in a follow-up PR.
2025-04-02 10:00:46 +11:00
Oli Scherer
51184c70c8 Ensure calculcate_dtor is only ever called on local types 2025-04-01 09:25:12 +00:00
Oli Scherer
a7b687c26e Decouple trait impls of different traits wrt incremental 2025-04-01 09:25:12 +00:00
xizheyin
12604fa071
Skip suggest impl or dyn when poly trait is not a real trait
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-04-01 14:32:17 +08:00
Mara Bos
122d7e1dcd Remove terminating_scopes hash set. 2025-03-28 22:49:27 +01:00
Matthias Krüger
310bebc487
Rollup merge of #139047 - m-ou-se:remove-scope-depth, r=oli-obk
Remove ScopeDepth

The scope depth was tracked, but never seemed to be used for anything.

Every single place that used `(Scope, ScopeDepth)`, matched it on `(p, _)`.
2025-03-28 12:59:58 +01:00
Matthias Krüger
9597bf72dd
Rollup merge of #137889 - mu001999-contrib:update-doc, r=wesleywiser
update outdated doc with new example

update the illegal definition example because we can compile `struct Ref<'a, T> { x: &'a T }` ([play](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=2eb2f8800d423c316b545c864623ae16))
2025-03-28 12:59:54 +01:00
Mara Bos
deeac1c588 Remove outdated comment. 2025-03-28 08:36:16 +01:00
Mara Bos
3a9a5770ef Remove ScopeDepth entirely.
The scope depth was tracked, but never actually used for anything.
2025-03-28 08:31:47 +01:00
Nicholas Nethercote
78768361a0 Remove rustc_middle::ty::util::ExplicitSelf.
It's an old (2017 or earlier) type that describes a `self` receiver.
It's only used in `rustc_hir_analysis` for two error messages, and much
of the complexity isn't used. I suspect it used to be used for more
things.

This commit removes it, and moves a greatly simplified version of the
`determine` method into `rustc_hir_analysis`, renamed as
`get_self_string`. The big comment on the method is removed because it
no longer seems relevant.
2025-03-28 14:15:46 +11:00
Nicholas Nethercote
9f089e080c Add {ast,hir,thir}::PatKind::Missing variants.
"Missing" patterns are possible in bare fn types (`fn f(u32)`) and
similar places. Currently these are represented in the AST with
`ast::PatKind::Ident` with no `by_ref`, no `mut`, an empty ident, and no
sub-pattern. This flows through to `{hir,thir}::PatKind::Binding` for
HIR and THIR.

This is a bit nasty. It's very non-obvious, and easy to forget to check
for the exceptional empty identifier case.

This commit adds a new variant, `PatKind::Missing`, to do it properly.

The process I followed:
- Add a `Missing` variant to `{ast,hir,thir}::PatKind`.
- Chang `parse_param_general` to produce `ast::PatKind::Missing`
  instead of `ast::PatKind::Missing`.
- Look through `kw::Empty` occurrences to find functions where an
  existing empty ident check needs replacing with a `PatKind::Missing`
  check: `print_param`, `check_trait_item`, `is_named_param`.
- Add a `PatKind::Missing => unreachable!(),` arm to every exhaustive
  match identified by the compiler.
- Find which arms are actually reachable by running the test suite,
  changing them to something appropriate, usually by looking at what
  would happen to a `PatKind::Ident`/`PatKind::Binding` with no ref, no
  `mut`, an empty ident, and no subpattern.

Quite a few of the `unreachable!()` arms were never reached. This makes
sense because `PatKind::Missing` can't happen in every pattern, only
in places like bare fn tys and trait fn decls.

I also tried an alternative approach: modifying `ast::Param::pat` to
hold an `Option<P<Pat>>` instead of a `P<Pat>`, but that quickly turned
into a very large and painful change. Adding `PatKind::Missing` is much
easier.
2025-03-28 09:18:57 +11:00
Mara Bos
2cc3fa32ef Remove ScopeDepth from var_parent.
It was never used.
2025-03-26 17:18:35 +01:00
Mara Bos
0ad0142a5b Don't set cx.parent to None; it seems unnecessary. 2025-03-26 17:18:35 +01:00
Mara Bos
227f93395a Simplify RvalueCandidateType.
There is no difference between the Patternand Borrow cases. Reduce it to
a simple struct.
2025-03-26 17:18:35 +01:00
Mara Bos
1da5e60ac5 Don't record child scopes for patterns.
They are unused.
2025-03-26 17:18:18 +01:00
Hadrien Eyraud
6948343b9f fix: Check empty SIMD vector in inline asm 2025-03-23 19:41:39 +01:00
bors
db687889a5 Auto merge of #138719 - lcnr:concrete_opaque_types-closures, r=oli-obk
merge opaque types defined in nested bodies

A small step towards https://github.com/rust-lang/types-team/issues/129

r? `@oli-obk`
2025-03-22 06:55:52 +00:00
Matthias Krüger
3e04973891
Rollup merge of #138727 - compiler-errors:ty-var-origin, r=fmease
Do not rely on `type_var_origin` in `OrphanCheckErr::NonLocalInputType`

The ordering of ty var unification means that we may end up with a root variable whose ty var origin is from another item's params.

Let's not rely on this by just unifying the infer vars with the params of the impl + resolving. It's kinda goofy but it's clearer IMO.

Fixes #132826.

r? `@fmease` or `@lcnr`
2025-03-20 15:36:20 +01:00
Matthias Krüger
915576935a
Rollup merge of #138685 - nnethercote:use-Option-Ident-for-lowered-param-names, r=compiler-errors
Use `Option<Ident>` for lowered param names.

Parameter patterns are lowered to an `Ident` by `lower_fn_params_to_names`, which is used when lowering bare function types, trait methods, and foreign functions. Currently, there are two exceptional cases where the lowered param can become an empty `Ident`.

- If the incoming pattern is an empty `Ident`. This occurs if the parameter is anonymous, e.g. in a bare function type.

- If the incoming pattern is neither an ident nor an underscore. Any such parameter will have triggered a compile error (hence the `span_delayed_bug`), but lowering still occurs.

This commit replaces these empty `Ident` results with `None`, which eliminates a number of `kw::Empty` uses, and makes it impossible to fail to check for these exceptional cases.

Note: the `FIXME` comment in `is_unwrap_or_empty_symbol` is removed. It actually should have been removed in #138482, the precursor to this PR. That PR changed the lowering of wild patterns to `_` symbols instead of empty symbols, which made the mentioned underscore check load-bearing.

r? ``@compiler-errors``
2025-03-20 15:36:17 +01:00
Michael Goulet
220851cc75 Do not rely on type_var_origin in OrphanCheckErr::NonLocalInputType 2025-03-20 02:17:14 +00:00
lcnr
cfc78cec79 merge opaque types of nested bodies 2025-03-19 17:52:53 +01:00
lcnr
f8fe978fab remove unnecessary loop 2025-03-19 17:32:21 +01:00
Nicholas Nethercote
f27cab806e Use Option<Ident> for lowered param names.
Parameter patterns are lowered to an `Ident` by
`lower_fn_params_to_names`, which is used when lowering bare function
types, trait methods, and foreign functions. Currently, there are two
exceptional cases where the lowered param can become an empty `Ident`.

- If the incoming pattern is an empty `Ident`. This occurs if the
  parameter is anonymous, e.g. in a bare function type.

- If the incoming pattern is neither an ident nor an underscore. Any
  such parameter will have triggered a compile error (hence the
  `span_delayed_bug`), but lowering still occurs.

This commit replaces these empty `Ident` results with `None`, which
eliminates a number of `kw::Empty` uses, and makes it impossible to fail
to check for these exceptional cases.

Note: the `FIXME` comment in `is_unwrap_or_empty_symbol` is removed. It
actually should have been removed in #138482, the precursor to this PR.
That PR changed the lowering of wild patterns to `_` symbols instead of
empty symbols, which made the mentioned underscore check load-bearing.
2025-03-19 20:54:10 +11:00
Michael Goulet
93b31d9b21 Remove existing AFIDT implementation 2025-03-18 17:35:26 +00:00
Matthias Krüger
e1acc68c9d
Rollup merge of #138384 - nnethercote:hir-ItemKind-idents, r=fmease
Move `hir::Item::ident` into `hir::ItemKind`.

 `hir::Item` has an `ident` field.

- It's always non-empty for these item kinds: `ExternCrate`, `Static`, `Const`, `Fn`, `Macro`, `Mod`, `TyAlias`, `Enum`, `Struct`, `Union`, Trait`, TraitAalis`.

- It's always empty for these item kinds: `ForeignMod`, `GlobalAsm`, `Impl`.

- For `Use`, it is non-empty for `UseKind::Single` and empty for `UseKind::{Glob,ListStem}`.

All of this is quite non-obvious; the only documentation is a single comment saying "The name might be a dummy name in case of anonymous items". Some sites that handle items check for an empty ident, some don't. This is a very C-like way of doing things, but this is Rust, we have sum types, we can do this properly and never forget to check for the exceptional case and never YOLO possibly empty identifiers (or possibly dummy spans) around and hope that things will work out.

This is step towards `kw::Empty` elimination (#137978).

r? `@fmease`
2025-03-17 22:49:04 +01:00
Nicholas Nethercote
f2ddbcd24b Move hir::Item::ident into hir::ItemKind.
`hir::Item` has an `ident` field.

- It's always non-empty for these item kinds: `ExternCrate`, `Static`,
  `Const`, `Fn`, `Macro`, `Mod`, `TyAlias`, `Enum`, `Struct`, `Union`,
  Trait`, TraitAalis`.

- It's always empty for these item kinds: `ForeignMod`, `GlobalAsm`,
  `Impl`.

- For `Use`, it is non-empty for `UseKind::Single` and empty for
  `UseKind::{Glob,ListStem}`.

All of this is quite non-obvious; the only documentation is a single
comment saying "The name might be a dummy name in case of anonymous
items". Some sites that handle items check for an empty ident, some
don't. This is a very C-like way of doing things, but this is Rust, we
have sum types, we can do this properly and never forget to check for
the exceptional case and never YOLO possibly empty identifiers (or
possibly dummy spans) around and hope that things will work out.

The commit is large but it's mostly obvious plumbing work. Some notable
things.

- A similar transformation makes sense for `ast::Item`, but this is
  already a big change. That can be done later.

- Lots of assertions are added to item lowering to ensure that
  identifiers are empty/non-empty as expected. These will be removable
  when `ast::Item` is done later.

- `ItemKind::Use` doesn't get an `Ident`, but `UseKind::Single` does.

- `lower_use_tree` is significantly simpler. No more confusing `&mut
  Ident` to deal with.

- `ItemKind::ident` is a new method, it returns an `Option<Ident>`. It's
  used with `unwrap` in a few places; sometimes it's hard to tell
  exactly which item kinds might occur. None of these unwraps fail on
  the test suite. It's conceivable that some might fail on alternative
  input. We can deal with those if/when they happen.

- In `trait_path` the `find_map`/`if let` is replaced with a loop, and
  things end up much clearer that way.

- `named_span` no longer checks for an empty name; instead the call site
  now checks for a missing identifier if necessary.

- `maybe_inline_local` doesn't need the `glob` argument, it can be
  computed in-function from the `renamed` argument.

- `arbitrary_source_item_ordering::check_mod` had a big `if` statement
  that was just getting the ident from the item kinds that had one. It
  could be mostly replaced by a single call to the new `ItemKind::ident`
  method.

- `ItemKind` grows from 56 to 64 bytes, but `Item` stays the same size,
  and that's what matters, because `ItemKind` only occurs within `Item`.
2025-03-18 06:29:50 +11:00
bors
9c67cecd12 Auto merge of #138595 - jhpratt:rollup-09pvfzu, r=jhpratt
Rollup of 9 pull requests

Successful merges:

 - #136355 (Add `*_value` methods to proc_macro lib)
 - #137621 (Add std support to cygwin target)
 - #137793 (Stablize anonymous pipe)
 - #138341 (std: Mention clone-on-write mutation in Arc<T>)
 - #138517 (Improve upvar analysis for deref of child capture)
 - #138584 (Update Rust Foundation links in Readme)
 - #138586 (Document `#![register_tool]`)
 - #138590 (Flatten and simplify some control flow 🫓)
 - #138592 (update change entry for #137147)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-03-17 10:43:38 +00:00
Yotam Ofek
51e8309f50 Flatten and simplify some control flow 2025-03-17 09:15:49 +00:00
Yotam Ofek
a3e4dff183 Use strip_{prefix|suffix} instead of {starts|ends}_with+indexing 2025-03-17 07:06:10 +00:00
Michael Goulet
e3ac1fa81a Add RTN support to rustdoc 2025-03-15 18:13:27 +00:00
Michael Goulet
b88f85a410 Stop relying on rustc_type_ir in non-type-system crates 2025-03-15 06:42:48 +00:00
Michael Goulet
e5a2220327 Fold visit into ty 2025-03-15 06:34:36 +00:00
Michael Goulet
dc0cdfd753 Squash fold into ty 2025-03-15 06:34:36 +00:00
Yotam Ofek
e6f7ab50c0 Small grammar fix in comment 2025-03-14 21:03:21 +00:00
Yotam Ofek
5da1ba41b3 Fix typo in hir lowering lint diag 2025-03-14 21:03:21 +00:00
Matthias Krüger
b5955e74e8
Rollup merge of #138126 - compiler-errors:rtn-for-sugg, r=oli-obk
Add an opt-out in pretty printing for RTN rendering

Today, we render RPITIT types like `impl Sized { T::method(..) }` when RTN is enabled. This is very useful for diagnostics, since it's often not clear what the `impl Sized` type means by itself, and it makes it clear that that's an RPITIT that can be bounded using RTN syntax. See #115624.

However, since we don't distinguish types that are rendered for the purposes of printing messages vs suggestions, this representation leaks into suggestions and turns into code that can't be parsed. This PR adds a new `with_types_for_suggestion! {}` and `with_types_for_signature! {}` options to the pretty printing architecture to make it clear that we're rendering a type for code suggestions.

This can be applied later as we find that we need it.
2025-03-13 17:44:04 +01:00
Matthias Krüger
1a7d2b9219
Rollup merge of #138109 - Kohei316:feat/rust-doc-precise-capturing-arg, r=aDotInTheVoid,compiler-errors
make precise capturing args in rustdoc Json typed

close #137616

This PR includes below changes.

- Add `rustc_hir::PreciseCapturingArgKind` which allows the query system to return a arg's data.
- Add `rustdoc::clean::types::PreciseCapturingArg` and change to use it.
- Add `rustdoc-json-types::PreciseCapturingArg` and change to use it.
- Update `tests/rustdoc-json/impl-trait-precise-capturing.rs`.
- Bump `rustdoc_json_types::FORMAT_VERSION`.
2025-03-13 11:28:26 +01:00
bors
8536f201ff Auto merge of #138416 - Manishearth:rollup-fejor9p, r=Manishearth
Rollup of 12 pull requests

Successful merges:

 - #134076 (Stabilize `std::io::ErrorKind::InvalidFilename`)
 - #137504 (Move methods from Map to TyCtxt, part 4.)
 - #138175 (Support rmeta inputs for --crate-type=bin --emit=obj)
 - #138259 (Disentangle `ForwardGenericParamBan` and `ConstParamTy` ribs)
 - #138280 (fix ICE in pretty-printing `global_asm!`)
 - #138318 (Rustdoc: remove a bunch of `@ts-expect-error` from main.js)
 - #138331 (Use `RUSTC_LINT_FLAGS` more)
 - #138357 (merge `TypeChecker` and `TypeVerifier`)
 - #138394 (remove unnecessary variant)
 - #138403 (Delegation: one more ICE fix for `MethodCall` generation)
 - #138407 (Delegation: reject C-variadics)
 - #138409 (Use sa_sigaction instead of sa_union.__su_sigaction for AIX)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-03-13 01:37:26 +00:00
Michael Goulet
7a08d0368f Add an opt-out in pretty printing for RTN rendering 2025-03-12 19:42:18 +00:00
bors
249cb84316 Auto merge of #138414 - matthiaskrgr:rollup-9ablqdb, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #137314 (change definitely unproductive cycles to error)
 - #137701 (Convert `ShardedHashMap` to use `hashbrown::HashTable`)
 - #138269 (uefi: fs: Implement FileType, FilePermissions and FileAttr)
 - #138331 (Use `RUSTC_LINT_FLAGS` more)
 - #138345 (Some autodiff cleanups)
 - #138387 (intrinsics: remove unnecessary leading underscore from argument names)
 - #138390 (fix incorrect tracing log)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-03-12 17:27:43 +00:00
Manish Goregaokar
9d1b62c109
Rollup merge of #138407 - Bryanskiy:delegation-variadic, r=petrochenkov
Delegation: reject C-variadics

The explanation is contained in attached issues.

Fixes https://github.com/rust-lang/rust/issues/127443
Fixes https://github.com/rust-lang/rust/issues/127413

r? `@petrochenkov`
2025-03-12 10:19:34 -07:00
Manish Goregaokar
245d3a90ca
Rollup merge of #138331 - nnethercote:use-RUSTC_LINT_FLAGS-more, r=onur-ozkan,jieyouxu
Use `RUSTC_LINT_FLAGS` more

An alternative to the failed #138084.

Fixes #138106.

r? `````@jieyouxu`````
2025-03-12 10:19:30 -07:00
Manish Goregaokar
f88f27aff0
Rollup merge of #137504 - nnethercote:remove-Map-4, r=Zalathar
Move methods from Map to TyCtxt, part 4.

A follow-up to https://github.com/rust-lang/rust/pull/137350.

r? ```@Zalathar```
2025-03-12 10:19:26 -07:00
Matthias Krüger
d93ef397ce
Rollup merge of #138331 - nnethercote:use-RUSTC_LINT_FLAGS-more, r=onur-ozkan,jieyouxu
Use `RUSTC_LINT_FLAGS` more

An alternative to the failed #138084.

Fixes #138106.

r? ````@jieyouxu````
2025-03-12 17:59:08 +01:00
bors
aaa2d47dae Auto merge of #138083 - nnethercote:rm-NtItem-NtStmt, r=petrochenkov
Remove `NtItem` and `NtStmt`

Another piece of #124141.

r? `@petrochenkov`
2025-03-12 14:18:36 +00:00
Bryanskiy
ccdba16f42 Delegation: reject C-variadics 2025-03-12 17:14:51 +03:00
Nicholas Nethercote
256c27e748 Move methods from Map to TyCtxt, part 4.
Continuing the work from #137350.

Removes the unused methods: `expect_variant`, `expect_field`,
`expect_foreign_item`.

Every method gains a `hir_` prefix.
2025-03-12 08:55:37 +11:00
bors
c625102320 Auto merge of #138366 - matthiaskrgr:rollup-cn16m7q, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #137715 (Allow int literals for pattern types with int base types)
 - #138002 (Disable CFI for weakly linked syscalls)
 - #138051 (Add support for downloading GCC from CI)
 - #138231 (Prevent ICE in autodiff validation by emitting user-friendly errors)
 - #138245 (stabilize `ci_rustc_if_unchanged_logic` test for local environments)
 - #138256 (Do not feed anon const a type that references generics that it does not have)
 - #138284 (Do not write user type annotation for const param value path)
 - #138296 (Remove `AdtFlags::IS_ANONYMOUS` and `Copy`/`Clone` condition for anonymous ADT)
 - #138352 (miri native_calls: ensure we actually expose *mutable* provenance to the memory FFI can access)
 - #138354 (remove redundant `body`  arguments)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-03-11 21:17:18 +00:00
Matthias Krüger
4ff58c9103
Rollup merge of #138256 - compiler-errors:anon-const-ty, r=BoxyUwU
Do not feed anon const a type that references generics that it does not have

Fixes #137865

See the comment I left in the code. We could alternatively give these anon consts the generics from the parent, but that would be moving in a GCE-esque direction that we may not want. Open to tweaks here.

r? BoxyUwU
2025-03-11 19:35:31 +01:00
bors
6650252439 Auto merge of #128440 - oli-obk:defines, r=lcnr
Add `#[define_opaques]` attribute and require it for all type-alias-impl-trait sites that register a hidden type

Instead of relying on the signature of items to decide whether they are constraining an opaque type, the opaque types that the item constrains must be explicitly listed.

A previous version of this PR used an actual attribute, but had to keep the resolved `DefId`s in a side table.

Now we just lower to fields in the AST that have no surface syntax, instead a builtin attribute macro fills in those fields where applicable.

Note that for convenience referencing opaque types in associated types from associated methods on the same impl will not require an attribute. If that causes problems `#[defines()]` can be used to overwrite the default of searching for opaques in the signature.

One wart of this design is that closures and static items do not have generics. So since I stored the opaques in the generics of functions, consts and methods, I would need to add a custom field to closures and statics to track this information. During a T-types discussion we decided to just not do this for now.

fixes #131298
2025-03-11 18:13:31 +00:00
Jakub Beránek
03a79a77ac
Rollup merge of #138315 - matthiaskrgr:nextback, r=fmease
use next_back() instead of last() on DoubleEndedIterator
2025-03-11 13:30:55 +01:00
Oli Scherer
cb4751d4b8 Implement #[define_opaque] attribute for functions. 2025-03-11 12:05:02 +00:00
Nicholas Nethercote
ff0a5fe975 Remove #![warn(unreachable_pub)] from all compiler/ crates.
It's no longer necessary now that `-Wunreachable_pub` is being passed.
2025-03-11 13:14:21 +11:00
bors
90384941aa Auto merge of #138302 - matthiaskrgr:rollup-an2up80, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #136395 (Update to rand 0.9.0)
 - #137279 (Make some invalid codegen attr errors structured/translatable)
 - #137585 (Update documentation to consistently use 'm' in atomic synchronization example)
 - #137926 (Add a test for `-znostart-stop-gc` usage with LLD)
 - #138074 (Support `File::seek` for Hermit)
 - #138238 (Fix dyn -> param suggestion in struct ICEs)
 - #138270 (chore: Fix some comments)
 - #138286 (triagebot.toml: Don't label `test/rustdoc-json` as A-rustdoc-search (…)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-03-11 00:55:25 +00:00
Matthias Krüger
dcf6137b5c use next_back() instead of last() on DoubleEndedIterator 2025-03-10 19:03:51 +01:00
Matthias Krüger
44ec67fffb
Rollup merge of #138306 - jieyouxu:revert-workspace-lints, r=Noratrieb
Revert "Use workspace lints for crates in `compiler/` #138084"

Revert <https://github.com/rust-lang/rust/pull/138084> to buy time to consider options that avoids breaking downstream usages of cargo on distributed `rustc-src` artifacts, where such cargo invocations fail due to inability to inherit `lints` from workspace root manifest's `workspace.lints` (this is only valid for the source rust-lang/rust workspace, but not really the distributed `rustc-src` artifacts). The problem is that the `rustc-src` component doesn't include the root `Cargo.toml` manifest.

This breakage was reported in https://github.com/rust-lang/rust/issues/138304.

This reverts commit 48caf81484, reversing changes made to c6662879b2.

cc `@RalfJung`

r? `@nnethercote` (sorry, I didn't consider this being a thing 💀)
2025-03-10 15:57:22 +01:00
Michael Goulet
bc4f0bb486 Pass InferCtxt to InlineAsmCtxt to properly taint on error
Split up some of the tests bc tainting causes some errors to become
suppressed
2025-03-10 14:28:09 +00:00
morine0122
112f7b01a1 make precise capturing args in rustdoc Json typed 2025-03-10 21:40:09 +09:00
许杰友 Jieyou Xu (Joe)
063ef18fdc Revert "Use workspace lints for crates in compiler/ #138084"
Revert <https://github.com/rust-lang/rust/pull/138084> to buy time to
consider options that avoids breaking downstream usages of cargo on
distributed `rustc-src` artifacts, where such cargo invocations fail due
to inability to inherit `lints` from workspace root manifest's
`workspace.lints` (this is only valid for the source rust-lang/rust
workspace, but not really the distributed `rustc-src` artifacts).

This breakage was reported in
<https://github.com/rust-lang/rust/issues/138304>.

This reverts commit 48caf81484, reversing
changes made to c6662879b2.
2025-03-10 18:12:47 +08:00
Matthias Krüger
1ae083ddd5
Rollup merge of #138238 - compiler-errors:dyn-suggestion-in-struct, r=nnethercote
Fix dyn -> param suggestion in struct ICEs

Makes the logic from #138042 a bit less ICEy and more clean. Also fixes an incorrect suggestion when the struct already has generics. I'll point out the major changes and observations in the code.

Fixes #138229
Fixes #138211

r? nnethercote since you reviewed the original pr, or re-roll if you don't want to review this
2025-03-10 09:32:14 +01:00
Michael Goulet
ed6dfddfeb Do not feed anon const a type that references generics that it does not have 2025-03-09 20:03:13 +00:00
Matthias Krüger
48caf81484
Rollup merge of #138084 - nnethercote:workspace-lints, r=jieyouxu
Use workspace lints for crates in `compiler/`

This is nicer and hopefully less error prone than specifying lints via bootstrap.

r? ``@jieyouxu``
2025-03-09 10:34:50 +01:00
Michael Goulet
ceb040135d Fix suggestion when there are generics, inline some things 2025-03-08 20:44:57 +00:00
Michael Goulet
bca0ab8d7a Rework maybe_suggest_add_generic_impl_trait 2025-03-08 20:40:59 +00:00
Jacob Pratt
9aac24d68a
Rollup merge of #138173 - compiler-errors:incoherent-negative-impl, r=oli-obk
Delay bug for negative auto trait rather than ICEing

Fixes #138149

r? oli-obk
2025-03-07 21:57:53 -05:00
Nicholas Nethercote
8a3e03392e Remove #![warn(unreachable_pub)] from all compiler/ crates.
(Except for `rustc_codegen_cranelift`.)

It's no longer necessary now that `unreachable_pub` is in the workspace
lints.
2025-03-08 08:41:43 +11:00
Nicholas Nethercote
beba32cebb Specify rust lints for compiler/ crates via Cargo.
By naming them in `[workspace.lints.rust]` in the top-level
`Cargo.toml`, and then making all `compiler/` crates inherit them with
`[lints] workspace = true`. (I omitted `rustc_codegen_{cranelift,gcc}`,
because they're a bit different.)

The advantages of this over the current approach:
- It uses a standard Cargo feature, rather than special handling in
  bootstrap. So, easier to understand, and less likely to get
  accidentally broken in the future.
- It works for proc macro crates.

It's a shame it doesn't work for rustc-specific lints, as the comments
explain.
2025-03-08 08:41:09 +11:00
Matthias Krüger
e70adad70a
Rollup merge of #138042 - xizheyin:issue-135759, r=nnethercote
Suggest struct or union to add generic that impls trait

Fixes #135759

cc ```@tdittr```
2025-03-07 19:15:35 +01:00
Michael Goulet
bbc80a819b Delay bug for negative auto trait rather than ICEing 2025-03-07 17:20:57 +00:00
Nicholas Nethercote
7943932384 Pass Option<Symbol> to def_path_data/create_def methods.
It's clearer than using `kw::Empty` to mean `None`.
2025-03-07 20:53:00 +11:00
Nicholas Nethercote
293fe0a966 Increase recursion_limit in numerous crates.
This is temporarily needed for `x doc compiler` to work. They can be
removed once the `Nonterminal` is removed (#124141).
2025-03-07 14:51:07 +11:00
Michael Goulet
1c3733aa69
Rollup merge of #137808 - jswrenn:droppy-unsafe-fields, r=nnethercote
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

Tracking Issue: #132922
2025-03-06 12:22:19 -05:00
Michael Goulet
00132141c7
Rollup merge of #137764 - compiler-errors:always-applicable-negative-impl, r=lcnr
Ensure that negative auto impls are always applicable

r? lcnr (or reassign if you dont want to review)

https://github.com/rust-lang/rust/issues/68318#issuecomment-2689265030
2025-03-06 12:22:16 -05:00
Michael Goulet
aab7b145d0
Rollup merge of #137565 - compiler-errors:macro-ex, r=estebank
Try to point of macro expansion from resolver and method errors if it involves macro var

In the case that a macro caller passes an identifier into a macro generating a path or method expression, point out that identifier in the context of the *macro* so it's a bit more clear how the macro is involved in causing the error.

r? ``````````@estebank`````````` or reassign
2025-03-06 12:22:13 -05:00
Oli Scherer
e8f7a382be Remove the Option part of range ends in the HIR 2025-03-06 10:47:40 +00:00
Oli Scherer
0e7b283573 Avoid having to handle an Option in the type system 2025-03-06 10:03:11 +00:00
Oli Scherer
4f2b108816 Prefer a two value enum over bool 2025-03-06 10:03:11 +00:00