summaryrefslogtreecommitdiff
path: root/src/diagnostic.rs
blob: 0173d2a88f02e1fcb5e5c07414773ba0e2a97589 (plain)
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
use proc_macro2::TokenStream;
use quote::quote;
use syn::{punctuated::Punctuated, DeriveInput, Token};

use crate::code::Code;
use crate::diagnostic_arg::DiagnosticArg;
use crate::diagnostic_source::DiagnosticSource;
use crate::forward::{Forward, WhichFn};
use crate::help::Help;
use crate::label::Labels;
use crate::related::Related;
use crate::severity::Severity;
use crate::source_code::SourceCode;
use crate::url::Url;

pub enum Diagnostic {
    Struct {
        generics: syn::Generics,
        ident: syn::Ident,
        fields: syn::Fields,
        args: DiagnosticDefArgs,
    },
    Enum {
        ident: syn::Ident,
        generics: syn::Generics,
        variants: Vec<DiagnosticDef>,
    },
}

pub struct DiagnosticDef {
    pub ident: syn::Ident,
    pub fields: syn::Fields,
    pub args: DiagnosticDefArgs,
}

pub enum DiagnosticDefArgs {
    Transparent(Forward),
    Concrete(Box<DiagnosticConcreteArgs>),
}

impl DiagnosticDefArgs {
    pub(crate) fn forward_or_override_enum(
        &self,
        variant: &syn::Ident,
        which_fn: WhichFn,
        mut f: impl FnMut(&DiagnosticConcreteArgs) -> Option<TokenStream>,
    ) -> Option<TokenStream> {
        match self {
            Self::Transparent(forward) => Some(forward.gen_enum_match_arm(variant, which_fn)),
            Self::Concrete(concrete) => f(concrete).or_else(|| {
                concrete
                    .forward
                    .as_ref()
                    .map(|forward| forward.gen_enum_match_arm(variant, which_fn))
            }),
        }
    }
}

#[derive(Default)]
pub struct DiagnosticConcreteArgs {
    pub code: Option<Code>,
    pub severity: Option<Severity>,
    pub help: Option<Help>,
    pub labels: Option<Labels>,
    pub source_code: Option<SourceCode>,
    pub url: Option<Url>,
    pub forward: Option<Forward>,
    pub related: Option<Related>,
    pub diagnostic_source: Option<DiagnosticSource>,
}

impl DiagnosticConcreteArgs {
    fn for_fields(fields: &syn::Fields) -> Result<Self, syn::Error> {
        let labels = Labels::from_fields(fields)?;
        let source_code = SourceCode::from_fields(fields)?;
        let related = Related::from_fields(fields)?;
        let help = Help::from_fields(fields)?;
        let diagnostic_source = DiagnosticSource::from_fields(fields)?;
        Ok(DiagnosticConcreteArgs {
            code: None,
            help,
            related,
            severity: None,
            labels,
            url: None,
            forward: None,
            source_code,
            diagnostic_source,
        })
    }

    fn add_args(
        &mut self,
        attr: &syn::Attribute,
        args: impl Iterator<Item = DiagnosticArg>,
        errors: &mut Vec<syn::Error>,
    ) {
        for arg in args {
            match arg {
                DiagnosticArg::Transparent => {
                    errors.push(syn::Error::new_spanned(attr, "transparent not allowed"));
                }
                DiagnosticArg::Forward(to_field) => {
                    if self.forward.is_some() {
                        errors.push(syn::Error::new_spanned(
                            attr,
                            "forward has already been specified",
                        ));
                    }
                    self.forward = Some(to_field);
                }
                DiagnosticArg::Code(new_code) => {
                    if self.code.is_some() {
                        errors.push(syn::Error::new_spanned(
                            attr,
                            "code has already been specified",
                        ));
                    }
                    self.code = Some(new_code);
                }
                DiagnosticArg::Severity(sev) => {
                    if self.severity.is_some() {
                        errors.push(syn::Error::new_spanned(
                            attr,
                            "severity has already been specified",
                        ));
                    }
                    self.severity = Some(sev);
                }
                DiagnosticArg::Help(hl) => {
                    if self.help.is_some() {
                        errors.push(syn::Error::new_spanned(
                            attr,
                            "help has already been specified",
                        ));
                    }
                    self.help = Some(hl);
                }
                DiagnosticArg::Url(u) => {
                    if self.url.is_some() {
                        errors.push(syn::Error::new_spanned(
                            attr,
                            "url has already been specified",
                        ));
                    }
                    self.url = Some(u);
                }
            }
        }
    }
}

impl DiagnosticDefArgs {
    fn parse(
        _ident: &syn::Ident,
        fields: &syn::Fields,
        attrs: &[&syn::Attribute],
        allow_transparent: bool,
    ) -> syn::Result<Self> {
        let mut errors = Vec::new();

        // Handle the only condition where Transparent is allowed
        if allow_transparent && attrs.len() == 1 {
            if let Ok(args) =
                attrs[0].parse_args_with(Punctuated::<DiagnosticArg, Token![,]>::parse_terminated)
            {
                if matches!(args.first(), Some(DiagnosticArg::Transparent)) {
                    let forward = Forward::for_transparent_field(fields)?;
                    return Ok(Self::Transparent(forward));
                }
            }
        }

        // Create errors for any appearances of Transparent
        let error_message = if allow_transparent {
            "diagnostic(transparent) not allowed in combination with other args"
        } else {
            "diagnostic(transparent) not allowed here"
        };
        fn is_transparent(d: &DiagnosticArg) -> bool {
            matches!(d, DiagnosticArg::Transparent)
        }

        let mut concrete = DiagnosticConcreteArgs::for_fields(fields)?;
        for attr in attrs {
            let args =
                attr.parse_args_with(Punctuated::<DiagnosticArg, Token![,]>::parse_terminated);
            let args = match args {
                Ok(args) => args,
                Err(error) => {
                    errors.push(error);
                    continue;
                }
            };

            if args.iter().any(is_transparent) {
                errors.push(syn::Error::new_spanned(attr, error_message));
            }

            let args = args
                .into_iter()
                .filter(|x| !matches!(x, DiagnosticArg::Transparent));

            concrete.add_args(attr, args, &mut errors);
        }

        let combined_error = errors.into_iter().reduce(|mut lhs, rhs| {
            lhs.combine(rhs);
            lhs
        });
        if let Some(error) = combined_error {
            Err(error)
        } else {
            Ok(DiagnosticDefArgs::Concrete(Box::new(concrete)))
        }
    }
}

impl Diagnostic {
    pub fn from_derive_input(input: DeriveInput) -> Result<Self, syn::Error> {
        let input_attrs = input
            .attrs
            .iter()
            .filter(|x| x.path().is_ident("diagnostic"))
            .collect::<Vec<&syn::Attribute>>();
        Ok(match input.data {
            syn::Data::Struct(data_struct) => {
                let args = DiagnosticDefArgs::parse(
                    &input.ident,
                    &data_struct.fields,
                    &input_attrs,
                    true,
                )?;

                Diagnostic::Struct {
                    fields: data_struct.fields,
                    ident: input.ident,
                    generics: input.generics,
                    args,
                }
            }
            syn::Data::Enum(syn::DataEnum { variants, .. }) => {
                let mut vars = Vec::new();
                for var in variants {
                    let mut variant_attrs = input_attrs.clone();
                    variant_attrs
                        .extend(var.attrs.iter().filter(|x| x.path().is_ident("diagnostic")));
                    let args =
                        DiagnosticDefArgs::parse(&var.ident, &var.fields, &variant_attrs, true)?;
                    vars.push(DiagnosticDef {
                        ident: var.ident,
                        fields: var.fields,
                        args,
                    });
                }
                Diagnostic::Enum {
                    ident: input.ident,
                    generics: input.generics,
                    variants: vars,
                }
            }
            syn::Data::Union(_) => {
                return Err(syn::Error::new(
                    input.ident.span(),
                    "Can't derive Diagnostic for Unions",
                ))
            }
        })
    }

    pub fn gen(&self) -> TokenStream {
        match self {
            Self::Struct {
                ident,
                fields,
                generics,
                args,
            } => {
                let (impl_generics, ty_generics, where_clause) = &generics.split_for_impl();
                match args {
                    DiagnosticDefArgs::Transparent(forward) => {
                        let code_method = forward.gen_struct_method(WhichFn::Code);
                        let help_method = forward.gen_struct_method(WhichFn::Help);
                        let url_method = forward.gen_struct_method(WhichFn::Url);
                        let labels_method = forward.gen_struct_method(WhichFn::Labels);
                        let source_code_method = forward.gen_struct_method(WhichFn::SourceCode);
                        let severity_method = forward.gen_struct_method(WhichFn::Severity);
                        let related_method = forward.gen_struct_method(WhichFn::Related);
                        let diagnostic_source_method =
                            forward.gen_struct_method(WhichFn::DiagnosticSource);

                        quote! {
                            impl #impl_generics miette::Diagnostic for #ident #ty_generics #where_clause {
                                #code_method
                                #help_method
                                #url_method
                                #labels_method
                                #severity_method
                                #source_code_method
                                #related_method
                                #diagnostic_source_method
                            }
                        }
                    }
                    DiagnosticDefArgs::Concrete(concrete) => {
                        let forward = |which| {
                            concrete
                                .forward
                                .as_ref()
                                .map(|fwd| fwd.gen_struct_method(which))
                        };
                        let code_body = concrete
                            .code
                            .as_ref()
                            .and_then(|x| x.gen_struct())
                            .or_else(|| forward(WhichFn::Code));
                        let help_body = concrete
                            .help
                            .as_ref()
                            .and_then(|x| x.gen_struct(fields))
                            .or_else(|| forward(WhichFn::Help));
                        let sev_body = concrete
                            .severity
                            .as_ref()
                            .and_then(|x| x.gen_struct())
                            .or_else(|| forward(WhichFn::Severity));
                        let rel_body = concrete
                            .related
                            .as_ref()
                            .and_then(|x| x.gen_struct())
                            .or_else(|| forward(WhichFn::Related));
                        let url_body = concrete
                            .url
                            .as_ref()
                            .and_then(|x| x.gen_struct(ident, fields))
                            .or_else(|| forward(WhichFn::Url));
                        let labels_body = concrete
                            .labels
                            .as_ref()
                            .and_then(|x| x.gen_struct(fields))
                            .or_else(|| forward(WhichFn::Labels));
                        let src_body = concrete
                            .source_code
                            .as_ref()
                            .and_then(|x| x.gen_struct(fields))
                            .or_else(|| forward(WhichFn::SourceCode));
                        let diagnostic_source = concrete
                            .diagnostic_source
                            .as_ref()
                            .and_then(|x| x.gen_struct())
                            .or_else(|| forward(WhichFn::DiagnosticSource));
                        quote! {
                            impl #impl_generics miette::Diagnostic for #ident #ty_generics #where_clause {
                                #code_body
                                #help_body
                                #sev_body
                                #rel_body
                                #url_body
                                #labels_body
                                #src_body
                                #diagnostic_source
                            }
                        }
                    }
                }
            }
            Self::Enum {
                ident,
                generics,
                variants,
            } => {
                let (impl_generics, ty_generics, where_clause) = &generics.split_for_impl();
                let code_body = Code::gen_enum(variants);
                let help_body = Help::gen_enum(variants);
                let sev_body = Severity::gen_enum(variants);
                let labels_body = Labels::gen_enum(variants);
                let src_body = SourceCode::gen_enum(variants);
                let rel_body = Related::gen_enum(variants);
                let url_body = Url::gen_enum(ident, variants);
                let diagnostic_source_body = DiagnosticSource::gen_enum(variants);
                quote! {
                    impl #impl_generics miette::Diagnostic for #ident #ty_generics #where_clause {
                        #code_body
                        #help_body
                        #sev_body
                        #labels_body
                        #src_body
                        #rel_body
                        #url_body
                        #diagnostic_source_body
                    }
                }
            }
        }
    }
}