1mod 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#[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
79fn 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 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 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 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 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 #[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}