summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_ast_passes
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:02:58 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:02:58 +0000
commit698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch)
tree173a775858bd501c378080a10dca74132f05bc50 /compiler/rustc_ast_passes
parentInitial commit. (diff)
downloadrustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz
rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'compiler/rustc_ast_passes')
-rw-r--r--compiler/rustc_ast_passes/Cargo.toml18
-rw-r--r--compiler/rustc_ast_passes/src/ast_validation.rs1909
-rw-r--r--compiler/rustc_ast_passes/src/feature_gate.rs901
-rw-r--r--compiler/rustc_ast_passes/src/lib.rs18
-rw-r--r--compiler/rustc_ast_passes/src/node_count.rs135
-rw-r--r--compiler/rustc_ast_passes/src/show_span.rs65
6 files changed, 3046 insertions, 0 deletions
diff --git a/compiler/rustc_ast_passes/Cargo.toml b/compiler/rustc_ast_passes/Cargo.toml
new file mode 100644
index 000000000..22742b2ad
--- /dev/null
+++ b/compiler/rustc_ast_passes/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "rustc_ast_passes"
+version = "0.0.0"
+edition = "2021"
+
+[dependencies]
+itertools = "0.10.1"
+tracing = "0.1"
+rustc_ast_pretty = { path = "../rustc_ast_pretty" }
+rustc_attr = { path = "../rustc_attr" }
+rustc_data_structures = { path = "../rustc_data_structures" }
+rustc_errors = { path = "../rustc_errors" }
+rustc_feature = { path = "../rustc_feature" }
+rustc_parse = { path = "../rustc_parse" }
+rustc_session = { path = "../rustc_session" }
+rustc_span = { path = "../rustc_span" }
+rustc_target = { path = "../rustc_target" }
+rustc_ast = { path = "../rustc_ast" }
diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs
new file mode 100644
index 000000000..2d9d0073f
--- /dev/null
+++ b/compiler/rustc_ast_passes/src/ast_validation.rs
@@ -0,0 +1,1909 @@
+// Validate AST before lowering it to HIR.
+//
+// This pass is supposed to catch things that fit into AST data structures,
+// but not permitted by the language. It runs after expansion when AST is frozen,
+// so it can check for erroneous constructions produced by syntax extensions.
+// This pass is supposed to perform only simple checks not requiring name resolution
+// or type checking or some other kind of complex analysis.
+
+use itertools::{Either, Itertools};
+use rustc_ast::ptr::P;
+use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor};
+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, pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed,
+};
+use rustc_parse::validate_attr;
+use rustc_session::lint::builtin::{
+ DEPRECATED_WHERE_CLAUSE_LOCATION, MISSING_ABI, PATTERNS_IN_FNS_WITHOUT_BODY,
+};
+use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer};
+use rustc_session::Session;
+use rustc_span::source_map::Spanned;
+use rustc_span::symbol::{kw, sym, Ident};
+use rustc_span::Span;
+use rustc_target::spec::abi;
+use std::mem;
+use std::ops::{Deref, DerefMut};
+
+const MORE_EXTERN: &str =
+ "for more information, visit https://doc.rust-lang.org/std/keyword.extern.html";
+
+/// Is `self` allowed semantically as the first parameter in an `FnDecl`?
+enum SelfSemantic {
+ Yes,
+ No,
+}
+
+struct AstValidator<'a> {
+ session: &'a Session,
+
+ /// The span of the `extern` in an `extern { ... }` block, if any.
+ extern_mod: Option<&'a Item>,
+
+ /// Are we inside a trait impl?
+ in_trait_impl: bool,
+
+ in_const_trait_impl: bool,
+
+ has_proc_macro_decls: bool,
+
+ /// Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
+ /// Nested `impl Trait` _is_ allowed in associated type position,
+ /// e.g., `impl Iterator<Item = impl Debug>`.
+ outer_impl_trait: Option<Span>,
+
+ is_tilde_const_allowed: bool,
+
+ /// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
+ /// 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>,
+
+ lint_buffer: &'a mut LintBuffer,
+}
+
+impl<'a> AstValidator<'a> {
+ fn with_in_trait_impl(
+ &mut self,
+ is_in: bool,
+ constness: Option<Const>,
+ f: impl FnOnce(&mut Self),
+ ) {
+ let old = mem::replace(&mut self.in_trait_impl, is_in);
+ let old_const =
+ mem::replace(&mut self.in_const_trait_impl, matches!(constness, Some(Const::Yes(_))));
+ f(self);
+ self.in_trait_impl = old;
+ self.in_const_trait_impl = old_const;
+ }
+
+ fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
+ let old = mem::replace(&mut self.is_impl_trait_banned, true);
+ f(self);
+ self.is_impl_trait_banned = old;
+ }
+
+ fn with_tilde_const(&mut self, allowed: bool, f: impl FnOnce(&mut Self)) {
+ let old = mem::replace(&mut self.is_tilde_const_allowed, allowed);
+ f(self);
+ self.is_tilde_const_allowed = old;
+ }
+
+ fn with_tilde_const_allowed(&mut self, f: impl FnOnce(&mut Self)) {
+ self.with_tilde_const(true, f)
+ }
+
+ fn with_banned_tilde_const(&mut self, f: impl FnOnce(&mut Self)) {
+ self.with_tilde_const(false, f)
+ }
+
+ fn with_let_management(
+ &mut self,
+ forbidden_let_reason: Option<ForbiddenLetReason>,
+ f: impl FnOnce(&mut Self, Option<ForbiddenLetReason>),
+ ) {
+ let old = mem::replace(&mut self.forbidden_let_reason, forbidden_let_reason);
+ f(self, old);
+ self.forbidden_let_reason = old;
+ }
+
+ /// Emits an error banning the `let` expression provided in the given location.
+ fn ban_let_expr(&self, expr: &'a Expr, forbidden_let_reason: ForbiddenLetReason) {
+ let sess = &self.session;
+ if sess.opts.unstable_features.is_nightly_build() {
+ let err = "`let` expressions are not supported here";
+ let mut diag = sess.struct_span_err(expr.span, err);
+ diag.note("only supported directly in conditions of `if` and `while` expressions");
+ match forbidden_let_reason {
+ ForbiddenLetReason::GenericForbidden => {}
+ ForbiddenLetReason::NotSupportedOr(span) => {
+ diag.span_note(
+ span,
+ "`||` operators are not supported in let chain expressions",
+ );
+ }
+ ForbiddenLetReason::NotSupportedParentheses(span) => {
+ diag.span_note(
+ span,
+ "`let`s wrapped in parentheses are not supported in a context with let \
+ chains",
+ );
+ }
+ }
+ diag.emit();
+ } else {
+ sess.struct_span_err(expr.span, "expected expression, found statement (`let`)")
+ .note("variable declaration using `let` is a statement")
+ .emit();
+ }
+ }
+
+ fn check_gat_where(
+ &mut self,
+ id: NodeId,
+ before_predicates: &[WherePredicate],
+ where_clauses: (ast::TyAliasWhereClause, ast::TyAliasWhereClause),
+ ) {
+ if !before_predicates.is_empty() {
+ let mut state = State::new();
+ if !where_clauses.1.0 {
+ state.space();
+ state.word_space("where");
+ } else {
+ state.word_space(",");
+ }
+ let mut first = true;
+ for p in before_predicates.iter() {
+ if !first {
+ state.word_space(",");
+ }
+ first = false;
+ state.print_where_predicate(p);
+ }
+ let suggestion = state.s.eof();
+ self.lint_buffer.buffer_lint_with_diagnostic(
+ DEPRECATED_WHERE_CLAUSE_LOCATION,
+ id,
+ where_clauses.0.1,
+ "where clause not allowed here",
+ BuiltinLintDiagnostics::DeprecatedWhereclauseLocation(
+ where_clauses.1.1.shrink_to_hi(),
+ suggestion,
+ ),
+ );
+ }
+ }
+
+ 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);
+ if outer.is_some() {
+ self.with_banned_tilde_const(f);
+ } else {
+ 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.err_handler().span_err(
+ constraint.span,
+ "associated type bounds are not allowed within structs, enums, or unions",
+ );
+ }
+ }
+ }
+ self.visit_assoc_constraint(constraint);
+ }
+
+ // Mirrors `visit::walk_ty`, but tracks relevant state.
+ fn walk_ty(&mut self, t: &'a Ty) {
+ match t.kind {
+ TyKind::ImplTrait(..) => {
+ self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
+ }
+ TyKind::TraitObject(..) => self.with_banned_tilde_const(|this| visit::walk_ty(this, t)),
+ TyKind::Path(ref qself, ref path) => {
+ // We allow these:
+ // - `Option<impl Trait>`
+ // - `option::Option<impl Trait>`
+ // - `option::Option<T>::Foo<impl Trait>
+ //
+ // But not these:
+ // - `<impl Trait>::Foo`
+ // - `option::Option<impl Trait>::Foo`.
+ //
+ // To implement this, we disallow `impl Trait` from `qself`
+ // (for cases like `<impl Trait>::Foo>`)
+ // but we allow `impl Trait` in `GenericArgs`
+ // iff there are no more PathSegments.
+ if let Some(ref qself) = *qself {
+ // `impl Trait` in `qself` is always illegal
+ self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
+ }
+
+ // Note that there should be a call to visit_path here,
+ // so if any logic is added to process `Path`s a call to it should be
+ // added both in visit_path and here. This code mirrors visit::walk_path.
+ for (i, segment) in path.segments.iter().enumerate() {
+ // Allow `impl Trait` iff we're on the final path segment
+ if i == path.segments.len() - 1 {
+ self.visit_path_segment(path.span, segment);
+ } else {
+ self.with_banned_impl_trait(|this| {
+ this.visit_path_segment(path.span, segment)
+ });
+ }
+ }
+ }
+ _ => visit::walk_ty(self, t),
+ }
+ }
+
+ fn visit_struct_field_def(&mut self, field: &'a FieldDef) {
+ if let Some(ident) = field.ident {
+ if ident.name == kw::Underscore {
+ self.visit_vis(&field.vis);
+ self.visit_ident(ident);
+ self.visit_ty_common(&field.ty);
+ self.walk_ty(&field.ty);
+ walk_list!(self, visit_attribute, &field.attrs);
+ return;
+ }
+ }
+ self.visit_field_def(field);
+ }
+
+ fn err_handler(&self) -> &rustc_errors::Handler {
+ &self.session.diagnostic()
+ }
+
+ 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.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
+ }
+ }
+
+ fn check_label(&self, ident: Ident) {
+ if ident.without_first_quote().is_reserved() {
+ self.err_handler()
+ .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
+ }
+ }
+
+ fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
+ if let VisibilityKind::Inherited = vis.kind {
+ return;
+ }
+
+ let mut err =
+ struct_span_err!(self.session, vis.span, E0449, "unnecessary visibility qualifier");
+ if vis.kind.is_pub() {
+ err.span_label(vis.span, "`pub` not permitted here because it's implied");
+ }
+ if let Some(note) = note {
+ err.note(note);
+ }
+ err.emit();
+ }
+
+ fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, Option<Ident>, bool)) {
+ for Param { pat, .. } in &decl.inputs {
+ match pat.kind {
+ PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, None) | PatKind::Wild => {}
+ PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ident, None) => {
+ report_err(pat.span, Some(ident), true)
+ }
+ _ => report_err(pat.span, None, false),
+ }
+ }
+ }
+
+ fn check_trait_fn_not_async(&self, fn_span: Span, asyncness: Async) {
+ if let Async::Yes { span, .. } = asyncness {
+ struct_span_err!(
+ self.session,
+ fn_span,
+ E0706,
+ "functions in traits cannot be declared `async`"
+ )
+ .span_label(span, "`async` because of this")
+ .note("`async` trait functions are not currently supported")
+ .note("consider using the `async-trait` crate: https://crates.io/crates/async-trait")
+ .emit();
+ }
+ }
+
+ fn check_trait_fn_not_const(&self, constness: Const) {
+ if let Const::Yes(span) = constness {
+ struct_span_err!(
+ self.session,
+ span,
+ E0379,
+ "functions in traits cannot be declared const"
+ )
+ .span_label(span, "functions in traits cannot be const")
+ .emit();
+ }
+ }
+
+ 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.err_handler()
+ .span_err(spans, "lifetime bounds cannot be used in this context");
+ }
+ None
+ }
+ _ => Some(param.ident.span),
+ })
+ .collect();
+ if !non_lt_param_spans.is_empty() {
+ self.err_handler().span_err(
+ non_lt_param_spans,
+ "only lifetime parameters can be used in this context",
+ );
+ }
+ }
+
+ fn check_fn_decl(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
+ self.check_decl_num_args(fn_decl);
+ self.check_decl_cvaradic_pos(fn_decl);
+ self.check_decl_attrs(fn_decl);
+ self.check_decl_self_param(fn_decl, self_semantic);
+ }
+
+ /// Emits fatal error if function declaration has more than `u16::MAX` arguments
+ /// Error is fatal to prevent errors during typechecking
+ fn check_decl_num_args(&self, fn_decl: &FnDecl) {
+ let max_num_args: usize = u16::MAX.into();
+ if fn_decl.inputs.len() > max_num_args {
+ let Param { span, .. } = fn_decl.inputs[0];
+ self.err_handler().span_fatal(
+ span,
+ &format!("function can not have more than {} arguments", max_num_args),
+ );
+ }
+ }
+
+ fn check_decl_cvaradic_pos(&self, fn_decl: &FnDecl) {
+ match &*fn_decl.inputs {
+ [Param { ty, span, .. }] => {
+ if let TyKind::CVarArgs = ty.kind {
+ self.err_handler().span_err(
+ *span,
+ "C-variadic function must be declared with at least one named argument",
+ );
+ }
+ }
+ [ps @ .., _] => {
+ for Param { ty, span, .. } in ps {
+ if let TyKind::CVarArgs = ty.kind {
+ self.err_handler().span_err(
+ *span,
+ "`...` must be the last argument of a C-variadic function",
+ );
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+
+ fn check_decl_attrs(&self, fn_decl: &FnDecl) {
+ fn_decl
+ .inputs
+ .iter()
+ .flat_map(|i| i.attrs.as_ref())
+ .filter(|attr| {
+ let arr = [
+ sym::allow,
+ sym::cfg,
+ sym::cfg_attr,
+ sym::deny,
+ sym::expect,
+ sym::forbid,
+ sym::warn,
+ ];
+ !arr.contains(&attr.name_or_empty()) && rustc_attr::is_builtin_attr(attr)
+ })
+ .for_each(|attr| {
+ if attr.is_doc_comment() {
+ self.err_handler()
+ .struct_span_err(
+ attr.span,
+ "documentation comments cannot be applied to function parameters",
+ )
+ .span_label(attr.span, "doc comments are not allowed here")
+ .emit();
+ } else {
+ self.err_handler().span_err(
+ attr.span,
+ "allow, cfg, cfg_attr, deny, expect, \
+ forbid, and warn are the only allowed built-in attributes in function parameters",
+ );
+ }
+ });
+ }
+
+ 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.err_handler()
+ .struct_span_err(
+ param.span,
+ "`self` parameter is only allowed in associated functions",
+ )
+ .span_label(param.span, "not semantically valid as function parameter")
+ .note("associated functions are those in `impl` or `trait` definitions")
+ .emit();
+ }
+ }
+ }
+
+ 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.err_handler()
+ .struct_span_err(span, "`default` is only allowed on items in trait impls")
+ .span_label(def_span, "`default` because of this")
+ .emit();
+ }
+ }
+
+ fn error_item_without_body(&self, sp: Span, ctx: &str, msg: &str, sugg: &str) {
+ self.error_item_without_body_with_help(sp, ctx, msg, sugg, |_| ());
+ }
+
+ fn error_item_without_body_with_help(
+ &self,
+ sp: Span,
+ ctx: &str,
+ msg: &str,
+ sugg: &str,
+ help: impl FnOnce(&mut DiagnosticBuilder<'_, ErrorGuaranteed>),
+ ) {
+ let source_map = self.session.source_map();
+ let end = source_map.end_point(sp);
+ let replace_span = if source_map.span_to_snippet(end).map(|s| s == ";").unwrap_or(false) {
+ end
+ } else {
+ sp.shrink_to_hi()
+ };
+ let mut err = self.err_handler().struct_span_err(sp, msg);
+ err.span_suggestion(
+ replace_span,
+ &format!("provide a definition for the {}", ctx),
+ sugg,
+ Applicability::HasPlaceholders,
+ );
+ help(&mut err);
+ err.emit();
+ }
+
+ fn check_impl_item_provided<T>(&self, sp: Span, body: &Option<T>, ctx: &str, sugg: &str) {
+ if body.is_none() {
+ let msg = format!("associated {} in `impl` without body", ctx);
+ self.error_item_without_body(sp, ctx, &msg, sugg);
+ }
+ }
+
+ fn check_type_no_bounds(&self, bounds: &[GenericBound], ctx: &str) {
+ let span = match bounds {
+ [] => return,
+ [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();
+ }
+
+ 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();
+ };
+
+ if !generics.params.is_empty() {
+ cannot_have(generics.span, "generic parameters", "generic parameters");
+ }
+
+ if !generics.where_clause.predicates.is_empty() {
+ cannot_have(where_span, "`where` clauses", "`where` clause");
+ }
+ }
+
+ fn check_foreign_kind_bodyless(&self, ident: Ident, kind: &str, body: Option<Span>) {
+ 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();
+ }
+
+ /// An `fn` in `extern { ... }` cannot have a body `{ ... }`.
+ fn check_foreign_fn_bodyless(&self, ident: Ident, body: Option<&Block>) {
+ 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();
+ }
+
+ fn current_extern_span(&self) -> Span {
+ self.session.source_map().guess_head_span(self.extern_mod.unwrap().span)
+ }
+
+ /// 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();
+ }
+ }
+
+ /// 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();
+ }
+ }
+
+ /// Reject C-variadic type unless the function is foreign,
+ /// or free and `unsafe extern "C"` semantically.
+ fn check_c_variadic_type(&self, fk: FnKind<'a>) {
+ match (fk.ctxt(), fk.header()) {
+ (Some(FnCtxt::Foreign), _) => return,
+ (Some(FnCtxt::Free), Some(header)) => match header.ext {
+ Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. }, _)
+ | Extern::Implicit(_)
+ if matches!(header.unsafety, Unsafe::Yes(_)) =>
+ {
+ return;
+ }
+ _ => {}
+ },
+ _ => {}
+ };
+
+ 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();
+ }
+ }
+ }
+
+ fn check_item_named(&self, ident: Ident, kind: &str) {
+ 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();
+ }
+
+ 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();
+ }
+
+ 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();
+ }
+
+ fn deny_generic_params(&self, generics: &Generics, ident_span: 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();
+ }
+ }
+
+ 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 deny_super_traits(&self, bounds: &GenericBounds, ident_span: Span) {
+ if let [.., last] = &bounds[..] {
+ let span = ident_span.shrink_to_hi().to(last.span());
+ self.emit_e0568(span, ident_span);
+ }
+ }
+
+ fn deny_where_clause(&self, where_clause: &WhereClause, ident_span: Span) {
+ if !where_clause.predicates.is_empty() {
+ self.emit_e0568(where_clause.span, ident_span);
+ }
+ }
+
+ fn deny_items(&self, trait_items: &[P<AssocItem>], ident_span: 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();
+ }
+ }
+
+ fn correct_generic_order_suggestion(&self, data: &AngleBracketedArgs) -> String {
+ // Lifetimes always come first.
+ let lt_sugg = data.args.iter().filter_map(|arg| match arg {
+ AngleBracketedArg::Arg(lt @ GenericArg::Lifetime(_)) => {
+ Some(pprust::to_string(|s| s.print_generic_arg(lt)))
+ }
+ _ => None,
+ });
+ let args_sugg = data.args.iter().filter_map(|a| match a {
+ AngleBracketedArg::Arg(GenericArg::Lifetime(_)) | AngleBracketedArg::Constraint(_) => {
+ None
+ }
+ AngleBracketedArg::Arg(arg) => Some(pprust::to_string(|s| s.print_generic_arg(arg))),
+ });
+ // Constraints always come last.
+ let constraint_sugg = data.args.iter().filter_map(|a| match a {
+ AngleBracketedArg::Arg(_) => None,
+ AngleBracketedArg::Constraint(c) => {
+ Some(pprust::to_string(|s| s.print_assoc_constraint(c)))
+ }
+ });
+ format!(
+ "<{}>",
+ lt_sugg.chain(args_sugg).chain(constraint_sugg).collect::<Vec<String>>().join(", ")
+ )
+ }
+
+ /// Enforce generic args coming before constraints in `<...>` of a path segment.
+ fn check_generic_args_before_constraints(&self, data: &AngleBracketedArgs) {
+ // Early exit in case it's partitioned as it should be.
+ if data.args.iter().is_partitioned(|arg| matches!(arg, AngleBracketedArg::Arg(_))) {
+ return;
+ }
+ // Find all generic argument coming after the first constraint...
+ let (constraint_spans, arg_spans): (Vec<Span>, Vec<Span>) =
+ data.args.iter().partition_map(|arg| match arg {
+ AngleBracketedArg::Constraint(c) => Either::Left(c.span),
+ AngleBracketedArg::Arg(a) => Either::Right(a.span()),
+ });
+ 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();
+ }
+
+ fn visit_ty_common(&mut self, ty: &'a Ty) {
+ match ty.kind {
+ TyKind::BareFn(ref 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.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);
+ }
+ }
+ TyKind::TraitObject(ref bounds, ..) => {
+ let mut any_lifetime_bounds = false;
+ for bound in bounds {
+ if let GenericBound::Outlives(ref lifetime) = *bound {
+ if any_lifetime_bounds {
+ struct_span_err!(
+ self.session,
+ lifetime.ident.span,
+ E0226,
+ "only a single explicit lifetime bound is permitted"
+ )
+ .emit();
+ break;
+ }
+ any_lifetime_bounds = true;
+ }
+ }
+ }
+ TyKind::ImplTrait(_, ref bounds) => {
+ if self.is_impl_trait_banned {
+ struct_span_err!(
+ self.session,
+ ty.span,
+ E0667,
+ "`impl Trait` is not allowed in path parameters"
+ )
+ .emit();
+ }
+
+ 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();
+ }
+
+ if !bounds.iter().any(|b| matches!(b, GenericBound::Trait(..))) {
+ self.err_handler().span_err(ty.span, "at least one trait must be specified");
+ }
+ }
+ _ => {}
+ }
+ }
+
+ fn maybe_lint_missing_abi(&mut self, span: Span, id: NodeId) {
+ // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
+ // call site which do not have a macro backtrace. See #61963.
+ let is_macro_callsite = self
+ .session
+ .source_map()
+ .span_to_snippet(span)
+ .map(|snippet| snippet.starts_with("#["))
+ .unwrap_or(true);
+ if !is_macro_callsite {
+ self.lint_buffer.buffer_lint_with_diagnostic(
+ MISSING_ABI,
+ id,
+ span,
+ "extern declarations without an explicit ABI are deprecated",
+ BuiltinLintDiagnostics::MissingAbi(span, abi::Abi::FALLBACK),
+ )
+ }
+ }
+}
+
+/// Checks that generic parameters are in the correct order,
+/// which is lifetimes, then types and then consts. (`<'a, T, const N: usize>`)
+fn validate_generic_param_order(
+ handler: &rustc_errors::Handler,
+ generics: &[GenericParam],
+ span: Span,
+) {
+ let mut max_param: Option<ParamKindOrd> = None;
+ let mut out_of_order = FxHashMap::default();
+ let mut param_idents = Vec::with_capacity(generics.len());
+
+ for (idx, param) in generics.iter().enumerate() {
+ let ident = param.ident;
+ let (kind, bounds, span) = (&param.kind, &param.bounds, ident.span);
+ let (ord_kind, ident) = match &param.kind {
+ GenericParamKind::Lifetime => (ParamKindOrd::Lifetime, ident.to_string()),
+ GenericParamKind::Type { default: _ } => (ParamKindOrd::Type, ident.to_string()),
+ GenericParamKind::Const { ref ty, kw_span: _, default: _ } => {
+ let ty = pprust::ty_to_string(ty);
+ (ParamKindOrd::Const, format!("const {}: {}", ident, ty))
+ }
+ };
+ param_idents.push((kind, ord_kind, bounds, idx, ident));
+ match max_param {
+ Some(max_param) if max_param > ord_kind => {
+ let entry = out_of_order.entry(ord_kind).or_insert((max_param, vec![]));
+ entry.1.push(span);
+ }
+ Some(_) | None => max_param = Some(ord_kind),
+ };
+ }
+
+ if !out_of_order.is_empty() {
+ let mut ordered_params = "<".to_string();
+ param_idents.sort_by_key(|&(_, po, _, i, _)| (po, i));
+ let mut first = true;
+ for (kind, _, bounds, _, ident) in param_idents {
+ if !first {
+ ordered_params += ", ";
+ }
+ ordered_params += &ident;
+
+ if !bounds.is_empty() {
+ ordered_params += ": ";
+ ordered_params += &pprust::bounds_to_string(&bounds);
+ }
+
+ match kind {
+ GenericParamKind::Type { default: Some(default) } => {
+ ordered_params += " = ";
+ ordered_params += &pprust::ty_to_string(default);
+ }
+ GenericParamKind::Type { default: None } => (),
+ GenericParamKind::Lifetime => (),
+ GenericParamKind::Const { ty: _, kw_span: _, default: Some(default) } => {
+ ordered_params += " = ";
+ ordered_params += &pprust::expr_to_string(&*default.value);
+ }
+ GenericParamKind::Const { ty: _, kw_span: _, default: None } => (),
+ }
+ first = false;
+ }
+
+ 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();
+ }
+ }
+}
+
+impl<'a> Visitor<'a> for AstValidator<'a> {
+ fn visit_attribute(&mut self, attr: &Attribute) {
+ validate_attr::check_meta(&self.session.parse_sess, attr);
+ }
+
+ fn visit_expr(&mut self, expr: &'a Expr) {
+ self.with_let_management(Some(ForbiddenLetReason::GenericForbidden), |this, forbidden_let_reason| {
+ match &expr.kind {
+ ExprKind::Binary(Spanned { node: BinOpKind::Or, span }, lhs, rhs) => {
+ let local_reason = Some(ForbiddenLetReason::NotSupportedOr(*span));
+ this.with_let_management(local_reason, |this, _| this.visit_expr(lhs));
+ this.with_let_management(local_reason, |this, _| this.visit_expr(rhs));
+ }
+ ExprKind::If(cond, then, opt_else) => {
+ this.visit_block(then);
+ walk_list!(this, visit_expr, opt_else);
+ this.with_let_management(None, |this, _| this.visit_expr(cond));
+ return;
+ }
+ ExprKind::Let(..) if let Some(elem) = forbidden_let_reason => {
+ this.ban_let_expr(expr, elem);
+ },
+ ExprKind::Match(scrutinee, arms) => {
+ this.visit_expr(scrutinee);
+ for arm in arms {
+ this.visit_expr(&arm.body);
+ this.visit_pat(&arm.pat);
+ walk_list!(this, visit_attribute, &arm.attrs);
+ if let Some(guard) = &arm.guard && let ExprKind::Let(_, guard_expr, _) = &guard.kind {
+ this.with_let_management(None, |this, _| {
+ this.visit_expr(guard_expr)
+ });
+ return;
+ }
+ }
+ }
+ ExprKind::Paren(local_expr) => {
+ fn has_let_expr(expr: &Expr) -> bool {
+ match expr.kind {
+ ExprKind::Binary(_, ref lhs, ref rhs) => has_let_expr(lhs) || has_let_expr(rhs),
+ ExprKind::Let(..) => true,
+ _ => false,
+ }
+ }
+ let local_reason = if has_let_expr(local_expr) {
+ Some(ForbiddenLetReason::NotSupportedParentheses(local_expr.span))
+ }
+ else {
+ forbidden_let_reason
+ };
+ this.with_let_management(local_reason, |this, _| this.visit_expr(local_expr));
+ }
+ ExprKind::Binary(Spanned { node: BinOpKind::And, .. }, ..) => {
+ this.with_let_management(forbidden_let_reason, |this, _| visit::walk_expr(this, expr));
+ return;
+ }
+ ExprKind::While(cond, then, opt_label) => {
+ walk_list!(this, visit_label, opt_label);
+ this.visit_block(then);
+ this.with_let_management(None, |this, _| this.visit_expr(cond));
+ return;
+ }
+ _ => visit::walk_expr(this, expr),
+ }
+ });
+ }
+
+ fn visit_ty(&mut self, ty: &'a Ty) {
+ self.visit_ty_common(ty);
+ self.walk_ty(ty)
+ }
+
+ fn visit_label(&mut self, label: &'a Label) {
+ self.check_label(label.ident);
+ visit::walk_label(self, label);
+ }
+
+ fn visit_lifetime(&mut self, lifetime: &'a Lifetime, _: visit::LifetimeCtxt) {
+ self.check_lifetime(lifetime.ident);
+ visit::walk_lifetime(self, lifetime);
+ }
+
+ fn visit_field_def(&mut self, s: &'a FieldDef) {
+ visit::walk_field_def(self, s)
+ }
+
+ fn visit_item(&mut self, item: &'a Item) {
+ if item.attrs.iter().any(|attr| self.session.is_proc_macro_attr(attr)) {
+ self.has_proc_macro_decls = true;
+ }
+
+ if self.session.contains_name(&item.attrs, sym::no_mangle) {
+ self.check_nomangle_item_asciionly(item.ident, item.span);
+ }
+
+ match item.kind {
+ ItemKind::Impl(box Impl {
+ unsafety,
+ polarity,
+ defaultness: _,
+ constness,
+ ref generics,
+ of_trait: Some(ref t),
+ ref self_ty,
+ ref items,
+ }) => {
+ 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();
+ }
+ 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.visit_vis(&item.vis);
+ this.visit_ident(item.ident);
+ if let Const::Yes(_) = constness {
+ this.with_tilde_const_allowed(|this| this.visit_generics(generics));
+ } else {
+ this.visit_generics(generics);
+ }
+ this.visit_trait_ref(t);
+ this.visit_ty(self_ty);
+
+ walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl);
+ });
+ return; // Avoid visiting again.
+ }
+ ItemKind::Impl(box Impl {
+ unsafety,
+ polarity,
+ defaultness,
+ constness,
+ generics: _,
+ of_trait: None,
+ ref 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
+ };
+
+ self.invalid_visibility(
+ &item.vis,
+ Some("place qualifiers on individual impl items instead"),
+ );
+ if let Unsafe::Yes(span) = unsafety {
+ error(span, "unsafe").code(error_code!(E0197)).emit();
+ }
+ if let ImplPolarity::Negative(span) = polarity {
+ error(span, "negative").emit();
+ }
+ if let Defaultness::Default(def_span) = defaultness {
+ error(def_span, "`default`")
+ .note("only trait implementations may be annotated with `default`")
+ .emit();
+ }
+ if let Const::Yes(span) = constness {
+ error(span, "`const`")
+ .note("only trait implementations may be annotated with `const`")
+ .emit();
+ }
+ }
+ ItemKind::Fn(box Fn { defaultness, ref sig, ref generics, ref body }) => {
+ self.check_defaultness(item.span, defaultness);
+
+ if body.is_none() {
+ let msg = "free function without a body";
+ let ext = sig.header.ext;
+
+ let f = |e: &mut DiagnosticBuilder<'_, _>| {
+ if let Extern::Implicit(start_span) | Extern::Explicit(_, start_span) = &ext
+ {
+ let start_suggestion = if let Extern::Explicit(abi, _) = ext {
+ format!("extern \"{}\" {{", abi.symbol_unescaped)
+ } else {
+ "extern {".to_owned()
+ };
+
+ let end_suggestion = " }".to_owned();
+ let end_span = item.span.shrink_to_hi();
+
+ e
+ .multipart_suggestion(
+ "if you meant to declare an externally defined function, use an `extern` block",
+ vec![(*start_span, start_suggestion), (end_span, end_suggestion)],
+ Applicability::MaybeIncorrect,
+ );
+ }
+ };
+
+ self.error_item_without_body_with_help(
+ item.span,
+ "function",
+ msg,
+ " { <body> }",
+ f,
+ );
+ }
+
+ self.visit_vis(&item.vis);
+ self.visit_ident(item.ident);
+ let kind =
+ FnKind::Fn(FnCtxt::Free, item.ident, sig, &item.vis, generics, body.as_deref());
+ self.visit_fn(kind, item.span, item.id);
+ walk_list!(self, visit_attribute, &item.attrs);
+ return; // Avoid visiting again.
+ }
+ ItemKind::ForeignMod(ForeignMod { abi, unsafety, .. }) => {
+ let old_item = mem::replace(&mut self.extern_mod, Some(item));
+ self.invalid_visibility(
+ &item.vis,
+ Some("place qualifiers on individual foreign items instead"),
+ );
+ if let Unsafe::Yes(span) = unsafety {
+ self.err_handler().span_err(span, "extern block cannot be declared unsafe");
+ }
+ if abi.is_none() {
+ self.maybe_lint_missing_abi(item.span, item.id);
+ }
+ visit::walk_item(self, item);
+ self.extern_mod = old_item;
+ return; // Avoid visiting again.
+ }
+ ItemKind::Enum(ref def, _) => {
+ for variant in &def.variants {
+ self.invalid_visibility(&variant.vis, None);
+ for field in variant.data.fields() {
+ self.invalid_visibility(&field.vis, None);
+ }
+ }
+ }
+ ItemKind::Trait(box Trait { is_auto, ref generics, ref bounds, ref items, .. }) => {
+ if is_auto == IsAuto::Yes {
+ // Auto traits cannot have generics, super traits nor contain items.
+ self.deny_generic_params(generics, item.ident.span);
+ self.deny_super_traits(bounds, item.ident.span);
+ self.deny_where_clause(&generics.where_clause, item.ident.span);
+ self.deny_items(items, item.ident.span);
+ }
+
+ // Equivalent of `visit::walk_item` for `ItemKind::Trait` that inserts a bound
+ // context for the supertraits.
+ self.visit_vis(&item.vis);
+ self.visit_ident(item.ident);
+ self.visit_generics(generics);
+ self.with_tilde_const_allowed(|this| {
+ walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits)
+ });
+ walk_list!(self, visit_assoc_item, items, AssocCtxt::Trait);
+ walk_list!(self, visit_attribute, &item.attrs);
+ return;
+ }
+ ItemKind::Mod(unsafety, ref mod_kind) => {
+ if let Unsafe::Yes(span) = unsafety {
+ self.err_handler().span_err(span, "module cannot be declared unsafe");
+ }
+ // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
+ if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _))
+ && !self.session.contains_name(&item.attrs, sym::path)
+ {
+ self.check_mod_file_item_asciionly(item.ident);
+ }
+ }
+ ItemKind::Struct(ref vdata, ref generics) => match vdata {
+ // Duplicating the `Visitor` logic allows catching all cases
+ // of `Anonymous(Struct, Union)` outside of a field struct or union.
+ //
+ // Inside `visit_ty` the validator catches every `Anonymous(Struct, Union)` it
+ // encounters, and only on `ItemKind::Struct` and `ItemKind::Union`
+ // it uses `visit_ty_common`, which doesn't contain that specific check.
+ VariantData::Struct(ref fields, ..) => {
+ self.visit_vis(&item.vis);
+ self.visit_ident(item.ident);
+ self.visit_generics(generics);
+ self.with_banned_assoc_ty_bound(|this| {
+ walk_list!(this, visit_struct_field_def, fields);
+ });
+ walk_list!(self, visit_attribute, &item.attrs);
+ return;
+ }
+ _ => {}
+ },
+ ItemKind::Union(ref vdata, ref generics) => {
+ if vdata.fields().is_empty() {
+ self.err_handler().span_err(item.span, "unions cannot have zero fields");
+ }
+ match vdata {
+ VariantData::Struct(ref fields, ..) => {
+ self.visit_vis(&item.vis);
+ self.visit_ident(item.ident);
+ self.visit_generics(generics);
+ self.with_banned_assoc_ty_bound(|this| {
+ walk_list!(this, visit_struct_field_def, fields);
+ });
+ walk_list!(self, visit_attribute, &item.attrs);
+ return;
+ }
+ _ => {}
+ }
+ }
+ ItemKind::Const(def, .., None) => {
+ self.check_defaultness(item.span, def);
+ let msg = "free constant item without body";
+ self.error_item_without_body(item.span, "constant", msg, " = <expr>;");
+ }
+ ItemKind::Static(.., None) => {
+ let msg = "free static item without body";
+ self.error_item_without_body(item.span, "static", msg, " = <expr>;");
+ }
+ ItemKind::TyAlias(box TyAlias {
+ defaultness,
+ where_clauses,
+ ref bounds,
+ ref ty,
+ ..
+ }) => {
+ self.check_defaultness(item.span, defaultness);
+ if ty.is_none() {
+ let msg = "free type alias without body";
+ self.error_item_without_body(item.span, "type", msg, " = <type>;");
+ }
+ 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();
+ }
+ }
+ _ => {}
+ }
+
+ visit::walk_item(self, item);
+ }
+
+ fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
+ match &fi.kind {
+ ForeignItemKind::Fn(box Fn { defaultness, sig, body, .. }) => {
+ self.check_defaultness(fi.span, *defaultness);
+ self.check_foreign_fn_bodyless(fi.ident, body.as_deref());
+ self.check_foreign_fn_headerless(fi.ident, fi.span, sig.header);
+ self.check_foreign_item_ascii_only(fi.ident);
+ }
+ ForeignItemKind::TyAlias(box TyAlias {
+ defaultness,
+ generics,
+ where_clauses,
+ bounds,
+ ty,
+ ..
+ }) => {
+ self.check_defaultness(fi.span, *defaultness);
+ self.check_foreign_kind_bodyless(fi.ident, "type", ty.as_ref().map(|b| b.span));
+ self.check_type_no_bounds(bounds, "`extern` blocks");
+ self.check_foreign_ty_genericless(generics, where_clauses.0.1);
+ self.check_foreign_item_ascii_only(fi.ident);
+ }
+ ForeignItemKind::Static(_, _, body) => {
+ self.check_foreign_kind_bodyless(fi.ident, "static", body.as_ref().map(|b| b.span));
+ self.check_foreign_item_ascii_only(fi.ident);
+ }
+ ForeignItemKind::MacCall(..) => {}
+ }
+
+ visit::walk_foreign_item(self, fi)
+ }
+
+ // Mirrors `visit::walk_generic_args`, but tracks relevant state.
+ fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
+ match *generic_args {
+ GenericArgs::AngleBracketed(ref data) => {
+ self.check_generic_args_before_constraints(data);
+
+ for arg in &data.args {
+ match arg {
+ AngleBracketedArg::Arg(arg) => self.visit_generic_arg(arg),
+ // Type bindings such as `Item = impl Debug` in `Iterator<Item = Debug>`
+ // are allowed to contain nested `impl Trait`.
+ AngleBracketedArg::Constraint(constraint) => {
+ self.with_impl_trait(None, |this| {
+ this.visit_assoc_constraint_from_generic_args(constraint);
+ });
+ }
+ }
+ }
+ }
+ GenericArgs::Parenthesized(ref data) => {
+ walk_list!(self, visit_ty, &data.inputs);
+ if let FnRetTy::Ty(ty) = &data.output {
+ // `-> Foo` syntax is essentially an associated type binding,
+ // so it is also allowed to contain nested `impl Trait`.
+ self.with_impl_trait(None, |this| this.visit_ty(ty));
+ }
+ }
+ }
+ }
+
+ fn visit_generics(&mut self, generics: &'a Generics) {
+ let mut prev_param_default = None;
+ for param in &generics.params {
+ match param.kind {
+ GenericParamKind::Lifetime => (),
+ GenericParamKind::Type { default: Some(_), .. }
+ | GenericParamKind::Const { default: Some(_), .. } => {
+ prev_param_default = Some(param.ident.span);
+ }
+ 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();
+ break;
+ }
+ }
+ }
+ }
+
+ validate_generic_param_order(self.err_handler(), &generics.params, generics.span);
+
+ for predicate in &generics.where_clause.predicates {
+ if let WherePredicate::EqPredicate(ref predicate) = *predicate {
+ deny_equality_constraints(self, predicate, generics);
+ }
+ }
+ walk_list!(self, visit_generic_param, &generics.params);
+ 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,
+ // e.g., `T: for <'a> Foo<'a>` and `for <'a, 'b> &'b T: Foo<'a>`. If both are
+ // defined, then error.
+ if !bound_pred.bound_generic_params.is_empty() {
+ for bound in &bound_pred.bounds {
+ 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();
+ }
+ }
+ GenericBound::Outlives(_) => {}
+ }
+ }
+ }
+ }
+ _ => {}
+ }
+ self.visit_where_predicate(predicate);
+ }
+ }
+
+ fn visit_generic_param(&mut self, param: &'a GenericParam) {
+ if let GenericParamKind::Lifetime { .. } = param.kind {
+ self.check_lifetime(param.ident);
+ }
+ visit::walk_generic_param(self, param);
+ }
+
+ fn visit_param_bound(&mut self, bound: &'a GenericBound, ctxt: BoundKind) {
+ if let GenericBound::Trait(ref 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();
+ }
+ (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();
+ }
+ (_, TraitBoundModifier::MaybeConst) => {
+ if !self.is_tilde_const_allowed {
+ self.err_handler()
+ .struct_span_err(bound.span(), "`~const` is not allowed here")
+ .note("only allowed on bounds on traits' associated types and functions, const fns, const impls and its associated functions")
+ .emit();
+ }
+ }
+ (_, TraitBoundModifier::MaybeConstMaybe) => {
+ self.err_handler()
+ .span_err(bound.span(), "`~const` and `?` are mutually exclusive");
+ }
+ _ => {}
+ }
+ }
+
+ visit::walk_param_bound(self, bound)
+ }
+
+ fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
+ self.check_late_bound_lifetime_defs(&t.bound_generic_params);
+ visit::walk_poly_trait_ref(self, t, m);
+ }
+
+ 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,
+ generics: &'a Generics,
+ item_id: NodeId,
+ _: Span,
+ ) {
+ self.with_banned_assoc_ty_bound(|this| {
+ visit::walk_enum_def(this, enum_definition, generics, item_id)
+ })
+ }
+
+ 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() {
+ Some(FnCtxt::Assoc(_)) => SelfSemantic::Yes,
+ _ => SelfSemantic::No,
+ };
+ self.check_fn_decl(fk.decl(), self_semantic);
+
+ self.check_c_variadic_type(fk);
+
+ // Functions cannot both be `const async`
+ 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);
+ }
+
+ if let FnKind::Fn(
+ _,
+ _,
+ FnSig { span: sig_span, header: FnHeader { ext: Extern::Implicit(_), .. }, .. },
+ _,
+ _,
+ _,
+ ) = fk
+ {
+ self.maybe_lint_missing_abi(*sig_span, id);
+ }
+
+ // 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 diag = BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident);
+ self.lint_buffer.buffer_lint_with_diagnostic(
+ PATTERNS_IN_FNS_WITHOUT_BODY,
+ id,
+ span,
+ msg,
+ diag,
+ )
+ }
+ } else {
+ self.err_handler()
+ .struct_span_err(span, msg)
+ .span_label(span, label)
+ .code(code)
+ .emit();
+ }
+ });
+ }
+
+ let tilde_const_allowed =
+ matches!(fk.header(), Some(FnHeader { constness: Const::Yes(_), .. }))
+ || matches!(fk.ctxt(), Some(FnCtxt::Assoc(_)));
+
+ self.with_tilde_const(tilde_const_allowed, |this| visit::walk_fn(this, fk, span));
+ }
+
+ fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
+ if self.session.contains_name(&item.attrs, sym::no_mangle) {
+ self.check_nomangle_item_asciionly(item.ident, item.span);
+ }
+
+ if ctxt == AssocCtxt::Trait || !self.in_trait_impl {
+ self.check_defaultness(item.span, item.kind.defaultness());
+ }
+
+ if ctxt == AssocCtxt::Impl {
+ match &item.kind {
+ AssocItemKind::Const(_, _, body) => {
+ self.check_impl_item_provided(item.span, body, "constant", " = <expr>;");
+ }
+ AssocItemKind::Fn(box Fn { body, .. }) => {
+ self.check_impl_item_provided(item.span, body, "function", " { <body> }");
+ }
+ AssocItemKind::TyAlias(box TyAlias {
+ generics,
+ where_clauses,
+ where_predicates_split,
+ bounds,
+ ty,
+ ..
+ }) => {
+ self.check_impl_item_provided(item.span, ty, "type", " = <type>;");
+ self.check_type_no_bounds(bounds, "`impl`s");
+ if ty.is_some() {
+ self.check_gat_where(
+ item.id,
+ generics.where_clause.predicates.split_at(*where_predicates_split).0,
+ *where_clauses,
+ );
+ }
+ }
+ _ => {}
+ }
+ }
+
+ if ctxt == AssocCtxt::Trait || self.in_trait_impl {
+ self.invalid_visibility(&item.vis, None);
+ if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
+ self.check_trait_fn_not_const(sig.header.constness);
+ self.check_trait_fn_not_async(item.span, sig.header.asyncness);
+ }
+ }
+
+ if let AssocItemKind::Const(..) = item.kind {
+ self.check_item_named(item.ident, "const");
+ }
+
+ match item.kind {
+ AssocItemKind::TyAlias(box TyAlias { ref generics, ref bounds, ref ty, .. })
+ if ctxt == AssocCtxt::Trait =>
+ {
+ self.visit_vis(&item.vis);
+ self.visit_ident(item.ident);
+ walk_list!(self, visit_attribute, &item.attrs);
+ self.with_tilde_const_allowed(|this| {
+ this.visit_generics(generics);
+ walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
+ });
+ walk_list!(self, visit_ty, ty);
+ }
+ AssocItemKind::Fn(box Fn { ref sig, ref generics, ref body, .. })
+ if self.in_const_trait_impl
+ || ctxt == AssocCtxt::Trait
+ || matches!(sig.header.constness, Const::Yes(_)) =>
+ {
+ self.visit_vis(&item.vis);
+ self.visit_ident(item.ident);
+ let kind = FnKind::Fn(
+ FnCtxt::Assoc(ctxt),
+ item.ident,
+ sig,
+ &item.vis,
+ generics,
+ body.as_deref(),
+ );
+ self.visit_fn(kind, item.span, item.id);
+ }
+ _ => self
+ .with_in_trait_impl(false, None, |this| visit::walk_assoc_item(this, item, ctxt)),
+ }
+ }
+}
+
+/// When encountering an equality constraint in a `where` clause, emit an error. If the code seems
+/// like it's setting an associated type, provide an appropriate suggestion.
+fn deny_equality_constraints(
+ this: &mut AstValidator<'_>,
+ 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");
+
+ // Given `<A as Foo>::Bar = RhsTy`, suggest `A: Foo<Bar = RhsTy>`.
+ if let TyKind::Path(Some(qself), full_path) = &predicate.lhs_ty.kind {
+ if let TyKind::Path(None, path) = &qself.ty.kind {
+ match &path.segments[..] {
+ [PathSegment { ident, args: None, .. }] => {
+ for param in &generics.params {
+ if param.ident == *ident {
+ let param = ident;
+ match &full_path.segments[qself.position..] {
+ [PathSegment { ident, args, .. }] => {
+ // Make a new `Path` from `foo::Bar` to `Foo<Bar = RhsTy>`.
+ let mut assoc_path = full_path.clone();
+ // Remove `Bar` from `Foo::Bar`.
+ assoc_path.segments.pop();
+ let len = assoc_path.segments.len() - 1;
+ let gen_args = args.as_ref().map(|p| (**p).clone());
+ // Build `<Bar = RhsTy>`.
+ let arg = AngleBracketedArg::Constraint(AssocConstraint {
+ id: rustc_ast::node_id::DUMMY_NODE_ID,
+ ident: *ident,
+ gen_args,
+ kind: AssocConstraintKind::Equality {
+ term: predicate.rhs_ty.clone().into(),
+ },
+ span: ident.span,
+ });
+ // Add `<Bar = RhsTy>` to `Foo`.
+ match &mut assoc_path.segments[len].args {
+ Some(args) => match args.deref_mut() {
+ GenericArgs::Parenthesized(_) => continue,
+ GenericArgs::AngleBracketed(args) => {
+ args.args.push(arg);
+ }
+ },
+ empty_args => {
+ *empty_args = AngleBracketedArgs {
+ span: ident.span,
+ args: 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,
+ );
+ }
+ _ => {}
+ };
+ }
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ // Given `A: Foo, A::Bar = RhsTy`, suggest `A: Foo<Bar = RhsTy>`.
+ if let TyKind::Path(None, full_path) = &predicate.lhs_ty.kind {
+ if let [potential_param, potential_assoc] = &full_path.segments[..] {
+ for param in &generics.params {
+ if param.ident == potential_param.ident {
+ for bound in &param.bounds {
+ if let ast::GenericBound::Trait(trait_ref, TraitBoundModifier::None) = bound
+ {
+ if let [trait_segment] = &trait_ref.trait_ref.path.segments[..] {
+ let assoc = pprust::path_to_string(&ast::Path::from_ident(
+ potential_assoc.ident,
+ ));
+ let ty = pprust::ty_to_string(&predicate.rhs_ty);
+ let (args, span) = match &trait_segment.args {
+ Some(args) => match args.deref() {
+ ast::GenericArgs::AngleBracketed(args) => {
+ let Some(arg) = args.args.last() else {
+ continue;
+ };
+ (
+ format!(", {} = {}", assoc, ty),
+ arg.span().shrink_to_hi(),
+ )
+ }
+ _ => continue,
+ },
+ None => (
+ format!("<{} = {}>", assoc, ty),
+ 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.note(
+ "see issue #20041 <https://github.com/rust-lang/rust/issues/20041> for more information",
+ );
+ err.emit();
+}
+
+pub fn check_crate(session: &Session, krate: &Crate, lints: &mut LintBuffer) -> bool {
+ let mut validator = AstValidator {
+ session,
+ extern_mod: None,
+ in_trait_impl: false,
+ in_const_trait_impl: false,
+ has_proc_macro_decls: false,
+ outer_impl_trait: None,
+ is_tilde_const_allowed: false,
+ is_impl_trait_banned: false,
+ is_assoc_ty_bound_banned: false,
+ forbidden_let_reason: Some(ForbiddenLetReason::GenericForbidden),
+ lint_buffer: lints,
+ };
+ visit::walk_crate(&mut validator, krate);
+
+ validator.has_proc_macro_decls
+}
+
+/// Used to forbid `let` expressions in certain syntactic locations.
+#[derive(Clone, Copy)]
+enum ForbiddenLetReason {
+ /// `let` is not valid and the source environment is not important
+ GenericForbidden,
+ /// A let chain with the `||` operator
+ NotSupportedOr(Span),
+ /// A let chain with invalid parentheses
+ ///
+ /// For exemple, `let 1 = 1 && (expr && expr)` is allowed
+ /// but `(let 1 = 1 && (let 1 = 1 && (let 1 = 1))) && let a = 1` is not
+ NotSupportedParentheses(Span),
+}
diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs
new file mode 100644
index 000000000..789eca1f0
--- /dev/null
+++ b/compiler/rustc_ast_passes/src/feature_gate.rs
@@ -0,0 +1,901 @@
+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, VariantData};
+use rustc_errors::{struct_span_err, Applicability};
+use rustc_feature::{AttributeGate, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
+use rustc_feature::{Features, GateIssue};
+use rustc_session::parse::{feature_err, feature_err_issue};
+use rustc_session::Session;
+use rustc_span::source_map::Spanned;
+use rustc_span::symbol::sym;
+use rustc_span::Span;
+
+use tracing::debug;
+
+macro_rules! gate_feature_fn {
+ ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $help: expr) => {{
+ let (visitor, has_feature, span, name, explain, help) =
+ (&*$visitor, $has_feature, $span, $name, $explain, $help);
+ let has_feature: bool = has_feature(visitor.features);
+ debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
+ if !has_feature && !span.allows_unstable($name) {
+ feature_err_issue(&visitor.sess.parse_sess, name, span, GateIssue::Language, explain)
+ .help(help)
+ .emit();
+ }
+ }};
+ ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr) => {{
+ let (visitor, has_feature, span, name, explain) =
+ (&*$visitor, $has_feature, $span, $name, $explain);
+ let has_feature: bool = has_feature(visitor.features);
+ debug!("gate_feature(feature = {:?}, span = {:?}); has? {}", name, span, has_feature);
+ if !has_feature && !span.allows_unstable($name) {
+ feature_err_issue(&visitor.sess.parse_sess, name, span, GateIssue::Language, explain)
+ .emit();
+ }
+ }};
+}
+
+macro_rules! gate_feature_post {
+ ($visitor: expr, $feature: ident, $span: expr, $explain: expr, $help: expr) => {
+ gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain, $help)
+ };
+ ($visitor: expr, $feature: ident, $span: expr, $explain: expr) => {
+ gate_feature_fn!($visitor, |x: &Features| x.$feature, $span, sym::$feature, $explain)
+ };
+}
+
+pub fn check_attribute(attr: &ast::Attribute, sess: &Session, features: &Features) {
+ PostExpansionVisitor { sess, features }.visit_attribute(attr)
+}
+
+struct PostExpansionVisitor<'a> {
+ sess: &'a Session,
+
+ // `sess` contains a `Features`, but this might not be that one.
+ features: &'a Features,
+}
+
+impl<'a> PostExpansionVisitor<'a> {
+ fn check_abi(&self, abi: ast::StrLit, constness: ast::Const) {
+ let ast::StrLit { symbol_unescaped, span, .. } = abi;
+
+ if let ast::Const::Yes(_) = constness {
+ match symbol_unescaped {
+ // Stable
+ sym::Rust | sym::C => {}
+ abi => gate_feature_post!(
+ &self,
+ const_extern_fn,
+ span,
+ &format!("`{}` as a `const fn` ABI is unstable", abi)
+ ),
+ }
+ }
+
+ match symbol_unescaped.as_str() {
+ // Stable
+ "Rust" | "C" | "cdecl" | "stdcall" | "fastcall" | "aapcs" | "win64" | "sysv64"
+ | "system" => {}
+ "rust-intrinsic" => {
+ gate_feature_post!(&self, intrinsics, span, "intrinsics are subject to change");
+ }
+ "platform-intrinsic" => {
+ gate_feature_post!(
+ &self,
+ platform_intrinsics,
+ span,
+ "platform intrinsics are experimental and possibly buggy"
+ );
+ }
+ "vectorcall" => {
+ gate_feature_post!(
+ &self,
+ abi_vectorcall,
+ span,
+ "vectorcall is experimental and subject to change"
+ );
+ }
+ "thiscall" => {
+ gate_feature_post!(
+ &self,
+ abi_thiscall,
+ span,
+ "thiscall is experimental and subject to change"
+ );
+ }
+ "rust-call" => {
+ gate_feature_post!(
+ &self,
+ unboxed_closures,
+ span,
+ "rust-call ABI is subject to change"
+ );
+ }
+ "rust-cold" => {
+ gate_feature_post!(
+ &self,
+ rust_cold_cc,
+ span,
+ "rust-cold is experimental and subject to change"
+ );
+ }
+ "ptx-kernel" => {
+ gate_feature_post!(
+ &self,
+ abi_ptx,
+ span,
+ "PTX ABIs are experimental and subject to change"
+ );
+ }
+ "unadjusted" => {
+ gate_feature_post!(
+ &self,
+ abi_unadjusted,
+ span,
+ "unadjusted ABI is an implementation detail and perma-unstable"
+ );
+ }
+ "msp430-interrupt" => {
+ gate_feature_post!(
+ &self,
+ abi_msp430_interrupt,
+ span,
+ "msp430-interrupt ABI is experimental and subject to change"
+ );
+ }
+ "x86-interrupt" => {
+ gate_feature_post!(
+ &self,
+ abi_x86_interrupt,
+ span,
+ "x86-interrupt ABI is experimental and subject to change"
+ );
+ }
+ "amdgpu-kernel" => {
+ gate_feature_post!(
+ &self,
+ abi_amdgpu_kernel,
+ span,
+ "amdgpu-kernel ABI is experimental and subject to change"
+ );
+ }
+ "avr-interrupt" | "avr-non-blocking-interrupt" => {
+ gate_feature_post!(
+ &self,
+ abi_avr_interrupt,
+ span,
+ "avr-interrupt and avr-non-blocking-interrupt ABIs are experimental and subject to change"
+ );
+ }
+ "efiapi" => {
+ gate_feature_post!(
+ &self,
+ abi_efiapi,
+ span,
+ "efiapi ABI is experimental and subject to change"
+ );
+ }
+ "C-cmse-nonsecure-call" => {
+ gate_feature_post!(
+ &self,
+ abi_c_cmse_nonsecure_call,
+ span,
+ "C-cmse-nonsecure-call ABI is experimental and subject to change"
+ );
+ }
+ "C-unwind" => {
+ gate_feature_post!(
+ &self,
+ c_unwind,
+ span,
+ "C-unwind ABI is experimental and subject to change"
+ );
+ }
+ "stdcall-unwind" => {
+ gate_feature_post!(
+ &self,
+ c_unwind,
+ span,
+ "stdcall-unwind ABI is experimental and subject to change"
+ );
+ }
+ "system-unwind" => {
+ gate_feature_post!(
+ &self,
+ c_unwind,
+ span,
+ "system-unwind ABI is experimental and subject to change"
+ );
+ }
+ "thiscall-unwind" => {
+ gate_feature_post!(
+ &self,
+ c_unwind,
+ span,
+ "thiscall-unwind ABI is experimental and subject to change"
+ );
+ }
+ "cdecl-unwind" => {
+ gate_feature_post!(
+ &self,
+ c_unwind,
+ span,
+ "cdecl-unwind ABI is experimental and subject to change"
+ );
+ }
+ "fastcall-unwind" => {
+ gate_feature_post!(
+ &self,
+ c_unwind,
+ span,
+ "fastcall-unwind ABI is experimental and subject to change"
+ );
+ }
+ "vectorcall-unwind" => {
+ gate_feature_post!(
+ &self,
+ c_unwind,
+ span,
+ "vectorcall-unwind ABI is experimental and subject to change"
+ );
+ }
+ "aapcs-unwind" => {
+ gate_feature_post!(
+ &self,
+ c_unwind,
+ span,
+ "aapcs-unwind ABI is experimental and subject to change"
+ );
+ }
+ "win64-unwind" => {
+ gate_feature_post!(
+ &self,
+ c_unwind,
+ span,
+ "win64-unwind ABI is experimental and subject to change"
+ );
+ }
+ "sysv64-unwind" => {
+ gate_feature_post!(
+ &self,
+ c_unwind,
+ span,
+ "sysv64-unwind ABI is experimental and subject to change"
+ );
+ }
+ "wasm" => {
+ gate_feature_post!(
+ &self,
+ wasm_abi,
+ span,
+ "wasm ABI is experimental and subject to change"
+ );
+ }
+ abi => {
+ if self.sess.opts.pretty.map_or(true, |ppm| ppm.needs_hir()) {
+ self.sess.parse_sess.span_diagnostic.delay_span_bug(
+ span,
+ &format!("unrecognized ABI not caught in lowering: {}", abi),
+ );
+ }
+ }
+ }
+ }
+
+ fn check_extern(&self, ext: ast::Extern, constness: ast::Const) {
+ if let ast::Extern::Explicit(abi, _) = ext {
+ self.check_abi(abi, constness);
+ }
+ }
+
+ fn maybe_report_invalid_custom_discriminants(&self, variants: &[ast::Variant]) {
+ let has_fields = variants.iter().any(|variant| match variant.data {
+ VariantData::Tuple(..) | VariantData::Struct(..) => true,
+ VariantData::Unit(..) => false,
+ });
+
+ let discriminant_spans = variants
+ .iter()
+ .filter(|variant| match variant.data {
+ VariantData::Tuple(..) | VariantData::Struct(..) => false,
+ VariantData::Unit(..) => true,
+ })
+ .filter_map(|variant| variant.disr_expr.as_ref().map(|c| c.value.span))
+ .collect::<Vec<_>>();
+
+ if !discriminant_spans.is_empty() && has_fields {
+ let mut err = feature_err(
+ &self.sess.parse_sess,
+ sym::arbitrary_enum_discriminant,
+ discriminant_spans.clone(),
+ "custom discriminant values are not allowed in enums with tuple or struct variants",
+ );
+ for sp in discriminant_spans {
+ err.span_label(sp, "disallowed custom discriminant");
+ }
+ for variant in variants.iter() {
+ match &variant.data {
+ VariantData::Struct(..) => {
+ err.span_label(variant.span, "struct variant defined here");
+ }
+ VariantData::Tuple(..) => {
+ err.span_label(variant.span, "tuple variant defined here");
+ }
+ VariantData::Unit(..) => {}
+ }
+ }
+ err.emit();
+ }
+ }
+
+ fn check_gat(&self, generics: &ast::Generics, span: Span) {
+ if !generics.params.is_empty() {
+ gate_feature_post!(
+ &self,
+ generic_associated_types,
+ span,
+ "generic associated types are unstable"
+ );
+ }
+ if !generics.where_clause.predicates.is_empty() {
+ gate_feature_post!(
+ &self,
+ generic_associated_types,
+ span,
+ "where clauses on associated types are unstable"
+ );
+ }
+ }
+
+ /// Feature gate `impl Trait` inside `type Alias = $type_expr;`.
+ fn check_impl_trait(&self, ty: &ast::Ty) {
+ struct ImplTraitVisitor<'a> {
+ vis: &'a PostExpansionVisitor<'a>,
+ }
+ impl Visitor<'_> for ImplTraitVisitor<'_> {
+ fn visit_ty(&mut self, ty: &ast::Ty) {
+ if let ast::TyKind::ImplTrait(..) = ty.kind {
+ gate_feature_post!(
+ &self.vis,
+ type_alias_impl_trait,
+ ty.span,
+ "`impl Trait` in type aliases is unstable"
+ );
+ }
+ visit::walk_ty(self, ty);
+ }
+ }
+ ImplTraitVisitor { vis: self }.visit_ty(ty);
+ }
+}
+
+impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
+ fn visit_attribute(&mut self, attr: &ast::Attribute) {
+ let attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
+ // Check feature gates for built-in attributes.
+ if let Some(BuiltinAttribute {
+ gate: AttributeGate::Gated(_, name, descr, has_feature),
+ ..
+ }) = attr_info
+ {
+ gate_feature_fn!(self, has_feature, attr.span, *name, descr);
+ }
+ // Check unstable flavors of the `#[doc]` attribute.
+ if attr.has_name(sym::doc) {
+ for nested_meta in attr.meta_item_list().unwrap_or_default() {
+ macro_rules! gate_doc { ($($name:ident => $feature:ident)*) => {
+ $(if nested_meta.has_name(sym::$name) {
+ let msg = concat!("`#[doc(", stringify!($name), ")]` is experimental");
+ gate_feature_post!(self, $feature, attr.span, msg);
+ })*
+ }}
+
+ gate_doc!(
+ cfg => doc_cfg
+ cfg_hide => doc_cfg_hide
+ masked => doc_masked
+ notable_trait => doc_notable_trait
+ );
+
+ if nested_meta.has_name(sym::keyword) {
+ let msg = "`#[doc(keyword)]` is meant for internal use only";
+ gate_feature_post!(self, rustdoc_internals, attr.span, msg);
+ }
+
+ if nested_meta.has_name(sym::fake_variadic) {
+ let msg = "`#[doc(fake_variadic)]` is meant for internal use only";
+ gate_feature_post!(self, rustdoc_internals, attr.span, msg);
+ }
+ }
+ }
+
+ // Emit errors for non-staged-api crates.
+ if !self.features.staged_api {
+ if attr.has_name(sym::unstable)
+ || attr.has_name(sym::stable)
+ || attr.has_name(sym::rustc_const_unstable)
+ || attr.has_name(sym::rustc_const_stable)
+ {
+ struct_span_err!(
+ self.sess,
+ attr.span,
+ E0734,
+ "stability attributes may not be used outside of the standard library",
+ )
+ .emit();
+ }
+ }
+ }
+
+ fn visit_item(&mut self, i: &'a ast::Item) {
+ match i.kind {
+ ast::ItemKind::ForeignMod(ref foreign_module) => {
+ if let Some(abi) = foreign_module.abi {
+ self.check_abi(abi, ast::Const::No);
+ }
+ }
+
+ ast::ItemKind::Fn(..) => {
+ if self.sess.contains_name(&i.attrs, sym::start) {
+ gate_feature_post!(
+ &self,
+ start,
+ i.span,
+ "`#[start]` functions are experimental \
+ and their signature may change \
+ over time"
+ );
+ }
+ }
+
+ 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) {
+ if item.has_name(sym::simd) {
+ gate_feature_post!(
+ &self,
+ repr_simd,
+ attr.span,
+ "SIMD types are experimental and possibly buggy"
+ );
+ }
+ }
+ }
+ }
+
+ ast::ItemKind::Enum(ast::EnumDef { ref variants, .. }, ..) => {
+ for variant in variants {
+ match (&variant.data, &variant.disr_expr) {
+ (ast::VariantData::Unit(..), _) => {}
+ (_, Some(disr_expr)) => gate_feature_post!(
+ &self,
+ arbitrary_enum_discriminant,
+ disr_expr.value.span,
+ "discriminants on non-unit variants are experimental"
+ ),
+ _ => {}
+ }
+ }
+
+ let has_feature = self.features.arbitrary_enum_discriminant;
+ if !has_feature && !i.span.allows_unstable(sym::arbitrary_enum_discriminant) {
+ self.maybe_report_invalid_custom_discriminants(&variants);
+ }
+ }
+
+ ast::ItemKind::Impl(box ast::Impl { polarity, defaultness, ref of_trait, .. }) => {
+ if let ast::ImplPolarity::Negative(span) = polarity {
+ gate_feature_post!(
+ &self,
+ negative_impls,
+ span.to(of_trait.as_ref().map_or(span, |t| t.path.span)),
+ "negative trait bounds are not yet fully implemented; \
+ use marker types for now"
+ );
+ }
+
+ if let ast::Defaultness::Default(_) = defaultness {
+ gate_feature_post!(&self, specialization, i.span, "specialization is unstable");
+ }
+ }
+
+ ast::ItemKind::Trait(box ast::Trait { is_auto: ast::IsAuto::Yes, .. }) => {
+ gate_feature_post!(
+ &self,
+ auto_traits,
+ i.span,
+ "auto traits are experimental and possibly buggy"
+ );
+ }
+
+ ast::ItemKind::TraitAlias(..) => {
+ gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental");
+ }
+
+ ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => {
+ let msg = "`macro` is experimental";
+ gate_feature_post!(&self, decl_macro, i.span, msg);
+ }
+
+ ast::ItemKind::TyAlias(box ast::TyAlias { ty: Some(ref ty), .. }) => {
+ self.check_impl_trait(&ty)
+ }
+
+ _ => {}
+ }
+
+ visit::walk_item(self, i);
+ }
+
+ fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
+ match i.kind {
+ ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
+ let link_name = self.sess.first_attr_value_str_by_name(&i.attrs, sym::link_name);
+ let links_to_llvm =
+ link_name.map_or(false, |val| val.as_str().starts_with("llvm."));
+ if links_to_llvm {
+ gate_feature_post!(
+ &self,
+ link_llvm_intrinsics,
+ i.span,
+ "linking to LLVM intrinsics is experimental"
+ );
+ }
+ }
+ ast::ForeignItemKind::TyAlias(..) => {
+ gate_feature_post!(&self, extern_types, i.span, "extern types are experimental");
+ }
+ ast::ForeignItemKind::MacCall(..) => {}
+ }
+
+ visit::walk_foreign_item(self, i)
+ }
+
+ fn visit_ty(&mut self, ty: &'a ast::Ty) {
+ match ty.kind {
+ ast::TyKind::BareFn(ref bare_fn_ty) => {
+ // Function pointers cannot be `const`
+ self.check_extern(bare_fn_ty.ext, ast::Const::No);
+ }
+ ast::TyKind::Never => {
+ gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental");
+ }
+ _ => {}
+ }
+ visit::walk_ty(self, ty)
+ }
+
+ fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
+ if let ast::FnRetTy::Ty(ref output_ty) = *ret_ty {
+ if let ast::TyKind::Never = output_ty.kind {
+ // Do nothing.
+ } else {
+ self.visit_ty(output_ty)
+ }
+ }
+ }
+
+ fn visit_stmt(&mut self, stmt: &'a ast::Stmt) {
+ if let ast::StmtKind::Semi(expr) = &stmt.kind
+ && let ast::ExprKind::Assign(lhs, _, _) = &expr.kind
+ && let ast::ExprKind::Type(..) = lhs.kind
+ && self.sess.parse_sess.span_diagnostic.err_count() == 0
+ && !self.features.type_ascription
+ && !lhs.span.allows_unstable(sym::type_ascription)
+ {
+ // When we encounter a statement of the form `foo: Ty = val;`, this will emit a type
+ // ascription error, but the likely intention was to write a `let` statement. (#78907).
+ feature_err_issue(
+ &self.sess.parse_sess,
+ sym::type_ascription,
+ lhs.span,
+ GateIssue::Language,
+ "type ascription is experimental",
+ ).span_suggestion_verbose(
+ lhs.span.shrink_to_lo(),
+ "you might have meant to introduce a new binding",
+ "let ".to_string(),
+ Applicability::MachineApplicable,
+ ).emit();
+ }
+ visit::walk_stmt(self, stmt);
+ }
+
+ fn visit_expr(&mut self, e: &'a ast::Expr) {
+ match e.kind {
+ ast::ExprKind::Box(_) => {
+ gate_feature_post!(
+ &self,
+ box_syntax,
+ e.span,
+ "box expression syntax is experimental; you can call `Box::new` instead"
+ );
+ }
+ ast::ExprKind::Type(..) => {
+ // To avoid noise about type ascription in common syntax errors, only emit if it
+ // is the *only* error.
+ if self.sess.parse_sess.span_diagnostic.err_count() == 0 {
+ gate_feature_post!(
+ &self,
+ type_ascription,
+ e.span,
+ "type ascription is experimental"
+ );
+ }
+ }
+ ast::ExprKind::TryBlock(_) => {
+ gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
+ }
+ ast::ExprKind::Block(_, Some(label)) => {
+ gate_feature_post!(
+ &self,
+ label_break_value,
+ label.ident.span,
+ "labels on blocks are unstable"
+ );
+ }
+ _ => {}
+ }
+ visit::walk_expr(self, e)
+ }
+
+ fn visit_pat(&mut self, pattern: &'a ast::Pat) {
+ match &pattern.kind {
+ PatKind::Slice(pats) => {
+ for pat in pats {
+ let inner_pat = match &pat.kind {
+ PatKind::Ident(.., Some(pat)) => pat,
+ _ => pat,
+ };
+ if let PatKind::Range(Some(_), None, Spanned { .. }) = inner_pat.kind {
+ gate_feature_post!(
+ &self,
+ half_open_range_patterns,
+ pat.span,
+ "`X..` patterns in slices are experimental"
+ );
+ }
+ }
+ }
+ PatKind::Box(..) => {
+ gate_feature_post!(
+ &self,
+ box_patterns,
+ pattern.span,
+ "box pattern syntax is experimental"
+ );
+ }
+ PatKind::Range(_, Some(_), Spanned { node: RangeEnd::Excluded, .. }) => {
+ gate_feature_post!(
+ &self,
+ exclusive_range_pattern,
+ pattern.span,
+ "exclusive range pattern syntax is experimental"
+ );
+ }
+ _ => {}
+ }
+ visit::walk_pat(self, pattern)
+ }
+
+ 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 fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
+ gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable");
+ }
+
+ visit::walk_fn(self, fn_kind, span)
+ }
+
+ fn visit_assoc_constraint(&mut self, constraint: &'a AssocConstraint) {
+ if let AssocConstraintKind::Bound { .. } = constraint.kind {
+ gate_feature_post!(
+ &self,
+ associated_type_bounds,
+ constraint.span,
+ "associated type bounds are unstable"
+ )
+ }
+ visit::walk_assoc_constraint(self, constraint)
+ }
+
+ fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
+ let is_fn = match i.kind {
+ ast::AssocItemKind::Fn(_) => true,
+ ast::AssocItemKind::TyAlias(box ast::TyAlias { ref generics, ref ty, .. }) => {
+ if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
+ gate_feature_post!(
+ &self,
+ associated_type_defaults,
+ i.span,
+ "associated type defaults are unstable"
+ );
+ }
+ if let Some(ty) = ty {
+ self.check_impl_trait(ty);
+ }
+ self.check_gat(generics, i.span);
+ false
+ }
+ _ => false,
+ };
+ if let ast::Defaultness::Default(_) = i.kind.defaultness() {
+ // Limit `min_specialization` to only specializing functions.
+ gate_feature_fn!(
+ &self,
+ |x: &Features| x.specialization || (is_fn && x.min_specialization),
+ i.span,
+ sym::specialization,
+ "specialization is unstable"
+ );
+ }
+ visit::walk_assoc_item(self, i, ctxt)
+ }
+}
+
+pub fn check_crate(krate: &ast::Crate, sess: &Session) {
+ maybe_stage_features(sess, krate);
+ check_incompatible_features(sess);
+ let mut visitor = PostExpansionVisitor { sess, features: &sess.features_untracked() };
+
+ let spans = sess.parse_sess.gated_spans.spans.borrow();
+ macro_rules! gate_all {
+ ($gate:ident, $msg:literal, $help:literal) => {
+ if let Some(spans) = spans.get(&sym::$gate) {
+ for span in spans {
+ gate_feature_post!(&visitor, $gate, *span, $msg, $help);
+ }
+ }
+ };
+ ($gate:ident, $msg:literal) => {
+ if let Some(spans) = spans.get(&sym::$gate) {
+ for span in spans {
+ gate_feature_post!(&visitor, $gate, *span, $msg);
+ }
+ }
+ };
+ }
+ gate_all!(
+ if_let_guard,
+ "`if let` guards are experimental",
+ "you can write `if matches!(<expr>, <pattern>)` instead of `if let <pattern> = <expr>`"
+ );
+ gate_all!(let_chains, "`let` expressions in this position are unstable");
+ gate_all!(
+ async_closure,
+ "async closures are unstable",
+ "to use an async block, remove the `||`: `async {`"
+ );
+ gate_all!(
+ closure_lifetime_binder,
+ "`for<...>` binders for closures are experimental",
+ "consider removing `for<...>`"
+ );
+ gate_all!(more_qualified_paths, "usage of qualified paths in this context is experimental");
+ gate_all!(generators, "yield syntax is experimental");
+ gate_all!(raw_ref_op, "raw address of syntax is experimental");
+ gate_all!(const_trait_impl, "const trait impls are experimental");
+ gate_all!(half_open_range_patterns, "half-open range patterns are unstable");
+ gate_all!(inline_const, "inline-const is experimental");
+ gate_all!(inline_const_pat, "inline-const in pattern position is experimental");
+ gate_all!(associated_const_equality, "associated const equality is incomplete");
+ gate_all!(yeet_expr, "`do yeet` expression is experimental");
+
+ // All uses of `gate_all!` below this point were added in #65742,
+ // and subsequently disabled (with the non-early gating readded).
+ macro_rules! gate_all {
+ ($gate:ident, $msg:literal) => {
+ // FIXME(eddyb) do something more useful than always
+ // disabling these uses of early feature-gatings.
+ if false {
+ for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
+ gate_feature_post!(&visitor, $gate, *span, $msg);
+ }
+ }
+ };
+ }
+
+ gate_all!(trait_alias, "trait aliases are experimental");
+ gate_all!(associated_type_bounds, "associated type bounds are unstable");
+ gate_all!(decl_macro, "`macro` is experimental");
+ gate_all!(box_patterns, "box pattern syntax is experimental");
+ gate_all!(exclusive_range_pattern, "exclusive range pattern syntax is experimental");
+ gate_all!(try_blocks, "`try` blocks are unstable");
+ gate_all!(label_break_value, "labels on blocks are unstable");
+ gate_all!(box_syntax, "box expression syntax is experimental; you can call `Box::new` instead");
+ // To avoid noise about type ascription in common syntax errors,
+ // only emit if it is the *only* error. (Also check it last.)
+ if sess.parse_sess.span_diagnostic.err_count() == 0 {
+ gate_all!(type_ascription, "type ascription is experimental");
+ }
+
+ visit::walk_crate(&mut visitor, krate);
+}
+
+fn maybe_stage_features(sess: &Session, krate: &ast::Crate) {
+ // checks if `#![feature]` has been used to enable any lang feature
+ // does not check the same for lib features unless there's at least one
+ // declared lang feature
+ if !sess.opts.unstable_features.is_nightly_build() {
+ let lang_features = &sess.features_untracked().declared_lang_features;
+ if lang_features.len() == 0 {
+ 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 all_stable = true;
+ for ident in
+ attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident())
+ {
+ let name = ident.name;
+ let stable_since = lang_features
+ .iter()
+ .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
+ ));
+ } else {
+ all_stable = false;
+ }
+ }
+ if all_stable {
+ err.span_suggestion(
+ attr.span,
+ "remove the attribute",
+ "",
+ Applicability::MachineApplicable,
+ );
+ }
+ err.emit();
+ }
+ }
+}
+
+fn check_incompatible_features(sess: &Session) {
+ let features = sess.features_untracked();
+
+ let declared_features = features
+ .declared_lang_features
+ .iter()
+ .copied()
+ .map(|(name, span, _)| (name, span))
+ .chain(features.declared_lib_features.iter().copied());
+
+ for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES
+ .iter()
+ .filter(|&&(f1, f2)| features.enabled(f1) && features.enabled(f2))
+ {
+ if let Some((f1_name, f1_span)) = declared_features.clone().find(|(name, _)| name == f1) {
+ 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.clone(),
+ &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();
+ }
+ }
+ }
+}
diff --git a/compiler/rustc_ast_passes/src/lib.rs b/compiler/rustc_ast_passes/src/lib.rs
new file mode 100644
index 000000000..9d52c3288
--- /dev/null
+++ b/compiler/rustc_ast_passes/src/lib.rs
@@ -0,0 +1,18 @@
+//! The `rustc_ast_passes` crate contains passes which validate the AST in `syntax`
+//! parsed by `rustc_parse` and then lowered, after the passes in this crate,
+//! by `rustc_ast_lowering`.
+//!
+//! The crate also contains other misc AST visitors, e.g. `node_count` and `show_span`.
+
+#![allow(rustc::potential_query_instability)]
+#![feature(box_patterns)]
+#![feature(if_let_guard)]
+#![feature(iter_is_partitioned)]
+#![feature(let_chains)]
+#![feature(let_else)]
+#![recursion_limit = "256"]
+
+pub mod ast_validation;
+pub mod feature_gate;
+pub mod node_count;
+pub mod show_span;
diff --git a/compiler/rustc_ast_passes/src/node_count.rs b/compiler/rustc_ast_passes/src/node_count.rs
new file mode 100644
index 000000000..9c7369c83
--- /dev/null
+++ b/compiler/rustc_ast_passes/src/node_count.rs
@@ -0,0 +1,135 @@
+// Simply gives a rough count of the number of nodes in an AST.
+
+use rustc_ast::visit::*;
+use rustc_ast::*;
+use rustc_span::symbol::Ident;
+use rustc_span::Span;
+
+pub struct NodeCounter {
+ pub count: usize,
+}
+
+impl NodeCounter {
+ pub fn new() -> NodeCounter {
+ NodeCounter { count: 0 }
+ }
+}
+
+impl<'ast> Visitor<'ast> for NodeCounter {
+ fn visit_ident(&mut self, _ident: Ident) {
+ self.count += 1;
+ }
+ fn visit_foreign_item(&mut self, i: &ForeignItem) {
+ self.count += 1;
+ walk_foreign_item(self, i)
+ }
+ fn visit_item(&mut self, i: &Item) {
+ self.count += 1;
+ walk_item(self, i)
+ }
+ fn visit_local(&mut self, l: &Local) {
+ self.count += 1;
+ walk_local(self, l)
+ }
+ fn visit_block(&mut self, b: &Block) {
+ self.count += 1;
+ walk_block(self, b)
+ }
+ fn visit_stmt(&mut self, s: &Stmt) {
+ self.count += 1;
+ walk_stmt(self, s)
+ }
+ fn visit_arm(&mut self, a: &Arm) {
+ self.count += 1;
+ walk_arm(self, a)
+ }
+ fn visit_pat(&mut self, p: &Pat) {
+ self.count += 1;
+ walk_pat(self, p)
+ }
+ fn visit_expr(&mut self, ex: &Expr) {
+ self.count += 1;
+ walk_expr(self, ex)
+ }
+ fn visit_ty(&mut self, t: &Ty) {
+ self.count += 1;
+ walk_ty(self, t)
+ }
+ fn visit_generic_param(&mut self, param: &GenericParam) {
+ self.count += 1;
+ walk_generic_param(self, param)
+ }
+ fn visit_generics(&mut self, g: &Generics) {
+ self.count += 1;
+ walk_generics(self, g)
+ }
+ fn visit_fn(&mut self, fk: visit::FnKind<'_>, s: Span, _: NodeId) {
+ self.count += 1;
+ walk_fn(self, fk, s)
+ }
+ fn visit_assoc_item(&mut self, ti: &AssocItem, ctxt: AssocCtxt) {
+ self.count += 1;
+ walk_assoc_item(self, ti, ctxt);
+ }
+ fn visit_trait_ref(&mut self, t: &TraitRef) {
+ self.count += 1;
+ walk_trait_ref(self, t)
+ }
+ fn visit_param_bound(&mut self, bounds: &GenericBound, _ctxt: BoundKind) {
+ self.count += 1;
+ walk_param_bound(self, bounds)
+ }
+ fn visit_poly_trait_ref(&mut self, t: &PolyTraitRef, m: &TraitBoundModifier) {
+ self.count += 1;
+ walk_poly_trait_ref(self, t, m)
+ }
+ fn visit_variant_data(&mut self, s: &VariantData) {
+ self.count += 1;
+ walk_struct_def(self, s)
+ }
+ fn visit_field_def(&mut self, s: &FieldDef) {
+ self.count += 1;
+ walk_field_def(self, s)
+ }
+ fn visit_enum_def(
+ &mut self,
+ enum_definition: &EnumDef,
+ generics: &Generics,
+ item_id: NodeId,
+ _: Span,
+ ) {
+ self.count += 1;
+ walk_enum_def(self, enum_definition, generics, item_id)
+ }
+ fn visit_variant(&mut self, v: &Variant) {
+ self.count += 1;
+ walk_variant(self, v)
+ }
+ fn visit_lifetime(&mut self, lifetime: &Lifetime, _: visit::LifetimeCtxt) {
+ self.count += 1;
+ walk_lifetime(self, lifetime)
+ }
+ fn visit_mac_call(&mut self, mac: &MacCall) {
+ self.count += 1;
+ walk_mac(self, mac)
+ }
+ fn visit_path(&mut self, path: &Path, _id: NodeId) {
+ self.count += 1;
+ walk_path(self, path)
+ }
+ fn visit_use_tree(&mut self, use_tree: &UseTree, id: NodeId, _nested: bool) {
+ self.count += 1;
+ walk_use_tree(self, use_tree, id)
+ }
+ fn visit_generic_args(&mut self, path_span: Span, generic_args: &GenericArgs) {
+ self.count += 1;
+ walk_generic_args(self, path_span, generic_args)
+ }
+ fn visit_assoc_constraint(&mut self, constraint: &AssocConstraint) {
+ self.count += 1;
+ walk_assoc_constraint(self, constraint)
+ }
+ fn visit_attribute(&mut self, _attr: &Attribute) {
+ self.count += 1;
+ }
+}
diff --git a/compiler/rustc_ast_passes/src/show_span.rs b/compiler/rustc_ast_passes/src/show_span.rs
new file mode 100644
index 000000000..27637e311
--- /dev/null
+++ b/compiler/rustc_ast_passes/src/show_span.rs
@@ -0,0 +1,65 @@
+//! Span debugger
+//!
+//! This module shows spans for all expressions in the crate
+//! to help with compiler debugging.
+
+use std::str::FromStr;
+
+use rustc_ast as ast;
+use rustc_ast::visit;
+use rustc_ast::visit::Visitor;
+
+enum Mode {
+ Expression,
+ Pattern,
+ Type,
+}
+
+impl FromStr for Mode {
+ type Err = ();
+ fn from_str(s: &str) -> Result<Mode, ()> {
+ let mode = match s {
+ "expr" => Mode::Expression,
+ "pat" => Mode::Pattern,
+ "ty" => Mode::Type,
+ _ => return Err(()),
+ };
+ Ok(mode)
+ }
+}
+
+struct ShowSpanVisitor<'a> {
+ span_diagnostic: &'a rustc_errors::Handler,
+ mode: Mode,
+}
+
+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");
+ }
+ 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");
+ }
+ 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");
+ }
+ visit::walk_ty(self, t);
+ }
+}
+
+pub fn run(span_diagnostic: &rustc_errors::Handler, mode: &str, krate: &ast::Crate) {
+ let Ok(mode) = mode.parse() else {
+ return;
+ };
+ let mut v = ShowSpanVisitor { span_diagnostic, mode };
+ visit::walk_crate(&mut v, krate);
+}