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.
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.
11 // Validate AST before lowering it to HIR
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.
20 use rustc::session::Session;
23 use syntax::codemap::Spanned;
24 use syntax::symbol::keywords;
25 use syntax::visit::{self, Visitor};
29 struct AstValidator<'a> {
33 impl<'a> AstValidator<'a> {
34 fn err_handler(&self) -> &errors::Handler {
35 &self.session.parse_sess.span_diagnostic
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");
47 fn check_label(&self, ident: Ident) {
48 if ident.without_first_quote().is_reserved() {
50 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
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");
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,
67 "unnecessary visibility qualifier");
68 if vis.node == VisibilityKind::Public {
69 err.span_label(vis.span, "`pub` not permitted here because it's implied");
71 if let Some(note) = note {
78 fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
79 for arg in &decl.inputs {
81 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
83 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
84 report_err(arg.pat.span, true),
85 _ => report_err(arg.pat.span, false),
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()
97 fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
98 match constness.node {
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")
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_));
115 err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
122 /// matches '-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus),
123 /// or path for ranges.
125 /// FIXME: do we want to allow expr -> pattern conversion to create path expressions?
126 /// That means making this work:
128 /// ```rust,ignore (FIXME)
137 fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
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 \
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();
156 .span_err(spans, "lifetime bounds cannot be used in this context");
160 _ => Some(param.ident.span),
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");
169 impl<'a> Visitor<'a> for AstValidator<'a> {
170 fn visit_expr(&mut self, expr: &'a Expr) {
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");
175 ExprKind::ObsoleteInPlace(..) => {
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>")
185 visit::walk_expr(self, expr)
188 fn visit_ty(&mut self, ty: &'a Ty) {
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();
195 self.check_late_bound_lifetime_defs(&bfty.generic_params);
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");
206 any_lifetime_bounds = true;
209 self.no_questions_in_bounds(bounds, "trait object types", false);
211 TyKind::ImplTrait(ref bounds) => {
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");
220 visit::walk_ty(self, ty)
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.
229 // ($p:path) => { use $p; }
231 // foo!(bar::baz<T>);
232 use_tree.prefix.segments.iter().find(|segment| {
233 segment.args.is_some()
235 self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
236 "generic arguments in import path");
239 visit::walk_use_tree(self, use_tree, id);
242 fn visit_label(&mut self, label: &'a Label) {
243 self.check_label(label.ident);
244 visit::walk_label(self, label);
247 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
248 self.check_lifetime(lifetime.ident);
249 visit::walk_lifetime(self, lifetime);
252 fn visit_item(&mut self, item: &'a Item) {
254 ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
255 self.invalid_visibility(&item.vis, None);
256 if ty.node == TyKind::Err {
258 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
259 .help("use `auto trait Trait {}` instead").emit();
261 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
262 span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
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);
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");
277 if polarity == ImplPolarity::Negative {
278 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
280 if defaultness == Defaultness::Default {
282 .struct_span_err(item.span, "inherent impls cannot be default")
283 .note("only trait implementations may be annotated with default").emit();
286 ItemKind::ForeignMod(..) => {
287 self.invalid_visibility(
289 Some("place qualifiers on individual foreign items instead"),
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);
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();
307 if !bounds.is_empty() {
308 struct_span_err!(self.session, item.span, E0568,
309 "auto traits cannot have super traits").emit();
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();
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);
322 self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
324 self.session.buffer_lint(
325 lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
327 "patterns aren't allowed in methods without bodies");
329 struct_span_err!(self.session, span, E0642,
330 "patterns aren't allowed in methods without bodies").emit();
337 ItemKind::TraitAlias(Generics { ref params, .. }, ..) => {
338 for param in params {
340 GenericParamKind::Lifetime { .. } => {}
341 GenericParamKind::Type { ref default, .. } => {
342 if !param.bounds.is_empty() {
344 .span_err(param.ident.span, "type parameters on the left \
345 side of a trait alias cannot be bounded");
347 if !default.is_none() {
349 .span_err(param.ident.span, "type parameters on the left \
350 side of a trait alias cannot have defaults");
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);
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");
370 if vdata.fields().len() == 0 {
371 self.err_handler().span_err(item.span,
372 "unions cannot have zero fields");
378 visit::walk_item(self, item)
381 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
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();
390 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
393 visit::walk_foreign_item(self, fi)
396 fn visit_vis(&mut self, vis: &'a Visibility) {
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");
407 visit::walk_vis(self, vis)
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 (¶m.kind, seen_non_lifetime_param) {
415 (GenericParamKind::Lifetime { .. }, true) => {
417 .span_err(param.ident.span, "lifetime parameters must be leading");
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 {
426 .span_err(span, "type parameters with a default must be trailing");
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)");
438 visit::walk_generics(self, generics)
441 fn visit_generic_param(&mut self, param: &'a GenericParam) {
442 if let GenericParamKind::Lifetime { .. } = param.kind {
443 self.check_lifetime(param.ident);
445 visit::walk_generic_param(self, param);
448 fn visit_pat(&mut self, pat: &'a Pat) {
450 PatKind::Lit(ref expr) => {
451 self.check_expr_within_pat(expr, false);
453 PatKind::Range(ref start, ref end, _) => {
454 self.check_expr_within_pat(start, true);
455 self.check_expr_within_pat(end, true);
460 visit::walk_pat(self, pat)
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);
468 visit::walk_where_predicate(self, p);
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);
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`?");
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>,
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>)
497 let old_outer_impl_trait = self.outer_impl_trait;
498 self.outer_impl_trait = outer_impl_trait;
500 self.outer_impl_trait = old_outer_impl_trait;
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")
516 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t));
518 visit::walk_ty(self, t);
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),
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));
534 GenericArgs::Parenthesized(ref data) => {
535 for type_ in &data.inputs {
536 self.visit_ty(type_);
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_));
547 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
548 // covered in AstValidator
552 // Bans `impl Trait` in path projections like `<impl Iterator>::Item` or `Foo::Bar<impl Trait>`.
553 struct ImplTraitProjectionVisitor<'a> {
554 session: &'a Session,
558 impl<'a> ImplTraitProjectionVisitor<'a> {
559 fn with_ban<F>(&mut self, f: F)
560 where F: FnOnce(&mut ImplTraitProjectionVisitor<'a>)
562 let old_is_banned = self.is_banned;
563 self.is_banned = true;
565 self.is_banned = old_is_banned;
569 impl<'a> Visitor<'a> for ImplTraitProjectionVisitor<'a> {
570 fn visit_ty(&mut self, t: &'a Ty) {
572 TyKind::ImplTrait(_) => {
574 struct_span_err!(self.session, t.span, E0667,
575 "`impl Trait` is not allowed in path parameters")
579 TyKind::Path(ref qself, ref path) => {
581 // - `Option<impl Trait>`
582 // - `option::Option<impl Trait>`
583 // - `option::Option<T>::Foo<impl Trait>
586 // - `<impl Trait>::Foo`
587 // - `option::Option<impl Trait>::Foo`.
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));
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);
604 visit::walk_path_segment(this, path.span, segment));
608 _ => visit::walk_ty(self, t),
612 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
613 // covered in AstValidator
617 pub fn check_crate(session: &Session, krate: &Crate) {
619 &mut NestedImplTraitVisitor {
621 outer_impl_trait: None,
625 &mut ImplTraitProjectionVisitor {
630 visit::walk_crate(&mut AstValidator { session: session }, krate)