1
Fork 0

Auto merge of #102292 - fee1-dead-contrib:rollup-61ptdkt, r=fee1-dead

Rollup of 4 pull requests

Successful merges:

 - #101851 (Clean up (sub)diagnostic derives)
 - #102244 (Only generate closure def id for async fns with body)
 - #102263 (Clarify Iterator::rposition code example)
 - #102280 (rustdoc: clean up `.out-of-band`/`.in-band` CSS)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2022-09-26 02:45:13 +00:00
commit fe217c28ff
77 changed files with 1098 additions and 941 deletions

View file

@ -1055,9 +1055,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
asyncness: Async,
body: Option<&Block>,
) -> hir::BodyId {
let closure_id = match asyncness {
Async::Yes { closure_id, .. } => closure_id,
Async::No => return self.lower_fn_body_block(span, decl, body),
let (closure_id, body) = match (asyncness, body) {
(Async::Yes { closure_id, .. }, Some(body)) => (closure_id, body),
_ => return self.lower_fn_body_block(span, decl, body),
};
self.lower_body(|this| {
@ -1199,16 +1199,15 @@ impl<'hir> LoweringContext<'_, 'hir> {
parameters.push(new_parameter);
}
let body_span = body.map_or(span, |b| b.span);
let async_expr = this.make_async_expr(
CaptureBy::Value,
closure_id,
None,
body_span,
body.span,
hir::AsyncGeneratorKind::Fn,
|this| {
// Create a block from the user's function body:
let user_body = this.lower_block_expr_opt(body_span, body);
let user_body = this.lower_block_expr(body);
// Transform into `drop-temps { <user-body> }`, an expression:
let desugared_span =
@ -1240,7 +1239,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
(
this.arena.alloc_from_iter(parameters),
this.expr(body_span, async_expr, AttrVec::new()),
this.expr(body.span, async_expr, AttrVec::new()),
)
})
}

View file

@ -1,17 +1,17 @@
#![deny(unused_must_use)]
use super::error::throw_invalid_nested_attr;
use super::utils::{SpannedOption, SubdiagnosticKind};
use crate::diagnostics::error::{
invalid_nested_attr, span_err, throw_invalid_attr, throw_invalid_nested_attr, throw_span_err,
DiagnosticDeriveError,
invalid_nested_attr, span_err, throw_invalid_attr, throw_span_err, DiagnosticDeriveError,
};
use crate::diagnostics::utils::{
report_error_if_not_applied_to_span, report_type_error, type_is_unit, type_matches_path,
Applicability, FieldInfo, FieldInnerTy, HasFieldMap, SetOnce,
FieldInfo, FieldInnerTy, HasFieldMap, SetOnce,
};
use proc_macro2::{Ident, Span, TokenStream};
use quote::{format_ident, quote};
use std::collections::HashMap;
use std::str::FromStr;
use syn::{
parse_quote, spanned::Spanned, Attribute, Field, Meta, MetaList, MetaNameValue, NestedMeta,
Path, Type,
@ -40,10 +40,10 @@ pub(crate) struct DiagnosticDeriveBuilder {
pub kind: DiagnosticDeriveKind,
/// Slug is a mandatory part of the struct attribute as corresponds to the Fluent message that
/// has the actual diagnostic message.
pub slug: Option<(Path, proc_macro::Span)>,
pub slug: SpannedOption<Path>,
/// Error codes are a optional part of the struct attribute - this is only set to detect
/// multiple specifications.
pub code: Option<(String, proc_macro::Span)>,
pub code: SpannedOption<()>,
}
impl HasFieldMap for DiagnosticDeriveBuilder {
@ -127,6 +127,30 @@ impl DiagnosticDeriveBuilder {
|| is_subdiagnostic
}
fn parse_subdiag_attribute(
&self,
attr: &Attribute,
) -> Result<(SubdiagnosticKind, Path), DiagnosticDeriveError> {
let (subdiag, slug) = SubdiagnosticKind::from_attr(attr, self)?;
if let SubdiagnosticKind::MultipartSuggestion { .. } = subdiag {
let meta = attr.parse_meta()?;
throw_invalid_attr!(attr, &meta, |diag| diag
.help("consider creating a `Subdiagnostic` instead"));
}
let slug = slug.unwrap_or_else(|| match subdiag {
SubdiagnosticKind::Label => parse_quote! { _subdiag::label },
SubdiagnosticKind::Note => parse_quote! { _subdiag::note },
SubdiagnosticKind::Help => parse_quote! { _subdiag::help },
SubdiagnosticKind::Warn => parse_quote! { _subdiag::warn },
SubdiagnosticKind::Suggestion { .. } => parse_quote! { _subdiag::suggestion },
SubdiagnosticKind::MultipartSuggestion { .. } => unreachable!(),
});
Ok((subdiag, slug))
}
/// Establishes state in the `DiagnosticDeriveBuilder` resulting from the struct
/// attributes like `#[diag(..)]`, such as the slug and error code. Generates
/// diagnostic builder calls for setting error code and creating note/help messages.
@ -135,98 +159,64 @@ impl DiagnosticDeriveBuilder {
attr: &Attribute,
) -> Result<TokenStream, DiagnosticDeriveError> {
let diag = &self.diag;
let span = attr.span().unwrap();
let name = attr.path.segments.last().unwrap().ident.to_string();
let name = name.as_str();
let meta = attr.parse_meta()?;
let is_diag = name == "diag";
if name == "diag" {
let Meta::List(MetaList { ref nested, .. }) = meta else {
throw_invalid_attr!(
attr,
&meta
);
};
let nested = match meta {
// Most attributes are lists, like `#[diag(..)]` for most cases or
// `#[help(..)]`/`#[note(..)]` when the user is specifying a alternative slug.
Meta::List(MetaList { ref nested, .. }) => nested,
// Subdiagnostics without spans can be applied to the type too, and these are just
// paths: `#[help]`, `#[note]` and `#[warning]`
Meta::Path(_) if !is_diag => {
let fn_name = if name == "warning" {
Ident::new("warn", attr.span())
} else {
Ident::new(name, attr.span())
};
return Ok(quote! { #diag.#fn_name(rustc_errors::fluent::_subdiag::#fn_name); });
}
_ => throw_invalid_attr!(attr, &meta),
};
let mut nested_iter = nested.into_iter().peekable();
// Check the kind before doing any further processing so that there aren't misleading
// "no kind specified" errors if there are failures later.
match name {
"error" | "lint" => throw_invalid_attr!(attr, &meta, |diag| {
diag.help("`error` and `lint` have been replaced by `diag`")
}),
"warn_" => throw_invalid_attr!(attr, &meta, |diag| {
diag.help("`warn_` have been replaced by `warning`")
}),
"diag" | "help" | "note" | "warning" => (),
_ => throw_invalid_attr!(attr, &meta, |diag| {
diag.help("only `diag`, `help`, `note` and `warning` are valid attributes")
}),
}
match nested_iter.peek() {
Some(NestedMeta::Meta(Meta::Path(slug))) => {
self.slug.set_once(slug.clone(), slug.span().unwrap());
nested_iter.next();
}
Some(NestedMeta::Meta(Meta::NameValue { .. })) => {}
Some(nested_attr) => throw_invalid_nested_attr!(attr, &nested_attr, |diag| diag
.help("a diagnostic slug is required as the first argument")),
None => throw_invalid_attr!(attr, &meta, |diag| diag
.help("a diagnostic slug is required as the first argument")),
};
// First nested element should always be the path, e.g. `#[diag(typeck::invalid)]` or
// `#[help(typeck::another_help)]`.
let mut nested_iter = nested.into_iter();
if let Some(nested_attr) = nested_iter.next() {
// Report an error if there are any other list items after the path.
if !is_diag && nested_iter.next().is_some() {
throw_invalid_nested_attr!(attr, &nested_attr, |diag| {
diag.help(
"`help`, `note` and `warning` struct attributes can only have one argument",
)
});
}
match nested_attr {
NestedMeta::Meta(Meta::Path(path)) => {
if is_diag {
self.slug.set_once((path.clone(), span));
} else {
let fn_name = proc_macro2::Ident::new(name, attr.span());
return Ok(quote! { #diag.#fn_name(rustc_errors::fluent::#path); });
// Remaining attributes are optional, only `code = ".."` at the moment.
let mut tokens = TokenStream::new();
for nested_attr in nested_iter {
let (value, path) = match nested_attr {
NestedMeta::Meta(Meta::NameValue(MetaNameValue {
lit: syn::Lit::Str(value),
path,
..
})) => (value, path),
NestedMeta::Meta(Meta::Path(_)) => {
invalid_nested_attr(attr, &nested_attr)
.help("diagnostic slug must be the first argument")
.emit();
continue;
}
}
NestedMeta::Meta(meta @ Meta::NameValue(_))
if is_diag && meta.path().segments.last().unwrap().ident == "code" =>
{
// don't error for valid follow-up attributes
}
nested_attr => throw_invalid_nested_attr!(attr, &nested_attr, |diag| {
diag.help("first argument of the attribute should be the diagnostic slug")
}),
};
}
_ => {
invalid_nested_attr(attr, &nested_attr).emit();
continue;
}
};
// Remaining attributes are optional, only `code = ".."` at the moment.
let mut tokens = Vec::new();
for nested_attr in nested_iter {
let meta = match nested_attr {
syn::NestedMeta::Meta(meta) => meta,
_ => throw_invalid_nested_attr!(attr, &nested_attr),
};
let path = meta.path();
let nested_name = path.segments.last().unwrap().ident.to_string();
// Struct attributes are only allowed to be applied once, and the diagnostic
// changes will be set in the initialisation code.
if let Meta::NameValue(MetaNameValue { lit: syn::Lit::Str(s), .. }) = &meta {
let span = s.span().unwrap();
let nested_name = path.segments.last().unwrap().ident.to_string();
// Struct attributes are only allowed to be applied once, and the diagnostic
// changes will be set in the initialisation code.
let span = value.span().unwrap();
match nested_name.as_str() {
"code" => {
self.code.set_once((s.value(), span));
let code = &self.code.as_ref().map(|(v, _)| v);
tokens.push(quote! {
self.code.set_once((), span);
let code = value.value();
tokens.extend(quote! {
#diag.code(rustc_errors::DiagnosticId::Error(#code.to_string()));
});
}
@ -234,12 +224,22 @@ impl DiagnosticDeriveBuilder {
.help("only `code` is a valid nested attributes following the slug")
.emit(),
}
} else {
invalid_nested_attr(attr, &nested_attr).emit()
}
return Ok(tokens);
}
Ok(tokens.into_iter().collect())
let (subdiag, slug) = self.parse_subdiag_attribute(attr)?;
let fn_ident = format_ident!("{}", subdiag);
match subdiag {
SubdiagnosticKind::Note | SubdiagnosticKind::Help | SubdiagnosticKind::Warn => {
Ok(self.add_subdiagnostic(&fn_ident, slug))
}
SubdiagnosticKind::Label | SubdiagnosticKind::Suggestion { .. } => {
throw_invalid_attr!(attr, &meta, |diag| diag
.help("`#[label]` and `#[suggestion]` can only be applied to fields"));
}
SubdiagnosticKind::MultipartSuggestion { .. } => unreachable!(),
}
}
fn generate_field_attrs_code(&mut self, binding_info: &BindingInfo<'_>) -> TokenStream {
@ -303,232 +303,83 @@ impl DiagnosticDeriveBuilder {
info: FieldInfo<'_>,
binding: TokenStream,
) -> Result<TokenStream, DiagnosticDeriveError> {
let meta = attr.parse_meta()?;
match meta {
Meta::Path(_) => self.generate_inner_field_code_path(attr, info, binding),
Meta::List(MetaList { .. }) => self.generate_inner_field_code_list(attr, info, binding),
_ => throw_invalid_attr!(attr, &meta),
}
}
fn generate_inner_field_code_path(
&mut self,
attr: &Attribute,
info: FieldInfo<'_>,
binding: TokenStream,
) -> Result<TokenStream, DiagnosticDeriveError> {
assert!(matches!(attr.parse_meta()?, Meta::Path(_)));
let diag = &self.diag;
let meta = attr.parse_meta()?;
let ident = &attr.path.segments.last().unwrap().ident;
let name = ident.to_string();
let name = name.as_str();
match name {
"skip_arg" => {
// Don't need to do anything - by virtue of the attribute existing, the
// `set_arg` call will not be generated.
Ok(quote! {})
}
"primary_span" => {
match self.kind {
if let Meta::Path(_) = meta {
let ident = &attr.path.segments.last().unwrap().ident;
let name = ident.to_string();
let name = name.as_str();
match name {
"skip_arg" => {
// Don't need to do anything - by virtue of the attribute existing, the
// `set_arg` call will not be generated.
return Ok(quote! {});
}
"primary_span" => match self.kind {
DiagnosticDeriveKind::Diagnostic => {
report_error_if_not_applied_to_span(attr, &info)?;
Ok(quote! {
return Ok(quote! {
#diag.set_span(#binding);
})
});
}
DiagnosticDeriveKind::LintDiagnostic => {
throw_invalid_attr!(attr, &meta, |diag| {
diag.help("the `primary_span` field attribute is not valid for lint diagnostics")
})
}
}
},
"subdiagnostic" => return Ok(quote! { #diag.subdiagnostic(#binding); }),
_ => {}
}
"label" => {
}
let (subdiag, slug) = self.parse_subdiag_attribute(attr)?;
let fn_ident = format_ident!("{}", subdiag);
match subdiag {
SubdiagnosticKind::Label => {
report_error_if_not_applied_to_span(attr, &info)?;
Ok(self.add_spanned_subdiagnostic(binding, ident, parse_quote! { _subdiag::label }))
Ok(self.add_spanned_subdiagnostic(binding, &fn_ident, slug))
}
"note" | "help" | "warning" => {
let warn_ident = Ident::new("warn", Span::call_site());
let (ident, path) = match name {
"note" => (ident, parse_quote! { _subdiag::note }),
"help" => (ident, parse_quote! { _subdiag::help }),
"warning" => (&warn_ident, parse_quote! { _subdiag::warn }),
_ => unreachable!(),
};
SubdiagnosticKind::Note | SubdiagnosticKind::Help | SubdiagnosticKind::Warn => {
if type_matches_path(&info.ty, &["rustc_span", "Span"]) {
Ok(self.add_spanned_subdiagnostic(binding, ident, path))
Ok(self.add_spanned_subdiagnostic(binding, &fn_ident, slug))
} else if type_is_unit(&info.ty) {
Ok(self.add_subdiagnostic(ident, path))
Ok(self.add_subdiagnostic(&fn_ident, slug))
} else {
report_type_error(attr, "`Span` or `()`")?
}
}
"subdiagnostic" => Ok(quote! { #diag.subdiagnostic(#binding); }),
_ => throw_invalid_attr!(attr, &meta, |diag| {
diag.help(
"only `skip_arg`, `primary_span`, `label`, `note`, `help` and `subdiagnostic` \
are valid field attributes",
)
}),
}
}
SubdiagnosticKind::Suggestion {
suggestion_kind,
applicability: static_applicability,
code,
} => {
let (span_field, mut applicability) = self.span_and_applicability_of_ty(info)?;
fn generate_inner_field_code_list(
&mut self,
attr: &Attribute,
info: FieldInfo<'_>,
binding: TokenStream,
) -> Result<TokenStream, DiagnosticDeriveError> {
let meta = attr.parse_meta()?;
let Meta::List(MetaList { ref path, ref nested, .. }) = meta else { unreachable!() };
let ident = &attr.path.segments.last().unwrap().ident;
let name = path.segments.last().unwrap().ident.to_string();
let name = name.as_ref();
match name {
"suggestion" | "suggestion_short" | "suggestion_hidden" | "suggestion_verbose" => {
return self.generate_inner_field_code_suggestion(attr, info);
}
"label" | "help" | "note" | "warning" => (),
_ => throw_invalid_attr!(attr, &meta, |diag| {
diag.help(
"only `label`, `help`, `note`, `warn` or `suggestion{,_short,_hidden,_verbose}` are \
valid field attributes",
)
}),
}
// For `#[label(..)]`, `#[note(..)]` and `#[help(..)]`, the first nested element must be a
// path, e.g. `#[label(typeck::label)]`.
let mut nested_iter = nested.into_iter();
let msg = match nested_iter.next() {
Some(NestedMeta::Meta(Meta::Path(path))) => path.clone(),
Some(nested_attr) => throw_invalid_nested_attr!(attr, &nested_attr),
None => throw_invalid_attr!(attr, &meta),
};
// None of these attributes should have anything following the slug.
if nested_iter.next().is_some() {
throw_invalid_attr!(attr, &meta);
}
match name {
"label" => {
report_error_if_not_applied_to_span(attr, &info)?;
Ok(self.add_spanned_subdiagnostic(binding, ident, msg))
}
"note" | "help" if type_matches_path(&info.ty, &["rustc_span", "Span"]) => {
Ok(self.add_spanned_subdiagnostic(binding, ident, msg))
}
"note" | "help" if type_is_unit(&info.ty) => Ok(self.add_subdiagnostic(ident, msg)),
// `warning` must be special-cased because the attribute `warn` already has meaning and
// so isn't used, despite the diagnostic API being named `warn`.
"warning" if type_matches_path(&info.ty, &["rustc_span", "Span"]) => Ok(self
.add_spanned_subdiagnostic(binding, &Ident::new("warn", Span::call_site()), msg)),
"warning" if type_is_unit(&info.ty) => {
Ok(self.add_subdiagnostic(&Ident::new("warn", Span::call_site()), msg))
}
"note" | "help" | "warning" => report_type_error(attr, "`Span` or `()`")?,
_ => unreachable!(),
}
}
fn generate_inner_field_code_suggestion(
&mut self,
attr: &Attribute,
info: FieldInfo<'_>,
) -> Result<TokenStream, DiagnosticDeriveError> {
let diag = &self.diag;
let mut meta = attr.parse_meta()?;
let Meta::List(MetaList { ref path, ref mut nested, .. }) = meta else { unreachable!() };
let (span_field, mut applicability) = self.span_and_applicability_of_ty(info)?;
let mut msg = None;
let mut code = None;
let mut nested_iter = nested.into_iter().peekable();
if let Some(nested_attr) = nested_iter.peek() {
if let NestedMeta::Meta(Meta::Path(path)) = nested_attr {
msg = Some(path.clone());
}
};
// Move the iterator forward if a path was found (don't otherwise so that
// code/applicability can be found or an error emitted).
if msg.is_some() {
let _ = nested_iter.next();
}
for nested_attr in nested_iter {
let meta = match nested_attr {
syn::NestedMeta::Meta(ref meta) => meta,
syn::NestedMeta::Lit(_) => throw_invalid_nested_attr!(attr, &nested_attr),
};
let nested_name = meta.path().segments.last().unwrap().ident.to_string();
let nested_name = nested_name.as_str();
match meta {
Meta::NameValue(MetaNameValue { lit: syn::Lit::Str(s), .. }) => {
let span = meta.span().unwrap();
match nested_name {
"code" => {
let formatted_str = self.build_format(&s.value(), s.span());
code = Some(formatted_str);
}
"applicability" => {
applicability = match applicability {
Some(v) => {
span_err(
span,
"applicability cannot be set in both the field and \
attribute",
)
.emit();
Some(v)
}
None => match Applicability::from_str(&s.value()) {
Ok(v) => Some(quote! { #v }),
Err(()) => {
span_err(span, "invalid applicability").emit();
None
}
},
}
}
_ => throw_invalid_nested_attr!(attr, &nested_attr, |diag| {
diag.help(
"only `message`, `code` and `applicability` are valid field \
attributes",
)
}),
}
if let Some((static_applicability, span)) = static_applicability {
applicability.set_once(quote! { #static_applicability }, span);
}
_ => throw_invalid_nested_attr!(attr, &nested_attr, |diag| {
if matches!(meta, Meta::Path(_)) {
diag.help("a diagnostic slug must be the first argument to the attribute")
} else {
diag
}
}),
let applicability = applicability
.value()
.unwrap_or_else(|| quote! { rustc_errors::Applicability::Unspecified });
let style = suggestion_kind.to_suggestion_style();
Ok(quote! {
#diag.span_suggestion_with_style(
#span_field,
rustc_errors::fluent::#slug,
#code,
#applicability,
#style
);
})
}
SubdiagnosticKind::MultipartSuggestion { .. } => unreachable!(),
}
let applicability =
applicability.unwrap_or_else(|| quote!(rustc_errors::Applicability::Unspecified));
let name = path.segments.last().unwrap().ident.to_string();
let method = format_ident!("span_{}", name);
let msg = msg.unwrap_or_else(|| parse_quote! { _subdiag::suggestion });
let msg = quote! { rustc_errors::fluent::#msg };
let code = code.unwrap_or_else(|| quote! { String::new() });
Ok(quote! { #diag.#method(#span_field, #msg, #code, #applicability); })
}
/// Adds a spanned subdiagnostic by generating a `diag.span_$kind` call with the current slug
@ -561,7 +412,7 @@ impl DiagnosticDeriveBuilder {
fn span_and_applicability_of_ty(
&self,
info: FieldInfo<'_>,
) -> Result<(TokenStream, Option<TokenStream>), DiagnosticDeriveError> {
) -> Result<(TokenStream, SpannedOption<TokenStream>), DiagnosticDeriveError> {
match &info.ty {
// If `ty` is `Span` w/out applicability, then use `Applicability::Unspecified`.
ty @ Type::Path(..) if type_matches_path(ty, &["rustc_span", "Span"]) => {
@ -573,46 +424,37 @@ impl DiagnosticDeriveBuilder {
let mut span_idx = None;
let mut applicability_idx = None;
fn type_err(span: &Span) -> Result<!, DiagnosticDeriveError> {
span_err(span.unwrap(), "wrong types for suggestion")
.help(
"`#[suggestion(...)]` on a tuple field must be applied to fields \
of type `(Span, Applicability)`",
)
.emit();
Err(DiagnosticDeriveError::ErrorHandled)
}
for (idx, elem) in tup.elems.iter().enumerate() {
if type_matches_path(elem, &["rustc_span", "Span"]) {
if span_idx.is_none() {
span_idx = Some(syn::Index::from(idx));
} else {
throw_span_err!(
info.span.unwrap(),
"type of field annotated with `#[suggestion(...)]` contains more \
than one `Span`"
);
}
span_idx.set_once(syn::Index::from(idx), elem.span().unwrap());
} else if type_matches_path(elem, &["rustc_errors", "Applicability"]) {
if applicability_idx.is_none() {
applicability_idx = Some(syn::Index::from(idx));
} else {
throw_span_err!(
info.span.unwrap(),
"type of field annotated with `#[suggestion(...)]` contains more \
than one Applicability"
);
}
applicability_idx.set_once(syn::Index::from(idx), elem.span().unwrap());
} else {
type_err(&elem.span())?;
}
}
if let Some(span_idx) = span_idx {
let binding = &info.binding.binding;
let span = quote!(#binding.#span_idx);
let applicability = applicability_idx
.map(|applicability_idx| quote!(#binding.#applicability_idx))
.unwrap_or_else(|| quote!(rustc_errors::Applicability::Unspecified));
let Some((span_idx, _)) = span_idx else {
type_err(&tup.span())?;
};
let Some((applicability_idx, applicability_span)) = applicability_idx else {
type_err(&tup.span())?;
};
let binding = &info.binding.binding;
let span = quote!(#binding.#span_idx);
let applicability = quote!(#binding.#applicability_idx);
return Ok((span, Some(applicability)));
}
throw_span_err!(info.span.unwrap(), "wrong types for suggestion", |diag| {
diag.help(
"`#[suggestion(...)]` on a tuple field must be applied to fields of type \
`(Span, Applicability)`",
)
});
Ok((span, Some((applicability, applicability_span))))
}
// If `ty` isn't a `Span` or `(Span, Applicability)` then emit an error.
_ => throw_span_err!(info.span.unwrap(), "wrong field type for suggestion", |diag| {

View file

@ -4,98 +4,17 @@ use crate::diagnostics::error::{
span_err, throw_invalid_attr, throw_invalid_nested_attr, throw_span_err, DiagnosticDeriveError,
};
use crate::diagnostics::utils::{
report_error_if_not_applied_to_applicability, report_error_if_not_applied_to_span,
Applicability, FieldInfo, FieldInnerTy, HasFieldMap, SetOnce,
report_error_if_not_applied_to_applicability, report_error_if_not_applied_to_span, FieldInfo,
FieldInnerTy, HasFieldMap, SetOnce,
};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;
use syn::{spanned::Spanned, Attribute, Meta, MetaList, MetaNameValue, NestedMeta, Path};
use synstructure::{BindingInfo, Structure, VariantInfo};
/// Which kind of suggestion is being created?
#[derive(Clone, Copy)]
enum SubdiagnosticSuggestionKind {
/// `#[suggestion]`
Normal,
/// `#[suggestion_short]`
Short,
/// `#[suggestion_hidden]`
Hidden,
/// `#[suggestion_verbose]`
Verbose,
}
impl FromStr for SubdiagnosticSuggestionKind {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"" => Ok(SubdiagnosticSuggestionKind::Normal),
"_short" => Ok(SubdiagnosticSuggestionKind::Short),
"_hidden" => Ok(SubdiagnosticSuggestionKind::Hidden),
"_verbose" => Ok(SubdiagnosticSuggestionKind::Verbose),
_ => Err(()),
}
}
}
impl SubdiagnosticSuggestionKind {
pub fn to_suggestion_style(&self) -> TokenStream {
match self {
SubdiagnosticSuggestionKind::Normal => {
quote! { rustc_errors::SuggestionStyle::ShowCode }
}
SubdiagnosticSuggestionKind::Short => {
quote! { rustc_errors::SuggestionStyle::HideCodeInline }
}
SubdiagnosticSuggestionKind::Hidden => {
quote! { rustc_errors::SuggestionStyle::HideCodeAlways }
}
SubdiagnosticSuggestionKind::Verbose => {
quote! { rustc_errors::SuggestionStyle::ShowAlways }
}
}
}
}
/// Which kind of subdiagnostic is being created from a variant?
#[derive(Clone)]
enum SubdiagnosticKind {
/// `#[label(...)]`
Label,
/// `#[note(...)]`
Note,
/// `#[help(...)]`
Help,
/// `#[warning(...)]`
Warn,
/// `#[suggestion{,_short,_hidden,_verbose}]`
Suggestion { suggestion_kind: SubdiagnosticSuggestionKind, code: TokenStream },
/// `#[multipart_suggestion{,_short,_hidden,_verbose}]`
MultipartSuggestion { suggestion_kind: SubdiagnosticSuggestionKind },
}
impl quote::IdentFragment for SubdiagnosticKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SubdiagnosticKind::Label => write!(f, "label"),
SubdiagnosticKind::Note => write!(f, "note"),
SubdiagnosticKind::Help => write!(f, "help"),
SubdiagnosticKind::Warn => write!(f, "warn"),
SubdiagnosticKind::Suggestion { .. } => write!(f, "suggestion_with_style"),
SubdiagnosticKind::MultipartSuggestion { .. } => {
write!(f, "multipart_suggestion_with_style")
}
}
}
fn span(&self) -> Option<proc_macro2::Span> {
None
}
}
use super::error::invalid_attr;
use super::utils::{SpannedOption, SubdiagnosticKind};
/// The central struct for constructing the `add_to_diagnostic` method from an annotated struct.
pub(crate) struct SubdiagnosticDerive<'a> {
@ -195,10 +114,10 @@ struct SubdiagnosticDeriveBuilder<'a> {
fields: HashMap<String, TokenStream>,
/// Identifier for the binding to the `#[primary_span]` field.
span_field: Option<(proc_macro2::Ident, proc_macro::Span)>,
/// If a suggestion, the identifier for the binding to the `#[applicability]` field or a
/// `rustc_errors::Applicability::*` variant directly.
applicability: Option<(TokenStream, proc_macro::Span)>,
span_field: SpannedOption<proc_macro2::Ident>,
/// The binding to the `#[applicability]` field, if present.
applicability: SpannedOption<TokenStream>,
/// Set to true when a `#[suggestion_part]` field is encountered, used to generate an error
/// during finalization if still `false`.
@ -217,6 +136,7 @@ struct KindsStatistics {
has_multipart_suggestion: bool,
all_multipart_suggestions: bool,
has_normal_suggestion: bool,
all_applicabilities_static: bool,
}
impl<'a> FromIterator<&'a SubdiagnosticKind> for KindsStatistics {
@ -225,8 +145,15 @@ impl<'a> FromIterator<&'a SubdiagnosticKind> for KindsStatistics {
has_multipart_suggestion: false,
all_multipart_suggestions: true,
has_normal_suggestion: false,
all_applicabilities_static: true,
};
for kind in kinds {
if let SubdiagnosticKind::MultipartSuggestion { applicability: None, .. }
| SubdiagnosticKind::Suggestion { applicability: None, .. } = kind
{
ret.all_applicabilities_static = false;
}
if let SubdiagnosticKind::MultipartSuggestion { .. } = kind {
ret.has_multipart_suggestion = true;
} else {
@ -246,129 +173,14 @@ impl<'a> SubdiagnosticDeriveBuilder<'a> {
let mut kind_slugs = vec![];
for attr in self.variant.ast().attrs {
let span = attr.span().unwrap();
let (kind, slug) = SubdiagnosticKind::from_attr(attr, self)?;
let name = attr.path.segments.last().unwrap().ident.to_string();
let name = name.as_str();
let Some(slug) = slug else {
let name = attr.path.segments.last().unwrap().ident.to_string();
let name = name.as_str();
let meta = attr.parse_meta()?;
let Meta::List(MetaList { ref nested, .. }) = meta else {
throw_invalid_attr!(attr, &meta);
};
let mut kind = match name {
"label" => SubdiagnosticKind::Label,
"note" => SubdiagnosticKind::Note,
"help" => SubdiagnosticKind::Help,
"warning" => SubdiagnosticKind::Warn,
_ => {
if let Some(suggestion_kind) =
name.strip_prefix("suggestion").and_then(|s| s.parse().ok())
{
SubdiagnosticKind::Suggestion { suggestion_kind, code: TokenStream::new() }
} else if let Some(suggestion_kind) =
name.strip_prefix("multipart_suggestion").and_then(|s| s.parse().ok())
{
SubdiagnosticKind::MultipartSuggestion { suggestion_kind }
} else {
throw_invalid_attr!(attr, &meta);
}
}
};
let mut slug = None;
let mut code = None;
let mut nested_iter = nested.into_iter();
if let Some(nested_attr) = nested_iter.next() {
match nested_attr {
NestedMeta::Meta(Meta::Path(path)) => {
slug.set_once((path.clone(), span));
}
NestedMeta::Meta(meta @ Meta::NameValue(_))
if matches!(
meta.path().segments.last().unwrap().ident.to_string().as_str(),
"code" | "applicability"
) =>
{
// Don't error for valid follow-up attributes.
}
nested_attr => {
throw_invalid_nested_attr!(attr, &nested_attr, |diag| {
diag.help(
"first argument of the attribute should be the diagnostic \
slug",
)
})
}
};
}
for nested_attr in nested_iter {
let meta = match nested_attr {
NestedMeta::Meta(ref meta) => meta,
_ => throw_invalid_nested_attr!(attr, &nested_attr),
};
let span = meta.span().unwrap();
let nested_name = meta.path().segments.last().unwrap().ident.to_string();
let nested_name = nested_name.as_str();
let value = match meta {
Meta::NameValue(MetaNameValue { lit: syn::Lit::Str(value), .. }) => value,
Meta::Path(_) => throw_invalid_nested_attr!(attr, &nested_attr, |diag| {
diag.help("a diagnostic slug must be the first argument to the attribute")
}),
_ => throw_invalid_nested_attr!(attr, &nested_attr),
};
match nested_name {
"code" => {
if matches!(kind, SubdiagnosticKind::Suggestion { .. }) {
let formatted_str = self.build_format(&value.value(), value.span());
code.set_once((formatted_str, span));
} else {
span_err(
span,
&format!(
"`code` is not a valid nested attribute of a `{}` attribute",
name
),
)
.emit();
}
}
"applicability" => {
if matches!(
kind,
SubdiagnosticKind::Suggestion { .. }
| SubdiagnosticKind::MultipartSuggestion { .. }
) {
let value =
Applicability::from_str(&value.value()).unwrap_or_else(|()| {
span_err(span, "invalid applicability").emit();
Applicability::Unspecified
});
self.applicability.set_once((quote! { #value }, span));
} else {
span_err(
span,
&format!(
"`applicability` is not a valid nested attribute of a `{}` attribute",
name
)
).emit();
}
}
_ => throw_invalid_nested_attr!(attr, &nested_attr, |diag| {
diag.help("only `code` and `applicability` are valid nested attributes")
}),
}
}
let Some((slug, _)) = slug else {
throw_span_err!(
span,
attr.span().unwrap(),
&format!(
"diagnostic slug must be first argument of a `#[{}(...)]` attribute",
name
@ -376,21 +188,7 @@ impl<'a> SubdiagnosticDeriveBuilder<'a> {
);
};
match kind {
SubdiagnosticKind::Suggestion { code: ref mut code_field, .. } => {
let Some((code, _)) = code else {
throw_span_err!(span, "suggestion without `code = \"...\"`");
};
*code_field = code;
}
SubdiagnosticKind::Label
| SubdiagnosticKind::Note
| SubdiagnosticKind::Help
| SubdiagnosticKind::Warn
| SubdiagnosticKind::MultipartSuggestion { .. } => {}
}
kind_slugs.push((kind, slug))
kind_slugs.push((kind, slug));
}
Ok(kind_slugs)
@ -474,19 +272,19 @@ impl<'a> SubdiagnosticDeriveBuilder<'a> {
"skip_arg" => Ok(quote! {}),
"primary_span" => {
if kind_stats.has_multipart_suggestion {
throw_invalid_attr!(attr, &Meta::Path(path), |diag| {
diag.help(
invalid_attr(attr, &Meta::Path(path))
.help(
"multipart suggestions use one or more `#[suggestion_part]`s rather \
than one `#[primary_span]`",
)
})
.emit();
} else {
report_error_if_not_applied_to_span(attr, &info)?;
let binding = info.binding.binding.clone();
self.span_field.set_once(binding, span);
}
report_error_if_not_applied_to_span(attr, &info)?;
let binding = info.binding.binding.clone();
self.span_field.set_once((binding, span));
Ok(quote! {})
}
"suggestion_part" => {
@ -495,28 +293,39 @@ impl<'a> SubdiagnosticDeriveBuilder<'a> {
if kind_stats.has_multipart_suggestion {
span_err(span, "`#[suggestion_part(...)]` attribute without `code = \"...\"`")
.emit();
Ok(quote! {})
} else {
throw_invalid_attr!(attr, &Meta::Path(path), |diag| {
diag.help(
"`#[suggestion_part(...)]` is only valid in multipart suggestions, use `#[primary_span]` instead",
)
});
invalid_attr(attr, &Meta::Path(path))
.help(
"`#[suggestion_part(...)]` is only valid in multipart suggestions, \
use `#[primary_span]` instead",
)
.emit();
}
Ok(quote! {})
}
"applicability" => {
if kind_stats.has_multipart_suggestion || kind_stats.has_normal_suggestion {
report_error_if_not_applied_to_applicability(attr, &info)?;
if kind_stats.all_applicabilities_static {
span_err(
span,
"`#[applicability]` has no effect if all `#[suggestion]`/\
`#[multipart_suggestion]` attributes have a static \
`applicability = \"...\"`",
)
.emit();
}
let binding = info.binding.binding.clone();
self.applicability.set_once((quote! { #binding }, span));
self.applicability.set_once(quote! { #binding }, span);
} else {
span_err(span, "`#[applicability]` is only valid on suggestions").emit();
}
Ok(quote! {})
}
_ => throw_invalid_attr!(attr, &Meta::Path(path), |diag| {
_ => {
let mut span_attrs = vec![];
if kind_stats.has_multipart_suggestion {
span_attrs.push("suggestion_part");
@ -524,11 +333,16 @@ impl<'a> SubdiagnosticDeriveBuilder<'a> {
if !kind_stats.all_multipart_suggestions {
span_attrs.push("primary_span")
}
diag.help(format!(
"only `{}`, `applicability` and `skip_arg` are valid field attributes",
span_attrs.join(", ")
))
}),
invalid_attr(attr, &Meta::Path(path))
.help(format!(
"only `{}`, `applicability` and `skip_arg` are valid field attributes",
span_attrs.join(", ")
))
.emit();
Ok(quote! {})
}
}
}
@ -577,7 +391,7 @@ impl<'a> SubdiagnosticDeriveBuilder<'a> {
match nested_name {
"code" => {
let formatted_str = self.build_format(&value.value(), value.span());
code.set_once((formatted_str, span));
code.set_once(formatted_str, span);
}
_ => throw_invalid_nested_attr!(attr, &nested_attr, |diag| {
diag.help("`code` is the only valid nested attribute")
@ -635,11 +449,7 @@ impl<'a> SubdiagnosticDeriveBuilder<'a> {
.map(|binding| self.generate_field_attr_code(binding, kind_stats))
.collect();
let span_field = self.span_field.as_ref().map(|(span, _)| span);
let applicability = self.applicability.take().map_or_else(
|| quote! { rustc_errors::Applicability::Unspecified },
|(applicability, _)| applicability,
);
let span_field = self.span_field.value_ref();
let diag = &self.diag;
let mut calls = TokenStream::new();
@ -647,7 +457,13 @@ impl<'a> SubdiagnosticDeriveBuilder<'a> {
let name = format_ident!("{}{}", if span_field.is_some() { "span_" } else { "" }, kind);
let message = quote! { rustc_errors::fluent::#slug };
let call = match kind {
SubdiagnosticKind::Suggestion { suggestion_kind, code } => {
SubdiagnosticKind::Suggestion { suggestion_kind, applicability, code } => {
let applicability = applicability
.value()
.map(|a| quote! { #a })
.or_else(|| self.applicability.take().value())
.unwrap_or_else(|| quote! { rustc_errors::Applicability::Unspecified });
if let Some(span) = span_field {
let style = suggestion_kind.to_suggestion_style();
@ -657,7 +473,13 @@ impl<'a> SubdiagnosticDeriveBuilder<'a> {
quote! { unreachable!(); }
}
}
SubdiagnosticKind::MultipartSuggestion { suggestion_kind } => {
SubdiagnosticKind::MultipartSuggestion { suggestion_kind, applicability } => {
let applicability = applicability
.value()
.map(|a| quote! { #a })
.or_else(|| self.applicability.take().value())
.unwrap_or_else(|| quote! { rustc_errors::Applicability::Unspecified });
if !self.has_suggestion_parts {
span_err(
self.span,

View file

@ -1,12 +1,18 @@
use crate::diagnostics::error::{span_err, throw_span_err, DiagnosticDeriveError};
use crate::diagnostics::error::{
span_err, throw_invalid_attr, throw_invalid_nested_attr, throw_span_err, DiagnosticDeriveError,
};
use proc_macro::Span;
use proc_macro2::TokenStream;
use quote::{format_ident, quote, ToTokens};
use std::collections::{BTreeSet, HashMap};
use std::fmt;
use std::str::FromStr;
use syn::{spanned::Spanned, Attribute, Meta, Type, TypeTuple};
use syn::{MetaList, MetaNameValue, NestedMeta, Path};
use synstructure::{BindingInfo, Structure};
use super::error::invalid_nested_attr;
/// Checks whether the type name of `ty` matches `name`.
///
/// Given some struct at `a::b::c::Foo`, this will return true for `c::Foo`, `b::c::Foo`, or
@ -172,13 +178,17 @@ pub(crate) struct FieldInfo<'a> {
/// Small helper trait for abstracting over `Option` fields that contain a value and a `Span`
/// for error reporting if they are set more than once.
pub(crate) trait SetOnce<T> {
fn set_once(&mut self, _: (T, Span));
fn set_once(&mut self, value: T, span: Span);
fn value(self) -> Option<T>;
fn value_ref(&self) -> Option<&T>;
}
impl<T> SetOnce<T> for Option<(T, Span)> {
fn set_once(&mut self, (value, span): (T, Span)) {
/// An [`Option<T>`] that keeps track of the span that caused it to be set; used with [`SetOnce`].
pub(super) type SpannedOption<T> = Option<(T, Span)>;
impl<T> SetOnce<T> for SpannedOption<T> {
fn set_once(&mut self, value: T, span: Span) {
match self {
None => {
*self = Some((value, span));
@ -194,6 +204,10 @@ impl<T> SetOnce<T> for Option<(T, Span)> {
fn value(self) -> Option<T> {
self.map(|(v, _)| v)
}
fn value_ref(&self) -> Option<&T> {
self.as_ref().map(|(v, _)| v)
}
}
pub(crate) trait HasFieldMap {
@ -303,6 +317,7 @@ pub(crate) trait HasFieldMap {
/// `Applicability` of a suggestion - mirrors `rustc_errors::Applicability` - and used to represent
/// the user's selection of applicability if specified in an attribute.
#[derive(Clone, Copy)]
pub(crate) enum Applicability {
MachineApplicable,
MaybeIncorrect,
@ -359,3 +374,250 @@ pub(crate) fn build_field_mapping<'a>(structure: &Structure<'a>) -> HashMap<Stri
fields_map
}
/// Possible styles for suggestion subdiagnostics.
#[derive(Clone, Copy)]
pub(super) enum SuggestionKind {
/// `#[suggestion]`
Normal,
/// `#[suggestion_short]`
Short,
/// `#[suggestion_hidden]`
Hidden,
/// `#[suggestion_verbose]`
Verbose,
}
impl FromStr for SuggestionKind {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"" => Ok(SuggestionKind::Normal),
"_short" => Ok(SuggestionKind::Short),
"_hidden" => Ok(SuggestionKind::Hidden),
"_verbose" => Ok(SuggestionKind::Verbose),
_ => Err(()),
}
}
}
impl SuggestionKind {
pub fn to_suggestion_style(&self) -> TokenStream {
match self {
SuggestionKind::Normal => {
quote! { rustc_errors::SuggestionStyle::ShowCode }
}
SuggestionKind::Short => {
quote! { rustc_errors::SuggestionStyle::HideCodeInline }
}
SuggestionKind::Hidden => {
quote! { rustc_errors::SuggestionStyle::HideCodeAlways }
}
SuggestionKind::Verbose => {
quote! { rustc_errors::SuggestionStyle::ShowAlways }
}
}
}
}
/// Types of subdiagnostics that can be created using attributes
#[derive(Clone)]
pub(super) enum SubdiagnosticKind {
/// `#[label(...)]`
Label,
/// `#[note(...)]`
Note,
/// `#[help(...)]`
Help,
/// `#[warning(...)]`
Warn,
/// `#[suggestion{,_short,_hidden,_verbose}]`
Suggestion {
suggestion_kind: SuggestionKind,
applicability: SpannedOption<Applicability>,
code: TokenStream,
},
/// `#[multipart_suggestion{,_short,_hidden,_verbose}]`
MultipartSuggestion {
suggestion_kind: SuggestionKind,
applicability: SpannedOption<Applicability>,
},
}
impl SubdiagnosticKind {
/// Constructs a `SubdiagnosticKind` from a field or type attribute such as `#[note]`,
/// `#[error(parser::add_paren)]` or `#[suggestion(code = "...")]`. Returns the
/// `SubdiagnosticKind` and the diagnostic slug, if specified.
pub(super) fn from_attr(
attr: &Attribute,
fields: &impl HasFieldMap,
) -> Result<(SubdiagnosticKind, Option<Path>), DiagnosticDeriveError> {
let span = attr.span().unwrap();
let name = attr.path.segments.last().unwrap().ident.to_string();
let name = name.as_str();
let meta = attr.parse_meta()?;
let mut kind = match name {
"label" => SubdiagnosticKind::Label,
"note" => SubdiagnosticKind::Note,
"help" => SubdiagnosticKind::Help,
"warning" => SubdiagnosticKind::Warn,
_ => {
if let Some(suggestion_kind) =
name.strip_prefix("suggestion").and_then(|s| s.parse().ok())
{
SubdiagnosticKind::Suggestion {
suggestion_kind,
applicability: None,
code: TokenStream::new(),
}
} else if let Some(suggestion_kind) =
name.strip_prefix("multipart_suggestion").and_then(|s| s.parse().ok())
{
SubdiagnosticKind::MultipartSuggestion { suggestion_kind, applicability: None }
} else {
throw_invalid_attr!(attr, &meta);
}
}
};
let nested = match meta {
Meta::List(MetaList { ref nested, .. }) => {
// An attribute with properties, such as `#[suggestion(code = "...")]` or
// `#[error(some::slug)]`
nested
}
Meta::Path(_) => {
// An attribute without a slug or other properties, such as `#[note]` - return
// without further processing.
//
// Only allow this if there are no mandatory properties, such as `code = "..."` in
// `#[suggestion(...)]`
match kind {
SubdiagnosticKind::Label
| SubdiagnosticKind::Note
| SubdiagnosticKind::Help
| SubdiagnosticKind::Warn
| SubdiagnosticKind::MultipartSuggestion { .. } => return Ok((kind, None)),
SubdiagnosticKind::Suggestion { .. } => {
throw_span_err!(span, "suggestion without `code = \"...\"`")
}
}
}
_ => {
throw_invalid_attr!(attr, &meta)
}
};
let mut code = None;
let mut nested_iter = nested.into_iter().peekable();
// Peek at the first nested attribute: if it's a slug path, consume it.
let slug = if let Some(NestedMeta::Meta(Meta::Path(path))) = nested_iter.peek() {
let path = path.clone();
// Advance the iterator.
nested_iter.next();
Some(path)
} else {
None
};
for nested_attr in nested_iter {
let meta = match nested_attr {
NestedMeta::Meta(ref meta) => meta,
NestedMeta::Lit(_) => {
invalid_nested_attr(attr, &nested_attr).emit();
continue;
}
};
let span = meta.span().unwrap();
let nested_name = meta.path().segments.last().unwrap().ident.to_string();
let nested_name = nested_name.as_str();
let value = match meta {
Meta::NameValue(MetaNameValue { lit: syn::Lit::Str(value), .. }) => value,
Meta::Path(_) => throw_invalid_nested_attr!(attr, &nested_attr, |diag| {
diag.help("a diagnostic slug must be the first argument to the attribute")
}),
_ => {
invalid_nested_attr(attr, &nested_attr).emit();
continue;
}
};
match (nested_name, &mut kind) {
("code", SubdiagnosticKind::Suggestion { .. }) => {
let formatted_str = fields.build_format(&value.value(), value.span());
code.set_once(formatted_str, span);
}
(
"applicability",
SubdiagnosticKind::Suggestion { ref mut applicability, .. }
| SubdiagnosticKind::MultipartSuggestion { ref mut applicability, .. },
) => {
let value = Applicability::from_str(&value.value()).unwrap_or_else(|()| {
span_err(span, "invalid applicability").emit();
Applicability::Unspecified
});
applicability.set_once(value, span);
}
// Invalid nested attribute
(_, SubdiagnosticKind::Suggestion { .. }) => {
invalid_nested_attr(attr, &nested_attr)
.help("only `code` and `applicability` are valid nested attributes")
.emit();
}
(_, SubdiagnosticKind::MultipartSuggestion { .. }) => {
invalid_nested_attr(attr, &nested_attr)
.help("only `applicability` is a valid nested attributes")
.emit()
}
_ => {
invalid_nested_attr(attr, &nested_attr).emit();
}
}
}
match kind {
SubdiagnosticKind::Suggestion { code: ref mut code_field, .. } => {
*code_field = if let Some((code, _)) = code {
code
} else {
span_err(span, "suggestion without `code = \"...\"`").emit();
quote! { "" }
}
}
SubdiagnosticKind::Label
| SubdiagnosticKind::Note
| SubdiagnosticKind::Help
| SubdiagnosticKind::Warn
| SubdiagnosticKind::MultipartSuggestion { .. } => {}
}
Ok((kind, slug))
}
}
impl quote::IdentFragment for SubdiagnosticKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SubdiagnosticKind::Label => write!(f, "label"),
SubdiagnosticKind::Note => write!(f, "note"),
SubdiagnosticKind::Help => write!(f, "help"),
SubdiagnosticKind::Warn => write!(f, "warn"),
SubdiagnosticKind::Suggestion { .. } => write!(f, "suggestion_with_style"),
SubdiagnosticKind::MultipartSuggestion { .. } => {
write!(f, "multipart_suggestion_with_style")
}
}
}
fn span(&self) -> Option<proc_macro2::Span> {
None
}
}

View file

@ -289,7 +289,7 @@ pub enum BadTypePlusSub {
#[diag(parser::maybe_recover_from_bad_qpath_stage_2)]
struct BadQPathStage2 {
#[primary_span]
#[suggestion(applicability = "maybe-incorrect")]
#[suggestion(code = "", applicability = "maybe-incorrect")]
span: Span,
ty: String,
}
@ -298,7 +298,7 @@ struct BadQPathStage2 {
#[diag(parser::incorrect_semicolon)]
struct IncorrectSemicolon<'a> {
#[primary_span]
#[suggestion_short(applicability = "machine-applicable")]
#[suggestion_short(code = "", applicability = "machine-applicable")]
span: Span,
#[help]
opt_help: Option<()>,
@ -309,7 +309,7 @@ struct IncorrectSemicolon<'a> {
#[diag(parser::incorrect_use_of_await)]
struct IncorrectUseOfAwait {
#[primary_span]
#[suggestion(parser::parentheses_suggestion, applicability = "machine-applicable")]
#[suggestion(parser::parentheses_suggestion, code = "", applicability = "machine-applicable")]
span: Span,
}
@ -329,7 +329,7 @@ struct IncorrectAwait {
struct InInTypo {
#[primary_span]
span: Span,
#[suggestion(applicability = "machine-applicable")]
#[suggestion(code = "", applicability = "machine-applicable")]
sugg_span: Span,
}

View file

@ -462,7 +462,7 @@ pub struct LinkSection {
pub struct NoMangleForeign {
#[label]
pub span: Span,
#[suggestion(applicability = "machine-applicable")]
#[suggestion(code = "", applicability = "machine-applicable")]
pub attr_span: Span,
pub foreign_item_kind: &'static str,
}
@ -596,7 +596,7 @@ pub enum UnusedNote {
#[derive(LintDiagnostic)]
#[diag(passes::unused)]
pub struct Unused {
#[suggestion(applicability = "machine-applicable")]
#[suggestion(code = "", applicability = "machine-applicable")]
pub attr_span: Span,
#[subdiagnostic]
pub note: UnusedNote,

View file

@ -1,6 +1,5 @@
use crate::{ImplTraitContext, Resolver};
use rustc_ast::visit::{self, FnKind};
use rustc_ast::walk_list;
use rustc_ast::*;
use rustc_expand::expand::AstFragment;
use rustc_hir::def_id::LocalDefId;
@ -148,8 +147,13 @@ impl<'a, 'b> visit::Visitor<'a> for DefCollector<'a, 'b> {
self.with_parent(return_impl_trait_id, |this| {
this.visit_fn_ret_ty(&sig.decl.output)
});
let closure_def = self.create_def(closure_id, DefPathData::ClosureExpr, span);
self.with_parent(closure_def, |this| walk_list!(this, visit_block, body));
// If this async fn has no body (i.e. it's an async fn signature in a trait)
// then the closure_def will never be used, and we should avoid generating a
// def-id for it.
if let Some(body) = body {
let closure_def = self.create_def(closure_id, DefPathData::ClosureExpr, span);
self.with_parent(closure_def, |this| this.visit_block(body));
}
return;
}
}