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