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 ambiguous 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!("ambiguous 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 unambiguous. This function returns a span and
197 /// a `BinOpKind` (either `&&` or `||` depending on what was ambiguous) if it is determined
198 /// that the current expression parsed is ambiguous 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_ambiguous = lhs.as_ref()
207 .and_then(|lhs| self.while_if_let_expr_ambiguity(lhs));
208 let rhs_ambiguous = rhs.as_ref()
209 .and_then(|rhs| self.while_if_let_expr_ambiguity(rhs));
211 lhs_ambiguous.or(rhs_ambiguous)
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::Mod(_) => {
407 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
408 attr::first_attr_value_str_by_name(&item.attrs, "path");
409 if attr::contains_name(&item.attrs, "warn_directory_ownership") {
410 let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
411 let msg = "cannot declare a new module at this location";
412 self.session.buffer_lint(lint, item.id, item.span, msg);
415 ItemKind::Union(ref vdata, _) => {
416 if !vdata.is_struct() {
417 self.err_handler().span_err(item.span,
418 "tuple and unit unions are not permitted");
420 if vdata.fields().is_empty() {
421 self.err_handler().span_err(item.span,
422 "unions cannot have zero fields");
428 visit::walk_item(self, item)
431 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
433 ForeignItemKind::Fn(ref decl, _) => {
434 self.check_decl_no_pat(decl, |span, _| {
435 struct_span_err!(self.session, span, E0130,
436 "patterns aren't allowed in foreign function declarations")
437 .span_label(span, "pattern not allowed in foreign function").emit();
440 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
443 visit::walk_foreign_item(self, fi)
446 fn visit_vis(&mut self, vis: &'a Visibility) {
447 if let VisibilityKind::Restricted { ref path, .. } = vis.node {
448 path.segments.iter().find(|segment| segment.args.is_some()).map(|segment| {
449 self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
450 "generic arguments in visibility path");
454 visit::walk_vis(self, vis)
457 fn visit_generics(&mut self, generics: &'a Generics) {
458 let mut seen_non_lifetime_param = false;
459 let mut seen_default = None;
460 for param in &generics.params {
461 match (¶m.kind, seen_non_lifetime_param) {
462 (GenericParamKind::Lifetime { .. }, true) => {
464 .span_err(param.ident.span, "lifetime parameters must be leading");
466 (GenericParamKind::Lifetime { .. }, false) => {}
467 (GenericParamKind::Type { ref default, .. }, _) => {
468 seen_non_lifetime_param = true;
469 if default.is_some() {
470 seen_default = Some(param.ident.span);
471 } else if let Some(span) = seen_default {
473 .span_err(span, "type parameters with a default must be trailing");
479 for predicate in &generics.where_clause.predicates {
480 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
481 self.err_handler().span_err(predicate.span, "equality constraints are not yet \
482 supported in where clauses (#20041)");
485 visit::walk_generics(self, generics)
488 fn visit_generic_param(&mut self, param: &'a GenericParam) {
489 if let GenericParamKind::Lifetime { .. } = param.kind {
490 self.check_lifetime(param.ident);
492 visit::walk_generic_param(self, param);
495 fn visit_pat(&mut self, pat: &'a Pat) {
497 PatKind::Lit(ref expr) => {
498 self.check_expr_within_pat(expr, false);
500 PatKind::Range(ref start, ref end, _) => {
501 self.check_expr_within_pat(start, true);
502 self.check_expr_within_pat(end, true);
507 visit::walk_pat(self, pat)
510 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
511 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
512 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
513 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
515 visit::walk_where_predicate(self, p);
518 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
519 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
520 visit::walk_poly_trait_ref(self, t, m);
523 fn visit_mac(&mut self, mac: &Spanned<Mac_>) {
524 // when a new macro kind is added but the author forgets to set it up for expansion
525 // because that's the only part that won't cause a compiler error
526 self.session.diagnostic()
527 .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
528 the relevant `fold_*()` method in `PlaceholderExpander`?");
532 // Bans nested `impl Trait`, e.g., `impl Into<impl Debug>`.
533 // Nested `impl Trait` _is_ allowed in associated type position,
534 // e.g `impl Iterator<Item=impl Debug>`
535 struct NestedImplTraitVisitor<'a> {
536 session: &'a Session,
537 outer_impl_trait: Option<Span>,
540 impl<'a> NestedImplTraitVisitor<'a> {
541 fn with_impl_trait<F>(&mut self, outer_impl_trait: Option<Span>, f: F)
542 where F: FnOnce(&mut NestedImplTraitVisitor<'a>)
544 let old_outer_impl_trait = self.outer_impl_trait;
545 self.outer_impl_trait = outer_impl_trait;
547 self.outer_impl_trait = old_outer_impl_trait;
552 impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> {
553 fn visit_ty(&mut self, t: &'a Ty) {
554 if let TyKind::ImplTrait(..) = t.node {
555 if let Some(outer_impl_trait) = self.outer_impl_trait {
556 struct_span_err!(self.session, t.span, E0666,
557 "nested `impl Trait` is not allowed")
558 .span_label(outer_impl_trait, "outer `impl Trait`")
559 .span_label(t.span, "nested `impl Trait` here")
563 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t));
565 visit::walk_ty(self, t);
568 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
569 match *generic_args {
570 GenericArgs::AngleBracketed(ref data) => {
571 for arg in &data.args {
572 self.visit_generic_arg(arg)
574 for type_binding in &data.bindings {
575 // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
576 // are allowed to contain nested `impl Trait`.
577 self.with_impl_trait(None, |this| visit::walk_ty(this, &type_binding.ty));
580 GenericArgs::Parenthesized(ref data) => {
581 for type_ in &data.inputs {
582 self.visit_ty(type_);
584 if let Some(ref type_) = data.output {
585 // `-> Foo` syntax is essentially an associated type binding,
586 // so it is also allowed to contain nested `impl Trait`.
587 self.with_impl_trait(None, |this| visit::walk_ty(this, type_));
593 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
594 // covered in AstValidator
598 // Bans `impl Trait` in path projections like `<impl Iterator>::Item` or `Foo::Bar<impl Trait>`.
599 struct ImplTraitProjectionVisitor<'a> {
600 session: &'a Session,
604 impl<'a> ImplTraitProjectionVisitor<'a> {
605 fn with_ban<F>(&mut self, f: F)
606 where F: FnOnce(&mut ImplTraitProjectionVisitor<'a>)
608 let old_is_banned = self.is_banned;
609 self.is_banned = true;
611 self.is_banned = old_is_banned;
615 impl<'a> Visitor<'a> for ImplTraitProjectionVisitor<'a> {
616 fn visit_ty(&mut self, t: &'a Ty) {
618 TyKind::ImplTrait(..) => {
620 struct_span_err!(self.session, t.span, E0667,
621 "`impl Trait` is not allowed in path parameters").emit();
624 TyKind::Path(ref qself, ref path) => {
626 // - `Option<impl Trait>`
627 // - `option::Option<impl Trait>`
628 // - `option::Option<T>::Foo<impl Trait>
631 // - `<impl Trait>::Foo`
632 // - `option::Option<impl Trait>::Foo`.
634 // To implement this, we disallow `impl Trait` from `qself`
635 // (for cases like `<impl Trait>::Foo>`)
636 // but we allow `impl Trait` in `GenericArgs`
637 // iff there are no more PathSegments.
638 if let Some(ref qself) = *qself {
639 // `impl Trait` in `qself` is always illegal
640 self.with_ban(|this| this.visit_ty(&qself.ty));
643 for (i, segment) in path.segments.iter().enumerate() {
644 // Allow `impl Trait` iff we're on the final path segment
645 if i == path.segments.len() - 1 {
646 visit::walk_path_segment(self, path.span, segment);
649 visit::walk_path_segment(this, path.span, segment));
653 _ => visit::walk_ty(self, t),
657 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
658 // covered in AstValidator
662 pub fn check_crate(session: &Session, krate: &Crate) {
664 &mut NestedImplTraitVisitor {
666 outer_impl_trait: None,
670 &mut ImplTraitProjectionVisitor {
675 visit::walk_crate(&mut AstValidator { session }, krate)