TedDriggs / darling

A Rust proc-macro attribute parser
MIT License
983 stars 66 forks source link

Is it possible to parse undeclared attributes while analyzing `syn` tree? #307

Open nyurik opened 1 day ago

nyurik commented 1 day ago

I have a proc macro attached to a fn item. On some of the function's attributes inside that mod I would like to have custom attribute that has associated proc macro attributes declared. This is similar to how #[default] can be attached to an enum value inside the #[derive(Default)]. How can I do this, and would it be possible to document it somewhere?

Example

/// Usage
#[my_proc_macro]
fn bar(
  #[arg(default = "value")] baz: &str
) {
  todo!()
}
/// Fill out this struct from the `#[arg(default = "baz")]`
#[derive(Default, Debug, FromMeta)]
#[darling(default)]
pub struct ArgConfig {
    pub default: Option<String>,
}

// Parsing
#[proc_macro_attribute]
pub fn my_proc_macro(args: pm::TokenStream, input: pm::TokenStream) -> pm::TokenStream {
    let fn_item = parse_macro_input!(input as ItemFn);
    for arg in &fn_item.sig.inputs {
      let FnArg::Typed(ty) = arg else { continue };
      // use ty.attrs -- parse into ArgConfig
      todo!();
   }
}