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//! // No import needed: the helper trait lives in this module.
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    let vis = cfg.vis.clone().unwrap_or_else(|| trait_.vis.clone());
72    for n in cfg.sizes.clone() {
73        generated.push(codegen::generate(&trait_, track, &selected, n, &vis)?);
74    }
75
76    Ok(quote!(#trait_ #(#generated)*))
77}
78
79/// Picks the trait items to process.
80///
81/// Without an explicit list all methods are selected; associated consts and
82/// types are only selected when explicitly named.
83fn select<'a>(trait_: &'a ItemTrait, cfg: &Config) -> syn::Result<Selected<'a>> {
84    let Some(names) = &cfg.items else {
85        return Ok(Selected {
86            methods: trait_
87                .items
88                .iter()
89                .filter_map(|i| match i {
90                    TraitItem::Fn(f) => Some(f),
91                    _ => None,
92                })
93                .collect(),
94            consts: Vec::new(),
95            types: Vec::new(),
96        });
97    };
98
99    let mut selected = Selected { methods: Vec::new(), consts: Vec::new(), types: Vec::new() };
100    for name in names {
101        let mut found = false;
102        for item in &trait_.items {
103            let ident = match item {
104                TraitItem::Fn(f) => &f.sig.ident,
105                TraitItem::Const(c) => &c.ident,
106                TraitItem::Type(t) => &t.ident,
107                _ => continue,
108            };
109            if ident == name {
110                match item {
111                    TraitItem::Fn(f) => selected.methods.push(f),
112                    TraitItem::Const(c) => selected.consts.push(c),
113                    TraitItem::Type(t) => selected.types.push(t),
114                    _ => {}
115                }
116                found = true;
117                break;
118            }
119        }
120        if !found {
121            return Err(syn::Error::new_spanned(trait_, format!("trait item `{name}` not found")));
122        }
123    }
124    Ok(selected)
125}