【问题标题】:Escaping commas in macro output在宏输出中转义逗号
【发布时间】:2015-07-02 22:14:49
【问题描述】:

我正在尝试编写一个使我能够转换的宏 (a, b, c, d)(a, a + b, a + b + c, a + b + c + d) 等。这是我目前得到的:

macro_rules! pascal_next {
    ($x: expr) => ($x);
    ($x: expr, $y: expr) => (
        ($x, $x + $y)
    );
    ($x: expr, $y: expr, $($rest: expr),+) => (
        ($x, pascal_next!(
                $x + $y, $($rest),+
            )
        )
    );
}

但是,有一个问题是它实际上会输出 (a, (a + b, (a + b + c, a + b + c +d)))。起源是第二个匹配规则($x: expr, $y: expr) => (($x, $x + $y));,产生了一个额外的括号,所以会有嵌套的括号。如果我不在外面放一个括号,我会得到错误错误:

意外令牌:,

那么可以在 Rust 宏中输出逗号, 吗?

【问题讨论】:

    标签: macros rust


    【解决方案1】:

    没有;宏的结果必须是一个完整的语法结构,如表达式或项目。您绝对不能使用随机的语法位,例如逗号或右大括号。

    您可以通过在获得完整的最终表达式之前不输出任何内容来解决此问题。看!

    #![feature(trace_macros)]
    
    macro_rules! pascal_impl {
        /*
        The input to this macro takes the following form:
    
        ```ignore
        (
            // The current output accumulator.
            ($($out:tt)*);
    
            // The current additive prefix.
            $prefix:expr;
    
            // The remaining, comma-terminated elements.
            ...
        )
        ```
        */
    
        /*
        Termination condition: there is no input left.  As
        such, dump the output.
        */
        (
            $out:expr;
            $_prefix:expr;
        ) => {
            $out
        };
    
        /*
        Otherwise, we have more to scrape!
        */
        (
            ($($out:tt)*);
            $prefix:expr;
            $e:expr, $($rest:tt)*
        ) => {
            pascal_impl!(
                ($($out)* $prefix+$e,);
                $prefix+$e;
                $($rest)*
            )
        };
    }
    
    macro_rules! pascal {
        ($($es:expr),+) => { pascal_impl!((); 0; $($es),+,) };
    }
    
    trace_macros!(true);
    
    fn main() {
        println!("{:?}", pascal!(1, 2, 3, 4));
    }
    

    注意:要在稳定的编译器上使用它,您需要删除 #![feature(trace_macros)]trace_macros!(true); 行。其他都应该没问题。

    它的作用是递归地咀嚼输入,将部分(并且可能语义上无效)输出作为输入传递到下一级递归。这让我们可以建立一个“开放列表”,否则我们无法做到。

    然后,一旦我们没有输入,我们只需将部分输出重新解释为完整的表达式,然后......完成。

    我包含跟踪内容的原因是为了向您展示它运行时的样子:

    pascal! { 1 , 2 , 3 , 4 }
    pascal_impl! { (  ) ; 0 ; 1 , 2 , 3 , 4 , }
    pascal_impl! { ( 0 + 1 , ) ; 0 + 1 ; 2 , 3 , 4 , }
    pascal_impl! { ( 0 + 1 , 0 + 1 + 2 , ) ; 0 + 1 + 2 ; 3 , 4 , }
    pascal_impl! { ( 0 + 1 , 0 + 1 + 2 , 0 + 1 + 2 + 3 , ) ; 0 + 1 + 2 + 3 ; 4 , }
    pascal_impl! { ( 0 + 1 , 0 + 1 + 2 , 0 + 1 + 2 + 3 , 0 + 1 + 2 + 3 + 4 , ) ; 0 + 1 + 2 + 3 + 4 ; }
    

    输出是:

    (1, 3, 6, 10)
    

    需要注意的一点:大量未注释的整数文字会导致编译时间急剧增加。如果发生这种情况,您可以通过简单地注释 all 整数文字(如 1i32)来解决它。

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多