首页 > 解决方案 > 如何在 Rust 过程宏中获取 impl 块的类型?

问题描述

我正在尝试编写一个可以应用于这样的 impl 块的 Rust 过程宏;

struct SomeStruct { }

#[my_macro]
impl SomeStruct { }

我正在使用 syn 和 quote 来解析和格式化TokenStream宏中的 s。它看起来像这样:

#[proc_macro_attribute]
pub fn my_macro(meta: TokenStream, code: TokenStream) -> TokenStream {
    let input = parse_macro_input!(code as ItemImpl);

    // ...

    TokenStream::from(quote!(#input))
}

有没有办法使用 syn 访问 impl 块的类型名称?我没有看到任何ItemImpl可以为我提供该信息的字段。

标签: rustrust-macros

解决方案


文档列出了 9 个字段ItemImpl

  1. attrs: Vec<Attribute>
  2. defaultness: Option<Default>
  3. unsafety: Option<Unsafe>
  4. impl_token: Impl
  5. generics: Generics
  6. trait_: Option<(Option<Bang>, Path, For)>
  7. self_ty: Box<Type>
  8. brace_token: Brace
  9. items: Vec<ImplItem>

其中只有一个有“类型”这个词:self_ty.

use syn; // 0.15.23

fn example(input: syn::ItemImpl) {
    println!("{:#?}", input.self_ty);
}

fn main() {
    let code = syn::parse_str(
        r###"
        impl Foo {}
        "###,
    )
    .unwrap();

    example(code);
}
Path(
    TypePath {
        qself: None,
        path: Path {
            leading_colon: None,
            segments: [
                PathSegment {
                    ident: Ident(
                        Foo
                    ),
                    arguments: None
                }
            ]
        }
    }
)

推荐阅读