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};
20 use errors::Applicability;
22 struct AstValidator<'a> {
25 // Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
26 // Nested `impl Trait` _is_ allowed in associated type position,
27 // e.g `impl Iterator<Item=impl Debug>`
28 outer_impl_trait: Option<Span>,
30 // Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
31 // or `Foo::Bar<impl Trait>`
32 is_impl_trait_banned: bool,
35 impl<'a> AstValidator<'a> {
36 fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
37 let old = mem::replace(&mut self.is_impl_trait_banned, true);
39 self.is_impl_trait_banned = old;
42 fn with_impl_trait(&mut self, outer_impl_trait: Option<Span>, f: impl FnOnce(&mut Self)) {
43 let old = mem::replace(&mut self.outer_impl_trait, outer_impl_trait);
45 self.outer_impl_trait = old;
48 // Mirrors visit::walk_ty, but tracks relevant state
49 fn walk_ty(&mut self, t: &'a Ty) {
51 TyKind::ImplTrait(..) => {
52 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
54 TyKind::Path(ref qself, ref path) => {
56 // - `Option<impl Trait>`
57 // - `option::Option<impl Trait>`
58 // - `option::Option<T>::Foo<impl Trait>
61 // - `<impl Trait>::Foo`
62 // - `option::Option<impl Trait>::Foo`.
64 // To implement this, we disallow `impl Trait` from `qself`
65 // (for cases like `<impl Trait>::Foo>`)
66 // but we allow `impl Trait` in `GenericArgs`
67 // iff there are no more PathSegments.
68 if let Some(ref qself) = *qself {
69 // `impl Trait` in `qself` is always illegal
70 self.with_banned_impl_trait(|this| this.visit_ty(&qself.ty));
73 // Note that there should be a call to visit_path here,
74 // so if any logic is added to process `Path`s a call to it should be
75 // added both in visit_path and here. This code mirrors visit::walk_path.
76 for (i, segment) in path.segments.iter().enumerate() {
77 // Allow `impl Trait` iff we're on the final path segment
78 if i == path.segments.len() - 1 {
79 self.visit_path_segment(path.span, segment);
81 self.with_banned_impl_trait(|this| {
82 this.visit_path_segment(path.span, segment)
87 _ => visit::walk_ty(self, t),
91 fn err_handler(&self) -> &errors::Handler {
92 &self.session.diagnostic()
95 fn check_lifetime(&self, ident: Ident) {
96 let valid_names = [keywords::UnderscoreLifetime.name(),
97 keywords::StaticLifetime.name(),
98 keywords::Invalid.name()];
99 if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
100 self.err_handler().span_err(ident.span, "lifetimes cannot use keyword names");
104 fn check_label(&self, ident: Ident) {
105 if ident.without_first_quote().is_reserved() {
107 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
111 fn invalid_non_exhaustive_attribute(&self, variant: &Variant) {
112 let has_non_exhaustive = attr::contains_name(&variant.node.attrs, "non_exhaustive");
113 if has_non_exhaustive {
114 self.err_handler().span_err(variant.span,
115 "#[non_exhaustive] is not yet supported on variants");
119 fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
120 if let VisibilityKind::Inherited = vis.node {
124 let mut err = struct_span_err!(self.session,
127 "unnecessary visibility qualifier");
128 if vis.node.is_pub() {
129 err.span_label(vis.span, "`pub` not permitted here because it's implied");
131 if let Some(note) = note {
137 fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
138 for arg in &decl.inputs {
140 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
142 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
143 report_err(arg.pat.span, true),
144 _ => report_err(arg.pat.span, false),
149 fn check_trait_fn_not_async(&self, span: Span, asyncness: IsAsync) {
150 if asyncness.is_async() {
151 struct_span_err!(self.session, span, E0706,
152 "trait fns cannot be declared `async`").emit()
156 fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
157 if constness.node == Constness::Const {
158 struct_span_err!(self.session, constness.span, E0379,
159 "trait fns cannot be declared const")
160 .span_label(constness.span, "trait fns cannot be const")
165 fn no_questions_in_bounds(&self, bounds: &GenericBounds, where_: &str, is_trait: bool) {
166 for bound in bounds {
167 if let GenericBound::Trait(ref poly, TraitBoundModifier::Maybe) = *bound {
168 let mut err = self.err_handler().struct_span_err(poly.span,
169 &format!("`?Trait` is not permitted in {}", where_));
171 err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
178 /// matches '-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus),
179 /// or path for ranges.
181 /// FIXME: do we want to allow expr -> pattern conversion to create path expressions?
182 /// That means making this work:
184 /// ```rust,ignore (FIXME)
193 fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
195 ExprKind::Lit(..) => {}
196 ExprKind::Path(..) if allow_paths => {}
197 ExprKind::Unary(UnOp::Neg, ref inner)
198 if match inner.node { ExprKind::Lit(_) => true, _ => false } => {}
199 _ => self.err_handler().span_err(expr.span, "arbitrary expressions aren't allowed \
204 fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) {
205 // Check only lifetime parameters are present and that the lifetime
206 // parameters that are present have no bounds.
207 let non_lt_param_spans: Vec<_> = params.iter().filter_map(|param| match param.kind {
208 GenericParamKind::Lifetime { .. } => {
209 if !param.bounds.is_empty() {
210 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
212 .span_err(spans, "lifetime bounds cannot be used in this context");
216 _ => Some(param.ident.span),
218 if !non_lt_param_spans.is_empty() {
219 self.err_handler().span_err(non_lt_param_spans,
220 "only lifetime parameters can be used in this context");
224 /// With eRFC 2497, we need to check whether an expression is ambiguous and warn or error
225 /// depending on the edition, this function handles that.
226 fn while_if_let_ambiguity(&self, expr: &P<Expr>) {
227 if let Some((span, op_kind)) = self.while_if_let_expr_ambiguity(&expr) {
228 let mut err = self.err_handler().struct_span_err(
229 span, &format!("ambiguous use of `{}`", op_kind.to_string())
233 "this will be a error until the `let_chains` feature is stabilized"
236 "see rust-lang/rust#53668 for more information"
239 if let Ok(snippet) = self.session.source_map().span_to_snippet(span) {
240 err.span_suggestion_with_applicability(
241 span, "consider adding parentheses", format!("({})", snippet),
242 Applicability::MachineApplicable,
250 /// With eRFC 2497 adding if-let chains, there is a requirement that the parsing of
251 /// `&&` and `||` in a if-let statement be unambiguous. This function returns a span and
252 /// a `BinOpKind` (either `&&` or `||` depending on what was ambiguous) if it is determined
253 /// that the current expression parsed is ambiguous and will break in future.
254 fn while_if_let_expr_ambiguity(&self, expr: &P<Expr>) -> Option<(Span, BinOpKind)> {
255 debug!("while_if_let_expr_ambiguity: expr.node: {:?}", expr.node);
257 ExprKind::Binary(op, _, _) if op.node == BinOpKind::And || op.node == BinOpKind::Or => {
258 Some((expr.span, op.node))
260 ExprKind::Range(ref lhs, ref rhs, _) => {
261 let lhs_ambiguous = lhs.as_ref()
262 .and_then(|lhs| self.while_if_let_expr_ambiguity(lhs));
263 let rhs_ambiguous = rhs.as_ref()
264 .and_then(|rhs| self.while_if_let_expr_ambiguity(rhs));
266 lhs_ambiguous.or(rhs_ambiguous)
274 impl<'a> Visitor<'a> for AstValidator<'a> {
275 fn visit_expr(&mut self, expr: &'a Expr) {
277 ExprKind::IfLet(_, ref expr, _, _) | ExprKind::WhileLet(_, ref expr, _, _) =>
278 self.while_if_let_ambiguity(&expr),
279 ExprKind::InlineAsm(..) if !self.session.target.target.options.allow_asm => {
280 span_err!(self.session, expr.span, E0472, "asm! is unsupported on this target");
282 ExprKind::ObsoleteInPlace(ref place, ref val) => {
283 let mut err = self.err_handler().struct_span_err(
285 "emplacement syntax is obsolete (for now, anyway)",
288 "for more information, see \
289 <https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"
292 ExprKind::Lit(ref v) if v.node.is_numeric() => {
293 err.span_suggestion_with_applicability(
294 place.span.between(val.span),
295 "if you meant to write a comparison against a negative value, add a \
296 space in between `<` and `-`",
298 Applicability::MaybeIncorrect
308 visit::walk_expr(self, expr)
311 fn visit_ty(&mut self, ty: &'a Ty) {
313 TyKind::BareFn(ref bfty) => {
314 self.check_decl_no_pat(&bfty.decl, |span, _| {
315 struct_span_err!(self.session, span, E0561,
316 "patterns aren't allowed in function pointer types").emit();
318 self.check_late_bound_lifetime_defs(&bfty.generic_params);
320 TyKind::TraitObject(ref bounds, ..) => {
321 let mut any_lifetime_bounds = false;
322 for bound in bounds {
323 if let GenericBound::Outlives(ref lifetime) = *bound {
324 if any_lifetime_bounds {
325 span_err!(self.session, lifetime.ident.span, E0226,
326 "only a single explicit lifetime bound is permitted");
329 any_lifetime_bounds = true;
332 self.no_questions_in_bounds(bounds, "trait object types", false);
334 TyKind::ImplTrait(_, ref bounds) => {
335 if self.is_impl_trait_banned {
336 struct_span_err!(self.session, ty.span, E0667,
337 "`impl Trait` is not allowed in path parameters").emit();
340 if let Some(outer_impl_trait) = self.outer_impl_trait {
341 struct_span_err!(self.session, ty.span, E0666,
342 "nested `impl Trait` is not allowed")
343 .span_label(outer_impl_trait, "outer `impl Trait`")
344 .span_label(ty.span, "nested `impl Trait` here")
349 .any(|b| if let GenericBound::Trait(..) = *b { true } else { false }) {
350 self.err_handler().span_err(ty.span, "at least one trait must be specified");
359 fn visit_label(&mut self, label: &'a Label) {
360 self.check_label(label.ident);
361 visit::walk_label(self, label);
364 fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
365 self.check_lifetime(lifetime.ident);
366 visit::walk_lifetime(self, lifetime);
369 fn visit_item(&mut self, item: &'a Item) {
371 ItemKind::Impl(unsafety, polarity, _, _, Some(..), ref ty, ref impl_items) => {
372 self.invalid_visibility(&item.vis, None);
373 if let TyKind::Err = ty.node {
375 .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
376 .help("use `auto trait Trait {}` instead").emit();
378 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
379 span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
381 for impl_item in impl_items {
382 self.invalid_visibility(&impl_item.vis, None);
383 if let ImplItemKind::Method(ref sig, _) = impl_item.node {
384 self.check_trait_fn_not_const(sig.header.constness);
385 self.check_trait_fn_not_async(impl_item.span, sig.header.asyncness);
389 ItemKind::Impl(unsafety, polarity, defaultness, _, None, _, _) => {
390 self.invalid_visibility(&item.vis,
391 Some("place qualifiers on individual impl items instead"));
392 if unsafety == Unsafety::Unsafe {
393 span_err!(self.session, item.span, E0197, "inherent impls cannot be unsafe");
395 if polarity == ImplPolarity::Negative {
396 self.err_handler().span_err(item.span, "inherent impls cannot be negative");
398 if defaultness == Defaultness::Default {
400 .struct_span_err(item.span, "inherent impls cannot be default")
401 .note("only trait implementations may be annotated with default").emit();
404 ItemKind::ForeignMod(..) => {
405 self.invalid_visibility(
407 Some("place qualifiers on individual foreign items instead"),
410 ItemKind::Enum(ref def, _) => {
411 for variant in &def.variants {
412 self.invalid_non_exhaustive_attribute(variant);
413 for field in variant.node.data.fields() {
414 self.invalid_visibility(&field.vis, None);
418 ItemKind::Trait(is_auto, _, ref generics, ref bounds, ref trait_items) => {
419 if is_auto == IsAuto::Yes {
420 // Auto traits cannot have generics, super traits nor contain items.
421 if !generics.params.is_empty() {
422 struct_span_err!(self.session, item.span, E0567,
423 "auto traits cannot have generic parameters").emit();
425 if !bounds.is_empty() {
426 struct_span_err!(self.session, item.span, E0568,
427 "auto traits cannot have super traits").emit();
429 if !trait_items.is_empty() {
430 struct_span_err!(self.session, item.span, E0380,
431 "auto traits cannot have methods or associated items").emit();
434 self.no_questions_in_bounds(bounds, "supertraits", true);
435 for trait_item in trait_items {
436 if let TraitItemKind::Method(ref sig, ref block) = trait_item.node {
437 self.check_trait_fn_not_async(trait_item.span, sig.header.asyncness);
438 self.check_trait_fn_not_const(sig.header.constness);
440 self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
442 self.session.buffer_lint(
443 lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
445 "patterns aren't allowed in methods without bodies");
447 struct_span_err!(self.session, span, E0642,
448 "patterns aren't allowed in methods without bodies").emit();
455 ItemKind::Mod(_) => {
456 // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).
457 attr::first_attr_value_str_by_name(&item.attrs, "path");
458 if attr::contains_name(&item.attrs, "warn_directory_ownership") {
459 let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
460 let msg = "cannot declare a new module at this location";
461 self.session.buffer_lint(lint, item.id, item.span, msg);
464 ItemKind::Union(ref vdata, _) => {
465 if !vdata.is_struct() {
466 self.err_handler().span_err(item.span,
467 "tuple and unit unions are not permitted");
469 if vdata.fields().is_empty() {
470 self.err_handler().span_err(item.span,
471 "unions cannot have zero fields");
477 visit::walk_item(self, item)
480 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
482 ForeignItemKind::Fn(ref decl, _) => {
483 self.check_decl_no_pat(decl, |span, _| {
484 struct_span_err!(self.session, span, E0130,
485 "patterns aren't allowed in foreign function declarations")
486 .span_label(span, "pattern not allowed in foreign function").emit();
489 ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
492 visit::walk_foreign_item(self, fi)
495 // Mirrors visit::walk_generic_args, but tracks relevant state
496 fn visit_generic_args(&mut self, _: Span, generic_args: &'a GenericArgs) {
497 match *generic_args {
498 GenericArgs::AngleBracketed(ref data) => {
499 walk_list!(self, visit_generic_arg, &data.args);
500 // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
501 // are allowed to contain nested `impl Trait`.
502 self.with_impl_trait(None, |this| {
503 walk_list!(this, visit_assoc_type_binding, &data.bindings);
506 GenericArgs::Parenthesized(ref data) => {
507 walk_list!(self, visit_ty, &data.inputs);
508 if let Some(ref type_) = data.output {
509 // `-> Foo` syntax is essentially an associated type binding,
510 // so it is also allowed to contain nested `impl Trait`.
511 self.with_impl_trait(None, |this| visit::walk_ty(this, type_));
517 fn visit_generics(&mut self, generics: &'a Generics) {
518 let mut seen_non_lifetime_param = false;
519 let mut seen_default = None;
520 for param in &generics.params {
521 match (¶m.kind, seen_non_lifetime_param) {
522 (GenericParamKind::Lifetime { .. }, true) => {
524 .span_err(param.ident.span, "lifetime parameters must be leading");
526 (GenericParamKind::Lifetime { .. }, false) => {}
527 (GenericParamKind::Type { ref default, .. }, _) => {
528 seen_non_lifetime_param = true;
529 if default.is_some() {
530 seen_default = Some(param.ident.span);
531 } else if let Some(span) = seen_default {
533 .span_err(span, "type parameters with a default must be trailing");
539 for predicate in &generics.where_clause.predicates {
540 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
542 .span_err(predicate.span, "equality constraints are not yet \
543 supported in where clauses (see #20041)");
546 visit::walk_generics(self, generics)
549 fn visit_generic_param(&mut self, param: &'a GenericParam) {
550 if let GenericParamKind::Lifetime { .. } = param.kind {
551 self.check_lifetime(param.ident);
553 visit::walk_generic_param(self, param);
556 fn visit_pat(&mut self, pat: &'a Pat) {
558 PatKind::Lit(ref expr) => {
559 self.check_expr_within_pat(expr, false);
561 PatKind::Range(ref start, ref end, _) => {
562 self.check_expr_within_pat(start, true);
563 self.check_expr_within_pat(end, true);
568 visit::walk_pat(self, pat)
571 fn visit_where_predicate(&mut self, p: &'a WherePredicate) {
572 if let &WherePredicate::BoundPredicate(ref bound_predicate) = p {
573 // A type binding, eg `for<'c> Foo: Send+Clone+'c`
574 self.check_late_bound_lifetime_defs(&bound_predicate.bound_generic_params);
576 visit::walk_where_predicate(self, p);
579 fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef, m: &'a TraitBoundModifier) {
580 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
581 visit::walk_poly_trait_ref(self, t, m);
584 fn visit_mac(&mut self, mac: &Spanned<Mac_>) {
585 // when a new macro kind is added but the author forgets to set it up for expansion
586 // because that's the only part that won't cause a compiler error
587 self.session.diagnostic()
588 .span_bug(mac.span, "macro invocation missed in expansion; did you forget to override \
589 the relevant `fold_*()` method in `PlaceholderExpander`?");
593 pub fn check_crate(session: &Session, krate: &Crate) {
594 visit::walk_crate(&mut AstValidator {
596 outer_impl_trait: None,
597 is_impl_trait_banned: false,