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;
14 use syntax::source_map::Spanned;
15 use syntax::symbol::keywords;
17 use syntax::visit::{self, Visitor};
18 use syntax_ext::proc_macro_decls::is_proc_macro_attr;
21 use errors::Applicability;
23 struct AstValidator<'a> {
25 has_proc_macro_decls: bool,
26 has_global_allocator: bool,
28 // Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
29 // Nested `impl Trait` _is_ allowed in associated type position,
30 // e.g `impl Iterator<Item=impl Debug>`
31 outer_impl_trait: Option<Span>,
33 // Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
34 // or `Foo::Bar<impl Trait>`
35 is_impl_trait_banned: bool,
38 impl<'a> AstValidator<'a> {
39 fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
40 let old = mem::replace(&mut self.is_impl_trait_banned, true);
42 self.is_impl_trait_banned = old;
45 fn with_impl_trait(&mut self, outer_impl_trait: Option<Span>, f: impl FnOnce(&mut Self)) {
46 let old = mem::replace(&mut self.outer_impl_trait, outer_impl_trait);
48 self.outer_impl_trait = old;
51 // Mirrors visit::walk_ty, but tracks relevant state
52 fn walk_ty(&mut self, t: &'a Ty) {
54 TyKind::ImplTrait(..) => {
55 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
57 TyKind::Path(ref qself, ref path) => {
59 // - `Option<impl Trait>`
60 // - `option::Option<impl Trait>`
61 // - `option::Option<T>::Foo<impl Trait>
64 // - `<impl Trait>::Foo`
65 // - `option::Option<impl Trait>::Foo`.
67 // To implement this, we disallow `impl Trait` from `qself`
68 // (for cases like `<impl Trait>::Foo>`)
69 // but we allow `impl Trait` in `GenericArgs`
70 // iff there are no more PathSegments.
71 if let Some(ref qself) = *qself {
72 // `impl Trait` in `qself` is always illegal
73 self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
76 // Note that there should be a call to visit_path here,
77 // so if any logic is added to process `Path`s a call to it should be
78 // added both in visit_path and here. This code mirrors visit::walk_path.
79 for (i, segment) in path.segments.iter().enumerate() {
80 // Allow `impl Trait` iff we're on the final path segment
81 if i == path.segments.len() - 1 {
82 self.visit_path_segment(path.span, segment);
84 self.with_banned_impl_trait(|this| {
85 this.visit_path_segment(path.span, segment)
90 _ => visit::walk_ty(self, t),
94 fn err_handler(&self) -> &errors::Handler {
95 &self.session.diagnostic()
98 fn check_lifetime(&self, ident: Ident) {
99 let valid_names = [keywords::UnderscoreLifetime.name(),
100 keywords::StaticLifetime.name(),
101 keywords::Invalid.name()];
102 if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
103 self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
107 fn check_label(&self, ident: Ident) {
108 if ident.without_first_quote().is_reserved() {
110 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
114 fn invalid_non_exhaustive_attribute(&self, variant: &Variant) {
115 let has_non_exhaustive = attr::contains_name(&variant.node.attrs, "non_exhaustive");
116 if has_non_exhaustive {
117 self.err_handler().span_err(variant.span,
118 "#[non_exhaustive] is not yet supported on variants");
122 fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
123 if let VisibilityKind::Inherited = vis.node {
127 let mut err = struct_span_err!(self.session,
130 "unnecessary visibility qualifier");
131 if vis.node.is_pub() {
132 err.span_label(vis.span, "`pub` not permitted here because it's implied");
134 if let Some(note) = note {
140 fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
141 for arg in &decl.inputs {
143 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
145 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
146 report_err(arg.pat.span, true),
147 _ => report_err(arg.pat.span, false),
152 fn check_trait_fn_not_async(&self, span: Span, asyncness: IsAsync) {
153 if asyncness.is_async() {
154 struct_span_err!(self.session, span, E0706,
155 "trait fns cannot be declared `async`").emit()
159 fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
160 if constness.node == Constness::Const {
161 struct_span_err!(self.session, constness.span, E0379,
162 "trait fns cannot be declared const")
163 .span_label(constness.span, "trait fns cannot be const")
168 fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
169 for bound in bounds {
170 if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
171 let mut err = self.err_handler().struct_span_err(poly.span,
172 &format!("`?Trait` is not permitted in {}", where_));
174 err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
181 /// matches '-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus),
182 /// or path for ranges.
184 /// FIXME: do we want to allow expr -> pattern conversion to create path expressions?
185 /// That means making this work:
187 /// ```rust,ignore (FIXME)
196 fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
198 ExprKind::Lit(..) => {}
199 ExprKind::Path(..) if allow_paths => {}
200 ExprKind::Unary(UnOp::Neg, ref inner)
201 if match inner.node { ExprKind::Lit(_) => true, _ => false } => {}
202 _ => self.err_handler().span_err(expr.span, "arbitrary expressions aren't allowed \
207 fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
208 // Check only lifetime parameters are present and that the lifetime
209 // parameters that are present have no bounds.
210 let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind {
211 GenericParamKind::Lifetime { .. } => {
212 if !param.bounds.is_empty() {
213 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
215 .span_err(spans, "lifetime bounds cannot be used in this context");
219 _ => Some(param.ident.span),
221 if !non_lt_param_spans.is_empty() {
222 self.err_handler().span_err(non_lt_param_spans,
223 "only lifetime parameters can be used in this context");
227 /// With eRFC 2497, we need to check whether an expression is ambiguous and warn or error
228 /// depending on the edition, this function handles that.
229 fn while_if_let_ambiguity(&self, expr: &P<Expr>) {
230 if let Some((span, op_kind)) = self.while_if_let_expr_ambiguity(&expr) {
231 let mut err = self.err_handler().struct_span_err(
232 span, &format!("ambiguous use of `{}`", op_kind.to_string())
236 "this will be a error until the `let_chains` feature is stabilized"
239 "see rust-lang/rust#53668 for more information"
242 if let Ok(snippet) = self.session.source_map().span_to_snippet(span) {
244 span, "consider adding parentheses", format!("({})", snippet),
245 Applicability::MachineApplicable,
253 /// With eRFC 2497 adding if-let chains, there is a requirement that the parsing of
254 /// `&&` and `||` in a if-let statement be unambiguous. This function returns a span and
255 /// a `BinOpKind` (either `&&` or `||` depending on what was ambiguous) if it is determined
256 /// that the current expression parsed is ambiguous and will break in future.
257 fn while_if_let_expr_ambiguity(&self, expr: &P<Expr>) -> Option<(Span, BinOpKind)> {
258 debug!("while_if_let_expr_ambiguity: expr.node: {:?}", expr.node);
260 ExprKind::Binary(op, _, _) if op.node == BinOpKind::And || op.node == BinOpKind::Or => {
261 Some((expr.span, op.node))
263 ExprKind::Range(ref lhs, ref rhs, _) => {
264 let lhs_ambiguous = lhs.as_ref()
265 .and_then(|lhs| self.while_if_let_expr_ambiguity(lhs));
266 let rhs_ambiguous = rhs.as_ref()
267 .and_then(|rhs| self.while_if_let_expr_ambiguity(rhs));
269 lhs_ambiguous.or(rhs_ambiguous)
277 impl<'a> Visitor<'a> for AstValidator<'a> {
278 fn visit_expr(&mut self, expr: &'a Expr) {
280 ExprKind::IfLet(_, ref expr, _, _) | ExprKind::WhileLet(_, ref expr, _, _) =>
281 self.while_if_let_ambiguity(&expr),
282 ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
283 span_err!(self.session, expr.span, E0472, "asm! is unsupported on this target");
285 ExprKind::ObsoleteInPlace(ref place, ref val) => {
286 let mut err = self.err_handler().struct_span_err(
288 "emplacement syntax is obsolete (for now, anyway)",
291 "for more information, see \
292 <https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"
295 ExprKind::Lit(ref v) if v.node.is_numeric() => {
297 place.span.between(val.span),
298 "if you meant to write a comparison against a negative value, add a \
299 space in between `<` and `-`",
301 Applicability::MaybeIncorrect
311 visit::walk_expr(self, expr)
314 fn visit_ty(&mut self, ty: &'a Ty) {
316 TyKind::BareFn(ref bfty) => {
317 self.check_decl_no_pat(&bfty.decl, |span, _| {
318 struct_span_err!(self.session, span, E0561,
319 "patterns aren't allowed in function pointer types").emit();
321 self.check_late_bound_lifetime_defs(&bfty.generic_params);
323 TyKind::TraitObject(ref bounds, ..) => {
324 let mut any_lifetime_bounds = false;
325 for bound in bounds {
326 if let GenericBound::Outlives(ref lifetime) = *bound {
327 if any_lifetime_bounds {
328 span_err!(self.session, lifetime.ident.span, E0226,
329 "only a single explicit lifetime bound is permitted");
332 any_lifetime_bounds = true;
335 self.no_questions_in_bounds(bounds, "trait object types", false);
337 TyKind::ImplTrait(_, ref bounds) => {
338 if self.is_impl_trait_banned {
339 struct_span_err!(self.session, ty.span, E0667,
340 "`impl Trait` is not allowed in path parameters").emit();
343 if let Some(outer_impl_trait) = self.outer_impl_trait {
344 struct_span_err!(self.session, ty.span, E0666,
345 "nested `impl Trait` is not allowed")
346 .span_label(outer_impl_trait, "outer `impl Trait`")
347 .span_label(ty.span, "nested `impl Trait` here")
352 .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
353 self.err_handler().span_err(ty.span, "at least one trait must be specified");
362 fn visit_label(&mut self, label: &'a Label) {
363 self.check_label(label.ident);
364 visit::walk_label(self, label);
367 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
368 self.check_lifetime(lifetime.ident);
369 visit::walk_lifetime(self, lifetime);
372 fn visit_item(&mut self, item: &'a Item) {
373 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr) ) {
374 self.has_proc_macro_decls = true;
377 if attr::contains_name(&item.attrs, "global_allocator") {
378 self.has_global_allocator = true;
382 ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
383 self.invalid_visibility(&item.vis, None);
384 if let TyKind::Err = ty.node {
386 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
387 .help("use `auto trait Trait {}` instead").emit();
389 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
390 span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
392 for impl_item in impl_items {
393 self.invalid_visibility(&impl_item.vis, None);
394 if let ImplItemKind::Method(ref sig, _) = impl_item.node {
395 self.check_trait_fn_not_const(sig.header.constness);
396 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness);
400 ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
401 self.invalid_visibility(&item.vis,
402 Some("place qualifiers on individual impl items instead"));
403 if unsafety == Unsafety::Unsafe {
404 span_err!(self.session, item.span, E0197, "inherent impls cannot be unsafe");
406 if polarity == ImplPolarity::Negative {
407 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
409 if defaultness == Defaultness::Default {
411 .struct_span_err(item.span, "inherent impls cannot be default")
412 .note("only trait implementations may be annotated with default").emit();
415 ItemKind::ForeignMod(..) => {
416 self.invalid_visibility(
418 Some("place qualifiers on individual foreign items instead"),
421 ItemKind::Enum(ref def, _) => {
422 for variant in &def.variants {
423 self.invalid_non_exhaustive_attribute(variant);
424 for field in variant.node.data.fields() {
425 self.invalid_visibility(&field.vis, None);
429 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
430 if is_auto == IsAuto::Yes {
431 // Auto traits cannot have generics, super traits nor contain items.
432 if !generics.params.is_empty() {
433 struct_span_err!(self.session, item.span, E0567,
434 "auto traits cannot have generic parameters").emit();
436 if !bounds.is_empty() {
437 struct_span_err!(self.session, item.span, E0568,
438 "auto traits cannot have super traits").emit();
440 if !trait_items.is_empty() {
441 struct_span_err!(self.session, item.span, E0380,
442 "auto traits cannot have methods or associated items").emit();
445 self.no_questions_in_bounds(bounds, "supertraits", true);
446 for trait_item in trait_items {
447 if let TraitItemKind::Method(ref sig, ref block) = trait_item.node {
448 self.check_trait_fn_not_async(trait_item.span, sig.header.asyncness);
449 self.check_trait_fn_not_const(sig.header.constness);
451 self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
453 self.session.buffer_lint(
454 lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
456 "patterns aren't allowed in methods without bodies");
458 struct_span_err!(self.session, span, E0642,
459 "patterns aren't allowed in methods without bodies").emit();
466 ItemKind::Mod(_) => {
467 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
468 attr::first_attr_value_str_by_name(&item.attrs, "path");
469 if attr::contains_name(&item.attrs, "warn_directory_ownership") {
470 let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
471 let msg = "cannot declare a new module at this location";
472 self.session.buffer_lint(lint, item.id, item.span, msg);
475 ItemKind::Union(ref vdata, _) => {
476 if !vdata.is_struct() {
477 self.err_handler().span_err(item.span,
478 "tuple and unit unions are not permitted");
480 if vdata.fields().is_empty() {
481 self.err_handler().span_err(item.span,
482 "unions cannot have zero fields");
488 visit::walk_item(self, item)
491 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
493 ForeignItemKind::Fn(ref decl, _) => {
494 self.check_decl_no_pat(decl, |span, _| {
495 struct_span_err!(self.session, span, E0130,
496 "patterns aren't allowed in foreign function declarations")
497 .span_label(span, "pattern not allowed in foreign function").emit();
500 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
503 visit::walk_foreign_item(self, fi)
506 // Mirrors visit::walk_generic_args, but tracks relevant state
507 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
508 match *generic_args {
509 GenericArgs::AngleBracketed(ref data) => {
510 walk_list!(self, visit_generic_arg, &data.args);
511 // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
512 // are allowed to contain nested `impl Trait`.
513 self.with_impl_trait(None, |this| {
514 walk_list!(this, visit_assoc_type_binding, &data.bindings);
517 GenericArgs::Parenthesized(ref data) => {
518 walk_list!(self, visit_ty, &data.inputs);
519 if let Some(ref type_) = data.output {
520 // `-> Foo` syntax is essentially an associated type binding,
521 // so it is also allowed to contain nested `impl Trait`.
522 self.with_impl_trait(None, |this| visit::walk_ty(this, type_));
528 fn visit_generics(&mut self, generics: &'a Generics) {
529 let mut seen_non_lifetime_param = false;
530 let mut seen_default = None;
531 for param in &generics.params {
532 match (¶m.kind, seen_non_lifetime_param) {
533 (GenericParamKind::Lifetime { .. }, true) => {
535 .span_err(param.ident.span, "lifetime parameters must be leading");
537 (GenericParamKind::Lifetime { .. }, false) => {}
538 (GenericParamKind::Type { ref default, .. }, _) => {
539 seen_non_lifetime_param = true;
540 if default.is_some() {
541 seen_default = Some(param.ident.span);
542 } else if let Some(span) = seen_default {
544 .span_err(span, "type parameters with a default must be trailing");
550 for predicate in &generics.where_clause.predicates {
551 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
553 .span_err(predicate.span, "equality constraints are not yet \
554 supported in where clauses (see #20041)");
557 visit::walk_generics(self, generics)
560 fn visit_generic_param(&mut self, param: &'a GenericParam) {
561 if let GenericParamKind::Lifetime { .. } = param.kind {
562 self.check_lifetime(param.ident);
564 visit::walk_generic_param(self, param);
567 fn visit_pat(&mut self, pat: &'a Pat) {
569 PatKind::Lit(ref expr) => {
570 self.check_expr_within_pat(expr, false);
572 PatKind::Range(ref start, ref end, _) => {
573 self.check_expr_within_pat(start, true);
574 self.check_expr_within_pat(end, true);
579 visit::walk_pat(self, pat)
582 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
583 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
584 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
585 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
587 visit::walk_where_predicate(self, p);
590 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
591 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
592 visit::walk_poly_trait_ref(self, t, m);
595 fn visit_mac(&mut self, mac: &Spanned<Mac_>) {
596 // when a new macro kind is added but the author forgets to set it up for expansion
597 // because that's the only part that won't cause a compiler error
598 self.session.diagnostic()
599 .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
600 the relevant `fold_*()` method in `PlaceholderExpander`?");
604 pub fn check_crate(session: &Session, krate: &Crate) -> (bool, bool) {
605 let mut validator = AstValidator {
607 has_proc_macro_decls: false,
608 has_global_allocator: false,
609 outer_impl_trait: None,
610 is_impl_trait_banned: false,
612 visit::walk_crate(&mut validator, krate);
614 (validator.has_proc_macro_decls, validator.has_global_allocator)