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