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) {
185 err.span_suggestion_with_applicability(
186 span, "consider adding parentheses", format!("({})", snippet),
187 Applicability::MachineApplicable,
195 /// With eRFC 2497 adding if-let chains, there is a requirement that the parsing of
196 /// `&&` and `||` in a if-let statement be unambigious. This function returns a span and
197 /// a `BinOpKind` (either `&&` or `||` depending on what was ambigious) if it is determined
198 /// that the current expression parsed is ambigious and will break in future.
199 fn while_if_let_expr_ambiguity(&self, expr: &P<Expr>) -> Option<(Span, BinOpKind)> {
200 debug!("while_if_let_expr_ambiguity: expr.node: {:?}", expr.node);
202 ExprKind::Binary(op, _, _) if op.node == BinOpKind::And || op.node == BinOpKind::Or => {
203 Some((expr.span, op.node))
205 ExprKind::Range(ref lhs, ref rhs, _) => {
206 let lhs_ambigious = lhs.as_ref()
207 .and_then(|lhs| self.while_if_let_expr_ambiguity(lhs));
208 let rhs_ambigious = rhs.as_ref()
209 .and_then(|rhs| self.while_if_let_expr_ambiguity(rhs));
211 lhs_ambigious.or(rhs_ambigious)
219 impl<'a> Visitor<'a> for AstValidator<'a> {
220 fn visit_expr(&mut self, expr: &'a Expr) {
222 ExprKind::IfLet(_, ref expr, _, _) | ExprKind::WhileLet(_, ref expr, _, _) =>
223 self.while_if_let_ambiguity(&expr),
224 ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
225 span_err!(self.session, expr.span, E0472, "asm! is unsupported on this target");
227 ExprKind::ObsoleteInPlace(ref place, ref val) => {
228 let mut err = self.err_handler().struct_span_err(
230 "emplacement syntax is obsolete (for now, anyway)",
233 "for more information, see \
234 <https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"
237 ExprKind::Lit(ref v) if v.node.is_numeric() => {
238 err.span_suggestion_with_applicability(
239 place.span.between(val.span),
240 "if you meant to write a comparison against a negative value, add a \
241 space in between `<` and `-`",
243 Applicability::MaybeIncorrect
253 visit::walk_expr(self, expr)
256 fn visit_ty(&mut self, ty: &'a Ty) {
258 TyKind::BareFn(ref bfty) => {
259 self.check_decl_no_pat(&bfty.decl, |span, _| {
260 struct_span_err!(self.session, span, E0561,
261 "patterns aren't allowed in function pointer types").emit();
263 self.check_late_bound_lifetime_defs(&bfty.generic_params);
265 TyKind::TraitObject(ref bounds, ..) => {
266 let mut any_lifetime_bounds = false;
267 for bound in bounds {
268 if let GenericBound::Outlives(ref lifetime) = *bound {
269 if any_lifetime_bounds {
270 span_err!(self.session, lifetime.ident.span, E0226,
271 "only a single explicit lifetime bound is permitted");
274 any_lifetime_bounds = true;
277 self.no_questions_in_bounds(bounds, "trait object types", false);
279 TyKind::ImplTrait(_, ref bounds) => {
281 .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
282 self.err_handler().span_err(ty.span, "at least one trait must be specified");
288 visit::walk_ty(self, ty)
291 fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
292 // Check if the path in this `use` is not generic, such as `use foo::bar<T>;` While this
293 // can't happen normally thanks to the parser, a generic might sneak in if the `use` is
294 // built using a macro.
297 // ($p:path) => { use $p; }
299 // foo!(bar::baz<T>);
300 use_tree.prefix.segments.iter().find(|segment| {
301 segment.args.is_some()
303 self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
304 "generic arguments in import path");
307 visit::walk_use_tree(self, use_tree, id);
310 fn visit_label(&mut self, label: &'a Label) {
311 self.check_label(label.ident);
312 visit::walk_label(self, label);
315 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
316 self.check_lifetime(lifetime.ident);
317 visit::walk_lifetime(self, lifetime);
320 fn visit_item(&mut self, item: &'a Item) {
322 ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
323 self.invalid_visibility(&item.vis, None);
324 if let TyKind::Err = ty.node {
326 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
327 .help("use `auto trait Trait {}` instead").emit();
329 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
330 span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
332 for impl_item in impl_items {
333 self.invalid_visibility(&impl_item.vis, None);
334 if let ImplItemKind::Method(ref sig, _) = impl_item.node {
335 self.check_trait_fn_not_const(sig.header.constness);
336 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness);
340 ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
341 self.invalid_visibility(&item.vis,
342 Some("place qualifiers on individual impl items instead"));
343 if unsafety == Unsafety::Unsafe {
344 span_err!(self.session, item.span, E0197, "inherent impls cannot be unsafe");
346 if polarity == ImplPolarity::Negative {
347 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
349 if defaultness == Defaultness::Default {
351 .struct_span_err(item.span, "inherent impls cannot be default")
352 .note("only trait implementations may be annotated with default").emit();
355 ItemKind::ForeignMod(..) => {
356 self.invalid_visibility(
358 Some("place qualifiers on individual foreign items instead"),
361 ItemKind::Enum(ref def, _) => {
362 for variant in &def.variants {
363 self.invalid_non_exhaustive_attribute(variant);
364 for field in variant.node.data.fields() {
365 self.invalid_visibility(&field.vis, None);
369 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
370 if is_auto == IsAuto::Yes {
371 // Auto traits cannot have generics, super traits nor contain items.
372 if !generics.params.is_empty() {
373 struct_span_err!(self.session, item.span, E0567,
374 "auto traits cannot have generic parameters").emit();
376 if !bounds.is_empty() {
377 struct_span_err!(self.session, item.span, E0568,
378 "auto traits cannot have super traits").emit();
380 if !trait_items.is_empty() {
381 struct_span_err!(self.session, item.span, E0380,
382 "auto traits cannot have methods or associated items").emit();
385 self.no_questions_in_bounds(bounds, "supertraits", true);
386 for trait_item in trait_items {
387 if let TraitItemKind::Method(ref sig, ref block) = trait_item.node {
388 self.check_trait_fn_not_async(trait_item.span, sig.header.asyncness);
389 self.check_trait_fn_not_const(sig.header.constness);
391 self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
393 self.session.buffer_lint(
394 lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
396 "patterns aren't allowed in methods without bodies");
398 struct_span_err!(self.session, span, E0642,
399 "patterns aren't allowed in methods without bodies").emit();
406 ItemKind::TraitAlias(Generics { ref params, .. }, ..) => {
407 for param in params {
409 GenericParamKind::Lifetime { .. } => {}
410 GenericParamKind::Type { ref default, .. } => {
411 if !param.bounds.is_empty() {
413 .span_err(param.ident.span, "type parameters on the left \
414 side of a trait alias cannot be bounded");
416 if !default.is_none() {
418 .span_err(param.ident.span, "type parameters on the left \
419 side of a trait alias cannot have defaults");
425 ItemKind::Mod(_) => {
426 // Ensure that `path` attributes on modules are recorded as used (c.f. #35584).
427 attr::first_attr_value_str_by_name(&item.attrs, "path");
428 if attr::contains_name(&item.attrs, "warn_directory_ownership") {
429 let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
430 let msg = "cannot declare a new module at this location";
431 self.session.buffer_lint(lint, item.id, item.span, msg);
434 ItemKind::Union(ref vdata, _) => {
435 if !vdata.is_struct() {
436 self.err_handler().span_err(item.span,
437 "tuple and unit unions are not permitted");
439 if vdata.fields().is_empty() {
440 self.err_handler().span_err(item.span,
441 "unions cannot have zero fields");
447 visit::walk_item(self, item)
450 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
452 ForeignItemKind::Fn(ref decl, _) => {
453 self.check_decl_no_pat(decl, |span, _| {
454 struct_span_err!(self.session, span, E0130,
455 "patterns aren't allowed in foreign function declarations")
456 .span_label(span, "pattern not allowed in foreign function").emit();
459 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
462 visit::walk_foreign_item(self, fi)
465 fn visit_vis(&mut self, vis: &'a Visibility) {
466 if let VisibilityKind::Restricted { ref path, .. } = vis.node {
467 path.segments.iter().find(|segment| segment.args.is_some()).map(|segment| {
468 self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
469 "generic arguments in visibility path");
473 visit::walk_vis(self, vis)
476 fn visit_generics(&mut self, generics: &'a Generics) {
477 let mut seen_non_lifetime_param = false;
478 let mut seen_default = None;
479 for param in &generics.params {
480 match (¶m.kind, seen_non_lifetime_param) {
481 (GenericParamKind::Lifetime { .. }, true) => {
483 .span_err(param.ident.span, "lifetime parameters must be leading");
485 (GenericParamKind::Lifetime { .. }, false) => {}
486 (GenericParamKind::Type { ref default, .. }, _) => {
487 seen_non_lifetime_param = true;
488 if default.is_some() {
489 seen_default = Some(param.ident.span);
490 } else if let Some(span) = seen_default {
492 .span_err(span, "type parameters with a default must be trailing");
498 for predicate in &generics.where_clause.predicates {
499 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
500 self.err_handler().span_err(predicate.span, "equality constraints are not yet \
501 supported in where clauses (#20041)");
504 visit::walk_generics(self, generics)
507 fn visit_generic_param(&mut self, param: &'a GenericParam) {
508 if let GenericParamKind::Lifetime { .. } = param.kind {
509 self.check_lifetime(param.ident);
511 visit::walk_generic_param(self, param);
514 fn visit_pat(&mut self, pat: &'a Pat) {
516 PatKind::Lit(ref expr) => {
517 self.check_expr_within_pat(expr, false);
519 PatKind::Range(ref start, ref end, _) => {
520 self.check_expr_within_pat(start, true);
521 self.check_expr_within_pat(end, true);
526 visit::walk_pat(self, pat)
529 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
530 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
531 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
532 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
534 visit::walk_where_predicate(self, p);
537 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
538 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
539 visit::walk_poly_trait_ref(self, t, m);
542 fn visit_mac(&mut self, mac: &Spanned<Mac_>) {
543 // when a new macro kind is added but the author forgets to set it up for expansion
544 // because that's the only part that won't cause a compiler error
545 self.session.diagnostic()
546 .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
547 the relevant `fold_*()` method in `PlaceholderExpander`?");
551 // Bans nested `impl Trait`, e.g. `impl Into<impl Debug>`.
552 // Nested `impl Trait` _is_ allowed in associated type position,
553 // e.g `impl Iterator<Item=impl Debug>`
554 struct NestedImplTraitVisitor<'a> {
555 session: &'a Session,
556 outer_impl_trait: Option<Span>,
559 impl<'a> NestedImplTraitVisitor<'a> {
560 fn with_impl_trait<F>(&mut self, outer_impl_trait: Option<Span>, f: F)
561 where F: FnOnce(&mut NestedImplTraitVisitor<'a>)
563 let old_outer_impl_trait = self.outer_impl_trait;
564 self.outer_impl_trait = outer_impl_trait;
566 self.outer_impl_trait = old_outer_impl_trait;
571 impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> {
572 fn visit_ty(&mut self, t: &'a Ty) {
573 if let TyKind::ImplTrait(..) = t.node {
574 if let Some(outer_impl_trait) = self.outer_impl_trait {
575 struct_span_err!(self.session, t.span, E0666,
576 "nested `impl Trait` is not allowed")
577 .span_label(outer_impl_trait, "outer `impl Trait`")
578 .span_label(t.span, "nested `impl Trait` here")
582 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t));
584 visit::walk_ty(self, t);
587 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
588 match *generic_args {
589 GenericArgs::AngleBracketed(ref data) => {
590 for arg in &data.args {
591 self.visit_generic_arg(arg)
593 for type_binding in &data.bindings {
594 // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
595 // are allowed to contain nested `impl Trait`.
596 self.with_impl_trait(None, |this| visit::walk_ty(this, &type_binding.ty));
599 GenericArgs::Parenthesized(ref data) => {
600 for type_ in &data.inputs {
601 self.visit_ty(type_);
603 if let Some(ref type_) = data.output {
604 // `-> Foo` syntax is essentially an associated type binding,
605 // so it is also allowed to contain nested `impl Trait`.
606 self.with_impl_trait(None, |this| visit::walk_ty(this, type_));
612 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
613 // covered in AstValidator
617 // Bans `impl Trait` in path projections like `<impl Iterator>::Item` or `Foo::Bar<impl Trait>`.
618 struct ImplTraitProjectionVisitor<'a> {
619 session: &'a Session,
623 impl<'a> ImplTraitProjectionVisitor<'a> {
624 fn with_ban<F>(&mut self, f: F)
625 where F: FnOnce(&mut ImplTraitProjectionVisitor<'a>)
627 let old_is_banned = self.is_banned;
628 self.is_banned = true;
630 self.is_banned = old_is_banned;
634 impl<'a> Visitor<'a> for ImplTraitProjectionVisitor<'a> {
635 fn visit_ty(&mut self, t: &'a Ty) {
637 TyKind::ImplTrait(..) => {
639 struct_span_err!(self.session, t.span, E0667,
640 "`impl Trait` is not allowed in path parameters").emit();
643 TyKind::Path(ref qself, ref path) => {
645 // - `Option<impl Trait>`
646 // - `option::Option<impl Trait>`
647 // - `option::Option<T>::Foo<impl Trait>
650 // - `<impl Trait>::Foo`
651 // - `option::Option<impl Trait>::Foo`.
653 // To implement this, we disallow `impl Trait` from `qself`
654 // (for cases like `<impl Trait>::Foo>`)
655 // but we allow `impl Trait` in `GenericArgs`
656 // iff there are no more PathSegments.
657 if let Some(ref qself) = *qself {
658 // `impl Trait` in `qself` is always illegal
659 self.with_ban(|this| this.visit_ty(&qself.ty));
662 for (i, segment) in path.segments.iter().enumerate() {
663 // Allow `impl Trait` iff we're on the final path segment
664 if i == path.segments.len() - 1 {
665 visit::walk_path_segment(self, path.span, segment);
668 visit::walk_path_segment(this, path.span, segment));
672 _ => visit::walk_ty(self, t),
676 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
677 // covered in AstValidator
681 pub fn check_crate(session: &Session, krate: &Crate) {
683 &mut NestedImplTraitVisitor {
685 outer_impl_trait: None,
689 &mut ImplTraitProjectionVisitor {
694 visit::walk_crate(&mut AstValidator { session: session }, krate)