rust-lang / rust-lang/rust

Weird error spans when using metavariable twice

Open
#146,040 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics A-macros D-imprecise-spans T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the provided macro_rules example with the stated nightly rustc version and compare the current and desired diagnostics. Start by tracing metavariable span and context handling when $first is used twice, then add a regression test covering the shown input and expected span output.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.