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