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::source_map::Spanned;
24 use syntax::symbol::keywords;
26 use syntax::visit::{self, Visitor};
29 use errors::Applicability;
31 struct AstValidator<'a> {
35 impl<'a> AstValidator<'a> {
36 fn err_handler(&self) -> &errors::Handler {
37 &self.session.diagnostic()
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");
49 fn check_label(&self, ident: Ident) {
50 if ident.without_first_quote().is_reserved() {
52 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
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");
64 fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
65 if let VisibilityKind::Inherited = vis.node {
69 let mut err = struct_span_err!(self.session,
72 "unnecessary visibility qualifier");
73 if vis.node.is_pub() {
74 err.span_label(vis.span, "`pub` not permitted here because it's implied");
76 if let Some(note) = note {
82 fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
83 for arg in &decl.inputs {
85 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
87 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
88 report_err(arg.pat.span, true),
89 _ => report_err(arg.pat.span, false),
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()
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")
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_));
116 err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
123 /// matches '-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus),
124 /// or path for ranges.
126 /// FIXME: do we want to allow expr -> pattern conversion to create path expressions?
127 /// That means making this work:
129 /// ```rust,ignore (FIXME)
138 fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
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 \
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();
157 .span_err(spans, "lifetime bounds cannot be used in this context");
161 _ => Some(param.ident.span),
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");
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())
178 "this will be a error until the `let_chains` feature is stabilized"
181 "see rust-lang/rust#53668 for more information"
184 if let Ok(snippet) = self.session.source_map().span_to_snippet(span) {
186 span, "consider adding parentheses", format!("({})", snippet),
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);
201 ExprKind::Binary(op, _, _) if op.node == BinOpKind::And || op.node == BinOpKind::Or => {
202 Some((expr.span, op.node))
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));
210 lhs_ambigious.or(rhs_ambigious)
218 impl<'a> Visitor<'a> for AstValidator<'a> {
219 fn visit_expr(&mut self, expr: &'a Expr) {
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");
226 ExprKind::ObsoleteInPlace(ref place, ref val) => {
227 let mut err = self.err_handler().struct_span_err(
229 "emplacement syntax is obsolete (for now, anyway)",
232 "for more information, see \
233 <https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"
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 `-`",
242 Applicability::MaybeIncorrect
252 visit::walk_expr(self, expr)
255 fn visit_ty(&mut self, ty: &'a Ty) {
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();
262 self.check_late_bound_lifetime_defs(&bfty.generic_params);
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");
273 any_lifetime_bounds = true;
276 self.no_questions_in_bounds(bounds, "trait object types", false);
278 TyKind::ImplTrait(_, ref bounds) => {
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");
287 visit::walk_ty(self, ty)
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.
296 // ($p:path) => { use $p; }
298 // foo!(bar::baz<T>);
299 use_tree.prefix.segments.iter().find(|segment| {
300 segment.args.is_some()
302 self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
303 "generic arguments in import path");
306 visit::walk_use_tree(self, use_tree, id);
309 fn visit_label(&mut self, label: &'a Label) {
310 self.check_label(label.ident);
311 visit::walk_label(self, label);
314 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
315 self.check_lifetime(lifetime.ident);
316 visit::walk_lifetime(self, lifetime);
319 fn visit_item(&mut self, item: &'a Item) {
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 {
325 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
326 .help("use `auto trait Trait {}` instead").emit();
328 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
329 span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
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);
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");
345 if polarity == ImplPolarity::Negative {
346 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
348 if defaultness == Defaultness::Default {
350 .struct_span_err(item.span, "inherent impls cannot be default")
351 .note("only trait implementations may be annotated with default").emit();
354 ItemKind::ForeignMod(..) => {
355 self.invalid_visibility(
357 Some("place qualifiers on individual foreign items instead"),
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);
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();
375 if !bounds.is_empty() {
376 struct_span_err!(self.session, item.span, E0568,
377 "auto traits cannot have super traits").emit();
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();
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);
390 self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
392 self.session.buffer_lint(
393 lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
395 "patterns aren't allowed in methods without bodies");
397 struct_span_err!(self.session, span, E0642,
398 "patterns aren't allowed in methods without bodies").emit();
405 ItemKind::TraitAlias(Generics { ref params, .. }, ..) => {
406 for param in params {
408 GenericParamKind::Lifetime { .. } => {}
409 GenericParamKind::Type { ref default, .. } => {
410 if !param.bounds.is_empty() {
412 .span_err(param.ident.span, "type parameters on the left \
413 side of a trait alias cannot be bounded");
415 if !default.is_none() {
417 .span_err(param.ident.span, "type parameters on the left \
418 side of a trait alias cannot have defaults");
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);
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");
438 if vdata.fields().is_empty() {
439 self.err_handler().span_err(item.span,
440 "unions cannot have zero fields");
446 visit::walk_item(self, item)
449 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
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();
458 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
461 visit::walk_foreign_item(self, fi)
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");
472 visit::walk_vis(self, vis)
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 (¶m.kind, seen_non_lifetime_param) {
480 (GenericParamKind::Lifetime { .. }, true) => {
482 .span_err(param.ident.span, "lifetime parameters must be leading");
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 {
491 .span_err(span, "type parameters with a default must be trailing");
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)");
503 visit::walk_generics(self, generics)
506 fn visit_generic_param(&mut self, param: &'a GenericParam) {
507 if let GenericParamKind::Lifetime { .. } = param.kind {
508 self.check_lifetime(param.ident);
510 visit::walk_generic_param(self, param);
513 fn visit_pat(&mut self, pat: &'a Pat) {
515 PatKind::Lit(ref expr) => {
516 self.check_expr_within_pat(expr, false);
518 PatKind::Range(ref start, ref end, _) => {
519 self.check_expr_within_pat(start, true);
520 self.check_expr_within_pat(end, true);
525 visit::walk_pat(self, pat)
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);
533 visit::walk_where_predicate(self, p);
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);
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`?");
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>,
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>)
562 let old_outer_impl_trait = self.outer_impl_trait;
563 self.outer_impl_trait = outer_impl_trait;
565 self.outer_impl_trait = old_outer_impl_trait;
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")
581 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t));
583 visit::walk_ty(self, t);
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)
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));
598 GenericArgs::Parenthesized(ref data) => {
599 for type_ in &data.inputs {
600 self.visit_ty(type_);
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_));
611 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
612 // covered in AstValidator
616 // Bans `impl Trait` in path projections like `<impl Iterator>::Item` or `Foo::Bar<impl Trait>`.
617 struct ImplTraitProjectionVisitor<'a> {
618 session: &'a Session,
622 impl<'a> ImplTraitProjectionVisitor<'a> {
623 fn with_ban<F>(&mut self, f: F)
624 where F: FnOnce(&mut ImplTraitProjectionVisitor<'a>)
626 let old_is_banned = self.is_banned;
627 self.is_banned = true;
629 self.is_banned = old_is_banned;
633 impl<'a> Visitor<'a> for ImplTraitProjectionVisitor<'a> {
634 fn visit_ty(&mut self, t: &'a Ty) {
636 TyKind::ImplTrait(..) => {
638 struct_span_err!(self.session, t.span, E0667,
639 "`impl Trait` is not allowed in path parameters").emit();
642 TyKind::Path(ref qself, ref path) => {
644 // - `Option<impl Trait>`
645 // - `option::Option<impl Trait>`
646 // - `option::Option<T>::Foo<impl Trait>
649 // - `<impl Trait>::Foo`
650 // - `option::Option<impl Trait>::Foo`.
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));
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);
667 visit::walk_path_segment(this, path.span, segment));
671 _ => visit::walk_ty(self, t),
675 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
676 // covered in AstValidator
680 pub fn check_crate(session: &Session, krate: &Crate) {
682 &mut NestedImplTraitVisitor {
684 outer_impl_trait: None,
688 &mut ImplTraitProjectionVisitor {
693 visit::walk_crate(&mut AstValidator { session: session }, krate)