1use proc_macro::TokenStream;
7use quote::quote;
8use syn::{
9 Attribute, Data, DataEnum, DataStruct, DeriveInput, Fields, Ident, LitStr, Result,
10 parse_macro_input,
11};
12
13#[proc_macro_derive(Diagnostic, attributes(diag))]
14pub fn derive_diagnostic(input: TokenStream) -> TokenStream {
15 let input = parse_macro_input!(input as DeriveInput);
16
17 match expand_diagnostic(&input) {
18 Ok(tokens) => tokens.into(),
19 Err(error) => error.to_compile_error().into(),
20 }
21}
22
23#[derive(Clone, Default)]
24struct TypeOptions {
25 code: Option<LitStr>,
26 help: Option<LitStr>,
27 notes: Vec<LitStr>,
28 severity: Option<SeverityValue>,
29 suggestions: Vec<SuggestionOptions>,
30}
31
32#[derive(Clone, Default)]
33struct SuggestionOptions {
34 title: Option<LitStr>,
35 explanation: Option<LitStr>,
36 applicability: Option<ApplicabilityValue>,
37}
38
39#[derive(Clone, Copy)]
40enum SeverityValue {
41 Trace,
42 Debug,
43 Info,
44 Warning,
45 Error,
46 Fatal,
47}
48
49#[derive(Clone, Copy, PartialEq, Eq)]
50enum ApplicabilityValue {
51 Manual,
52 MaybeIncorrect,
53 HasPlaceholders,
54 MachineApplicable,
55}
56
57#[derive(Clone, Copy)]
58enum LabelKindValue {
59 Primary,
60 Secondary,
61}
62
63struct LabelField {
64 field: Ident,
65 kind: LabelKindValue,
66 message: Option<LitStr>,
67 length_field: Option<Ident>,
68}
69
70fn expand_diagnostic(input: &DeriveInput) -> Result<proc_macro2::TokenStream> {
71 let options = parse_options(&input.attrs)?;
72
73 match &input.data {
74 Data::Struct(data) => expand_struct(input, data, &options),
75
76 Data::Enum(data) => expand_enum(input, data, &options),
77
78 Data::Union(_) => Err(syn::Error::new_spanned(
79 input,
80 "diagprint::Diagnostic does not support unions",
81 )),
82 }
83}
84
85fn expand_struct(
86 input: &DeriveInput,
87 data: &DataStruct,
88 options: &TypeOptions,
89) -> Result<proc_macro2::TokenStream> {
90 let fields = match &data.fields {
91 Fields::Named(fields) => &fields.named,
92
93 _ => {
94 return Err(syn::Error::new_spanned(
95 input,
96 "diagprint::Diagnostic structs currently require named fields",
97 ));
98 }
99 };
100
101 let mut labels = Vec::new();
102
103 for field in fields {
104 let Some(field_ident) = field.ident.clone() else {
105 continue;
106 };
107
108 if let Some(label) = parse_label_field(field, field_ident)? {
109 labels.push(label);
110 }
111 }
112
113 let name = &input.ident;
114 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
115
116 let severity = severity_tokens(options.severity.unwrap_or(SeverityValue::Error));
117
118 let code = optional_string_tokens(&options.code);
119 let help = optional_string_tokens(&options.help);
120 let notes = notes_tokens(&options.notes);
121 let suggestions = suggestions_tokens(&options.suggestions)?;
122
123 let labels = labels.iter().map(struct_label_tokens).collect::<Vec<_>>();
124
125 Ok(quote! {
126 impl #impl_generics ::diagprint::DiagnosticMetadata
127 for #name #ty_generics #where_clause
128 {
129 fn diagnostic_severity(
130 &self,
131 ) -> ::diagprint::Severity {
132 #severity
133 }
134
135 fn diagnostic_code(
136 &self,
137 ) -> Option<String> {
138 #code
139 }
140
141 fn diagnostic_help(
142 &self,
143 ) -> Option<String> {
144 #help
145 }
146
147 fn diagnostic_notes(
148 &self,
149 ) -> Vec<String> {
150 #notes
151 }
152
153 fn diagnostic_labels(
154 &self,
155 ) -> Vec<::diagprint::Label> {
156 vec![#(#labels),*]
157 }
158
159 fn diagnostic_suggestions(
160 &self,
161 ) -> Vec<::diagprint::Suggestion> {
162 #suggestions
163 }
164 }
165 })
166}
167
168fn expand_enum(
169 input: &DeriveInput,
170 data: &DataEnum,
171 base_options: &TypeOptions,
172) -> Result<proc_macro2::TokenStream> {
173 let name = &input.ident;
174 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
175
176 let mut severity_arms = Vec::new();
177 let mut code_arms = Vec::new();
178 let mut help_arms = Vec::new();
179 let mut notes_arms = Vec::new();
180 let mut label_arms = Vec::new();
181 let mut suggestion_arms = Vec::new();
182
183 for variant in &data.variants {
184 let variant_ident = &variant.ident;
185 let variant_options = parse_options(&variant.attrs)?;
186
187 let options = merge_options(base_options, &variant_options);
188
189 let generic_pattern = match &variant.fields {
190 Fields::Unit => {
191 quote!(Self::#variant_ident)
192 }
193
194 Fields::Named(_) => {
195 quote!(Self::#variant_ident { .. })
196 }
197
198 Fields::Unnamed(_) => {
199 return Err(syn::Error::new_spanned(
200 variant,
201 "diagprint::Diagnostic enum variants currently support unit or named-field variants",
202 ));
203 }
204 };
205
206 let severity = severity_tokens(options.severity.unwrap_or(SeverityValue::Error));
207
208 let code = optional_string_tokens(&options.code);
209
210 let help = optional_string_tokens(&options.help);
211
212 let notes = notes_tokens(&options.notes);
213
214 let suggestions = suggestions_tokens(&options.suggestions)?;
215
216 severity_arms.push(quote! {
217 #generic_pattern => #severity,
218 });
219
220 code_arms.push(quote! {
221 #generic_pattern => #code,
222 });
223
224 help_arms.push(quote! {
225 #generic_pattern => #help,
226 });
227
228 notes_arms.push(quote! {
229 #generic_pattern => #notes,
230 });
231
232 suggestion_arms.push(quote! {
233 #generic_pattern => #suggestions,
234 });
235
236 match &variant.fields {
237 Fields::Unit => {
238 label_arms.push(quote! {
239 Self::#variant_ident => Vec::new(),
240 });
241 }
242
243 Fields::Named(fields) => {
244 let mut labels = Vec::new();
245
246 for field in &fields.named {
247 let Some(field_ident) = field.ident.clone() else {
248 continue;
249 };
250
251 if let Some(label) = parse_label_field(field, field_ident)? {
252 labels.push(label);
253 }
254 }
255
256 if labels.is_empty() {
257 label_arms.push(quote! {
258 Self::#variant_ident { .. } => {
259 Vec::new()
260 },
261 });
262
263 continue;
264 }
265
266 let bindings = label_bindings(&labels);
267
268 let label_values = labels.iter().map(enum_label_tokens).collect::<Vec<_>>();
269
270 label_arms.push(quote! {
271 Self::#variant_ident {
272 #(#bindings),*,
273 ..
274 } => {
275 vec![#(#label_values),*]
276 },
277 });
278 }
279
280 Fields::Unnamed(_) => unreachable!(),
281 }
282 }
283
284 Ok(quote! {
285 impl #impl_generics ::diagprint::DiagnosticMetadata
286 for #name #ty_generics #where_clause
287 {
288 fn diagnostic_severity(
289 &self,
290 ) -> ::diagprint::Severity {
291 match self {
292 #(#severity_arms)*
293 }
294 }
295
296 fn diagnostic_code(
297 &self,
298 ) -> Option<String> {
299 match self {
300 #(#code_arms)*
301 }
302 }
303
304 fn diagnostic_help(
305 &self,
306 ) -> Option<String> {
307 match self {
308 #(#help_arms)*
309 }
310 }
311
312 fn diagnostic_notes(
313 &self,
314 ) -> Vec<String> {
315 match self {
316 #(#notes_arms)*
317 }
318 }
319
320 fn diagnostic_labels(
321 &self,
322 ) -> Vec<::diagprint::Label> {
323 match self {
324 #(#label_arms)*
325 }
326 }
327
328 fn diagnostic_suggestions(
329 &self,
330 ) -> Vec<::diagprint::Suggestion> {
331 match self {
332 #(#suggestion_arms)*
333 }
334 }
335 }
336 })
337}
338
339fn parse_options(attrs: &[Attribute]) -> Result<TypeOptions> {
340 let mut options = TypeOptions::default();
341
342 for attr in attrs {
343 if !attr.path().is_ident("diag") {
344 continue;
345 }
346
347 attr.parse_nested_meta(|meta| {
348 if meta.path.is_ident("code") {
349 if options.code.is_some() {
350 return Err(meta.error("duplicate diag code"));
351 }
352
353 options.code = Some(meta.value()?.parse()?);
354
355 return Ok(());
356 }
357
358 if meta.path.is_ident("help") {
359 if options.help.is_some() {
360 return Err(meta.error("duplicate diag help"));
361 }
362
363 options.help = Some(meta.value()?.parse()?);
364
365 return Ok(());
366 }
367
368 if meta.path.is_ident("note") {
369 options.notes.push(meta.value()?.parse()?);
370
371 return Ok(());
372 }
373
374 if meta.path.is_ident("severity") {
375 if options.severity.is_some() {
376 return Err(meta.error("duplicate diag severity"));
377 }
378
379 let severity: Ident = meta.value()?.parse()?;
380
381 options.severity = Some(parse_severity(&severity)?);
382
383 return Ok(());
384 }
385
386 if meta.path.is_ident("suggestion") {
387 let suggestion = parse_suggestion(meta)?;
388
389 options.suggestions.push(suggestion);
390
391 return Ok(());
392 }
393
394 Err(meta.error("unsupported #[diag(...)] option"))
395 })?;
396 }
397
398 Ok(options)
399}
400
401fn parse_suggestion(meta: syn::meta::ParseNestedMeta<'_>) -> Result<SuggestionOptions> {
402 let mut suggestion = SuggestionOptions::default();
403
404 meta.parse_nested_meta(|nested| {
405 if nested.path.is_ident("title") {
406 if suggestion.title.is_some() {
407 return Err(nested.error("duplicate suggestion title"));
408 }
409
410 suggestion.title = Some(nested.value()?.parse()?);
411
412 return Ok(());
413 }
414
415 if nested.path.is_ident("explanation") {
416 if suggestion.explanation.is_some() {
417 return Err(nested.error("duplicate suggestion explanation"));
418 }
419
420 suggestion.explanation = Some(nested.value()?.parse()?);
421
422 return Ok(());
423 }
424
425 if nested.path.is_ident("applicability") {
426 if suggestion.applicability.is_some() {
427 return Err(nested.error("duplicate suggestion applicability"));
428 }
429
430 let applicability: Ident = nested.value()?.parse()?;
431
432 suggestion.applicability = Some(parse_applicability(&applicability)?);
433
434 return Ok(());
435 }
436
437 Err(nested.error("unsupported suggestion option"))
438 })?;
439
440 if suggestion.title.is_none() {
441 return Err(meta.error("suggestion requires title = \"...\""));
442 }
443
444 if suggestion.applicability == Some(ApplicabilityValue::MachineApplicable) {
445 return Err(meta.error(
446 "machine_applicable suggestions require guarded edits; derive-generated edits are not supported yet",
447 ));
448 }
449
450 Ok(suggestion)
451}
452
453fn merge_options(base: &TypeOptions, variant: &TypeOptions) -> TypeOptions {
454 let mut notes = base.notes.clone();
455 notes.extend(variant.notes.iter().cloned());
456
457 let mut suggestions = base.suggestions.clone();
458 suggestions.extend(variant.suggestions.iter().cloned());
459
460 TypeOptions {
461 code: variant.code.clone().or_else(|| base.code.clone()),
462
463 help: variant.help.clone().or_else(|| base.help.clone()),
464
465 notes,
466
467 severity: variant.severity.or(base.severity),
468
469 suggestions,
470 }
471}
472
473fn parse_label_field(field: &syn::Field, field_ident: Ident) -> Result<Option<LabelField>> {
474 let mut kind = None;
475 let mut message = None;
476 let mut length_field = None;
477
478 for attr in &field.attrs {
479 if !attr.path().is_ident("diag") {
480 continue;
481 }
482
483 attr.parse_nested_meta(|meta| {
484 if meta.path.is_ident("primary") {
485 set_label_kind(&mut kind, LabelKindValue::Primary, &meta)?;
486
487 return Ok(());
488 }
489
490 if meta.path.is_ident("secondary") {
491 set_label_kind(&mut kind, LabelKindValue::Secondary, &meta)?;
492
493 return Ok(());
494 }
495
496 if meta.path.is_ident("message") {
497 if message.is_some() {
498 return Err(meta.error("duplicate label message"));
499 }
500
501 message = Some(meta.value()?.parse()?);
502
503 return Ok(());
504 }
505
506 if meta.path.is_ident("length") {
507 if length_field.is_some() {
508 return Err(meta.error("duplicate label length"));
509 }
510
511 length_field = Some(meta.value()?.parse()?);
512
513 return Ok(());
514 }
515
516 Err(meta.error("unsupported #[diag(...)] field option"))
517 })?;
518 }
519
520 let Some(kind) = kind else {
521 return Ok(None);
522 };
523
524 Ok(Some(LabelField {
525 field: field_ident,
526 kind,
527 message,
528 length_field,
529 }))
530}
531
532fn label_bindings(labels: &[LabelField]) -> Vec<Ident> {
533 let mut bindings = Vec::new();
534 let mut names = Vec::new();
535
536 for label in labels {
537 push_binding(&mut bindings, &mut names, &label.field);
538
539 if let Some(length_field) = &label.length_field {
540 push_binding(&mut bindings, &mut names, length_field);
541 }
542 }
543
544 bindings
545}
546
547fn push_binding(bindings: &mut Vec<Ident>, names: &mut Vec<String>, ident: &Ident) {
548 let name = ident.to_string();
549
550 if !names.contains(&name) {
551 names.push(name);
552 bindings.push(ident.clone());
553 }
554}
555
556fn set_label_kind(
557 current: &mut Option<LabelKindValue>,
558 value: LabelKindValue,
559 meta: &syn::meta::ParseNestedMeta<'_>,
560) -> Result<()> {
561 if current.is_some() {
562 return Err(meta.error("a label cannot be both primary and secondary"));
563 }
564
565 *current = Some(value);
566
567 Ok(())
568}
569
570fn parse_severity(ident: &Ident) -> Result<SeverityValue> {
571 match ident.to_string().to_ascii_lowercase().as_str() {
572 "trace" => Ok(SeverityValue::Trace),
573 "debug" => Ok(SeverityValue::Debug),
574 "info" => Ok(SeverityValue::Info),
575
576 "warning" | "warn" => Ok(SeverityValue::Warning),
577
578 "error" => Ok(SeverityValue::Error),
579 "fatal" => Ok(SeverityValue::Fatal),
580
581 _ => Err(syn::Error::new_spanned(
582 ident,
583 "severity must be trace, debug, info, warning, error, or fatal",
584 )),
585 }
586}
587
588fn parse_applicability(ident: &Ident) -> Result<ApplicabilityValue> {
589 match ident.to_string().to_ascii_lowercase().as_str() {
590 "manual" => Ok(ApplicabilityValue::Manual),
591
592 "maybe_incorrect" => Ok(ApplicabilityValue::MaybeIncorrect),
593
594 "has_placeholders" => Ok(ApplicabilityValue::HasPlaceholders),
595
596 "machine_applicable" => Ok(ApplicabilityValue::MachineApplicable),
597
598 _ => Err(syn::Error::new_spanned(
599 ident,
600 "applicability must be manual, maybe_incorrect, has_placeholders, or machine_applicable",
601 )),
602 }
603}
604
605fn severity_tokens(severity: SeverityValue) -> proc_macro2::TokenStream {
606 match severity {
607 SeverityValue::Trace => {
608 quote!(::diagprint::Severity::Trace)
609 }
610
611 SeverityValue::Debug => {
612 quote!(::diagprint::Severity::Debug)
613 }
614
615 SeverityValue::Info => {
616 quote!(::diagprint::Severity::Info)
617 }
618
619 SeverityValue::Warning => {
620 quote!(::diagprint::Severity::Warning)
621 }
622
623 SeverityValue::Error => {
624 quote!(::diagprint::Severity::Error)
625 }
626
627 SeverityValue::Fatal => {
628 quote!(::diagprint::Severity::Fatal)
629 }
630 }
631}
632
633fn applicability_tokens(applicability: ApplicabilityValue) -> proc_macro2::TokenStream {
634 match applicability {
635 ApplicabilityValue::Manual => {
636 quote!(::diagprint::Applicability::Manual)
637 }
638
639 ApplicabilityValue::MaybeIncorrect => {
640 quote!(::diagprint::Applicability::MaybeIncorrect)
641 }
642
643 ApplicabilityValue::HasPlaceholders => {
644 quote!(::diagprint::Applicability::HasPlaceholders)
645 }
646
647 ApplicabilityValue::MachineApplicable => {
648 quote!(::diagprint::Applicability::MachineApplicable)
649 }
650 }
651}
652
653fn optional_string_tokens(value: &Option<LitStr>) -> proc_macro2::TokenStream {
654 match value {
655 Some(value) => quote! {
656 Some(#value.to_owned())
657 },
658
659 None => quote! {
660 None
661 },
662 }
663}
664
665fn notes_tokens(notes: &[LitStr]) -> proc_macro2::TokenStream {
666 quote! {
667 vec![#(#notes.to_owned()),*]
668 }
669}
670
671fn suggestions_tokens(suggestions: &[SuggestionOptions]) -> Result<proc_macro2::TokenStream> {
672 let values = suggestions
673 .iter()
674 .map(suggestion_tokens)
675 .collect::<Result<Vec<_>>>()?;
676
677 Ok(quote! {
678 vec![#(#values),*]
679 })
680}
681
682fn suggestion_tokens(suggestion: &SuggestionOptions) -> Result<proc_macro2::TokenStream> {
683 let title = suggestion.title.as_ref().ok_or_else(|| {
684 syn::Error::new(
685 proc_macro2::Span::call_site(),
686 "suggestion title is required",
687 )
688 })?;
689
690 let applicability = applicability_tokens(
691 suggestion
692 .applicability
693 .unwrap_or(ApplicabilityValue::Manual),
694 );
695
696 let mut expression = quote! {
697 ::diagprint::Suggestion::new(#title)
698 .applicability(#applicability)
699 };
700
701 if let Some(explanation) = &suggestion.explanation {
702 expression = quote! {
703 #expression.explanation(#explanation)
704 };
705 }
706
707 Ok(expression)
708}
709
710fn struct_label_tokens(label: &LabelField) -> proc_macro2::TokenStream {
711 let field = &label.field;
712
713 let kind = label_kind_tokens(label.kind);
714
715 let message = optional_string_tokens(&label.message);
716
717 let length = match &label.length_field {
718 Some(length_field) => quote! {
719 Some(self.#length_field)
720 },
721
722 None => quote! {
723 None
724 },
725 };
726
727 quote! {
728 ::diagprint::Label {
729 kind: #kind,
730 location: self.#field.clone(),
731 length: #length,
732 message: #message,
733 }
734 }
735}
736
737fn enum_label_tokens(label: &LabelField) -> proc_macro2::TokenStream {
738 let field = &label.field;
739
740 let kind = label_kind_tokens(label.kind);
741
742 let message = optional_string_tokens(&label.message);
743
744 let length = match &label.length_field {
745 Some(length_field) => quote! {
746 Some(*#length_field)
747 },
748
749 None => quote! {
750 None
751 },
752 };
753
754 quote! {
755 ::diagprint::Label {
756 kind: #kind,
757 location: (*#field).clone(),
758 length: #length,
759 message: #message,
760 }
761 }
762}
763
764fn label_kind_tokens(kind: LabelKindValue) -> proc_macro2::TokenStream {
765 match kind {
766 LabelKindValue::Primary => {
767 quote!(::diagprint::LabelKind::Primary)
768 }
769
770 LabelKindValue::Secondary => {
771 quote!(::diagprint::LabelKind::Secondary)
772 }
773 }
774}
775
776#[cfg(test)]
777mod tests {
778 use super::*;
779 use syn::parse_quote;
780
781 #[test]
782 fn machine_applicable_without_edit_is_rejected() {
783 let input: DeriveInput = parse_quote! {
784 #[diag(
785 suggestion(
786 title = "apply fix",
787 applicability = machine_applicable
788 )
789 )]
790 struct Example {
791 location: String,
792 }
793 };
794
795 let Err(error) = expand_diagnostic(&input) else {
796 panic!("machine-applicable suggestion without guarded edits was unexpectedly accepted");
797 };
798
799 assert!(error.to_string().contains("require guarded edits"));
800 }
801
802 #[test]
803 fn tuple_enum_variants_are_rejected() {
804 let input: DeriveInput = parse_quote! {
805 enum Example {
806 Unsupported(String),
807 }
808 };
809
810 let Err(error) = expand_diagnostic(&input) else {
811 panic!("tuple enum variant was unexpectedly accepted");
812 };
813
814 assert!(error.to_string().contains("unit or named-field"));
815 }
816}