]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/ast_validation.rs
Ignore new test on Windows
[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 ambigious 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!("ambigious 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(
186                     span, "consider adding parentheses", format!("({})", snippet),
187                 );
188             }
189
190             err.emit();
191         }
192     }
193
194     /// With eRFC 2497 adding if-let chains, there is a requirement that the parsing of
195     /// `&&` and `||` in a if-let statement be unambigious. This function returns a span and
196     /// a `BinOpKind` (either `&&` or `||` depending on what was ambigious) if it is determined
197     /// that the current expression parsed is ambigious and will break in future.
198     fn while_if_let_expr_ambiguity(&self, expr: &P<Expr>) -> Option<(Span, BinOpKind)> {
199         debug!("while_if_let_expr_ambiguity: expr.node: {:?}", expr.node);
200         match &expr.node {
201             ExprKind::Binary(op, _, _) if op.node == BinOpKind::And || op.node == BinOpKind::Or => {
202                 Some((expr.span, op.node))
203             },
204             ExprKind::Range(ref lhs, ref rhs, _) => {
205                 let lhs_ambigious = lhs.as_ref()
206                     .and_then(|lhs| self.while_if_let_expr_ambiguity(lhs));
207                 let rhs_ambigious = rhs.as_ref()
208                     .and_then(|rhs| self.while_if_let_expr_ambiguity(rhs));
209
210                 lhs_ambigious.or(rhs_ambigious)
211             }
212             _ => None,
213         }
214     }
215
216 }
217
218 impl<'a> Visitor<'a> for AstValidator<'a> {
219     fn visit_expr(&mut self, expr: &'a Expr) {
220         match expr.node {
221             ExprKind::IfLet(_, ref expr, _, _) | ExprKind::WhileLet(_, ref expr, _, _) =>
222                 self.while_if_let_ambiguity(&expr),
223             ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
224                 span_err!(self.session, expr.span, E0472, "asm! is unsupported on this target");
225             }
226             ExprKind::ObsoleteInPlace(ref place, ref val) => {
227                 let mut err = self.err_handler().struct_span_err(
228                     expr.span,
229                     "emplacement syntax is obsolete (for now, anyway)",
230                 );
231                 err.note(
232                     "for more information, see \
233                      <https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"
234                 );
235                 match val.node {
236                     ExprKind::Lit(ref v) if v.node.is_numeric() => {
237                         err.span_suggestion_with_applicability(
238                             place.span.between(val.span),
239                             "if you meant to write a comparison against a negative value, add a \
240                              space in between `<` and `-`",
241                             "< -".to_string(),
242                             Applicability::MaybeIncorrect
243                         );
244                     }
245                     _ => {}
246                 }
247                 err.emit();
248             }
249             _ => {}
250         }
251
252         visit::walk_expr(self, expr)
253     }
254
255     fn visit_ty(&mut self, ty: &'a Ty) {
256         match ty.node {
257             TyKind::BareFn(ref bfty) => {
258                 self.check_decl_no_pat(&bfty.decl, |span, _| {
259                     struct_span_err!(self.session, span, E0561,
260                                      "patterns aren't allowed in function pointer types").emit();
261                 });
262                 self.check_late_bound_lifetime_defs(&bfty.generic_params);
263             }
264             TyKind::TraitObject(ref bounds, ..) => {
265                 let mut any_lifetime_bounds = false;
266                 for bound in bounds {
267                     if let GenericBound::Outlives(ref lifetime) = *bound {
268                         if any_lifetime_bounds {
269                             span_err!(self.session, lifetime.ident.span, E0226,
270                                       "only a single explicit lifetime bound is permitted");
271                             break;
272                         }
273                         any_lifetime_bounds = true;
274                     }
275                 }
276                 self.no_questions_in_bounds(bounds, "trait object types", false);
277             }
278             TyKind::ImplTrait(_, ref bounds) => {
279                 if !bounds.iter()
280                           .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
281                     self.err_handler().span_err(ty.span, "at least one trait must be specified");
282                 }
283             }
284             _ => {}
285         }
286
287         visit::walk_ty(self, ty)
288     }
289
290     fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
291         // Check if the path in this `use` is not generic, such as `use foo::bar<T>;` While this
292         // can't happen normally thanks to the parser, a generic might sneak in if the `use` is
293         // built using a macro.
294         //
295         // macro_use foo {
296         //     ($p:path) => { use $p; }
297         // }
298         // foo!(bar::baz<T>);
299         use_tree.prefix.segments.iter().find(|segment| {
300             segment.args.is_some()
301         }).map(|segment| {
302             self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
303                                         "generic arguments in import path");
304         });
305
306         visit::walk_use_tree(self, use_tree, id);
307     }
308
309     fn visit_label(&mut self, label: &'a Label) {
310         self.check_label(label.ident);
311         visit::walk_label(self, label);
312     }
313
314     fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
315         self.check_lifetime(lifetime.ident);
316         visit::walk_lifetime(self, lifetime);
317     }
318
319     fn visit_item(&mut self, item: &'a Item) {
320         match item.node {
321             ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
322                 self.invalid_visibility(&item.vis, None);
323                 if let TyKind::Err = ty.node {
324                     self.err_handler()
325                         .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
326                         .help("use `auto trait Trait {}` instead").emit();
327                 }
328                 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
329                     span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
330                 }
331                 for impl_item in impl_items {
332                     self.invalid_visibility(&impl_item.vis, None);
333                     if let ImplItemKind::Method(ref sig, _) = impl_item.node {
334                         self.check_trait_fn_not_const(sig.header.constness);
335                         self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness);
336                     }
337                 }
338             }
339             ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
340                 self.invalid_visibility(&item.vis,
341                                         Some("place qualifiers on individual impl items instead"));
342                 if unsafety == Unsafety::Unsafe {
343                     span_err!(self.session, item.span, E0197, "inherent impls cannot be unsafe");
344                 }
345                 if polarity == ImplPolarity::Negative {
346                     self.err_handler().span_err(item.span, "inherent impls cannot be negative");
347                 }
348                 if defaultness == Defaultness::Default {
349                     self.err_handler()
350                         .struct_span_err(item.span, "inherent impls cannot be default")
351                         .note("only trait implementations may be annotated with default").emit();
352                 }
353             }
354             ItemKind::ForeignMod(..) => {
355                 self.invalid_visibility(
356                     &item.vis,
357                     Some("place qualifiers on individual foreign items instead"),
358                 );
359             }
360             ItemKind::Enum(ref def, _) => {
361                 for variant in &def.variants {
362                     self.invalid_non_exhaustive_attribute(variant);
363                     for field in variant.node.data.fields() {
364                         self.invalid_visibility(&field.vis, None);
365                     }
366                 }
367             }
368             ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
369                 if is_auto == IsAuto::Yes {
370                     // Auto traits cannot have generics, super traits nor contain items.
371                     if !generics.params.is_empty() {
372                         struct_span_err!(self.session, item.span, E0567,
373                                         "auto traits cannot have generic parameters").emit();
374                     }
375                     if !bounds.is_empty() {
376                         struct_span_err!(self.session, item.span, E0568,
377                                         "auto traits cannot have super traits").emit();
378                     }
379                     if !trait_items.is_empty() {
380                         struct_span_err!(self.session, item.span, E0380,
381                                 "auto traits cannot have methods or associated items").emit();
382                     }
383                 }
384                 self.no_questions_in_bounds(bounds, "supertraits", true);
385                 for trait_item in trait_items {
386                     if let TraitItemKind::Method(ref sig, ref block) = trait_item.node {
387                         self.check_trait_fn_not_async(trait_item.span, sig.header.asyncness);
388                         self.check_trait_fn_not_const(sig.header.constness);
389                         if block.is_none() {
390                             self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
391                                 if mut_ident {
392                                     self.session.buffer_lint(
393                                         lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
394                                         trait_item.id, span,
395                                         "patterns aren't allowed in methods without bodies");
396                                 } else {
397                                     struct_span_err!(self.session, span, E0642,
398                                         "patterns aren't allowed in methods without bodies").emit();
399                                 }
400                             });
401                         }
402                     }
403                 }
404             }
405             ItemKind::TraitAlias(Generics { ref params, .. }, ..) => {
406                 for param in params {
407                     match param.kind {
408                         GenericParamKind::Lifetime { .. } => {}
409                         GenericParamKind::Type { ref default, .. } => {
410                             if !param.bounds.is_empty() {
411                                 self.err_handler()
412                                     .span_err(param.ident.span, "type parameters on the left \
413                                         side of a trait alias cannot be bounded");
414                             }
415                             if !default.is_none() {
416                                 self.err_handler()
417                                     .span_err(param.ident.span, "type parameters on the left \
418                                         side of a trait alias cannot have defaults");
419                             }
420                         }
421                     }
422                 }
423             }
424             ItemKind::Mod(_) => {
425                 // Ensure that `path` attributes on modules are recorded as used (c.f. #35584).
426                 attr::first_attr_value_str_by_name(&item.attrs, "path");
427                 if attr::contains_name(&item.attrs, "warn_directory_ownership") {
428                     let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
429                     let msg = "cannot declare a new module at this location";
430                     self.session.buffer_lint(lint, item.id, item.span, msg);
431                 }
432             }
433             ItemKind::Union(ref vdata, _) => {
434                 if !vdata.is_struct() {
435                     self.err_handler().span_err(item.span,
436                                                 "tuple and unit unions are not permitted");
437                 }
438                 if vdata.fields().is_empty() {
439                     self.err_handler().span_err(item.span,
440                                                 "unions cannot have zero fields");
441                 }
442             }
443             _ => {}
444         }
445
446         visit::walk_item(self, item)
447     }
448
449     fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
450         match fi.node {
451             ForeignItemKind::Fn(ref decl, _) => {
452                 self.check_decl_no_pat(decl, |span, _| {
453                     struct_span_err!(self.session, span, E0130,
454                                      "patterns aren't allowed in foreign function declarations")
455                         .span_label(span, "pattern not allowed in foreign function").emit();
456                 });
457             }
458             ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
459         }
460
461         visit::walk_foreign_item(self, fi)
462     }
463
464     fn visit_vis(&mut self, vis: &'a Visibility) {
465         if let VisibilityKind::Restricted { ref path, .. } = vis.node {
466             path.segments.iter().find(|segment| segment.args.is_some()).map(|segment| {
467                 self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
468                                             "generic arguments in visibility path");
469             });
470         }
471
472         visit::walk_vis(self, vis)
473     }
474
475     fn visit_generics(&mut self, generics: &'a Generics) {
476         let mut seen_non_lifetime_param = false;
477         let mut seen_default = None;
478         for param in &generics.params {
479             match (&param.kind, seen_non_lifetime_param) {
480                 (GenericParamKind::Lifetime { .. }, true) => {
481                     self.err_handler()
482                         .span_err(param.ident.span, "lifetime parameters must be leading");
483                 },
484                 (GenericParamKind::Lifetime { .. }, false) => {}
485                 (GenericParamKind::Type { ref default, .. }, _) => {
486                     seen_non_lifetime_param = true;
487                     if default.is_some() {
488                         seen_default = Some(param.ident.span);
489                     } else if let Some(span) = seen_default {
490                         self.err_handler()
491                             .span_err(span, "type parameters with a default must be trailing");
492                         break;
493                     }
494                 }
495             }
496         }
497         for predicate in &generics.where_clause.predicates {
498             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
499                 self.err_handler().span_err(predicate.span, "equality constraints are not yet \
500                                                              supported in where clauses (#20041)");
501             }
502         }
503         visit::walk_generics(self, generics)
504     }
505
506     fn visit_generic_param(&mut self, param: &'a GenericParam) {
507         if let GenericParamKind::Lifetime { .. } = param.kind {
508             self.check_lifetime(param.ident);
509         }
510         visit::walk_generic_param(self, param);
511     }
512
513     fn visit_pat(&mut self, pat: &'a Pat) {
514         match pat.node {
515             PatKind::Lit(ref expr) => {
516                 self.check_expr_within_pat(expr, false);
517             }
518             PatKind::Range(ref start, ref end, _) => {
519                 self.check_expr_within_pat(start, true);
520                 self.check_expr_within_pat(end, true);
521             }
522             _ => {}
523         }
524
525         visit::walk_pat(self, pat)
526     }
527
528     fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
529         if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
530             // A type binding, eg `for<'c> Foo: Send+Clone+'c`
531             self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
532         }
533         visit::walk_where_predicate(self, p);
534     }
535
536     fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
537         self.check_late_bound_lifetime_defs(&t.bound_generic_params);
538         visit::walk_poly_trait_ref(self, t, m);
539     }
540
541     fn visit_mac(&mut self, mac: &Spanned<Mac_>) {
542         // when a new macro kind is added but the author forgets to set it up for expansion
543         // because that's the only part that won't cause a compiler error
544         self.session.diagnostic()
545             .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
546                                  the relevant `fold_*()` method in `PlaceholderExpander`?");
547     }
548 }
549
550 // Bans nested `impl Trait`, e.g. `impl Into<impl Debug>`.
551 // Nested `impl Trait` _is_ allowed in associated type position,
552 // e.g `impl Iterator<Item=impl Debug>`
553 struct NestedImplTraitVisitor<'a> {
554     session: &'a Session,
555     outer_impl_trait: Option<Span>,
556 }
557
558 impl<'a> NestedImplTraitVisitor<'a> {
559     fn with_impl_trait<F>(&mut self, outer_impl_trait: Option<Span>, f: F)
560         where F: FnOnce(&mut NestedImplTraitVisitor<'a>)
561     {
562         let old_outer_impl_trait = self.outer_impl_trait;
563         self.outer_impl_trait = outer_impl_trait;
564         f(self);
565         self.outer_impl_trait = old_outer_impl_trait;
566     }
567 }
568
569
570 impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> {
571     fn visit_ty(&mut self, t: &'a Ty) {
572         if let TyKind::ImplTrait(..) = t.node {
573             if let Some(outer_impl_trait) = self.outer_impl_trait {
574                 struct_span_err!(self.session, t.span, E0666,
575                                  "nested `impl Trait` is not allowed")
576                     .span_label(outer_impl_trait, "outer `impl Trait`")
577                     .span_label(t.span, "nested `impl Trait` here")
578                     .emit();
579
580             }
581             self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t));
582         } else {
583             visit::walk_ty(self, t);
584         }
585     }
586     fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
587         match *generic_args {
588             GenericArgs::AngleBracketed(ref data) => {
589                 for arg in &data.args {
590                     self.visit_generic_arg(arg)
591                 }
592                 for type_binding in &data.bindings {
593                     // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
594                     // are allowed to contain nested `impl Trait`.
595                     self.with_impl_trait(None, |this| visit::walk_ty(this, &type_binding.ty));
596                 }
597             }
598             GenericArgs::Parenthesized(ref data) => {
599                 for type_ in &data.inputs {
600                     self.visit_ty(type_);
601                 }
602                 if let Some(ref type_) = data.output {
603                     // `-> Foo` syntax is essentially an associated type binding,
604                     // so it is also allowed to contain nested `impl Trait`.
605                     self.with_impl_trait(None, |this| visit::walk_ty(this, type_));
606                 }
607             }
608         }
609     }
610
611     fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
612         // covered in AstValidator
613     }
614 }
615
616 // Bans `impl Trait` in path projections like `<impl Iterator>::Item` or `Foo::Bar<impl Trait>`.
617 struct ImplTraitProjectionVisitor<'a> {
618     session: &'a Session,
619     is_banned: bool,
620 }
621
622 impl<'a> ImplTraitProjectionVisitor<'a> {
623     fn with_ban<F>(&mut self, f: F)
624         where F: FnOnce(&mut ImplTraitProjectionVisitor<'a>)
625     {
626         let old_is_banned = self.is_banned;
627         self.is_banned = true;
628         f(self);
629         self.is_banned = old_is_banned;
630     }
631 }
632
633 impl<'a> Visitor<'a> for ImplTraitProjectionVisitor<'a> {
634     fn visit_ty(&mut self, t: &'a Ty) {
635         match t.node {
636             TyKind::ImplTrait(..) => {
637                 if self.is_banned {
638                     struct_span_err!(self.session, t.span, E0667,
639                         "`impl Trait` is not allowed in path parameters").emit();
640                 }
641             }
642             TyKind::Path(ref qself, ref path) => {
643                 // We allow these:
644                 //  - `Option<impl Trait>`
645                 //  - `option::Option<impl Trait>`
646                 //  - `option::Option<T>::Foo<impl Trait>
647                 //
648                 // But not these:
649                 //  - `<impl Trait>::Foo`
650                 //  - `option::Option<impl Trait>::Foo`.
651                 //
652                 // To implement this, we disallow `impl Trait` from `qself`
653                 // (for cases like `<impl Trait>::Foo>`)
654                 // but we allow `impl Trait` in `GenericArgs`
655                 // iff there are no more PathSegments.
656                 if let Some(ref qself) = *qself {
657                     // `impl Trait` in `qself` is always illegal
658                     self.with_ban(|this| this.visit_ty(&qself.ty));
659                 }
660
661                 for (i, segment) in path.segments.iter().enumerate() {
662                     // Allow `impl Trait` iff we're on the final path segment
663                     if i == path.segments.len() - 1 {
664                         visit::walk_path_segment(self, path.span, segment);
665                     } else {
666                         self.with_ban(|this|
667                             visit::walk_path_segment(this, path.span, segment));
668                     }
669                 }
670             }
671             _ => visit::walk_ty(self, t),
672         }
673     }
674
675     fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
676         // covered in AstValidator
677     }
678 }
679
680 pub fn check_crate(session: &Session, krate: &Crate) {
681     visit::walk_crate(
682         &mut NestedImplTraitVisitor {
683             session,
684             outer_impl_trait: None,
685         }, krate);
686
687     visit::walk_crate(
688         &mut ImplTraitProjectionVisitor {
689             session,
690             is_banned: false,
691         }, krate);
692
693     visit::walk_crate(&mut AstValidator { session: session }, krate)
694 }