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_label(&mut self, label: &'a Label) {
282 self.check_label(label.ident);
283 visit::walk_label(self, label);
286 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
287 self.check_lifetime(lifetime.ident);
288 visit::walk_lifetime(self, lifetime);
291 fn visit_item(&mut self, item: &'a Item) {
293 ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
294 self.invalid_visibility(&item.vis, None);
295 if let TyKind::Err = ty.node {
297 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
298 .help("use `auto trait Trait {}` instead").emit();
300 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
301 span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
303 for impl_item in impl_items {
304 self.invalid_visibility(&impl_item.vis, None);
305 if let ImplItemKind::Method(ref sig, _) = impl_item.node {
306 self.check_trait_fn_not_const(sig.header.constness);
307 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness);
311 ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
312 self.invalid_visibility(&item.vis,
313 Some("place qualifiers on individual impl items instead"));
314 if unsafety == Unsafety::Unsafe {
315 span_err!(self.session, item.span, E0197, "inherent impls cannot be unsafe");
317 if polarity == ImplPolarity::Negative {
318 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
320 if defaultness == Defaultness::Default {
322 .struct_span_err(item.span, "inherent impls cannot be default")
323 .note("only trait implementations may be annotated with default").emit();
326 ItemKind::ForeignMod(..) => {
327 self.invalid_visibility(
329 Some("place qualifiers on individual foreign items instead"),
332 ItemKind::Enum(ref def, _) => {
333 for variant in &def.variants {
334 self.invalid_non_exhaustive_attribute(variant);
335 for field in variant.node.data.fields() {
336 self.invalid_visibility(&field.vis, None);
340 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
341 if is_auto == IsAuto::Yes {
342 // Auto traits cannot have generics, super traits nor contain items.
343 if !generics.params.is_empty() {
344 struct_span_err!(self.session, item.span, E0567,
345 "auto traits cannot have generic parameters").emit();
347 if !bounds.is_empty() {
348 struct_span_err!(self.session, item.span, E0568,
349 "auto traits cannot have super traits").emit();
351 if !trait_items.is_empty() {
352 struct_span_err!(self.session, item.span, E0380,
353 "auto traits cannot have methods or associated items").emit();
356 self.no_questions_in_bounds(bounds, "supertraits", true);
357 for trait_item in trait_items {
358 if let TraitItemKind::Method(ref sig, ref block) = trait_item.node {
359 self.check_trait_fn_not_async(trait_item.span, sig.header.asyncness);
360 self.check_trait_fn_not_const(sig.header.constness);
362 self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
364 self.session.buffer_lint(
365 lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
367 "patterns aren't allowed in methods without bodies");
369 struct_span_err!(self.session, span, E0642,
370 "patterns aren't allowed in methods without bodies").emit();
377 ItemKind::Mod(_) => {
378 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
379 attr::first_attr_value_str_by_name(&item.attrs, "path");
380 if attr::contains_name(&item.attrs, "warn_directory_ownership") {
381 let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
382 let msg = "cannot declare a new module at this location";
383 self.session.buffer_lint(lint, item.id, item.span, msg);
386 ItemKind::Union(ref vdata, _) => {
387 if !vdata.is_struct() {
388 self.err_handler().span_err(item.span,
389 "tuple and unit unions are not permitted");
391 if vdata.fields().is_empty() {
392 self.err_handler().span_err(item.span,
393 "unions cannot have zero fields");
399 visit::walk_item(self, item)
402 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
404 ForeignItemKind::Fn(ref decl, _) => {
405 self.check_decl_no_pat(decl, |span, _| {
406 struct_span_err!(self.session, span, E0130,
407 "patterns aren't allowed in foreign function declarations")
408 .span_label(span, "pattern not allowed in foreign function").emit();
411 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
414 visit::walk_foreign_item(self, fi)
417 fn visit_generics(&mut self, generics: &'a Generics) {
418 let mut seen_non_lifetime_param = false;
419 let mut seen_default = None;
420 for param in &generics.params {
421 match (¶m.kind, seen_non_lifetime_param) {
422 (GenericParamKind::Lifetime { .. }, true) => {
424 .span_err(param.ident.span, "lifetime parameters must be leading");
426 (GenericParamKind::Lifetime { .. }, false) => {}
427 (GenericParamKind::Type { ref default, .. }, _) => {
428 seen_non_lifetime_param = true;
429 if default.is_some() {
430 seen_default = Some(param.ident.span);
431 } else if let Some(span) = seen_default {
433 .span_err(span, "type parameters with a default must be trailing");
439 for predicate in &generics.where_clause.predicates {
440 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
442 .span_err(predicate.span, "equality constraints are not yet \
443 supported in where clauses (see #20041)");
446 visit::walk_generics(self, generics)
449 fn visit_generic_param(&mut self, param: &'a GenericParam) {
450 if let GenericParamKind::Lifetime { .. } = param.kind {
451 self.check_lifetime(param.ident);
453 visit::walk_generic_param(self, param);
456 fn visit_pat(&mut self, pat: &'a Pat) {
458 PatKind::Lit(ref expr) => {
459 self.check_expr_within_pat(expr, false);
461 PatKind::Range(ref start, ref end, _) => {
462 self.check_expr_within_pat(start, true);
463 self.check_expr_within_pat(end, true);
468 visit::walk_pat(self, pat)
471 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
472 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
473 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
474 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
476 visit::walk_where_predicate(self, p);
479 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
480 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
481 visit::walk_poly_trait_ref(self, t, m);
484 fn visit_mac(&mut self, mac: &Spanned<Mac_>) {
485 // when a new macro kind is added but the author forgets to set it up for expansion
486 // because that's the only part that won't cause a compiler error
487 self.session.diagnostic()
488 .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
489 the relevant `fold_*()` method in `PlaceholderExpander`?");
493 // Bans nested `impl Trait`, e.g., `impl Into<impl Debug>`.
494 // Nested `impl Trait` _is_ allowed in associated type position,
495 // e.g `impl Iterator<Item=impl Debug>`
496 struct NestedImplTraitVisitor<'a> {
497 session: &'a Session,
498 outer_impl_trait: Option<Span>,
501 impl<'a> NestedImplTraitVisitor<'a> {
502 fn with_impl_trait<F>(&mut self, outer_impl_trait: Option<Span>, f: F)
503 where F: FnOnce(&mut NestedImplTraitVisitor<'a>)
505 let old_outer_impl_trait = self.outer_impl_trait;
506 self.outer_impl_trait = outer_impl_trait;
508 self.outer_impl_trait = old_outer_impl_trait;
513 impl<'a> Visitor<'a> for NestedImplTraitVisitor<'a> {
514 fn visit_ty(&mut self, t: &'a Ty) {
515 if let TyKind::ImplTrait(..) = t.node {
516 if let Some(outer_impl_trait) = self.outer_impl_trait {
517 struct_span_err!(self.session, t.span, E0666,
518 "nested `impl Trait` is not allowed")
519 .span_label(outer_impl_trait, "outer `impl Trait`")
520 .span_label(t.span, "nested `impl Trait` here")
524 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t));
526 visit::walk_ty(self, t);
529 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
530 match *generic_args {
531 GenericArgs::AngleBracketed(ref data) => {
532 for arg in &data.args {
533 self.visit_generic_arg(arg)
535 for type_binding in &data.bindings {
536 // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
537 // are allowed to contain nested `impl Trait`.
538 self.with_impl_trait(None, |this| visit::walk_ty(this, &type_binding.ty));
541 GenericArgs::Parenthesized(ref data) => {
542 for type_ in &data.inputs {
543 self.visit_ty(type_);
545 if let Some(ref type_) = data.output {
546 // `-> Foo` syntax is essentially an associated type binding,
547 // so it is also allowed to contain nested `impl Trait`.
548 self.with_impl_trait(None, |this| visit::walk_ty(this, type_));
554 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
555 // covered in AstValidator
559 // Bans `impl Trait` in path projections like `<impl Iterator>::Item` or `Foo::Bar<impl Trait>`.
560 struct ImplTraitProjectionVisitor<'a> {
561 session: &'a Session,
565 impl<'a> ImplTraitProjectionVisitor<'a> {
566 fn with_ban<F>(&mut self, f: F)
567 where F: FnOnce(&mut ImplTraitProjectionVisitor<'a>)
569 let old_is_banned = self.is_banned;
570 self.is_banned = true;
572 self.is_banned = old_is_banned;
576 impl<'a> Visitor<'a> for ImplTraitProjectionVisitor<'a> {
577 fn visit_ty(&mut self, t: &'a Ty) {
579 TyKind::ImplTrait(..) => {
581 struct_span_err!(self.session, t.span, E0667,
582 "`impl Trait` is not allowed in path parameters").emit();
585 TyKind::Path(ref qself, ref path) => {
587 // - `Option<impl Trait>`
588 // - `option::Option<impl Trait>`
589 // - `option::Option<T>::Foo<impl Trait>
592 // - `<impl Trait>::Foo`
593 // - `option::Option<impl Trait>::Foo`.
595 // To implement this, we disallow `impl Trait` from `qself`
596 // (for cases like `<impl Trait>::Foo>`)
597 // but we allow `impl Trait` in `GenericArgs`
598 // iff there are no more PathSegments.
599 if let Some(ref qself) = *qself {
600 // `impl Trait` in `qself` is always illegal
601 self.with_ban(|this| this.visit_ty(&qself.ty));
604 for (i, segment) in path.segments.iter().enumerate() {
605 // Allow `impl Trait` iff we're on the final path segment
606 if i == path.segments.len() - 1 {
607 visit::walk_path_segment(self, path.span, segment);
610 visit::walk_path_segment(this, path.span, segment));
614 _ => visit::walk_ty(self, t),
618 fn visit_mac(&mut self, _mac: &Spanned<Mac_>) {
619 // covered in AstValidator
623 pub fn check_crate(session: &Session, krate: &Crate) {
625 &mut NestedImplTraitVisitor {
627 outer_impl_trait: None,
631 &mut ImplTraitProjectionVisitor {
636 visit::walk_crate(&mut AstValidator { session }, krate)