1 // Validate AST before lowering it to HIR
3 // This pass is supposed to catch things that fit into AST data structures,
4 // but not permitted by the language. It runs after expansion when AST is frozen,
5 // so it can check for erroneous constructions produced by syntax extensions.
6 // This pass is supposed to perform only simple checks not requiring name resolution
7 // or type checking or some other kind of complex analysis.
10 use rustc::session::Session;
13 use syntax::source_map::Spanned;
14 use syntax::symbol::keywords;
16 use syntax::visit::{self, Visitor};
19 use errors::Applicability;
21 struct AstValidator<'a> {
25 impl<'a> AstValidator<'a> {
26 fn err_handler(&self) -> &errors::Handler {
27 &self.session.diagnostic()
30 fn check_lifetime(&self, ident: Ident) {
31 let valid_names = [keywords::UnderscoreLifetime.name(),
32 keywords::StaticLifetime.name(),
33 keywords::Invalid.name()];
34 if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
35 self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
39 fn check_label(&self, ident: Ident) {
40 if ident.without_first_quote().is_reserved() {
42 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
46 fn invalid_non_exhaustive_attribute(&self, variant: &Variant) {
47 let has_non_exhaustive = attr::contains_name(&variant.node.attrs, "non_exhaustive");
48 if has_non_exhaustive {
49 self.err_handler().span_err(variant.span,
50 "#[non_exhaustive] is not yet supported on variants");
54 fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
55 if let VisibilityKind::Inherited = vis.node {
59 let mut err = struct_span_err!(self.session,
62 "unnecessary visibility qualifier");
63 if vis.node.is_pub() {
64 err.span_label(vis.span, "`pub` not permitted here because it's implied");
66 if let Some(note) = note {
72 fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
73 for arg in &decl.inputs {
75 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
77 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
78 report_err(arg.pat.span, true),
79 _ => report_err(arg.pat.span, false),
84 fn check_trait_fn_not_async(&self, span: Span, asyncness: IsAsync) {
85 if asyncness.is_async() {
86 struct_span_err!(self.session, span, E0706,
87 "trait fns cannot be declared `async`").emit()
91 fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
92 if constness.node == Constness::Const {
93 struct_span_err!(self.session, constness.span, E0379,
94 "trait fns cannot be declared const")
95 .span_label(constness.span, "trait fns cannot be const")
100 fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
101 for bound in bounds {
102 if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
103 let mut err = self.err_handler().struct_span_err(poly.span,
104 &format!("`?Trait` is not permitted in {}", where_));
106 err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
113 /// matches '-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus),
114 /// or path for ranges.
116 /// FIXME: do we want to allow expr -> pattern conversion to create path expressions?
117 /// That means making this work:
119 /// ```rust,ignore (FIXME)
128 fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
130 ExprKind::Lit(..) => {}
131 ExprKind::Path(..) if allow_paths => {}
132 ExprKind::Unary(UnOp::Neg, ref inner)
133 if match inner.node { ExprKind::Lit(_) => true, _ => false } => {}
134 _ => self.err_handler().span_err(expr.span, "arbitrary expressions aren't allowed \
139 fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
140 // Check only lifetime parameters are present and that the lifetime
141 // parameters that are present have no bounds.
142 let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind {
143 GenericParamKind::Lifetime { .. } => {
144 if !param.bounds.is_empty() {
145 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
147 .span_err(spans, "lifetime bounds cannot be used in this context");
151 _ => Some(param.ident.span),
153 if !non_lt_param_spans.is_empty() {
154 self.err_handler().span_err(non_lt_param_spans,
155 "only lifetime parameters can be used in this context");
159 /// With eRFC 2497, we need to check whether an expression is ambiguous and warn or error
160 /// depending on the edition, this function handles that.
161 fn while_if_let_ambiguity(&self, expr: &P<Expr>) {
162 if let Some((span, op_kind)) = self.while_if_let_expr_ambiguity(&expr) {
163 let mut err = self.err_handler().struct_span_err(
164 span, &format!("ambiguous use of `{}`", op_kind.to_string())
168 "this will be a error until the `let_chains` feature is stabilized"
171 "see rust-lang/rust#53668 for more information"
174 if let Ok(snippet) = self.session.source_map().span_to_snippet(span) {
175 err.span_suggestion_with_applicability(
176 span, "consider adding parentheses", format!("({})", snippet),
177 Applicability::MachineApplicable,
185 /// With eRFC 2497 adding if-let chains, there is a requirement that the parsing of
186 /// `&&` and `||` in a if-let statement be unambiguous. This function returns a span and
187 /// a `BinOpKind` (either `&&` or `||` depending on what was ambiguous) if it is determined
188 /// that the current expression parsed is ambiguous and will break in future.
189 fn while_if_let_expr_ambiguity(&self, expr: &P<Expr>) -> Option<(Span, BinOpKind)> {
190 debug!("while_if_let_expr_ambiguity: expr.node: {:?}", expr.node);
192 ExprKind::Binary(op, _, _) if op.node == BinOpKind::And || op.node == BinOpKind::Or => {
193 Some((expr.span, op.node))
195 ExprKind::Range(ref lhs, ref rhs, _) => {
196 let lhs_ambiguous = lhs.as_ref()
197 .and_then(|lhs| self.while_if_let_expr_ambiguity(lhs));
198 let rhs_ambiguous = rhs.as_ref()
199 .and_then(|rhs| self.while_if_let_expr_ambiguity(rhs));
201 lhs_ambiguous.or(rhs_ambiguous)
209 impl<'a> Visitor<'a> for AstValidator<'a> {
210 fn visit_expr(&mut self, expr: &'a Expr) {
212 ExprKind::IfLet(_, ref expr, _, _) | ExprKind::WhileLet(_, ref expr, _, _) =>
213 self.while_if_let_ambiguity(&expr),
214 ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
215 span_err!(self.session, expr.span, E0472, "asm! is unsupported on this target");
217 ExprKind::ObsoleteInPlace(ref place, ref val) => {
218 let mut err = self.err_handler().struct_span_err(
220 "emplacement syntax is obsolete (for now, anyway)",
223 "for more information, see \
224 <https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"
227 ExprKind::Lit(ref v) if v.node.is_numeric() => {
228 err.span_suggestion_with_applicability(
229 place.span.between(val.span),
230 "if you meant to write a comparison against a negative value, add a \
231 space in between `<` and `-`",
233 Applicability::MaybeIncorrect
243 visit::walk_expr(self, expr)
246 fn visit_ty(&mut self, ty: &'a Ty) {
248 TyKind::BareFn(ref bfty) => {
249 self.check_decl_no_pat(&bfty.decl, |span, _| {
250 struct_span_err!(self.session, span, E0561,
251 "patterns aren't allowed in function pointer types").emit();
253 self.check_late_bound_lifetime_defs(&bfty.generic_params);
255 TyKind::TraitObject(ref bounds, ..) => {
256 let mut any_lifetime_bounds = false;
257 for bound in bounds {
258 if let GenericBound::Outlives(ref lifetime) = *bound {
259 if any_lifetime_bounds {
260 span_err!(self.session, lifetime.ident.span, E0226,
261 "only a single explicit lifetime bound is permitted");
264 any_lifetime_bounds = true;
267 self.no_questions_in_bounds(bounds, "trait object types", false);
269 TyKind::ImplTrait(_, ref bounds) => {
271 .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
272 self.err_handler().span_err(ty.span, "at least one trait must be specified");
278 visit::walk_ty(self, ty)
281 fn visit_use_tree(&mut self, use_tree: &'a UseTree, id: NodeId, _nested: bool) {
282 // Check if the path in this `use` is not generic, such as `use foo::bar<T>;` While this
283 // can't happen normally thanks to the parser, a generic might sneak in if the `use` is
284 // built using a macro.
287 // ($p:path) => { use $p; }
289 // foo!(bar::baz<T>);
290 use_tree.prefix.segments.iter().find(|segment| {
291 segment.args.is_some()
293 self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
294 "generic arguments in import path");
297 visit::walk_use_tree(self, use_tree, id);
300 fn visit_label(&mut self, label: &'a Label) {
301 self.check_label(label.ident);
302 visit::walk_label(self, label);
305 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
306 self.check_lifetime(lifetime.ident);
307 visit::walk_lifetime(self, lifetime);
310 fn visit_item(&mut self, item: &'a Item) {
312 ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
313 self.invalid_visibility(&item.vis, None);
314 if let TyKind::Err = ty.node {
316 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
317 .help("use `auto trait Trait {}` instead").emit();
319 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
320 span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
322 for impl_item in impl_items {
323 self.invalid_visibility(&impl_item.vis, None);
324 if let ImplItemKind::Method(ref sig, _) = impl_item.node {
325 self.check_trait_fn_not_const(sig.header.constness);
326 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness);
330 ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
331 self.invalid_visibility(&item.vis,
332 Some("place qualifiers on individual impl items instead"));
333 if unsafety == Unsafety::Unsafe {
334 span_err!(self.session, item.span, E0197, "inherent impls cannot be unsafe");
336 if polarity == ImplPolarity::Negative {
337 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
339 if defaultness == Defaultness::Default {
341 .struct_span_err(item.span, "inherent impls cannot be default")
342 .note("only trait implementations may be annotated with default").emit();
345 ItemKind::ForeignMod(..) => {
346 self.invalid_visibility(
348 Some("place qualifiers on individual foreign items instead"),
351 ItemKind::Enum(ref def, _) => {
352 for variant in &def.variants {
353 self.invalid_non_exhaustive_attribute(variant);
354 for field in variant.node.data.fields() {
355 self.invalid_visibility(&field.vis, None);
359 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
360 if is_auto == IsAuto::Yes {
361 // Auto traits cannot have generics, super traits nor contain items.
362 if !generics.params.is_empty() {
363 struct_span_err!(self.session, item.span, E0567,
364 "auto traits cannot have generic parameters").emit();
366 if !bounds.is_empty() {
367 struct_span_err!(self.session, item.span, E0568,
368 "auto traits cannot have super traits").emit();
370 if !trait_items.is_empty() {
371 struct_span_err!(self.session, item.span, E0380,
372 "auto traits cannot have methods or associated items").emit();
375 self.no_questions_in_bounds(bounds, "supertraits", true);
376 for trait_item in trait_items {
377 if let TraitItemKind::Method(ref sig, ref block) = trait_item.node {
378 self.check_trait_fn_not_async(trait_item.span, sig.header.asyncness);
379 self.check_trait_fn_not_const(sig.header.constness);
381 self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
383 self.session.buffer_lint(
384 lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
386 "patterns aren't allowed in methods without bodies");
388 struct_span_err!(self.session, span, E0642,
389 "patterns aren't allowed in methods without bodies").emit();
396 ItemKind::Mod(_) => {
397 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
398 attr::first_attr_value_str_by_name(&item.attrs, "path");
399 if attr::contains_name(&item.attrs, "warn_directory_ownership") {
400 let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
401 let msg = "cannot declare a new module at this location";
402 self.session.buffer_lint(lint, item.id, item.span, msg);
405 ItemKind::Union(ref vdata, _) => {
406 if !vdata.is_struct() {
407 self.err_handler().span_err(item.span,
408 "tuple and unit unions are not permitted");
410 if vdata.fields().is_empty() {
411 self.err_handler().span_err(item.span,
412 "unions cannot have zero fields");
418 visit::walk_item(self, item)
421 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
423 ForeignItemKind::Fn(ref decl, _) => {
424 self.check_decl_no_pat(decl, |span, _| {
425 struct_span_err!(self.session, span, E0130,
426 "patterns aren't allowed in foreign function declarations")
427 .span_label(span, "pattern not allowed in foreign function").emit();
430 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
433 visit::walk_foreign_item(self, fi)
436 fn visit_vis(&mut self, vis: &'a Visibility) {
437 if let VisibilityKind::Restricted { ref path, .. } = vis.node {
438 path.segments.iter().find(|segment| segment.args.is_some()).map(|segment| {
439 self.err_handler().span_err(segment.args.as_ref().unwrap().span(),
440 "generic arguments in visibility path");
444 visit::walk_vis(self, vis)
447 fn visit_generics(&mut self, generics: &'a Generics) {
448 let mut seen_non_lifetime_param = false;
449 let mut seen_default = None;
450 for param in &generics.params {
451 match (¶m.kind, seen_non_lifetime_param) {
452 (GenericParamKind::Lifetime { .. }, true) => {
454 .span_err(param.ident.span, "lifetime parameters must be leading");
456 (GenericParamKind::Lifetime { .. }, false) => {}
457 (GenericParamKind::Type { ref default, .. }, _) => {
458 seen_non_lifetime_param = true;
459 if default.is_some() {
460 seen_default = Some(param.ident.span);
461 } else if let Some(span) = seen_default {
463 .span_err(span, "type parameters with a default must be trailing");
469 for predicate in &generics.where_clause.predicates {
470 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
471 self.err_handler().span_err(predicate.span, "equality constraints are not yet \
472 supported in where clauses (#20041)");
475 visit::walk_generics(self, generics)
478 fn visit_generic_param(&mut self, param: &'a GenericParam) {
479 if let GenericParamKind::Lifetime { .. } = param.kind {
480 self.check_lifetime(param.ident);
482 visit::walk_generic_param(self, param);
485 fn visit_pat(&mut self, pat: &'a Pat) {
487 PatKind::Lit(ref expr) => {
488 self.check_expr_within_pat(expr, false);
490 PatKind::Range(ref start, ref end, _) => {
491 self.check_expr_within_pat(start, true);
492 self.check_expr_within_pat(end, true);
497 visit::walk_pat(self, pat)
500 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
501 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
502 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
503 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
505 visit::walk_where_predicate(self, p);
508 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
509 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
510 visit::walk_poly_trait_ref(self, t, m);
513 fn visit_mac(&mut self, mac: &Spanned<Mac_>) {
514 // when a new macro kind is added but the author forgets to set it up for expansion
515 // because that's the only part that won't cause a compiler error
516 self.session.diagnostic()
517 .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
518 the relevant `fold_*()` method in `PlaceholderExpander`?");
522 // Bans nested `impl Trait`, e.g., `impl Into<impl Debug>`.
523 // Nested `impl Trait` _is_ allowed in associated type position,
524 // e.g `impl Iterator<Item=impl Debug>`
525 struct NestedImplTraitVisitor<'a> {
526 session: &'a Session,
527 outer_impl_trait: Option<Span>,
530 impl<'a> NestedImplTraitVisitor<'a> {
531 fn with_impl_trait<F>(&mut self, outer_impl_trait: Option<Span>, f: F)
532 where F: FnOnce(&mut NestedImplTraitVisitor<'a>)
534 let old_outer_impl_trait = self.outer_impl_trait;
535 self.outer_impl_trait = outer_impl_trait;
537 self.outer_impl_trait = old_outer_impl_trait;
542 impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> {
543 fn visit_ty(&mut self, t: &'a Ty) {
544 if let TyKind::ImplTrait(..) = t.node {
545 if let Some(outer_impl_trait) = self.outer_impl_trait {
546 struct_span_err!(self.session, t.span, E0666,
547 "nested `impl Trait` is not allowed")
548 .span_label(outer_impl_trait, "outer `impl Trait`")
549 .span_label(t.span, "nested `impl Trait` here")
553 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t));
555 visit::walk_ty(self, t);
558 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
559 match *generic_args {
560 GenericArgs::AngleBracketed(ref data) => {
561 for arg in &data.args {
562 self.visit_generic_arg(arg)
564 for type_binding in &data.bindings {
565 // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
566 // are allowed to contain nested `impl Trait`.
567 self.with_impl_trait(None, |this| visit::walk_ty(this, &type_binding.ty));
570 GenericArgs::Parenthesized(ref data) => {
571 for type_ in &data.inputs {
572 self.visit_ty(type_);
574 if let Some(ref type_) = data.output {
575 // `-> Foo` syntax is essentially an associated type binding,
576 // so it is also allowed to contain nested `impl Trait`.
577 self.with_impl_trait(None, |this| visit::walk_ty(this, type_));
583 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
584 // covered in AstValidator
588 // Bans `impl Trait` in path projections like `<impl Iterator>::Item` or `Foo::Bar<impl Trait>`.
589 struct ImplTraitProjectionVisitor<'a> {
590 session: &'a Session,
594 impl<'a> ImplTraitProjectionVisitor<'a> {
595 fn with_ban<F>(&mut self, f: F)
596 where F: FnOnce(&mut ImplTraitProjectionVisitor<'a>)
598 let old_is_banned = self.is_banned;
599 self.is_banned = true;
601 self.is_banned = old_is_banned;
605 impl<'a> Visitor<'a> for ImplTraitProjectionVisitor<'a> {
606 fn visit_ty(&mut self, t: &'a Ty) {
608 TyKind::ImplTrait(..) => {
610 struct_span_err!(self.session, t.span, E0667,
611 "`impl Trait` is not allowed in path parameters").emit();
614 TyKind::Path(ref qself, ref path) => {
616 // - `Option<impl Trait>`
617 // - `option::Option<impl Trait>`
618 // - `option::Option<T>::Foo<impl Trait>
621 // - `<impl Trait>::Foo`
622 // - `option::Option<impl Trait>::Foo`.
624 // To implement this, we disallow `impl Trait` from `qself`
625 // (for cases like `<impl Trait>::Foo>`)
626 // but we allow `impl Trait` in `GenericArgs`
627 // iff there are no more PathSegments.
628 if let Some(ref qself) = *qself {
629 // `impl Trait` in `qself` is always illegal
630 self.with_ban(|this| this.visit_ty(&qself.ty));
633 for (i, segment) in path.segments.iter().enumerate() {
634 // Allow `impl Trait` iff we're on the final path segment
635 if i == path.segments.len() - 1 {
636 visit::walk_path_segment(self, path.span, segment);
639 visit::walk_path_segment(this, path.span, segment));
643 _ => visit::walk_ty(self, t),
647 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
648 // covered in AstValidator
652 pub fn check_crate(session: &Session, krate: &Crate) {
654 &mut NestedImplTraitVisitor {
656 outer_impl_trait: None,
660 &mut ImplTraitProjectionVisitor {
665 visit::walk_crate(&mut AstValidator { session }, krate)