]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/ast_validation.rs
Make `bound_context` more like neighboring functions
[rust.git] / src / librustc_passes / 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 errors::{struct_span_err, Applicability, FatalError};
10 use rustc::lint;
11 use rustc::session::Session;
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_parse::validate_attr;
14 use rustc_span::source_map::Spanned;
15 use rustc_span::symbol::{kw, sym};
16 use rustc_span::Span;
17 use std::mem;
18 use syntax::ast::*;
19 use syntax::attr;
20 use syntax::expand::is_proc_macro_attr;
21 use syntax::print::pprust;
22 use syntax::visit::{self, Visitor};
23 use syntax::walk_list;
24
25 use rustc_error_codes::*;
26
27 /// A syntactic context that disallows certain kinds of bounds (e.g., `?Trait` or `?const Trait`).
28 #[derive(Clone, Copy)]
29 enum BoundContext {
30     ImplTrait,
31     TraitBounds,
32     TraitObject,
33 }
34
35 impl BoundContext {
36     fn description(&self) -> &'static str {
37         match self {
38             Self::ImplTrait => "`impl Trait`",
39             Self::TraitBounds => "supertraits",
40             Self::TraitObject => "trait objects",
41         }
42     }
43 }
44
45 struct AstValidator<'a> {
46     session: &'a Session,
47     has_proc_macro_decls: bool,
48
49     /// Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
50     /// Nested `impl Trait` _is_ allowed in associated type position,
51     /// e.g., `impl Iterator<Item = impl Debug>`.
52     outer_impl_trait: Option<Span>,
53
54     /// Keeps track of the `BoundContext` as we recurse.
55     ///
56     /// This is used to forbid `?const Trait` bounds in, e.g.,
57     /// `impl Iterator<Item = Box<dyn ?const Trait>`.
58     bound_context: Option<BoundContext>,
59
60     /// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
61     /// or `Foo::Bar<impl Trait>`
62     is_impl_trait_banned: bool,
63
64     /// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in
65     /// certain positions.
66     is_assoc_ty_bound_banned: bool,
67
68     lint_buffer: &'a mut lint::LintBuffer,
69 }
70
71 impl<'a> AstValidator<'a> {
72     fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
73         let old = mem::replace(&mut self.is_impl_trait_banned, true);
74         f(self);
75         self.is_impl_trait_banned = old;
76     }
77
78     fn with_banned_assoc_ty_bound(&mut self, f: impl FnOnce(&mut Self)) {
79         let old = mem::replace(&mut self.is_assoc_ty_bound_banned, true);
80         f(self);
81         self.is_assoc_ty_bound_banned = old;
82     }
83
84     fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
85         let old = mem::replace(&mut self.outer_impl_trait, outer);
86         if outer.is_some() {
87             self.with_bound_context(BoundContext::ImplTrait, |this| f(this));
88         } else {
89             f(self)
90         }
91         self.outer_impl_trait = old;
92     }
93
94     fn with_bound_context(&mut self, ctx: BoundContext, f: impl FnOnce(&mut Self)) {
95         let old = self.bound_context.replace(ctx);
96         f(self);
97         self.bound_context = old;
98     }
99
100     fn visit_assoc_ty_constraint_from_generic_args(&mut self, constraint: &'a AssocTyConstraint) {
101         match constraint.kind {
102             AssocTyConstraintKind::Equality { .. } => {}
103             AssocTyConstraintKind::Bound { .. } => {
104                 if self.is_assoc_ty_bound_banned {
105                     self.err_handler().span_err(
106                         constraint.span,
107                         "associated type bounds are not allowed within structs, enums, or unions",
108                     );
109                 }
110             }
111         }
112         self.visit_assoc_ty_constraint(constraint);
113     }
114
115     // Mirrors `visit::walk_ty`, but tracks relevant state.
116     fn walk_ty(&mut self, t: &'a Ty) {
117         match t.kind {
118             TyKind::ImplTrait(..) => {
119                 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
120             }
121             TyKind::TraitObject(..) => {
122                 self.with_bound_context(BoundContext::TraitObject, |this| visit::walk_ty(this, t));
123             }
124             TyKind::Path(ref qself, ref path) => {
125                 // We allow these:
126                 //  - `Option<impl Trait>`
127                 //  - `option::Option<impl Trait>`
128                 //  - `option::Option<T>::Foo<impl Trait>
129                 //
130                 // But not these:
131                 //  - `<impl Trait>::Foo`
132                 //  - `option::Option<impl Trait>::Foo`.
133                 //
134                 // To implement this, we disallow `impl Trait` from `qself`
135                 // (for cases like `<impl Trait>::Foo>`)
136                 // but we allow `impl Trait` in `GenericArgs`
137                 // iff there are no more PathSegments.
138                 if let Some(ref qself) = *qself {
139                     // `impl Trait` in `qself` is always illegal
140                     self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
141                 }
142
143                 // Note that there should be a call to visit_path here,
144                 // so if any logic is added to process `Path`s a call to it should be
145                 // added both in visit_path and here. This code mirrors visit::walk_path.
146                 for (i, segment) in path.segments.iter().enumerate() {
147                     // Allow `impl Trait` iff we're on the final path segment
148                     if i == path.segments.len() - 1 {
149                         self.visit_path_segment(path.span, segment);
150                     } else {
151                         self.with_banned_impl_trait(|this| {
152                             this.visit_path_segment(path.span, segment)
153                         });
154                     }
155                 }
156             }
157             _ => visit::walk_ty(self, t),
158         }
159     }
160
161     fn err_handler(&self) -> &errors::Handler {
162         &self.session.diagnostic()
163     }
164
165     fn check_lifetime(&self, ident: Ident) {
166         let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Invalid];
167         if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
168             self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
169         }
170     }
171
172     fn check_label(&self, ident: Ident) {
173         if ident.without_first_quote().is_reserved() {
174             self.err_handler()
175                 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
176         }
177     }
178
179     fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
180         if let VisibilityKind::Inherited = vis.node {
181             return;
182         }
183
184         let mut err =
185             struct_span_err!(self.session, vis.span, E0449, "unnecessary visibility qualifier");
186         if vis.node.is_pub() {
187             err.span_label(vis.span, "`pub` not permitted here because it's implied");
188         }
189         if let Some(note) = note {
190             err.note(note);
191         }
192         err.emit();
193     }
194
195     fn check_decl_no_pat(decl: &FnDecl, mut report_err: impl FnMut(Span, bool)) {
196         for Param { pat, .. } in &decl.inputs {
197             match pat.kind {
198                 PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, None) | PatKind::Wild => {}
199                 PatKind::Ident(BindingMode::ByValue(Mutability::Mut), _, None) => {
200                     report_err(pat.span, true)
201                 }
202                 _ => report_err(pat.span, false),
203             }
204         }
205     }
206
207     fn check_trait_fn_not_async(&self, span: Span, asyncness: IsAsync) {
208         if asyncness.is_async() {
209             struct_span_err!(self.session, span, E0706, "trait fns cannot be declared `async`")
210                 .note("`async` trait functions are not currently supported")
211                 .note(
212                     "consider using the `async-trait` crate: \
213                        https://crates.io/crates/async-trait",
214                 )
215                 .emit();
216         }
217     }
218
219     fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
220         if constness.node == Constness::Const {
221             struct_span_err!(
222                 self.session,
223                 constness.span,
224                 E0379,
225                 "trait fns cannot be declared const"
226             )
227             .span_label(constness.span, "trait fns cannot be const")
228             .emit();
229         }
230     }
231
232     // FIXME(ecstaticmorse): Instead, use `bound_context` to check this in `visit_param_bound`.
233     fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
234         for bound in bounds {
235             if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
236                 let mut err = self.err_handler().struct_span_err(
237                     poly.span,
238                     &format!("`?Trait` is not permitted in {}", where_),
239                 );
240                 if is_trait {
241                     let path_str = pprust::path_to_string(&poly.trait_ref.path);
242                     err.note(&format!("traits are `?{}` by default", path_str));
243                 }
244                 err.emit();
245             }
246         }
247     }
248
249     /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
250     /// or paths for ranges.
251     //
252     // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
253     // That means making this work:
254     //
255     // ```rust,ignore (FIXME)
256     // struct S;
257     // macro_rules! m {
258     //     ($a:expr) => {
259     //         let $a = S;
260     //     }
261     // }
262     // m!(S);
263     // ```
264     fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
265         match expr.kind {
266             ExprKind::Lit(..) | ExprKind::Err => {}
267             ExprKind::Path(..) if allow_paths => {}
268             ExprKind::Unary(UnOp::Neg, ref inner)
269                 if match inner.kind {
270                     ExprKind::Lit(_) => true,
271                     _ => false,
272                 } => {}
273             _ => self.err_handler().span_err(
274                 expr.span,
275                 "arbitrary expressions aren't allowed \
276                                                          in patterns",
277             ),
278         }
279     }
280
281     fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
282         // Check only lifetime parameters are present and that the lifetime
283         // parameters that are present have no bounds.
284         let non_lt_param_spans: Vec<_> = params
285             .iter()
286             .filter_map(|param| match param.kind {
287                 GenericParamKind::Lifetime { .. } => {
288                     if !param.bounds.is_empty() {
289                         let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
290                         self.err_handler()
291                             .span_err(spans, "lifetime bounds cannot be used in this context");
292                     }
293                     None
294                 }
295                 _ => Some(param.ident.span),
296             })
297             .collect();
298         if !non_lt_param_spans.is_empty() {
299             self.err_handler().span_err(
300                 non_lt_param_spans,
301                 "only lifetime parameters can be used in this context",
302             );
303         }
304     }
305
306     fn check_fn_decl(&self, fn_decl: &FnDecl) {
307         match &*fn_decl.inputs {
308             [Param { ty, span, .. }] => {
309                 if let TyKind::CVarArgs = ty.kind {
310                     self.err_handler().span_err(
311                         *span,
312                         "C-variadic function must be declared with at least one named argument",
313                     );
314                 }
315             }
316             [ps @ .., _] => {
317                 for Param { ty, span, .. } in ps {
318                     if let TyKind::CVarArgs = ty.kind {
319                         self.err_handler().span_err(
320                             *span,
321                             "`...` must be the last argument of a C-variadic function",
322                         );
323                     }
324                 }
325             }
326             _ => {}
327         }
328
329         fn_decl
330             .inputs
331             .iter()
332             .flat_map(|i| i.attrs.as_ref())
333             .filter(|attr| {
334                 let arr = [sym::allow, sym::cfg, sym::cfg_attr, sym::deny, sym::forbid, sym::warn];
335                 !arr.contains(&attr.name_or_empty()) && attr::is_builtin_attr(attr)
336             })
337             .for_each(|attr| {
338                 if attr.is_doc_comment() {
339                     self.err_handler()
340                         .struct_span_err(
341                             attr.span,
342                             "documentation comments cannot be applied to function parameters",
343                         )
344                         .span_label(attr.span, "doc comments are not allowed here")
345                         .emit();
346                 } else {
347                     self.err_handler().span_err(
348                         attr.span,
349                         "allow, cfg, cfg_attr, deny, \
350                 forbid, and warn are the only allowed built-in attributes in function parameters",
351                     )
352                 }
353             });
354     }
355
356     fn check_defaultness(&self, span: Span, defaultness: Defaultness) {
357         if let Defaultness::Default = defaultness {
358             self.err_handler()
359                 .struct_span_err(span, "`default` is only allowed on items in `impl` definitions")
360                 .emit();
361         }
362     }
363
364     fn check_impl_item_provided<T>(&self, sp: Span, body: &Option<T>, ctx: &str, sugg: &str) {
365         if body.is_some() {
366             return;
367         }
368
369         self.err_handler()
370             .struct_span_err(sp, &format!("associated {} in `impl` without body", ctx))
371             .span_suggestion(
372                 self.session.source_map().end_point(sp),
373                 &format!("provide a definition for the {}", ctx),
374                 sugg.to_string(),
375                 Applicability::HasPlaceholders,
376             )
377             .emit();
378     }
379
380     fn check_impl_assoc_type_no_bounds(&self, bounds: &[GenericBound]) {
381         let span = match bounds {
382             [] => return,
383             [b0] => b0.span(),
384             [b0, .., bl] => b0.span().to(bl.span()),
385         };
386         self.err_handler()
387             .struct_span_err(span, "bounds on associated `type`s in `impl`s have no effect")
388             .emit();
389     }
390
391     fn check_c_varadic_type(&self, decl: &FnDecl) {
392         for Param { ty, span, .. } in &decl.inputs {
393             if let TyKind::CVarArgs = ty.kind {
394                 self.err_handler()
395                     .struct_span_err(
396                         *span,
397                         "only foreign or `unsafe extern \"C\" functions may be C-variadic",
398                     )
399                     .emit();
400             }
401         }
402     }
403 }
404
405 enum GenericPosition {
406     Param,
407     Arg,
408 }
409
410 fn validate_generics_order<'a>(
411     sess: &Session,
412     handler: &errors::Handler,
413     generics: impl Iterator<Item = (ParamKindOrd, Option<&'a [GenericBound]>, Span, Option<String>)>,
414     pos: GenericPosition,
415     span: Span,
416 ) {
417     let mut max_param: Option<ParamKindOrd> = None;
418     let mut out_of_order = FxHashMap::default();
419     let mut param_idents = vec![];
420     let mut found_type = false;
421     let mut found_const = false;
422
423     for (kind, bounds, span, ident) in generics {
424         if let Some(ident) = ident {
425             param_idents.push((kind, bounds, param_idents.len(), ident));
426         }
427         let max_param = &mut max_param;
428         match max_param {
429             Some(max_param) if *max_param > kind => {
430                 let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
431                 entry.1.push(span);
432             }
433             Some(_) | None => *max_param = Some(kind),
434         };
435         match kind {
436             ParamKindOrd::Type => found_type = true,
437             ParamKindOrd::Const => found_const = true,
438             _ => {}
439         }
440     }
441
442     let mut ordered_params = "<".to_string();
443     if !out_of_order.is_empty() {
444         param_idents.sort_by_key(|&(po, _, i, _)| (po, i));
445         let mut first = true;
446         for (_, bounds, _, ident) in param_idents {
447             if !first {
448                 ordered_params += ", ";
449             }
450             ordered_params += &ident;
451             if let Some(bounds) = bounds {
452                 if !bounds.is_empty() {
453                     ordered_params += ": ";
454                     ordered_params += &pprust::bounds_to_string(&bounds);
455                 }
456             }
457             first = false;
458         }
459     }
460     ordered_params += ">";
461
462     let pos_str = match pos {
463         GenericPosition::Param => "parameter",
464         GenericPosition::Arg => "argument",
465     };
466
467     for (param_ord, (max_param, spans)) in &out_of_order {
468         let mut err = handler.struct_span_err(
469             spans.clone(),
470             &format!(
471                 "{} {pos}s must be declared prior to {} {pos}s",
472                 param_ord,
473                 max_param,
474                 pos = pos_str,
475             ),
476         );
477         if let GenericPosition::Param = pos {
478             err.span_suggestion(
479                 span,
480                 &format!(
481                     "reorder the {}s: lifetimes, then types{}",
482                     pos_str,
483                     if sess.features_untracked().const_generics { ", then consts" } else { "" },
484                 ),
485                 ordered_params.clone(),
486                 Applicability::MachineApplicable,
487             );
488         }
489         err.emit();
490     }
491
492     // FIXME(const_generics): we shouldn't have to abort here at all, but we currently get ICEs
493     // if we don't. Const parameters and type parameters can currently conflict if they
494     // are out-of-order.
495     if !out_of_order.is_empty() && found_type && found_const {
496         FatalError.raise();
497     }
498 }
499
500 impl<'a> Visitor<'a> for AstValidator<'a> {
501     fn visit_attribute(&mut self, attr: &Attribute) {
502         validate_attr::check_meta(&self.session.parse_sess, attr);
503     }
504
505     fn visit_expr(&mut self, expr: &'a Expr) {
506         match &expr.kind {
507             ExprKind::Closure(_, _, _, fn_decl, _, _) => {
508                 self.check_fn_decl(fn_decl);
509             }
510             ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
511                 struct_span_err!(
512                     self.session,
513                     expr.span,
514                     E0472,
515                     "asm! is unsupported on this target"
516                 )
517                 .emit();
518             }
519             _ => {}
520         }
521
522         visit::walk_expr(self, expr);
523     }
524
525     fn visit_ty(&mut self, ty: &'a Ty) {
526         match ty.kind {
527             TyKind::BareFn(ref bfty) => {
528                 self.check_fn_decl(&bfty.decl);
529                 Self::check_decl_no_pat(&bfty.decl, |span, _| {
530                     struct_span_err!(
531                         self.session,
532                         span,
533                         E0561,
534                         "patterns aren't allowed in function pointer types"
535                     )
536                     .emit();
537                 });
538                 self.check_late_bound_lifetime_defs(&bfty.generic_params);
539             }
540             TyKind::TraitObject(ref bounds, ..) => {
541                 let mut any_lifetime_bounds = false;
542                 for bound in bounds {
543                     if let GenericBound::Outlives(ref lifetime) = *bound {
544                         if any_lifetime_bounds {
545                             struct_span_err!(
546                                 self.session,
547                                 lifetime.ident.span,
548                                 E0226,
549                                 "only a single explicit lifetime bound is permitted"
550                             )
551                             .emit();
552                             break;
553                         }
554                         any_lifetime_bounds = true;
555                     }
556                 }
557                 self.no_questions_in_bounds(bounds, "trait object types", false);
558             }
559             TyKind::ImplTrait(_, ref bounds) => {
560                 if self.is_impl_trait_banned {
561                     struct_span_err!(
562                         self.session,
563                         ty.span,
564                         E0667,
565                         "`impl Trait` is not allowed in path parameters"
566                     )
567                     .emit();
568                 }
569
570                 if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
571                     struct_span_err!(
572                         self.session,
573                         ty.span,
574                         E0666,
575                         "nested `impl Trait` is not allowed"
576                     )
577                     .span_label(outer_impl_trait_sp, "outer `impl Trait`")
578                     .span_label(ty.span, "nested `impl Trait` here")
579                     .emit();
580                 }
581
582                 if !bounds
583                     .iter()
584                     .any(|b| if let GenericBound::Trait(..) = *b { true } else { false })
585                 {
586                     self.err_handler().span_err(ty.span, "at least one trait must be specified");
587                 }
588
589                 self.walk_ty(ty);
590                 return;
591             }
592             _ => {}
593         }
594
595         self.walk_ty(ty)
596     }
597
598     fn visit_label(&mut self, label: &'a Label) {
599         self.check_label(label.ident);
600         visit::walk_label(self, label);
601     }
602
603     fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
604         self.check_lifetime(lifetime.ident);
605         visit::walk_lifetime(self, lifetime);
606     }
607
608     fn visit_item(&mut self, item: &'a Item) {
609         if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
610             self.has_proc_macro_decls = true;
611         }
612
613         match item.kind {
614             ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
615                 self.invalid_visibility(&item.vis, None);
616                 if let TyKind::Err = ty.kind {
617                     self.err_handler()
618                         .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
619                         .help("use `auto trait Trait {}` instead")
620                         .emit();
621                 }
622                 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
623                     struct_span_err!(
624                         self.session,
625                         item.span,
626                         E0198,
627                         "negative impls cannot be unsafe"
628                     )
629                     .emit();
630                 }
631                 for impl_item in impl_items {
632                     self.invalid_visibility(&impl_item.vis, None);
633                     if let AssocItemKind::Fn(ref sig, _) = impl_item.kind {
634                         self.check_trait_fn_not_const(sig.header.constness);
635                         self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness.node);
636                     }
637                 }
638             }
639             ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
640                 self.invalid_visibility(
641                     &item.vis,
642                     Some("place qualifiers on individual impl items instead"),
643                 );
644                 if unsafety == Unsafety::Unsafe {
645                     struct_span_err!(
646                         self.session,
647                         item.span,
648                         E0197,
649                         "inherent impls cannot be unsafe"
650                     )
651                     .emit();
652                 }
653                 if polarity == ImplPolarity::Negative {
654                     self.err_handler().span_err(item.span, "inherent impls cannot be negative");
655                 }
656                 if defaultness == Defaultness::Default {
657                     self.err_handler()
658                         .struct_span_err(item.span, "inherent impls cannot be default")
659                         .note("only trait implementations may be annotated with default")
660                         .emit();
661                 }
662             }
663             ItemKind::Fn(ref sig, ref generics, _) => {
664                 self.visit_fn_header(&sig.header);
665                 self.check_fn_decl(&sig.decl);
666                 // We currently do not permit const generics in `const fn`, as
667                 // this is tantamount to allowing compile-time dependent typing.
668                 if sig.header.constness.node == Constness::Const {
669                     // Look for const generics and error if we find any.
670                     for param in &generics.params {
671                         match param.kind {
672                             GenericParamKind::Const { .. } => {
673                                 self.err_handler()
674                                     .struct_span_err(
675                                         item.span,
676                                         "const parameters are not permitted in `const fn`",
677                                     )
678                                     .emit();
679                             }
680                             _ => {}
681                         }
682                     }
683                 }
684                 // Reject C-varadic type unless the function is `unsafe extern "C"` semantically.
685                 match sig.header.ext {
686                     Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. })
687                     | Extern::Implicit
688                         if sig.header.unsafety == Unsafety::Unsafe => {}
689                     _ => self.check_c_varadic_type(&sig.decl),
690                 }
691             }
692             ItemKind::ForeignMod(..) => {
693                 self.invalid_visibility(
694                     &item.vis,
695                     Some("place qualifiers on individual foreign items instead"),
696                 );
697             }
698             ItemKind::Enum(ref def, _) => {
699                 for variant in &def.variants {
700                     self.invalid_visibility(&variant.vis, None);
701                     for field in variant.data.fields() {
702                         self.invalid_visibility(&field.vis, None);
703                     }
704                 }
705             }
706             ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
707                 if is_auto == IsAuto::Yes {
708                     // Auto traits cannot have generics, super traits nor contain items.
709                     if !generics.params.is_empty() {
710                         struct_span_err!(
711                             self.session,
712                             item.span,
713                             E0567,
714                             "auto traits cannot have generic parameters"
715                         )
716                         .emit();
717                     }
718                     if !bounds.is_empty() {
719                         struct_span_err!(
720                             self.session,
721                             item.span,
722                             E0568,
723                             "auto traits cannot have super traits"
724                         )
725                         .emit();
726                     }
727                     if !trait_items.is_empty() {
728                         struct_span_err!(
729                             self.session,
730                             item.span,
731                             E0380,
732                             "auto traits cannot have methods or associated items"
733                         )
734                         .emit();
735                     }
736                 }
737                 self.no_questions_in_bounds(bounds, "supertraits", true);
738
739                 // Equivalent of `visit::walk_item` for `ItemKind::Trait` that inserts a bound
740                 // context for the supertraits.
741                 self.visit_vis(&item.vis);
742                 self.visit_ident(item.ident);
743                 self.visit_generics(generics);
744                 self.with_bound_context(BoundContext::TraitBounds, |this| {
745                     walk_list!(this, visit_param_bound, bounds);
746                 });
747                 walk_list!(self, visit_trait_item, trait_items);
748                 walk_list!(self, visit_attribute, &item.attrs);
749                 return;
750             }
751             ItemKind::Mod(_) => {
752                 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
753                 attr::first_attr_value_str_by_name(&item.attrs, sym::path);
754             }
755             ItemKind::Union(ref vdata, _) => {
756                 if let VariantData::Tuple(..) | VariantData::Unit(..) = vdata {
757                     self.err_handler()
758                         .span_err(item.span, "tuple and unit unions are not permitted");
759                 }
760                 if vdata.fields().is_empty() {
761                     self.err_handler().span_err(item.span, "unions cannot have zero fields");
762                 }
763             }
764             _ => {}
765         }
766
767         visit::walk_item(self, item)
768     }
769
770     fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
771         match fi.kind {
772             ForeignItemKind::Fn(ref decl, _) => {
773                 self.check_fn_decl(decl);
774                 Self::check_decl_no_pat(decl, |span, _| {
775                     struct_span_err!(
776                         self.session,
777                         span,
778                         E0130,
779                         "patterns aren't allowed in foreign function declarations"
780                     )
781                     .span_label(span, "pattern not allowed in foreign function")
782                     .emit();
783                 });
784             }
785             ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
786         }
787
788         visit::walk_foreign_item(self, fi)
789     }
790
791     // Mirrors `visit::walk_generic_args`, but tracks relevant state.
792     fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
793         match *generic_args {
794             GenericArgs::AngleBracketed(ref data) => {
795                 walk_list!(self, visit_generic_arg, &data.args);
796                 validate_generics_order(
797                     self.session,
798                     self.err_handler(),
799                     data.args.iter().map(|arg| {
800                         (
801                             match arg {
802                                 GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
803                                 GenericArg::Type(..) => ParamKindOrd::Type,
804                                 GenericArg::Const(..) => ParamKindOrd::Const,
805                             },
806                             None,
807                             arg.span(),
808                             None,
809                         )
810                     }),
811                     GenericPosition::Arg,
812                     generic_args.span(),
813                 );
814
815                 // Type bindings such as `Item = impl Debug` in `Iterator<Item = Debug>`
816                 // are allowed to contain nested `impl Trait`.
817                 self.with_impl_trait(None, |this| {
818                     walk_list!(
819                         this,
820                         visit_assoc_ty_constraint_from_generic_args,
821                         &data.constraints
822                     );
823                 });
824             }
825             GenericArgs::Parenthesized(ref data) => {
826                 walk_list!(self, visit_ty, &data.inputs);
827                 if let FunctionRetTy::Ty(ty) = &data.output {
828                     // `-> Foo` syntax is essentially an associated type binding,
829                     // so it is also allowed to contain nested `impl Trait`.
830                     self.with_impl_trait(None, |this| this.visit_ty(ty));
831                 }
832             }
833         }
834     }
835
836     fn visit_generics(&mut self, generics: &'a Generics) {
837         let mut prev_ty_default = None;
838         for param in &generics.params {
839             if let GenericParamKind::Type { ref default, .. } = param.kind {
840                 if default.is_some() {
841                     prev_ty_default = Some(param.ident.span);
842                 } else if let Some(span) = prev_ty_default {
843                     self.err_handler()
844                         .span_err(span, "type parameters with a default must be trailing");
845                     break;
846                 }
847             }
848         }
849
850         validate_generics_order(
851             self.session,
852             self.err_handler(),
853             generics.params.iter().map(|param| {
854                 let ident = Some(param.ident.to_string());
855                 let (kind, ident) = match &param.kind {
856                     GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, ident),
857                     GenericParamKind::Type { .. } => (ParamKindOrd::Type, ident),
858                     GenericParamKind::Const { ref ty } => {
859                         let ty = pprust::ty_to_string(ty);
860                         (ParamKindOrd::Const, Some(format!("const {}: {}", param.ident, ty)))
861                     }
862                 };
863                 (kind, Some(&*param.bounds), param.ident.span, ident)
864             }),
865             GenericPosition::Param,
866             generics.span,
867         );
868
869         for predicate in &generics.where_clause.predicates {
870             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
871                 self.err_handler()
872                     .struct_span_err(
873                         predicate.span,
874                         "equality constraints are not yet supported in `where` clauses",
875                     )
876                     .span_label(predicate.span, "not supported")
877                     .note(
878                         "for more information, see https://github.com/rust-lang/rust/issues/20041",
879                     )
880                     .emit();
881             }
882         }
883
884         visit::walk_generics(self, generics)
885     }
886
887     fn visit_generic_param(&mut self, param: &'a GenericParam) {
888         if let GenericParamKind::Lifetime { .. } = param.kind {
889             self.check_lifetime(param.ident);
890         }
891         visit::walk_generic_param(self, param);
892     }
893
894     fn visit_param_bound(&mut self, bound: &'a GenericBound) {
895         if let GenericBound::Trait(poly, maybe_bound) = bound {
896             match poly.trait_ref.constness {
897                 Some(Constness::NotConst) => {
898                     if *maybe_bound == TraitBoundModifier::Maybe {
899                         self.err_handler()
900                             .span_err(bound.span(), "`?const` and `?` are mutually exclusive");
901                     }
902
903                     if let Some(ctx) = self.bound_context {
904                         let msg = format!("`?const` is not permitted in {}", ctx.description());
905                         self.err_handler().span_err(bound.span(), &msg);
906                     }
907                 }
908
909                 Some(Constness::Const) => bug!("Parser should reject bare `const` on bounds"),
910                 None => {}
911             }
912         }
913
914         visit::walk_param_bound(self, bound)
915     }
916
917     fn visit_pat(&mut self, pat: &'a Pat) {
918         match pat.kind {
919             PatKind::Lit(ref expr) => {
920                 self.check_expr_within_pat(expr, false);
921             }
922             PatKind::Range(ref start, ref end, _) => {
923                 self.check_expr_within_pat(start, true);
924                 self.check_expr_within_pat(end, true);
925             }
926             _ => {}
927         }
928
929         visit::walk_pat(self, pat)
930     }
931
932     fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
933         if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
934             // A type binding, eg `for<'c> Foo: Send+Clone+'c`
935             self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
936         }
937         visit::walk_where_predicate(self, p);
938     }
939
940     fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
941         self.check_late_bound_lifetime_defs(&t.bound_generic_params);
942         visit::walk_poly_trait_ref(self, t, m);
943     }
944
945     fn visit_variant_data(&mut self, s: &'a VariantData) {
946         self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s))
947     }
948
949     fn visit_enum_def(
950         &mut self,
951         enum_definition: &'a EnumDef,
952         generics: &'a Generics,
953         item_id: NodeId,
954         _: Span,
955     ) {
956         self.with_banned_assoc_ty_bound(|this| {
957             visit::walk_enum_def(this, enum_definition, generics, item_id)
958         })
959     }
960
961     fn visit_impl_item(&mut self, ii: &'a AssocItem) {
962         match &ii.kind {
963             AssocItemKind::Const(_, body) => {
964                 self.check_impl_item_provided(ii.span, body, "constant", " = <expr>;");
965             }
966             AssocItemKind::Fn(sig, body) => {
967                 self.check_impl_item_provided(ii.span, body, "function", " { <body> }");
968                 self.check_fn_decl(&sig.decl);
969             }
970             AssocItemKind::TyAlias(bounds, body) => {
971                 self.check_impl_item_provided(ii.span, body, "type", " = <type>;");
972                 self.check_impl_assoc_type_no_bounds(bounds);
973             }
974             _ => {}
975         }
976         visit::walk_impl_item(self, ii);
977     }
978
979     fn visit_trait_item(&mut self, ti: &'a AssocItem) {
980         self.invalid_visibility(&ti.vis, None);
981         self.check_defaultness(ti.span, ti.defaultness);
982
983         if let AssocItemKind::Fn(sig, block) = &ti.kind {
984             self.check_fn_decl(&sig.decl);
985             self.check_trait_fn_not_async(ti.span, sig.header.asyncness.node);
986             self.check_trait_fn_not_const(sig.header.constness);
987             if block.is_none() {
988                 Self::check_decl_no_pat(&sig.decl, |span, mut_ident| {
989                     if mut_ident {
990                         self.lint_buffer.buffer_lint(
991                             lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
992                             ti.id,
993                             span,
994                             "patterns aren't allowed in methods without bodies",
995                         );
996                     } else {
997                         struct_span_err!(
998                             self.session,
999                             span,
1000                             E0642,
1001                             "patterns aren't allowed in methods without bodies"
1002                         )
1003                         .emit();
1004                     }
1005                 });
1006             }
1007         }
1008
1009         visit::walk_trait_item(self, ti);
1010     }
1011
1012     fn visit_assoc_item(&mut self, item: &'a AssocItem) {
1013         if let AssocItemKind::Fn(sig, _) = &item.kind {
1014             self.check_c_varadic_type(&sig.decl);
1015         }
1016         visit::walk_assoc_item(self, item);
1017     }
1018 }
1019
1020 pub fn check_crate(session: &Session, krate: &Crate, lints: &mut lint::LintBuffer) -> bool {
1021     let mut validator = AstValidator {
1022         session,
1023         has_proc_macro_decls: false,
1024         outer_impl_trait: None,
1025         bound_context: None,
1026         is_impl_trait_banned: false,
1027         is_assoc_ty_bound_banned: false,
1028         lint_buffer: lints,
1029     };
1030     visit::walk_crate(&mut validator, krate);
1031
1032     validator.has_proc_macro_decls
1033 }