1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
#![recursion_limit = "4096"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::Span; use quote::quote; use std::rc::Rc; use syn::spanned::Spanned; use syn::*; enum ClapFieldName { Named(Ident), Unnamed(usize), } impl ClapFieldName { fn is_named(&self) -> bool { match self { ClapFieldName::Named(_) => true, _ => false, } } } struct ClapField { name: ClapFieldName, long: Option<LitStr>, help: Option<LitStr>, ty: Type, } impl ClapField { fn parse(name: ClapFieldName, data: &Field) -> parse::Result<Self> { let ty = data.ty.clone(); let mut long = None; let mut help = None; for attr in data.attrs.iter() { if let Ok(Meta::List(meta)) = attr.parse_meta() { if meta.ident == "preftool_clap" { for meta in meta.nested.iter() { match meta { NestedMeta::Literal(lit) => return Err(Error::new(lit.span(), "Unexpected literal")), NestedMeta::Meta(meta) => match meta { Meta::Word(w) => return Err(Error::new(w.span(), "Unexpected word meta")), Meta::List(l) => return Err(Error::new(l.span(), "Unexpected list meta")), Meta::NameValue(nv) => { if nv.ident == "name" { long = Some(Self::parse_lit_str("name", &nv.lit)?); } else if nv.ident == "help" { help = Some(Self::parse_lit_str("help", &nv.lit)?); } else { return Err(Error::new( nv.ident.span(), format!("Unknown property {}", nv.ident), )); } } }, } } } } } if !name.is_named() && long.is_none() { return Err(Error::new( data.span(), "Tuple fields must be decorated with name metadata.", )); } Ok(ClapField { name, long, help, ty, }) } fn parse_lit_str(name: &str, lit: &Lit) -> parse::Result<LitStr> { match lit { Lit::Str(s) => Ok(s.clone()), _ => Err(Error::new( lit.span(), format!("Expected string for '{}'", name), )), } } fn name(&self) -> LitStr { match &self.long { Some(n) => n.clone(), None => match &self.name { ClapFieldName::Named(i) => { let name = i.to_string(); LitStr::new(name.as_ref(), i.span()) } ClapFieldName::Unnamed(_) => panic!("ClapFields should always have names"), }, } } fn parse_fields(fields: &Fields) -> parse::Result<Vec<ClapField>> { match fields { Fields::Unit => Ok(Vec::new()), Fields::Unnamed(f) => { let mut fields = Vec::with_capacity(f.unnamed.len()); for (i, field) in f.unnamed.iter().enumerate() { let name = ClapFieldName::Unnamed(i); fields.push(ClapField::parse(name, field)?); } Ok(fields) } Fields::Named(f) => { let mut fields = Vec::with_capacity(f.named.len()); for field in f.named.iter() { let name = ClapFieldName::Named(field.ident.clone().unwrap()); fields.push(ClapField::parse(name, field)?); } Ok(fields) } } } } struct ClapStruct { name: Ident, fields: Vec<ClapField>, } impl ClapStruct { fn parse(input: &DeriveInput, item: &DataStruct) -> parse::Result<Self> { let name = input.ident.clone(); let fields = ClapField::parse_fields(&item.fields)?; Ok(ClapStruct { name, fields }) } fn parse_from_variant(variant: &Variant) -> parse::Result<Self> { let name = variant.ident.clone(); let fields = ClapField::parse_fields(&variant.fields)?; Ok(ClapStruct { name, fields }) } } struct ClapEnum { variants: Vec<Rc<ClapStruct>>, } impl ClapEnum { fn parse(input: &DeriveInput, item: &DataEnum) -> parse::Result<Self> { let _name = input.ident.clone(); let mut variants = Vec::with_capacity(item.variants.len()); for variant in item.variants.iter() { variants.push(Rc::new(ClapStruct::parse_from_variant(variant)?)); } Ok(ClapEnum { variants }) } } enum ClapItemData { Struct(Rc<ClapStruct>), Enum(Rc<ClapEnum>), } impl From<ClapStruct> for ClapItemData { fn from(s: ClapStruct) -> Self { ClapItemData::Struct(Rc::new(s)) } } impl From<ClapEnum> for ClapItemData { fn from(e: ClapEnum) -> Self { ClapItemData::Enum(Rc::new(e)) } } struct ClapItem { data: ClapItemData, generics: Generics, ident: Ident, } impl parse::Parse for ClapItem { fn parse(input: parse::ParseStream) -> parse::Result<Self> { let input = DeriveInput::parse(input)?; let data = match &input.data { Data::Struct(s) => Ok(ClapStruct::parse(&input, s)?.into()), Data::Enum(e) => Ok(ClapEnum::parse(&input, e)?.into()), Data::Union(_) => Err(Error::new(Span::call_site(), "Unions not supported.")), }?; let generics = input.generics; let ident = input.ident; Ok(ClapItem { data, generics, ident, }) } } #[proc_macro_derive(ClapConfig, attributes(preftool_clap))] pub fn derive_preftool_clap(input: TokenStream) -> TokenStream { let item: ClapItem = parse_macro_input!(input); let ident = &item.ident; let (impl_generics, ty_generics, where_clause) = item.generics.split_for_impl(); let conf = configure::item(&item.data); let populate = populate::item(&item.data); let out = quote! { impl #impl_generics ::preftool_clap::ClapConfig for #ident #ty_generics #where_clause { fn configure<'c>( app: &mut ::preftool_clap::AppBuilder, context: ::preftool_clap::Context<'c>, help: Option<&'static str>, ) { assert!(help.is_none(), "Help should not be provided for nested configure object."); #conf } fn populate<'a, 'c>( builder: &mut ::preftool::ConfigurationProviderBuilder, matches: &::clap::ArgMatches<'a>, context: ::preftool_clap::Context<'c>, ) { #populate } } }; out.into() } mod configure; mod populate;