Skip to main content

auto_tuple/
lib.rs

1//! Element-wise tuple-ization for traits.
2//!
3//! `#[auto_tuple]` generates, for each requested arity, a helper trait whose
4//! methods/consts/types forward element-wise to each element of an N-tuple:
5//! `(x, y).foo(a)` desugars to `(x.foo(a), y.foo(a))`. See `docs/design.md`
6//! for the full semantics.
7//!
8//! ```ignore
9//! use auto_tuple::auto_tuple;
10//!
11//! #[auto_tuple]
12//! trait Tr {
13//!     fn zero() -> usize;
14//! }
15//!
16//! struct X;
17//! struct Y;
18//!
19//! impl Tr for X { fn zero() -> usize { 1 } }
20//! impl Tr for Y { fn zero() -> usize { 2 } }
21//!
22//! # fn main() {
23//! use auto_tuple::_TrTuple2;   // helper trait must be in scope
24//! assert_eq!(<(X, Y)>::zero(), (1, 2));
25//! # }
26//! ```
27
28mod analyze;
29mod attr;
30mod codegen;
31mod rewrite;
32
33use proc_macro::TokenStream;
34use quote::quote;
35use syn::{ItemTrait, TraitItem};
36
37use crate::attr::Config;
38use crate::codegen::Selected;
39
40/// Generates tuple helper traits for the annotated trait.
41///
42/// Arguments: an optional range of arities (default `2..=12`) and an optional
43/// list of trait items to process (default: all methods; associated consts and
44/// types are only processed when explicitly named).
45#[proc_macro_attribute]
46pub fn auto_tuple(args: TokenStream, input: TokenStream) -> TokenStream {
47    match expand(args.into(), input.into()) {
48        Ok(ts) => ts.into(),
49        Err(err) => err.to_compile_error().into(),
50    }
51}
52
53fn expand(
54    args: proc_macro2::TokenStream, input: proc_macro2::TokenStream,
55) -> syn::Result<proc_macro2::TokenStream> {
56    let cfg = Config::from_tokens(args)?;
57    let trait_: ItemTrait = syn::parse2(input)?;
58
59    if trait_.modifiers.auto_token.is_some() {
60        return Err(syn::Error::new_spanned(
61            &trait_,
62            "auto traits are not supported by `#[auto_tuple]`",
63        ));
64    }
65
66    let selected = select(&trait_, &cfg)?;
67    let track =
68        analyze::decide_track(&trait_, &selected.methods, &selected.consts, &selected.types);
69
70    let mut generated = Vec::new();
71    for n in cfg.sizes.clone() {
72        generated.push(codegen::generate(&trait_, track, &selected, n)?);
73    }
74
75    Ok(quote!(#trait_ #(#generated)*))
76}
77
78/// Picks the trait items to process.
79///
80/// Without an explicit list all methods are selected; associated consts and
81/// types are only selected when explicitly named.
82fn select<'a>(trait_: &'a ItemTrait, cfg: &Config) -> syn::Result<Selected<'a>> {
83    let Some(names) = &cfg.items else {
84        return Ok(Selected {
85            methods: trait_
86                .items
87                .iter()
88                .filter_map(|i| match i {
89                    TraitItem::Fn(f) => Some(f),
90                    _ => None,
91                })
92                .collect(),
93            consts: Vec::new(),
94            types: Vec::new(),
95        });
96    };
97
98    let mut selected = Selected { methods: Vec::new(), consts: Vec::new(), types: Vec::new() };
99    for name in names {
100        let mut found = false;
101        for item in &trait_.items {
102            let ident = match item {
103                TraitItem::Fn(f) => &f.sig.ident,
104                TraitItem::Const(c) => &c.ident,
105                TraitItem::Type(t) => &t.ident,
106                _ => continue,
107            };
108            if ident == name {
109                match item {
110                    TraitItem::Fn(f) => selected.methods.push(f),
111                    TraitItem::Const(c) => selected.consts.push(c),
112                    TraitItem::Type(t) => selected.types.push(t),
113                    _ => {}
114                }
115                found = true;
116                break;
117            }
118        }
119        if !found {
120            return Err(syn::Error::new_spanned(trait_, format!("trait item `{name}` not found")));
121        }
122    }
123    Ok(selected)
124}