如何匹配宏中的特征范围? [英] How to match trait bounds in a macro?

查看:29
本文介绍了如何匹配宏中的特征范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试匹配泛型类型的特征范围:

I'm trying to match the trait bounds for generic types:

macro_rules! test {
    (
        where $(
            $bounded_type:ident: $( $bound:tt )++,
        )+
    ) => {
        // Dummy expansion for test:
        struct Foo<T, U>
        where $(
            $bounded_type : $( $bound )++,
        )+
        {
            t: T,
            u: U
        }
    }
}

test! {
    where
        T: PartialEq + Clone,
        U: PartialEq,
}

fn main() {}

不幸的是,如果我理解得很好,匹配特征的唯一方法是 tt 片段,但是该片段几乎可以匹配任何东西,所以无论我做什么,我都会遇到错误:

Unfortunately, if I understand well, the only way to match a trait is a tt fragment, but this fragment can match almost anything, so whatever I do, I get an error:

error: local ambiguity: multiple parsing options: built-in NTs tt ('bound') or 1 other option.

如何匹配这段代码?

请注意,我不需要 一些非常优雅的东西(对于普通用户来说不需要),但是当然,它越优雅越好.

Note that I do not need something very elegant (I do not need it for plublic users) but of course, the more elegant, the better.

推荐答案

您最好的选择是阅读

Your best bet is to read the source code for the parse-generics-shim crate; it's a bit old, but should hopefully still work. This is way too convoluted to explain in a Stack Overflow question, since it would basically involve copy+pasting the source of that crate into the answer.

更简单的方法是解析实际的Rust语法,并使用宏解析器可以处理的内容,例如将约束包装在一个组中(例如{...} ).

The easier approach is to just not parse actual Rust syntax, and use something the macro parser can handle, like wrapping the constraints in a group (like { ... }).

这篇关于如何匹配宏中的特征范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆