diff options
Diffstat (limited to 'compiler/rustc_ast_passes/src')
-rw-r--r-- | compiler/rustc_ast_passes/src/ast_validation.rs | 637 | ||||
-rw-r--r-- | compiler/rustc_ast_passes/src/errors.rs | 489 | ||||
-rw-r--r-- | compiler/rustc_ast_passes/src/feature_gate.rs | 111 | ||||
-rw-r--r-- | compiler/rustc_ast_passes/src/lib.rs | 8 | ||||
-rw-r--r-- | compiler/rustc_ast_passes/src/show_span.rs | 8 |
5 files changed, 744 insertions, 509 deletions
diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 902b4b1a1..2cc009410 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -13,7 +13,6 @@ use rustc_ast::walk_list; use rustc_ast::*; use rustc_ast_pretty::pprust::{self, State}; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::{error_code, fluent, pluralize, struct_span_err, Applicability}; use rustc_macros::Subdiagnostic; use rustc_parse::validate_attr; use rustc_session::lint::builtin::{ @@ -27,11 +26,10 @@ use rustc_span::Span; use rustc_target::spec::abi; use std::mem; use std::ops::{Deref, DerefMut}; +use thin_vec::thin_vec; -use crate::errors::*; - -const MORE_EXTERN: &str = - "for more information, visit https://doc.rust-lang.org/std/keyword.extern.html"; +use crate::errors; +use crate::fluent_generated as fluent; /// Is `self` allowed semantically as the first parameter in an `FnDecl`? enum SelfSemantic { @@ -69,10 +67,6 @@ struct AstValidator<'a> { /// or `Foo::Bar<impl Trait>` is_impl_trait_banned: bool, - /// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in - /// certain positions. - is_assoc_ty_bound_banned: bool, - /// See [ForbiddenLetReason] forbidden_let_reason: Option<ForbiddenLetReason>, @@ -136,9 +130,9 @@ impl<'a> AstValidator<'a> { fn ban_let_expr(&self, expr: &'a Expr, forbidden_let_reason: ForbiddenLetReason) { let sess = &self.session; if sess.opts.unstable_features.is_nightly_build() { - sess.emit_err(ForbiddenLet { span: expr.span, reason: forbidden_let_reason }); + sess.emit_err(errors::ForbiddenLet { span: expr.span, reason: forbidden_let_reason }); } else { - sess.emit_err(ForbiddenLetStable { span: expr.span }); + sess.emit_err(errors::ForbiddenLetStable { span: expr.span }); } } @@ -178,30 +172,12 @@ impl<'a> AstValidator<'a> { } } - fn with_banned_assoc_ty_bound(&mut self, f: impl FnOnce(&mut Self)) { - let old = mem::replace(&mut self.is_assoc_ty_bound_banned, true); - f(self); - self.is_assoc_ty_bound_banned = old; - } - fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) { let old = mem::replace(&mut self.outer_impl_trait, outer); f(self); self.outer_impl_trait = old; } - fn visit_assoc_constraint_from_generic_args(&mut self, constraint: &'a AssocConstraint) { - match constraint.kind { - AssocConstraintKind::Equality { .. } => {} - AssocConstraintKind::Bound { .. } => { - if self.is_assoc_ty_bound_banned { - self.session.emit_err(ForbiddenAssocConstraint { span: constraint.span }); - } - } - } - self.visit_assoc_constraint(constraint); - } - // Mirrors `visit::walk_ty`, but tracks relevant state. fn walk_ty(&mut self, t: &'a Ty) { match &t.kind { @@ -216,7 +192,7 @@ impl<'a> AstValidator<'a> { // We allow these: // - `Option<impl Trait>` // - `option::Option<impl Trait>` - // - `option::Option<T>::Foo<impl Trait> + // - `option::Option<T>::Foo<impl Trait>` // // But not these: // - `<impl Trait>::Foo` @@ -254,24 +230,24 @@ impl<'a> AstValidator<'a> { fn check_lifetime(&self, ident: Ident) { let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Empty]; if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() { - self.session.emit_err(KeywordLifetime { span: ident.span }); + self.session.emit_err(errors::KeywordLifetime { span: ident.span }); } } fn check_label(&self, ident: Ident) { if ident.without_first_quote().is_reserved() { - self.session.emit_err(InvalidLabel { span: ident.span, name: ident.name }); + self.session.emit_err(errors::InvalidLabel { span: ident.span, name: ident.name }); } } - fn invalid_visibility(&self, vis: &Visibility, note: Option<InvalidVisibilityNote>) { + fn invalid_visibility(&self, vis: &Visibility, note: Option<errors::InvalidVisibilityNote>) { if let VisibilityKind::Inherited = vis.kind { return; } - self.session.emit_err(InvalidVisibility { + self.session.emit_err(errors::InvalidVisibility { span: vis.span, - implied: if vis.kind.is_pub() { Some(vis.span) } else { None }, + implied: vis.kind.is_pub().then_some(vis.span), note, }); } @@ -290,28 +266,7 @@ impl<'a> AstValidator<'a> { fn check_trait_fn_not_const(&self, constness: Const) { if let Const::Yes(span) = constness { - self.session.emit_err(TraitFnConst { span }); - } - } - - fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) { - // Check only lifetime parameters are present and that the lifetime - // parameters that are present have no bounds. - let non_lt_param_spans: Vec<_> = params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - if !param.bounds.is_empty() { - let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect(); - self.session.emit_err(ForbiddenLifetimeBound { spans }); - } - None - } - _ => Some(param.ident.span), - }) - .collect(); - if !non_lt_param_spans.is_empty() { - self.session.emit_err(ForbiddenNonLifetimeParam { spans: non_lt_param_spans }); + self.session.emit_err(errors::TraitFnConst { span }); } } @@ -328,7 +283,7 @@ impl<'a> AstValidator<'a> { let max_num_args: usize = u16::MAX.into(); if fn_decl.inputs.len() > max_num_args { let Param { span, .. } = fn_decl.inputs[0]; - self.session.emit_fatal(FnParamTooMany { span, max_num_args }); + self.session.emit_fatal(errors::FnParamTooMany { span, max_num_args }); } } @@ -336,13 +291,13 @@ impl<'a> AstValidator<'a> { match &*fn_decl.inputs { [Param { ty, span, .. }] => { if let TyKind::CVarArgs = ty.kind { - self.session.emit_err(FnParamCVarArgsOnly { span: *span }); + self.session.emit_err(errors::FnParamCVarArgsOnly { span: *span }); } } [ps @ .., _] => { for Param { ty, span, .. } in ps { if let TyKind::CVarArgs = ty.kind { - self.session.emit_err(FnParamCVarArgsNotLast { span: *span }); + self.session.emit_err(errors::FnParamCVarArgsNotLast { span: *span }); } } } @@ -369,9 +324,9 @@ impl<'a> AstValidator<'a> { }) .for_each(|attr| { if attr.is_doc_comment() { - self.session.emit_err(FnParamDocComment { span: attr.span }); + self.session.emit_err(errors::FnParamDocComment { span: attr.span }); } else { - self.session.emit_err(FnParamForbiddenAttr { span: attr.span }); + self.session.emit_err(errors::FnParamForbiddenAttr { span: attr.span }); } }); } @@ -379,7 +334,7 @@ impl<'a> AstValidator<'a> { fn check_decl_self_param(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) { if let (SelfSemantic::No, [param, ..]) = (self_semantic, &*fn_decl.inputs) { if param.is_self() { - self.session.emit_err(FnParamForbiddenSelf { span: param.span }); + self.session.emit_err(errors::FnParamForbiddenSelf { span: param.span }); } } } @@ -387,7 +342,7 @@ impl<'a> AstValidator<'a> { fn check_defaultness(&self, span: Span, defaultness: Defaultness) { if let Defaultness::Default(def_span) = defaultness { let span = self.session.source_map().guess_head_span(span); - self.session.emit_err(ForbiddenDefault { span, def_span }); + self.session.emit_err(errors::ForbiddenDefault { span, def_span }); } } @@ -410,27 +365,17 @@ impl<'a> AstValidator<'a> { [b0] => b0.span(), [b0, .., bl] => b0.span().to(bl.span()), }; - self.err_handler() - .struct_span_err(span, &format!("bounds on `type`s in {} have no effect", ctx)) - .emit(); + self.err_handler().emit_err(errors::BoundInContext { span, ctx }); } fn check_foreign_ty_genericless(&self, generics: &Generics, where_span: Span) { let cannot_have = |span, descr, remove_descr| { - self.err_handler() - .struct_span_err( - span, - &format!("`type`s inside `extern` blocks cannot have {}", descr), - ) - .span_suggestion( - span, - &format!("remove the {}", remove_descr), - "", - Applicability::MaybeIncorrect, - ) - .span_label(self.current_extern_span(), "`extern` block begins here") - .note(MORE_EXTERN) - .emit(); + self.err_handler().emit_err(errors::ExternTypesCannotHave { + span, + descr, + remove_descr, + block_span: self.current_extern_span(), + }); }; if !generics.params.is_empty() { @@ -446,20 +391,12 @@ impl<'a> AstValidator<'a> { let Some(body) = body else { return; }; - self.err_handler() - .struct_span_err(ident.span, &format!("incorrect `{}` inside `extern` block", kind)) - .span_label(ident.span, "cannot have a body") - .span_label(body, "the invalid body") - .span_label( - self.current_extern_span(), - format!( - "`extern` blocks define existing foreign {0}s and {0}s \ - inside of them cannot have a body", - kind - ), - ) - .note(MORE_EXTERN) - .emit(); + self.err_handler().emit_err(errors::BodyInExtern { + span: ident.span, + body, + block: self.current_extern_span(), + kind, + }); } /// An `fn` in `extern { ... }` cannot have a body `{ ... }`. @@ -467,26 +404,11 @@ impl<'a> AstValidator<'a> { let Some(body) = body else { return; }; - self.err_handler() - .struct_span_err(ident.span, "incorrect function inside `extern` block") - .span_label(ident.span, "cannot have a body") - .span_suggestion( - body.span, - "remove the invalid body", - ";", - Applicability::MaybeIncorrect, - ) - .help( - "you might have meant to write a function accessible through FFI, \ - which can be done by writing `extern fn` outside of the `extern` block", - ) - .span_label( - self.current_extern_span(), - "`extern` blocks define existing foreign functions and functions \ - inside of them cannot have a body", - ) - .note(MORE_EXTERN) - .emit(); + self.err_handler().emit_err(errors::FnBodyInExtern { + span: ident.span, + body: body.span, + block: self.current_extern_span(), + }); } fn current_extern_span(&self) -> Span { @@ -496,34 +418,21 @@ impl<'a> AstValidator<'a> { /// An `fn` in `extern { ... }` cannot have qualifiers, e.g. `async fn`. fn check_foreign_fn_headerless(&self, ident: Ident, span: Span, header: FnHeader) { if header.has_qualifiers() { - self.err_handler() - .struct_span_err(ident.span, "functions in `extern` blocks cannot have qualifiers") - .span_label(self.current_extern_span(), "in this `extern` block") - .span_suggestion_verbose( - span.until(ident.span.shrink_to_lo()), - "remove the qualifiers", - "fn ", - Applicability::MaybeIncorrect, - ) - .emit(); + self.err_handler().emit_err(errors::FnQualifierInExtern { + span: ident.span, + block: self.current_extern_span(), + sugg_span: span.until(ident.span.shrink_to_lo()), + }); } } /// An item in `extern { ... }` cannot use non-ascii identifier. fn check_foreign_item_ascii_only(&self, ident: Ident) { if !ident.as_str().is_ascii() { - let n = 83942; - self.err_handler() - .struct_span_err( - ident.span, - "items in `extern` blocks cannot use non-ascii identifiers", - ) - .span_label(self.current_extern_span(), "in this `extern` block") - .note(&format!( - "this limitation may be lifted in the future; see issue #{} <https://github.com/rust-lang/rust/issues/{}> for more information", - n, n, - )) - .emit(); + self.err_handler().emit_err(errors::ExternItemAscii { + span: ident.span, + block: self.current_extern_span(), + }); } } @@ -546,12 +455,7 @@ impl<'a> AstValidator<'a> { for Param { ty, span, .. } in &fk.decl().inputs { if let TyKind::CVarArgs = ty.kind { - self.err_handler() - .struct_span_err( - *span, - "only foreign or `unsafe extern \"C\"` functions may be C-variadic", - ) - .emit(); + self.err_handler().emit_err(errors::BadCVariadic { span: *span }); } } } @@ -560,75 +464,32 @@ impl<'a> AstValidator<'a> { if ident.name != kw::Underscore { return; } - self.err_handler() - .struct_span_err(ident.span, &format!("`{}` items in this context need a name", kind)) - .span_label(ident.span, format!("`_` is not a valid name for this `{}` item", kind)) - .emit(); + self.err_handler().emit_err(errors::ItemUnderscore { span: ident.span, kind }); } fn check_nomangle_item_asciionly(&self, ident: Ident, item_span: Span) { if ident.name.as_str().is_ascii() { return; } - let head_span = self.session.source_map().guess_head_span(item_span); - struct_span_err!( - self.session, - head_span, - E0754, - "`#[no_mangle]` requires ASCII identifier" - ) - .emit(); + let span = self.session.source_map().guess_head_span(item_span); + self.session.emit_err(errors::NoMangleAscii { span }); } fn check_mod_file_item_asciionly(&self, ident: Ident) { if ident.name.as_str().is_ascii() { return; } - struct_span_err!( - self.session, - ident.span, - E0754, - "trying to load file for module `{}` with non-ascii identifier name", - ident.name - ) - .help("consider using `#[path]` attribute to specify filesystem path") - .emit(); + self.session.emit_err(errors::ModuleNonAscii { span: ident.span, name: ident.name }); } - fn deny_generic_params(&self, generics: &Generics, ident_span: Span) { + fn deny_generic_params(&self, generics: &Generics, ident: Span) { if !generics.params.is_empty() { - struct_span_err!( - self.session, - generics.span, - E0567, - "auto traits cannot have generic parameters" - ) - .span_label(ident_span, "auto trait cannot have generic parameters") - .span_suggestion( - generics.span, - "remove the parameters", - "", - Applicability::MachineApplicable, - ) - .emit(); + self.session.emit_err(errors::AutoTraitGeneric { span: generics.span, ident }); } } - fn emit_e0568(&self, span: Span, ident_span: Span) { - struct_span_err!( - self.session, - span, - E0568, - "auto traits cannot have super traits or lifetime bounds" - ) - .span_label(ident_span, "auto trait cannot have super traits or lifetime bounds") - .span_suggestion( - span, - "remove the super traits or lifetime bounds", - "", - Applicability::MachineApplicable, - ) - .emit(); + fn emit_e0568(&self, span: Span, ident: Span) { + self.session.emit_err(errors::AutoTraitBounds { span, ident }); } fn deny_super_traits(&self, bounds: &GenericBounds, ident_span: Span) { @@ -644,24 +505,11 @@ impl<'a> AstValidator<'a> { } } - fn deny_items(&self, trait_items: &[P<AssocItem>], ident_span: Span) { + fn deny_items(&self, trait_items: &[P<AssocItem>], ident: Span) { if !trait_items.is_empty() { let spans: Vec<_> = trait_items.iter().map(|i| i.ident.span).collect(); - let total_span = trait_items.first().unwrap().span.to(trait_items.last().unwrap().span); - struct_span_err!( - self.session, - spans, - E0380, - "auto traits cannot have associated items" - ) - .span_suggestion( - total_span, - "remove these associated items", - "", - Applicability::MachineApplicable, - ) - .span_label(ident_span, "auto trait cannot have associated items") - .emit(); + let total = trait_items.first().unwrap().span.to(trait_items.last().unwrap().span); + self.session.emit_err(errors::AutoTraitItems { spans, total, ident }); } } @@ -707,29 +555,17 @@ impl<'a> AstValidator<'a> { let args_len = arg_spans.len(); let constraint_len = constraint_spans.len(); // ...and then error: - self.err_handler() - .struct_span_err( - arg_spans.clone(), - "generic arguments must come before the first constraint", - ) - .span_label(constraint_spans[0], &format!("constraint{}", pluralize!(constraint_len))) - .span_label( - *arg_spans.iter().last().unwrap(), - &format!("generic argument{}", pluralize!(args_len)), - ) - .span_labels(constraint_spans, "") - .span_labels(arg_spans, "") - .span_suggestion_verbose( - data.span, - &format!( - "move the constraint{} after the generic argument{}", - pluralize!(constraint_len), - pluralize!(args_len) - ), - self.correct_generic_order_suggestion(&data), - Applicability::MachineApplicable, - ) - .emit(); + self.err_handler().emit_err(errors::ArgsBeforeConstraint { + arg_spans: arg_spans.clone(), + constraints: constraint_spans[0], + args: *arg_spans.iter().last().unwrap(), + data: data.span, + constraint_spans: errors::EmptyLabelManySpans(constraint_spans), + arg_spans2: errors::EmptyLabelManySpans(arg_spans), + suggestion: self.correct_generic_order_suggestion(&data), + constraint_len, + args_len, + }); } fn visit_ty_common(&mut self, ty: &'a Ty) { @@ -737,15 +573,8 @@ impl<'a> AstValidator<'a> { TyKind::BareFn(bfty) => { self.check_fn_decl(&bfty.decl, SelfSemantic::No); Self::check_decl_no_pat(&bfty.decl, |span, _, _| { - struct_span_err!( - self.session, - span, - E0561, - "patterns aren't allowed in function pointer types" - ) - .emit(); + self.session.emit_err(errors::PatternFnPointer { span }); }); - self.check_late_bound_lifetime_defs(&bfty.generic_params); if let Extern::Implicit(_) = bfty.ext { let sig_span = self.session.source_map().next_point(ty.span.shrink_to_lo()); self.maybe_lint_missing_abi(sig_span, ty.id); @@ -756,13 +585,8 @@ impl<'a> AstValidator<'a> { for bound in bounds { if let GenericBound::Outlives(lifetime) = bound { if any_lifetime_bounds { - struct_span_err!( - self.session, - lifetime.ident.span, - E0226, - "only a single explicit lifetime bound is permitted" - ) - .emit(); + self.session + .emit_err(errors::TraitObjectBound { span: lifetime.ident.span }); break; } any_lifetime_bounds = true; @@ -771,29 +595,19 @@ impl<'a> AstValidator<'a> { } TyKind::ImplTrait(_, bounds) => { if self.is_impl_trait_banned { - struct_span_err!( - self.session, - ty.span, - E0667, - "`impl Trait` is not allowed in path parameters" - ) - .emit(); + self.session.emit_err(errors::ImplTraitPath { span: ty.span }); } if let Some(outer_impl_trait_sp) = self.outer_impl_trait { - struct_span_err!( - self.session, - ty.span, - E0666, - "nested `impl Trait` is not allowed" - ) - .span_label(outer_impl_trait_sp, "outer `impl Trait`") - .span_label(ty.span, "nested `impl Trait` here") - .emit(); + self.session.emit_err(errors::NestedImplTrait { + span: ty.span, + outer: outer_impl_trait_sp, + inner: ty.span, + }); } if !bounds.iter().any(|b| matches!(b, GenericBound::Trait(..))) { - self.err_handler().span_err(ty.span, "at least one trait must be specified"); + self.err_handler().emit_err(errors::AtLeastOneTrait { span: ty.span }); } } _ => {} @@ -814,7 +628,7 @@ impl<'a> AstValidator<'a> { MISSING_ABI, id, span, - "extern declarations without an explicit ABI are deprecated", + fluent::ast_passes_extern_without_abi, BuiltinLintDiagnostics::MissingAbi(span, abi::Abi::FALLBACK), ) } @@ -887,20 +701,13 @@ fn validate_generic_param_order( ordered_params += ">"; for (param_ord, (max_param, spans)) in &out_of_order { - let mut err = handler.struct_span_err( - spans.clone(), - &format!( - "{} parameters must be declared prior to {} parameters", - param_ord, max_param, - ), - ); - err.span_suggestion( - span, - "reorder the parameters: lifetimes, then consts and types", - &ordered_params, - Applicability::MachineApplicable, - ); - err.emit(); + handler.emit_err(errors::OutOfOrderParams { + spans: spans.clone(), + sugg_span: span, + param_ord, + max_param, + ordered_params: &ordered_params, + }); } } } @@ -1014,25 +821,15 @@ impl<'a> Visitor<'a> for AstValidator<'a> { self.with_in_trait_impl(true, Some(*constness), |this| { this.invalid_visibility(&item.vis, None); if let TyKind::Err = self_ty.kind { - this.err_handler() - .struct_span_err( - item.span, - "`impl Trait for .. {}` is an obsolete syntax", - ) - .help("use `auto trait Trait {}` instead") - .emit(); + this.err_handler().emit_err(errors::ObsoleteAuto { span: item.span }); } if let (&Unsafe::Yes(span), &ImplPolarity::Negative(sp)) = (unsafety, polarity) { - struct_span_err!( - this.session, - sp.to(t.path.span), - E0198, - "negative impls cannot be unsafe" - ) - .span_label(sp, "negative because of this") - .span_label(span, "unsafe because of this") - .emit(); + this.session.emit_err(errors::UnsafeNegativeImpl { + span: sp.to(t.path.span), + negative: sp, + r#unsafe: span, + }); } this.visit_vis(&item.vis); @@ -1060,52 +857,54 @@ impl<'a> Visitor<'a> for AstValidator<'a> { self_ty, items: _, }) => { - let error = |annotation_span, annotation| { - let mut err = self.err_handler().struct_span_err( - self_ty.span, - &format!("inherent impls cannot be {}", annotation), - ); - err.span_label(annotation_span, &format!("{} because of this", annotation)); - err.span_label(self_ty.span, "inherent impl for this type"); - err - }; + let error = + |annotation_span, annotation, only_trait: bool| errors::InherentImplCannot { + span: self_ty.span, + annotation_span, + annotation, + self_ty: self_ty.span, + only_trait: only_trait.then_some(()), + }; self.invalid_visibility( &item.vis, - Some(InvalidVisibilityNote::IndividualImplItems), + Some(errors::InvalidVisibilityNote::IndividualImplItems), ); if let &Unsafe::Yes(span) = unsafety { - error(span, "unsafe").code(error_code!(E0197)).emit(); + self.err_handler().emit_err(errors::InherentImplCannotUnsafe { + span: self_ty.span, + annotation_span: span, + annotation: "unsafe", + self_ty: self_ty.span, + }); } if let &ImplPolarity::Negative(span) = polarity { - error(span, "negative").emit(); + self.err_handler().emit_err(error(span, "negative", false)); } if let &Defaultness::Default(def_span) = defaultness { - error(def_span, "`default`") - .note("only trait implementations may be annotated with `default`") - .emit(); + self.err_handler().emit_err(error(def_span, "`default`", true)); } if let &Const::Yes(span) = constness { - error(span, "`const`") - .note("only trait implementations may be annotated with `const`") - .emit(); + self.err_handler().emit_err(error(span, "`const`", true)); } } ItemKind::Fn(box Fn { defaultness, sig, generics, body }) => { self.check_defaultness(item.span, *defaultness); if body.is_none() { - self.session.emit_err(FnWithoutBody { + self.session.emit_err(errors::FnWithoutBody { span: item.span, replace_span: self.ending_semi_or_hi(item.span), extern_block_suggestion: match sig.header.ext { Extern::None => None, - Extern::Implicit(start_span) => Some(ExternBlockSuggestion::Implicit { - start_span, - end_span: item.span.shrink_to_hi(), - }), + Extern::Implicit(start_span) => { + Some(errors::ExternBlockSuggestion::Implicit { + start_span, + end_span: item.span.shrink_to_hi(), + }) + } Extern::Explicit(abi, start_span) => { - Some(ExternBlockSuggestion::Explicit { + Some(errors::ExternBlockSuggestion::Explicit { start_span, end_span: item.span.shrink_to_hi(), abi: abi.symbol_unescaped, @@ -1127,10 +926,10 @@ impl<'a> Visitor<'a> for AstValidator<'a> { let old_item = mem::replace(&mut self.extern_mod, Some(item)); self.invalid_visibility( &item.vis, - Some(InvalidVisibilityNote::IndividualForeignItems), + Some(errors::InvalidVisibilityNote::IndividualForeignItems), ); if let &Unsafe::Yes(span) = unsafety { - self.err_handler().span_err(span, "extern block cannot be declared unsafe"); + self.err_handler().emit_err(errors::UnsafeItem { span, kind: "extern block" }); } if abi.is_none() { self.maybe_lint_missing_abi(item.span, item.id); @@ -1170,7 +969,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } ItemKind::Mod(unsafety, mod_kind) => { if let &Unsafe::Yes(span) = unsafety { - self.err_handler().span_err(span, "module cannot be declared unsafe"); + self.err_handler().emit_err(errors::UnsafeItem { span, kind: "module" }); } // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584). if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _)) @@ -1181,18 +980,18 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } ItemKind::Union(vdata, ..) => { if vdata.fields().is_empty() { - self.err_handler().span_err(item.span, "unions cannot have zero fields"); + self.err_handler().emit_err(errors::FieldlessUnion { span: item.span }); } } ItemKind::Const(def, .., None) => { self.check_defaultness(item.span, *def); - self.session.emit_err(ConstWithoutBody { + self.session.emit_err(errors::ConstWithoutBody { span: item.span, replace_span: self.ending_semi_or_hi(item.span), }); } ItemKind::Static(.., None) => { - self.session.emit_err(StaticWithoutBody { + self.session.emit_err(errors::StaticWithoutBody { span: item.span, replace_span: self.ending_semi_or_hi(item.span), }); @@ -1200,21 +999,15 @@ impl<'a> Visitor<'a> for AstValidator<'a> { ItemKind::TyAlias(box TyAlias { defaultness, where_clauses, bounds, ty, .. }) => { self.check_defaultness(item.span, *defaultness); if ty.is_none() { - self.session.emit_err(TyAliasWithoutBody { + self.session.emit_err(errors::TyAliasWithoutBody { span: item.span, replace_span: self.ending_semi_or_hi(item.span), }); } self.check_type_no_bounds(bounds, "this context"); if where_clauses.1.0 { - let mut err = self.err_handler().struct_span_err( - where_clauses.1.1, - "where clauses are not allowed after the type for type aliases", - ); - err.note( - "see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information", - ); - err.emit(); + self.err_handler() + .emit_err(errors::WhereAfterTypeAlias { span: where_clauses.1.1 }); } } _ => {} @@ -1268,7 +1061,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { // are allowed to contain nested `impl Trait`. AngleBracketedArg::Constraint(constraint) => { self.with_impl_trait(None, |this| { - this.visit_assoc_constraint_from_generic_args(constraint); + this.visit_assoc_constraint(constraint); }); } } @@ -1296,11 +1089,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { if let Some(span) = prev_param_default { - let mut err = self.err_handler().struct_span_err( - span, - "generic parameters with a default must be trailing", - ); - err.emit(); + self.err_handler().emit_err(errors::GenericDefaultTrailing { span }); break; } } @@ -1318,9 +1107,6 @@ impl<'a> Visitor<'a> for AstValidator<'a> { for predicate in &generics.where_clause.predicates { match predicate { WherePredicate::BoundPredicate(bound_pred) => { - // A type binding, eg `for<'c> Foo: Send+Clone+'c` - self.check_late_bound_lifetime_defs(&bound_pred.bound_generic_params); - // This is slightly complicated. Our representation for poly-trait-refs contains a single // binder and thus we only allow a single level of quantification. However, // the syntax of Rust permits quantification in two places in where clauses, @@ -1331,13 +1117,8 @@ impl<'a> Visitor<'a> for AstValidator<'a> { match bound { GenericBound::Trait(t, _) => { if !t.bound_generic_params.is_empty() { - struct_span_err!( - self.err_handler(), - t.span, - E0316, - "nested quantification of lifetimes" - ) - .emit(); + self.err_handler() + .emit_err(errors::NestedLifetimes { span: t.span }); } } GenericBound::Outlives(_) => {} @@ -1362,32 +1143,27 @@ impl<'a> Visitor<'a> for AstValidator<'a> { if let GenericBound::Trait(poly, modify) = bound { match (ctxt, modify) { (BoundKind::SuperTraits, TraitBoundModifier::Maybe) => { - let mut err = self - .err_handler() - .struct_span_err(poly.span, "`?Trait` is not permitted in supertraits"); - let path_str = pprust::path_to_string(&poly.trait_ref.path); - err.note(&format!("traits are `?{}` by default", path_str)); - err.emit(); + self.err_handler().emit_err(errors::OptionalTraitSupertrait { + span: poly.span, + path_str: pprust::path_to_string(&poly.trait_ref.path) + }); } (BoundKind::TraitObject, TraitBoundModifier::Maybe) => { - let mut err = self.err_handler().struct_span_err( - poly.span, - "`?Trait` is not permitted in trait object types", - ); - err.emit(); + self.err_handler().emit_err(errors::OptionalTraitObject {span: poly.span}); } (_, TraitBoundModifier::MaybeConst) if let Some(reason) = &self.disallow_tilde_const => { - let mut err = self.err_handler().struct_span_err(bound.span(), "`~const` is not allowed here"); - match reason { - DisallowTildeConstContext::TraitObject => err.note("trait objects cannot have `~const` trait bounds"), - DisallowTildeConstContext::Fn(FnKind::Closure(..)) => err.note("closures cannot have `~const` trait bounds"), - DisallowTildeConstContext::Fn(FnKind::Fn(_, ident, ..)) => err.span_note(ident.span, "this function is not `const`, so it cannot have `~const` trait bounds"), + let reason = match reason { + DisallowTildeConstContext::TraitObject => errors::TildeConstReason::TraitObject, + DisallowTildeConstContext::Fn(FnKind::Closure(..)) => errors::TildeConstReason::Closure, + DisallowTildeConstContext::Fn(FnKind::Fn(_, ident, ..)) => errors::TildeConstReason::Function { ident: ident.span }, }; - err.emit(); + self.err_handler().emit_err(errors::TildeConstDisallowed { + span: bound.span(), + reason + }); } (_, TraitBoundModifier::MaybeConstMaybe) => { - self.err_handler() - .span_err(bound.span(), "`~const` and `?` are mutually exclusive"); + self.err_handler().emit_err(errors::OptionalConstExclusive {span: bound.span()}); } _ => {} } @@ -1396,19 +1172,6 @@ impl<'a> Visitor<'a> for AstValidator<'a> { visit::walk_param_bound(self, bound) } - fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef) { - self.check_late_bound_lifetime_defs(&t.bound_generic_params); - visit::walk_poly_trait_ref(self, t); - } - - fn visit_variant_data(&mut self, s: &'a VariantData) { - self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s)) - } - - fn visit_enum_def(&mut self, enum_definition: &'a EnumDef) { - self.with_banned_assoc_ty_bound(|this| visit::walk_enum_def(this, enum_definition)) - } - fn visit_fn(&mut self, fk: FnKind<'a>, span: Span, id: NodeId) { // Only associated `fn`s can have `self` parameters. let self_semantic = match fk.ctxt() { @@ -1420,25 +1183,18 @@ impl<'a> Visitor<'a> for AstValidator<'a> { self.check_c_variadic_type(fk); // Functions cannot both be `const async` - if let Some(FnHeader { + if let Some(&FnHeader { constness: Const::Yes(cspan), asyncness: Async::Yes { span: aspan, .. }, .. }) = fk.header() { - self.err_handler() - .struct_span_err( - vec![*cspan, *aspan], - "functions cannot be both `const` and `async`", - ) - .span_label(*cspan, "`const` because of this") - .span_label(*aspan, "`async` because of this") - .span_label(span, "") // Point at the fn header. - .emit(); - } - - if let FnKind::Closure(ClosureBinder::For { generic_params, .. }, ..) = fk { - self.check_late_bound_lifetime_defs(generic_params); + self.err_handler().emit_err(errors::ConstAndAsync { + spans: vec![cspan, aspan], + cspan, + aspan, + span, + }); } if let FnKind::Fn( @@ -1456,20 +1212,12 @@ impl<'a> Visitor<'a> for AstValidator<'a> { // Functions without bodies cannot have patterns. if let FnKind::Fn(ctxt, _, sig, _, _, None) = fk { Self::check_decl_no_pat(&sig.decl, |span, ident, mut_ident| { - let (code, msg, label) = match ctxt { - FnCtxt::Foreign => ( - error_code!(E0130), - "patterns aren't allowed in foreign function declarations", - "pattern not allowed in foreign function", - ), - _ => ( - error_code!(E0642), - "patterns aren't allowed in functions without bodies", - "pattern not allowed in function without body", - ), - }; if mut_ident && matches!(ctxt, FnCtxt::Assoc(_)) { if let Some(ident) = ident { + let msg = match ctxt { + FnCtxt::Foreign => fluent::ast_passes_pattern_in_foreign, + _ => fluent::ast_passes_pattern_in_bodiless, + }; let diag = BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident); self.lint_buffer.buffer_lint_with_diagnostic( PATTERNS_IN_FNS_WITHOUT_BODY, @@ -1480,11 +1228,12 @@ impl<'a> Visitor<'a> for AstValidator<'a> { ) } } else { - self.err_handler() - .struct_span_err(span, msg) - .span_label(span, label) - .code(code) - .emit(); + match ctxt { + FnCtxt::Foreign => { + self.err_handler().emit_err(errors::PatternInForeign { span }) + } + _ => self.err_handler().emit_err(errors::PatternInBodiless { span }), + }; } }); } @@ -1511,7 +1260,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { match &item.kind { AssocItemKind::Const(_, _, body) => { if body.is_none() { - self.session.emit_err(AssocConstWithoutBody { + self.session.emit_err(errors::AssocConstWithoutBody { span: item.span, replace_span: self.ending_semi_or_hi(item.span), }); @@ -1519,7 +1268,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } AssocItemKind::Fn(box Fn { body, .. }) => { if body.is_none() { - self.session.emit_err(AssocFnWithoutBody { + self.session.emit_err(errors::AssocFnWithoutBody { span: item.span, replace_span: self.ending_semi_or_hi(item.span), }); @@ -1534,7 +1283,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { .. }) => { if ty.is_none() { - self.session.emit_err(AssocTypeWithoutBody { + self.session.emit_err(errors::AssocTypeWithoutBody { span: item.span, replace_span: self.ending_semi_or_hi(item.span), }); @@ -1606,11 +1355,7 @@ fn deny_equality_constraints( predicate: &WhereEqPredicate, generics: &Generics, ) { - let mut err = this.err_handler().struct_span_err( - predicate.span, - "equality constraints are not yet supported in `where` clauses", - ); - err.span_label(predicate.span, "not supported"); + let mut err = errors::EqualityInWhere { span: predicate.span, assoc: None, assoc2: None }; // Given `<A as Foo>::Bar = RhsTy`, suggest `A: Foo<Bar = RhsTy>`. if let TyKind::Path(Some(qself), full_path) = &predicate.lhs_ty.kind { @@ -1649,25 +1394,17 @@ fn deny_equality_constraints( empty_args => { *empty_args = AngleBracketedArgs { span: ident.span, - args: vec![arg], + args: thin_vec![arg], } .into(); } } - err.span_suggestion_verbose( - predicate.span, - &format!( - "if `{}` is an associated type you're trying to set, \ - use the associated type binding syntax", - ident - ), - format!( - "{}: {}", - param, - pprust::path_to_string(&assoc_path) - ), - Applicability::MaybeIncorrect, - ); + err.assoc = Some(errors::AssociatedSuggestion { + span: predicate.span, + ident: *ident, + param: *param, + path: pprust::path_to_string(&assoc_path), + }) } _ => {} }; @@ -1709,15 +1446,13 @@ fn deny_equality_constraints( trait_segment.span().shrink_to_hi(), ), }; - err.multipart_suggestion( - &format!( - "if `{}::{}` is an associated type you're trying to set, \ - use the associated type binding syntax", - trait_segment.ident, potential_assoc.ident, - ), - vec![(span, args), (predicate.span, String::new())], - Applicability::MaybeIncorrect, - ); + err.assoc2 = Some(errors::AssociatedSuggestion2 { + span, + args, + predicate: predicate.span, + trait_segment: trait_segment.ident, + potential_assoc: potential_assoc.ident, + }); } } } @@ -1725,10 +1460,7 @@ fn deny_equality_constraints( } } } - err.note( - "see issue #20041 <https://github.com/rust-lang/rust/issues/20041> for more information", - ); - err.emit(); + this.err_handler().emit_err(err); } pub fn check_crate(session: &Session, krate: &Crate, lints: &mut LintBuffer) -> bool { @@ -1741,7 +1473,6 @@ pub fn check_crate(session: &Session, krate: &Crate, lints: &mut LintBuffer) -> outer_impl_trait: None, disallow_tilde_const: None, is_impl_trait_banned: false, - is_assoc_ty_bound_banned: false, forbidden_let_reason: Some(ForbiddenLetReason::GenericForbidden), lint_buffer: lints, }; @@ -1756,12 +1487,12 @@ pub(crate) enum ForbiddenLetReason { /// `let` is not valid and the source environment is not important GenericForbidden, /// A let chain with the `||` operator - #[note(not_supported_or)] + #[note(ast_passes_not_supported_or)] NotSupportedOr(#[primary_span] Span), /// A let chain with invalid parentheses /// /// For example, `let 1 = 1 && (expr && expr)` is allowed /// but `(let 1 = 1 && (let 1 = 1 && (let 1 = 1))) && let a = 1` is not - #[note(not_supported_parentheses)] + #[note(ast_passes_not_supported_parentheses)] NotSupportedParentheses(#[primary_span] Span), } diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 09e262452..d007097d9 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -1,9 +1,12 @@ //! Errors emitted by ast_passes. +use rustc_ast::ParamKindOrd; +use rustc_errors::AddToDiagnostic; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_span::{Span, Symbol}; +use rustc_span::{symbol::Ident, Span, Symbol}; use crate::ast_validation::ForbiddenLetReason; +use crate::fluent_generated as fluent; #[derive(Diagnostic)] #[diag(ast_passes_forbidden_let)] @@ -24,13 +27,6 @@ pub struct ForbiddenLetStable { } #[derive(Diagnostic)] -#[diag(ast_passes_forbidden_assoc_constraint)] -pub struct ForbiddenAssocConstraint { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] #[diag(ast_passes_keyword_lifetime)] pub struct KeywordLifetime { #[primary_span] @@ -50,7 +46,7 @@ pub struct InvalidLabel { pub struct InvalidVisibility { #[primary_span] pub span: Span, - #[label(implied)] + #[label(ast_passes_implied)] pub implied: Option<Span>, #[subdiagnostic] pub note: Option<InvalidVisibilityNote>, @@ -58,9 +54,9 @@ pub struct InvalidVisibility { #[derive(Subdiagnostic)] pub enum InvalidVisibilityNote { - #[note(individual_impl_items)] + #[note(ast_passes_individual_impl_items)] IndividualImplItems, - #[note(individual_foreign_items)] + #[note(ast_passes_individual_foreign_items)] IndividualForeignItems, } @@ -224,3 +220,474 @@ pub enum ExternBlockSuggestion { abi: Symbol, }, } + +#[derive(Diagnostic)] +#[diag(ast_passes_bound_in_context)] +pub struct BoundInContext<'a> { + #[primary_span] + pub span: Span, + pub ctx: &'a str, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_extern_types_cannot)] +#[note(ast_passes_extern_keyword_link)] +pub struct ExternTypesCannotHave<'a> { + #[primary_span] + #[suggestion(code = "", applicability = "maybe-incorrect")] + pub span: Span, + pub descr: &'a str, + pub remove_descr: &'a str, + #[label] + pub block_span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_body_in_extern)] +#[note(ast_passes_extern_keyword_link)] +pub struct BodyInExtern<'a> { + #[primary_span] + #[label(ast_passes_cannot_have)] + pub span: Span, + #[label(ast_passes_invalid)] + pub body: Span, + #[label(ast_passes_existing)] + pub block: Span, + pub kind: &'a str, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_fn_body_extern)] +#[help] +#[note(ast_passes_extern_keyword_link)] +pub struct FnBodyInExtern { + #[primary_span] + #[label(ast_passes_cannot_have)] + pub span: Span, + #[suggestion(code = ";", applicability = "maybe-incorrect")] + pub body: Span, + #[label] + pub block: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_extern_fn_qualifiers)] +pub struct FnQualifierInExtern { + #[primary_span] + pub span: Span, + #[label] + pub block: Span, + #[suggestion(code = "fn ", applicability = "maybe-incorrect", style = "verbose")] + pub sugg_span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_extern_item_ascii)] +#[note] +pub struct ExternItemAscii { + #[primary_span] + pub span: Span, + #[label] + pub block: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_bad_c_variadic)] +pub struct BadCVariadic { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_item_underscore)] +pub struct ItemUnderscore<'a> { + #[primary_span] + #[label] + pub span: Span, + pub kind: &'a str, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_nomangle_ascii, code = "E0754")] +pub struct NoMangleAscii { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_module_nonascii, code = "E0754")] +#[help] +pub struct ModuleNonAscii { + #[primary_span] + pub span: Span, + pub name: Symbol, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_auto_generic, code = "E0567")] +pub struct AutoTraitGeneric { + #[primary_span] + #[suggestion(code = "", applicability = "machine-applicable")] + pub span: Span, + #[label] + pub ident: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_auto_super_lifetime, code = "E0568")] +pub struct AutoTraitBounds { + #[primary_span] + #[suggestion(code = "", applicability = "machine-applicable")] + pub span: Span, + #[label] + pub ident: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_auto_items, code = "E0380")] +pub struct AutoTraitItems { + #[primary_span] + pub spans: Vec<Span>, + #[suggestion(code = "", applicability = "machine-applicable")] + pub total: Span, + #[label] + pub ident: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_generic_before_constraints)] +pub struct ArgsBeforeConstraint { + #[primary_span] + pub arg_spans: Vec<Span>, + #[label(ast_passes_constraints)] + pub constraints: Span, + #[label(ast_passes_args)] + pub args: Span, + #[suggestion(code = "{suggestion}", applicability = "machine-applicable", style = "verbose")] + pub data: Span, + pub suggestion: String, + pub constraint_len: usize, + pub args_len: usize, + #[subdiagnostic] + pub constraint_spans: EmptyLabelManySpans, + #[subdiagnostic] + pub arg_spans2: EmptyLabelManySpans, +} + +pub struct EmptyLabelManySpans(pub Vec<Span>); + +// The derive for `Vec<Span>` does multiple calls to `span_label`, adding commas between each +impl AddToDiagnostic for EmptyLabelManySpans { + fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) + where + F: Fn( + &mut rustc_errors::Diagnostic, + rustc_errors::SubdiagnosticMessage, + ) -> rustc_errors::SubdiagnosticMessage, + { + diag.span_labels(self.0, ""); + } +} + +#[derive(Diagnostic)] +#[diag(ast_passes_pattern_in_fn_pointer, code = "E0561")] +pub struct PatternFnPointer { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_trait_object_single_bound, code = "E0226")] +pub struct TraitObjectBound { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_impl_trait_path, code = "E0667")] +pub struct ImplTraitPath { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_nested_impl_trait, code = "E0666")] +pub struct NestedImplTrait { + #[primary_span] + pub span: Span, + #[label(ast_passes_outer)] + pub outer: Span, + #[label(ast_passes_inner)] + pub inner: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_at_least_one_trait)] +pub struct AtLeastOneTrait { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_out_of_order_params)] +pub struct OutOfOrderParams<'a> { + #[primary_span] + pub spans: Vec<Span>, + #[suggestion(code = "{ordered_params}", applicability = "machine-applicable")] + pub sugg_span: Span, + pub param_ord: &'a ParamKindOrd, + pub max_param: &'a ParamKindOrd, + pub ordered_params: &'a str, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_obsolete_auto)] +#[help] +pub struct ObsoleteAuto { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_unsafe_negative_impl, code = "E0198")] +pub struct UnsafeNegativeImpl { + #[primary_span] + pub span: Span, + #[label(ast_passes_negative)] + pub negative: Span, + #[label(ast_passes_unsafe)] + pub r#unsafe: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_inherent_cannot_be)] +pub struct InherentImplCannot<'a> { + #[primary_span] + pub span: Span, + #[label(ast_passes_because)] + pub annotation_span: Span, + pub annotation: &'a str, + #[label(ast_passes_type)] + pub self_ty: Span, + #[note(ast_passes_only_trait)] + pub only_trait: Option<()>, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_inherent_cannot_be, code = "E0197")] +pub struct InherentImplCannotUnsafe<'a> { + #[primary_span] + pub span: Span, + #[label(ast_passes_because)] + pub annotation_span: Span, + pub annotation: &'a str, + #[label(ast_passes_type)] + pub self_ty: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_unsafe_item)] +pub struct UnsafeItem { + #[primary_span] + pub span: Span, + pub kind: &'static str, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_fieldless_union)] +pub struct FieldlessUnion { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_where_after_type_alias)] +#[note] +pub struct WhereAfterTypeAlias { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_generic_default_trailing)] +pub struct GenericDefaultTrailing { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_nested_lifetimes, code = "E0316")] +pub struct NestedLifetimes { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_optional_trait_supertrait)] +#[note] +pub struct OptionalTraitSupertrait { + #[primary_span] + pub span: Span, + pub path_str: String, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_optional_trait_object)] +pub struct OptionalTraitObject { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_tilde_const_disallowed)] +pub struct TildeConstDisallowed { + #[primary_span] + pub span: Span, + #[subdiagnostic] + pub reason: TildeConstReason, +} + +#[derive(Subdiagnostic)] +pub enum TildeConstReason { + #[note(ast_passes_trait)] + TraitObject, + #[note(ast_passes_closure)] + Closure, + #[note(ast_passes_function)] + Function { + #[primary_span] + ident: Span, + }, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_optional_const_exclusive)] +pub struct OptionalConstExclusive { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_const_and_async)] +pub struct ConstAndAsync { + #[primary_span] + pub spans: Vec<Span>, + #[label(ast_passes_const)] + pub cspan: Span, + #[label(ast_passes_async)] + pub aspan: Span, + #[label] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_pattern_in_foreign, code = "E0130")] +pub struct PatternInForeign { + #[primary_span] + #[label] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_pattern_in_bodiless, code = "E0642")] +pub struct PatternInBodiless { + #[primary_span] + #[label] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_equality_in_where)] +#[note] +pub struct EqualityInWhere { + #[primary_span] + #[label] + pub span: Span, + #[subdiagnostic] + pub assoc: Option<AssociatedSuggestion>, + #[subdiagnostic] + pub assoc2: Option<AssociatedSuggestion2>, +} + +#[derive(Subdiagnostic)] +#[suggestion( + ast_passes_suggestion, + code = "{param}: {path}", + style = "verbose", + applicability = "maybe-incorrect" +)] +pub struct AssociatedSuggestion { + #[primary_span] + pub span: Span, + pub ident: Ident, + pub param: Ident, + pub path: String, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion(ast_passes_suggestion_path, applicability = "maybe-incorrect")] +pub struct AssociatedSuggestion2 { + #[suggestion_part(code = "{args}")] + pub span: Span, + pub args: String, + #[suggestion_part(code = "")] + pub predicate: Span, + pub trait_segment: Ident, + pub potential_assoc: Ident, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_stability_outside_std, code = "E0734")] +pub struct StabilityOutsideStd { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_feature_on_non_nightly, code = "E0554")] +pub struct FeatureOnNonNightly { + #[primary_span] + pub span: Span, + pub channel: &'static str, + #[subdiagnostic] + pub stable_features: Vec<StableFeature>, + #[suggestion(code = "", applicability = "machine-applicable")] + pub sugg: Option<Span>, +} + +pub struct StableFeature { + pub name: Symbol, + pub since: Symbol, +} + +impl AddToDiagnostic for StableFeature { + fn add_to_diagnostic_with<F>(self, diag: &mut rustc_errors::Diagnostic, _: F) + where + F: Fn( + &mut rustc_errors::Diagnostic, + rustc_errors::SubdiagnosticMessage, + ) -> rustc_errors::SubdiagnosticMessage, + { + diag.set_arg("name", self.name); + diag.set_arg("since", self.since); + diag.help(fluent::ast_passes_stable_since); + } +} + +#[derive(Diagnostic)] +#[diag(ast_passes_incompatbile_features)] +#[help] +pub struct IncompatibleFeatures { + #[primary_span] + pub spans: Vec<Span>, + pub f1: Symbol, + pub f2: Symbol, +} + +#[derive(Diagnostic)] +#[diag(ast_passes_show_span)] +pub struct ShowSpan { + #[primary_span] + pub span: Span, + pub msg: &'static str, +} diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 89ba6f936..96042ea30 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -2,7 +2,7 @@ use rustc_ast as ast; use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor}; use rustc_ast::{AssocConstraint, AssocConstraintKind, NodeId}; use rustc_ast::{PatKind, RangeEnd}; -use rustc_errors::{struct_span_err, Applicability, StashKey}; +use rustc_errors::{Applicability, StashKey}; use rustc_feature::{AttributeGate, BuiltinAttribute, Features, GateIssue, BUILTIN_ATTRIBUTE_MAP}; use rustc_session::parse::{feature_err, feature_err_issue, feature_warn}; use rustc_session::Session; @@ -10,6 +10,10 @@ use rustc_span::source_map::Spanned; use rustc_span::symbol::sym; use rustc_span::Span; use rustc_target::spec::abi; +use thin_vec::ThinVec; +use tracing::debug; + +use crate::errors; macro_rules! gate_feature_fn { ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $help: expr) => {{ @@ -136,6 +140,34 @@ impl<'a> PostExpansionVisitor<'a> { } ImplTraitVisitor { vis: self }.visit_ty(ty); } + + fn check_late_bound_lifetime_defs(&self, params: &[ast::GenericParam]) { + // Check only lifetime parameters are present and that the lifetime + // parameters that are present have no bounds. + let non_lt_param_spans: Vec<_> = params + .iter() + .filter_map(|param| match param.kind { + ast::GenericParamKind::Lifetime { .. } => None, + _ => Some(param.ident.span), + }) + .collect(); + // FIXME: gate_feature_post doesn't really handle multispans... + if !non_lt_param_spans.is_empty() && !self.features.non_lifetime_binders { + feature_err( + &self.sess.parse_sess, + sym::non_lifetime_binders, + non_lt_param_spans, + crate::fluent_generated::ast_passes_forbidden_non_lifetime_param, + ) + .emit(); + } + for param in params { + if !param.bounds.is_empty() { + let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect(); + self.sess.emit_err(errors::ForbiddenLifetimeBound { spans }); + } + } + } } impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { @@ -147,7 +179,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { .. }) = attr_info { - gate_feature_fn!(self, has_feature, attr.span, *name, descr); + gate_feature_fn!(self, has_feature, attr.span, *name, *descr); } // Check unstable flavors of the `#[doc]` attribute. if attr.has_name(sym::doc) { @@ -186,13 +218,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { || attr.has_name(sym::rustc_const_stable) || attr.has_name(sym::rustc_default_body_unstable) { - struct_span_err!( - self.sess, - attr.span, - E0734, - "stability attributes may not be used outside of the standard library", - ) - .emit(); + self.sess.emit_err(errors::StabilityOutsideStd { span: attr.span }); } } } @@ -220,7 +246,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { ast::ItemKind::Struct(..) => { for attr in self.sess.filter_by_name(&i.attrs, sym::repr) { - for item in attr.meta_item_list().unwrap_or_else(Vec::new) { + for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) { if item.has_name(sym::simd) { gate_feature_post!( &self, @@ -306,6 +332,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { ast::TyKind::BareFn(bare_fn_ty) => { // Function pointers cannot be `const` self.check_extern(bare_fn_ty.ext, ast::Const::No); + self.check_late_bound_lifetime_defs(&bare_fn_ty.generic_params); } ast::TyKind::Never => { gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental"); @@ -318,6 +345,19 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { visit::walk_ty(self, ty) } + fn visit_generics(&mut self, g: &'a ast::Generics) { + for predicate in &g.where_clause.predicates { + match predicate { + ast::WherePredicate::BoundPredicate(bound_pred) => { + // A type binding, eg `for<'c> Foo: Send+Clone+'c` + self.check_late_bound_lifetime_defs(&bound_pred.bound_generic_params); + } + _ => {} + } + } + visit::walk_generics(self, g); + } + fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) { if let ast::FnRetTy::Ty(output_ty) = ret_ty { if let ast::TyKind::Never = output_ty.kind { @@ -346,7 +386,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { ).span_suggestion_verbose( lhs.span.shrink_to_lo(), "you might have meant to introduce a new binding", - "let ".to_string(), + "let ", Applicability::MachineApplicable, ).emit(); } @@ -437,12 +477,21 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { visit::walk_pat(self, pattern) } + fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) { + self.check_late_bound_lifetime_defs(&t.bound_generic_params); + visit::walk_poly_trait_ref(self, t); + } + fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) { if let Some(header) = fn_kind.header() { // Stability of const fn methods are covered in `visit_assoc_item` below. self.check_extern(header.ext, header.constness); } + if let FnKind::Closure(ast::ClosureBinder::For { generic_params, .. }, ..) = fn_kind { + self.check_late_bound_lifetime_defs(generic_params); + } + if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() { gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable"); } @@ -580,13 +629,13 @@ fn maybe_stage_features(sess: &Session, krate: &ast::Crate) { return; } for attr in krate.attrs.iter().filter(|attr| attr.has_name(sym::feature)) { - let mut err = struct_span_err!( - sess.parse_sess.span_diagnostic, - attr.span, - E0554, - "`#![feature]` may not be used on the {} release channel", - option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)") - ); + let mut err = errors::FeatureOnNonNightly { + span: attr.span, + channel: option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)"), + stable_features: vec![], + sugg: None, + }; + let mut all_stable = true; for ident in attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident()) @@ -597,24 +646,15 @@ fn maybe_stage_features(sess: &Session, krate: &ast::Crate) { .flat_map(|&(feature, _, since)| if feature == name { since } else { None }) .next(); if let Some(since) = stable_since { - err.help(&format!( - "the feature `{}` has been stable since {} and no longer requires \ - an attribute to enable", - name, since - )); + err.stable_features.push(errors::StableFeature { name, since }); } else { all_stable = false; } } if all_stable { - err.span_suggestion( - attr.span, - "remove the attribute", - "", - Applicability::MachineApplicable, - ); + err.sugg = Some(attr.span); } - err.emit(); + sess.parse_sess.span_diagnostic.emit_err(err); } } } @@ -637,16 +677,7 @@ fn check_incompatible_features(sess: &Session) { if let Some((f2_name, f2_span)) = declared_features.clone().find(|(name, _)| name == f2) { let spans = vec![f1_span, f2_span]; - sess.struct_span_err( - spans, - &format!( - "features `{}` and `{}` are incompatible, using them at the same time \ - is not allowed", - f1_name, f2_name - ), - ) - .help("remove one of these features") - .emit(); + sess.emit_err(errors::IncompatibleFeatures { spans, f1: f1_name, f2: f2_name }); } } } diff --git a/compiler/rustc_ast_passes/src/lib.rs b/compiler/rustc_ast_passes/src/lib.rs index f58fffc91..b9dcaee23 100644 --- a/compiler/rustc_ast_passes/src/lib.rs +++ b/compiler/rustc_ast_passes/src/lib.rs @@ -10,12 +10,16 @@ #![feature(iter_is_partitioned)] #![feature(let_chains)] #![recursion_limit = "256"] +#![deny(rustc::untranslatable_diagnostic)] +#![deny(rustc::diagnostic_outside_of_impl)] -#[macro_use] -extern crate tracing; +use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage}; +use rustc_macros::fluent_messages; pub mod ast_validation; mod errors; pub mod feature_gate; pub mod node_count; pub mod show_span; + +fluent_messages! { "../locales/en-US.ftl" } diff --git a/compiler/rustc_ast_passes/src/show_span.rs b/compiler/rustc_ast_passes/src/show_span.rs index 27637e311..280cf3284 100644 --- a/compiler/rustc_ast_passes/src/show_span.rs +++ b/compiler/rustc_ast_passes/src/show_span.rs @@ -9,6 +9,8 @@ use rustc_ast as ast; use rustc_ast::visit; use rustc_ast::visit::Visitor; +use crate::errors; + enum Mode { Expression, Pattern, @@ -36,21 +38,21 @@ struct ShowSpanVisitor<'a> { impl<'a> Visitor<'a> for ShowSpanVisitor<'a> { fn visit_expr(&mut self, e: &'a ast::Expr) { if let Mode::Expression = self.mode { - self.span_diagnostic.span_warn(e.span, "expression"); + self.span_diagnostic.emit_warning(errors::ShowSpan { span: e.span, msg: "expression" }); } visit::walk_expr(self, e); } fn visit_pat(&mut self, p: &'a ast::Pat) { if let Mode::Pattern = self.mode { - self.span_diagnostic.span_warn(p.span, "pattern"); + self.span_diagnostic.emit_warning(errors::ShowSpan { span: p.span, msg: "pattern" }); } visit::walk_pat(self, p); } fn visit_ty(&mut self, t: &'a ast::Ty) { if let Mode::Type = self.mode { - self.span_diagnostic.span_warn(t.span, "type"); + self.span_diagnostic.emit_warning(errors::ShowSpan { span: t.span, msg: "type" }); } visit::walk_ty(self, t); } |