]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_passes/src/ast_validation.rs
Rollup merge of #98101 - vladimir-ea:stdlib_watch_os, r=thomcc
[rust.git] / compiler / rustc_ast_passes / src / ast_validation.rs
1 // Validate AST before lowering it to HIR.
2 //
3 // This pass is supposed to catch things that fit into AST data structures,
4 // but not permitted by the language. It runs after expansion when AST is frozen,
5 // so it can check for erroneous constructions produced by syntax extensions.
6 // This pass is supposed to perform only simple checks not requiring name resolution
7 // or type checking or some other kind of complex analysis.
8
9 use itertools::{Either, Itertools};
10 use rustc_ast::ptr::P;
11 use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor};
12 use rustc_ast::walk_list;
13 use rustc_ast::*;
14 use rustc_ast_pretty::pprust::{self, State};
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_errors::{
17     error_code, pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorGuaranteed,
18 };
19 use rustc_parse::validate_attr;
20 use rustc_session::lint::builtin::{
21     DEPRECATED_WHERE_CLAUSE_LOCATION, MISSING_ABI, PATTERNS_IN_FNS_WITHOUT_BODY,
22 };
23 use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer};
24 use rustc_session::Session;
25 use rustc_span::source_map::Spanned;
26 use rustc_span::symbol::{kw, sym, Ident};
27 use rustc_span::Span;
28 use rustc_target::spec::abi;
29 use std::mem;
30 use std::ops::{Deref, DerefMut};
31
32 const MORE_EXTERN: &str =
33     "for more information, visit https://doc.rust-lang.org/std/keyword.extern.html";
34
35 /// Is `self` allowed semantically as the first parameter in an `FnDecl`?
36 enum SelfSemantic {
37     Yes,
38     No,
39 }
40
41 struct AstValidator<'a> {
42     session: &'a Session,
43
44     /// The span of the `extern` in an `extern { ... }` block, if any.
45     extern_mod: Option<&'a Item>,
46
47     /// Are we inside a trait impl?
48     in_trait_impl: bool,
49
50     in_const_trait_impl: bool,
51
52     has_proc_macro_decls: bool,
53
54     /// Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
55     /// Nested `impl Trait` _is_ allowed in associated type position,
56     /// e.g., `impl Iterator<Item = impl Debug>`.
57     outer_impl_trait: Option<Span>,
58
59     is_tilde_const_allowed: bool,
60
61     /// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
62     /// or `Foo::Bar<impl Trait>`
63     is_impl_trait_banned: bool,
64
65     /// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in
66     /// certain positions.
67     is_assoc_ty_bound_banned: bool,
68
69     /// See [ForbiddenLetReason]
70     forbidden_let_reason: Option<ForbiddenLetReason>,
71
72     lint_buffer: &'a mut LintBuffer,
73 }
74
75 impl<'a> AstValidator<'a> {
76     fn with_in_trait_impl(
77         &mut self,
78         is_in: bool,
79         constness: Option<Const>,
80         f: impl FnOnce(&mut Self),
81     ) {
82         let old = mem::replace(&mut self.in_trait_impl, is_in);
83         let old_const =
84             mem::replace(&mut self.in_const_trait_impl, matches!(constness, Some(Const::Yes(_))));
85         f(self);
86         self.in_trait_impl = old;
87         self.in_const_trait_impl = old_const;
88     }
89
90     fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
91         let old = mem::replace(&mut self.is_impl_trait_banned, true);
92         f(self);
93         self.is_impl_trait_banned = old;
94     }
95
96     fn with_tilde_const(&mut self, allowed: bool, f: impl FnOnce(&mut Self)) {
97         let old = mem::replace(&mut self.is_tilde_const_allowed, allowed);
98         f(self);
99         self.is_tilde_const_allowed = old;
100     }
101
102     fn with_tilde_const_allowed(&mut self, f: impl FnOnce(&mut Self)) {
103         self.with_tilde_const(true, f)
104     }
105
106     fn with_banned_tilde_const(&mut self, f: impl FnOnce(&mut Self)) {
107         self.with_tilde_const(false, f)
108     }
109
110     fn with_let_management(
111         &mut self,
112         forbidden_let_reason: Option<ForbiddenLetReason>,
113         f: impl FnOnce(&mut Self, Option<ForbiddenLetReason>),
114     ) {
115         let old = mem::replace(&mut self.forbidden_let_reason, forbidden_let_reason);
116         f(self, old);
117         self.forbidden_let_reason = old;
118     }
119
120     /// Emits an error banning the `let` expression provided in the given location.
121     fn ban_let_expr(&self, expr: &'a Expr, forbidden_let_reason: ForbiddenLetReason) {
122         let err = "`let` expressions are not supported here";
123         let mut diag = self.session.struct_span_err(expr.span, err);
124         diag.note("only supported directly in conditions of `if` and `while` expressions");
125         match forbidden_let_reason {
126             ForbiddenLetReason::GenericForbidden => {}
127             ForbiddenLetReason::NotSupportedOr(span) => {
128                 diag.span_note(span, "`||` operators are not supported in let chain expressions");
129             }
130             ForbiddenLetReason::NotSupportedParentheses(span) => {
131                 diag.span_note(
132                     span,
133                     "`let`s wrapped in parentheses are not supported in a context with let \
134                     chains",
135                 );
136             }
137         }
138         diag.emit();
139     }
140
141     fn check_gat_where(
142         &mut self,
143         id: NodeId,
144         before_predicates: &[WherePredicate],
145         where_clauses: (ast::TyAliasWhereClause, ast::TyAliasWhereClause),
146     ) {
147         if !before_predicates.is_empty() {
148             let mut state = State::new();
149             if !where_clauses.1.0 {
150                 state.space();
151                 state.word_space("where");
152             } else {
153                 state.word_space(",");
154             }
155             let mut first = true;
156             for p in before_predicates.iter() {
157                 if !first {
158                     state.word_space(",");
159                 }
160                 first = false;
161                 state.print_where_predicate(p);
162             }
163             let suggestion = state.s.eof();
164             self.lint_buffer.buffer_lint_with_diagnostic(
165                 DEPRECATED_WHERE_CLAUSE_LOCATION,
166                 id,
167                 where_clauses.0.1,
168                 "where clause not allowed here",
169                 BuiltinLintDiagnostics::DeprecatedWhereclauseLocation(
170                     where_clauses.1.1.shrink_to_hi(),
171                     suggestion,
172                 ),
173             );
174         }
175     }
176
177     fn with_banned_assoc_ty_bound(&mut self, f: impl FnOnce(&mut Self)) {
178         let old = mem::replace(&mut self.is_assoc_ty_bound_banned, true);
179         f(self);
180         self.is_assoc_ty_bound_banned = old;
181     }
182
183     fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
184         let old = mem::replace(&mut self.outer_impl_trait, outer);
185         if outer.is_some() {
186             self.with_banned_tilde_const(f);
187         } else {
188             f(self);
189         }
190         self.outer_impl_trait = old;
191     }
192
193     fn visit_assoc_constraint_from_generic_args(&mut self, constraint: &'a AssocConstraint) {
194         match constraint.kind {
195             AssocConstraintKind::Equality { .. } => {}
196             AssocConstraintKind::Bound { .. } => {
197                 if self.is_assoc_ty_bound_banned {
198                     self.err_handler().span_err(
199                         constraint.span,
200                         "associated type bounds are not allowed within structs, enums, or unions",
201                     );
202                 }
203             }
204         }
205         self.visit_assoc_constraint(constraint);
206     }
207
208     // Mirrors `visit::walk_ty`, but tracks relevant state.
209     fn walk_ty(&mut self, t: &'a Ty) {
210         match t.kind {
211             TyKind::ImplTrait(..) => {
212                 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
213             }
214             TyKind::TraitObject(..) => self.with_banned_tilde_const(|this| visit::walk_ty(this, t)),
215             TyKind::Path(ref qself, ref path) => {
216                 // We allow these:
217                 //  - `Option<impl Trait>`
218                 //  - `option::Option<impl Trait>`
219                 //  - `option::Option<T>::Foo<impl Trait>
220                 //
221                 // But not these:
222                 //  - `<impl Trait>::Foo`
223                 //  - `option::Option<impl Trait>::Foo`.
224                 //
225                 // To implement this, we disallow `impl Trait` from `qself`
226                 // (for cases like `<impl Trait>::Foo>`)
227                 // but we allow `impl Trait` in `GenericArgs`
228                 // iff there are no more PathSegments.
229                 if let Some(ref qself) = *qself {
230                     // `impl Trait` in `qself` is always illegal
231                     self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
232                 }
233
234                 // Note that there should be a call to visit_path here,
235                 // so if any logic is added to process `Path`s a call to it should be
236                 // added both in visit_path and here. This code mirrors visit::walk_path.
237                 for (i, segment) in path.segments.iter().enumerate() {
238                     // Allow `impl Trait` iff we're on the final path segment
239                     if i == path.segments.len() - 1 {
240                         self.visit_path_segment(path.span, segment);
241                     } else {
242                         self.with_banned_impl_trait(|this| {
243                             this.visit_path_segment(path.span, segment)
244                         });
245                     }
246                 }
247             }
248             _ => visit::walk_ty(self, t),
249         }
250     }
251
252     fn visit_struct_field_def(&mut self, field: &'a FieldDef) {
253         if let Some(ident) = field.ident {
254             if ident.name == kw::Underscore {
255                 self.visit_vis(&field.vis);
256                 self.visit_ident(ident);
257                 self.visit_ty_common(&field.ty);
258                 self.walk_ty(&field.ty);
259                 walk_list!(self, visit_attribute, &field.attrs);
260                 return;
261             }
262         }
263         self.visit_field_def(field);
264     }
265
266     fn err_handler(&self) -> &rustc_errors::Handler {
267         &self.session.diagnostic()
268     }
269
270     fn check_lifetime(&self, ident: Ident) {
271         let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Empty];
272         if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
273             self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
274         }
275     }
276
277     fn check_label(&self, ident: Ident) {
278         if ident.without_first_quote().is_reserved() {
279             self.err_handler()
280                 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
281         }
282     }
283
284     fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
285         if let VisibilityKind::Inherited = vis.kind {
286             return;
287         }
288
289         let mut err =
290             struct_span_err!(self.session, vis.span, E0449, "unnecessary visibility qualifier");
291         if vis.kind.is_pub() {
292             err.span_label(vis.span, "`pub` not permitted here because it's implied");
293         }
294         if let Some(note) = note {
295             err.note(note);
296         }
297         err.emit();
298     }
299
300     fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, Option<Ident>, bool)) {
301         for Param { pat, .. } in &decl.inputs {
302             match pat.kind {
303                 PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, None) | PatKind::Wild => {}
304                 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), ident, None) => {
305                     report_err(pat.span, Some(ident), true)
306                 }
307                 _ => report_err(pat.span, None, false),
308             }
309         }
310     }
311
312     fn check_trait_fn_not_async(&self, fn_span: Span, asyncness: Async) {
313         if let Async::Yes { span, .. } = asyncness {
314             struct_span_err!(
315                 self.session,
316                 fn_span,
317                 E0706,
318                 "functions in traits cannot be declared `async`"
319             )
320             .span_label(span, "`async` because of this")
321             .note("`async` trait functions are not currently supported")
322             .note("consider using the `async-trait` crate: https://crates.io/crates/async-trait")
323             .emit();
324         }
325     }
326
327     fn check_trait_fn_not_const(&self, constness: Const) {
328         if let Const::Yes(span) = constness {
329             struct_span_err!(
330                 self.session,
331                 span,
332                 E0379,
333                 "functions in traits cannot be declared const"
334             )
335             .span_label(span, "functions in traits cannot be const")
336             .emit();
337         }
338     }
339
340     fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
341         // Check only lifetime parameters are present and that the lifetime
342         // parameters that are present have no bounds.
343         let non_lt_param_spans: Vec<_> = params
344             .iter()
345             .filter_map(|param| match param.kind {
346                 GenericParamKind::Lifetime { .. } => {
347                     if !param.bounds.is_empty() {
348                         let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
349                         self.err_handler()
350                             .span_err(spans, "lifetime bounds cannot be used in this context");
351                     }
352                     None
353                 }
354                 _ => Some(param.ident.span),
355             })
356             .collect();
357         if !non_lt_param_spans.is_empty() {
358             self.err_handler().span_err(
359                 non_lt_param_spans,
360                 "only lifetime parameters can be used in this context",
361             );
362         }
363     }
364
365     fn check_fn_decl(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
366         self.check_decl_num_args(fn_decl);
367         self.check_decl_cvaradic_pos(fn_decl);
368         self.check_decl_attrs(fn_decl);
369         self.check_decl_self_param(fn_decl, self_semantic);
370     }
371
372     /// Emits fatal error if function declaration has more than `u16::MAX` arguments
373     /// Error is fatal to prevent errors during typechecking
374     fn check_decl_num_args(&self, fn_decl: &FnDecl) {
375         let max_num_args: usize = u16::MAX.into();
376         if fn_decl.inputs.len() > max_num_args {
377             let Param { span, .. } = fn_decl.inputs[0];
378             self.err_handler().span_fatal(
379                 span,
380                 &format!("function can not have more than {} arguments", max_num_args),
381             );
382         }
383     }
384
385     fn check_decl_cvaradic_pos(&self, fn_decl: &FnDecl) {
386         match &*fn_decl.inputs {
387             [Param { ty, span, .. }] => {
388                 if let TyKind::CVarArgs = ty.kind {
389                     self.err_handler().span_err(
390                         *span,
391                         "C-variadic function must be declared with at least one named argument",
392                     );
393                 }
394             }
395             [ps @ .., _] => {
396                 for Param { ty, span, .. } in ps {
397                     if let TyKind::CVarArgs = ty.kind {
398                         self.err_handler().span_err(
399                             *span,
400                             "`...` must be the last argument of a C-variadic function",
401                         );
402                     }
403                 }
404             }
405             _ => {}
406         }
407     }
408
409     fn check_decl_attrs(&self, fn_decl: &FnDecl) {
410         fn_decl
411             .inputs
412             .iter()
413             .flat_map(|i| i.attrs.as_ref())
414             .filter(|attr| {
415                 let arr = [
416                     sym::allow,
417                     sym::cfg,
418                     sym::cfg_attr,
419                     sym::deny,
420                     sym::expect,
421                     sym::forbid,
422                     sym::warn,
423                 ];
424                 !arr.contains(&attr.name_or_empty()) && rustc_attr::is_builtin_attr(attr)
425             })
426             .for_each(|attr| {
427                 if attr.is_doc_comment() {
428                     self.err_handler()
429                         .struct_span_err(
430                             attr.span,
431                             "documentation comments cannot be applied to function parameters",
432                         )
433                         .span_label(attr.span, "doc comments are not allowed here")
434                         .emit();
435                 } else {
436                     self.err_handler().span_err(
437                         attr.span,
438                         "allow, cfg, cfg_attr, deny, expect, \
439                 forbid, and warn are the only allowed built-in attributes in function parameters",
440                     );
441                 }
442             });
443     }
444
445     fn check_decl_self_param(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) {
446         if let (SelfSemantic::No, [param, ..]) = (self_semantic, &*fn_decl.inputs) {
447             if param.is_self() {
448                 self.err_handler()
449                     .struct_span_err(
450                         param.span,
451                         "`self` parameter is only allowed in associated functions",
452                     )
453                     .span_label(param.span, "not semantically valid as function parameter")
454                     .note("associated functions are those in `impl` or `trait` definitions")
455                     .emit();
456             }
457         }
458     }
459
460     fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
461         if let Defaultness::Default(def_span) = defaultness {
462             let span = self.session.source_map().guess_head_span(span);
463             self.err_handler()
464                 .struct_span_err(span, "`default` is only allowed on items in trait impls")
465                 .span_label(def_span, "`default` because of this")
466                 .emit();
467         }
468     }
469
470     fn error_item_without_body(&self, sp: Span, ctx: &str, msg: &str, sugg: &str) {
471         self.error_item_without_body_with_help(sp, ctx, msg, sugg, |_| ());
472     }
473
474     fn error_item_without_body_with_help(
475         &self,
476         sp: Span,
477         ctx: &str,
478         msg: &str,
479         sugg: &str,
480         help: impl FnOnce(&mut DiagnosticBuilder<'_, ErrorGuaranteed>),
481     ) {
482         let source_map = self.session.source_map();
483         let end = source_map.end_point(sp);
484         let replace_span = if source_map.span_to_snippet(end).map(|s| s == ";").unwrap_or(false) {
485             end
486         } else {
487             sp.shrink_to_hi()
488         };
489         let mut err = self.err_handler().struct_span_err(sp, msg);
490         err.span_suggestion(
491             replace_span,
492             &format!("provide a definition for the {}", ctx),
493             sugg,
494             Applicability::HasPlaceholders,
495         );
496         help(&mut err);
497         err.emit();
498     }
499
500     fn check_impl_item_provided<T>(&self, sp: Span, body: &Option<T>, ctx: &str, sugg: &str) {
501         if body.is_none() {
502             let msg = format!("associated {} in `impl` without body", ctx);
503             self.error_item_without_body(sp, ctx, &msg, sugg);
504         }
505     }
506
507     fn check_type_no_bounds(&self, bounds: &[GenericBound], ctx: &str) {
508         let span = match bounds {
509             [] => return,
510             [b0] => b0.span(),
511             [b0, .., bl] => b0.span().to(bl.span()),
512         };
513         self.err_handler()
514             .struct_span_err(span, &format!("bounds on `type`s in {} have no effect", ctx))
515             .emit();
516     }
517
518     fn check_foreign_ty_genericless(&self, generics: &Generics, where_span: Span) {
519         let cannot_have = |span, descr, remove_descr| {
520             self.err_handler()
521                 .struct_span_err(
522                     span,
523                     &format!("`type`s inside `extern` blocks cannot have {}", descr),
524                 )
525                 .span_suggestion(
526                     span,
527                     &format!("remove the {}", remove_descr),
528                     "",
529                     Applicability::MaybeIncorrect,
530                 )
531                 .span_label(self.current_extern_span(), "`extern` block begins here")
532                 .note(MORE_EXTERN)
533                 .emit();
534         };
535
536         if !generics.params.is_empty() {
537             cannot_have(generics.span, "generic parameters", "generic parameters");
538         }
539
540         if !generics.where_clause.predicates.is_empty() {
541             cannot_have(where_span, "`where` clauses", "`where` clause");
542         }
543     }
544
545     fn check_foreign_kind_bodyless(&self, ident: Ident, kind: &str, body: Option<Span>) {
546         let Some(body) = body else {
547             return;
548         };
549         self.err_handler()
550             .struct_span_err(ident.span, &format!("incorrect `{}` inside `extern` block", kind))
551             .span_label(ident.span, "cannot have a body")
552             .span_label(body, "the invalid body")
553             .span_label(
554                 self.current_extern_span(),
555                 format!(
556                     "`extern` blocks define existing foreign {0}s and {0}s \
557                     inside of them cannot have a body",
558                     kind
559                 ),
560             )
561             .note(MORE_EXTERN)
562             .emit();
563     }
564
565     /// An `fn` in `extern { ... }` cannot have a body `{ ... }`.
566     fn check_foreign_fn_bodyless(&self, ident: Ident, body: Option<&Block>) {
567         let Some(body) = body else {
568             return;
569         };
570         self.err_handler()
571             .struct_span_err(ident.span, "incorrect function inside `extern` block")
572             .span_label(ident.span, "cannot have a body")
573             .span_suggestion(
574                 body.span,
575                 "remove the invalid body",
576                 ";",
577                 Applicability::MaybeIncorrect,
578             )
579             .help(
580                 "you might have meant to write a function accessible through FFI, \
581                 which can be done by writing `extern fn` outside of the `extern` block",
582             )
583             .span_label(
584                 self.current_extern_span(),
585                 "`extern` blocks define existing foreign functions and functions \
586                 inside of them cannot have a body",
587             )
588             .note(MORE_EXTERN)
589             .emit();
590     }
591
592     fn current_extern_span(&self) -> Span {
593         self.session.source_map().guess_head_span(self.extern_mod.unwrap().span)
594     }
595
596     /// An `fn` in `extern { ... }` cannot have qualifiers, e.g. `async fn`.
597     fn check_foreign_fn_headerless(&self, ident: Ident, span: Span, header: FnHeader) {
598         if header.has_qualifiers() {
599             self.err_handler()
600                 .struct_span_err(ident.span, "functions in `extern` blocks cannot have qualifiers")
601                 .span_label(self.current_extern_span(), "in this `extern` block")
602                 .span_suggestion_verbose(
603                     span.until(ident.span.shrink_to_lo()),
604                     "remove the qualifiers",
605                     "fn ",
606                     Applicability::MaybeIncorrect,
607                 )
608                 .emit();
609         }
610     }
611
612     /// An item in `extern { ... }` cannot use non-ascii identifier.
613     fn check_foreign_item_ascii_only(&self, ident: Ident) {
614         if !ident.as_str().is_ascii() {
615             let n = 83942;
616             self.err_handler()
617                 .struct_span_err(
618                     ident.span,
619                     "items in `extern` blocks cannot use non-ascii identifiers",
620                 )
621                 .span_label(self.current_extern_span(), "in this `extern` block")
622                 .note(&format!(
623                     "this limitation may be lifted in the future; see issue #{} <https://github.com/rust-lang/rust/issues/{}> for more information",
624                     n, n,
625                 ))
626                 .emit();
627         }
628     }
629
630     /// Reject C-variadic type unless the function is foreign,
631     /// or free and `unsafe extern "C"` semantically.
632     fn check_c_variadic_type(&self, fk: FnKind<'a>) {
633         match (fk.ctxt(), fk.header()) {
634             (Some(FnCtxt::Foreign), _) => return,
635             (Some(FnCtxt::Free), Some(header)) => match header.ext {
636                 Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. }, _)
637                 | Extern::Implicit(_)
638                     if matches!(header.unsafety, Unsafe::Yes(_)) =>
639                 {
640                     return;
641                 }
642                 _ => {}
643             },
644             _ => {}
645         };
646
647         for Param { ty, span, .. } in &fk.decl().inputs {
648             if let TyKind::CVarArgs = ty.kind {
649                 self.err_handler()
650                     .struct_span_err(
651                         *span,
652                         "only foreign or `unsafe extern \"C\"` functions may be C-variadic",
653                     )
654                     .emit();
655             }
656         }
657     }
658
659     fn check_item_named(&self, ident: Ident, kind: &str) {
660         if ident.name != kw::Underscore {
661             return;
662         }
663         self.err_handler()
664             .struct_span_err(ident.span, &format!("`{}` items in this context need a name", kind))
665             .span_label(ident.span, format!("`_` is not a valid name for this `{}` item", kind))
666             .emit();
667     }
668
669     fn check_nomangle_item_asciionly(&self, ident: Ident, item_span: Span) {
670         if ident.name.as_str().is_ascii() {
671             return;
672         }
673         let head_span = self.session.source_map().guess_head_span(item_span);
674         struct_span_err!(
675             self.session,
676             head_span,
677             E0754,
678             "`#[no_mangle]` requires ASCII identifier"
679         )
680         .emit();
681     }
682
683     fn check_mod_file_item_asciionly(&self, ident: Ident) {
684         if ident.name.as_str().is_ascii() {
685             return;
686         }
687         struct_span_err!(
688             self.session,
689             ident.span,
690             E0754,
691             "trying to load file for module `{}` with non-ascii identifier name",
692             ident.name
693         )
694         .help("consider using `#[path]` attribute to specify filesystem path")
695         .emit();
696     }
697
698     fn deny_generic_params(&self, generics: &Generics, ident_span: Span) {
699         if !generics.params.is_empty() {
700             struct_span_err!(
701                 self.session,
702                 generics.span,
703                 E0567,
704                 "auto traits cannot have generic parameters"
705             )
706             .span_label(ident_span, "auto trait cannot have generic parameters")
707             .span_suggestion(
708                 generics.span,
709                 "remove the parameters",
710                 "",
711                 Applicability::MachineApplicable,
712             )
713             .emit();
714         }
715     }
716
717     fn emit_e0568(&self, span: Span, ident_span: Span) {
718         struct_span_err!(
719             self.session,
720             span,
721             E0568,
722             "auto traits cannot have super traits or lifetime bounds"
723         )
724         .span_label(ident_span, "auto trait cannot have super traits or lifetime bounds")
725         .span_suggestion(
726             span,
727             "remove the super traits or lifetime bounds",
728             "",
729             Applicability::MachineApplicable,
730         )
731         .emit();
732     }
733
734     fn deny_super_traits(&self, bounds: &GenericBounds, ident_span: Span) {
735         if let [.., last] = &bounds[..] {
736             let span = ident_span.shrink_to_hi().to(last.span());
737             self.emit_e0568(span, ident_span);
738         }
739     }
740
741     fn deny_where_clause(&self, where_clause: &WhereClause, ident_span: Span) {
742         if !where_clause.predicates.is_empty() {
743             self.emit_e0568(where_clause.span, ident_span);
744         }
745     }
746
747     fn deny_items(&self, trait_items: &[P<AssocItem>], ident_span: Span) {
748         if !trait_items.is_empty() {
749             let spans: Vec<_> = trait_items.iter().map(|i| i.ident.span).collect();
750             let total_span = trait_items.first().unwrap().span.to(trait_items.last().unwrap().span);
751             struct_span_err!(
752                 self.session,
753                 spans,
754                 E0380,
755                 "auto traits cannot have associated items"
756             )
757             .span_suggestion(
758                 total_span,
759                 "remove these associated items",
760                 "",
761                 Applicability::MachineApplicable,
762             )
763             .span_label(ident_span, "auto trait cannot have associated items")
764             .emit();
765         }
766     }
767
768     fn correct_generic_order_suggestion(&self, data: &AngleBracketedArgs) -> String {
769         // Lifetimes always come first.
770         let lt_sugg = data.args.iter().filter_map(|arg| match arg {
771             AngleBracketedArg::Arg(lt @ GenericArg::Lifetime(_)) => {
772                 Some(pprust::to_string(|s| s.print_generic_arg(lt)))
773             }
774             _ => None,
775         });
776         let args_sugg = data.args.iter().filter_map(|a| match a {
777             AngleBracketedArg::Arg(GenericArg::Lifetime(_)) | AngleBracketedArg::Constraint(_) => {
778                 None
779             }
780             AngleBracketedArg::Arg(arg) => Some(pprust::to_string(|s| s.print_generic_arg(arg))),
781         });
782         // Constraints always come last.
783         let constraint_sugg = data.args.iter().filter_map(|a| match a {
784             AngleBracketedArg::Arg(_) => None,
785             AngleBracketedArg::Constraint(c) => {
786                 Some(pprust::to_string(|s| s.print_assoc_constraint(c)))
787             }
788         });
789         format!(
790             "<{}>",
791             lt_sugg.chain(args_sugg).chain(constraint_sugg).collect::<Vec<String>>().join(", ")
792         )
793     }
794
795     /// Enforce generic args coming before constraints in `<...>` of a path segment.
796     fn check_generic_args_before_constraints(&self, data: &AngleBracketedArgs) {
797         // Early exit in case it's partitioned as it should be.
798         if data.args.iter().is_partitioned(|arg| matches!(arg, AngleBracketedArg::Arg(_))) {
799             return;
800         }
801         // Find all generic argument coming after the first constraint...
802         let (constraint_spans, arg_spans): (Vec<Span>, Vec<Span>) =
803             data.args.iter().partition_map(|arg| match arg {
804                 AngleBracketedArg::Constraint(c) => Either::Left(c.span),
805                 AngleBracketedArg::Arg(a) => Either::Right(a.span()),
806             });
807         let args_len = arg_spans.len();
808         let constraint_len = constraint_spans.len();
809         // ...and then error:
810         self.err_handler()
811             .struct_span_err(
812                 arg_spans.clone(),
813                 "generic arguments must come before the first constraint",
814             )
815             .span_label(constraint_spans[0], &format!("constraint{}", pluralize!(constraint_len)))
816             .span_label(
817                 *arg_spans.iter().last().unwrap(),
818                 &format!("generic argument{}", pluralize!(args_len)),
819             )
820             .span_labels(constraint_spans, "")
821             .span_labels(arg_spans, "")
822             .span_suggestion_verbose(
823                 data.span,
824                 &format!(
825                     "move the constraint{} after the generic argument{}",
826                     pluralize!(constraint_len),
827                     pluralize!(args_len)
828                 ),
829                 self.correct_generic_order_suggestion(&data),
830                 Applicability::MachineApplicable,
831             )
832             .emit();
833     }
834
835     fn visit_ty_common(&mut self, ty: &'a Ty) {
836         match ty.kind {
837             TyKind::BareFn(ref bfty) => {
838                 self.check_fn_decl(&bfty.decl, SelfSemantic::No);
839                 Self::check_decl_no_pat(&bfty.decl, |span, _, _| {
840                     struct_span_err!(
841                         self.session,
842                         span,
843                         E0561,
844                         "patterns aren't allowed in function pointer types"
845                     )
846                     .emit();
847                 });
848                 self.check_late_bound_lifetime_defs(&bfty.generic_params);
849                 if let Extern::Implicit(_) = bfty.ext {
850                     let sig_span = self.session.source_map().next_point(ty.span.shrink_to_lo());
851                     self.maybe_lint_missing_abi(sig_span, ty.id);
852                 }
853             }
854             TyKind::TraitObject(ref bounds, ..) => {
855                 let mut any_lifetime_bounds = false;
856                 for bound in bounds {
857                     if let GenericBound::Outlives(ref lifetime) = *bound {
858                         if any_lifetime_bounds {
859                             struct_span_err!(
860                                 self.session,
861                                 lifetime.ident.span,
862                                 E0226,
863                                 "only a single explicit lifetime bound is permitted"
864                             )
865                             .emit();
866                             break;
867                         }
868                         any_lifetime_bounds = true;
869                     }
870                 }
871             }
872             TyKind::ImplTrait(_, ref bounds) => {
873                 if self.is_impl_trait_banned {
874                     struct_span_err!(
875                         self.session,
876                         ty.span,
877                         E0667,
878                         "`impl Trait` is not allowed in path parameters"
879                     )
880                     .emit();
881                 }
882
883                 if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
884                     struct_span_err!(
885                         self.session,
886                         ty.span,
887                         E0666,
888                         "nested `impl Trait` is not allowed"
889                     )
890                     .span_label(outer_impl_trait_sp, "outer `impl Trait`")
891                     .span_label(ty.span, "nested `impl Trait` here")
892                     .emit();
893                 }
894
895                 if !bounds.iter().any(|b| matches!(b, GenericBound::Trait(..))) {
896                     self.err_handler().span_err(ty.span, "at least one trait must be specified");
897                 }
898             }
899             _ => {}
900         }
901     }
902
903     fn maybe_lint_missing_abi(&mut self, span: Span, id: NodeId) {
904         // FIXME(davidtwco): This is a hack to detect macros which produce spans of the
905         // call site which do not have a macro backtrace. See #61963.
906         let is_macro_callsite = self
907             .session
908             .source_map()
909             .span_to_snippet(span)
910             .map(|snippet| snippet.starts_with("#["))
911             .unwrap_or(true);
912         if !is_macro_callsite {
913             self.lint_buffer.buffer_lint_with_diagnostic(
914                 MISSING_ABI,
915                 id,
916                 span,
917                 "extern declarations without an explicit ABI are deprecated",
918                 BuiltinLintDiagnostics::MissingAbi(span, abi::Abi::FALLBACK),
919             )
920         }
921     }
922 }
923
924 /// Checks that generic parameters are in the correct order,
925 /// which is lifetimes, then types and then consts. (`<'a, T, const N: usize>`)
926 fn validate_generic_param_order(
927     handler: &rustc_errors::Handler,
928     generics: &[GenericParam],
929     span: Span,
930 ) {
931     let mut max_param: Option<ParamKindOrd> = None;
932     let mut out_of_order = FxHashMap::default();
933     let mut param_idents = Vec::with_capacity(generics.len());
934
935     for (idx, param) in generics.iter().enumerate() {
936         let ident = param.ident;
937         let (kind, bounds, span) = (&param.kind, &param.bounds, ident.span);
938         let (ord_kind, ident) = match &param.kind {
939             GenericParamKind::Lifetime => (ParamKindOrd::Lifetime, ident.to_string()),
940             GenericParamKind::Type { default: _ } => (ParamKindOrd::Type, ident.to_string()),
941             GenericParamKind::Const { ref ty, kw_span: _, default: _ } => {
942                 let ty = pprust::ty_to_string(ty);
943                 (ParamKindOrd::Const, format!("const {}: {}", ident, ty))
944             }
945         };
946         param_idents.push((kind, ord_kind, bounds, idx, ident));
947         match max_param {
948             Some(max_param) if max_param > ord_kind => {
949                 let entry = out_of_order.entry(ord_kind).or_insert((max_param, vec![]));
950                 entry.1.push(span);
951             }
952             Some(_) | None => max_param = Some(ord_kind),
953         };
954     }
955
956     if !out_of_order.is_empty() {
957         let mut ordered_params = "<".to_string();
958         param_idents.sort_by_key(|&(_, po, _, i, _)| (po, i));
959         let mut first = true;
960         for (kind, _, bounds, _, ident) in param_idents {
961             if !first {
962                 ordered_params += ", ";
963             }
964             ordered_params += &ident;
965
966             if !bounds.is_empty() {
967                 ordered_params += ": ";
968                 ordered_params += &pprust::bounds_to_string(&bounds);
969             }
970
971             match kind {
972                 GenericParamKind::Type { default: Some(default) } => {
973                     ordered_params += " = ";
974                     ordered_params += &pprust::ty_to_string(default);
975                 }
976                 GenericParamKind::Type { default: None } => (),
977                 GenericParamKind::Lifetime => (),
978                 GenericParamKind::Const { ty: _, kw_span: _, default: Some(default) } => {
979                     ordered_params += " = ";
980                     ordered_params += &pprust::expr_to_string(&*default.value);
981                 }
982                 GenericParamKind::Const { ty: _, kw_span: _, default: None } => (),
983             }
984             first = false;
985         }
986
987         ordered_params += ">";
988
989         for (param_ord, (max_param, spans)) in &out_of_order {
990             let mut err = handler.struct_span_err(
991                 spans.clone(),
992                 &format!(
993                     "{} parameters must be declared prior to {} parameters",
994                     param_ord, max_param,
995                 ),
996             );
997             err.span_suggestion(
998                 span,
999                 "reorder the parameters: lifetimes, then consts and types",
1000                 &ordered_params,
1001                 Applicability::MachineApplicable,
1002             );
1003             err.emit();
1004         }
1005     }
1006 }
1007
1008 impl<'a> Visitor<'a> for AstValidator<'a> {
1009     fn visit_attribute(&mut self, attr: &Attribute) {
1010         validate_attr::check_meta(&self.session.parse_sess, attr);
1011     }
1012
1013     fn visit_expr(&mut self, expr: &'a Expr) {
1014         self.with_let_management(Some(ForbiddenLetReason::GenericForbidden), |this, forbidden_let_reason| {
1015             match &expr.kind {
1016                 ExprKind::Binary(Spanned { node: BinOpKind::Or, span }, lhs, rhs) => {
1017                     let local_reason = Some(ForbiddenLetReason::NotSupportedOr(*span));
1018                     this.with_let_management(local_reason, |this, _| this.visit_expr(lhs));
1019                     this.with_let_management(local_reason, |this, _| this.visit_expr(rhs));
1020                 }
1021                 ExprKind::If(cond, then, opt_else) => {
1022                     this.visit_block(then);
1023                     walk_list!(this, visit_expr, opt_else);
1024                     this.with_let_management(None, |this, _| this.visit_expr(cond));
1025                     return;
1026                 }
1027                 ExprKind::Let(..) if let Some(elem) = forbidden_let_reason => {
1028                     this.ban_let_expr(expr, elem);
1029                 },
1030                 ExprKind::Match(scrutinee, arms) => {
1031                     this.visit_expr(scrutinee);
1032                     for arm in arms {
1033                         this.visit_expr(&arm.body);
1034                         this.visit_pat(&arm.pat);
1035                         walk_list!(this, visit_attribute, &arm.attrs);
1036                         if let Some(guard) = &arm.guard && let ExprKind::Let(_, guard_expr, _) = &guard.kind {
1037                             this.with_let_management(None, |this, _| {
1038                                 this.visit_expr(guard_expr)
1039                             });
1040                             return;
1041                         }
1042                     }
1043                 }
1044                 ExprKind::Paren(local_expr) => {
1045                     fn has_let_expr(expr: &Expr) -> bool {
1046                         match expr.kind {
1047                             ExprKind::Binary(_, ref lhs, ref rhs) => has_let_expr(lhs) || has_let_expr(rhs),
1048                             ExprKind::Let(..) => true,
1049                             _ => false,
1050                         }
1051                     }
1052                     let local_reason = if has_let_expr(local_expr) {
1053                         Some(ForbiddenLetReason::NotSupportedParentheses(local_expr.span))
1054                     }
1055                     else {
1056                         forbidden_let_reason
1057                     };
1058                     this.with_let_management(local_reason, |this, _| this.visit_expr(local_expr));
1059                 }
1060                 ExprKind::Binary(Spanned { node: BinOpKind::And, .. }, ..) => {
1061                     this.with_let_management(forbidden_let_reason, |this, _| visit::walk_expr(this, expr));
1062                     return;
1063                 }
1064                 ExprKind::While(cond, then, opt_label) => {
1065                     walk_list!(this, visit_label, opt_label);
1066                     this.visit_block(then);
1067                     this.with_let_management(None, |this, _| this.visit_expr(cond));
1068                     return;
1069                 }
1070                 _ => visit::walk_expr(this, expr),
1071             }
1072         });
1073     }
1074
1075     fn visit_ty(&mut self, ty: &'a Ty) {
1076         self.visit_ty_common(ty);
1077         self.walk_ty(ty)
1078     }
1079
1080     fn visit_label(&mut self, label: &'a Label) {
1081         self.check_label(label.ident);
1082         visit::walk_label(self, label);
1083     }
1084
1085     fn visit_lifetime(&mut self, lifetime: &'a Lifetime, _: visit::LifetimeCtxt) {
1086         self.check_lifetime(lifetime.ident);
1087         visit::walk_lifetime(self, lifetime);
1088     }
1089
1090     fn visit_field_def(&mut self, s: &'a FieldDef) {
1091         visit::walk_field_def(self, s)
1092     }
1093
1094     fn visit_item(&mut self, item: &'a Item) {
1095         if item.attrs.iter().any(|attr| self.session.is_proc_macro_attr(attr)) {
1096             self.has_proc_macro_decls = true;
1097         }
1098
1099         if self.session.contains_name(&item.attrs, sym::no_mangle) {
1100             self.check_nomangle_item_asciionly(item.ident, item.span);
1101         }
1102
1103         match item.kind {
1104             ItemKind::Impl(box Impl {
1105                 unsafety,
1106                 polarity,
1107                 defaultness: _,
1108                 constness,
1109                 ref generics,
1110                 of_trait: Some(ref t),
1111                 ref self_ty,
1112                 ref items,
1113             }) => {
1114                 self.with_in_trait_impl(true, Some(constness), |this| {
1115                     this.invalid_visibility(&item.vis, None);
1116                     if let TyKind::Err = self_ty.kind {
1117                         this.err_handler()
1118                             .struct_span_err(
1119                                 item.span,
1120                                 "`impl Trait for .. {}` is an obsolete syntax",
1121                             )
1122                             .help("use `auto trait Trait {}` instead")
1123                             .emit();
1124                     }
1125                     if let (Unsafe::Yes(span), ImplPolarity::Negative(sp)) = (unsafety, polarity) {
1126                         struct_span_err!(
1127                             this.session,
1128                             sp.to(t.path.span),
1129                             E0198,
1130                             "negative impls cannot be unsafe"
1131                         )
1132                         .span_label(sp, "negative because of this")
1133                         .span_label(span, "unsafe because of this")
1134                         .emit();
1135                     }
1136
1137                     this.visit_vis(&item.vis);
1138                     this.visit_ident(item.ident);
1139                     if let Const::Yes(_) = constness {
1140                         this.with_tilde_const_allowed(|this| this.visit_generics(generics));
1141                     } else {
1142                         this.visit_generics(generics);
1143                     }
1144                     this.visit_trait_ref(t);
1145                     this.visit_ty(self_ty);
1146
1147                     walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl);
1148                 });
1149                 return; // Avoid visiting again.
1150             }
1151             ItemKind::Impl(box Impl {
1152                 unsafety,
1153                 polarity,
1154                 defaultness,
1155                 constness,
1156                 generics: _,
1157                 of_trait: None,
1158                 ref self_ty,
1159                 items: _,
1160             }) => {
1161                 let error = |annotation_span, annotation| {
1162                     let mut err = self.err_handler().struct_span_err(
1163                         self_ty.span,
1164                         &format!("inherent impls cannot be {}", annotation),
1165                     );
1166                     err.span_label(annotation_span, &format!("{} because of this", annotation));
1167                     err.span_label(self_ty.span, "inherent impl for this type");
1168                     err
1169                 };
1170
1171                 self.invalid_visibility(
1172                     &item.vis,
1173                     Some("place qualifiers on individual impl items instead"),
1174                 );
1175                 if let Unsafe::Yes(span) = unsafety {
1176                     error(span, "unsafe").code(error_code!(E0197)).emit();
1177                 }
1178                 if let ImplPolarity::Negative(span) = polarity {
1179                     error(span, "negative").emit();
1180                 }
1181                 if let Defaultness::Default(def_span) = defaultness {
1182                     error(def_span, "`default`")
1183                         .note("only trait implementations may be annotated with `default`")
1184                         .emit();
1185                 }
1186                 if let Const::Yes(span) = constness {
1187                     error(span, "`const`")
1188                         .note("only trait implementations may be annotated with `const`")
1189                         .emit();
1190                 }
1191             }
1192             ItemKind::Fn(box Fn { defaultness, ref sig, ref generics, ref body }) => {
1193                 self.check_defaultness(item.span, defaultness);
1194
1195                 if body.is_none() {
1196                     let msg = "free function without a body";
1197                     let ext = sig.header.ext;
1198
1199                     let f = |e: &mut DiagnosticBuilder<'_, _>| {
1200                         if let Extern::Implicit(start_span) | Extern::Explicit(_, start_span) = &ext
1201                         {
1202                             let start_suggestion = if let Extern::Explicit(abi, _) = ext {
1203                                 format!("extern \"{}\" {{", abi.symbol_unescaped)
1204                             } else {
1205                                 "extern {".to_owned()
1206                             };
1207
1208                             let end_suggestion = " }".to_owned();
1209                             let end_span = item.span.shrink_to_hi();
1210
1211                             e
1212                             .multipart_suggestion(
1213                                 "if you meant to declare an externally defined function, use an `extern` block",
1214                                 vec![(*start_span, start_suggestion), (end_span, end_suggestion)],
1215                                 Applicability::MaybeIncorrect,
1216                              );
1217                         }
1218                     };
1219
1220                     self.error_item_without_body_with_help(
1221                         item.span,
1222                         "function",
1223                         msg,
1224                         " { <body> }",
1225                         f,
1226                     );
1227                 }
1228
1229                 self.visit_vis(&item.vis);
1230                 self.visit_ident(item.ident);
1231                 let kind =
1232                     FnKind::Fn(FnCtxt::Free, item.ident, sig, &item.vis, generics, body.as_deref());
1233                 self.visit_fn(kind, item.span, item.id);
1234                 walk_list!(self, visit_attribute, &item.attrs);
1235                 return; // Avoid visiting again.
1236             }
1237             ItemKind::ForeignMod(ForeignMod { abi, unsafety, .. }) => {
1238                 let old_item = mem::replace(&mut self.extern_mod, Some(item));
1239                 self.invalid_visibility(
1240                     &item.vis,
1241                     Some("place qualifiers on individual foreign items instead"),
1242                 );
1243                 if let Unsafe::Yes(span) = unsafety {
1244                     self.err_handler().span_err(span, "extern block cannot be declared unsafe");
1245                 }
1246                 if abi.is_none() {
1247                     self.maybe_lint_missing_abi(item.span, item.id);
1248                 }
1249                 visit::walk_item(self, item);
1250                 self.extern_mod = old_item;
1251                 return; // Avoid visiting again.
1252             }
1253             ItemKind::Enum(ref def, _) => {
1254                 for variant in &def.variants {
1255                     self.invalid_visibility(&variant.vis, None);
1256                     for field in variant.data.fields() {
1257                         self.invalid_visibility(&field.vis, None);
1258                     }
1259                 }
1260             }
1261             ItemKind::Trait(box Trait { is_auto, ref generics, ref bounds, ref items, .. }) => {
1262                 if is_auto == IsAuto::Yes {
1263                     // Auto traits cannot have generics, super traits nor contain items.
1264                     self.deny_generic_params(generics, item.ident.span);
1265                     self.deny_super_traits(bounds, item.ident.span);
1266                     self.deny_where_clause(&generics.where_clause, item.ident.span);
1267                     self.deny_items(items, item.ident.span);
1268                 }
1269
1270                 // Equivalent of `visit::walk_item` for `ItemKind::Trait` that inserts a bound
1271                 // context for the supertraits.
1272                 self.visit_vis(&item.vis);
1273                 self.visit_ident(item.ident);
1274                 self.visit_generics(generics);
1275                 self.with_banned_tilde_const(|this| {
1276                     walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits)
1277                 });
1278                 walk_list!(self, visit_assoc_item, items, AssocCtxt::Trait);
1279                 walk_list!(self, visit_attribute, &item.attrs);
1280                 return;
1281             }
1282             ItemKind::Mod(unsafety, ref mod_kind) => {
1283                 if let Unsafe::Yes(span) = unsafety {
1284                     self.err_handler().span_err(span, "module cannot be declared unsafe");
1285                 }
1286                 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
1287                 if !matches!(mod_kind, ModKind::Loaded(_, Inline::Yes, _))
1288                     && !self.session.contains_name(&item.attrs, sym::path)
1289                 {
1290                     self.check_mod_file_item_asciionly(item.ident);
1291                 }
1292             }
1293             ItemKind::Struct(ref vdata, ref generics) => match vdata {
1294                 // Duplicating the `Visitor` logic allows catching all cases
1295                 // of `Anonymous(Struct, Union)` outside of a field struct or union.
1296                 //
1297                 // Inside `visit_ty` the validator catches every `Anonymous(Struct, Union)` it
1298                 // encounters, and only on `ItemKind::Struct` and `ItemKind::Union`
1299                 // it uses `visit_ty_common`, which doesn't contain that specific check.
1300                 VariantData::Struct(ref fields, ..) => {
1301                     self.visit_vis(&item.vis);
1302                     self.visit_ident(item.ident);
1303                     self.visit_generics(generics);
1304                     self.with_banned_assoc_ty_bound(|this| {
1305                         walk_list!(this, visit_struct_field_def, fields);
1306                     });
1307                     walk_list!(self, visit_attribute, &item.attrs);
1308                     return;
1309                 }
1310                 _ => {}
1311             },
1312             ItemKind::Union(ref vdata, ref generics) => {
1313                 if vdata.fields().is_empty() {
1314                     self.err_handler().span_err(item.span, "unions cannot have zero fields");
1315                 }
1316                 match vdata {
1317                     VariantData::Struct(ref fields, ..) => {
1318                         self.visit_vis(&item.vis);
1319                         self.visit_ident(item.ident);
1320                         self.visit_generics(generics);
1321                         self.with_banned_assoc_ty_bound(|this| {
1322                             walk_list!(this, visit_struct_field_def, fields);
1323                         });
1324                         walk_list!(self, visit_attribute, &item.attrs);
1325                         return;
1326                     }
1327                     _ => {}
1328                 }
1329             }
1330             ItemKind::Const(def, .., None) => {
1331                 self.check_defaultness(item.span, def);
1332                 let msg = "free constant item without body";
1333                 self.error_item_without_body(item.span, "constant", msg, " = <expr>;");
1334             }
1335             ItemKind::Static(.., None) => {
1336                 let msg = "free static item without body";
1337                 self.error_item_without_body(item.span, "static", msg, " = <expr>;");
1338             }
1339             ItemKind::TyAlias(box TyAlias {
1340                 defaultness,
1341                 where_clauses,
1342                 ref bounds,
1343                 ref ty,
1344                 ..
1345             }) => {
1346                 self.check_defaultness(item.span, defaultness);
1347                 if ty.is_none() {
1348                     let msg = "free type alias without body";
1349                     self.error_item_without_body(item.span, "type", msg, " = <type>;");
1350                 }
1351                 self.check_type_no_bounds(bounds, "this context");
1352                 if where_clauses.1.0 {
1353                     let mut err = self.err_handler().struct_span_err(
1354                         where_clauses.1.1,
1355                         "where clauses are not allowed after the type for type aliases",
1356                     );
1357                     err.note(
1358                         "see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information",
1359                     );
1360                     err.emit();
1361                 }
1362             }
1363             _ => {}
1364         }
1365
1366         visit::walk_item(self, item);
1367     }
1368
1369     fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
1370         match &fi.kind {
1371             ForeignItemKind::Fn(box Fn { defaultness, sig, body, .. }) => {
1372                 self.check_defaultness(fi.span, *defaultness);
1373                 self.check_foreign_fn_bodyless(fi.ident, body.as_deref());
1374                 self.check_foreign_fn_headerless(fi.ident, fi.span, sig.header);
1375                 self.check_foreign_item_ascii_only(fi.ident);
1376             }
1377             ForeignItemKind::TyAlias(box TyAlias {
1378                 defaultness,
1379                 generics,
1380                 where_clauses,
1381                 bounds,
1382                 ty,
1383                 ..
1384             }) => {
1385                 self.check_defaultness(fi.span, *defaultness);
1386                 self.check_foreign_kind_bodyless(fi.ident, "type", ty.as_ref().map(|b| b.span));
1387                 self.check_type_no_bounds(bounds, "`extern` blocks");
1388                 self.check_foreign_ty_genericless(generics, where_clauses.0.1);
1389                 self.check_foreign_item_ascii_only(fi.ident);
1390             }
1391             ForeignItemKind::Static(_, _, body) => {
1392                 self.check_foreign_kind_bodyless(fi.ident, "static", body.as_ref().map(|b| b.span));
1393                 self.check_foreign_item_ascii_only(fi.ident);
1394             }
1395             ForeignItemKind::MacCall(..) => {}
1396         }
1397
1398         visit::walk_foreign_item(self, fi)
1399     }
1400
1401     // Mirrors `visit::walk_generic_args`, but tracks relevant state.
1402     fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
1403         match *generic_args {
1404             GenericArgs::AngleBracketed(ref data) => {
1405                 self.check_generic_args_before_constraints(data);
1406
1407                 for arg in &data.args {
1408                     match arg {
1409                         AngleBracketedArg::Arg(arg) => self.visit_generic_arg(arg),
1410                         // Type bindings such as `Item = impl Debug` in `Iterator<Item = Debug>`
1411                         // are allowed to contain nested `impl Trait`.
1412                         AngleBracketedArg::Constraint(constraint) => {
1413                             self.with_impl_trait(None, |this| {
1414                                 this.visit_assoc_constraint_from_generic_args(constraint);
1415                             });
1416                         }
1417                     }
1418                 }
1419             }
1420             GenericArgs::Parenthesized(ref data) => {
1421                 walk_list!(self, visit_ty, &data.inputs);
1422                 if let FnRetTy::Ty(ty) = &data.output {
1423                     // `-> Foo` syntax is essentially an associated type binding,
1424                     // so it is also allowed to contain nested `impl Trait`.
1425                     self.with_impl_trait(None, |this| this.visit_ty(ty));
1426                 }
1427             }
1428         }
1429     }
1430
1431     fn visit_generics(&mut self, generics: &'a Generics) {
1432         let mut prev_param_default = None;
1433         for param in &generics.params {
1434             match param.kind {
1435                 GenericParamKind::Lifetime => (),
1436                 GenericParamKind::Type { default: Some(_), .. }
1437                 | GenericParamKind::Const { default: Some(_), .. } => {
1438                     prev_param_default = Some(param.ident.span);
1439                 }
1440                 GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
1441                     if let Some(span) = prev_param_default {
1442                         let mut err = self.err_handler().struct_span_err(
1443                             span,
1444                             "generic parameters with a default must be trailing",
1445                         );
1446                         err.emit();
1447                         break;
1448                     }
1449                 }
1450             }
1451         }
1452
1453         validate_generic_param_order(self.err_handler(), &generics.params, generics.span);
1454
1455         for predicate in &generics.where_clause.predicates {
1456             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
1457                 deny_equality_constraints(self, predicate, generics);
1458             }
1459         }
1460         walk_list!(self, visit_generic_param, &generics.params);
1461         for predicate in &generics.where_clause.predicates {
1462             match predicate {
1463                 WherePredicate::BoundPredicate(bound_pred) => {
1464                     // A type binding, eg `for<'c> Foo: Send+Clone+'c`
1465                     self.check_late_bound_lifetime_defs(&bound_pred.bound_generic_params);
1466
1467                     // This is slightly complicated. Our representation for poly-trait-refs contains a single
1468                     // binder and thus we only allow a single level of quantification. However,
1469                     // the syntax of Rust permits quantification in two places in where clauses,
1470                     // e.g., `T: for <'a> Foo<'a>` and `for <'a, 'b> &'b T: Foo<'a>`. If both are
1471                     // defined, then error.
1472                     if !bound_pred.bound_generic_params.is_empty() {
1473                         for bound in &bound_pred.bounds {
1474                             match bound {
1475                                 GenericBound::Trait(t, _) => {
1476                                     if !t.bound_generic_params.is_empty() {
1477                                         struct_span_err!(
1478                                             self.err_handler(),
1479                                             t.span,
1480                                             E0316,
1481                                             "nested quantification of lifetimes"
1482                                         )
1483                                         .emit();
1484                                     }
1485                                 }
1486                                 GenericBound::Outlives(_) => {}
1487                             }
1488                         }
1489                     }
1490                 }
1491                 _ => {}
1492             }
1493             self.visit_where_predicate(predicate);
1494         }
1495     }
1496
1497     fn visit_generic_param(&mut self, param: &'a GenericParam) {
1498         if let GenericParamKind::Lifetime { .. } = param.kind {
1499             self.check_lifetime(param.ident);
1500         }
1501         visit::walk_generic_param(self, param);
1502     }
1503
1504     fn visit_param_bound(&mut self, bound: &'a GenericBound, ctxt: BoundKind) {
1505         if let GenericBound::Trait(ref poly, modify) = *bound {
1506             match (ctxt, modify) {
1507                 (BoundKind::SuperTraits, TraitBoundModifier::Maybe) => {
1508                     let mut err = self
1509                         .err_handler()
1510                         .struct_span_err(poly.span, "`?Trait` is not permitted in supertraits");
1511                     let path_str = pprust::path_to_string(&poly.trait_ref.path);
1512                     err.note(&format!("traits are `?{}` by default", path_str));
1513                     err.emit();
1514                 }
1515                 (BoundKind::TraitObject, TraitBoundModifier::Maybe) => {
1516                     let mut err = self.err_handler().struct_span_err(
1517                         poly.span,
1518                         "`?Trait` is not permitted in trait object types",
1519                     );
1520                     err.emit();
1521                 }
1522                 (_, TraitBoundModifier::MaybeConst) => {
1523                     if !self.is_tilde_const_allowed {
1524                         self.err_handler()
1525                             .struct_span_err(bound.span(), "`~const` is not allowed here")
1526                             .note("only allowed on bounds on traits' associated types and functions, const fns, const impls and its associated functions")
1527                             .emit();
1528                     }
1529                 }
1530                 (_, TraitBoundModifier::MaybeConstMaybe) => {
1531                     self.err_handler()
1532                         .span_err(bound.span(), "`~const` and `?` are mutually exclusive");
1533                 }
1534                 _ => {}
1535             }
1536         }
1537
1538         visit::walk_param_bound(self, bound)
1539     }
1540
1541     fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
1542         self.check_late_bound_lifetime_defs(&t.bound_generic_params);
1543         visit::walk_poly_trait_ref(self, t, m);
1544     }
1545
1546     fn visit_variant_data(&mut self, s: &'a VariantData) {
1547         self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s))
1548     }
1549
1550     fn visit_enum_def(
1551         &mut self,
1552         enum_definition: &'a EnumDef,
1553         generics: &'a Generics,
1554         item_id: NodeId,
1555         _: Span,
1556     ) {
1557         self.with_banned_assoc_ty_bound(|this| {
1558             visit::walk_enum_def(this, enum_definition, generics, item_id)
1559         })
1560     }
1561
1562     fn visit_fn(&mut self, fk: FnKind<'a>, span: Span, id: NodeId) {
1563         // Only associated `fn`s can have `self` parameters.
1564         let self_semantic = match fk.ctxt() {
1565             Some(FnCtxt::Assoc(_)) => SelfSemantic::Yes,
1566             _ => SelfSemantic::No,
1567         };
1568         self.check_fn_decl(fk.decl(), self_semantic);
1569
1570         self.check_c_variadic_type(fk);
1571
1572         // Functions cannot both be `const async`
1573         if let Some(FnHeader {
1574             constness: Const::Yes(cspan),
1575             asyncness: Async::Yes { span: aspan, .. },
1576             ..
1577         }) = fk.header()
1578         {
1579             self.err_handler()
1580                 .struct_span_err(
1581                     vec![*cspan, *aspan],
1582                     "functions cannot be both `const` and `async`",
1583                 )
1584                 .span_label(*cspan, "`const` because of this")
1585                 .span_label(*aspan, "`async` because of this")
1586                 .span_label(span, "") // Point at the fn header.
1587                 .emit();
1588         }
1589
1590         if let FnKind::Closure(ClosureBinder::For { generic_params, .. }, ..) = fk {
1591             self.check_late_bound_lifetime_defs(generic_params);
1592         }
1593
1594         if let FnKind::Fn(
1595             _,
1596             _,
1597             FnSig { span: sig_span, header: FnHeader { ext: Extern::Implicit(_), .. }, .. },
1598             _,
1599             _,
1600             _,
1601         ) = fk
1602         {
1603             self.maybe_lint_missing_abi(*sig_span, id);
1604         }
1605
1606         // Functions without bodies cannot have patterns.
1607         if let FnKind::Fn(ctxt, _, sig, _, _, None) = fk {
1608             Self::check_decl_no_pat(&sig.decl, |span, ident, mut_ident| {
1609                 let (code, msg, label) = match ctxt {
1610                     FnCtxt::Foreign => (
1611                         error_code!(E0130),
1612                         "patterns aren't allowed in foreign function declarations",
1613                         "pattern not allowed in foreign function",
1614                     ),
1615                     _ => (
1616                         error_code!(E0642),
1617                         "patterns aren't allowed in functions without bodies",
1618                         "pattern not allowed in function without body",
1619                     ),
1620                 };
1621                 if mut_ident && matches!(ctxt, FnCtxt::Assoc(_)) {
1622                     if let Some(ident) = ident {
1623                         let diag = BuiltinLintDiagnostics::PatternsInFnsWithoutBody(span, ident);
1624                         self.lint_buffer.buffer_lint_with_diagnostic(
1625                             PATTERNS_IN_FNS_WITHOUT_BODY,
1626                             id,
1627                             span,
1628                             msg,
1629                             diag,
1630                         )
1631                     }
1632                 } else {
1633                     self.err_handler()
1634                         .struct_span_err(span, msg)
1635                         .span_label(span, label)
1636                         .code(code)
1637                         .emit();
1638                 }
1639             });
1640         }
1641
1642         let tilde_const_allowed =
1643             matches!(fk.header(), Some(FnHeader { constness: Const::Yes(_), .. }))
1644                 || matches!(fk.ctxt(), Some(FnCtxt::Assoc(_)));
1645
1646         self.with_tilde_const(tilde_const_allowed, |this| visit::walk_fn(this, fk, span));
1647     }
1648
1649     fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
1650         if self.session.contains_name(&item.attrs, sym::no_mangle) {
1651             self.check_nomangle_item_asciionly(item.ident, item.span);
1652         }
1653
1654         if ctxt == AssocCtxt::Trait || !self.in_trait_impl {
1655             self.check_defaultness(item.span, item.kind.defaultness());
1656         }
1657
1658         if ctxt == AssocCtxt::Impl {
1659             match &item.kind {
1660                 AssocItemKind::Const(_, _, body) => {
1661                     self.check_impl_item_provided(item.span, body, "constant", " = <expr>;");
1662                 }
1663                 AssocItemKind::Fn(box Fn { body, .. }) => {
1664                     self.check_impl_item_provided(item.span, body, "function", " { <body> }");
1665                 }
1666                 AssocItemKind::TyAlias(box TyAlias {
1667                     generics,
1668                     where_clauses,
1669                     where_predicates_split,
1670                     bounds,
1671                     ty,
1672                     ..
1673                 }) => {
1674                     self.check_impl_item_provided(item.span, ty, "type", " = <type>;");
1675                     self.check_type_no_bounds(bounds, "`impl`s");
1676                     if ty.is_some() {
1677                         self.check_gat_where(
1678                             item.id,
1679                             generics.where_clause.predicates.split_at(*where_predicates_split).0,
1680                             *where_clauses,
1681                         );
1682                     }
1683                 }
1684                 _ => {}
1685             }
1686         }
1687
1688         if ctxt == AssocCtxt::Trait || self.in_trait_impl {
1689             self.invalid_visibility(&item.vis, None);
1690             if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
1691                 self.check_trait_fn_not_const(sig.header.constness);
1692                 self.check_trait_fn_not_async(item.span, sig.header.asyncness);
1693             }
1694         }
1695
1696         if let AssocItemKind::Const(..) = item.kind {
1697             self.check_item_named(item.ident, "const");
1698         }
1699
1700         match item.kind {
1701             AssocItemKind::TyAlias(box TyAlias { ref generics, ref bounds, ref ty, .. })
1702                 if ctxt == AssocCtxt::Trait =>
1703             {
1704                 self.visit_vis(&item.vis);
1705                 self.visit_ident(item.ident);
1706                 walk_list!(self, visit_attribute, &item.attrs);
1707                 self.with_tilde_const_allowed(|this| {
1708                     this.visit_generics(generics);
1709                     walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
1710                 });
1711                 walk_list!(self, visit_ty, ty);
1712             }
1713             AssocItemKind::Fn(box Fn { ref sig, ref generics, ref body, .. })
1714                 if self.in_const_trait_impl
1715                     || ctxt == AssocCtxt::Trait
1716                     || matches!(sig.header.constness, Const::Yes(_)) =>
1717             {
1718                 self.visit_vis(&item.vis);
1719                 self.visit_ident(item.ident);
1720                 let kind = FnKind::Fn(
1721                     FnCtxt::Assoc(ctxt),
1722                     item.ident,
1723                     sig,
1724                     &item.vis,
1725                     generics,
1726                     body.as_deref(),
1727                 );
1728                 self.visit_fn(kind, item.span, item.id);
1729             }
1730             _ => self
1731                 .with_in_trait_impl(false, None, |this| visit::walk_assoc_item(this, item, ctxt)),
1732         }
1733     }
1734 }
1735
1736 /// When encountering an equality constraint in a `where` clause, emit an error. If the code seems
1737 /// like it's setting an associated type, provide an appropriate suggestion.
1738 fn deny_equality_constraints(
1739     this: &mut AstValidator<'_>,
1740     predicate: &WhereEqPredicate,
1741     generics: &Generics,
1742 ) {
1743     let mut err = this.err_handler().struct_span_err(
1744         predicate.span,
1745         "equality constraints are not yet supported in `where` clauses",
1746     );
1747     err.span_label(predicate.span, "not supported");
1748
1749     // Given `<A as Foo>::Bar = RhsTy`, suggest `A: Foo<Bar = RhsTy>`.
1750     if let TyKind::Path(Some(qself), full_path) = &predicate.lhs_ty.kind {
1751         if let TyKind::Path(None, path) = &qself.ty.kind {
1752             match &path.segments[..] {
1753                 [PathSegment { ident, args: None, .. }] => {
1754                     for param in &generics.params {
1755                         if param.ident == *ident {
1756                             let param = ident;
1757                             match &full_path.segments[qself.position..] {
1758                                 [PathSegment { ident, args, .. }] => {
1759                                     // Make a new `Path` from `foo::Bar` to `Foo<Bar = RhsTy>`.
1760                                     let mut assoc_path = full_path.clone();
1761                                     // Remove `Bar` from `Foo::Bar`.
1762                                     assoc_path.segments.pop();
1763                                     let len = assoc_path.segments.len() - 1;
1764                                     let gen_args = args.as_ref().map(|p| (**p).clone());
1765                                     // Build `<Bar = RhsTy>`.
1766                                     let arg = AngleBracketedArg::Constraint(AssocConstraint {
1767                                         id: rustc_ast::node_id::DUMMY_NODE_ID,
1768                                         ident: *ident,
1769                                         gen_args,
1770                                         kind: AssocConstraintKind::Equality {
1771                                             term: predicate.rhs_ty.clone().into(),
1772                                         },
1773                                         span: ident.span,
1774                                     });
1775                                     // Add `<Bar = RhsTy>` to `Foo`.
1776                                     match &mut assoc_path.segments[len].args {
1777                                         Some(args) => match args.deref_mut() {
1778                                             GenericArgs::Parenthesized(_) => continue,
1779                                             GenericArgs::AngleBracketed(args) => {
1780                                                 args.args.push(arg);
1781                                             }
1782                                         },
1783                                         empty_args => {
1784                                             *empty_args = AngleBracketedArgs {
1785                                                 span: ident.span,
1786                                                 args: vec![arg],
1787                                             }
1788                                             .into();
1789                                         }
1790                                     }
1791                                     err.span_suggestion_verbose(
1792                                         predicate.span,
1793                                         &format!(
1794                                             "if `{}` is an associated type you're trying to set, \
1795                                             use the associated type binding syntax",
1796                                             ident
1797                                         ),
1798                                         format!(
1799                                             "{}: {}",
1800                                             param,
1801                                             pprust::path_to_string(&assoc_path)
1802                                         ),
1803                                         Applicability::MaybeIncorrect,
1804                                     );
1805                                 }
1806                                 _ => {}
1807                             };
1808                         }
1809                     }
1810                 }
1811                 _ => {}
1812             }
1813         }
1814     }
1815     // Given `A: Foo, A::Bar = RhsTy`, suggest `A: Foo<Bar = RhsTy>`.
1816     if let TyKind::Path(None, full_path) = &predicate.lhs_ty.kind {
1817         if let [potential_param, potential_assoc] = &full_path.segments[..] {
1818             for param in &generics.params {
1819                 if param.ident == potential_param.ident {
1820                     for bound in &param.bounds {
1821                         if let ast::GenericBound::Trait(trait_ref, TraitBoundModifier::None) = bound
1822                         {
1823                             if let [trait_segment] = &trait_ref.trait_ref.path.segments[..] {
1824                                 let assoc = pprust::path_to_string(&ast::Path::from_ident(
1825                                     potential_assoc.ident,
1826                                 ));
1827                                 let ty = pprust::ty_to_string(&predicate.rhs_ty);
1828                                 let (args, span) = match &trait_segment.args {
1829                                     Some(args) => match args.deref() {
1830                                         ast::GenericArgs::AngleBracketed(args) => {
1831                                             let Some(arg) = args.args.last() else {
1832                                                 continue;
1833                                             };
1834                                             (
1835                                                 format!(", {} = {}", assoc, ty),
1836                                                 arg.span().shrink_to_hi(),
1837                                             )
1838                                         }
1839                                         _ => continue,
1840                                     },
1841                                     None => (
1842                                         format!("<{} = {}>", assoc, ty),
1843                                         trait_segment.span().shrink_to_hi(),
1844                                     ),
1845                                 };
1846                                 err.multipart_suggestion(
1847                                     &format!(
1848                                         "if `{}::{}` is an associated type you're trying to set, \
1849                                         use the associated type binding syntax",
1850                                         trait_segment.ident, potential_assoc.ident,
1851                                     ),
1852                                     vec![(span, args), (predicate.span, String::new())],
1853                                     Applicability::MaybeIncorrect,
1854                                 );
1855                             }
1856                         }
1857                     }
1858                 }
1859             }
1860         }
1861     }
1862     err.note(
1863         "see issue #20041 <https://github.com/rust-lang/rust/issues/20041> for more information",
1864     );
1865     err.emit();
1866 }
1867
1868 pub fn check_crate(session: &Session, krate: &Crate, lints: &mut LintBuffer) -> bool {
1869     let mut validator = AstValidator {
1870         session,
1871         extern_mod: None,
1872         in_trait_impl: false,
1873         in_const_trait_impl: false,
1874         has_proc_macro_decls: false,
1875         outer_impl_trait: None,
1876         is_tilde_const_allowed: false,
1877         is_impl_trait_banned: false,
1878         is_assoc_ty_bound_banned: false,
1879         forbidden_let_reason: Some(ForbiddenLetReason::GenericForbidden),
1880         lint_buffer: lints,
1881     };
1882     visit::walk_crate(&mut validator, krate);
1883
1884     validator.has_proc_macro_decls
1885 }
1886
1887 /// Used to forbid `let` expressions in certain syntactic locations.
1888 #[derive(Clone, Copy)]
1889 enum ForbiddenLetReason {
1890     /// `let` is not valid and the source environment is not important
1891     GenericForbidden,
1892     /// A let chain with the `||` operator
1893     NotSupportedOr(Span),
1894     /// A let chain with invalid parentheses
1895     ///
1896     /// For exemple, `let 1 = 1 && (expr && expr)` is allowed
1897     /// but `(let 1 = 1 && (let 1 = 1 && (let 1 = 1))) && let a = 1` is not
1898     NotSupportedParentheses(Span),
1899 }