首页 > 解决方案 > 为什么 tt 元变量拒绝多个标记?

问题描述

我一直在尝试使用 Rust 宏,但我遇到了令牌树的绊脚石,我知道令牌树将接受任何有效的令牌序列,并将它们分组到基于配对(), [],的层次结构中{}

当我尝试传入任何标记序列时,我会收到拒绝序列中第二个标记的解析错误。

#![feature(trace_macros)]
#![allow(dead_code)]

macro_rules! repro {
    ($foo:tt) => {
        stringify!($foo);
    };
}

fn main() {
    trace_macros!(true);
    // println!("{}", repro!(bar)); works

    //these break, but succeed for meta type expr
    println!("{}", repro!(bar: fizz));
    println!("{}", repro!(1 + 2));
    trace_macros!(false);
}

在上面的代码中,':' 和 '+' 标记会触发失败:

error: no rules expected the token `:`
  --> src/main.rs:15:30
   |
4  | macro_rules! repro {
   | ------------------ when calling this macro
...
15 |     println!("{}", repro!(bar: fizz));
   |                              ^ no rules expected this token in macro call

note: trace_macro
  --> src/main.rs:15:5
   |
15 |     println!("{}", repro!(bar: fizz));
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: expanding `println! { "{}" , repro ! (bar : fizz) }`
   = note: to `{ $crate :: io :: _print (format_args_nl ! ("{}" , repro ! (bar : fizz))) ; }`

note: trace_macro
  --> src/main.rs:15:20
   |
15 |     println!("{}", repro!(bar: fizz));
   |                    ^^^^^^^^^^^^^^^^^
   |
   = note: expanding `repro! { bar : fizz }`

error: no rules expected the token `+`
  --> src/main.rs:16:29
   |
4  | macro_rules! repro {
   | ------------------ when calling this macro
...
16 |     println!("{}", repro!(1 + 2));
   |                             ^ no rules expected this token in macro call

note: trace_macro
  --> src/main.rs:16:20
   |
16 |     println!("{}", repro!(1 + 2));
   |                    ^^^^^^^^^^^^^
   |
   = note: expanding `repro! { 1 + 2 }`

note: trace_macro
  --> src/main.rs:16:5
   |
16 |     println!("{}", repro!(1 + 2));
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: expanding `println! { "{}" , repro ! (1 + 2) }`
   = note: to `{ $crate :: io :: _print (format_args_nl ! ("{}" , repro ! (1 + 2))) ; }`

我希望bar: fizz映射到['bar', ':', 'fizz']1 + 2映射到['1', '+', '2']

标签: rustmacros

解决方案


推荐阅读