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//! ```rust
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, cfg.name.as_deref())?);
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}
126
127#[cfg(test)]
128mod proptests {
129    use proc_macro2::TokenStream;
130    use proptest::prelude::*;
131
132    use super::expand;
133
134    /// Identifiers that may collide with generated names (`__T0`, `__TA0`,
135    /// `__arg0`, ...) or with ordinary user names.
136    fn ident_strategy() -> impl Strategy<Value = String> {
137        prop_oneof![
138            "__T0", "__T1", "__TA0", "__TA1", "__L0_a", "__C0_N", "__arg0", "T", "U", "N", "a",
139            "foo", "bar", "x", "y",
140        ]
141    }
142
143    /// Trait generic-parameter shapes (all syntactically valid).
144    fn trait_generics_strategy() -> impl Strategy<Value = String> {
145        prop_oneof![
146            Just(String::new()),
147            Just("<T>".to_string()),
148            Just("<T, U>".to_string()),
149            Just("<'a>".to_string()),
150            Just("<const N: usize>".to_string()),
151            Just("<T: Clone>".to_string()),
152            Just("<T = u32>".to_string()),
153        ]
154    }
155
156    /// Method shapes covering receivers, args, generics, async, unsafe,
157    /// `Self`-typed params/returns, RPIT and `where` clauses.
158    fn method_strategy() -> impl Strategy<Value = String> {
159        prop_oneof![
160            "fn foo(&self) -> usize;",
161            "fn foo(&mut self, x: usize) -> usize;",
162            "fn foo(self);",
163            "fn foo();",
164            "fn foo<X>(x: X) -> X;",
165            "fn foo<T: Clone>(&self, x: T) -> T;",
166            "fn foo(&self, x: &Self);",
167            "fn foo(&mut self, x: &mut Self);",
168            "fn foo(&self) -> Box<Self>;",
169            "fn foo(&self) -> Vec<Self> where Self: Sized;",
170            "async fn foo(&self) -> usize;",
171            "unsafe fn foo(&self) -> usize;",
172            "fn foo(&self) -> impl Iterator<Item = Self>;",
173            "fn foo(&self, x: Self::Output) -> Self::Output;",
174            "fn foo(&self) -> usize where Self: Sized;",
175        ]
176    }
177
178    /// Associated const/type items (syntactically valid).
179    fn extra_item_strategy() -> impl Strategy<Value = String> {
180        prop_oneof!["const MAX: usize;", "type Out;", "type Out: Clone;", "type Out = usize;",]
181    }
182
183    proptest! {
184        /// Any syntactically valid trait — including names that collide with
185        /// the macro's generated identifiers and every supported signature
186        /// shape — must expand without panicking (errors as `compile_error!`
187        /// are fine; the point is "never a macro panic").
188        #[test]
189        fn arbitrary_trait_never_panics(
190            trait_name in ident_strategy(),
191            trait_generics in trait_generics_strategy(),
192            methods in prop::collection::vec(method_strategy(), 0..6),
193            extra_items in prop::collection::vec(extra_item_strategy(), 0..3),
194        ) {
195            let body = [methods.join(" "), extra_items.join(" ")].join(" ");
196            let src = format!("trait {trait_name}{trait_generics} {{ {body} }}");
197            let tokens: TokenStream = src.parse().unwrap();
198            let _ = expand(TokenStream::new(), tokens);
199        }
200    }
201}