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