]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/ast_validation.rs
Auto merge of #60630 - nnethercote:use-Symbol-more, r=petrochenkov
[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, sym};
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, MultiSpan};
24 use errors::{Applicability, FatalError};
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_visibility(&self, vis: &Visibility, note: Option<&str>) {
196         if let VisibilityKind::Inherited = vis.node {
197             return
198         }
199
200         let mut err = struct_span_err!(self.session,
201                                         vis.span,
202                                         E0449,
203                                         "unnecessary visibility qualifier");
204         if vis.node.is_pub() {
205             err.span_label(vis.span, "`pub` not permitted here because it's implied");
206         }
207         if let Some(note) = note {
208             err.note(note);
209         }
210         err.emit();
211     }
212
213     fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
214         for arg in &decl.inputs {
215             match arg.pat.node {
216                 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
217                 PatKind::Wild => {}
218                 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
219                     report_err(arg.pat.span, true),
220                 _ => report_err(arg.pat.span, false),
221             }
222         }
223     }
224
225     fn check_trait_fn_not_async(&self, span: Span, asyncness: &IsAsync) {
226         if asyncness.is_async() {
227             struct_span_err!(self.session, span, E0706,
228                              "trait fns cannot be declared `async`").emit()
229         }
230     }
231
232     fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
233         if constness.node == Constness::Const {
234             struct_span_err!(self.session, constness.span, E0379,
235                              "trait fns cannot be declared const")
236                 .span_label(constness.span, "trait fns cannot be const")
237                 .emit();
238         }
239     }
240
241     fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
242         for bound in bounds {
243             if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
244                 let mut err = self.err_handler().struct_span_err(poly.span,
245                     &format!("`?Trait` is not permitted in {}", where_));
246                 if is_trait {
247                     err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
248                 }
249                 err.emit();
250             }
251         }
252     }
253
254     /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
255     /// or paths for ranges.
256     //
257     // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
258     // That means making this work:
259     //
260     // ```rust,ignore (FIXME)
261     // struct S;
262     // macro_rules! m {
263     //     ($a:expr) => {
264     //         let $a = S;
265     //     }
266     // }
267     // m!(S);
268     // ```
269     fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
270         match expr.node {
271             ExprKind::Lit(..) => {}
272             ExprKind::Path(..) if allow_paths => {}
273             ExprKind::Unary(UnOp::Neg, ref inner)
274                 if match inner.node { ExprKind::Lit(_) => true, _ => false } => {}
275             _ => self.err_handler().span_err(expr.span, "arbitrary expressions aren't allowed \
276                                                          in patterns")
277         }
278     }
279
280     fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
281         // Check only lifetime parameters are present and that the lifetime
282         // parameters that are present have no bounds.
283         let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind {
284             GenericParamKind::Lifetime { .. } => {
285                 if !param.bounds.is_empty() {
286                     let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
287                     self.err_handler()
288                         .span_err(spans, "lifetime bounds cannot be used in this context");
289                 }
290                 None
291             }
292             _ => Some(param.ident.span),
293         }).collect();
294         if !non_lt_param_spans.is_empty() {
295             self.err_handler().span_err(non_lt_param_spans,
296                 "only lifetime parameters can be used in this context");
297         }
298     }
299
300     /// With eRFC 2497, we need to check whether an expression is ambiguous and warn or error
301     /// depending on the edition, this function handles that.
302     fn while_if_let_ambiguity(&self, expr: &P<Expr>) {
303         if let Some((span, op_kind)) = self.while_if_let_expr_ambiguity(&expr) {
304             let mut err = self.err_handler().struct_span_err(
305                 span, &format!("ambiguous use of `{}`", op_kind.to_string())
306             );
307
308             err.note(
309                 "this will be a error until the `let_chains` feature is stabilized"
310             );
311             err.note(
312                 "see rust-lang/rust#53668 for more information"
313             );
314
315             if let Ok(snippet) = self.session.source_map().span_to_snippet(span) {
316                 err.span_suggestion(
317                     span, "consider adding parentheses", format!("({})", snippet),
318                     Applicability::MachineApplicable,
319                 );
320             }
321
322             err.emit();
323         }
324     }
325
326     /// With eRFC 2497 adding if-let chains, there is a requirement that the parsing of
327     /// `&&` and `||` in a if-let statement be unambiguous. This function returns a span and
328     /// a `BinOpKind` (either `&&` or `||` depending on what was ambiguous) if it is determined
329     /// that the current expression parsed is ambiguous and will break in future.
330     fn while_if_let_expr_ambiguity(&self, expr: &P<Expr>) -> Option<(Span, BinOpKind)> {
331         debug!("while_if_let_expr_ambiguity: expr.node: {:?}", expr.node);
332         match &expr.node {
333             ExprKind::Binary(op, _, _) if op.node == BinOpKind::And || op.node == BinOpKind::Or => {
334                 Some((expr.span, op.node))
335             },
336             ExprKind::Range(ref lhs, ref rhs, _) => {
337                 let lhs_ambiguous = lhs.as_ref()
338                     .and_then(|lhs| self.while_if_let_expr_ambiguity(lhs));
339                 let rhs_ambiguous = rhs.as_ref()
340                     .and_then(|rhs| self.while_if_let_expr_ambiguity(rhs));
341
342                 lhs_ambiguous.or(rhs_ambiguous)
343             }
344             _ => None,
345         }
346     }
347 }
348
349 enum GenericPosition {
350     Param,
351     Arg,
352 }
353
354 fn validate_generics_order<'a>(
355     sess: &Session,
356     handler: &errors::Handler,
357     generics: impl Iterator<
358         Item = (
359             ParamKindOrd,
360             Option<&'a [GenericBound]>,
361             Span,
362             Option<String>
363         ),
364     >,
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     let mut found_type = false;
372     let mut found_const = false;
373
374     for (kind, bounds, span, ident) in generics {
375         if let Some(ident) = ident {
376             param_idents.push((kind, bounds, param_idents.len(), ident));
377         }
378         let max_param = &mut max_param;
379         match max_param {
380             Some(max_param) if *max_param > kind => {
381                 let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
382                 entry.1.push(span);
383             }
384             Some(_) | None => *max_param = Some(kind),
385         };
386         match kind {
387             ParamKindOrd::Type => found_type = true,
388             ParamKindOrd::Const => found_const = true,
389             _ => {}
390         }
391     }
392
393     let mut ordered_params = "<".to_string();
394     if !out_of_order.is_empty() {
395         param_idents.sort_by_key(|&(po, _, i, _)| (po, i));
396         let mut first = true;
397         for (_, bounds, _, ident) in param_idents {
398             if !first {
399                 ordered_params += ", ";
400             }
401             ordered_params += &ident;
402             if let Some(bounds) = bounds {
403                 if !bounds.is_empty() {
404                     ordered_params += ": ";
405                     ordered_params += &pprust::bounds_to_string(&bounds);
406                 }
407             }
408             first = false;
409         }
410     }
411     ordered_params += ">";
412
413     let pos_str = match pos {
414         GenericPosition::Param => "parameter",
415         GenericPosition::Arg => "argument",
416     };
417
418     for (param_ord, (max_param, spans)) in &out_of_order {
419         let mut err = handler.struct_span_err(spans.clone(),
420             &format!(
421                 "{} {pos}s must be declared prior to {} {pos}s",
422                 param_ord,
423                 max_param,
424                 pos = pos_str,
425             ));
426         if let GenericPosition::Param = pos {
427             err.span_suggestion(
428                 span,
429                 &format!(
430                     "reorder the {}s: lifetimes, then types{}",
431                     pos_str,
432                     if sess.features_untracked().const_generics { ", then consts" } else { "" },
433                 ),
434                 ordered_params.clone(),
435                 Applicability::MachineApplicable,
436             );
437         }
438         err.emit();
439     }
440
441     // FIXME(const_generics): we shouldn't have to abort here at all, but we currently get ICEs
442     // if we don't. Const parameters and type parameters can currently conflict if they
443     // are out-of-order.
444     if !out_of_order.is_empty() && found_type && found_const {
445         FatalError.raise();
446     }
447 }
448
449 impl<'a> Visitor<'a> for AstValidator<'a> {
450     fn visit_expr(&mut self, expr: &'a Expr) {
451         match expr.node {
452             ExprKind::IfLet(_, ref expr, _, _) | ExprKind::WhileLet(_, ref expr, _, _) =>
453                 self.while_if_let_ambiguity(&expr),
454             ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
455                 span_err!(self.session, expr.span, E0472, "asm! is unsupported on this target");
456             }
457             ExprKind::ObsoleteInPlace(ref place, ref val) => {
458                 let mut err = self.err_handler().struct_span_err(
459                     expr.span,
460                     "emplacement syntax is obsolete (for now, anyway)",
461                 );
462                 err.note(
463                     "for more information, see \
464                      <https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"
465                 );
466                 match val.node {
467                     ExprKind::Lit(ref v) if v.node.is_numeric() => {
468                         err.span_suggestion(
469                             place.span.between(val.span),
470                             "if you meant to write a comparison against a negative value, add a \
471                              space in between `<` and `-`",
472                             "< -".to_string(),
473                             Applicability::MaybeIncorrect
474                         );
475                     }
476                     _ => {}
477                 }
478                 err.emit();
479             }
480             _ => {}
481         }
482
483         visit::walk_expr(self, expr)
484     }
485
486     fn visit_ty(&mut self, ty: &'a Ty) {
487         match ty.node {
488             TyKind::BareFn(ref bfty) => {
489                 self.check_decl_no_pat(&bfty.decl, |span, _| {
490                     struct_span_err!(self.session, span, E0561,
491                                      "patterns aren't allowed in function pointer types").emit();
492                 });
493                 self.check_late_bound_lifetime_defs(&bfty.generic_params);
494             }
495             TyKind::TraitObject(ref bounds, ..) => {
496                 let mut any_lifetime_bounds = false;
497                 for bound in bounds {
498                     if let GenericBound::Outlives(ref lifetime) = *bound {
499                         if any_lifetime_bounds {
500                             span_err!(self.session, lifetime.ident.span, E0226,
501                                       "only a single explicit lifetime bound is permitted");
502                             break;
503                         }
504                         any_lifetime_bounds = true;
505                     }
506                 }
507                 self.no_questions_in_bounds(bounds, "trait object types", false);
508             }
509             TyKind::ImplTrait(_, ref bounds) => {
510                 if self.is_impl_trait_banned {
511                     if self.warning_period_57979_impl_trait_in_proj {
512                         self.session.buffer_lint(
513                             NESTED_IMPL_TRAIT, ty.id, ty.span,
514                             "`impl Trait` is not allowed in path parameters");
515                     } else {
516                         struct_span_err!(self.session, ty.span, E0667,
517                             "`impl Trait` is not allowed in path parameters").emit();
518                     }
519                 }
520
521                 if let Some(outer_impl_trait) = self.outer_impl_trait {
522                     if outer_impl_trait.should_warn_instead_of_error() {
523                         self.session.buffer_lint_with_diagnostic(
524                             NESTED_IMPL_TRAIT, ty.id, ty.span,
525                             "nested `impl Trait` is not allowed",
526                             BuiltinLintDiagnostics::NestedImplTrait {
527                                 outer_impl_trait_span: outer_impl_trait.span,
528                                 inner_impl_trait_span: ty.span,
529                             });
530                     } else {
531                         struct_span_err!(self.session, ty.span, E0666,
532                             "nested `impl Trait` is not allowed")
533                             .span_label(outer_impl_trait.span, "outer `impl Trait`")
534                             .span_label(ty.span, "nested `impl Trait` here")
535                             .emit();
536                     }
537                 }
538
539                 if !bounds.iter()
540                           .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
541                     self.err_handler().span_err(ty.span, "at least one trait must be specified");
542                 }
543
544                 self.with_impl_trait_in_proj_warning(true, |this| this.walk_ty(ty));
545                 return;
546             }
547             _ => {}
548         }
549
550         self.walk_ty(ty)
551     }
552
553     fn visit_label(&mut self, label: &'a Label) {
554         self.check_label(label.ident);
555         visit::walk_label(self, label);
556     }
557
558     fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
559         self.check_lifetime(lifetime.ident);
560         visit::walk_lifetime(self, lifetime);
561     }
562
563     fn visit_item(&mut self, item: &'a Item) {
564         if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)  ) {
565             self.has_proc_macro_decls = true;
566         }
567
568         if attr::contains_name(&item.attrs, sym::global_allocator) {
569             self.has_global_allocator = true;
570         }
571
572         match item.node {
573             ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
574                 self.invalid_visibility(&item.vis, None);
575                 if let TyKind::Err = ty.node {
576                     self.err_handler()
577                         .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
578                         .help("use `auto trait Trait {}` instead").emit();
579                 }
580                 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
581                     span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
582                 }
583                 for impl_item in impl_items {
584                     self.invalid_visibility(&impl_item.vis, None);
585                     if let ImplItemKind::Method(ref sig, _) = impl_item.node {
586                         self.check_trait_fn_not_const(sig.header.constness);
587                         self.check_trait_fn_not_async(impl_item.span, &sig.header.asyncness.node);
588                     }
589                 }
590             }
591             ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
592                 self.invalid_visibility(&item.vis,
593                                         Some("place qualifiers on individual impl items instead"));
594                 if unsafety == Unsafety::Unsafe {
595                     span_err!(self.session, item.span, E0197, "inherent impls cannot be unsafe");
596                 }
597                 if polarity == ImplPolarity::Negative {
598                     self.err_handler().span_err(item.span, "inherent impls cannot be negative");
599                 }
600                 if defaultness == Defaultness::Default {
601                     self.err_handler()
602                         .struct_span_err(item.span, "inherent impls cannot be default")
603                         .note("only trait implementations may be annotated with default").emit();
604                 }
605             }
606             ItemKind::Fn(_, ref header, ref generics, _) => {
607                 // We currently do not permit const generics in `const fn`, as
608                 // this is tantamount to allowing compile-time dependent typing.
609                 self.visit_fn_header(header);
610                 if header.constness.node == Constness::Const {
611                     // Look for const generics and error if we find any.
612                     for param in &generics.params {
613                         match param.kind {
614                             GenericParamKind::Const { .. } => {
615                                 self.err_handler()
616                                     .struct_span_err(
617                                         item.span,
618                                         "const parameters are not permitted in `const fn`",
619                                     )
620                                     .emit();
621                             }
622                             _ => {}
623                         }
624                     }
625                 }
626             }
627             ItemKind::ForeignMod(..) => {
628                 self.invalid_visibility(
629                     &item.vis,
630                     Some("place qualifiers on individual foreign items instead"),
631                 );
632             }
633             ItemKind::Enum(ref def, _) => {
634                 for variant in &def.variants {
635                     for field in variant.node.data.fields() {
636                         self.invalid_visibility(&field.vis, None);
637                     }
638                 }
639             }
640             ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
641                 if is_auto == IsAuto::Yes {
642                     // Auto traits cannot have generics, super traits nor contain items.
643                     if !generics.params.is_empty() {
644                         struct_span_err!(self.session, item.span, E0567,
645                                         "auto traits cannot have generic parameters").emit();
646                     }
647                     if !bounds.is_empty() {
648                         struct_span_err!(self.session, item.span, E0568,
649                                         "auto traits cannot have super traits").emit();
650                     }
651                     if !trait_items.is_empty() {
652                         struct_span_err!(self.session, item.span, E0380,
653                                 "auto traits cannot have methods or associated items").emit();
654                     }
655                 }
656                 self.no_questions_in_bounds(bounds, "supertraits", true);
657                 for trait_item in trait_items {
658                     if let TraitItemKind::Method(ref sig, ref block) = trait_item.node {
659                         self.check_trait_fn_not_async(trait_item.span, &sig.header.asyncness.node);
660                         self.check_trait_fn_not_const(sig.header.constness);
661                         if block.is_none() {
662                             self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
663                                 if mut_ident {
664                                     self.session.buffer_lint(
665                                         lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
666                                         trait_item.id, span,
667                                         "patterns aren't allowed in methods without bodies");
668                                 } else {
669                                     struct_span_err!(self.session, span, E0642,
670                                         "patterns aren't allowed in methods without bodies").emit();
671                                 }
672                             });
673                         }
674                     }
675                 }
676             }
677             ItemKind::Mod(_) => {
678                 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
679                 attr::first_attr_value_str_by_name(&item.attrs, sym::path);
680                 if attr::contains_name(&item.attrs, sym::warn_directory_ownership) {
681                     let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
682                     let msg = "cannot declare a new module at this location";
683                     self.session.buffer_lint(lint, item.id, item.span, msg);
684                 }
685             }
686             ItemKind::Union(ref vdata, _) => {
687                 if let VariantData::Tuple(..) | VariantData::Unit(..) = vdata {
688                     self.err_handler().span_err(item.span,
689                                                 "tuple and unit unions are not permitted");
690                 }
691                 if vdata.fields().is_empty() {
692                     self.err_handler().span_err(item.span,
693                                                 "unions cannot have zero fields");
694                 }
695             }
696             ItemKind::Existential(ref bounds, _) => {
697                 if !bounds.iter()
698                           .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
699                     let msp = MultiSpan::from_spans(bounds.iter()
700                         .map(|bound| bound.span()).collect());
701                     self.err_handler().span_err(msp, "at least one trait must be specified");
702                 }
703             }
704             _ => {}
705         }
706
707         visit::walk_item(self, item)
708     }
709
710     fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
711         match fi.node {
712             ForeignItemKind::Fn(ref decl, _) => {
713                 self.check_decl_no_pat(decl, |span, _| {
714                     struct_span_err!(self.session, span, E0130,
715                                      "patterns aren't allowed in foreign function declarations")
716                         .span_label(span, "pattern not allowed in foreign function").emit();
717                 });
718             }
719             ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
720         }
721
722         visit::walk_foreign_item(self, fi)
723     }
724
725     // Mirrors visit::walk_generic_args, but tracks relevant state
726     fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
727         match *generic_args {
728             GenericArgs::AngleBracketed(ref data) => {
729                 walk_list!(self, visit_generic_arg, &data.args);
730                 validate_generics_order(
731                     self.session,
732                     self.err_handler(),
733                     data.args.iter().map(|arg| {
734                         (match arg {
735                             GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
736                             GenericArg::Type(..) => ParamKindOrd::Type,
737                             GenericArg::Const(..) => ParamKindOrd::Const,
738                         }, None, arg.span(), None)
739                     }),
740                     GenericPosition::Arg,
741                     generic_args.span(),
742                 );
743
744                 // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
745                 // are allowed to contain nested `impl Trait`.
746                 self.with_impl_trait(None, |this| {
747                     walk_list!(this, visit_assoc_type_binding_from_generic_args, &data.bindings);
748                 });
749             }
750             GenericArgs::Parenthesized(ref data) => {
751                 walk_list!(self, visit_ty, &data.inputs);
752                 if let Some(ref type_) = data.output {
753                     // `-> Foo` syntax is essentially an associated type binding,
754                     // so it is also allowed to contain nested `impl Trait`.
755                     self.with_impl_trait(None, |this| this.visit_ty_from_generic_args(type_));
756                 }
757             }
758         }
759     }
760
761     fn visit_generics(&mut self, generics: &'a Generics) {
762         let mut prev_ty_default = None;
763         for param in &generics.params {
764             if let GenericParamKind::Type { ref default, .. } = param.kind {
765                 if default.is_some() {
766                     prev_ty_default = Some(param.ident.span);
767                 } else if let Some(span) = prev_ty_default {
768                     self.err_handler()
769                         .span_err(span, "type parameters with a default must be trailing");
770                     break;
771                 }
772             }
773         }
774
775         validate_generics_order(
776             self.session,
777             self.err_handler(),
778             generics.params.iter().map(|param| {
779                 let ident = Some(param.ident.to_string());
780                 let (kind, ident) = match &param.kind {
781                     GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, ident),
782                     GenericParamKind::Type { .. } => (ParamKindOrd::Type, ident),
783                     GenericParamKind::Const { ref ty } => {
784                         let ty = pprust::ty_to_string(ty);
785                         (ParamKindOrd::Const, Some(format!("const {}: {}", param.ident, ty)))
786                     }
787                 };
788                 (kind, Some(&*param.bounds), param.ident.span, ident)
789             }),
790             GenericPosition::Param,
791             generics.span,
792         );
793
794         for predicate in &generics.where_clause.predicates {
795             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
796                 self.err_handler()
797                     .span_err(predicate.span, "equality constraints are not yet \
798                                                supported in where clauses (see #20041)");
799             }
800         }
801
802         visit::walk_generics(self, generics)
803     }
804
805     fn visit_generic_param(&mut self, param: &'a GenericParam) {
806         if let GenericParamKind::Lifetime { .. } = param.kind {
807             self.check_lifetime(param.ident);
808         }
809         visit::walk_generic_param(self, param);
810     }
811
812     fn visit_pat(&mut self, pat: &'a Pat) {
813         match pat.node {
814             PatKind::Lit(ref expr) => {
815                 self.check_expr_within_pat(expr, false);
816             }
817             PatKind::Range(ref start, ref end, _) => {
818                 self.check_expr_within_pat(start, true);
819                 self.check_expr_within_pat(end, true);
820             }
821             _ => {}
822         }
823
824         visit::walk_pat(self, pat)
825     }
826
827     fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
828         if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
829             // A type binding, eg `for<'c> Foo: Send+Clone+'c`
830             self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
831         }
832         visit::walk_where_predicate(self, p);
833     }
834
835     fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
836         self.check_late_bound_lifetime_defs(&t.bound_generic_params);
837         visit::walk_poly_trait_ref(self, t, m);
838     }
839
840     fn visit_mac(&mut self, mac: &Spanned<Mac_>) {
841         // when a new macro kind is added but the author forgets to set it up for expansion
842         // because that's the only part that won't cause a compiler error
843         self.session.diagnostic()
844             .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
845                                  the relevant `fold_*()` method in `PlaceholderExpander`?");
846     }
847
848     fn visit_fn_header(&mut self, header: &'a FnHeader) {
849         if header.asyncness.node.is_async() && self.session.rust_2015() {
850             struct_span_err!(self.session, header.asyncness.span, E0670,
851                              "`async fn` is not permitted in the 2015 edition").emit();
852         }
853     }
854 }
855
856 pub fn check_crate(session: &Session, krate: &Crate) -> (bool, bool) {
857     let mut validator = AstValidator {
858         session,
859         has_proc_macro_decls: false,
860         has_global_allocator: false,
861         outer_impl_trait: None,
862         is_impl_trait_banned: false,
863         warning_period_57979_didnt_record_next_impl_trait: false,
864         warning_period_57979_impl_trait_in_proj: false,
865     };
866     visit::walk_crate(&mut validator, krate);
867
868     (validator.has_proc_macro_decls, validator.has_global_allocator)
869 }