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