如何通过Rust宏将表达式中的一个标识符替换为另一个标识符?

hoh*_*ern 10 rust rust-macros

我正在尝试建立一个进行一些代码转换的宏,并且应该能够解析其自身的语法。这是我能想到的最简单的例子:

replace!(x, y, x * 100 + z) ~> y * 100 + z
Run Code Online (Sandbox Code Playgroud)

此宏应该能够用作为第三参数提供的表达式中的第二个标识符替换第一个标识符。宏应该对第三个参数的语言有所了解(在我的特定情况下,与示例相反,它不会在Rust中解析),并对其进行递归应用。

在Rust中构建此类宏的最有效方法是什么?我知道这种proc_macro方法和macro_rules!一种方法。但是我不确定是否macro_rules!足够强大来处理此问题,并且找不到如何使用来构建自己的转换的文档proc_macro。谁能指出我正确的方向?

Luk*_*odt 11

macro_rules!宏解决方案

使用声明性宏(macro_rules!)来实现此操作有些棘手,但可行。但是,有必要使用一些技巧。

但是首先,下面是代码(Playground):

macro_rules! replace {
    // This is the "public interface". The only thing we do here is to delegate
    // to the actual implementation. The implementation is more complicated to
    // call, because it has an "out" parameter which accumulates the token we
    // will generate.
    ($x:ident, $y:ident, $($e:tt)*) => {
        replace!(@impl $x, $y, [], $($e)*)
    };

    // Recursion stop: if there are no tokens to check anymore, we just emit
    // what we accumulated in the out parameter so far.
    (@impl $x:ident, $y:ident, [$($out:tt)*], ) => {
        $($out)*
    };

    // This is the arm that's used when the first token in the stream is an
    // identifier. We potentially replace the identifier and push it to the
    // out tokens.
    (@impl $x:ident, $y:ident, [$($out:tt)*], $head:ident $($tail:tt)*) => {{
        replace!(
            @impl $x, $y, 
            [$($out)* replace!(@replace $x $y $head)],
            $($tail)*
        )
    }};

    // These arms are here to recurse into "groups" (tokens inside of a 
    // (), [] or {} pair)
    (@impl $x:ident, $y:ident, [$($out:tt)*], ( $($head:tt)* ) $($tail:tt)*) => {{
        replace!(
            @impl $x, $y, 
            [$($out)* ( replace!($x, $y, $($head)*) ) ], 
            $($tail)*
        )
    }};
    (@impl $x:ident, $y:ident, [$($out:tt)*], [ $($head:tt)* ] $($tail:tt)*) => {{
        replace!(
            @impl $x, $y, 
            [$($out)* [ replace!($x, $y, $($head)*) ] ], 
            $($tail)*
        )
    }};
    (@impl $x:ident, $y:ident, [$($out:tt)*], { $($head:tt)* } $($tail:tt)*) => {{
        replace!(
            @impl $x, $y, 
            [$($out)* { replace!($x, $y, $($head)*) } ], 
            $($tail)*
        )
    }};

    // This is the standard recusion case: we have a non-identifier token as
    // head, so we just put it into the out parameter.
    (@impl $x:ident, $y:ident, [$($out:tt)*], $head:tt $($tail:tt)*) => {{
        replace!(@impl $x, $y, [$($out)* $head], $($tail)*)
    }};

    // Helper to replace the identifier if its the needle. 
    (@replace $needle:ident $replacement:ident $i:ident) => {{
        // This is a trick to check two identifiers for equality. Note that 
        // the patterns in this macro don't contain any meta variables (the 
        // out meta variables $needle and $i are interpolated).
        macro_rules! __inner_helper {
            // Identifiers equal, emit $replacement
            ($needle $needle) => { $replacement };
            // Identifiers not equal, emit original
            ($needle $i) => { $i };                
        }

        __inner_helper!($needle $i)
    }}
}


fn main() {
    let foo = 3;
    let bar = 7;
    let z = 5;

    dbg!(replace!(abc, foo, bar * 100 + z));  // no replacement
    dbg!(replace!(bar, foo, bar * 100 + z));  // replace `bar` with `foo`
}
Run Code Online (Sandbox Code Playgroud)

它输出:

[src/main.rs:56] replace!(abc , foo , bar * 100 + z) = 705
[src/main.rs:57] replace!(bar , foo , bar * 100 + z) = 305
Run Code Online (Sandbox Code Playgroud)

这是如何运作的?

在理解此宏之前,需要了解两个主要技巧:降低累加以及如何检查两个标识符是否相等

此外,请确保:@foobar宏模式开头的内容不是特殊功能,而仅仅是标记内部帮助程序宏的约定(另请参见:《宏的小书》StackOverflow问题)。


下推积累“ Rust宏小书”的这一章中有很好的描述。重要的部分是:

Rust中的所有宏都必须产生一个完整的,受支持的语法元素(例如表达式,项目等)。这意味着不可能将宏扩展为部分构造。

但是通常有必要获得部分结果,例如,在用某些输入处理令牌的情况下。为了解决这个问题,基本上有一个“ out”参数,它只是随每个递归宏调用而增长的令牌列表。这是可行的,因为宏输入可以是任意标记,而不必是有效的Rust构造。

这种模式仅对用作“增量TT杀手”的宏有意义,而我的解决方案正是这样做的。TLBORM中有关于此模式的章节


第二个关键点是检查两个标识符是否相等。这是通过一个有趣的技巧完成的:宏定义了一个新的宏,然后立即使用它。让我们看一下代码:

(@replace $needle:ident $replacement:ident $i:ident) => {{
    macro_rules! __inner_helper {
        ($needle $needle) => { $replacement };
        ($needle $i) => { $i };                
    }

    __inner_helper!($needle $i)
}}
Run Code Online (Sandbox Code Playgroud)

让我们经历两个不同的调用:

  • replace!(@replace foo bar baz):这扩展为:

    macro_rules! __inner_helper {
        (foo foo) => { bar };
        (foo baz) => { baz };
    }
    
    __inner_helper!(foo baz)
    
    Run Code Online (Sandbox Code Playgroud)

    inner_helper!现在,调用显然采用第二种模式,即baz

  • replace!(@replace foo bar foo) 另一方面扩展为:

    macro_rules! __inner_helper {
        (foo foo) => { bar };
        (foo foo) => { foo };
    }
    
    __inner_helper!(foo foo)
    
    Run Code Online (Sandbox Code Playgroud)

    这次,inner_helper!调用采用第一个模式,结果为bar

我从一个基本上只能提供以下内容的板条箱中学到了这个技巧:一个宏,检查两个标识符是否相等。但不幸的是,我再也找不到这个箱子了。让我知道您是否知道该板条箱的名称!


但是,此实现有一些限制:

  • 作为增量TT muncher,它会为输入中的每个令牌递归。因此很容易达到递归限制(可以增加,但不是最佳)。可以编写此宏的非递归版本,但是到目前为止,我还没有找到一种方法来做到这一点。

  • macro_rules!关于标识符,宏有点奇怪。上面提出的解决方案在self作为标识符时可能表现得很奇怪。有关主题的更多信息,请参见本章


proc-macro解决方案

当然,这也可以通过proc-macro完成。它还涉及较少的奇怪技巧。我的解决方案如下所示:

extern crate proc_macro;

use proc_macro::{
    Ident, TokenStream, TokenTree,
    token_stream,
};


#[proc_macro]
pub fn replace(input: TokenStream) -> TokenStream {
    let mut it = input.into_iter();

    // Get first parameters
    let needle = get_ident(&mut it);
    let _comma = it.next().unwrap();
    let replacement = get_ident(&mut it);
    let _comma = it.next().unwrap();

    // Return the remaining tokens, but replace identifiers.
    it.map(|tt| {
        match tt {
            // Comparing `Ident`s can only be done via string comparison right
            // now. Note that this ignores syntax contexts which can be a
            // problem in some situation.
            TokenTree::Ident(ref i) if i.to_string() == needle.to_string() => {
                TokenTree::Ident(replacement.clone())
            }

            // All other tokens are just forwarded
            other => other,
        }
    }).collect()
}

/// Extract an identifier from the iterator.
fn get_ident(it: &mut token_stream::IntoIter) -> Ident {
    match it.next() {
        Some(TokenTree::Ident(i)) => i,
        _ => panic!("oh noes!"),
    }
}
Run Code Online (Sandbox Code Playgroud)

main()在上面的示例中使用此proc宏的工作原理完全相同。

注意:此处为了简化示例,忽略了错误处理。请参阅此问题,了解如何在proc宏中进行错误报告。

我认为,除此之外,该代码不需要太多解释。此proc宏版本也不受宏的递归限制问题的困扰macro_rules!