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 syntax::print::pprust;
12 use rustc::session::Session;
13 use rustc_data_structures::fx::FxHashMap;
16 use syntax::source_map::Spanned;
17 use syntax::symbol::keywords;
19 use syntax::visit::{self, Visitor};
20 use syntax::{span_err, struct_span_err, walk_list};
21 use syntax_ext::proc_macro_decls::is_proc_macro_attr;
23 use errors::Applicability;
26 struct AstValidator<'a> {
28 has_proc_macro_decls: bool,
29 has_global_allocator: bool,
31 // Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
32 // Nested `impl Trait` _is_ allowed in associated type position,
33 // e.g `impl Iterator<Item=impl Debug>`
34 outer_impl_trait: Option<Span>,
36 // Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
37 // or `Foo::Bar<impl Trait>`
38 is_impl_trait_banned: bool,
41 impl<'a> AstValidator<'a> {
42 fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
43 let old = mem::replace(&mut self.is_impl_trait_banned, true);
45 self.is_impl_trait_banned = old;
48 fn with_impl_trait(&mut self, outer_impl_trait: Option<Span>, f: impl FnOnce(&mut Self)) {
49 let old = mem::replace(&mut self.outer_impl_trait, outer_impl_trait);
51 self.outer_impl_trait = old;
54 // Mirrors visit::walk_ty, but tracks relevant state
55 fn walk_ty(&mut self, t: &'a Ty) {
57 TyKind::ImplTrait(..) => {
58 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
60 TyKind::Path(ref qself, ref path) => {
62 // - `Option<impl Trait>`
63 // - `option::Option<impl Trait>`
64 // - `option::Option<T>::Foo<impl Trait>
67 // - `<impl Trait>::Foo`
68 // - `option::Option<impl Trait>::Foo`.
70 // To implement this, we disallow `impl Trait` from `qself`
71 // (for cases like `<impl Trait>::Foo>`)
72 // but we allow `impl Trait` in `GenericArgs`
73 // iff there are no more PathSegments.
74 if let Some(ref qself) = *qself {
75 // `impl Trait` in `qself` is always illegal
76 self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
79 // Note that there should be a call to visit_path here,
80 // so if any logic is added to process `Path`s a call to it should be
81 // added both in visit_path and here. This code mirrors visit::walk_path.
82 for (i, segment) in path.segments.iter().enumerate() {
83 // Allow `impl Trait` iff we're on the final path segment
84 if i == path.segments.len() - 1 {
85 self.visit_path_segment(path.span, segment);
87 self.with_banned_impl_trait(|this| {
88 this.visit_path_segment(path.span, segment)
93 _ => visit::walk_ty(self, t),
97 fn err_handler(&self) -> &errors::Handler {
98 &self.session.diagnostic()
101 fn check_lifetime(&self, ident: Ident) {
102 let valid_names = [keywords::UnderscoreLifetime.name(),
103 keywords::StaticLifetime.name(),
104 keywords::Invalid.name()];
105 if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
106 self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
110 fn check_label(&self, ident: Ident) {
111 if ident.without_first_quote().is_reserved() {
113 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
117 fn invalid_non_exhaustive_attribute(&self, variant: &Variant) {
118 let has_non_exhaustive = attr::contains_name(&variant.node.attrs, "non_exhaustive");
119 if has_non_exhaustive {
120 self.err_handler().span_err(variant.span,
121 "#[non_exhaustive] is not yet supported on variants");
125 fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
126 if let VisibilityKind::Inherited = vis.node {
130 let mut err = struct_span_err!(self.session,
133 "unnecessary visibility qualifier");
134 if vis.node.is_pub() {
135 err.span_label(vis.span, "`pub` not permitted here because it's implied");
137 if let Some(note) = note {
143 fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
144 for arg in &decl.inputs {
146 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
148 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
149 report_err(arg.pat.span, true),
150 _ => report_err(arg.pat.span, false),
155 fn check_trait_fn_not_async(&self, span: Span, asyncness: IsAsync) {
156 if asyncness.is_async() {
157 struct_span_err!(self.session, span, E0706,
158 "trait fns cannot be declared `async`").emit()
162 fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
163 if constness.node == Constness::Const {
164 struct_span_err!(self.session, constness.span, E0379,
165 "trait fns cannot be declared const")
166 .span_label(constness.span, "trait fns cannot be const")
171 fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
172 for bound in bounds {
173 if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
174 let mut err = self.err_handler().struct_span_err(poly.span,
175 &format!("`?Trait` is not permitted in {}", where_));
177 err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
184 /// Matches `'-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus)`,
185 /// or paths for ranges.
187 // FIXME: do we want to allow `expr -> pattern` conversion to create path expressions?
188 // That means making this work:
190 // ```rust,ignore (FIXME)
199 fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
201 ExprKind::Lit(..) => {}
202 ExprKind::Path(..) if allow_paths => {}
203 ExprKind::Unary(UnOp::Neg, ref inner)
204 if match inner.node { ExprKind::Lit(_) => true, _ => false } => {}
205 _ => self.err_handler().span_err(expr.span, "arbitrary expressions aren't allowed \
210 fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
211 // Check only lifetime parameters are present and that the lifetime
212 // parameters that are present have no bounds.
213 let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind {
214 GenericParamKind::Lifetime { .. } => {
215 if !param.bounds.is_empty() {
216 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
218 .span_err(spans, "lifetime bounds cannot be used in this context");
222 _ => Some(param.ident.span),
224 if !non_lt_param_spans.is_empty() {
225 self.err_handler().span_err(non_lt_param_spans,
226 "only lifetime parameters can be used in this context");
230 /// With eRFC 2497, we need to check whether an expression is ambiguous and warn or error
231 /// depending on the edition, this function handles that.
232 fn while_if_let_ambiguity(&self, expr: &P<Expr>) {
233 if let Some((span, op_kind)) = self.while_if_let_expr_ambiguity(&expr) {
234 let mut err = self.err_handler().struct_span_err(
235 span, &format!("ambiguous use of `{}`", op_kind.to_string())
239 "this will be a error until the `let_chains` feature is stabilized"
242 "see rust-lang/rust#53668 for more information"
245 if let Ok(snippet) = self.session.source_map().span_to_snippet(span) {
247 span, "consider adding parentheses", format!("({})", snippet),
248 Applicability::MachineApplicable,
256 /// With eRFC 2497 adding if-let chains, there is a requirement that the parsing of
257 /// `&&` and `||` in a if-let statement be unambiguous. This function returns a span and
258 /// a `BinOpKind` (either `&&` or `||` depending on what was ambiguous) if it is determined
259 /// that the current expression parsed is ambiguous and will break in future.
260 fn while_if_let_expr_ambiguity(&self, expr: &P<Expr>) -> Option<(Span, BinOpKind)> {
261 debug!("while_if_let_expr_ambiguity: expr.node: {:?}", expr.node);
263 ExprKind::Binary(op, _, _) if op.node == BinOpKind::And || op.node == BinOpKind::Or => {
264 Some((expr.span, op.node))
266 ExprKind::Range(ref lhs, ref rhs, _) => {
267 let lhs_ambiguous = lhs.as_ref()
268 .and_then(|lhs| self.while_if_let_expr_ambiguity(lhs));
269 let rhs_ambiguous = rhs.as_ref()
270 .and_then(|rhs| self.while_if_let_expr_ambiguity(rhs));
272 lhs_ambiguous.or(rhs_ambiguous)
279 enum GenericPosition {
284 fn validate_generics_order<'a>(
285 handler: &errors::Handler,
286 generics: impl Iterator<Item = (ParamKindOrd, Span, Option<String>)>,
287 pos: GenericPosition,
290 let mut max_param: Option<ParamKindOrd> = None;
291 let mut out_of_order = FxHashMap::default();
292 let mut param_idents = vec![];
294 for (kind, span, ident) in generics {
295 if let Some(ident) = ident {
296 param_idents.push((kind, param_idents.len(), ident));
298 let max_param = &mut max_param;
300 Some(max_param) if *max_param > kind => {
301 let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
304 Some(_) | None => *max_param = Some(kind),
308 let mut ordered_params = "<".to_string();
309 if !out_of_order.is_empty() {
310 param_idents.sort_by_key(|&(po, i, _)| (po, i));
311 let mut first = true;
312 for (_, _, ident) in param_idents {
314 ordered_params += ", ";
316 ordered_params += &ident;
320 ordered_params += ">";
322 let pos_str = match pos {
323 GenericPosition::Param => "parameter",
324 GenericPosition::Arg => "argument",
327 for (param_ord, (max_param, spans)) in out_of_order {
328 let mut err = handler.struct_span_err(spans,
330 "{} {pos}s must be declared prior to {} {pos}s",
335 if let GenericPosition::Param = pos {
338 &format!("reorder the {}s: lifetimes, then types, then consts", pos_str),
339 ordered_params.clone(),
340 Applicability::MachineApplicable,
347 impl<'a> Visitor<'a> for AstValidator<'a> {
348 fn visit_expr(&mut self, expr: &'a Expr) {
350 ExprKind::IfLet(_, ref expr, _, _) | ExprKind::WhileLet(_, ref expr, _, _) =>
351 self.while_if_let_ambiguity(&expr),
352 ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
353 span_err!(self.session, expr.span, E0472, "asm! is unsupported on this target");
355 ExprKind::ObsoleteInPlace(ref place, ref val) => {
356 let mut err = self.err_handler().struct_span_err(
358 "emplacement syntax is obsolete (for now, anyway)",
361 "for more information, see \
362 <https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"
365 ExprKind::Lit(ref v) if v.node.is_numeric() => {
367 place.span.between(val.span),
368 "if you meant to write a comparison against a negative value, add a \
369 space in between `<` and `-`",
371 Applicability::MaybeIncorrect
381 visit::walk_expr(self, expr)
384 fn visit_ty(&mut self, ty: &'a Ty) {
386 TyKind::BareFn(ref bfty) => {
387 self.check_decl_no_pat(&bfty.decl, |span, _| {
388 struct_span_err!(self.session, span, E0561,
389 "patterns aren't allowed in function pointer types").emit();
391 self.check_late_bound_lifetime_defs(&bfty.generic_params);
393 TyKind::TraitObject(ref bounds, ..) => {
394 let mut any_lifetime_bounds = false;
395 for bound in bounds {
396 if let GenericBound::Outlives(ref lifetime) = *bound {
397 if any_lifetime_bounds {
398 span_err!(self.session, lifetime.ident.span, E0226,
399 "only a single explicit lifetime bound is permitted");
402 any_lifetime_bounds = true;
405 self.no_questions_in_bounds(bounds, "trait object types", false);
407 TyKind::ImplTrait(_, ref bounds) => {
408 if self.is_impl_trait_banned {
409 struct_span_err!(self.session, ty.span, E0667,
410 "`impl Trait` is not allowed in path parameters").emit();
413 if let Some(outer_impl_trait) = self.outer_impl_trait {
414 struct_span_err!(self.session, ty.span, E0666,
415 "nested `impl Trait` is not allowed")
416 .span_label(outer_impl_trait, "outer `impl Trait`")
417 .span_label(ty.span, "nested `impl Trait` here")
422 .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
423 self.err_handler().span_err(ty.span, "at least one trait must be specified");
432 fn visit_label(&mut self, label: &'a Label) {
433 self.check_label(label.ident);
434 visit::walk_label(self, label);
437 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
438 self.check_lifetime(lifetime.ident);
439 visit::walk_lifetime(self, lifetime);
442 fn visit_item(&mut self, item: &'a Item) {
443 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr) ) {
444 self.has_proc_macro_decls = true;
447 if attr::contains_name(&item.attrs, "global_allocator") {
448 self.has_global_allocator = true;
452 ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
453 self.invalid_visibility(&item.vis, None);
454 if let TyKind::Err = ty.node {
456 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
457 .help("use `auto trait Trait {}` instead").emit();
459 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
460 span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
462 for impl_item in impl_items {
463 self.invalid_visibility(&impl_item.vis, None);
464 if let ImplItemKind::Method(ref sig, _) = impl_item.node {
465 self.check_trait_fn_not_const(sig.header.constness);
466 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness.node);
470 ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
471 self.invalid_visibility(&item.vis,
472 Some("place qualifiers on individual impl items instead"));
473 if unsafety == Unsafety::Unsafe {
474 span_err!(self.session, item.span, E0197, "inherent impls cannot be unsafe");
476 if polarity == ImplPolarity::Negative {
477 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
479 if defaultness == Defaultness::Default {
481 .struct_span_err(item.span, "inherent impls cannot be default")
482 .note("only trait implementations may be annotated with default").emit();
485 ItemKind::Fn(_, ref header, ref generics, _) => {
486 // We currently do not permit const generics in `const fn`, as
487 // this is tantamount to allowing compile-time dependent typing.
488 self.visit_fn_header(header);
489 if header.constness.node == Constness::Const {
490 // Look for const generics and error if we find any.
491 for param in &generics.params {
493 GenericParamKind::Const { .. } => {
497 "const parameters are not permitted in `const fn`",
506 ItemKind::ForeignMod(..) => {
507 self.invalid_visibility(
509 Some("place qualifiers on individual foreign items instead"),
512 ItemKind::Enum(ref def, _) => {
513 for variant in &def.variants {
514 self.invalid_non_exhaustive_attribute(variant);
515 for field in variant.node.data.fields() {
516 self.invalid_visibility(&field.vis, None);
520 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
521 if is_auto == IsAuto::Yes {
522 // Auto traits cannot have generics, super traits nor contain items.
523 if !generics.params.is_empty() {
524 struct_span_err!(self.session, item.span, E0567,
525 "auto traits cannot have generic parameters").emit();
527 if !bounds.is_empty() {
528 struct_span_err!(self.session, item.span, E0568,
529 "auto traits cannot have super traits").emit();
531 if !trait_items.is_empty() {
532 struct_span_err!(self.session, item.span, E0380,
533 "auto traits cannot have methods or associated items").emit();
536 self.no_questions_in_bounds(bounds, "supertraits", true);
537 for trait_item in trait_items {
538 if let TraitItemKind::Method(ref sig, ref block) = trait_item.node {
539 self.check_trait_fn_not_async(trait_item.span, sig.header.asyncness.node);
540 self.check_trait_fn_not_const(sig.header.constness);
542 self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
544 self.session.buffer_lint(
545 lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
547 "patterns aren't allowed in methods without bodies");
549 struct_span_err!(self.session, span, E0642,
550 "patterns aren't allowed in methods without bodies").emit();
557 ItemKind::Mod(_) => {
558 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
559 attr::first_attr_value_str_by_name(&item.attrs, "path");
560 if attr::contains_name(&item.attrs, "warn_directory_ownership") {
561 let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
562 let msg = "cannot declare a new module at this location";
563 self.session.buffer_lint(lint, item.id, item.span, msg);
566 ItemKind::Union(ref vdata, _) => {
567 if !vdata.is_struct() {
568 self.err_handler().span_err(item.span,
569 "tuple and unit unions are not permitted");
571 if vdata.fields().is_empty() {
572 self.err_handler().span_err(item.span,
573 "unions cannot have zero fields");
579 visit::walk_item(self, item)
582 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
584 ForeignItemKind::Fn(ref decl, _) => {
585 self.check_decl_no_pat(decl, |span, _| {
586 struct_span_err!(self.session, span, E0130,
587 "patterns aren't allowed in foreign function declarations")
588 .span_label(span, "pattern not allowed in foreign function").emit();
591 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
594 visit::walk_foreign_item(self, fi)
597 // Mirrors visit::walk_generic_args, but tracks relevant state
598 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
599 match *generic_args {
600 GenericArgs::AngleBracketed(ref data) => {
601 walk_list!(self, visit_generic_arg, &data.args);
602 validate_generics_order(self.err_handler(), data.args.iter().map(|arg| {
604 GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
605 GenericArg::Type(..) => ParamKindOrd::Type,
606 GenericArg::Const(..) => ParamKindOrd::Const,
608 }), GenericPosition::Arg, generic_args.span());
609 // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
610 // are allowed to contain nested `impl Trait`.
611 self.with_impl_trait(None, |this| {
612 walk_list!(this, visit_assoc_type_binding, &data.bindings);
615 GenericArgs::Parenthesized(ref data) => {
616 walk_list!(self, visit_ty, &data.inputs);
617 if let Some(ref type_) = data.output {
618 // `-> Foo` syntax is essentially an associated type binding,
619 // so it is also allowed to contain nested `impl Trait`.
620 self.with_impl_trait(None, |this| this.visit_ty(type_));
626 fn visit_generics(&mut self, generics: &'a Generics) {
627 let mut prev_ty_default = None;
628 for param in &generics.params {
629 if let GenericParamKind::Type { ref default, .. } = param.kind {
630 if default.is_some() {
631 prev_ty_default = Some(param.ident.span);
632 } else if let Some(span) = prev_ty_default {
634 .span_err(span, "type parameters with a default must be trailing");
640 validate_generics_order(self.err_handler(), generics.params.iter().map(|param| {
641 let span = param.ident.span;
642 let ident = Some(param.ident.to_string());
644 GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, span, ident),
645 GenericParamKind::Type { .. } => (ParamKindOrd::Type, span, ident),
646 GenericParamKind::Const { ref ty } => {
647 let ty = pprust::ty_to_string(ty);
648 (ParamKindOrd::Const, span, Some(format!("const {}: {}", param.ident, ty)))
651 }), GenericPosition::Param, generics.span);
653 for predicate in &generics.where_clause.predicates {
654 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
656 .span_err(predicate.span, "equality constraints are not yet \
657 supported in where clauses (see #20041)");
661 visit::walk_generics(self, generics)
664 fn visit_generic_param(&mut self, param: &'a GenericParam) {
665 if let GenericParamKind::Lifetime { .. } = param.kind {
666 self.check_lifetime(param.ident);
668 visit::walk_generic_param(self, param);
671 fn visit_pat(&mut self, pat: &'a Pat) {
673 PatKind::Lit(ref expr) => {
674 self.check_expr_within_pat(expr, false);
676 PatKind::Range(ref start, ref end, _) => {
677 self.check_expr_within_pat(start, true);
678 self.check_expr_within_pat(end, true);
683 visit::walk_pat(self, pat)
686 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
687 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
688 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
689 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
691 visit::walk_where_predicate(self, p);
694 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
695 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
696 visit::walk_poly_trait_ref(self, t, m);
699 fn visit_mac(&mut self, mac: &Spanned<Mac_>) {
700 // when a new macro kind is added but the author forgets to set it up for expansion
701 // because that's the only part that won't cause a compiler error
702 self.session.diagnostic()
703 .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
704 the relevant `fold_*()` method in `PlaceholderExpander`?");
707 fn visit_fn_header(&mut self, header: &'a FnHeader) {
708 if header.asyncness.node.is_async() && self.session.rust_2015() {
709 struct_span_err!(self.session, header.asyncness.span, E0670,
710 "`async fn` is not permitted in the 2015 edition").emit();
715 pub fn check_crate(session: &Session, krate: &Crate) -> (bool, bool) {
716 let mut validator = AstValidator {
718 has_proc_macro_decls: false,
719 has_global_allocator: false,
720 outer_impl_trait: None,
721 is_impl_trait_banned: false,
723 visit::walk_crate(&mut validator, krate);
725 (validator.has_proc_macro_decls, validator.has_global_allocator)