gpt4 book ai didi

rust - 无法使用 syn/darling 获取字段属性

转载 作者:行者123 更新时间:2023-12-05 05:05:55 31 4
gpt4 key购买 nike

我正在尝试使用 syn/darling crates 在 proc-macro 中获取字段属性。这是一个 MRE

Cargo.toml

[package]
name = "darling_attrs"
version = "0.1.0"
edition = "2018"

[lib]
proc-macro = true

[dependencies]
darling = "0.10"
proc-macro2 = "1.0"
quote = "1.0"
syn = { version = "1.0", features = ["full"] }

src/lib.rs

extern crate proc_macro;
extern crate proc_macro2;

mod cat;

use proc_macro::TokenStream;
use syn::DeriveInput;

#[proc_macro_derive(Cat)]
pub fn derive_cat(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as DeriveInput);
cat::expand_derive_cat(&input)
}

src/cat.rs

use darling::{FromField, FromDeriveInput};
use proc_macro::TokenStream;
use quote::{ToTokens, quote};

#[derive(Clone, Debug, FromField)]
struct StructField {
ident: Option<syn::Ident>,
ty: syn::Type,
vis: syn::Visibility,
// If the line would be commented, all will be fine
attrs: Vec<syn::Attribute>,
}

#[derive(Debug, FromDeriveInput)]
#[darling(supports(struct_named))]
struct Cat {
ident: syn::Ident,
data: darling::ast::Data<(), StructField>,
}

impl ToTokens for Cat {
fn to_tokens(&self, out: &mut proc_macro2::TokenStream) {
let tokens = quote!{};

let fields = self.data.clone().take_struct().unwrap();

//dbg!(fields);

out.extend(tokens)
}
}

pub fn expand_derive_cat(input: &syn::DeriveInput) -> TokenStream {
let cat = match Cat::from_derive_input(&input) {
Ok(parsed) => parsed,
Err(e) => return e.write_errors().into(),
};

let tokens = quote! { #cat };
tokens.into()
}

但是报错了

error[E0425]: cannot find value `__fwd_attrs` in this scope
--> src/cat.rs:5:24
|
5 | #[derive(Clone, Debug, FromField)]
| ^^^^^^^^^ not found in this scope

error: aborting due to previous error

For more information about this error, try `rustc --explain E0425`.
error: could not compile `darling_attrs`.

To learn more, run the command again with --verbose.

如果 cat.rs 的第 11 行(我已经用评论标记了它)会被评论,程序将编译无误。

这里是 impl FromField for Vec .据我了解,this code 存在一些问题但我不知道如何解决这个问题。

如何在我的 StructField::attrs 上设置字段属性?

最佳答案

crate documentation 中所述,您错过了结构“StructField”的“forward_attrs” .

例如:

#[derive(Clone, Debug, FromField)]
#[darling(forward_attrs(cfg)]
struct StructField {
ident: Option<syn::Ident>,
ty: syn::Type,
vis: syn::Visibility,
// If the line would be commented, all will be fine
attrs: Vec<syn::Attribute>,
}

关于rust - 无法使用 syn/darling 获取字段属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60253187/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com