11

我正在尝试编写一个将重写某些 Rust 控制流的宏,但我很难匹配if表达式。问题是谓词是一个表达式,但expr不允许 an 后跟 a blockor {

我最好的方法是使用tt

macro_rules! branch {
    (
        if $pred:tt 
            $r1:block
        else
            $r2:block
    ) => {
        if $pred { 
            $r1
        } else {
            $r2
        }
    };
}

这适用于单令牌或分组谓词:

branch! {
    if (foo == bar) {
        1
    } else {
        2
    }
}

但如果谓词未分组,则失败:

branch! {
    if foo == bar {
        1
    } else {
        2
    }
}
error: no rules expected the token `==`

我还尝试tt在谓词中使用重复模式:

macro_rules! branch {
    (
        if $($pred:tt)+
            $r1:block
        else
            $r2:block
    ) => {
        if $($pred)+ { 
            $r1
        } else {
            $r2
        }
    };
}

但这会产生一个错误,因为现在不清楚后续块是否也应该匹配tt

error: local ambiguity: multiple parsing options: built-in NTs tt ('pred') or block ('r1').

有没有办法做到这一点,还是我坚持发明特殊语法以在宏中使用?

4

1 回答 1

3

您可以使用TT muncher来解析谓词:

macro_rules! branch {
    {
        if $($rest:tt)*
    } => {
        branch_parser! {
            predicate = ()
            rest = ($($rest)*)
        }
    };
}

macro_rules! branch_parser {
    {
        predicate = ($($predicate:tt)*)
        rest = ({ $($then:tt)* } else { $($else:tt)* })
    } => {
        println!("predicate: {}", stringify!($($predicate)*));
        println!("then: {}", stringify!($($then)*));
        println!("else: {}", stringify!($($else)*));
    };

    {
        predicate = ($($predicate:tt)*)
        rest = ($next:tt $($rest:tt)*)
    } => {
        branch_parser! {
            predicate = ($($predicate)* $next)
            rest = ($($rest)*)
        }
    };
}

fn main() {
    branch! {
        if foo == bar {
            1
        } else {
            2
        }
    }
}

输出:

predicate: foo == bar
then: 1
else: 2
于 2018-10-08T00:33:42.143 回答