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