]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_macros/src/diagnostics/subdiagnostic.rs
Rollup merge of #106973 - oli-obk:tait_ice_closure_in_impl_header, r=lcnr
[rust.git] / compiler / rustc_macros / src / diagnostics / subdiagnostic.rs
1 #![deny(unused_must_use)]
2
3 use crate::diagnostics::error::{
4     invalid_attr, span_err, throw_invalid_attr, throw_invalid_nested_attr, throw_span_err,
5     DiagnosticDeriveError,
6 };
7 use crate::diagnostics::utils::{
8     build_field_mapping, is_doc_comment, new_code_ident,
9     report_error_if_not_applied_to_applicability, report_error_if_not_applied_to_span, FieldInfo,
10     FieldInnerTy, FieldMap, HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind,
11 };
12 use proc_macro2::TokenStream;
13 use quote::{format_ident, quote};
14 use syn::{spanned::Spanned, Attribute, Meta, MetaList, NestedMeta, Path};
15 use synstructure::{BindingInfo, Structure, VariantInfo};
16
17 use super::utils::{build_suggestion_code, AllowMultipleAlternatives};
18
19 /// The central struct for constructing the `add_to_diagnostic` method from an annotated struct.
20 pub(crate) struct SubdiagnosticDeriveBuilder {
21     diag: syn::Ident,
22     f: syn::Ident,
23 }
24
25 impl SubdiagnosticDeriveBuilder {
26     pub(crate) fn new() -> Self {
27         let diag = format_ident!("diag");
28         let f = format_ident!("f");
29         Self { diag, f }
30     }
31
32     pub(crate) fn into_tokens(self, mut structure: Structure<'_>) -> TokenStream {
33         let implementation = {
34             let ast = structure.ast();
35             let span = ast.span().unwrap();
36             match ast.data {
37                 syn::Data::Struct(..) | syn::Data::Enum(..) => (),
38                 syn::Data::Union(..) => {
39                     span_err(
40                         span,
41                         "`#[derive(Subdiagnostic)]` can only be used on structs and enums",
42                     );
43                 }
44             }
45
46             let is_enum = matches!(ast.data, syn::Data::Enum(..));
47             if is_enum {
48                 for attr in &ast.attrs {
49                     // Always allow documentation comments.
50                     if is_doc_comment(attr) {
51                         continue;
52                     }
53
54                     span_err(
55                         attr.span().unwrap(),
56                         "unsupported type attribute for subdiagnostic enum",
57                     )
58                     .emit();
59                 }
60             }
61
62             structure.bind_with(|_| synstructure::BindStyle::Move);
63             let variants_ = structure.each_variant(|variant| {
64                 let mut builder = SubdiagnosticDeriveVariantBuilder {
65                     parent: &self,
66                     variant,
67                     span,
68                     formatting_init: TokenStream::new(),
69                     fields: build_field_mapping(variant),
70                     span_field: None,
71                     applicability: None,
72                     has_suggestion_parts: false,
73                     is_enum,
74                 };
75                 builder.into_tokens().unwrap_or_else(|v| v.to_compile_error())
76             });
77
78             quote! {
79                 match self {
80                     #variants_
81                 }
82             }
83         };
84
85         let diag = &self.diag;
86         let f = &self.f;
87         let ret = structure.gen_impl(quote! {
88             gen impl rustc_errors::AddToDiagnostic for @Self {
89                 fn add_to_diagnostic_with<__F>(self, #diag: &mut rustc_errors::Diagnostic, #f: __F)
90                 where
91                     __F: core::ops::Fn(
92                         &mut rustc_errors::Diagnostic,
93                         rustc_errors::SubdiagnosticMessage
94                     ) -> rustc_errors::SubdiagnosticMessage,
95                 {
96                     use rustc_errors::{Applicability, IntoDiagnosticArg};
97                     #implementation
98                 }
99             }
100         });
101         ret
102     }
103 }
104
105 /// Tracks persistent information required for building up the call to add to the diagnostic
106 /// for the final generated method. This is a separate struct to `SubdiagnosticDerive`
107 /// only to be able to destructure and split `self.builder` and the `self.structure` up to avoid a
108 /// double mut borrow later on.
109 struct SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
110     /// The identifier to use for the generated `DiagnosticBuilder` instance.
111     parent: &'parent SubdiagnosticDeriveBuilder,
112
113     /// Info for the current variant (or the type if not an enum).
114     variant: &'a VariantInfo<'a>,
115     /// Span for the entire type.
116     span: proc_macro::Span,
117
118     /// Initialization of format strings for code suggestions.
119     formatting_init: TokenStream,
120
121     /// Store a map of field name to its corresponding field. This is built on construction of the
122     /// derive builder.
123     fields: FieldMap,
124
125     /// Identifier for the binding to the `#[primary_span]` field.
126     span_field: SpannedOption<proc_macro2::Ident>,
127
128     /// The binding to the `#[applicability]` field, if present.
129     applicability: SpannedOption<TokenStream>,
130
131     /// Set to true when a `#[suggestion_part]` field is encountered, used to generate an error
132     /// during finalization if still `false`.
133     has_suggestion_parts: bool,
134
135     /// Set to true when this variant is an enum variant rather than just the body of a struct.
136     is_enum: bool,
137 }
138
139 impl<'parent, 'a> HasFieldMap for SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
140     fn get_field_binding(&self, field: &String) -> Option<&TokenStream> {
141         self.fields.get(field)
142     }
143 }
144
145 /// Provides frequently-needed information about the diagnostic kinds being derived for this type.
146 #[derive(Clone, Copy, Debug)]
147 struct KindsStatistics {
148     has_multipart_suggestion: bool,
149     all_multipart_suggestions: bool,
150     has_normal_suggestion: bool,
151     all_applicabilities_static: bool,
152 }
153
154 impl<'a> FromIterator<&'a SubdiagnosticKind> for KindsStatistics {
155     fn from_iter<T: IntoIterator<Item = &'a SubdiagnosticKind>>(kinds: T) -> Self {
156         let mut ret = Self {
157             has_multipart_suggestion: false,
158             all_multipart_suggestions: true,
159             has_normal_suggestion: false,
160             all_applicabilities_static: true,
161         };
162
163         for kind in kinds {
164             if let SubdiagnosticKind::MultipartSuggestion { applicability: None, .. }
165             | SubdiagnosticKind::Suggestion { applicability: None, .. } = kind
166             {
167                 ret.all_applicabilities_static = false;
168             }
169             if let SubdiagnosticKind::MultipartSuggestion { .. } = kind {
170                 ret.has_multipart_suggestion = true;
171             } else {
172                 ret.all_multipart_suggestions = false;
173             }
174
175             if let SubdiagnosticKind::Suggestion { .. } = kind {
176                 ret.has_normal_suggestion = true;
177             }
178         }
179         ret
180     }
181 }
182
183 impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
184     fn identify_kind(&mut self) -> Result<Vec<(SubdiagnosticKind, Path)>, DiagnosticDeriveError> {
185         let mut kind_slugs = vec![];
186
187         for attr in self.variant.ast().attrs {
188             let Some((kind, slug)) = SubdiagnosticKind::from_attr(attr, self)? else {
189                 // Some attributes aren't errors - like documentation comments - but also aren't
190                 // subdiagnostics.
191                 continue;
192             };
193
194             let Some(slug) = slug else {
195                 let name = attr.path.segments.last().unwrap().ident.to_string();
196                 let name = name.as_str();
197
198                 throw_span_err!(
199                     attr.span().unwrap(),
200                     &format!(
201                         "diagnostic slug must be first argument of a `#[{name}(...)]` attribute"
202                     )
203                 );
204             };
205
206             kind_slugs.push((kind, slug));
207         }
208
209         Ok(kind_slugs)
210     }
211
212     /// Generates the code for a field with no attributes.
213     fn generate_field_set_arg(&mut self, binding: &BindingInfo<'_>) -> TokenStream {
214         let ast = binding.ast();
215         assert_eq!(ast.attrs.len(), 0, "field with attribute used as diagnostic arg");
216
217         let diag = &self.parent.diag;
218         let ident = ast.ident.as_ref().unwrap();
219         // strip `r#` prefix, if present
220         let ident = format_ident!("{}", ident);
221
222         quote! {
223             #diag.set_arg(
224                 stringify!(#ident),
225                 #binding
226             );
227         }
228     }
229
230     /// Generates the necessary code for all attributes on a field.
231     fn generate_field_attr_code(
232         &mut self,
233         binding: &BindingInfo<'_>,
234         kind_stats: KindsStatistics,
235     ) -> TokenStream {
236         let ast = binding.ast();
237         assert!(ast.attrs.len() > 0, "field without attributes generating attr code");
238
239         // Abstract over `Vec<T>` and `Option<T>` fields using `FieldInnerTy`, which will
240         // apply the generated code on each element in the `Vec` or `Option`.
241         let inner_ty = FieldInnerTy::from_type(&ast.ty);
242         ast.attrs
243             .iter()
244             .map(|attr| {
245                 // Always allow documentation comments.
246                 if is_doc_comment(attr) {
247                     return quote! {};
248                 }
249
250                 let info = FieldInfo {
251                     binding,
252                     ty: inner_ty.inner_type().unwrap_or(&ast.ty),
253                     span: &ast.span(),
254                 };
255
256                 let generated = self
257                     .generate_field_code_inner(kind_stats, attr, info, inner_ty.will_iterate())
258                     .unwrap_or_else(|v| v.to_compile_error());
259
260                 inner_ty.with(binding, generated)
261             })
262             .collect()
263     }
264
265     fn generate_field_code_inner(
266         &mut self,
267         kind_stats: KindsStatistics,
268         attr: &Attribute,
269         info: FieldInfo<'_>,
270         clone_suggestion_code: bool,
271     ) -> Result<TokenStream, DiagnosticDeriveError> {
272         let meta = attr.parse_meta()?;
273         match meta {
274             Meta::Path(path) => self.generate_field_code_inner_path(kind_stats, attr, info, path),
275             Meta::List(list @ MetaList { .. }) => self.generate_field_code_inner_list(
276                 kind_stats,
277                 attr,
278                 info,
279                 list,
280                 clone_suggestion_code,
281             ),
282             _ => throw_invalid_attr!(attr, &meta),
283         }
284     }
285
286     /// Generates the code for a `[Meta::Path]`-like attribute on a field (e.g. `#[primary_span]`).
287     fn generate_field_code_inner_path(
288         &mut self,
289         kind_stats: KindsStatistics,
290         attr: &Attribute,
291         info: FieldInfo<'_>,
292         path: Path,
293     ) -> Result<TokenStream, DiagnosticDeriveError> {
294         let span = attr.span().unwrap();
295         let ident = &path.segments.last().unwrap().ident;
296         let name = ident.to_string();
297         let name = name.as_str();
298
299         match name {
300             "skip_arg" => Ok(quote! {}),
301             "primary_span" => {
302                 if kind_stats.has_multipart_suggestion {
303                     invalid_attr(attr, &Meta::Path(path))
304                         .help(
305                             "multipart suggestions use one or more `#[suggestion_part]`s rather \
306                             than one `#[primary_span]`",
307                         )
308                         .emit();
309                 } else {
310                     report_error_if_not_applied_to_span(attr, &info)?;
311
312                     let binding = info.binding.binding.clone();
313                     // FIXME(#100717): support `Option<Span>` on `primary_span` like in the
314                     // diagnostic derive
315                     self.span_field.set_once(binding, span);
316                 }
317
318                 Ok(quote! {})
319             }
320             "suggestion_part" => {
321                 self.has_suggestion_parts = true;
322
323                 if kind_stats.has_multipart_suggestion {
324                     span_err(span, "`#[suggestion_part(...)]` attribute without `code = \"...\"`")
325                         .emit();
326                 } else {
327                     invalid_attr(attr, &Meta::Path(path))
328                         .help(
329                             "`#[suggestion_part(...)]` is only valid in multipart suggestions, \
330                              use `#[primary_span]` instead",
331                         )
332                         .emit();
333                 }
334
335                 Ok(quote! {})
336             }
337             "applicability" => {
338                 if kind_stats.has_multipart_suggestion || kind_stats.has_normal_suggestion {
339                     report_error_if_not_applied_to_applicability(attr, &info)?;
340
341                     if kind_stats.all_applicabilities_static {
342                         span_err(
343                             span,
344                             "`#[applicability]` has no effect if all `#[suggestion]`/\
345                              `#[multipart_suggestion]` attributes have a static \
346                              `applicability = \"...\"`",
347                         )
348                         .emit();
349                     }
350                     let binding = info.binding.binding.clone();
351                     self.applicability.set_once(quote! { #binding }, span);
352                 } else {
353                     span_err(span, "`#[applicability]` is only valid on suggestions").emit();
354                 }
355
356                 Ok(quote! {})
357             }
358             _ => {
359                 let mut span_attrs = vec![];
360                 if kind_stats.has_multipart_suggestion {
361                     span_attrs.push("suggestion_part");
362                 }
363                 if !kind_stats.all_multipart_suggestions {
364                     span_attrs.push("primary_span")
365                 }
366
367                 invalid_attr(attr, &Meta::Path(path))
368                     .help(format!(
369                         "only `{}`, `applicability` and `skip_arg` are valid field attributes",
370                         span_attrs.join(", ")
371                     ))
372                     .emit();
373
374                 Ok(quote! {})
375             }
376         }
377     }
378
379     /// Generates the code for a `[Meta::List]`-like attribute on a field (e.g.
380     /// `#[suggestion_part(code = "...")]`).
381     fn generate_field_code_inner_list(
382         &mut self,
383         kind_stats: KindsStatistics,
384         attr: &Attribute,
385         info: FieldInfo<'_>,
386         list: MetaList,
387         clone_suggestion_code: bool,
388     ) -> Result<TokenStream, DiagnosticDeriveError> {
389         let span = attr.span().unwrap();
390         let ident = &list.path.segments.last().unwrap().ident;
391         let name = ident.to_string();
392         let name = name.as_str();
393
394         match name {
395             "suggestion_part" => {
396                 if !kind_stats.has_multipart_suggestion {
397                     throw_invalid_attr!(attr, &Meta::List(list), |diag| {
398                         diag.help(
399                             "`#[suggestion_part(...)]` is only valid in multipart suggestions",
400                         )
401                     })
402                 }
403
404                 self.has_suggestion_parts = true;
405
406                 report_error_if_not_applied_to_span(attr, &info)?;
407
408                 let mut code = None;
409                 for nested_attr in list.nested.iter() {
410                     let NestedMeta::Meta(ref meta) = nested_attr else {
411                         throw_invalid_nested_attr!(attr, nested_attr);
412                     };
413
414                     let span = meta.span().unwrap();
415                     let nested_name = meta.path().segments.last().unwrap().ident.to_string();
416                     let nested_name = nested_name.as_str();
417
418                     match nested_name {
419                         "code" => {
420                             let code_field = new_code_ident();
421                             let formatting_init = build_suggestion_code(
422                                 &code_field,
423                                 meta,
424                                 self,
425                                 AllowMultipleAlternatives::No,
426                             );
427                             code.set_once((code_field, formatting_init), span);
428                         }
429                         _ => throw_invalid_nested_attr!(attr, nested_attr, |diag| {
430                             diag.help("`code` is the only valid nested attribute")
431                         }),
432                     }
433                 }
434
435                 let Some((code_field, formatting_init)) = code.value() else {
436                     span_err(span, "`#[suggestion_part(...)]` attribute without `code = \"...\"`")
437                         .emit();
438                     return Ok(quote! {});
439                 };
440                 let binding = info.binding;
441
442                 self.formatting_init.extend(formatting_init);
443                 let code_field = if clone_suggestion_code {
444                     quote! { #code_field.clone() }
445                 } else {
446                     quote! { #code_field }
447                 };
448                 Ok(quote! { suggestions.push((#binding, #code_field)); })
449             }
450             _ => throw_invalid_attr!(attr, &Meta::List(list), |diag| {
451                 let mut span_attrs = vec![];
452                 if kind_stats.has_multipart_suggestion {
453                     span_attrs.push("suggestion_part");
454                 }
455                 if !kind_stats.all_multipart_suggestions {
456                     span_attrs.push("primary_span")
457                 }
458                 diag.help(format!(
459                     "only `{}`, `applicability` and `skip_arg` are valid field attributes",
460                     span_attrs.join(", ")
461                 ))
462             }),
463         }
464     }
465
466     pub fn into_tokens(&mut self) -> Result<TokenStream, DiagnosticDeriveError> {
467         let kind_slugs = self.identify_kind()?;
468         if kind_slugs.is_empty() {
469             if self.is_enum {
470                 // It's okay for a variant to not be a subdiagnostic at all..
471                 return Ok(quote! {});
472             } else {
473                 // ..but structs should always be _something_.
474                 throw_span_err!(
475                     self.variant.ast().ident.span().unwrap(),
476                     "subdiagnostic kind not specified"
477                 );
478             }
479         };
480
481         let kind_stats: KindsStatistics = kind_slugs.iter().map(|(kind, _slug)| kind).collect();
482
483         let init = if kind_stats.has_multipart_suggestion {
484             quote! { let mut suggestions = Vec::new(); }
485         } else {
486             quote! {}
487         };
488
489         let attr_args: TokenStream = self
490             .variant
491             .bindings()
492             .iter()
493             .filter(|binding| !binding.ast().attrs.is_empty())
494             .map(|binding| self.generate_field_attr_code(binding, kind_stats))
495             .collect();
496
497         let span_field = self.span_field.value_ref();
498
499         let diag = &self.parent.diag;
500         let f = &self.parent.f;
501         let mut calls = TokenStream::new();
502         for (kind, slug) in kind_slugs {
503             let message = format_ident!("__message");
504             calls.extend(quote! { let #message = #f(#diag, rustc_errors::fluent::#slug.into()); });
505
506             let name = format_ident!("{}{}", if span_field.is_some() { "span_" } else { "" }, kind);
507             let call = match kind {
508                 SubdiagnosticKind::Suggestion {
509                     suggestion_kind,
510                     applicability,
511                     code_init,
512                     code_field,
513                 } => {
514                     self.formatting_init.extend(code_init);
515
516                     let applicability = applicability
517                         .value()
518                         .map(|a| quote! { #a })
519                         .or_else(|| self.applicability.take().value())
520                         .unwrap_or_else(|| quote! { rustc_errors::Applicability::Unspecified });
521
522                     if let Some(span) = span_field {
523                         let style = suggestion_kind.to_suggestion_style();
524                         quote! { #diag.#name(#span, #message, #code_field, #applicability, #style); }
525                     } else {
526                         span_err(self.span, "suggestion without `#[primary_span]` field").emit();
527                         quote! { unreachable!(); }
528                     }
529                 }
530                 SubdiagnosticKind::MultipartSuggestion { suggestion_kind, applicability } => {
531                     let applicability = applicability
532                         .value()
533                         .map(|a| quote! { #a })
534                         .or_else(|| self.applicability.take().value())
535                         .unwrap_or_else(|| quote! { rustc_errors::Applicability::Unspecified });
536
537                     if !self.has_suggestion_parts {
538                         span_err(
539                             self.span,
540                             "multipart suggestion without any `#[suggestion_part(...)]` fields",
541                         )
542                         .emit();
543                     }
544
545                     let style = suggestion_kind.to_suggestion_style();
546
547                     quote! { #diag.#name(#message, suggestions, #applicability, #style); }
548                 }
549                 SubdiagnosticKind::Label => {
550                     if let Some(span) = span_field {
551                         quote! { #diag.#name(#span, #message); }
552                     } else {
553                         span_err(self.span, "label without `#[primary_span]` field").emit();
554                         quote! { unreachable!(); }
555                     }
556                 }
557                 _ => {
558                     if let Some(span) = span_field {
559                         quote! { #diag.#name(#span, #message); }
560                     } else {
561                         quote! { #diag.#name(#message); }
562                     }
563                 }
564             };
565
566             calls.extend(call);
567         }
568
569         let plain_args: TokenStream = self
570             .variant
571             .bindings()
572             .iter()
573             .filter(|binding| binding.ast().attrs.is_empty())
574             .map(|binding| self.generate_field_set_arg(binding))
575             .collect();
576
577         let formatting_init = &self.formatting_init;
578         Ok(quote! {
579             #init
580             #formatting_init
581             #attr_args
582             #plain_args
583             #calls
584         })
585     }
586 }