Commit graph

1342 commits

Author SHA1 Message Date
Matthias Krüger
540fb228af
Rollup merge of #139615 - nnethercote:rm-name_or_empty, r=jdonszelmann
Remove `name_or_empty`

Another step towards #137978.

r? ``@jdonszelmann``
2025-04-18 05:16:29 +02:00
Nicholas Nethercote
2fef0a30ae Replace infallible name_or_empty methods with fallible name methods.
I'm removing empty identifiers everywhere, because in practice they
always mean "no identifier" rather than "empty identifier". (An empty
identifier is impossible.) It's better to use `Option` to mean "no
identifier" because you then can't forget about the "no identifier"
possibility.

Some specifics:
- When testing an attribute for a single name, the commit uses the
  `has_name` method.
- When testing an attribute for multiple names, the commit uses the new
  `has_any_name` method.
- When using `match` on an attribute, the match arms now have `Some` on
  them.

In the tests, we now avoid printing empty identifiers by not printing
the identifier in the `error:` line at all, instead letting the carets
point out the problem.
2025-04-17 09:50:52 +10:00
Nicholas Nethercote
fe882bf330 Rename LifetimeName as LifetimeKind.
It's a much better name, more consistent with how we name such things.

Also rename `Lifetime::res` as `Lifetime::kind` to match. I suspect this
field used to have the type `LifetimeRes` and then the type was changed
but the field name remained the same.
2025-04-16 07:16:40 +10:00
bors
f433fa46b0 Auto merge of #139845 - Zalathar:rollup-u5u5y1v, r=Zalathar
Rollup of 17 pull requests

Successful merges:

 - #138374 (Enable contracts for const functions)
 - #138380 (ci: add runners for vanilla LLVM 20)
 - #138393 (Allow const patterns of matches to contain pattern types)
 - #139517 (std: sys: process: uefi: Use NULL stdin by default)
 - #139554 (std: add Output::exit_ok)
 - #139660 (compiletest: Add an experimental new executor to replace libtest)
 - #139669 (Overhaul `AssocItem`)
 - #139671 (Proc macro span API redesign: Replace proc_macro::SourceFile by Span::{file, local_file})
 - #139750 (std/thread: Use default stack size from menuconfig for NuttX)
 - #139772 (Remove `hir::Map`)
 - #139785 (Let CStrings be either 1 or 2 byte aligned.)
 - #139789 (do not unnecessarily leak auto traits in item bounds)
 - #139791 (drop global where-bounds before merging candidates)
 - #139798 (normalize: prefer `ParamEnv` over `AliasBound` candidates)
 - #139822 (Fix: Map EOPNOTSUPP to ErrorKind::Unsupported on Unix)
 - #139833 (Fix some HIR pretty-printing problems)
 - #139836 (Basic tests of MPMC receiver cloning)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-04-15 08:02:23 +00:00
Stuart Cook
9d6c95d146
Rollup merge of #139772 - nnethercote:rm-hir-Map, r=Zalathar
Remove `hir::Map`

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

r? `@Zalathar`
2025-04-15 15:47:28 +10:00
Stuart Cook
380ad1b5d4
Rollup merge of #138374 - celinval:issue-136925-const-contract, r=compiler-errors,oli-obk,RalfJung
Enable contracts for const functions

Use `const_eval_select!()` macro to enable contract checking only at runtime. The existing contract logic relies on closures, which are not supported in constant functions.

This commit also removes one level of indirection for ensures clauses since we no longer build a closure around the ensures predicate.

Resolves #136925

**Call-out:** This is still a draft PR since CI is broken due to a new warning message for unreachable code when the bottom of the function is indeed unreachable. It's not clear to me why the warning wasn't triggered before.

r? ```@compiler-errors```
2025-04-15 15:47:24 +10:00
Yotam Ofek
4b63362f3d Use newtype_index!-generated types more idiomatically 2025-04-14 16:17:06 +00:00
bors
f836ae4e66 Auto merge of #124141 - nnethercote:rm-Nonterminal-and-TokenKind-Interpolated, r=petrochenkov
Remove `Nonterminal` and `TokenKind::Interpolated`

A third attempt at this; the first attempt was #96724 and the second was #114647.

r? `@ghost`
2025-04-14 03:56:55 +00:00
Nicholas Nethercote
9734e44b83 Documentation fixes.
Remove old references to the HIR map.
2025-04-14 09:18:15 +10:00
Jacob Pratt
d04df1cba9
Rollup merge of #137043 - Sky9x:unsafe-pinned-pt1-libs, r=tgross35,RalfJung,WaffleLapkin
Initial `UnsafePinned` implementation [Part 1: Libs]

Initial libs changes necessary to unblock further work on [RFC 3467](https://rust-lang.github.io/rfcs/3467-unsafe-pinned.html).
Tracking issue: #125735

This PR is split off from #136964, and includes just the libs changes:
- `UnsafePinned` struct
- private `UnsafeUnpin` structural auto trait
- Lang items for both
- Compiler changes necessary to block niches on `UnsafePinned`

This PR does not change codegen, miri, the existing `!Unpin` hack, or anything else. That work is to be split into later PRs.

---

cc ``@RalfJung`` ``@Noratrieb``

``@rustbot`` label F-unsafe_pinned T-libs-api
2025-04-13 17:37:51 -04:00
Sky
21b7360a9a
Initial UnsafePinned/UnsafeUnpin impl [Part 1: Libs] 2025-04-13 01:11:04 -04:00
Samuel Tardieu
83dd8a2c2a Fix name of field in doc comment 2025-04-12 11:34:04 +02:00
Jacob Pratt
2b54f9bfb1
Rollup merge of #139662 - nnethercote:tweak-DefPathData, r=compiler-errors
Tweak `DefPathData`

Some improvements in and around `DefPathData`, following on from #137977.

r? `@spastorino`
2025-04-11 21:21:01 +02:00
Nicholas Nethercote
cdf5b8d4e7 Change how anonymous associated types are printed.
Give them their own symbol `anon_assoc`, as is done for all the other
anonymous `DefPathData` variants.
2025-04-11 20:13:16 +10:00
Nicholas Nethercote
9eca59a940 Introduce DefPathData::AnonAssocTy.
PR #137977 changed `DefPathData::TypeNs` to contain `Option<Symbol>` to
account for RPITIT assoc types being anonymous. This commit changes it
back to `Symbol` and gives anonymous assoc types their own variant. It
makes things a bit nicer overall.
2025-04-11 19:08:14 +10:00
Stuart Cook
0abc6c6e98
Rollup merge of #138682 - Alexendoo:extra-symbols, r=fee1-dead
Allow drivers to supply a list of extra symbols to intern

Allows adding new symbols as `const`s in external drivers, desirable in Clippy so we can use them in patterns to replace code like 75530e9f72/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs (L66)

The Clippy change adds a couple symbols as a demo, the exact `clippy_utils` API and replacing other usages can be done on the Clippy side to minimise sync conflicts

---

try-job: aarch64-gnu
2025-04-11 13:31:44 +10:00
Alex Macleod
f740326216 Allow drivers to supply a list of extra symbols to intern 2025-04-10 13:39:23 +00:00
Nicholas Nethercote
663a317c20 Address review comments. 2025-04-10 09:39:21 +10:00
Nicholas Nethercote
1b3fc585cb Rename some name variables as ident.
It bugs me when variables of type `Ident` are called `name`. It leads to
silly things like `name.name`. `Ident` variables should be called
`ident`, and `name` should be used for variables of type `Symbol`.

This commit improves things by by doing `s/name/ident/` on a bunch of
`Ident` variables. Not all of them, but a decent chunk.
2025-04-10 09:30:55 +10:00
Celina G. Val
b9754f9e7b Enable contracts for const functions
Use `const_eval_select!()` macro to enable contract checking only at
runtime. The existing contract logic relies on closures,
which are not supported in constant functions.

This commit also removes one level of indirection for ensures clauses,
however, it currently has a spurious warning message when the bottom
of the function is unreachable.
2025-04-07 11:17:33 -07:00
Stuart Cook
27c6e40755
Rollup merge of #139112 - m-ou-se:super-let, r=lcnr
Implement `super let`

Tracking issue: https://github.com/rust-lang/rust/issues/139076

This implements `super let` as proposed in #139080, based on the following two equivalence rules.

1. For all expressions `$expr` in any context, these are equivalent:
  - `& $expr`
  - `{ super let a = & $expr; a }`

2. And, additionally, these are equivalent in any context when `$expr` is a temporary (aka rvalue):
  - `& $expr`
  - `{ super let a = $expr; & a }`

So far, this experiment has a few interesting results:

## Interesting result 1

In this snippet:

```rust
super let a = f(&temp());
```

I originally expected temporary `temp()` would be dropped at the end of the statement (`;`), just like in a regular `let`, because `temp()` is not subject to temporary lifetime extension.

However, it turns out that that would break the fundamental equivalence rules.

For example, in

```rust
g(&f(&temp()));
```

the temporary `temp()` will be dropped at the `;`.

The first equivalence rule tells us this must be equivalent:

```rust
g({ super let a = &f(&temp()); a });
```

But that means that `temp()` must live until the last `;` (after `g()`), not just the first `;` (after `f()`).

While this was somewhat surprising to me at first, it does match the exact behavior we need for `pin!()`: The following _should work_. (See also https://github.com/rust-lang/rust/issues/138718)

```rust
g(pin!(f(&mut temp())));
```

Here, `temp()` lives until the end of the statement. This makes sense from the perspective of the user, as no other `;` or `{}` are visible. Whether `pin!()` uses a `{}` block internally or not should be irrelevant.

This means that _nothing_ in a `super let` statement will be dropped at the end of that super let statement. It does not even need its own scope.

This raises questions that are useful for later on:

- Will this make temporaries live _too long_ in cases where `super let` is used not in a hidden block in a macro, but as a visible statement in code like the following?

    ```rust
    let writer = {
        super let file = File::create(&format!("/home/{user}/test"));
        Writer::new(&file)
    };
    ```

- Is a `let` statement in a block still the right syntax for this? Considering it has _no_ scope of its own, maybe neither a block nor a statement should be involved

This leads me to think that instead of `{ super let $pat = $init; $expr }`, we might want to consider something like `let $pat = $init in $expr` or `$expr where $pat = $init`. Although there are also issues with these, as it isn't obvious anymore if `$init` should be subject to temporary lifetime extension. (Do we want both `let _ = _ in ..` and `super let _ = _ in ..`?)

## Interesting result 2

What about `super let x;` without initializer?

```rust
let a = {
    super let x;
    x = temp();
    &x
};
```

This works fine with the implementation in this PR: `x` is extended to live as long as `a`.

While it matches my expectations, a somewhat interesting thing to realize is that these are _not_ equivalent:

- `super let x = $expr;`
- `super let x; x = $expr;`

In the first case, all temporaries in $expr will live at least as long as (the result of) the surrounding block.
In the second case, temporaries will be dropped at the end of the assignment statement. (Because the assignment statement itself "is not `super`".)

This difference in behavior might be confusing, but it _might_ be useful.
One might want to extend the lifetime of a variable without extending all the temporaries in the initializer expression.

On the other hand, that can also be expressed as:

- `let x = $expr; super let x = x;` (w/o temporary lifetime extension), or
- `super let x = { $expr };` (w/ temporary lifetime extension)

So, this raises these questions:

- Do we want to accept `super let x;` without initializer at all?

- Does it make sense for statements other than let statements to be "super"? An expression statement also drops temporaries at its `;`, so now that we discovered that `super let` basically disables that `;` (see interesting result 1), is there a use to having other statements without their own scope? (I don't think that's ever useful?)

## Interesting result 3

This works now:

```rust
super let Some(x) = a.get(i) else { return };
```

I didn't put in any special cases for `super let else`. This is just the behavior that 'naturally' falls out when implementing `super let` without thinking of the `let else` case.

- Should `super let else` work?

## Interesting result 4

This 'works':

```rust
fn main() {
    super let a = 123;
}
```

I didn't put in any special cases for `super let` at function scope. I had expected the code to cause an ICE or other weird failure when used at function body scope, because there's no way to let the variable live as long as the result of the function.

This raises the question:

- Does this mean that this behavior is the natural/expected behavior when `super let` is used at function scope? Or is this just a quirk and should we explicitly disallow `super let` in a function body? (Probably the latter.)

---

The questions above do not need an answer to land this PR. These questions should be considered when redesigning/rfc'ing/stabilizing the feature.
2025-04-07 22:29:18 +10:00
Stuart Cook
82df6229b6
Rollup merge of #139035 - nnethercote:PatKind-Missing, r=oli-obk
Add new `PatKind::Missing` variants

To avoid some ugly uses of `kw::Empty` when handling "missing" patterns, e.g. in bare fn tys. Helps with #137978. Details in the individual commits.

r? ``@oli-obk``
2025-04-07 22:29:17 +10: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
Matthias Krüger
48a3919884
Rollup merge of #138610 - oli-obk:no-sort-hir-ids, r=compiler-errors
impl !PartialOrd for HirId

revive of https://github.com/rust-lang/rust/pull/92233

Another checkbox of https://github.com/rust-lang/rust/issues/90317, another small step in making incremental less likely to die in horrible ways
2025-04-03 21:18:30 +02:00
Bryanskiy
581c5fbc40 Initial support for auto traits with default bounds 2025-04-03 14:59:39 +03:00
Oli Scherer
57c4ab7ff5 impl !PartialOrd for HirId 2025-04-03 09:22:21 +00:00
Nicholas Nethercote
ddcb370bc6 Tighten up assignment operator representations.
In the AST, currently we use `BinOpKind` within `ExprKind::AssignOp` and
`AssocOp::AssignOp`, even though this allows some nonsensical
combinations. E.g. there is no `&&=` operator. Likewise for HIR and
THIR.

This commit introduces `AssignOpKind` which only includes the ten
assignable operators, and uses it in `ExprKind::AssignOp` and
`AssocOp::AssignOp`. (And does similar things for `hir::ExprKind` and
`thir::ExprKind`.) This avoids the possibility of nonsensical
combinations, as seen by the removal of the `bug!` case in
`lang_item_for_binop`.

The commit is mostly plumbing, including:
- Adds an `impl From<AssignOpKind> for BinOpKind` (AST) and `impl
  From<AssignOp> for BinOp` (MIR/THIR).
- `BinOpCategory` can now be created from both `BinOpKind` and
  `AssignOpKind`.
- Replaces the `IsAssign` type with `Op`, which has more information and
  a few methods.
- `suggest_swapping_lhs_and_rhs`: moves the condition to the call site,
  it's easier that way.
- `check_expr_inner`: had to factor out some code into a separate
  method.

I'm on the fence about whether avoiding the nonsensical combinations is
worth the extra code.
2025-04-03 10:23:03 +11: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
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
Michael Goulet
897acc3e5d Encode synthetic by-move coroutine body with a different DefPathData 2025-03-30 22:53:21 +00:00
Nicholas Nethercote
8d2c63f514 Don't use kw::Empty in hir::Lifetime::ident.
`hir::Lifetime::ident` currently sometimes uses `kw::Empty` for elided
lifetimes and sometimes uses `kw::UnderscoreLifetime`, and the
distinction is used when creating some error suggestions, e.g. in
`Lifetime::suggestion` and `ImplicitLifetimeFinder::visit_ty`. I found
this *really* confusing, and it took me a while to understand what was
going on.

This commit replaces all uses of `kw::Empty` in `hir::Lifetime::ident`
with `kw::UnderscoreLifetime`. It adds a new field
`hir::Lifetime::is_path_anon` that mostly replaces the old
empty/underscore distinction and makes things much clearer.

Some other notable changes:

- Adds a big comment to `Lifetime` talking about permissable field
  values.

- Adds some assertions in `new_named_lifetime` about what ident values
  are permissible for the different `LifetimeRes` values.

- Adds a `Lifetime::new` constructor that does some checking to make
  sure the `is_elided` and `is_anonymous` states are valid.

- `add_static_impl_trait_suggestion` now looks at `Lifetime::res`
  instead of the ident when creating the suggestion. This is the one
  case where `is_path_anon` doesn't replace the old empty/underscore
  distinction.

- A couple of minor pretty-printing improvements.
2025-03-28 10:15:23 +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
Nicholas Nethercote
cfd00f9c16 Remove ImplicitObjectLifetimeDefault case from suggestion.
It has no effect on anything in the test suite.

This means it can also be rewritten as a neater pairwise `match`.
2025-03-28 08:25:07 +11:00
Nicholas Nethercote
c6d8d65496 Remove LifetimeSuggestionPosition and Lifetime::suggestion_position.
They both are only used in `Lifetime::suggestion`. This commit inlines
and removes them.
2025-03-28 08:25:07 +11:00
bors
0ce1369bde Auto merge of #136974 - m-ou-se:fmt-options-64-bit, r=scottmcm
Reduce FormattingOptions to 64 bits

This is part of https://github.com/rust-lang/rust/issues/99012

This reduces FormattingOptions from 6-7 machine words (384 bits on 64-bit platforms, 224 bits on 32-bit platforms) to just 64 bits (a single register on 64-bit platforms).

Before:

```rust
pub struct FormattingOptions {
    flags: u32, // only 6 bits used
    fill: char,
    align: Option<Alignment>,
    width: Option<usize>,
    precision: Option<usize>,
}
```

After:

```rust
pub struct FormattingOptions {
    /// Bits:
    ///  - 0-20: fill character (21 bits, a full `char`)
    ///  - 21: `+` flag
    ///  - 22: `-` flag
    ///  - 23: `#` flag
    ///  - 24: `0` flag
    ///  - 25: `x?` flag
    ///  - 26: `X?` flag
    ///  - 27: Width flag (if set, the width field below is used)
    ///  - 28: Precision flag (if set, the precision field below is used)
    ///  - 29-30: Alignment (0: Left, 1: Right, 2: Center, 3: Unknown)
    ///  - 31: Always set to 1
    flags: u32,
    /// Width if width flag above is set. Otherwise, always 0.
    width: u16,
    /// Precision if precision flag above is set. Otherwise, always 0.
    precision: u16,
}
```
2025-03-22 10:56:14 +00: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
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
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
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
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
Mara Bos
90645c187c Reduce FormattingOptions to 64 bits. 2025-03-12 16:32:00 +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
Matthias Krüger
4c6edb1df8
Rollup merge of #138376 - nnethercote:hir-ItemKind-ident-precursors, r=compiler-errors
Item-related cleanups

I have been looking at `hir::Item` closely and found a few minor cleanup opportunities.

r? ```@spastorino```
2025-03-12 08:06:51 +01:00
Nicholas Nethercote
d7029d7e2d Remove unused OwnerNode::ident method. 2025-03-12 09:54:25 +11:00
Nicholas Nethercote
0b2d7062c4 Introduce sym::dummy and Ident::dummy.
The idea is to identify cases of symbols/identifiers that are not
expected to be used. There isn't a perfectly sharp line between "dummy"
and "not dummy", but I think it's useful nonetheless.
2025-03-12 09:35:11 +11: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
Oli Scherer
69a1bb8bdb Error on define_opaques entries without any opaques actually referenced 2025-03-11 12:05:02 +00: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