是否有可能在自定义派生中获得结构的完整“命名空间”?

问题描述 投票:2回答:1

我读过this documentation page,但我仍然无法弄清楚如何做到这一点。

我的文件是:

|- pancakes.rs
|- main.rs

我在“pancakes.rs”中推导出结构Pancakes

#[derive(HelloWorld)]
struct Pancakes;

我从文档中复制了以下实现,但ident不包含完整的“命名空间”:

#[proc_macro_derive(HelloWorld)]
pub fn hello_world(input: TokenStream) -> TokenStream {
    let s = input.to_string();
    let ast = syn::parse_derive_input(&s).unwrap();
    let gen = impl_hello_world(&ast);
    gen.parse().unwrap()
}

fn impl_hello_world(ast: &syn::DeriveInput) -> quote::Tokens {
    let name = &ast.ident; // <---- HERE name = Pancakes, not pancakes::Pancakes
    quote! {
        impl HelloWorld for #name {
            fn hello_world() {
                println!("Hello, World! My name is {}", stringify!(#name));
            }
        }
    }
}

是否有可能获得有关结构的所有信息?我还想从使用派生的地方获取货物的lib名称。

rust
1个回答
3
投票

这是不可能的。自定义派生工作在令牌流上,您可以从中轻松构建AST。但是在这个级别上,名称还没有得到解决(这是有道理的,宏和自定义派生可以影响名称的解析方式,所以它们需要首先完全消耗)。

© www.soinside.com 2019 - 2024. All rights reserved.