]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/ast_validation.rs
submodule: update rls from c9d25b667a to f331ff7
[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_ext::proc_macro_decls::is_proc_macro_attr;
19 use syntax_pos::Span;
20 use errors;
21 use errors::Applicability;
22
23 struct AstValidator<'a> {
24     session: &'a Session,
25     has_proc_macro_decls: bool,
26     has_global_allocator: bool,
27
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>,
32
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,
36 }
37
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);
41         f(self);
42         self.is_impl_trait_banned = old;
43     }
44
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);
47         f(self);
48         self.outer_impl_trait = old;
49     }
50
51     // Mirrors visit::walk_ty, but tracks relevant state
52     fn walk_ty(&mut self, t: &'a Ty) {
53         match t.node {
54             TyKind::ImplTrait(..) => {
55                 self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
56             }
57             TyKind::Path(ref qself, ref path) => {
58                 // We allow these:
59                 //  - `Option<impl Trait>`
60                 //  - `option::Option<impl Trait>`
61                 //  - `option::Option<T>::Foo<impl Trait>
62                 //
63                 // But not these:
64                 //  - `<impl Trait>::Foo`
65                 //  - `option::Option<impl Trait>::Foo`.
66                 //
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));
74                 }
75
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);
83                     } else {
84                         self.with_banned_impl_trait(|this| {
85                             this.visit_path_segment(path.span, segment)
86                         });
87                     }
88                 }
89             }
90             _ => visit::walk_ty(self, t),
91         }
92     }
93
94     fn err_handler(&self) -> &errors::Handler {
95         &self.session.diagnostic()
96     }
97
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");
104         }
105     }
106
107     fn check_label(&self, ident: Ident) {
108         if ident.without_first_quote().is_reserved() {
109             self.err_handler()
110                 .span_err(ident.span, &format!("invalid label name `{}`", ident.name));
111         }
112     }
113
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");
119         }
120     }
121
122     fn invalid_visibility(&self, vis: &Visibility, note: Option<&str>) {
123         if let VisibilityKind::Inherited = vis.node {
124             return
125         }
126
127         let mut err = struct_span_err!(self.session,
128                                         vis.span,
129                                         E0449,
130                                         "unnecessary visibility qualifier");
131         if vis.node.is_pub() {
132             err.span_label(vis.span, "`pub` not permitted here because it's implied");
133         }
134         if let Some(note) = note {
135             err.note(note);
136         }
137         err.emit();
138     }
139
140     fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
141         for arg in &decl.inputs {
142             match arg.pat.node {
143                 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
144                 PatKind::Wild => {}
145                 PatKind::Ident(BindingMode::ByValue(Mutability::Mutable), _, None) =>
146                     report_err(arg.pat.span, true),
147                 _ => report_err(arg.pat.span, false),
148             }
149         }
150     }
151
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()
156         }
157     }
158
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")
164                 .emit();
165         }
166     }
167
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_));
173                 if is_trait {
174                     err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
175                 }
176                 err.emit();
177             }
178         }
179     }
180
181     /// matches '-' lit | lit (cf. parser::Parser::parse_literal_maybe_minus),
182     /// or path for ranges.
183     ///
184     /// FIXME: do we want to allow expr -> pattern conversion to create path expressions?
185     /// That means making this work:
186     ///
187     /// ```rust,ignore (FIXME)
188     ///     struct S;
189     ///     macro_rules! m {
190     ///         ($a:expr) => {
191     ///             let $a = S;
192     ///         }
193     ///     }
194     ///     m!(S);
195     /// ```
196     fn check_expr_within_pat(&self, expr: &Expr, allow_paths: bool) {
197         match expr.node {
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 \
203                                                          in patterns")
204         }
205     }
206
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();
214                     self.err_handler()
215                         .span_err(spans, "lifetime bounds cannot be used in this context");
216                 }
217                 None
218             }
219             _ => Some(param.ident.span),
220         }).collect();
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");
224         }
225     }
226
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())
233             );
234
235             err.note(
236                 "this will be a error until the `let_chains` feature is stabilized"
237             );
238             err.note(
239                 "see rust-lang/rust#53668 for more information"
240             );
241
242             if let Ok(snippet) = self.session.source_map().span_to_snippet(span) {
243                 err.span_suggestion(
244                     span, "consider adding parentheses", format!("({})", snippet),
245                     Applicability::MachineApplicable,
246                 );
247             }
248
249             err.emit();
250         }
251     }
252
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);
259         match &expr.node {
260             ExprKind::Binary(op, _, _) if op.node == BinOpKind::And || op.node == BinOpKind::Or => {
261                 Some((expr.span, op.node))
262             },
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));
268
269                 lhs_ambiguous.or(rhs_ambiguous)
270             }
271             _ => None,
272         }
273     }
274
275 }
276
277 impl<'a> Visitor<'a> for AstValidator<'a> {
278     fn visit_expr(&mut self, expr: &'a Expr) {
279         match expr.node {
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");
284             }
285             ExprKind::ObsoleteInPlace(ref place, ref val) => {
286                 let mut err = self.err_handler().struct_span_err(
287                     expr.span,
288                     "emplacement syntax is obsolete (for now, anyway)",
289                 );
290                 err.note(
291                     "for more information, see \
292                      <https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"
293                 );
294                 match val.node {
295                     ExprKind::Lit(ref v) if v.node.is_numeric() => {
296                         err.span_suggestion(
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 `-`",
300                             "< -".to_string(),
301                             Applicability::MaybeIncorrect
302                         );
303                     }
304                     _ => {}
305                 }
306                 err.emit();
307             }
308             _ => {}
309         }
310
311         visit::walk_expr(self, expr)
312     }
313
314     fn visit_ty(&mut self, ty: &'a Ty) {
315         match ty.node {
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();
320                 });
321                 self.check_late_bound_lifetime_defs(&bfty.generic_params);
322             }
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");
330                             break;
331                         }
332                         any_lifetime_bounds = true;
333                     }
334                 }
335                 self.no_questions_in_bounds(bounds, "trait object types", false);
336             }
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();
341                 }
342
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")
348                         .emit();
349
350                 }
351                 if !bounds.iter()
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");
354                 }
355             }
356             _ => {}
357         }
358
359         self.walk_ty(ty)
360     }
361
362     fn visit_label(&mut self, label: &'a Label) {
363         self.check_label(label.ident);
364         visit::walk_label(self, label);
365     }
366
367     fn visit_lifetime(&mut self, lifetime: &'a Lifetime) {
368         self.check_lifetime(lifetime.ident);
369         visit::walk_lifetime(self, lifetime);
370     }
371
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;
375         }
376
377         if attr::contains_name(&item.attrs, "global_allocator") {
378             self.has_global_allocator = true;
379         }
380
381         match item.node {
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 {
385                     self.err_handler()
386                         .struct_span_err(item.span, "`impl Trait for .. {}` is an obsolete syntax")
387                         .help("use `auto trait Trait {}` instead").emit();
388                 }
389                 if unsafety == Unsafety::Unsafe && polarity == ImplPolarity::Negative {
390                     span_err!(self.session, item.span, E0198, "negative impls cannot be unsafe");
391                 }
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);
397                     }
398                 }
399             }
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");
405                 }
406                 if polarity == ImplPolarity::Negative {
407                     self.err_handler().span_err(item.span, "inherent impls cannot be negative");
408                 }
409                 if defaultness == Defaultness::Default {
410                     self.err_handler()
411                         .struct_span_err(item.span, "inherent impls cannot be default")
412                         .note("only trait implementations may be annotated with default").emit();
413                 }
414             }
415             ItemKind::ForeignMod(..) => {
416                 self.invalid_visibility(
417                     &item.vis,
418                     Some("place qualifiers on individual foreign items instead"),
419                 );
420             }
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);
426                     }
427                 }
428             }
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();
435                     }
436                     if !bounds.is_empty() {
437                         struct_span_err!(self.session, item.span, E0568,
438                                         "auto traits cannot have super traits").emit();
439                     }
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();
443                     }
444                 }
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);
450                         if block.is_none() {
451                             self.check_decl_no_pat(&sig.decl, |span, mut_ident| {
452                                 if mut_ident {
453                                     self.session.buffer_lint(
454                                         lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
455                                         trait_item.id, span,
456                                         "patterns aren't allowed in methods without bodies");
457                                 } else {
458                                     struct_span_err!(self.session, span, E0642,
459                                         "patterns aren't allowed in methods without bodies").emit();
460                                 }
461                             });
462                         }
463                     }
464                 }
465             }
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);
473                 }
474             }
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");
479                 }
480                 if vdata.fields().is_empty() {
481                     self.err_handler().span_err(item.span,
482                                                 "unions cannot have zero fields");
483                 }
484             }
485             _ => {}
486         }
487
488         visit::walk_item(self, item)
489     }
490
491     fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
492         match fi.node {
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();
498                 });
499             }
500             ForeignItemKind::Static(..) | ForeignItemKind::Ty | ForeignItemKind::Macro(..) => {}
501         }
502
503         visit::walk_foreign_item(self, fi)
504     }
505
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);
515                 });
516             }
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_));
523                 }
524             }
525         }
526     }
527
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 (&param.kind, seen_non_lifetime_param) {
533                 (GenericParamKind::Lifetime { .. }, true) => {
534                     self.err_handler()
535                         .span_err(param.ident.span, "lifetime parameters must be leading");
536                 },
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 {
543                         self.err_handler()
544                             .span_err(span, "type parameters with a default must be trailing");
545                         break;
546                     }
547                 }
548             }
549         }
550         for predicate in &generics.where_clause.predicates {
551             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
552                 self.err_handler()
553                     .span_err(predicate.span, "equality constraints are not yet \
554                                                supported in where clauses (see #20041)");
555             }
556         }
557         visit::walk_generics(self, generics)
558     }
559
560     fn visit_generic_param(&mut self, param: &'a GenericParam) {
561         if let GenericParamKind::Lifetime { .. } = param.kind {
562             self.check_lifetime(param.ident);
563         }
564         visit::walk_generic_param(self, param);
565     }
566
567     fn visit_pat(&mut self, pat: &'a Pat) {
568         match pat.node {
569             PatKind::Lit(ref expr) => {
570                 self.check_expr_within_pat(expr, false);
571             }
572             PatKind::Range(ref start, ref end, _) => {
573                 self.check_expr_within_pat(start, true);
574                 self.check_expr_within_pat(end, true);
575             }
576             _ => {}
577         }
578
579         visit::walk_pat(self, pat)
580     }
581
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);
586         }
587         visit::walk_where_predicate(self, p);
588     }
589
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);
593     }
594
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`?");
601     }
602 }
603
604 pub fn check_crate(session: &Session, krate: &Crate) -> (bool, bool) {
605     let mut validator = AstValidator {
606         session,
607         has_proc_macro_decls: false,
608         has_global_allocator: false,
609         outer_impl_trait: None,
610         is_impl_trait_banned: false,
611     };
612     visit::walk_crate(&mut validator, krate);
613
614     (validator.has_proc_macro_decls, validator.has_global_allocator)
615 }