Skip to content

Span issues with FromStr in unstable proc_macro #48944

Open
@mystor

Description

@mystor

While writing improved tests for proc_macro2, I noticed some surprising behaviour of the FromStr impl for proc_macro::TokenStream.

When parsing a string with FromStr, a token parsed from the very beginning of the string can have a different source_file() than a token parsed elsewhere. For example:

let tokens = "aaa\nbbb".parse::<proc_macro::TokenStream>().unwrap().into_iter().collect::<Vec<_>>();
println!("span: {:?}", tokens[0].span);
println!("source_file: {:?}", tokens[0].span.source_file());
println!("");
println!("span: {:?}", tokens[1].span);
println!("source_file: {:?}", tokens[1].span.source_file());

Will produce the output:

span: Span(Span { lo: BytePos(6734829), hi: BytePos(6734832), ctxt: #0 })
source_file: SourceFile { path: ProcMacroSourceCode, is_real: false }

span: Span(Span { lo: BytePos(50), hi: BytePos(58), ctxt: #25 })
source_file: SourceFile { path: Real("pm_test.rs"), is_real: true }

I would've expected both tokens to have the same context, and similar BytePos-es. Specifically I would have expected both of these tokens to have a span located in a fake ProcMacroSourceCode file, but set to resolve in the context of the enclosing scope (as if span.resolved_at(Span::call_site()) was called).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-decl-macros-2-0Area: Declarative macros 2.0 (#39412)C-bugCategory: This is a bug.E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions