Skip to content

Weird error spans when using metavariable twice #146040

@madsmtm

Description

@madsmtm

Code

macro_rules! consume {
    ($($t:tt)*) => {};
}

macro_rules! use_first_tt {
    ($first:tt $($rest:tt)*) => {
        consume!($first); // Added
        $first $($rest)*
        // This part is included in the span as well
    };
}

use_first_tt! {
    compile_error!("foo");
}

Current output

error: foo
  --> src/lib.rs:8:9
   |
8  | /         $first $($rest)*
9  | |         // This part is included in the span as well
10 | |     };
...  |
13 | | use_first_tt! {
14 | |     compile_error!("foo");
   | |_________________________^

Desired output

error: foo
  --> src/lib.rs:14:5
   |
14 |     compile_error!("foo");
   |     ^^^^^^^^^^^^^^^^^^^^^

Rationale and extra context

It seems that the ctxt of $first is parsed wrongly, which causes the span merging (Span::to) to think that $first and the arguments ("foo") are in the same context, and can be merged directly.

This seems to only happen when using the $ident metavariable twice; if I remove the first use as follows, the output is as expected:

macro_rules! do_not_use_first_tt {
    ($ident:tt $($rest:tt)*) => {
        $ident $($rest)*
    };
}

do_not_use_first_tt! {
    compile_error!("foo");
}

Rust Version

$ rustc +nightly --version --verbose
rustc 1.91.0-nightly (160e7623e 2025-08-26)
binary: rustc
commit-hash: 160e7623e8cbbf1feab2b6e2a24733a98c7bde9c
commit-date: 2025-08-26
host: aarch64-apple-darwin
release: 1.91.0-nightly
LLVM version: 21.1.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)D-imprecise-spansDiagnostics: spans don't point to exactly the erroneous codeT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions