Skip to content

Macros: limitation in the expression parser for <$:path>::<ident> #48067

Description

@behnam

Background: https://users.rust-lang.org/t/macros-using-path-tokens-with-format-args/15480

When passing in a path token to a macro, then trying to suffix the metavariable with ::<ident> (or more), the parser cannot recognize the whole thing as an :expr, which causes failures on calls to macros like format_args!.

Repro:

macro_rules! something {
    ( $path:path ) => (
        //println!("Say: {}", $path::say);
        format_args!("Say: {}", $path::say);
    );
}

mod foo {
    const say: &str = "Hello";
}

mod bar {
    const say: &str = "World";

    mod baz {
        const say: &str = "Universe";
    }
}

fn main() {
    something!(foo);
    something!(bar);
    something!(bar::baz);
}

It fails with three instances of this error (with RUSTFLAGS='-Z external-macro-backtrace'):

error: expected token: `,`
  --> src/main.rs:4:9
   |
1  | / macro_rules! talk {
2  | |     ( $mod:path ) => (
3  | |         // print!("Say: {}", $mod::say);
4  | |         format_args!("Say: {}", $mod::say);
   | |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5  | |     );
6  | | }
   | |_- in this expansion of `talk!`
...
21 |       talk!(foo);
   |       ----------- in this macro invocation

A workaround is to use:

{ use $path as base; base::say }

but would be great if we could just use:

$path::say

I couldn't find an existing report. I'm guessing it falls under RFE.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

A-macrosArea: All kinds of macros (custom derive, macro_rules!, proc macros, ..)A-parserArea: The lexing & parsing of Rust source code to an ASTC-enhancementCategory: An issue proposing an enhancement or a PR with one.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