1#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]
2
3use proc_macro::TokenStream;
4use quote::{ToTokens, quote};
5use syn::{
6 Error, FnArg, Result, Token, Type, Variant, braced, parenthesized, parse::Parser,
7 punctuated::Punctuated, spanned::Spanned,
8};
9
10const FUNC_ATTR: &str = "func";
11const ASSOC_ATTR: &str = "assoc";
12
13#[proc_macro_derive(Assoc, attributes(func, assoc))]
14pub fn derive_assoc(input: TokenStream) -> TokenStream {
15 impl_macro(&syn::parse(input).expect("Failed to parse macro input"))
16 .unwrap_or_else(syn::Error::into_compile_error)
18 .into()
19}
20
21fn impl_macro(ast: &syn::DeriveInput) -> Result<proc_macro2::TokenStream> {
22 let name = &ast.ident;
23 let generics = &ast.generics;
24 let generic_params = &generics.params;
25 let where_clause = &generics.where_clause;
26 let fns = ast
27 .attrs
28 .iter()
29 .filter(|attr| attr.path().is_ident(FUNC_ATTR))
30 .map(|attr| syn::parse2::<DeriveFuncs>(attr.meta.to_token_stream()))
31 .collect::<Result<Vec<DeriveFuncs>>>()?;
32 let variants: Vec<&Variant> = if let syn::Data::Enum(data) = &ast.data {
33 data.variants.iter().collect()
34 } else {
35 panic!("#[derive(Assoc)] only applicable to enums")
36 };
37 let mut impls: Vec<proc_macro2::TokenStream> = Vec::new();
38 for DeriveFuncs(items) in fns {
39 let mut associated_funcs = Vec::new();
40 for item in &items {
41 match item {
42 DeriveItem::Func(func) => associated_funcs.push(func.assoc_name.clone()),
43 DeriveItem::Impl(imp) => {
44 associated_funcs.extend(imp.funcs.iter().map(|f| f.assoc_name.clone()))
45 }
46 }
47 }
48 let mut functions = Vec::new();
49 for item in items {
50 match item {
51 DeriveItem::Func(func) => functions.push(build_function(
52 &variants,
53 &func,
54 &associated_funcs,
55 name,
56 false,
57 )?),
58 DeriveItem::Impl(imp) => {
59 let trait_impl_for_other =
63 imp.trait_.is_some() && !type_is_enum(&imp.self_ty, name);
64 let mut methods = Vec::new();
65 for func in &imp.funcs {
66 if imp.trait_.is_some() && !matches!(func.vis, syn::Visibility::Inherited) {
67 return Err(Error::new_spanned(
68 &func.vis,
69 "Trait implementation methods cannot have a visibility modifier",
70 ));
71 }
72 methods.push(build_function(
73 &variants,
74 func,
75 &associated_funcs,
76 name,
77 trait_impl_for_other,
78 )?);
79 }
80 impls.push(build_impl(imp, &methods));
81 }
82 }
83 }
84 if !functions.is_empty() {
85 impls.push(quote! {
86 #[allow(clippy::used_underscore_binding)]
87 impl <#generic_params> #name #generics #where_clause
88 {
89 #(#functions)*
90 }
91 });
92 }
93 }
94 Ok(quote! { #(#impls)* })
95}
96
97fn build_impl(imp: DeriveImpl, methods: &[proc_macro2::TokenStream]) -> proc_macro2::TokenStream {
98 let unsafety = &imp.unsafety;
99 let generics = &imp.generics;
100 let where_clause = &generics.where_clause;
101 let self_ty = &imp.self_ty;
102 let header = if let Some((bang, trait_path, for_token)) = &imp.trait_ {
103 quote!(impl #generics #bang #trait_path #for_token #self_ty #where_clause)
104 } else {
105 quote!(impl #generics #self_ty #where_clause)
106 };
107 quote! {
108 #[allow(clippy::used_underscore_binding)]
109 #unsafety #header
110 {
111 #(#methods)*
112 }
113 }
114}
115
116fn type_is_enum(ty: &Type, name: &syn::Ident) -> bool {
117 match ty {
118 Type::Path(type_path) if type_path.qself.is_none() => type_path
119 .path
120 .segments
121 .last()
122 .is_some_and(|segment| segment.ident == *name),
123 Type::Group(group) => type_is_enum(&group.elem, name),
124 Type::Paren(paren) => type_is_enum(&paren.elem, name),
125 _ => false,
126 }
127}
128
129fn build_function(
130 variants: &[&Variant],
131 func: &DeriveFunc,
132 associated_funcs: &[syn::Ident],
133 enum_name: &syn::Ident,
134 trait_impl_for_other: bool,
135) -> Result<proc_macro2::TokenStream> {
136 let vis = &func.vis;
137 let sig = &func.sig;
138 let has_self = match func.sig.inputs.first() {
141 Some(FnArg::Receiver(_)) => true,
142 Some(FnArg::Typed(pat_type)) => {
143 let pat = &pat_type.pat;
144 quote!(#pat).to_string().trim() == "self"
145 }
146 None => false,
147 };
148 let is_reverse = !has_self && !trait_impl_for_other;
149 let enum_path = if trait_impl_for_other {
152 quote!(#enum_name)
153 } else {
154 quote!(Self)
155 };
156 let is_option = if let syn::ReturnType::Type(_, ty) = &func.sig.output {
157 let s = quote!(#ty).to_string();
158 let trimmed = s.trim();
159 trimmed.starts_with("Option") && trimmed.len() > 6 && trimmed[6..].trim().starts_with("<")
160 } else {
161 false
162 };
163 let mut arms = variants
164 .iter()
165 .map(|variant| {
166 build_variant_arm(
167 variant,
168 &func.assoc_name,
169 associated_funcs.iter().cloned(),
170 is_option,
171 is_reverse,
172 &func.def,
173 &enum_path,
174 )
175 })
176 .collect::<Result<Vec<(proc_macro2::TokenStream, Wildcard)>>>()?;
177 if is_option
178 && !arms
179 .iter()
180 .any(|(_, wildcard)| matches!(wildcard, Wildcard::True))
181 {
182 arms.push((quote!(_ => None,), Wildcard::True))
183 }
184 if is_reverse {
186 arms.sort_by(|(_, wildcard1), (_, wildcard2)| wildcard1.cmp(wildcard2));
187 }
188 let arms = arms.into_iter().map(|(toks, _)| toks);
189 let match_on = if is_reverse {
190 let mut result = quote!();
191 for input in &func.sig.inputs {
192 match input {
193 FnArg::Receiver(_) => {
194 result = quote!(self);
195 break;
196 }
197 FnArg::Typed(pat_type) => {
198 let pat = &pat_type.pat;
199 result = if result.is_empty() {
200 quote!(#pat)
201 } else {
202 quote!(#result, #pat)
203 };
204 }
205 }
206 }
207 if func.sig.inputs.is_empty() {
208 return Err(syn::Error::new(func.span, "Missing parameter"));
209 }
210 if func.sig.inputs.len() > 1 {
211 result = quote!((#result));
212 }
213 result
214 } else if has_self {
215 quote!(self)
216 } else {
217 match func.sig.inputs.first() {
218 Some(FnArg::Typed(pat_type)) => {
219 let pat = &pat_type.pat;
220 quote!(#pat)
221 }
222 _ => return Err(syn::Error::new(func.span, "Missing parameter")),
223 }
224 };
225 Ok(quote! {
226 #vis #sig
227 {
228 match #match_on
229 {
230 #(#arms)*
231 }
232 }
233 })
234}
235
236fn build_variant_arm(
237 variant: &Variant,
238 func: &syn::Ident,
239 mut assoc_funcs: impl Iterator<Item = syn::Ident>,
240 is_option: bool,
241 is_reverse: bool,
242 def: &Option<proc_macro2::TokenStream>,
243 enum_path: &proc_macro2::TokenStream,
244) -> Result<(proc_macro2::TokenStream, Wildcard)> {
245 let assocs = Association::get_variant_assocs(variant, is_reverse).filter(|assoc| {
247 assoc.func == *func || assoc_funcs.any(|assoc_func| assoc_func == assoc.func)
248 });
249 if is_reverse {
250 build_rev_assoc(assocs, variant, is_option, enum_path)
251 } else {
252 build_fwd_assoc(assocs, variant, is_option, func, def, enum_path)
253 }
254}
255
256fn build_fwd_assoc(
257 assocs: impl Iterator<Item = Association>,
258 variant: &Variant,
259 is_option: bool,
260 func_ident: &syn::Ident,
261 def: &Option<proc_macro2::TokenStream>,
262 enum_path: &proc_macro2::TokenStream,
263) -> Result<(proc_macro2::TokenStream, Wildcard)> {
264 let var_ident = &variant.ident;
265 let fields = match &variant.fields {
266 syn::Fields::Named(fields) => {
267 let named = fields
268 .named
269 .iter()
270 .map(|f| {
271 let ident = &f.ident;
272 let val: &Option<proc_macro2::Ident> = &f.ident.as_ref().map(|s| {
273 proc_macro2::Ident::new(&("_".to_string() + &s.to_string()), f.span())
274 });
275 quote!(#ident: #val)
276 })
277 .collect::<Vec<proc_macro2::TokenStream>>();
278 quote!({#(#named),*})
279 }
280 syn::Fields::Unnamed(fields) => {
281 let unnamed = fields
282 .unnamed
283 .iter()
284 .enumerate()
285 .map(|(i, f)| {
286 let ident =
287 proc_macro2::Ident::new(&("_".to_string() + &i.to_string()), f.span());
288 quote!(#ident)
289 })
290 .collect::<Vec<proc_macro2::TokenStream>>();
291 quote!((#(#unnamed),*))
292 }
293 _ => quote!(),
294 };
295 let assocs = assocs
296 .filter_map(|assoc| {
297 if let AssociationType::Forward(expr) = assoc.assoc {
298 Some(Ok(expr))
299 } else {
300 None
301 }
302 })
303 .collect::<Result<Vec<syn::Expr>>>()?;
304 match assocs.len() {
305 0 => {
306 if let Some(tokens) = def {
307 Ok(quote! { #enum_path::#var_ident #fields => #tokens, })
308 } else if is_option {
309 Ok(quote! { #enum_path::#var_ident #fields => None, })
310 } else {
311 Err(Error::new_spanned(
312 variant,
313 format!("Missing `assoc` attribute for {}", func_ident),
314 ))
315 }
316 }
317 1 => {
318 let val = &assocs[0];
319 if is_option {
320 if quote!(#val).to_string().trim() == "None" {
321 Ok(quote! { #enum_path::#var_ident #fields => #val, })
322 } else {
323 Ok(quote! { #enum_path::#var_ident #fields => Some(#val), })
324 }
325 } else {
326 Ok(quote! { #enum_path::#var_ident #fields => #val, })
327 }
328 }
329 _ => Err(Error::new_spanned(
330 variant,
331 format!("Too many `assoc` attributes for {}", func_ident),
332 )),
333 }
334 .map(|toks| (toks, Wildcard::None))
335}
336
337fn build_rev_assoc(
338 assocs: impl Iterator<Item = Association>,
339 variant: &Variant,
340 is_option: bool,
341 enum_path: &proc_macro2::TokenStream,
342) -> Result<(proc_macro2::TokenStream, Wildcard)> {
343 let var_ident = &variant.ident;
344 let assocs = assocs
345 .filter_map(|assoc| {
346 if let AssociationType::Reverse(pat) = assoc.assoc {
347 Some(Ok(pat))
348 } else {
349 None
350 }
351 })
352 .collect::<Result<Vec<syn::Pat>>>()?;
353 let mut concrete_pats: Vec<proc_macro2::TokenStream> = Vec::new();
354 let mut wildcard_pat: Option<proc_macro2::TokenStream> = None;
355 let mut wildcard_status = Wildcard::False;
356 for pat in assocs.iter() {
357 if !matches!(variant.fields, syn::Fields::Unit) {
358 return Err(Error::new_spanned(
359 variant,
360 "Reverse associations not allowed for tuple or struct-like variants",
361 ));
362 }
363 let arm = if is_option {
364 quote!(#pat => Some(#enum_path::#var_ident),)
365 } else {
366 quote!(#pat => #enum_path::#var_ident,)
367 };
368 if matches!(pat, syn::Pat::Wild(_)) {
369 if wildcard_pat.is_some() {
370 return Err(syn::Error::new_spanned(
371 pat,
372 "Only 1 wildcard allowed per reverse association",
373 ));
374 }
375 wildcard_status = Wildcard::True;
376 wildcard_pat = Some(arm);
377 } else {
378 concrete_pats.push(arm);
379 }
380 }
381 if let Some(wildcard_pat) = wildcard_pat {
382 concrete_pats.push(wildcard_pat)
383 }
384 Ok((quote!(#(#concrete_pats) *), wildcard_status))
385}
386
387#[derive(Clone)]
391struct DeriveFunc {
392 vis: syn::Visibility,
393 sig: syn::Signature,
394 assoc_name: syn::Ident,
399 span: proc_macro2::Span,
400 def: Option<proc_macro2::TokenStream>,
401}
402
403enum DeriveItem {
406 Func(DeriveFunc),
407 Impl(DeriveImpl),
408}
409
410struct DeriveImpl {
414 unsafety: Option<Token![unsafe]>,
415 generics: syn::Generics,
416 trait_: Option<(Option<Token![!]>, syn::Path, Token![for])>,
417 self_ty: syn::Type,
418 funcs: Vec<DeriveFunc>,
419}
420
421struct Association {
424 func: syn::Ident,
425 assoc: AssociationType,
426}
427
428enum AssociationType {
429 Forward(syn::Expr),
430 Reverse(syn::Pat),
431}
432
433#[derive(PartialEq, Eq, PartialOrd, Ord)]
438enum Wildcard {
439 False = 0,
440 None = 1,
441 True = 2,
442}
443
444impl syn::parse::Parse for DeriveFunc {
445 fn parse(input: syn::parse::ParseStream) -> Result<Self> {
447 let vis = input.parse::<syn::Visibility>()?;
448 let sig = input.parse::<syn::Signature>()?;
449 let span = sig.ident.span();
450 let assoc_name = if input.peek(Token![as]) {
451 input.parse::<Token![as]>()?;
452 input.parse::<syn::Ident>()?
453 } else {
454 sig.ident.clone()
455 };
456 let def = if input.peek(syn::token::Brace) {
457 let block = input.parse::<syn::Block>()?;
458 Some(ToTokens::into_token_stream(block))
459 } else {
460 None
461 };
462 Ok(DeriveFunc {
463 vis,
464 sig,
465 assoc_name,
466 span,
467 def,
468 })
469 }
470}
471
472impl syn::parse::Parse for DeriveItem {
473 fn parse(input: syn::parse::ParseStream) -> Result<Self> {
474 let is_impl =
475 input.peek(Token![impl]) || (input.peek(Token![unsafe]) && input.peek2(Token![impl]));
476 if is_impl {
477 Ok(DeriveItem::Impl(input.parse()?))
478 } else {
479 Ok(DeriveItem::Func(input.parse()?))
480 }
481 }
482}
483
484impl syn::parse::Parse for DeriveImpl {
485 fn parse(input: syn::parse::ParseStream) -> Result<Self> {
486 let unsafety = input.parse::<Option<Token![unsafe]>>()?;
487 input.parse::<Token![impl]>()?;
488 let mut generics = input.parse::<syn::Generics>()?;
489 let bang = input.parse::<Option<Token![!]>>()?;
490 let first_path = input.parse::<syn::Path>()?;
491 let (trait_, self_ty) = if input.peek(Token![for]) {
492 let for_token = input.parse::<Token![for]>()?;
493 let self_ty = input.parse::<syn::Type>()?;
494 (Some((bang, first_path, for_token)), self_ty)
495 } else {
496 if let Some(bang) = bang {
497 return Err(Error::new(
498 bang.span,
499 "`!` is only allowed in trait implementations",
500 ));
501 }
502 (
503 None,
504 syn::Type::Path(syn::TypePath {
505 attrs: Vec::new(),
506 qself: None,
507 path: first_path,
508 }),
509 )
510 };
511 generics.where_clause = input.parse::<Option<syn::WhereClause>>()?;
512 let content;
513 braced!(content in input);
514 let mut funcs = Vec::new();
515 while !content.is_empty() {
516 funcs.push(content.parse::<DeriveFunc>()?);
517 if content.peek(Token![,]) {
518 content.parse::<Token![,]>()?;
519 }
520 }
521 Ok(DeriveImpl {
522 unsafety,
523 generics,
524 trait_,
525 self_ty,
526 funcs,
527 })
528 }
529}
530
531struct DeriveFuncs(Vec<DeriveItem>);
532impl syn::parse::Parse for DeriveFuncs {
533 fn parse(input: syn::parse::ParseStream) -> Result<Self> {
535 input.step(|cursor| {
536 if let Some((_, next)) = cursor.token_tree() {
537 Ok(((), next))
538 } else {
539 Err(cursor.error("Missing function signature"))
540 }
541 })?;
542 let content;
543 parenthesized!(content in input);
544 Ok(Self(
545 content
546 .parse_terminated(DeriveItem::parse, Token!(,))
547 .map(|parsed| parsed.into_iter().collect())?,
548 ))
549 }
550}
551
552struct ForwardAssocTokens(syn::Ident, syn::Expr);
554impl syn::parse::Parse for ForwardAssocTokens {
555 fn parse(input: syn::parse::ParseStream) -> Result<Self> {
556 let ident = input.parse()?;
557 input.parse::<syn::Token!(=)>()?;
558 let expr = input.parse()?;
559 Ok(Self(ident, expr))
560 }
561}
562
563struct ReverseAssocTokens(syn::Ident, syn::Pat);
565impl syn::parse::Parse for ReverseAssocTokens {
566 fn parse(input: syn::parse::ParseStream) -> Result<Self> {
567 let ident = input.parse()?;
568 input.parse::<syn::Token!(=)>()?;
569 let pat = syn::Pat::parse_multi_with_leading_vert(input)?;
570 Ok(Self(ident, pat))
571 }
572}
573
574impl From<ForwardAssocTokens> for Association {
575 fn from(val: ForwardAssocTokens) -> Self {
576 Association {
577 func: val.0,
578 assoc: AssociationType::Forward(val.1),
579 }
580 }
581}
582
583impl From<ReverseAssocTokens> for Association {
584 fn from(val: ReverseAssocTokens) -> Self {
585 Association {
586 func: val.0,
587 assoc: AssociationType::Reverse(val.1),
588 }
589 }
590}
591
592impl Association {
593 fn get_variant_assocs(variant: &Variant, is_reverse: bool) -> impl Iterator<Item = Self> + '_ {
594 variant
595 .attrs
596 .iter()
597 .filter(|assoc_attr| assoc_attr.path().is_ident(ASSOC_ATTR))
598 .filter_map(move |attr| {
599 if let syn::Meta::List(meta_list) = &attr.meta {
600 if is_reverse {
601 let parser = Punctuated::<ReverseAssocTokens, Token![,]>::parse_terminated;
602 parser
603 .parse2(meta_list.tokens.clone())
604 .map(|tokens| {
605 tokens
606 .into_iter()
607 .map(|tokens| tokens.into())
608 .collect::<Vec<Self>>()
609 })
610 .ok()
611 } else {
612 let parser = Punctuated::<ForwardAssocTokens, Token![,]>::parse_terminated;
613 parser
614 .parse2(meta_list.tokens.clone())
615 .map(|tokens| {
616 tokens
617 .into_iter()
618 .map(|tokens| tokens.into())
619 .collect::<Vec<Self>>()
620 })
621 .ok()
622 }
623 } else {
624 None
625 }
626 })
627 .flatten()
628 }
629}