1use proc_macro::TokenStream;
4use proc_macro_crate::{FoundCrate, crate_name};
5use proc_macro2::TokenStream as TokenStream2;
6use quote::quote;
7use syn::{Attribute, Data, DeriveInput, Error, Fields, Ident, parse_macro_input, parse_quote};
8
9#[proc_macro_derive(Reportable, attributes(reportable))]
14pub fn derive_reportable(input: TokenStream) -> TokenStream {
15 let input = parse_macro_input!(input as DeriveInput);
16 expand(input)
17 .unwrap_or_else(Error::into_compile_error)
18 .into()
19}
20
21fn expand(input: DeriveInput) -> syn::Result<TokenStream2> {
22 let path = match crate_name("reportable") {
23 Ok(FoundCrate::Itself) => quote!(::reportable),
24 Ok(FoundCrate::Name(name)) => {
25 let name = Ident::new(&name, input.ident.span());
26 quote!(::#name)
27 }
28 Err(error) => return Err(Error::new_spanned(&input.ident, error)),
29 };
30 expand_with_path(input, &path)
31}
32
33fn expand_with_path(input: DeriveInput, path: &TokenStream2) -> syn::Result<TokenStream2> {
34 let default = classification(&input.attrs, "type")?;
35 let cases = match input.data {
37 Data::Struct(data) => vec![(quote!(Self), input.ident.clone(), data.fields, None)],
38 Data::Enum(data) => data
39 .variants
40 .into_iter()
41 .map(|variant| {
42 let name = &variant.ident;
43 let mode = classification(&variant.attrs, "variant")?;
44 Ok((quote!(Self::#name), variant.ident, variant.fields, mode))
45 })
46 .collect::<syn::Result<_>>()?,
47 Data::Union(_) => {
48 return Err(Error::new_spanned(
49 input.ident,
50 "Reportable only supports structs and enums",
51 ));
52 }
53 };
54
55 let mut generics = input.generics;
56 let mut arms = Vec::new();
57 for (prefix, ident, fields, mode) in cases {
58 for field in &fields {
59 reject_misplaced(&field.attrs)?;
60 }
61 let mode = mode.or(default).ok_or_else(|| {
62 Error::new_spanned(
63 &ident,
64 "add #[reportable(caller)], #[reportable(internal)], or #[reportable(transparent)]",
65 )
66 })?;
67 let arm = match mode {
68 Classification::Caller | Classification::Internal => {
69 let destination = match mode {
70 Classification::Caller => quote!(#path::ReportTo::Caller),
71 _ => quote!(#path::ReportTo::Internal),
72 };
73 let pattern = match fields {
74 Fields::Unit => quote!(#prefix),
75 Fields::Unnamed(_) => quote!(#prefix(..)),
76 Fields::Named(_) => quote!(#prefix { .. }),
77 };
78 quote!(#pattern => #destination)
79 }
80 Classification::Transparent => {
81 let mut iter = fields.iter();
82 let (Some(field), None) = (iter.next(), iter.next()) else {
83 return Err(Error::new_spanned(
84 &ident,
85 "#[reportable(transparent)] requires exactly one field",
86 ));
87 };
88 let ty = &field.ty;
89 generics
90 .make_where_clause()
91 .predicates
92 .push(parse_quote!(#ty: #path::Reportable));
93
94 let pattern = match &field.ident {
95 Some(field_name) => quote!(#prefix { #field_name: inner }),
96 None => quote!(#prefix(inner)),
97 };
98 quote!(#pattern => #path::Reportable::report_to(inner))
99 }
100 };
101 arms.push(arm);
102 }
103
104 let name = input.ident;
105 let (impl_generics, type_generics, where_clause) = generics.split_for_impl();
106 let body = if arms.is_empty() {
108 quote!(match *self {})
109 } else {
110 quote!(match self { #(#arms,)* })
111 };
112 Ok(quote! {
113 impl #impl_generics #path::Reportable for #name #type_generics #where_clause {
114 fn report_to(&self) -> #path::ReportTo {
115 #body
116 }
117 }
118 })
119}
120
121fn reject_misplaced(attrs: &[Attribute]) -> syn::Result<()> {
122 if let Some(attr) = attrs.iter().find(|attr| attr.path().is_ident("reportable")) {
123 return Err(Error::new_spanned(
124 attr,
125 "#[reportable(...)] belongs on a struct, enum, or enum variant",
126 ));
127 }
128 Ok(())
129}
130
131#[derive(Clone, Copy)]
132enum Classification {
133 Caller,
134 Internal,
135 Transparent,
136}
137
138fn classification(attrs: &[Attribute], scope: &str) -> syn::Result<Option<Classification>> {
139 let mut attrs = attrs
140 .iter()
141 .filter(|attr| attr.path().is_ident("reportable"));
142 let Some(attr) = attrs.next() else {
143 return Ok(None);
144 };
145 if let Some(duplicate) = attrs.next() {
146 return Err(Error::new_spanned(
147 duplicate,
148 format!("use exactly one #[reportable(...)] annotation per {scope}"),
149 ));
150 }
151 let mode: Ident = attr.parse_args()?;
152 match mode.to_string().as_str() {
153 "caller" => Ok(Some(Classification::Caller)),
154 "internal" => Ok(Some(Classification::Internal)),
155 "transparent" => Ok(Some(Classification::Transparent)),
156 _ => Err(Error::new_spanned(
157 mode,
158 "expected caller, internal, or transparent",
159 )),
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166
167 #[test]
168 fn rejects_ambiguous_or_misplaced_classification() {
169 let cases = [
170 (
171 quote!(
172 enum E {
173 Missing,
174 }
175 ),
176 "add #[reportable(caller)]",
177 ),
178 (
179 quote!(
180 enum E {
181 #[reportable(unknown)]
182 V,
183 }
184 ),
185 "expected caller",
186 ),
187 (
188 quote!(
189 enum E {
190 #[reportable(caller)]
191 #[reportable(internal)]
192 V,
193 }
194 ),
195 "exactly one",
196 ),
197 (
198 quote!(
199 enum E {
200 #[reportable(transparent)]
201 V,
202 }
203 ),
204 "exactly one field",
205 ),
206 (
207 quote!(
208 enum E {
209 #[reportable(transparent)]
210 V(u8, u8),
211 }
212 ),
213 "exactly one field",
214 ),
215 (
216 quote!(
217 #[reportable(caller)]
218 #[reportable(internal)]
219 enum E {
220 V,
221 }
222 ),
223 "exactly one",
224 ),
225 (
226 quote!(
227 #[reportable(transparent)]
228 enum E {
229 V,
230 }
231 ),
232 "exactly one field",
233 ),
234 (
235 quote!(
236 enum E {
237 #[reportable(internal)]
238 V(#[reportable(caller)] u8),
239 }
240 ),
241 "belongs on a struct, enum, or enum variant",
242 ),
243 (
244 quote!(
245 struct E;
246 ),
247 "add #[reportable(caller)]",
248 ),
249 (
250 quote!(
251 #[reportable(transparent)]
252 struct E(u8, u8);
253 ),
254 "exactly one field",
255 ),
256 (
257 quote!(
258 #[reportable(internal)]
259 struct E(#[reportable(caller)] u8);
260 ),
261 "belongs on a struct",
262 ),
263 (
264 quote!(union E { value: u8 }),
265 "only supports structs and enums",
266 ),
267 ];
268 for (input, expected) in cases {
269 let input = syn::parse2(input).unwrap();
270 let error = expand_with_path(input, "e!(::reportable)).unwrap_err();
271 assert!(error.to_string().contains(expected), "{error}");
272 }
273
274 for input in [
275 quote!(
276 enum E {
277 #[reportable()]
278 V,
279 }
280 ),
281 quote!(
282 enum E {
283 #[reportable(caller, internal)]
284 V,
285 }
286 ),
287 quote!(
288 enum E {
289 #[reportable = "caller"]
290 V,
291 }
292 ),
293 ] {
294 assert!(expand_with_path(syn::parse2(input).unwrap(), "e!(::reportable)).is_err());
295 }
296 }
297}