]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/ast_validation.rs
Tweak bad `continue` error
[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 std::mem;
10 use rustc::lint;
11 use rustc::session::Session;
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_parse::validate_attr;
14 use syntax::ast::*;
15 use syntax::attr;
16 use syntax::expand::is_proc_macro_attr;
17 use syntax::feature_gate::is_builtin_attr;
18 use syntax::print::pprust;
19 use syntax::source_map::Spanned;
20 use syntax::symbol::{kw, sym};
21 use syntax::visit::{self, Visitor};
22 use syntax::{span_err, struct_span_err, walk_list};
23 use syntax_pos::Span;
24 use errors::{Applicability, FatalError};
25
26 use rustc_error_codes::*;
27
28 struct AstValidator<'a> {
29     session: &'a Session,
30     has_proc_macro_decls: bool,
31
32     /// Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
33     /// Nested `impl Trait` _is_ allowed in associated type position,
34     /// e.g., `impl Iterator<Item = impl Debug>`.
35     outer_impl_trait: Option<Span>,
36
37     /// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
38     /// or `Foo::Bar<impl Trait>`
39     is_impl_trait_banned: bool,
40
41     /// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in
42     /// certain positions.
43     is_assoc_ty_bound_banned: bool,
44
45     lint_buffer: &'a mut lint::LintBuffer,
46 }
47
48 impl<'a> AstValidator<'a> {
49     fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
50         let old = mem::replace(&mut self.is_impl_trait_banned, true);
51         f(self);
52         self.is_impl_trait_banned = old;
53     }
54
55     fn with_banned_assoc_ty_bound(&mut self, f: impl FnOnce(&mut Self)) {
56         let old = mem::replace(&mut self.is_assoc_ty_bound_banned, true);
57         f(self);
58         self.is_assoc_ty_bound_banned = old;
59     }
60
61     fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
62         let old = mem::replace(&mut self.outer_impl_trait, outer);
63         f(self);
64         self.outer_impl_trait = old;
65     }
66
67     fn visit_assoc_ty_constraint_from_generic_args(&mut self, constraint: &'a AssocTyConstraint) {
68         match constraint.kind {
69             AssocTyConstraintKind::Equality { .. } => {}
70             AssocTyConstraintKind::Bound { .. } => {
71                 if self.is_assoc_ty_bound_banned {
72                     self.err_handler().span_err(constraint.span,
73                         "associated type bounds are not allowed within structs, enums, or unions"
74                     );
75                 }
76             }
77         }
78         self.visit_assoc_ty_constraint(constraint);
79     }
80
81     // Mirrors `visit::walk_ty`, but tracks relevant state.
82     fn walk_ty(&mut self, t: &'a Ty) {
83         match t.kind {
84             TyKind::ImplTrait(..) => {
85                 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
86             }
87             TyKind::Path(ref qself, ref path) => {
88                 // We allow these:
89                 //  - `Option<impl Trait>`
90                 //  - `option::Option<impl Trait>`
91                 //  - `option::Option<T>::Foo<impl Trait>
92                 //
93                 // But not these:
94                 //  - `<impl Trait>::Foo`
95                 //  - `option::Option<impl Trait>::Foo`.
96                 //
97                 // To implement this, we disallow `impl Trait` from `qself`
98                 // (for cases like `<impl Trait>::Foo>`)
99                 // but we allow `impl Trait` in `GenericArgs`
100                 // iff there are no more PathSegments.
101                 if let Some(ref qself) = *qself {
102                     // `impl Trait` in `qself` is always illegal
103                     self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
104                 }
105
106                 // Note that there should be a call to visit_path here,
107                 // so if any logic is added to process `Path`s a call to it should be
108                 // added both in visit_path and here. This code mirrors visit::walk_path.
109                 for (i, segment) in path.segments.iter().enumerate() {
110                     // Allow `impl Trait` iff we're on the final path segment
111                     if i == path.segments.len() - 1 {
112                         self.visit_path_segment(path.span, segment);
113                     } else {
114                         self.with_banned_impl_trait(|this| {
115                             this.visit_path_segment(path.span, segment)
116                         });
117                     }
118                 }
119             }
120             _ => visit::walk_ty(self, t),
121         }
122     }
123
124     fn err_handler(&self) -> &errors::Handler {
125         &self.session.diagnostic()
126     }
127
128     fn check_lifetime(&self, ident: Ident) {
129         let valid_names = [kw::UnderscoreLifetime,
130                            kw::StaticLifetime,
131                            kw::Invalid];
132         if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
133             self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
134         }
135     }
136
137     fn check_label(&self, ident: Ident) {
138         if ident.without_first_quote().is_reserved() {
139             self.err_handler()
140                 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
141         }
142     }
143
144     fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
145         if let VisibilityKind::Inherited = vis.node {
146             return
147         }
148
149         let mut err = struct_span_err!(self.session,
150                                         vis.span,
151                                         E0449,
152                                         "unnecessary visibility qualifier");
153         if vis.node.is_pub() {
154             err.span_label(vis.span, "`pub` not permitted here because it's implied");
155         }
156         if let Some(note) = note {
157             err.note(note);
158         }
159         err.emit();
160     }
161
162     fn check_decl_no_pat<F: FnMut(Span, bool)>(decl: &FnDecl, mut report_err: F) {
163         for arg in &decl.inputs {
164             match arg.pat.kind {
165                 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
166                 PatKind::Wild => {}
167                 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
168                     report_err(arg.pat.span, true),
169                 _ => report_err(arg.pat.span, false),
170             }
171         }
172     }
173
174     fn check_trait_fn_not_async(&self, span: Span, asyncness: IsAsync) {
175         if asyncness.is_async() {
176             struct_span_err!(self.session, span, E0706, "trait fns cannot be declared `async`")
177                 .note("`async` trait functions are not currently supported")
178                 .note("consider using the `async-trait` crate: \
179                        https://crates.io/crates/async-trait")
180                 .emit();
181         }
182     }
183
184     fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
185         if constness.node == Constness::Const {
186             struct_span_err!(self.session, constness.span, E0379,
187                              "trait fns cannot be declared const")
188                 .span_label(constness.span, "trait fns cannot be const")
189                 .emit();
190         }
191     }
192
193     fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
194         for bound in bounds {
195             if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
196                 let mut err = self.err_handler().struct_span_err(poly.span,
197                     &format!("`?Trait` is not permitted in {}", where_));
198                 if is_trait {
199                     let path_str = pprust::path_to_string(&poly.trait_ref.path);
200                     err.note(&format!("traits are `?{}` by default", path_str));
201                 }
202                 err.emit();
203             }
204         }
205     }
206
207     /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
208     /// or paths for ranges.
209     //
210     // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
211     // That means making this work:
212     //
213     // ```rust,ignore (FIXME)
214     // struct S;
215     // macro_rules! m {
216     //     ($a:expr) => {
217     //         let $a = S;
218     //     }
219     // }
220     // m!(S);
221     // ```
222     fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
223         match expr.kind {
224             ExprKind::Lit(..) | ExprKind::Err => {}
225             ExprKind::Path(..) if allow_paths => {}
226             ExprKind::Unary(UnOp::Neg, ref inner)
227                 if match inner.kind { ExprKind::Lit(_) => true, _ => false } => {}
228             _ => self.err_handler().span_err(expr.span, "arbitrary expressions aren't allowed \
229                                                          in patterns")
230         }
231     }
232
233     fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
234         // Check only lifetime parameters are present and that the lifetime
235         // parameters that are present have no bounds.
236         let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind {
237             GenericParamKind::Lifetime { .. } => {
238                 if !param.bounds.is_empty() {
239                     let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
240                     self.err_handler()
241                         .span_err(spans, "lifetime bounds cannot be used in this context");
242                 }
243                 None
244             }
245             _ => Some(param.ident.span),
246         }).collect();
247         if !non_lt_param_spans.is_empty() {
248             self.err_handler().span_err(non_lt_param_spans,
249                 "only lifetime parameters can be used in this context");
250         }
251     }
252
253     fn check_fn_decl(&self, fn_decl: &FnDecl) {
254         fn_decl
255             .inputs
256             .iter()
257             .flat_map(|i| i.attrs.as_ref())
258             .filter(|attr| {
259                 let arr = [sym::allow, sym::cfg, sym::cfg_attr, sym::deny, sym::forbid, sym::warn];
260                 !arr.contains(&attr.name_or_empty()) && is_builtin_attr(attr)
261             })
262             .for_each(|attr| if attr.is_doc_comment() {
263                 let mut err = self.err_handler().struct_span_err(
264                     attr.span,
265                     "documentation comments cannot be applied to function parameters"
266                 );
267                 err.span_label(attr.span, "doc comments are not allowed here");
268                 err.emit();
269             }
270             else {
271                 self.err_handler().span_err(attr.span, "allow, cfg, cfg_attr, deny, \
272                 forbid, and warn are the only allowed built-in attributes in function parameters")
273             });
274     }
275 }
276
277 enum GenericPosition {
278     Param,
279     Arg,
280 }
281
282 fn validate_generics_order<'a>(
283     sess: &Session,
284     handler: &errors::Handler,
285     generics: impl Iterator<
286         Item = (
287             ParamKindOrd,
288             Option<&'a [GenericBound]>,
289             Span,
290             Option<String>
291         ),
292     >,
293     pos: GenericPosition,
294     span: Span,
295 ) {
296     let mut max_param: Option<ParamKindOrd> = None;
297     let mut out_of_order = FxHashMap::default();
298     let mut param_idents = vec![];
299     let mut found_type = false;
300     let mut found_const = false;
301
302     for (kind, bounds, span, ident) in generics {
303         if let Some(ident) = ident {
304             param_idents.push((kind, bounds, param_idents.len(), ident));
305         }
306         let max_param = &mut max_param;
307         match max_param {
308             Some(max_param) if *max_param > kind => {
309                 let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
310                 entry.1.push(span);
311             }
312             Some(_) | None => *max_param = Some(kind),
313         };
314         match kind {
315             ParamKindOrd::Type => found_type = true,
316             ParamKindOrd::Const => found_const = true,
317             _ => {}
318         }
319     }
320
321     let mut ordered_params = "<".to_string();
322     if !out_of_order.is_empty() {
323         param_idents.sort_by_key(|&(po, _, i, _)| (po, i));
324         let mut first = true;
325         for (_, bounds, _, ident) in param_idents {
326             if !first {
327                 ordered_params += ", ";
328             }
329             ordered_params += &ident;
330             if let Some(bounds) = bounds {
331                 if !bounds.is_empty() {
332                     ordered_params += ": ";
333                     ordered_params += &pprust::bounds_to_string(&bounds);
334                 }
335             }
336             first = false;
337         }
338     }
339     ordered_params += ">";
340
341     let pos_str = match pos {
342         GenericPosition::Param => "parameter",
343         GenericPosition::Arg => "argument",
344     };
345
346     for (param_ord, (max_param, spans)) in &out_of_order {
347         let mut err = handler.struct_span_err(spans.clone(),
348             &format!(
349                 "{} {pos}s must be declared prior to {} {pos}s",
350                 param_ord,
351                 max_param,
352                 pos = pos_str,
353             ));
354         if let GenericPosition::Param = pos {
355             err.span_suggestion(
356                 span,
357                 &format!(
358                     "reorder the {}s: lifetimes, then types{}",
359                     pos_str,
360                     if sess.features_untracked().const_generics { ", then consts" } else { "" },
361                 ),
362                 ordered_params.clone(),
363                 Applicability::MachineApplicable,
364             );
365         }
366         err.emit();
367     }
368
369     // FIXME(const_generics): we shouldn't have to abort here at all, but we currently get ICEs
370     // if we don't. Const parameters and type parameters can currently conflict if they
371     // are out-of-order.
372     if !out_of_order.is_empty() && found_type && found_const {
373         FatalError.raise();
374     }
375 }
376
377 impl<'a> Visitor<'a> for AstValidator<'a> {
378     fn visit_attribute(&mut self, attr: &Attribute) {
379         validate_attr::check_meta(&self.session.parse_sess, attr);
380     }
381
382     fn visit_expr(&mut self, expr: &'a Expr) {
383         match &expr.kind {
384             ExprKind::Closure(_, _, _, fn_decl, _, _) => {
385                 self.check_fn_decl(fn_decl);
386             }
387             ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
388                 span_err!(self.session, expr.span, E0472, "asm! is unsupported on this target");
389             }
390             _ => {}
391         }
392
393         visit::walk_expr(self, expr);
394     }
395
396     fn visit_ty(&mut self, ty: &'a Ty) {
397         match ty.kind {
398             TyKind::BareFn(ref bfty) => {
399                 self.check_fn_decl(&bfty.decl);
400                 Self::check_decl_no_pat(&bfty.decl, |span, _| {
401                     struct_span_err!(self.session, span, E0561,
402                                      "patterns aren't allowed in function pointer types").emit();
403                 });
404                 self.check_late_bound_lifetime_defs(&bfty.generic_params);
405             }
406             TyKind::TraitObject(ref bounds, ..) => {
407                 let mut any_lifetime_bounds = false;
408                 for bound in bounds {
409                     if let GenericBound::Outlives(ref lifetime) = *bound {
410                         if any_lifetime_bounds {
411                             span_err!(self.session, lifetime.ident.span, E0226,
412                                       "only a single explicit lifetime bound is permitted");
413                             break;
414                         }
415                         any_lifetime_bounds = true;
416                     }
417                 }
418                 self.no_questions_in_bounds(bounds, "trait object types", false);
419             }
420             TyKind::ImplTrait(_, ref bounds) => {
421                 if self.is_impl_trait_banned {
422                     struct_span_err!(
423                         self.session, ty.span, E0667,
424                         "`impl Trait` is not allowed in path parameters"
425                     )
426                     .emit();
427                 }
428
429                 if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
430                     struct_span_err!(
431                         self.session, ty.span, E0666,
432                         "nested `impl Trait` is not allowed"
433                     )
434                     .span_label(outer_impl_trait_sp, "outer `impl Trait`")
435                     .span_label(ty.span, "nested `impl Trait` here")
436                     .emit();
437                 }
438
439                 if !bounds.iter()
440                           .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
441                     self.err_handler().span_err(ty.span, "at least one trait must be specified");
442                 }
443
444                 self.walk_ty(ty);
445                 return;
446             }
447             _ => {}
448         }
449
450         self.walk_ty(ty)
451     }
452
453     fn visit_label(&mut self, label: &'a Label) {
454         self.check_label(label.ident);
455         visit::walk_label(self, label);
456     }
457
458     fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
459         self.check_lifetime(lifetime.ident);
460         visit::walk_lifetime(self, lifetime);
461     }
462
463     fn visit_item(&mut self, item: &'a Item) {
464         if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)  ) {
465             self.has_proc_macro_decls = true;
466         }
467
468         match item.kind {
469             ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
470                 self.invalid_visibility(&item.vis, None);
471                 if let TyKind::Err = ty.kind {
472                     self.err_handler()
473                         .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
474                         .help("use `auto trait Trait {}` instead").emit();
475                 }
476                 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
477                     span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
478                 }
479                 for impl_item in impl_items {
480                     self.invalid_visibility(&impl_item.vis, None);
481                     if let ImplItemKind::Method(ref sig, _) = impl_item.kind {
482                         self.check_trait_fn_not_const(sig.header.constness);
483                         self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness.node);
484                     }
485                 }
486             }
487             ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
488                 self.invalid_visibility(&item.vis,
489                                         Some("place qualifiers on individual impl items instead"));
490                 if unsafety == Unsafety::Unsafe {
491                     span_err!(self.session, item.span, E0197, "inherent impls cannot be unsafe");
492                 }
493                 if polarity == ImplPolarity::Negative {
494                     self.err_handler().span_err(item.span, "inherent impls cannot be negative");
495                 }
496                 if defaultness == Defaultness::Default {
497                     self.err_handler()
498                         .struct_span_err(item.span, "inherent impls cannot be default")
499                         .note("only trait implementations may be annotated with default").emit();
500                 }
501             }
502             ItemKind::Fn(ref sig, ref generics, _) => {
503                 self.visit_fn_header(&sig.header);
504                 self.check_fn_decl(&sig.decl);
505                 // We currently do not permit const generics in `const fn`, as
506                 // this is tantamount to allowing compile-time dependent typing.
507                 if sig.header.constness.node == Constness::Const {
508                     // Look for const generics and error if we find any.
509                     for param in &generics.params {
510                         match param.kind {
511                             GenericParamKind::Const { .. } => {
512                                 self.err_handler()
513                                     .struct_span_err(
514                                         item.span,
515                                         "const parameters are not permitted in `const fn`",
516                                     )
517                                     .emit();
518                             }
519                             _ => {}
520                         }
521                     }
522                 }
523             }
524             ItemKind::ForeignMod(..) => {
525                 self.invalid_visibility(
526                     &item.vis,
527                     Some("place qualifiers on individual foreign items instead"),
528                 );
529             }
530             ItemKind::Enum(ref def, _) => {
531                 for variant in &def.variants {
532                     for field in variant.data.fields() {
533                         self.invalid_visibility(&field.vis, None);
534                     }
535                 }
536             }
537             ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
538                 if is_auto == IsAuto::Yes {
539                     // Auto traits cannot have generics, super traits nor contain items.
540                     if !generics.params.is_empty() {
541                         struct_span_err!(self.session, item.span, E0567,
542                             "auto traits cannot have generic parameters"
543                         ).emit();
544                     }
545                     if !bounds.is_empty() {
546                         struct_span_err!(self.session, item.span, E0568,
547                             "auto traits cannot have super traits"
548                         ).emit();
549                     }
550                     if !trait_items.is_empty() {
551                         struct_span_err!(self.session, item.span, E0380,
552                             "auto traits cannot have methods or associated items"
553                         ).emit();
554                     }
555                 }
556                 self.no_questions_in_bounds(bounds, "supertraits", true);
557                 for trait_item in trait_items {
558                     if let TraitItemKind::Method(ref sig, ref block) = trait_item.kind {
559                         self.check_fn_decl(&sig.decl);
560                         self.check_trait_fn_not_async(trait_item.span, sig.header.asyncness.node);
561                         self.check_trait_fn_not_const(sig.header.constness);
562                         if block.is_none() {
563                             Self::check_decl_no_pat(&sig.decl, |span, mut_ident| {
564                                 if mut_ident {
565                                     self.lint_buffer.buffer_lint(
566                                         lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
567                                         trait_item.id, span,
568                                         "patterns aren't allowed in methods without bodies");
569                                 } else {
570                                     struct_span_err!(self.session, span, E0642,
571                                         "patterns aren't allowed in methods without bodies").emit();
572                                 }
573                             });
574                         }
575                     }
576                 }
577             }
578             ItemKind::Mod(_) => {
579                 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
580                 attr::first_attr_value_str_by_name(&item.attrs, sym::path);
581             }
582             ItemKind::Union(ref vdata, _) => {
583                 if let VariantData::Tuple(..) | VariantData::Unit(..) = vdata {
584                     self.err_handler().span_err(item.span,
585                                                 "tuple and unit unions are not permitted");
586                 }
587                 if vdata.fields().is_empty() {
588                     self.err_handler().span_err(item.span,
589                                                 "unions cannot have zero fields");
590                 }
591             }
592             _ => {}
593         }
594
595         visit::walk_item(self, item)
596     }
597
598     fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
599         match fi.kind {
600             ForeignItemKind::Fn(ref decl, _) => {
601                 self.check_fn_decl(decl);
602                 Self::check_decl_no_pat(decl, |span, _| {
603                     struct_span_err!(self.session, span, E0130,
604                                      "patterns aren't allowed in foreign function declarations")
605                         .span_label(span, "pattern not allowed in foreign function").emit();
606                 });
607             }
608             ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
609         }
610
611         visit::walk_foreign_item(self, fi)
612     }
613
614     // Mirrors `visit::walk_generic_args`, but tracks relevant state.
615     fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
616         match *generic_args {
617             GenericArgs::AngleBracketed(ref data) => {
618                 walk_list!(self, visit_generic_arg, &data.args);
619                 validate_generics_order(
620                     self.session,
621                     self.err_handler(),
622                     data.args.iter().map(|arg| {
623                         (match arg {
624                             GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
625                             GenericArg::Type(..) => ParamKindOrd::Type,
626                             GenericArg::Const(..) => ParamKindOrd::Const,
627                         }, None, arg.span(), None)
628                     }),
629                     GenericPosition::Arg,
630                     generic_args.span(),
631                 );
632
633                 // Type bindings such as `Item = impl Debug` in `Iterator<Item = Debug>`
634                 // are allowed to contain nested `impl Trait`.
635                 self.with_impl_trait(None, |this| {
636                     walk_list!(this, visit_assoc_ty_constraint_from_generic_args,
637                         &data.constraints);
638                 });
639             }
640             GenericArgs::Parenthesized(ref data) => {
641                 walk_list!(self, visit_ty, &data.inputs);
642                 if let Some(ref type_) = data.output {
643                     // `-> Foo` syntax is essentially an associated type binding,
644                     // so it is also allowed to contain nested `impl Trait`.
645                     self.with_impl_trait(None, |this| this.visit_ty(type_));
646                 }
647             }
648         }
649     }
650
651     fn visit_generics(&mut self, generics: &'a Generics) {
652         let mut prev_ty_default = None;
653         for param in &generics.params {
654             if let GenericParamKind::Type { ref default, .. } = param.kind {
655                 if default.is_some() {
656                     prev_ty_default = Some(param.ident.span);
657                 } else if let Some(span) = prev_ty_default {
658                     self.err_handler()
659                         .span_err(span, "type parameters with a default must be trailing");
660                     break;
661                 }
662             }
663         }
664
665         validate_generics_order(
666             self.session,
667             self.err_handler(),
668             generics.params.iter().map(|param| {
669                 let ident = Some(param.ident.to_string());
670                 let (kind, ident) = match &param.kind {
671                     GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, ident),
672                     GenericParamKind::Type { .. } => (ParamKindOrd::Type, ident),
673                     GenericParamKind::Const { ref ty } => {
674                         let ty = pprust::ty_to_string(ty);
675                         (ParamKindOrd::Const, Some(format!("const {}: {}", param.ident, ty)))
676                     }
677                 };
678                 (kind, Some(&*param.bounds), param.ident.span, ident)
679             }),
680             GenericPosition::Param,
681             generics.span,
682         );
683
684         for predicate in &generics.where_clause.predicates {
685             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
686                 self.err_handler()
687                     .span_err(predicate.span, "equality constraints are not yet \
688                                                supported in where clauses (see #20041)");
689             }
690         }
691
692         visit::walk_generics(self, generics)
693     }
694
695     fn visit_generic_param(&mut self, param: &'a GenericParam) {
696         if let GenericParamKind::Lifetime { .. } = param.kind {
697             self.check_lifetime(param.ident);
698         }
699         visit::walk_generic_param(self, param);
700     }
701
702     fn visit_pat(&mut self, pat: &'a Pat) {
703         match pat.kind {
704             PatKind::Lit(ref expr) => {
705                 self.check_expr_within_pat(expr, false);
706             }
707             PatKind::Range(ref start, ref end, _) => {
708                 self.check_expr_within_pat(start, true);
709                 self.check_expr_within_pat(end, true);
710             }
711             _ => {}
712         }
713
714         visit::walk_pat(self, pat)
715     }
716
717     fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
718         if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
719             // A type binding, eg `for<'c> Foo: Send+Clone+'c`
720             self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
721         }
722         visit::walk_where_predicate(self, p);
723     }
724
725     fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
726         self.check_late_bound_lifetime_defs(&t.bound_generic_params);
727         visit::walk_poly_trait_ref(self, t, m);
728     }
729
730     fn visit_variant_data(&mut self, s: &'a VariantData) {
731         self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s))
732     }
733
734     fn visit_enum_def(&mut self, enum_definition: &'a EnumDef,
735                       generics: &'a Generics, item_id: NodeId, _: Span) {
736         self.with_banned_assoc_ty_bound(
737             |this| visit::walk_enum_def(this, enum_definition, generics, item_id))
738     }
739
740     fn visit_mac(&mut self, mac: &Mac) {
741         // when a new macro kind is added but the author forgets to set it up for expansion
742         // because that's the only part that won't cause a compiler error
743         self.session.diagnostic()
744             .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
745                                  the relevant `fold_*()` method in `PlaceholderExpander`?");
746     }
747
748     fn visit_impl_item(&mut self, ii: &'a ImplItem) {
749         if let ImplItemKind::Method(ref sig, _) = ii.kind {
750             self.check_fn_decl(&sig.decl);
751         }
752         visit::walk_impl_item(self, ii);
753     }
754 }
755
756 pub fn check_crate(session: &Session, krate: &Crate, lints: &mut lint::LintBuffer) -> bool {
757     let mut validator = AstValidator {
758         session,
759         has_proc_macro_decls: false,
760         outer_impl_trait: None,
761         is_impl_trait_banned: false,
762         is_assoc_ty_bound_banned: false,
763         lint_buffer: lints,
764     };
765     visit::walk_crate(&mut validator, krate);
766
767     validator.has_proc_macro_decls
768 }