declare_impl 0.8.2

Implementation of the proc macro for the error_set crate.
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
use proc_macro2::TokenStream;
use syn::{
    braced, parenthesized,
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    spanned::Spanned,
    token, Attribute, Ident, Result, TypeParam,
};

const DISPLAY_ATTRIBUTE_NAME: &str = "display";
const DISABLE_ATTRIBUTE_NAME: &str = "disable";

#[derive(Clone)]
pub(crate) struct AstErrorSet {
    pub(crate) set_items: Vec<AstErrorDeclaration>,
}

impl Parse for AstErrorSet {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut set_items = Vec::new();
        while !input.is_empty() {
            let set_item = input.parse::<AstErrorDeclaration>()?;
            set_items.push(set_item);
            if input.parse::<token::Semi>().is_err() {
                return Err(syn::Error::new(
                    input.span(),
                    "Missing ending `;` for the set.",
                ));
            }
        }
        Ok(AstErrorSet { set_items })
    }
}

#[derive(Clone)]
pub(crate) struct AstErrorDeclaration {
    pub(crate) attributes: Vec<Attribute>,
    pub(crate) error_name: Ident,
    pub(crate) generics: Vec<TypeParam>,
    pub(crate) disabled: Disabled,
    pub(crate) parts: Vec<AstInlineOrRefError>,
}

impl Parse for AstErrorDeclaration {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut attributes = input.call(Attribute::parse_outer)?;
        let disabled = extract_disabled(&mut attributes)?;
        if input.is_empty() {
            return Err(syn::Error::new(
                input.span(),
                    "Expected an error definition to be next after attributes. You may have a dangling doc comment.",
            ));
        }
        let save_position = input.fork();
        let error_name: Ident = input.parse()?;
        if !input.peek(syn::Token![=]) && !input.peek(syn::Token![<]) {
            return Err(syn::Error::new(
                save_position.span(),
                "Expected `=` or generic `<..>` to be next next.",
            ));
        }
        let generics = generics(&input)?;
        let last_position_save = input.fork();
        if !input.peek(syn::Token![=]) {
            return Err(syn::Error::new(
                last_position_save.span(),
                "Expected `=` to be next.",
            ));
        }
        input.parse::<syn::Token![=]>().unwrap();
        let mut parts = Vec::new();
        while !input.is_empty() {
            let part = input.parse::<AstInlineOrRefError>()?;
            parts.push(part);
            if input.is_empty() {
                break;
            }
            if !input.peek(token::Semi) && !input.peek(token::OrOr) {
                return Err(syn::Error::new(
                    input.span(),
                    "Expected `;` or `||` to be next.",
                ));
            }
            if input.peek(token::Semi) {
                break;
            }
            input.parse::<token::OrOr>().unwrap();
        }
        if parts.is_empty() {
            return Err(syn::Error::new(
                last_position_save.span(),
                "Missing error definitions",
            ));
        }
        return Ok(AstErrorDeclaration {
            attributes,
            error_name,
            generics,
            disabled,
            parts,
        });
    }
}

#[derive(Clone)]
pub(crate) enum AstInlineOrRefError {
    Inline(AstInlineError),
    Ref(RefError),
}

impl Parse for AstInlineOrRefError {
    fn parse(input: ParseStream) -> Result<Self> {
        if input.peek(token::Brace) {
            return match input.parse::<AstInlineError>() {
                Ok(inline_error) => Ok(AstInlineOrRefError::Inline(inline_error)),
                Err(err) => Err(err),
            };
        }
        match input.parse::<RefError>() {
            Ok(ref_error) => Ok(AstInlineOrRefError::Ref(ref_error)),
            Err(err) => Err(syn::parse::Error::new(
                err.span(),
                "Expected the error variants to be inline or a reference to another error enum.",
            )),
        }
    }
}

#[derive(Clone)]
pub(crate) struct AstInlineError {
    pub error_variants: Punctuated<AstErrorVariant, token::Comma>,
}

impl Parse for AstInlineError {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        let save_position = input.fork();
        let _brace_token = braced!(content in input);
        let error_variants = content.parse_terminated(
            |input: ParseStream| input.parse::<AstErrorVariant>(),
            token::Comma,
        )?;
        if error_variants.is_empty() {
            return Err(syn::parse::Error::new(
                save_position.span(),
                "Inline error variants cannot be empty",
            ));
        }
        return Ok(AstInlineError { error_variants });
    }
}

#[derive(Clone)]
pub(crate) struct RefError {
    pub(crate) name: Ident,
    pub(crate) generic_refs: Vec<Ident>,
}

impl Parse for RefError {
    fn parse(input: ParseStream) -> Result<Self> {
        let name = input.parse::<Ident>()?;
        let generics = generics(&input)?;
        Ok(RefError {
            name,
            generic_refs: generics,
        })
    }
}

//************************************************************************//

/// A variant for an error
#[derive(Clone)]
pub(crate) struct AstErrorVariant {
    pub(crate) attributes: Vec<Attribute>,
    pub(crate) display: Option<DisplayAttribute>,
    pub(crate) name: Ident,
    // Dev Note: `Some(Vec::new())` == `{}`, `Some(Vec::new(..))` == `{..}`, `None` == ``. `{}` means inline struct if has source as well.
    pub(crate) fields: Option<Vec<AstInlineErrorVariantField>>,
    pub(crate) source_type: Option<syn::TypePath>,
    #[allow(dead_code)] // todo remove when this is implemented
    pub(crate) backtrace_type: Option<syn::TypePath>,
}

impl Parse for AstErrorVariant {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut attributes = input.call(Attribute::parse_outer)?;
        let display = extract_display_attribute(&mut attributes)?;
        let name = input.parse::<Ident>()?;
        let content: syn::Result<_> = (|| {
            let content;
            parenthesized!(content in input);
            return Ok(content);
        })();
        let mut source_type = None;
        let mut backtrace_type = None;
        if let Ok(content) = content {
            let source_and_backtrace = content.parse_terminated(
                |input: ParseStream| input.parse::<syn::TypePath>(),
                token::Comma,
            );
            if let Ok(source_and_backtrace) = source_and_backtrace {
                if source_and_backtrace.len() <= 2 {
                    let mut source_and_backtrace = source_and_backtrace.into_iter();
                    source_type = source_and_backtrace.next();
                    backtrace_type = source_and_backtrace.next();
                } else {
                    return Err(syn::parse::Error::new(
                        source_and_backtrace.span(),
                        format!("Expected at most two elements - a source error type and a backtrace. Recieved {}.",source_and_backtrace.len() ),
                    ));
                }
            }
        }
        let content: syn::Result<_> = (|| {
            let content;
            syn::braced!(content in input);
            return Ok(content);
        })();
        let content = match content {
            Err(_) => {
                return Ok(AstErrorVariant {
                    attributes,
                    display,
                    name,
                    fields: None,
                    source_type,
                    backtrace_type,
                });
            }
            Ok(content) => content,
        };
        let fields = content
            .parse_terminated(AstInlineErrorVariantField::parse, syn::Token![,])?
            .into_iter()
            .collect::<Vec<_>>();
        let fields = Some(fields);
        Ok(AstErrorVariant {
            attributes,
            display,
            name,
            fields,
            source_type,
            backtrace_type,
        })
    }
}

//************************************************************************//

fn generics<T: Parse>(input: &ParseStream) -> Result<Vec<T>> {
    if input.peek(syn::Token![<]) {
        input.parse::<syn::Token![<]>()?;
        let mut generics = Vec::new();
        loop {
            let next = input.parse::<T>();
            match next {
                Ok(next) => generics.push(next),
                Err(_) => {}
            }
            let punc = input.parse::<syn::Token![,]>();
            if punc.is_err() {
                break;
            }
        }
        input.parse::<syn::Token![>]>()?;
        Ok(generics)
    } else {
        Ok(Vec::new())
    }
}

//************************************************************************//

#[derive(Clone)]
pub(crate) struct DisableArg {
    pub(crate) name: Ident,
    pub(crate) refs: Vec<syn::TypePath>,
}

impl Parse for DisableArg {
    fn parse(input: ParseStream) -> Result<Self> {
        let name = input.parse::<Ident>()?;
        let content: syn::Result<_> = (|| {
            let content;
            parenthesized!(content in input);
            return Ok(content);
        })();
        let refs = if let Ok(content) = content {
            let refs = content
                .parse_terminated(
                    |input: ParseStream| input.parse::<syn::TypePath>(),
                    token::Comma,
                )
                .ok();
            if let Some(refs) = refs {
                refs.into_iter().collect()
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        };

        Ok(DisableArg {
            name,
            refs
        })
    }
}

fn extract_disabled(attributes: &mut Vec<Attribute>) -> syn::Result<Disabled> {
    let mut to_remove = Vec::new();
    let mut disabled = Disabled::default();
    for (i, e) in attributes.iter().enumerate() {
        let this_disabled = extract_disabled_helper(e)?;
        if let Some(this_disabled) = this_disabled {
            disabled.merge(this_disabled);
            to_remove.push(i);
        }
    }

    if to_remove.is_empty() {
        return Ok(disabled);
    }
    let mut index = 0;
    attributes.retain(|_| {
        let retain = !&to_remove.contains(&index);
        index += 1;
        return retain;
    });

    Ok(disabled)
}

fn extract_disabled_helper(attribute: &Attribute) -> syn::Result<Option<Disabled>> {
    return match &attribute.meta {
        syn::Meta::Path(_) => Ok(None),
        syn::Meta::NameValue(_) => Ok(None),
        syn::Meta::List(list) => {
            let ident = list.path.get_ident();
            let Some(ident) = ident else {
                return Ok(None);
            };
            let ident = ident.to_string();
            if &*ident != DISABLE_ATTRIBUTE_NAME {
                return Ok(None);
            }

            let punc = match syn::parse::Parser::parse2(
                &|input: ParseStream| Punctuated::<DisableArg, token::Comma>::parse_terminated(input),
                list.tokens.clone(),
            ) {
                Ok(okay) => okay,
                Err(_) => return Err(syn::parse::Error::new(
                    list.tokens.span(),
                    format!("Invalid syntax for `{}` attribute.", DISABLE_ATTRIBUTE_NAME),
                )),
            };
            let mut from = None;
            let mut display = false;
            let mut debug = false;
            let mut error = false;
            for DisableArg { name, refs } in punc {
                let ident = name.to_string();
                match &*ident {
                    "From" => {
                        from = Some(refs);
                    }
                    "Display" => {
                        display = true;
                        if !refs.is_empty() {
                            return Err(syn::parse::Error::new(
                                name.span(),
                                format!(
                                    "`Display` does not take any arguments for `{}` attribute.",
                                    DISABLE_ATTRIBUTE_NAME
                                ),
                            ));
                        }
                    }
                    "Debug" => {
                        debug = true;
                        if !refs.is_empty() {
                            return Err(syn::parse::Error::new(
                                name.span(),
                                format!(
                                    "`Debug` does not take any arguments for `{}` attribute.",
                                    DISABLE_ATTRIBUTE_NAME
                                ),
                            ));
                        }
                    }
                    "Error" => {
                        error = true;
                        if !refs.is_empty() {
                            return Err(syn::parse::Error::new(
                                name.span(),
                                format!(
                                    "`Error` does not take any arguments for `{}` attribute.",
                                    DISABLE_ATTRIBUTE_NAME
                                ),
                            ));
                        }
                    }
                    _ => {
                        return Err(syn::parse::Error::new(
                            ident.span(),
                            format!(
                                "`{ident}` is not a valid option for `{DISABLE_ATTRIBUTE_NAME}`"
                            ),
                        ))
                    }
                }
            }
            Ok(Some(Disabled {
                from,
                display,
                debug,
                error,
            }))
        }
    };
}

#[derive(Clone)]
pub(crate) struct Disabled {
    /// `None` == no disabling, `Some` and empty == empty disables all, `Some` and args == only disable args
    pub(crate) from: Option<Vec<syn::TypePath>>,
    pub(crate) display: bool,
    pub(crate) debug: bool,
    pub(crate) error: bool,
}

impl Disabled {
    fn merge(&mut self, other: Disabled) {
        self.from = other.from;
        self.display = other.display;
        self.debug = other.debug;
        self.error = other.error;
    }
}

impl Default for Disabled {
    fn default() -> Self {
        Disabled {
            from: None,
            display: false,
            debug: false,
            error: false,
        }
    }
}

//************************************************************************//

/// The format string to use for display
#[derive(Clone)]
pub(crate) struct DisplayAttribute {
    pub(crate) tokens: TokenStream,
}

fn extract_display_attribute(
    attributes: &mut Vec<Attribute>,
) -> syn::Result<Option<DisplayAttribute>> {
    let mut to_remove = Vec::new();
    let mut displays = Vec::new();
    for (i, e) in attributes.iter().enumerate() {
        if let Some(display_tokens) = display_tokens(e) {
            displays.push(display_tokens);
            to_remove.push(i);
        }
    }
    if to_remove.is_empty() {
        return Ok(None);
    }
    let display = displays.remove(0);
    if to_remove.len() > 1 {
        return Err(syn::parse::Error::new(
            display.tokens.span(),
            format!("More than one `{}` attribute found", DISPLAY_ATTRIBUTE_NAME),
        ));
    }

    if to_remove.is_empty() {
        return Ok(Some(display));
    }

    let mut index = 0;
    attributes.retain(|_| {
        let retain = !&to_remove.contains(&index);
        index += 1;
        return retain;
    });
    Ok(Some(display))
}

fn display_tokens(attribute: &Attribute) -> Option<DisplayAttribute> {
    return match &attribute.meta {
        syn::Meta::Path(_) => None,
        syn::Meta::NameValue(_) => None,
        syn::Meta::List(list) => {
            let ident = list.path.get_ident();
            let Some(ident) = ident else {
                return None;
            };
            let ident = ident.to_string();
            if &*ident == DISPLAY_ATTRIBUTE_NAME {
                return Some(DisplayAttribute {
                    tokens: list.tokens.clone(),
                });
            }
            return None;
        }
    };
}

#[derive(Clone, PartialEq)]
pub(crate) struct AstInlineErrorVariantField {
    pub(crate) name: Ident,
    pub(crate) r#type: syn::Type,
}

impl Parse for AstInlineErrorVariantField {
    fn parse(input: ParseStream) -> Result<Self> {
        let name: Ident = input.parse()?;
        let _: syn::Token![:] = input.parse()?;
        let r#type: syn::Type = input.parse()?;
        Ok(AstInlineErrorVariantField { name, r#type })
    }
}

impl Eq for AstInlineErrorVariantField {}