]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/ast_validation.rs
Rollup merge of #57867 - Aaron1011:fix/gen-future-doc, r=Centril
[rust.git] / src / librustc_passes / ast_validation.rs
1 // Validate AST before lowering it to HIR
2 //
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.
8
9 use std::mem;
10 use rustc::lint;
11 use rustc::session::Session;
12 use syntax::ast::*;
13 use syntax::attr;
14 use syntax::source_map::Spanned;
15 use syntax::symbol::keywords;
16 use syntax::ptr::P;
17 use syntax::visit::{self, Visitor};
18 use syntax_pos::Span;
19 use errors;
20 use errors::Applicability;
21
22 struct AstValidator<'a> {
23     session: &'a Session,
24
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>,
29
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,
33 }
34
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);
38         f(self);
39         self.is_impl_trait_banned = old;
40     }
41
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);
44         f(self);
45         self.outer_impl_trait = old;
46     }
47
48     // Mirrors visit::walk_ty, but tracks relevant state
49     fn walk_ty(&mut self, t: &'a Ty) {
50         match t.node {
51             TyKind::ImplTrait(..) => {
52                 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
53             }
54             TyKind::Path(ref qself, ref path) => {
55                 // We allow these:
56                 //  - `Option<impl Trait>`
57                 //  - `option::Option<impl Trait>`
58                 //  - `option::Option<T>::Foo<impl Trait>
59                 //
60                 // But not these:
61                 //  - `<impl Trait>::Foo`
62                 //  - `option::Option<impl Trait>::Foo`.
63                 //
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));
71                 }
72
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);
80                     } else {
81                         self.with_banned_impl_trait(|this| {
82                             this.visit_path_segment(path.span, segment)
83                         });
84                     }
85                 }
86             }
87             _ => visit::walk_ty(self, t),
88         }
89     }
90
91     fn err_handler(&self) -> &errors::Handler {
92         &self.session.diagnostic()
93     }
94
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");
101         }
102     }
103
104     fn check_label(&self, ident: Ident) {
105         if ident.without_first_quote().is_reserved() {
106             self.err_handler()
107                 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
108         }
109     }
110
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");
116         }
117     }
118
119     fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
120         if let VisibilityKind::Inherited = vis.node {
121             return
122         }
123
124         let mut err = struct_span_err!(self.session,
125                                         vis.span,
126                                         E0449,
127                                         "unnecessary visibility qualifier");
128         if vis.node.is_pub() {
129             err.span_label(vis.span, "`pub` not permitted here because it's implied");
130         }
131         if let Some(note) = note {
132             err.note(note);
133         }
134         err.emit();
135     }
136
137     fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
138         for arg in &decl.inputs {
139             match arg.pat.node {
140                 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
141                 PatKind::Wild => {}
142                 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
143                     report_err(arg.pat.span, true),
144                 _ => report_err(arg.pat.span, false),
145             }
146         }
147     }
148
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()
153         }
154     }
155
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")
161                 .emit();
162         }
163     }
164
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_));
170                 if is_trait {
171                     err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
172                 }
173                 err.emit();
174             }
175         }
176     }
177
178     /// matches '-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus),
179     /// or path for ranges.
180     ///
181     /// FIXME: do we want to allow expr -> pattern conversion to create path expressions?
182     /// That means making this work:
183     ///
184     /// ```rust,ignore (FIXME)
185     ///     struct S;
186     ///     macro_rules! m {
187     ///         ($a:expr) => {
188     ///             let $a = S;
189     ///         }
190     ///     }
191     ///     m!(S);
192     /// ```
193     fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
194         match expr.node {
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 \
200                                                          in patterns")
201         }
202     }
203
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();
211                     self.err_handler()
212                         .span_err(spans, "lifetime bounds cannot be used in this context");
213                 }
214                 None
215             }
216             _ => Some(param.ident.span),
217         }).collect();
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");
221         }
222     }
223
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())
230             );
231
232             err.note(
233                 "this will be a error until the `let_chains` feature is stabilized"
234             );
235             err.note(
236                 "see rust-lang/rust#53668 for more information"
237             );
238
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,
243                 );
244             }
245
246             err.emit();
247         }
248     }
249
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);
256         match &expr.node {
257             ExprKind::Binary(op, _, _) if op.node == BinOpKind::And || op.node == BinOpKind::Or => {
258                 Some((expr.span, op.node))
259             },
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));
265
266                 lhs_ambiguous.or(rhs_ambiguous)
267             }
268             _ => None,
269         }
270     }
271
272 }
273
274 impl<'a> Visitor<'a> for AstValidator<'a> {
275     fn visit_expr(&mut self, expr: &'a Expr) {
276         match expr.node {
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");
281             }
282             ExprKind::ObsoleteInPlace(ref place, ref val) => {
283                 let mut err = self.err_handler().struct_span_err(
284                     expr.span,
285                     "emplacement syntax is obsolete (for now, anyway)",
286                 );
287                 err.note(
288                     "for more information, see \
289                      <https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"
290                 );
291                 match val.node {
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 `-`",
297                             "< -".to_string(),
298                             Applicability::MaybeIncorrect
299                         );
300                     }
301                     _ => {}
302                 }
303                 err.emit();
304             }
305             _ => {}
306         }
307
308         visit::walk_expr(self, expr)
309     }
310
311     fn visit_ty(&mut self, ty: &'a Ty) {
312         match ty.node {
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();
317                 });
318                 self.check_late_bound_lifetime_defs(&bfty.generic_params);
319             }
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");
327                             break;
328                         }
329                         any_lifetime_bounds = true;
330                     }
331                 }
332                 self.no_questions_in_bounds(bounds, "trait object types", false);
333             }
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();
338                 }
339
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")
345                         .emit();
346
347                 }
348                 if !bounds.iter()
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");
351                 }
352             }
353             _ => {}
354         }
355
356         self.walk_ty(ty)
357     }
358
359     fn visit_label(&mut self, label: &'a Label) {
360         self.check_label(label.ident);
361         visit::walk_label(self, label);
362     }
363
364     fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
365         self.check_lifetime(lifetime.ident);
366         visit::walk_lifetime(self, lifetime);
367     }
368
369     fn visit_item(&mut self, item: &'a Item) {
370         match item.node {
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 {
374                     self.err_handler()
375                         .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
376                         .help("use `auto trait Trait {}` instead").emit();
377                 }
378                 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
379                     span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
380                 }
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);
386                     }
387                 }
388             }
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");
394                 }
395                 if polarity == ImplPolarity::Negative {
396                     self.err_handler().span_err(item.span, "inherent impls cannot be negative");
397                 }
398                 if defaultness == Defaultness::Default {
399                     self.err_handler()
400                         .struct_span_err(item.span, "inherent impls cannot be default")
401                         .note("only trait implementations may be annotated with default").emit();
402                 }
403             }
404             ItemKind::ForeignMod(..) => {
405                 self.invalid_visibility(
406                     &item.vis,
407                     Some("place qualifiers on individual foreign items instead"),
408                 );
409             }
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);
415                     }
416                 }
417             }
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();
424                     }
425                     if !bounds.is_empty() {
426                         struct_span_err!(self.session, item.span, E0568,
427                                         "auto traits cannot have super traits").emit();
428                     }
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();
432                     }
433                 }
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);
439                         if block.is_none() {
440                             self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
441                                 if mut_ident {
442                                     self.session.buffer_lint(
443                                         lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
444                                         trait_item.id, span,
445                                         "patterns aren't allowed in methods without bodies");
446                                 } else {
447                                     struct_span_err!(self.session, span, E0642,
448                                         "patterns aren't allowed in methods without bodies").emit();
449                                 }
450                             });
451                         }
452                     }
453                 }
454             }
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);
462                 }
463             }
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");
468                 }
469                 if vdata.fields().is_empty() {
470                     self.err_handler().span_err(item.span,
471                                                 "unions cannot have zero fields");
472                 }
473             }
474             _ => {}
475         }
476
477         visit::walk_item(self, item)
478     }
479
480     fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
481         match fi.node {
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();
487                 });
488             }
489             ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
490         }
491
492         visit::walk_foreign_item(self, fi)
493     }
494
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);
504                 });
505             }
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_));
512                 }
513             }
514         }
515     }
516
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 (&param.kind, seen_non_lifetime_param) {
522                 (GenericParamKind::Lifetime { .. }, true) => {
523                     self.err_handler()
524                         .span_err(param.ident.span, "lifetime parameters must be leading");
525                 },
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 {
532                         self.err_handler()
533                             .span_err(span, "type parameters with a default must be trailing");
534                         break;
535                     }
536                 }
537             }
538         }
539         for predicate in &generics.where_clause.predicates {
540             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
541                 self.err_handler()
542                     .span_err(predicate.span, "equality constraints are not yet \
543                                                supported in where clauses (see #20041)");
544             }
545         }
546         visit::walk_generics(self, generics)
547     }
548
549     fn visit_generic_param(&mut self, param: &'a GenericParam) {
550         if let GenericParamKind::Lifetime { .. } = param.kind {
551             self.check_lifetime(param.ident);
552         }
553         visit::walk_generic_param(self, param);
554     }
555
556     fn visit_pat(&mut self, pat: &'a Pat) {
557         match pat.node {
558             PatKind::Lit(ref expr) => {
559                 self.check_expr_within_pat(expr, false);
560             }
561             PatKind::Range(ref start, ref end, _) => {
562                 self.check_expr_within_pat(start, true);
563                 self.check_expr_within_pat(end, true);
564             }
565             _ => {}
566         }
567
568         visit::walk_pat(self, pat)
569     }
570
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);
575         }
576         visit::walk_where_predicate(self, p);
577     }
578
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);
582     }
583
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`?");
590     }
591 }
592
593 pub fn check_crate(session: &Session, krate: &Crate) {
594     visit::walk_crate(&mut AstValidator {
595         session,
596         outer_impl_trait: None,
597         is_impl_trait_banned: false,
598     }, krate)
599 }