Commit Graph

48471 Commits

Author SHA1 Message Date
Josh Triplett
63cfb3af37 mbe: Defer checks for compile_error! until reporting an unused macro rule
The MBE parser checks rules at initial parse time to see if their RHS
has `compile_error!` in it, and returns a list of rule indexes and LHS
spans that don't map to `compile_error!`, for use in unused macro rule
checking.

Instead, have the unused macro rule reporting ask the macro for the rule
to report, and let the macro check at that time. That avoids checking
rules unless they're unused.

In the process, refactor the data structure used to store macro rules,
to group the LHS and RHS (and LHS span) of each rule together, and
refactor the unused rule tracking to only track rule indexes.

This ends up being a net simplification, and reduction in code size.
2025-07-05 16:23:13 -07:00
Josh Triplett
0d5ab3e46c mbe: Simplify a match to a let-else 2025-07-05 16:23:13 -07:00
Josh Triplett
a7382eae3f mbe: Add a helper to parse a single TokenTree
The parser repeatedly invokes the `parse` function, constructing a
one-entry vector, and assuming that the return value will be a one-entry
vector. Add a helper for that case. This will simplify adding additional
callers, and put all the logic in one place to allow potential future
simplification of the one-TT case.
2025-07-05 16:23:07 -07:00
Matthias Krüger
c3c4fd7c9c Rollup merge of #143494 - cjgillot:no-yield-in-scope, r=compiler-errors
Remove yields_in_scope from the scope tree.

I believe this has not been in use since we removed the HIR-based generator interior type computation.
2025-07-05 22:34:43 +02:00
Matthias Krüger
8a5d239949 Rollup merge of #143489 - cjgillot:mut-visit-span, r=petrochenkov
Complete rustc_ast::mut_visit for spans.

Extracted from https://github.com/rust-lang/rust/pull/127241

r? `@petrochenkov`
2025-07-05 22:34:42 +02:00
Matthias Krüger
0311159e02 Rollup merge of #143441 - compiler-errors:no-key, r=petrochenkov
Stop using `Key` trait unnecessarily

Few places where the `Key` trait was being used but not really for a useful reason. This fixes those usages.

Namely, `<Ty as Key>::default_span()` is `DUMMY_SP` anyways.
2025-07-05 22:34:41 +02:00
Matthias Krüger
9a921a32f6 Rollup merge of #143238 - JonathanBrouwer:ignore_parser, r=jdonszelmann
Port `#[ignore]` to the new attribute parsing infrastructure

Ports `ignore` to the new attribute parsing infrastructure for https://github.com/rust-lang/rust/issues/131229#issuecomment-2971353197

This PR duplicates a change from https://github.com/rust-lang/rust/pull/143237
Draft until that one is merged
2025-07-05 22:34:40 +02:00
bors
5adb489a80 Auto merge of #142732 - compiler-errors:more-root, r=lcnr
Canonicalize input ty/ct infer/placeholder in the root universe

We shouldn't care what universe the inputs are, since we only ever do the leak check on the universes instantiated after entering the canonical binder.
2025-07-05 20:34:08 +00:00
Jonathan Brouwer
2d8ffff10a Port #[ignore] to the new attribute parsing infrastructure
Signed-off-by: Jonathan Brouwer <jonathantbrouwer@gmail.com>
2025-07-05 21:23:09 +02:00
Michael Goulet
4185874592 Don't compress input universes 2025-07-05 18:41:59 +00:00
Michael Goulet
7f5d286de3 Canonicalize input ty/ct infer/placeholder in the root universe 2025-07-05 18:37:54 +00:00
Michael Goulet
8eb9f70979 Stop using Key trait randomly 2025-07-05 18:37:11 +00:00
Michael Goulet
995eeeb54c Don't call predicates_of on a dummy obligation cause's body id 2025-07-05 17:47:28 +00:00
Diggory Blake
ea7b756875 Make tempfile a normal dependency 2025-07-05 17:24:22 +01:00
Camille GILLOT
39ee1b2d77 Remove yields_in_scope from the scope tree. 2025-07-05 15:24:15 +00:00
Diggory Blake
a839b071f7 Use object crate from crates.io to fix windows build error 2025-07-05 15:58:42 +01:00
Ralf Jung
3cd13f72a2 codegen_ssa: replace a Result by an Either 2025-07-05 15:53:56 +02:00
Camille GILLOT
90762c26b6 Complete mut_visit. 2025-07-05 12:37:17 +00:00
Josh Triplett
6b71399d38 mbe: Introduce an enum for which part of a rule we're parsing
Rather than a `bool` that's `true` for the LHS and `false` for the RHS,
use a self-documenting enum.
2025-07-05 03:07:15 -07:00
bors
fd9ca711a3 Auto merge of #143473 - workingjubilee:rollup-bxie7zg, r=scottmcm
Rollup of 11 pull requests

Successful merges:

 - rust-lang/rust#142440 (`tests/ui`: A New Order [14/N])
 - rust-lang/rust#143040 (Add `const Rem`)
 - rust-lang/rust#143086 (Update poison.rs to fix the typo (sys->sync))
 - rust-lang/rust#143202 (`tests/ui`: A New Order [18/N])
 - rust-lang/rust#143296 (`tests/ui`: A New Order [21/N])
 - rust-lang/rust#143297 (`tests/ui`: A New Order [22/N])
 - rust-lang/rust#143299 (`tests/ui`: A New Order [24/N])
 - rust-lang/rust#143300 (`tests/ui`: A New Order [25/N])
 - rust-lang/rust#143397 (test passing a `VaList` from rust to C)
 - rust-lang/rust#143410 (Block SIMD in transmute_immediate; delete `OperandValueKind`)
 - rust-lang/rust#143452 (Fix CLI completion check in `tidy`)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-07-05 09:37:08 +00:00
ia0
db0b491258 Fix short linker error output
This PR does 2 things:

- It removes the braces when there's a single element. This is required since brace expansion (at
  least in bash and zsh) only triggers if there's at least 2 elements.

- It removes the extra `.rlib` suffixes of the elements. See
  https://github.com/rust-lang/rust/pull/135707#discussion_r2185212393 for context.

Running `cargo +stage1 build` on the following program:

```rust
unsafe extern "C" {
    fn foo() -> libc::c_int;
}

fn main() {
    let x = unsafe { foo() } as u32;
    // println!("{}", data_encoding::BASE64.encode(&x.to_le_bytes()));
}
```

Gives the following diff before and after the PR:

```diff
-/tmp/foo/target/debug/deps/{liblibc-faf416f178830595.rlib}.rlib
+/tmp/foo/target/debug/deps/liblibc-faf416f178830595.rlib
```

Running on the same program with the additional dependency, we get the following diff:

```diff
-/tmp/foo/target/debug/deps/{liblibc-faf416f178830595.rlib,libdata_encoding-84bb5aadfa9e8839.rlib}.rlib
+/tmp/foo/target/debug/deps/{liblibc-faf416f178830595,libdata_encoding-84bb5aadfa9e8839}.rlib
```

Do we want to add a UI test?
2025-07-05 11:07:03 +02:00
Folkert de Vries
ed3711ea29 use div_ceil instead of manual logic 2025-07-05 10:55:42 +02:00
Folkert de Vries
226b0fbe11 use is_multiple_of instead of manual modulo 2025-07-05 10:55:35 +02:00
dianne
bb64315978 only check for mixed deref/normal constructors when needed 2025-07-04 23:47:31 -07:00
dianne
50061f3b11 always check for mixed deref pattern and normal constructors
This makes it work for box patterns and in rust-analyzer.
2025-07-04 23:47:31 -07:00
bors
f0b67dd97d Auto merge of #139598 - compiler-errors:no-bound-var-symbol, r=WaffleLapkin
Remove `Symbol` from `Named` variant of `BoundRegionKind`/`LateParamRegionKind`

The `Symbol` is redundant, since we already store a `DefId` in the region variant. Instead, load the name via `item_name` when needed (which is almost always on the diagnostic path).

This introduces a `BoundRegionKind::NamedAnon` which is used for giving anonymous bound regions names, but which should only be used during pretty printing and error reporting.
2025-07-05 06:29:56 +00:00
Jubilee
33eb552ceb Rollup merge of #143410 - scottmcm:redo-transmute-again, r=RalfJung,workingjubilee
Block SIMD in transmute_immediate; delete `OperandValueKind`

Vectors have been causing me problems for years in this code, for example https://github.com/rust-lang/rust/pull/110021#discussion_r1160975086 and https://github.com/rust-lang/rust/pull/143194

See conversation in <https://rust-lang.zulipchat.com/#narrow/channel/131828-t-compiler/topic/Is.20transmuting.20a.20.60T.60.20to.20.60Tx1.60.20.28one-element.20SIMD.20vector.29.20UB.3F/near/526262799>.

By blocking SIMD in `transmute_immediate` it can be simplified to just take the `Scalar`s involved -- the backend types can be gotten from those `Scalar`s, rather than needing to be passed.  And there's an assert added to ICE it if it does get hit.

Accordingly, this changes `rvalue_creates_operand` to not send SIMD transmutes through the operand path, but to always go through memory instead, like they did back before rust-lang/rust#108442.

And thanks to those changes, I could also remove the `OperandValueKind` type that I added back then which `@RalfJung` rightly considers pretty sketchy.

cc `@folkertdev` `@workingjubilee` from the zulip conversation too
2025-07-04 23:26:24 -07:00
bors
733b47ea4b Auto merge of #138759 - scottmcm:operand-builder, r=saethlin
Allow `enum` and `union` literals to also create SSA values

Today, `Some(x)` always goes through an `alloca`, even in trivial cases where the niching means the constructor doesn't even change the value.

For example, <https://rust.godbolt.org/z/6KG6PqoYz>
```rust
pub fn demo(r: &i32) -> Option<&i32> {
    Some(r)
}
```
currently emits the IR
```llvm
define align 4 ptr `@demo(ptr` align 4 %r) unnamed_addr {
start:
  %_0 = alloca [8 x i8], align 8
  store ptr %r, ptr %_0, align 8
  %0 = load ptr, ptr %_0, align 8
  ret ptr %0
}
```
but with this PR it becomes just
```llvm
define align 4 ptr `@demo(ptr` align 4 %r) unnamed_addr {
start:
  ret ptr %r
}
```
(Of course the optimizer can clean that up, but it'd be nice if it didn't have to -- especially in debug where it doesn't run.  This is like rust-lang/rust#123886, but that only handled non-simd `struct`s -- this PR generalizes it to all non-simd ADTs.)

Doing this means handing variants other than `FIRST_VARIANT`, handling the active field for unions, refactoring the discriminant code so the Place and Operand parts can share the calculation, etc.

Other PRs that led up to this one:
- https://github.com/rust-lang/rust/pull/142005
- https://github.com/rust-lang/rust/pull/142103
- https://github.com/rust-lang/rust/pull/142324
- https://github.com/rust-lang/rust/pull/142383

---

try-job: aarch64-gnu
2025-07-05 01:37:08 +00:00
Matthias Krüger
e0dd7ecac1 Rollup merge of #143414 - dianne:box-usefulness-cleanup, r=Nadrieril
remove special-casing of boxes from match exhaustiveness/usefulness analysis

As a first step in replacing `box_patterns` with `deref_patterns`, this treats box patterns as deref patterns in the THIR and exhaustiveness analysis. This allows a bunch of special-casing to be removed. The emitted MIR is unchanged.

Incidentally, this fixes a bug caused by box patterns being treated like structs rather than pointers, where enabling `exhaustive_patterns` (rust-lang/rust#51085) could give rise to spurious `unreachable_patterns` lints on arms required for exhaustiveness. Following the lint's advice to remove the match arm would result in an error. I'm not sure what the current state of `exhaustive_patterns` is with regard to reference/box opsem, or whether there's any intention to have `unreachable_patterns` be more granular than the whole arm, but regardless this should hopefully make them easier to handle consistently.

Tracking issue for deref patterns: rust-lang/rust#87121

r? `@Nadrieril`
2025-07-05 00:12:12 +02:00
Matthias Krüger
2cde070b33 Rollup merge of #143408 - joshtriplett:fix-mbe-parser, r=compiler-errors
mbe: Gracefully handle macro rules that end after `=>`

Add a test for various cases of invalid macro definitions.

Closes: https://github.com/rust-lang/rust/issues/143351
2025-07-05 00:12:11 +02:00
Matthias Krüger
567c51d584 Rollup merge of #143406 - scottmcm:did-we-need-that-unsafe, r=compiler-errors
Remove some unnecessary `unsafe` in VecCache

I'm pretty sure, but until perf confirms,
r? ghost
2025-07-05 00:12:10 +02:00
Matthias Krüger
031bf9715a Rollup merge of #143372 - cjgillot:bare-glob-map, r=petrochenkov
Remove names_imported_by_glob_use query.

Based on https://github.com/rust-lang/rust/pull/143247
r? ``@ghost`` for perf
2025-07-05 00:12:09 +02:00
Matthias Krüger
afe8ee34a7 Rollup merge of #143085 - JonathanBrouwer:non_exhaustive_parser, r=jdonszelmann
Port `#[non_exhaustive]` to the new attribute parsing infrastructure

Ports `non_exhaustive` to the new attribute parsing infrastructure for https://github.com/rust-lang/rust/issues/131229#issuecomment-2971353197

r? ``@jdonszelmann``
2025-07-05 00:12:09 +02:00
xizheyin
4a261a1513 Use relative visibility when noting sealed trait to reduce false positive
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
2025-07-05 04:13:52 +08:00
Scott McMurray
4e615272bf Address PR feedback 2025-07-04 12:29:27 -07:00
Jonathan Brouwer
027126ce0b Port #[non_exhaustive] to the new attribute parsing infrastructure 2025-07-04 20:30:42 +02:00
Michael Goulet
dc8cac8e8d Nits 2025-07-04 18:26:09 +00:00
Michael Goulet
0ad96c1e1f Fix elided lifetimes in rustdoc 2025-07-04 18:26:09 +00:00
Michael Goulet
d79b669b09 Fix pretty printing of placeholder types 2025-07-04 18:26:09 +00:00
Michael Goulet
74570e526e Same for types 2025-07-04 18:26:09 +00:00
Michael Goulet
42c9bfd2b9 Remove Symbol for Named LateParam/Bound variants 2025-07-04 18:14:22 +00:00
bors
e3843659e9 Auto merge of #114669 - cjgillot:metadata-wp, r=petrochenkov
Make metadata a workproduct and reuse it

This PR aims to skip the generation of metadata by reusing the infrastructure that already exists for compiled codegen-units, namely "workproducts".

This can yield substantial gains (~10%) when we can demonstrate that metadata does not change between an incremental session and the next. This is the case if the crate is unchanged, or if all the changes are in upstream crates and have no effect on it. This latter case is most interesting, as it arises regularly for users with several crates in their workspace.

TODO:
- [x] Materialize the fact that metadata encoding relies on the relative order of definitions;
- [x] Refactor the handling of doc links.
2025-07-04 18:06:20 +00:00
Scott McMurray
e0c54c3a9b Rename transmute_immediatetransmute_scalar 2025-07-04 10:35:51 -07:00
Matthias Krüger
8e4cca85b5 Rollup merge of #143417 - klensy:termize, r=jieyouxu
bump termize dep

Bumps termize to drop one more winapi dep. Only change is really moving from winapi: https://github.com/JohnTitor/termize/releases/tag/v0.2.0

Clippy depends on termize 0.1.1, https://github.com/rust-lang/rust-clippy/pull/15207
2025-07-04 16:22:37 +02:00
Matthias Krüger
f3e7ec5560 Rollup merge of #143400 - GrigorenkoPV:attributes/lints, r=jdonszelmann
Port `#[rustc_pass_by_value]` to the new attribute system

Part of rust-lang/rust#131229

r? `@oli-obk`
2025-07-04 16:22:36 +02:00
Matthias Krüger
2faf66d091 Rollup merge of #143387 - dpaoliello:shouldpanicfn, r=bjorn3
Make __rust_alloc_error_handler_should_panic a function

Fixes rust-lang/rust#143253

`__rust_alloc_error_handler_should_panic` is a static but was being exported as a function.

For most targets this doesn't matter, but Arm64EC Windows uses different decorations for exported variables vs functions, hence it fails to link when `-Z oom=abort` is enabled.

We've had issues in the past with statics like this (see rust-lang/rust#141061) but the tldr; is that Arm64EC needs symbols correctly exported as either a function or data, and data MUST and MUST ONLY be marked `dllimport` when the symbol is being imported from another binary, which is non-trivial to calculate for these compiler-generated statics.

So, instead, the easiest thing to do is to make `__rust_alloc_error_handler_should_panic` a function instead.

Since `__rust_alloc_error_handler_should_panic` isn't involved in any linking shenanigans, I've marked it as `AlwaysInline` with the hopes that the various backends will see that it is just returning a constant and perform the same optimizations as the previous implementation.

r? `@bjorn3`
2025-07-04 16:22:36 +02:00
Matthias Krüger
18b374d5a7 Rollup merge of #143308 - compiler-errors:no-pointer-like, r=oli-obk
Remove `PointerLike` trait

r? oli-obk
2025-07-04 16:22:35 +02:00
Matthias Krüger
324aa5d4ba Rollup merge of #143286 - Muscraft:track-diagnostics-note, r=WaffleLapkin
Make -Ztrack-diagnostics emit like a note

[#t-compiler/diagnostics > Rendering -Ztrack-diagnostics like a note](https://rust-lang.zulipchat.com/#narrow/channel/147480-t-compiler.2Fdiagnostics/topic/Rendering.20-Ztrack-diagnostics.20like.20a.20note/with/526608647)

As discussed on the Zulip thread above, I want to make `-Ztrack-diagnostics` emit like a `note`. This is because I find its current output jarring, and the fact that it gets rendered completely left-aligned, [even in the middle of a snippet](86e05cd300/tests/ui/track-diagnostics/track6.stderr), seems like something that should be changed. Turning it into a `note` seems like the best choice, as it would align it with the rest of the output, and `note` is already used for somewhat similar things, like seeing why a lint was fired.

---

Note: turning `-Ztrack-diagnostics` into a `note` will also make `annotate-snippets` API a bit cleaner
2025-07-04 16:22:35 +02:00
Matthias Krüger
da25619e2a Rollup merge of #140643 - makai410:smir-refactor-migrate, r=oli-obk,celinval
Refactor StableMIR

This PR refactors stable-mir according to the guidance in [this doc](https://hackmd.io/jBRkZLqAQL2EVgwIIeNMHg). It reverses the dependency between `rustc_smir` and `stable_mir`, making `rustc_smir` completely agnostic  of `stable_mir`.

Under the new architecture, the `rustc_smir` crate would retain direct access to rustc queries, while `stable_mir` should proxy all such requests through `rustc_smir` instead of accessing rustc's internals directly. `stable_mir` would only be responsible for the conversion between internal and stable constructs.

This PR mainly introduces these changes:

- **Bridge / Tables<'tcx, B: Bridge>**

```rust
/// A trait defining types that are used to emulate StableMIR components, which is really
/// useful when programming in stable_mir-agnostic settings.
pub trait Bridge {
    type DefId: Copy + Debug + PartialEq + IndexedVal;
    type AllocId: Copy + Debug + PartialEq + IndexedVal;
    type Span: Copy + Debug + PartialEq + IndexedVal;
    type Ty: Copy + Debug + PartialEq + IndexedVal;
    type InstanceDef: Copy + Debug + PartialEq + IndexedVal;
    type TyConstId: Copy + Debug + PartialEq + IndexedVal;
    type MirConstId: Copy + Debug + PartialEq + IndexedVal;
    type Layout: Copy + Debug + PartialEq + IndexedVal;
    type Error: SmirError;
}

pub struct Tables<'tcx, B: Bridge> {
    tcx: TyCtxt<'tcx>,
    pub(crate) def_ids: IndexMap<DefId, B::DefId>,
    pub(crate) alloc_ids: IndexMap<AllocId, B::AllocId>,
    pub(crate) spans: IndexMap<rustc_span::Span, B::Span>,
    pub(crate) types: IndexMap<Ty<'tcx>, B::Ty>,
    pub(crate) instances: IndexMap<ty::Instance<'tcx>, B::InstanceDef>,
    pub(crate) ty_consts: IndexMap<ty::Const<'tcx>, B::TyConstId>,
    pub(crate) mir_consts: IndexMap<mir::Const<'tcx>, B::MirConstId>,
    pub(crate) layouts: IndexMap<rustc_abi::Layout<'tcx>, B::Layout>,
}
```

Since `rustc_smir` needs these stable types somewhere, using associated types is a good approach.

- **SmirContainer / SmirInterface**

```rust
/// A container which is used for TLS.
pub struct SmirContainer<'tcx, B: Bridge> {
    pub tables: RefCell<Tables<'tcx, B>>,
    pub cx: RefCell<SmirCtxt<'tcx, B>>,
}

impl<'tcx> SmirInterface for SmirContainer<'tcx, BridgeTys> {
    // ...
}

/// Provides direct access to rustc's internal queries.
///
/// The [`crate::stable_mir::compiler_interface::SmirInterface`] must go through
/// this context to obtain rustc-level information.
pub struct SmirCtxt<'tcx, B: Bridge> {
    tcx: TyCtxt<'tcx>,
    _marker: PhantomData<B>,
}
```

This PR moves `Tables` from `SmirCtxt` to a new `SmirContainer` struct, since mutable borrows of `tables` should only be managed by `SmirInterface`. This change prevents `SmirCtxt` from holding separate borrows and requires passing `tables` explicitly when needed:
```rust
impl<'tcx, B: Bridge> SmirCtxt<'tcx, B> {
    // ...
    /// Get the body of an Instance which is already monomorphized.
    pub fn instance_body(
        &self,
        instance: ty::Instance<'tcx>,
        tables: &mut Tables<'tcx, B>,
    ) -> Option<Body<'tcx>> {
        tables
            .instance_has_body(instance)
            .then(|| BodyBuilder::new(self.tcx, instance).build(tables))
    }
    // ...
}
```

This PR introduces `SmirContainer` as a separate struct rather than bundling it into a `SmirInterface` struct. This separation makes the architecture more modular and easier to reason about.

- **context/traits.rs**

We use this file to define traits that are used for encapsulating the associated functions in the rustc's internals. This is much easier to use and maintain than directly cramming everything into `SmirCtxt`. Here is a real-world use case:
```rust
impl RustcInternal for ExistentialTraitRef {
    type T<'tcx> = rustc_ty::ExistentialTraitRef<'tcx>;

    fn internal<'tcx>(
        &self,
        tables: &mut Tables<'_, BridgeTys>,
        cx: &SmirCtxt<'tcx, BridgeTys>,
    ) -> Self::T<'tcx> {
        use rustc_smir::context::SmirExistentialTraitRef;
        cx.new_from_args(self.def_id.0.internal(tables, cx), self.generic_args.internal(tables, cx))
    }
}
```

- **Separation of `rustc_smir::alloc`**

The previous `rustc_smir::alloc` had many direct calls to rustc queries. This PR splits it into two parts: `rustc_smir::alloc` and `stable_mir::alloc`. Following the same pattern as `SmirCtxt` and `SmirInterface`, the `rustc_smir::alloc` handles all direct interactions with rustc queries and performs the actual memory allocations, while the `stable_mir::alloc` is responsible for constructing stable components.

- **Removal of `convert/error.rs`**

We use `SmirError::from_internal` instead, since implementing `Stable` for these internal errors would be redundant—`tables` is not actually used. If we later need to add something like `LayoutError` to `stable_mir`, we could implement it as follows:
```rust
impl SmirError for stable_mir::LayoutError {
    fn from_internal<T: Debug>(err: T) -> Self {
        // ...
    }
}
```

**Unresolved questions:**

- There are still a few direct calls to rustc's internals scattered across `impl Stable`s, but most of them appear to be relatively stable, e.g., `mir::interpret::ConstAllocation::inner(self)` and `mir::syntax::SwitchTargets::otherwise(self)`.

r? `@celinval`
2025-07-04 16:22:34 +02:00
Camille GILLOT
17ce06a459 Add comment and move assertion. 2025-07-04 14:02:18 +00:00