quickerr 0.3.2

A macro to define errors quickly, like `thiserror` but terser and more opinionated
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#![deny(missing_docs, rustdoc::all)]
#![doc = include_str!("../README.md")]

use proc_macro::TokenStream;
use syn::__private::quote::quote;
use syn::__private::{ToTokens, TokenStream2};
use syn::parse::discouraged::Speculative;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::token::{self, Colon, Comma};
use syn::{bracketed, Attribute, Generics, Ident, LitStr, Result, Type, Visibility};

/// This macro allows quickly defining errors in the format that this crate produces.
///
/// It has 5 major forms:
/// - Unit struct:
/// ```
/// # use quickerr::error;
/// error! {
///     MyUnitError
///     "it's a unit error"
/// }
/// ```
/// - Record struct:
/// ```
/// # use quickerr::error;
/// # #[derive(Debug)]
/// # struct Type;
/// # #[derive(Debug)]
/// # struct Type2;
/// error! {
///     MyStructError
///     "it's a struct! Field 2 is {field2:?}"
///     field: Type,
///     field2: Type2,
/// }
/// ```
/// - Enum:
/// ```
/// # use quickerr::error;
/// # error! { SourceError1 "" }
/// # error! { MyUnitError "" }
/// # error! { MyStructError "" }
/// error! {
///     MyEnumError
///     "it's a whole enum"
///     SourceError1,
///     MyUnitError,
///     MyStructError,
/// }
/// ```
/// - Transparent enum:
/// ```
/// # use quickerr::error;
/// # error! { MyEnumError "uh oh" }
/// # error! { REALLY_LOUD_ERROR "uh oh" }
/// error! {
///     QuietAsAMouse
///     MyEnumError,
///     REALLY_LOUD_ERROR,
/// }
/// ```
/// - Array:
/// ```
/// # use quickerr::error;
/// # error! { SomeError "" }
/// error! {
///     ManyProblems
///     "encountered many problems"
///     [SomeError]
/// }
/// ```
///
/// Each form implements `Debug`, `Error`, and `From` as appropriate. The enum forms implement
/// [`std::error::Error::source()`] for each of their variants, and each variant must be the name
/// of an existing error type. The struct form exposes the fields for use in the error message.
/// The transparent enum form does not append a message, and simply passes the source along
/// directly. All forms are `#[non_exhaustive]` and all fields are public. They can be made public
/// by adding `pub` to the name like `pub MyError`.
///
/// Additional attributes can be added before the name to add them to the error type,
/// like so:
/// ```
/// # use quickerr::error;
/// error! {
///     #[derive(PartialEq, Eq)]
///     AttrsError
///     "has attributes!"
///     /// a number for something
///     num: i32
/// }
/// ```
///
/// Attributes can be added to fields and variants of struct/enum/array errors, and they can be
/// made generic:
/// ```
/// # use quickerr::error;
/// error! {
///     /// In case of emergency
///     BreakGlass<BreakingTool: std::fmt::Debug>
///     "preferably with a blunt object"
///     like_this_one: BreakingTool,
/// }
/// ```
///
/// If cfg attributes are used, they're copied to relevant places to ensure it compiles properly:
/// ```
/// # use quickerr::error;
/// # error!{ Case1 "" }
/// # error!{ Case2 "" }
/// # struct Foo;
/// # struct Bar;
/// error! {
///     #[cfg(feature = "drop_the_whole_error")]
///     EnumErr
///     "foo"
///     #[cfg(feature = "foo")]
///     Case1,
///     #[cfg(feature = "bar")]
///     Case2,
/// }
///
/// error! {
///     StructErr
///     "bar"
///     #[cfg(feature = "foo")]
///     field1: Foo,
///     #[cfg(feature = "bar")]
///     field2: Bar,
/// }
/// ```
/// Make sure not to use cfg'd fields in the error message string if those fields can ever be not
/// present.
#[proc_macro]
pub fn error(tokens: TokenStream) -> TokenStream {
    match error_impl(tokens.into()) {
        Ok(toks) => toks.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

fn error_impl(tokens: TokenStream2) -> Result<TokenStream2> {
    let Error {
        attrs,
        vis,
        name,
        generics,
        msg,
        contents,
    } = syn::parse2(tokens)?;

    let (impl_gen, ty_gen, where_gen) = generics.split_for_impl();

    let item_cfgs: Vec<&Attribute> = attrs
        .iter()
        .filter(|attr| attr.meta.path().is_ident("cfg"))
        .collect();
    let item_cfgs = quote! { #(#item_cfgs)* };

    Ok(match contents {
        ErrorContents::Unit => quote! {
            #(#attrs)*
            #[derive(Debug)]
            #[non_exhaustive]
            #vis struct #name #generics;

            #item_cfgs
            impl #impl_gen ::std::fmt::Display for #name #ty_gen #where_gen {
                fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                    f.write_str(#msg)
                }
            }

            #item_cfgs
            impl #impl_gen ::std::error::Error for #name #ty_gen #where_gen {}
        },
        ErrorContents::Struct { fields } => {
            let cfgs: Vec<Vec<&Attribute>> = fields
                .iter()
                .map(|field| {
                    field
                        .attrs
                        .iter()
                        .filter(|attr| attr.meta.path().is_ident("cfg"))
                        .collect()
                })
                .collect();
            let field_names: Vec<&Ident> = fields.iter().map(|field| &field.name).collect();
            quote! {
                #(#attrs)*
                #[derive(Debug)]
                #[non_exhaustive]
                #vis struct #name #generics {
                    #fields
                }

                #item_cfgs
                impl #impl_gen ::std::fmt::Display for #name #ty_gen #where_gen {
                    #[allow(unused_variables)]
                    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                        let Self {
                            #(
                                #(#cfgs)*
                                #field_names,
                            )*
                        } = self;
                        f.write_fmt(format_args!(#msg))
                    }
                }

                #item_cfgs
                impl #impl_gen ::std::error::Error for #name #ty_gen #where_gen {}
            }
        }
        ErrorContents::Enum { sources } => {
            let source_attrs: Vec<&Vec<Attribute>> =
                sources.iter().map(|source| &source.attrs).collect();
            let cfgs: Vec<Vec<Attribute>> = source_attrs
                .iter()
                .map(|&attrs| {
                    let mut attrs = attrs.clone();
                    attrs.retain(|attr| attr.meta.path().is_ident("cfg"));
                    attrs
                })
                .collect();
            let source_idents: Vec<&Ident> = sources.iter().map(|source| &source.ident).collect();
            let write_msg = match &msg {
                Some(msg) => quote! {
                    f.write_str(#msg)
                },
                None => {
                    quote! {
                        match self {
                            #(
                                #(#cfgs)*
                                Self::#source_idents(err) => ::std::fmt::Display::fmt(err, f),
                            )*
                            _ => unreachable!(),
                        }
                    }
                }
            };
            quote! {
                #(#attrs)*
                #[derive(Debug)]
                #[non_exhaustive]
                #vis enum #name #generics {
                    #(
                        #(#source_attrs)*
                        #source_idents(#source_idents),
                    )*
                }

                #item_cfgs
                impl #impl_gen ::std::fmt::Display for #name #ty_gen #where_gen {
                    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                        #write_msg
                    }
                }

                #item_cfgs
                impl #impl_gen ::std::error::Error for #name #ty_gen #where_gen {
                    fn source(&self) -> ::std::option::Option<&(dyn ::std::error::Error + 'static)> {
                        Some(match self {
                            #(
                                #(#cfgs)*
                                #name::#source_idents(err) => err,
                            )*
                            _ => unreachable!(),
                        })
                    }
                }

                #(
                    #item_cfgs
                    #(#cfgs)*
                    impl #impl_gen ::std::convert::From<#source_idents> for #name #ty_gen #where_gen {
                        fn from(source: #source_idents) -> Self {
                            Self::#source_idents(source)
                        }
                    }
                )*
            }
        }
        ErrorContents::Array {
            inner_attrs, inner, ..
        } => quote! {
            #(#attrs)*
            #[derive(Debug)]
            #[non_exhaustive]
            #vis struct #name #generics (#(#inner_attrs)* pub Vec<#inner>);

            #item_cfgs
            impl #impl_gen ::std::fmt::Display for #name #ty_gen #where_gen {
                fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                    f.write_str(#msg)?;
                    f.write_str(":")?;
                    for err in &self.0 {
                        f.write_str("\n")?;
                        f.write_fmt(format_args!("{}", err))?;
                    }
                    Ok(())
                }
            }

            #item_cfgs
            impl #impl_gen ::std::error::Error for #name #ty_gen #where_gen {}
        },
    })
}

struct Field {
    attrs: Vec<Attribute>,
    vis: Visibility,
    name: Ident,
    colon: Colon,
    ty: Type,
}

impl Parse for Field {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(Self {
            attrs: input.call(Attribute::parse_outer)?,
            vis: input.parse()?,
            name: input.parse()?,
            colon: input.parse()?,
            ty: input.parse()?,
        })
    }
}

impl ToTokens for Field {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        for attr in &self.attrs {
            attr.to_tokens(tokens);
        }
        self.vis.to_tokens(tokens);
        self.name.to_tokens(tokens);
        self.colon.to_tokens(tokens);
        self.ty.to_tokens(tokens);
    }
}

struct ErrorVariant {
    attrs: Vec<Attribute>,
    ident: Ident,
}

impl Parse for ErrorVariant {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(Self {
            attrs: input.call(Attribute::parse_outer)?,
            ident: input.parse()?,
        })
    }
}

enum ErrorContents {
    Unit,
    Struct {
        fields: Punctuated<Field, Comma>,
    },
    Enum {
        sources: Punctuated<ErrorVariant, Comma>,
    },
    Array {
        inner_attrs: Vec<Attribute>,
        inner: Type,
    },
}

impl Parse for ErrorContents {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.is_empty() {
            return Ok(Self::Unit);
        }

        let fork = input.fork();
        if let Ok(fields) = fork.call(Punctuated::parse_terminated) {
            input.advance_to(&fork);
            return Ok(Self::Struct { fields });
        }

        let fork = input.fork();
        if let Ok(sources) = fork.call(Punctuated::parse_terminated) {
            input.advance_to(&fork);
            return Ok(Self::Enum { sources });
        }

        if input.peek(token::Bracket) {
            let content;
            let _ = bracketed!(content in input);
            let attrs = content.call(Attribute::parse_outer)?;
            let inner = content.parse::<Type>()?;
            return Ok(Self::Array {
                inner_attrs: attrs,
                inner,
            });
        }

        Err(input.error("invalid error contents"))
    }
}

struct Error {
    attrs: Vec<Attribute>,
    vis: Visibility,
    name: Ident,
    generics: Generics,
    msg: Option<LitStr>,
    contents: ErrorContents,
}

impl Parse for Error {
    fn parse(input: ParseStream) -> Result<Self> {
        let attrs = input.call(Attribute::parse_outer)?;
        let vis = input.parse::<Visibility>()?;
        let name = input.parse::<Ident>()?;
        let generics = input.parse::<Generics>()?;
        let msg = input.parse::<LitStr>().ok();
        let contents = input.parse::<ErrorContents>()?;

        if msg.is_none() && !matches!(contents, ErrorContents::Enum { .. }) {
            return Err(input.error("any non-enum error must have a display message"));
        }

        Ok(Self {
            attrs,
            vis,
            name,
            generics,
            msg,
            contents,
        })
    }
}