1 #![deny(unused_must_use)]
3 use crate::diagnostics::error::{
4 invalid_attr, span_err, throw_invalid_attr, throw_invalid_nested_attr, throw_span_err,
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,
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};
17 use super::utils::{build_suggestion_code, AllowMultipleAlternatives};
19 /// The central struct for constructing the `add_to_diagnostic` method from an annotated struct.
20 pub(crate) struct SubdiagnosticDeriveBuilder {
25 impl SubdiagnosticDeriveBuilder {
26 pub(crate) fn new() -> Self {
27 let diag = format_ident!("diag");
28 let f = format_ident!("f");
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();
37 syn::Data::Struct(..) | syn::Data::Enum(..) => (),
38 syn::Data::Union(..) => {
41 "`#[derive(Subdiagnostic)]` can only be used on structs and enums",
46 let is_enum = matches!(ast.data, syn::Data::Enum(..));
48 for attr in &ast.attrs {
49 // Always allow documentation comments.
50 if is_doc_comment(attr) {
56 "unsupported type attribute for subdiagnostic enum",
62 structure.bind_with(|_| synstructure::BindStyle::Move);
63 let variants_ = structure.each_variant(|variant| {
64 let mut builder = SubdiagnosticDeriveVariantBuilder {
68 formatting_init: TokenStream::new(),
69 fields: build_field_mapping(variant),
72 has_suggestion_parts: false,
75 builder.into_tokens().unwrap_or_else(|v| v.to_compile_error())
85 let diag = &self.diag;
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)
92 &mut rustc_errors::Diagnostic,
93 rustc_errors::SubdiagnosticMessage
94 ) -> rustc_errors::SubdiagnosticMessage,
96 use rustc_errors::{Applicability, IntoDiagnosticArg};
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,
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,
118 /// Initialization of format strings for code suggestions.
119 formatting_init: TokenStream,
121 /// Store a map of field name to its corresponding field. This is built on construction of the
125 /// Identifier for the binding to the `#[primary_span]` field.
126 span_field: SpannedOption<proc_macro2::Ident>,
128 /// The binding to the `#[applicability]` field, if present.
129 applicability: SpannedOption<TokenStream>,
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,
135 /// Set to true when this variant is an enum variant rather than just the body of a struct.
139 impl<'parent, 'a> HasFieldMap for SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
140 fn get_field_binding(&self, field: &String) -> Option<&TokenStream> {
141 self.fields.get(field)
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,
154 impl<'a> FromIterator<&'a SubdiagnosticKind> for KindsStatistics {
155 fn from_iter<T: IntoIterator<Item = &'a SubdiagnosticKind>>(kinds: T) -> Self {
157 has_multipart_suggestion: false,
158 all_multipart_suggestions: true,
159 has_normal_suggestion: false,
160 all_applicabilities_static: true,
164 if let SubdiagnosticKind::MultipartSuggestion { applicability: None, .. }
165 | SubdiagnosticKind::Suggestion { applicability: None, .. } = kind
167 ret.all_applicabilities_static = false;
169 if let SubdiagnosticKind::MultipartSuggestion { .. } = kind {
170 ret.has_multipart_suggestion = true;
172 ret.all_multipart_suggestions = false;
175 if let SubdiagnosticKind::Suggestion { .. } = kind {
176 ret.has_normal_suggestion = true;
183 impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
184 fn identify_kind(&mut self) -> Result<Vec<(SubdiagnosticKind, Path)>, DiagnosticDeriveError> {
185 let mut kind_slugs = vec![];
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
194 let Some(slug) = slug else {
195 let name = attr.path.segments.last().unwrap().ident.to_string();
196 let name = name.as_str();
199 attr.span().unwrap(),
201 "diagnostic slug must be first argument of a `#[{name}(...)]` attribute"
206 kind_slugs.push((kind, slug));
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");
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);
230 /// Generates the necessary code for all attributes on a field.
231 fn generate_field_attr_code(
233 binding: &BindingInfo<'_>,
234 kind_stats: KindsStatistics,
236 let ast = binding.ast();
237 assert!(ast.attrs.len() > 0, "field without attributes generating attr code");
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);
245 // Always allow documentation comments.
246 if is_doc_comment(attr) {
250 let info = FieldInfo {
252 ty: inner_ty.inner_type().unwrap_or(&ast.ty),
257 .generate_field_code_inner(kind_stats, attr, info, inner_ty.will_iterate())
258 .unwrap_or_else(|v| v.to_compile_error());
260 inner_ty.with(binding, generated)
265 fn generate_field_code_inner(
267 kind_stats: KindsStatistics,
270 clone_suggestion_code: bool,
271 ) -> Result<TokenStream, DiagnosticDeriveError> {
272 let meta = attr.parse_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(
280 clone_suggestion_code,
282 _ => throw_invalid_attr!(attr, &meta),
286 /// Generates the code for a `[Meta::Path]`-like attribute on a field (e.g. `#[primary_span]`).
287 fn generate_field_code_inner_path(
289 kind_stats: KindsStatistics,
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();
300 "skip_arg" => Ok(quote! {}),
302 if kind_stats.has_multipart_suggestion {
303 invalid_attr(attr, &Meta::Path(path))
305 "multipart suggestions use one or more `#[suggestion_part]`s rather \
306 than one `#[primary_span]`",
310 report_error_if_not_applied_to_span(attr, &info)?;
312 let binding = info.binding.binding.clone();
313 // FIXME(#100717): support `Option<Span>` on `primary_span` like in the
315 self.span_field.set_once(binding, span);
320 "suggestion_part" => {
321 self.has_suggestion_parts = true;
323 if kind_stats.has_multipart_suggestion {
324 span_err(span, "`#[suggestion_part(...)]` attribute without `code = \"...\"`")
327 invalid_attr(attr, &Meta::Path(path))
329 "`#[suggestion_part(...)]` is only valid in multipart suggestions, \
330 use `#[primary_span]` instead",
338 if kind_stats.has_multipart_suggestion || kind_stats.has_normal_suggestion {
339 report_error_if_not_applied_to_applicability(attr, &info)?;
341 if kind_stats.all_applicabilities_static {
344 "`#[applicability]` has no effect if all `#[suggestion]`/\
345 `#[multipart_suggestion]` attributes have a static \
346 `applicability = \"...\"`",
350 let binding = info.binding.binding.clone();
351 self.applicability.set_once(quote! { #binding }, span);
353 span_err(span, "`#[applicability]` is only valid on suggestions").emit();
359 let mut span_attrs = vec![];
360 if kind_stats.has_multipart_suggestion {
361 span_attrs.push("suggestion_part");
363 if !kind_stats.all_multipart_suggestions {
364 span_attrs.push("primary_span")
367 invalid_attr(attr, &Meta::Path(path))
369 "only `{}`, `applicability` and `skip_arg` are valid field attributes",
370 span_attrs.join(", ")
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(
383 kind_stats: KindsStatistics,
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();
395 "suggestion_part" => {
396 if !kind_stats.has_multipart_suggestion {
397 throw_invalid_attr!(attr, &Meta::List(list), |diag| {
399 "`#[suggestion_part(...)]` is only valid in multipart suggestions",
404 self.has_suggestion_parts = true;
406 report_error_if_not_applied_to_span(attr, &info)?;
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);
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();
420 let code_field = new_code_ident();
421 let formatting_init = build_suggestion_code(
425 AllowMultipleAlternatives::No,
427 code.set_once((code_field, formatting_init), span);
429 _ => throw_invalid_nested_attr!(attr, nested_attr, |diag| {
430 diag.help("`code` is the only valid nested attribute")
435 let Some((code_field, formatting_init)) = code.value() else {
436 span_err(span, "`#[suggestion_part(...)]` attribute without `code = \"...\"`")
438 return Ok(quote! {});
440 let binding = info.binding;
442 self.formatting_init.extend(formatting_init);
443 let code_field = if clone_suggestion_code {
444 quote! { #code_field.clone() }
446 quote! { #code_field }
448 Ok(quote! { suggestions.push((#binding, #code_field)); })
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");
455 if !kind_stats.all_multipart_suggestions {
456 span_attrs.push("primary_span")
459 "only `{}`, `applicability` and `skip_arg` are valid field attributes",
460 span_attrs.join(", ")
466 pub fn into_tokens(&mut self) -> Result<TokenStream, DiagnosticDeriveError> {
467 let kind_slugs = self.identify_kind()?;
468 if kind_slugs.is_empty() {
470 // It's okay for a variant to not be a subdiagnostic at all..
471 return Ok(quote! {});
473 // ..but structs should always be _something_.
475 self.variant.ast().ident.span().unwrap(),
476 "subdiagnostic kind not specified"
481 let kind_stats: KindsStatistics = kind_slugs.iter().map(|(kind, _slug)| kind).collect();
483 let init = if kind_stats.has_multipart_suggestion {
484 quote! { let mut suggestions = Vec::new(); }
489 let attr_args: TokenStream = self
493 .filter(|binding| !binding.ast().attrs.is_empty())
494 .map(|binding| self.generate_field_attr_code(binding, kind_stats))
497 let span_field = self.span_field.value_ref();
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()); });
506 let name = format_ident!("{}{}", if span_field.is_some() { "span_" } else { "" }, kind);
507 let call = match kind {
508 SubdiagnosticKind::Suggestion {
514 self.formatting_init.extend(code_init);
516 let applicability = applicability
518 .map(|a| quote! { #a })
519 .or_else(|| self.applicability.take().value())
520 .unwrap_or_else(|| quote! { rustc_errors::Applicability::Unspecified });
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); }
526 span_err(self.span, "suggestion without `#[primary_span]` field").emit();
527 quote! { unreachable!(); }
530 SubdiagnosticKind::MultipartSuggestion { suggestion_kind, applicability } => {
531 let applicability = applicability
533 .map(|a| quote! { #a })
534 .or_else(|| self.applicability.take().value())
535 .unwrap_or_else(|| quote! { rustc_errors::Applicability::Unspecified });
537 if !self.has_suggestion_parts {
540 "multipart suggestion without any `#[suggestion_part(...)]` fields",
545 let style = suggestion_kind.to_suggestion_style();
547 quote! { #diag.#name(#message, suggestions, #applicability, #style); }
549 SubdiagnosticKind::Label => {
550 if let Some(span) = span_field {
551 quote! { #diag.#name(#span, #message); }
553 span_err(self.span, "label without `#[primary_span]` field").emit();
554 quote! { unreachable!(); }
558 if let Some(span) = span_field {
559 quote! { #diag.#name(#span, #message); }
561 quote! { #diag.#name(#message); }
569 let plain_args: TokenStream = self
573 .filter(|binding| binding.ast().attrs.is_empty())
574 .map(|binding| self.generate_field_set_arg(binding))
577 let formatting_init = &self.formatting_init;