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.
11 use rustc::session::Session;
12 use rustc_data_structures::fx::FxHashMap;
13 use rustc_parse::validate_attr;
16 use syntax::expand::is_proc_macro_attr;
17 use syntax::feature_gate::is_builtin_attr;
18 use syntax::print::pprust;
19 use syntax::source_map::Spanned;
20 use syntax::symbol::{kw, sym};
21 use syntax::visit::{self, Visitor};
22 use syntax::{span_err, struct_span_err, walk_list};
24 use errors::{Applicability, FatalError};
26 use rustc_error_codes::*;
28 struct AstValidator<'a> {
30 has_proc_macro_decls: bool,
32 /// Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
33 /// Nested `impl Trait` _is_ allowed in associated type position,
34 /// e.g., `impl Iterator<Item = impl Debug>`.
35 outer_impl_trait: Option<Span>,
37 /// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
38 /// or `Foo::Bar<impl Trait>`
39 is_impl_trait_banned: bool,
41 /// Used to ban associated type bounds (i.e., `Type<AssocType: Bounds>`) in
42 /// certain positions.
43 is_assoc_ty_bound_banned: bool,
45 lint_buffer: &'a mut lint::LintBuffer,
48 impl<'a> AstValidator<'a> {
49 fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
50 let old = mem::replace(&mut self.is_impl_trait_banned, true);
52 self.is_impl_trait_banned = old;
55 fn with_banned_assoc_ty_bound(&mut self, f: impl FnOnce(&mut Self)) {
56 let old = mem::replace(&mut self.is_assoc_ty_bound_banned, true);
58 self.is_assoc_ty_bound_banned = old;
61 fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
62 let old = mem::replace(&mut self.outer_impl_trait, outer);
64 self.outer_impl_trait = old;
67 fn visit_assoc_ty_constraint_from_generic_args(&mut self, constraint: &'a AssocTyConstraint) {
68 match constraint.kind {
69 AssocTyConstraintKind::Equality { .. } => {}
70 AssocTyConstraintKind::Bound { .. } => {
71 if self.is_assoc_ty_bound_banned {
72 self.err_handler().span_err(constraint.span,
73 "associated type bounds are not allowed within structs, enums, or unions"
78 self.visit_assoc_ty_constraint(constraint);
81 // Mirrors `visit::walk_ty`, but tracks relevant state.
82 fn walk_ty(&mut self, t: &'a Ty) {
84 TyKind::ImplTrait(..) => {
85 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
87 TyKind::Path(ref qself, ref path) => {
89 // - `Option<impl Trait>`
90 // - `option::Option<impl Trait>`
91 // - `option::Option<T>::Foo<impl Trait>
94 // - `<impl Trait>::Foo`
95 // - `option::Option<impl Trait>::Foo`.
97 // To implement this, we disallow `impl Trait` from `qself`
98 // (for cases like `<impl Trait>::Foo>`)
99 // but we allow `impl Trait` in `GenericArgs`
100 // iff there are no more PathSegments.
101 if let Some(ref qself) = *qself {
102 // `impl Trait` in `qself` is always illegal
103 self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
106 // Note that there should be a call to visit_path here,
107 // so if any logic is added to process `Path`s a call to it should be
108 // added both in visit_path and here. This code mirrors visit::walk_path.
109 for (i, segment) in path.segments.iter().enumerate() {
110 // Allow `impl Trait` iff we're on the final path segment
111 if i == path.segments.len() - 1 {
112 self.visit_path_segment(path.span, segment);
114 self.with_banned_impl_trait(|this| {
115 this.visit_path_segment(path.span, segment)
120 _ => visit::walk_ty(self, t),
124 fn err_handler(&self) -> &errors::Handler {
125 &self.session.diagnostic()
128 fn check_lifetime(&self, ident: Ident) {
129 let valid_names = [kw::UnderscoreLifetime,
132 if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
133 self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
137 fn check_label(&self, ident: Ident) {
138 if ident.without_first_quote().is_reserved() {
140 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
144 fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
145 if let VisibilityKind::Inherited = vis.node {
149 let mut err = struct_span_err!(self.session,
152 "unnecessary visibility qualifier");
153 if vis.node.is_pub() {
154 err.span_label(vis.span, "`pub` not permitted here because it's implied");
156 if let Some(note) = note {
162 fn check_decl_no_pat<F: FnMut(Span, bool)>(decl: &FnDecl, mut report_err: F) {
163 for arg in &decl.inputs {
165 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
167 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
168 report_err(arg.pat.span, true),
169 _ => report_err(arg.pat.span, false),
174 fn check_trait_fn_not_async(&self, span: Span, asyncness: IsAsync) {
175 if asyncness.is_async() {
176 struct_span_err!(self.session, span, E0706, "trait fns cannot be declared `async`")
177 .note("`async` trait functions are not currently supported")
178 .note("consider using the `async-trait` crate: \
179 https://crates.io/crates/async-trait")
184 fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
185 if constness.node == Constness::Const {
186 struct_span_err!(self.session, constness.span, E0379,
187 "trait fns cannot be declared const")
188 .span_label(constness.span, "trait fns cannot be const")
193 fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
194 for bound in bounds {
195 if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
196 let mut err = self.err_handler().struct_span_err(poly.span,
197 &format!("`?Trait` is not permitted in {}", where_));
199 let path_str = pprust::path_to_string(&poly.trait_ref.path);
200 err.note(&format!("traits are `?{}` by default", path_str));
207 /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
208 /// or paths for ranges.
210 // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
211 // That means making this work:
213 // ```rust,ignore (FIXME)
222 fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
224 ExprKind::Lit(..) | ExprKind::Err => {}
225 ExprKind::Path(..) if allow_paths => {}
226 ExprKind::Unary(UnOp::Neg, ref inner)
227 if match inner.kind { ExprKind::Lit(_) => true, _ => false } => {}
228 _ => self.err_handler().span_err(expr.span, "arbitrary expressions aren't allowed \
233 fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
234 // Check only lifetime parameters are present and that the lifetime
235 // parameters that are present have no bounds.
236 let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind {
237 GenericParamKind::Lifetime { .. } => {
238 if !param.bounds.is_empty() {
239 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
241 .span_err(spans, "lifetime bounds cannot be used in this context");
245 _ => Some(param.ident.span),
247 if !non_lt_param_spans.is_empty() {
248 self.err_handler().span_err(non_lt_param_spans,
249 "only lifetime parameters can be used in this context");
253 fn check_fn_decl(&self, fn_decl: &FnDecl) {
257 .flat_map(|i| i.attrs.as_ref())
259 let arr = [sym::allow, sym::cfg, sym::cfg_attr, sym::deny, sym::forbid, sym::warn];
260 !arr.contains(&attr.name_or_empty()) && is_builtin_attr(attr)
262 .for_each(|attr| if attr.is_doc_comment() {
263 let mut err = self.err_handler().struct_span_err(
265 "documentation comments cannot be applied to function parameters"
267 err.span_label(attr.span, "doc comments are not allowed here");
271 self.err_handler().span_err(attr.span, "allow, cfg, cfg_attr, deny, \
272 forbid, and warn are the only allowed built-in attributes in function parameters")
277 enum GenericPosition {
282 fn validate_generics_order<'a>(
284 handler: &errors::Handler,
285 generics: impl Iterator<
288 Option<&'a [GenericBound]>,
293 pos: GenericPosition,
296 let mut max_param: Option<ParamKindOrd> = None;
297 let mut out_of_order = FxHashMap::default();
298 let mut param_idents = vec![];
299 let mut found_type = false;
300 let mut found_const = false;
302 for (kind, bounds, span, ident) in generics {
303 if let Some(ident) = ident {
304 param_idents.push((kind, bounds, param_idents.len(), ident));
306 let max_param = &mut max_param;
308 Some(max_param) if *max_param > kind => {
309 let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
312 Some(_) | None => *max_param = Some(kind),
315 ParamKindOrd::Type => found_type = true,
316 ParamKindOrd::Const => found_const = true,
321 let mut ordered_params = "<".to_string();
322 if !out_of_order.is_empty() {
323 param_idents.sort_by_key(|&(po, _, i, _)| (po, i));
324 let mut first = true;
325 for (_, bounds, _, ident) in param_idents {
327 ordered_params += ", ";
329 ordered_params += &ident;
330 if let Some(bounds) = bounds {
331 if !bounds.is_empty() {
332 ordered_params += ": ";
333 ordered_params += &pprust::bounds_to_string(&bounds);
339 ordered_params += ">";
341 let pos_str = match pos {
342 GenericPosition::Param => "parameter",
343 GenericPosition::Arg => "argument",
346 for (param_ord, (max_param, spans)) in &out_of_order {
347 let mut err = handler.struct_span_err(spans.clone(),
349 "{} {pos}s must be declared prior to {} {pos}s",
354 if let GenericPosition::Param = pos {
358 "reorder the {}s: lifetimes, then types{}",
360 if sess.features_untracked().const_generics { ", then consts" } else { "" },
362 ordered_params.clone(),
363 Applicability::MachineApplicable,
369 // FIXME(const_generics): we shouldn't have to abort here at all, but we currently get ICEs
370 // if we don't. Const parameters and type parameters can currently conflict if they
372 if !out_of_order.is_empty() && found_type && found_const {
377 impl<'a> Visitor<'a> for AstValidator<'a> {
378 fn visit_attribute(&mut self, attr: &Attribute) {
379 validate_attr::check_meta(&self.session.parse_sess, attr);
382 fn visit_expr(&mut self, expr: &'a Expr) {
384 ExprKind::Closure(_, _, _, fn_decl, _, _) => {
385 self.check_fn_decl(fn_decl);
387 ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
388 span_err!(self.session, expr.span, E0472, "asm! is unsupported on this target");
393 visit::walk_expr(self, expr);
396 fn visit_ty(&mut self, ty: &'a Ty) {
398 TyKind::BareFn(ref bfty) => {
399 self.check_fn_decl(&bfty.decl);
400 Self::check_decl_no_pat(&bfty.decl, |span, _| {
401 struct_span_err!(self.session, span, E0561,
402 "patterns aren't allowed in function pointer types").emit();
404 self.check_late_bound_lifetime_defs(&bfty.generic_params);
406 TyKind::TraitObject(ref bounds, ..) => {
407 let mut any_lifetime_bounds = false;
408 for bound in bounds {
409 if let GenericBound::Outlives(ref lifetime) = *bound {
410 if any_lifetime_bounds {
411 span_err!(self.session, lifetime.ident.span, E0226,
412 "only a single explicit lifetime bound is permitted");
415 any_lifetime_bounds = true;
418 self.no_questions_in_bounds(bounds, "trait object types", false);
420 TyKind::ImplTrait(_, ref bounds) => {
421 if self.is_impl_trait_banned {
423 self.session, ty.span, E0667,
424 "`impl Trait` is not allowed in path parameters"
429 if let Some(outer_impl_trait_sp) = self.outer_impl_trait {
431 self.session, ty.span, E0666,
432 "nested `impl Trait` is not allowed"
434 .span_label(outer_impl_trait_sp, "outer `impl Trait`")
435 .span_label(ty.span, "nested `impl Trait` here")
440 .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
441 self.err_handler().span_err(ty.span, "at least one trait must be specified");
453 fn visit_label(&mut self, label: &'a Label) {
454 self.check_label(label.ident);
455 visit::walk_label(self, label);
458 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
459 self.check_lifetime(lifetime.ident);
460 visit::walk_lifetime(self, lifetime);
463 fn visit_item(&mut self, item: &'a Item) {
464 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr) ) {
465 self.has_proc_macro_decls = true;
469 ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
470 self.invalid_visibility(&item.vis, None);
471 if let TyKind::Err = ty.kind {
473 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
474 .help("use `auto trait Trait {}` instead").emit();
476 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
477 span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
479 for impl_item in impl_items {
480 self.invalid_visibility(&impl_item.vis, None);
481 if let ImplItemKind::Method(ref sig, _) = impl_item.kind {
482 self.check_trait_fn_not_const(sig.header.constness);
483 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness.node);
487 ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
488 self.invalid_visibility(&item.vis,
489 Some("place qualifiers on individual impl items instead"));
490 if unsafety == Unsafety::Unsafe {
491 span_err!(self.session, item.span, E0197, "inherent impls cannot be unsafe");
493 if polarity == ImplPolarity::Negative {
494 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
496 if defaultness == Defaultness::Default {
498 .struct_span_err(item.span, "inherent impls cannot be default")
499 .note("only trait implementations may be annotated with default").emit();
502 ItemKind::Fn(ref sig, ref generics, _) => {
503 self.visit_fn_header(&sig.header);
504 self.check_fn_decl(&sig.decl);
505 // We currently do not permit const generics in `const fn`, as
506 // this is tantamount to allowing compile-time dependent typing.
507 if sig.header.constness.node == Constness::Const {
508 // Look for const generics and error if we find any.
509 for param in &generics.params {
511 GenericParamKind::Const { .. } => {
515 "const parameters are not permitted in `const fn`",
524 ItemKind::ForeignMod(..) => {
525 self.invalid_visibility(
527 Some("place qualifiers on individual foreign items instead"),
530 ItemKind::Enum(ref def, _) => {
531 for variant in &def.variants {
532 for field in variant.data.fields() {
533 self.invalid_visibility(&field.vis, None);
537 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
538 if is_auto == IsAuto::Yes {
539 // Auto traits cannot have generics, super traits nor contain items.
540 if !generics.params.is_empty() {
541 struct_span_err!(self.session, item.span, E0567,
542 "auto traits cannot have generic parameters"
545 if !bounds.is_empty() {
546 struct_span_err!(self.session, item.span, E0568,
547 "auto traits cannot have super traits"
550 if !trait_items.is_empty() {
551 struct_span_err!(self.session, item.span, E0380,
552 "auto traits cannot have methods or associated items"
556 self.no_questions_in_bounds(bounds, "supertraits", true);
557 for trait_item in trait_items {
558 if let TraitItemKind::Method(ref sig, ref block) = trait_item.kind {
559 self.check_fn_decl(&sig.decl);
560 self.check_trait_fn_not_async(trait_item.span, sig.header.asyncness.node);
561 self.check_trait_fn_not_const(sig.header.constness);
563 Self::check_decl_no_pat(&sig.decl, |span, mut_ident| {
565 self.lint_buffer.buffer_lint(
566 lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
568 "patterns aren't allowed in methods without bodies");
570 struct_span_err!(self.session, span, E0642,
571 "patterns aren't allowed in methods without bodies").emit();
578 ItemKind::Mod(_) => {
579 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
580 attr::first_attr_value_str_by_name(&item.attrs, sym::path);
582 ItemKind::Union(ref vdata, _) => {
583 if let VariantData::Tuple(..) | VariantData::Unit(..) = vdata {
584 self.err_handler().span_err(item.span,
585 "tuple and unit unions are not permitted");
587 if vdata.fields().is_empty() {
588 self.err_handler().span_err(item.span,
589 "unions cannot have zero fields");
595 visit::walk_item(self, item)
598 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
600 ForeignItemKind::Fn(ref decl, _) => {
601 self.check_fn_decl(decl);
602 Self::check_decl_no_pat(decl, |span, _| {
603 struct_span_err!(self.session, span, E0130,
604 "patterns aren't allowed in foreign function declarations")
605 .span_label(span, "pattern not allowed in foreign function").emit();
608 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
611 visit::walk_foreign_item(self, fi)
614 // Mirrors `visit::walk_generic_args`, but tracks relevant state.
615 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
616 match *generic_args {
617 GenericArgs::AngleBracketed(ref data) => {
618 walk_list!(self, visit_generic_arg, &data.args);
619 validate_generics_order(
622 data.args.iter().map(|arg| {
624 GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
625 GenericArg::Type(..) => ParamKindOrd::Type,
626 GenericArg::Const(..) => ParamKindOrd::Const,
627 }, None, arg.span(), None)
629 GenericPosition::Arg,
633 // Type bindings such as `Item = impl Debug` in `Iterator<Item = Debug>`
634 // are allowed to contain nested `impl Trait`.
635 self.with_impl_trait(None, |this| {
636 walk_list!(this, visit_assoc_ty_constraint_from_generic_args,
640 GenericArgs::Parenthesized(ref data) => {
641 walk_list!(self, visit_ty, &data.inputs);
642 if let Some(ref type_) = data.output {
643 // `-> Foo` syntax is essentially an associated type binding,
644 // so it is also allowed to contain nested `impl Trait`.
645 self.with_impl_trait(None, |this| this.visit_ty(type_));
651 fn visit_generics(&mut self, generics: &'a Generics) {
652 let mut prev_ty_default = None;
653 for param in &generics.params {
654 if let GenericParamKind::Type { ref default, .. } = param.kind {
655 if default.is_some() {
656 prev_ty_default = Some(param.ident.span);
657 } else if let Some(span) = prev_ty_default {
659 .span_err(span, "type parameters with a default must be trailing");
665 validate_generics_order(
668 generics.params.iter().map(|param| {
669 let ident = Some(param.ident.to_string());
670 let (kind, ident) = match ¶m.kind {
671 GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, ident),
672 GenericParamKind::Type { .. } => (ParamKindOrd::Type, ident),
673 GenericParamKind::Const { ref ty } => {
674 let ty = pprust::ty_to_string(ty);
675 (ParamKindOrd::Const, Some(format!("const {}: {}", param.ident, ty)))
678 (kind, Some(&*param.bounds), param.ident.span, ident)
680 GenericPosition::Param,
684 for predicate in &generics.where_clause.predicates {
685 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
687 .span_err(predicate.span, "equality constraints are not yet \
688 supported in where clauses (see #20041)");
692 visit::walk_generics(self, generics)
695 fn visit_generic_param(&mut self, param: &'a GenericParam) {
696 if let GenericParamKind::Lifetime { .. } = param.kind {
697 self.check_lifetime(param.ident);
699 visit::walk_generic_param(self, param);
702 fn visit_pat(&mut self, pat: &'a Pat) {
704 PatKind::Lit(ref expr) => {
705 self.check_expr_within_pat(expr, false);
707 PatKind::Range(ref start, ref end, _) => {
708 self.check_expr_within_pat(start, true);
709 self.check_expr_within_pat(end, true);
714 visit::walk_pat(self, pat)
717 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
718 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
719 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
720 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
722 visit::walk_where_predicate(self, p);
725 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
726 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
727 visit::walk_poly_trait_ref(self, t, m);
730 fn visit_variant_data(&mut self, s: &'a VariantData) {
731 self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s))
734 fn visit_enum_def(&mut self, enum_definition: &'a EnumDef,
735 generics: &'a Generics, item_id: NodeId, _: Span) {
736 self.with_banned_assoc_ty_bound(
737 |this| visit::walk_enum_def(this, enum_definition, generics, item_id))
740 fn visit_mac(&mut self, mac: &Mac) {
741 // when a new macro kind is added but the author forgets to set it up for expansion
742 // because that's the only part that won't cause a compiler error
743 self.session.diagnostic()
744 .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
745 the relevant `fold_*()` method in `PlaceholderExpander`?");
748 fn visit_impl_item(&mut self, ii: &'a ImplItem) {
749 if let ImplItemKind::Method(ref sig, _) = ii.kind {
750 self.check_fn_decl(&sig.decl);
752 visit::walk_impl_item(self, ii);
756 pub fn check_crate(session: &Session, krate: &Crate, lints: &mut lint::LintBuffer) -> bool {
757 let mut validator = AstValidator {
759 has_proc_macro_decls: false,
760 outer_impl_trait: None,
761 is_impl_trait_banned: false,
762 is_assoc_ty_bound_banned: false,
765 visit::walk_crate(&mut validator, krate);
767 validator.has_proc_macro_decls