]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/ast_validation.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[rust.git] / src / librustc_passes / ast_validation.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Validate AST before lowering it to HIR
12 //
13 // This pass is supposed to catch things that fit into AST data structures,
14 // but not permitted by the language. It runs after expansion when AST is frozen,
15 // so it can check for erroneous constructions produced by syntax extensions.
16 // This pass is supposed to perform only simple checks not requiring name resolution
17 // or type checking or some other kind of complex analysis.
18
19 use rustc::lint;
20 use rustc::session::Session;
21 use syntax::ast::*;
22 use syntax::attr;
23 use syntax::codemap::Spanned;
24 use syntax::parse::token;
25 use syntax::symbol::keywords;
26 use syntax::visit::{self, Visitor};
27 use syntax_pos::Span;
28 use errors;
29
30 struct AstValidator<'a> {
31     session: &'a Session,
32 }
33
34 impl<'a> AstValidator<'a> {
35     fn err_handler(&self) -> &errors::Handler {
36         &self.session.parse_sess.span_diagnostic
37     }
38
39     fn check_label(&self, label: Ident, span: Span, id: NodeId) {
40         if label.name == keywords::StaticLifetime.name() {
41             self.err_handler().span_err(span, &format!("invalid label name `{}`", label.name));
42         }
43         if label.name == "'_" {
44             self.session.add_lint(lint::builtin::LIFETIME_UNDERSCORE,
45                                   id,
46                                   span,
47                                   format!("invalid label name `{}`", label.name));
48         }
49     }
50
51     fn invalid_visibility(&self, vis: &Visibility, span: Span, note: Option<&str>) {
52         if vis != &Visibility::Inherited {
53             let mut err = struct_span_err!(self.session,
54                                            span,
55                                            E0449,
56                                            "unnecessary visibility qualifier");
57             if vis == &Visibility::Public {
58                 err.span_label(span, &format!("`pub` not needed here"));
59             }
60             if let Some(note) = note {
61                 err.note(note);
62             }
63             err.emit();
64         }
65     }
66
67     fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
68         for arg in &decl.inputs {
69             match arg.pat.node {
70                 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
71                 PatKind::Wild => {}
72                 PatKind::Ident(..) => report_err(arg.pat.span, true),
73                 _ => report_err(arg.pat.span, false),
74             }
75         }
76     }
77
78     fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
79         match constness.node {
80             Constness::Const => {
81                 struct_span_err!(self.session, constness.span, E0379,
82                                  "trait fns cannot be declared const")
83                     .span_label(constness.span, &format!("trait fns cannot be const"))
84                     .emit();
85             }
86             _ => {}
87         }
88     }
89
90     fn no_questions_in_bounds(&self, bounds: &TyParamBounds, where_: &str, is_trait: bool) {
91         for bound in bounds {
92             if let TraitTyParamBound(ref poly, TraitBoundModifier::Maybe) = *bound {
93                 let mut err = self.err_handler().struct_span_err(poly.span,
94                                     &format!("`?Trait` is not permitted in {}", where_));
95                 if is_trait {
96                     err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
97                 }
98                 err.emit();
99             }
100         }
101     }
102 }
103
104 impl<'a> Visitor<'a> for AstValidator<'a> {
105     fn visit_lifetime(&mut self, lt: &'a Lifetime) {
106         if lt.name == "'_" {
107             self.session.add_lint(lint::builtin::LIFETIME_UNDERSCORE,
108                                   lt.id,
109                                   lt.span,
110                                   format!("invalid lifetime name `{}`", lt.name));
111         }
112
113         visit::walk_lifetime(self, lt)
114     }
115
116     fn visit_expr(&mut self, expr: &'a Expr) {
117         match expr.node {
118             ExprKind::While(.., Some(ident)) |
119             ExprKind::Loop(_, Some(ident)) |
120             ExprKind::WhileLet(.., Some(ident)) |
121             ExprKind::ForLoop(.., Some(ident)) |
122             ExprKind::Break(Some(ident), _) |
123             ExprKind::Continue(Some(ident)) => {
124                 self.check_label(ident.node, ident.span, expr.id);
125             }
126             _ => {}
127         }
128
129         visit::walk_expr(self, expr)
130     }
131
132     fn visit_ty(&mut self, ty: &'a Ty) {
133         match ty.node {
134             TyKind::BareFn(ref bfty) => {
135                 self.check_decl_no_pat(&bfty.decl, |span, _| {
136                     let mut err = struct_span_err!(self.session,
137                                                    span,
138                                                    E0561,
139                                                    "patterns aren't allowed in function pointer \
140                                                     types");
141                     err.span_note(span,
142                                   "this is a recent error, see issue #35203 for more details");
143                     err.emit();
144                 });
145             }
146             TyKind::TraitObject(ref bounds) => {
147                 let mut any_lifetime_bounds = false;
148                 for bound in bounds {
149                     if let RegionTyParamBound(ref lifetime) = *bound {
150                         if any_lifetime_bounds {
151                             span_err!(self.session, lifetime.span, E0226,
152                                       "only a single explicit lifetime bound is permitted");
153                             break;
154                         }
155                         any_lifetime_bounds = true;
156                     }
157                 }
158                 self.no_questions_in_bounds(bounds, "trait object types", false);
159             }
160             TyKind::ImplTrait(ref bounds) => {
161                 if !bounds.iter()
162                           .any(|b| if let TraitTyParamBound(..) = *b { true } else { false }) {
163                     self.err_handler().span_err(ty.span, "at least one trait must be specified");
164                 }
165             }
166             _ => {}
167         }
168
169         visit::walk_ty(self, ty)
170     }
171
172     fn visit_path(&mut self, path: &'a Path, id: NodeId) {
173         if path.segments.len() >= 2 && path.is_global() {
174             let ident = path.segments[1].identifier;
175             if token::Ident(ident).is_path_segment_keyword() {
176                 self.session.add_lint(lint::builtin::SUPER_OR_SELF_IN_GLOBAL_PATH,
177                                       id,
178                                       path.span,
179                                       format!("global paths cannot start with `{}`", ident));
180             }
181         }
182
183         visit::walk_path(self, path)
184     }
185
186     fn visit_item(&mut self, item: &'a Item) {
187         match item.node {
188             ItemKind::Use(ref view_path) => {
189                 let path = view_path.node.path();
190                 if path.segments.iter().any(|segment| segment.parameters.is_some()) {
191                     self.err_handler()
192                         .span_err(path.span, "type or lifetime parameters in import path");
193                 }
194             }
195             ItemKind::Impl(.., Some(..), _, ref impl_items) => {
196                 self.invalid_visibility(&item.vis, item.span, None);
197                 for impl_item in impl_items {
198                     self.invalid_visibility(&impl_item.vis, impl_item.span, None);
199                     if let ImplItemKind::Method(ref sig, _) = impl_item.node {
200                         self.check_trait_fn_not_const(sig.constness);
201                     }
202                 }
203             }
204             ItemKind::Impl(.., None, _, _) => {
205                 self.invalid_visibility(&item.vis,
206                                         item.span,
207                                         Some("place qualifiers on individual impl items instead"));
208             }
209             ItemKind::DefaultImpl(..) => {
210                 self.invalid_visibility(&item.vis, item.span, None);
211             }
212             ItemKind::ForeignMod(..) => {
213                 self.invalid_visibility(&item.vis,
214                                         item.span,
215                                         Some("place qualifiers on individual foreign items \
216                                               instead"));
217             }
218             ItemKind::Enum(ref def, _) => {
219                 for variant in &def.variants {
220                     for field in variant.node.data.fields() {
221                         self.invalid_visibility(&field.vis, field.span, None);
222                     }
223                 }
224             }
225             ItemKind::Trait(.., ref bounds, ref trait_items) => {
226                 self.no_questions_in_bounds(bounds, "supertraits", true);
227                 for trait_item in trait_items {
228                     if let TraitItemKind::Method(ref sig, ref block) = trait_item.node {
229                         self.check_trait_fn_not_const(sig.constness);
230                         if block.is_none() {
231                             self.check_decl_no_pat(&sig.decl, |span, _| {
232                                 self.session.add_lint(lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
233                                                       trait_item.id, span,
234                                                       "patterns aren't allowed in methods \
235                                                        without bodies".to_string());
236                             });
237                         }
238                     }
239                 }
240             }
241             ItemKind::Mod(_) => {
242                 // Ensure that `path` attributes on modules are recorded as used (c.f. #35584).
243                 attr::first_attr_value_str_by_name(&item.attrs, "path");
244                 if item.attrs.iter().any(|attr| attr.check_name("warn_directory_ownership")) {
245                     let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
246                     let msg = "cannot declare a new module at this location";
247                     self.session.add_lint(lint, item.id, item.span, msg.to_string());
248                 }
249             }
250             ItemKind::Union(ref vdata, _) => {
251                 if !vdata.is_struct() {
252                     self.err_handler().span_err(item.span,
253                                                 "tuple and unit unions are not permitted");
254                 }
255                 if vdata.fields().len() == 0 {
256                     self.err_handler().span_err(item.span,
257                                                 "unions cannot have zero fields");
258                 }
259             }
260             _ => {}
261         }
262
263         visit::walk_item(self, item)
264     }
265
266     fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
267         match fi.node {
268             ForeignItemKind::Fn(ref decl, _) => {
269                 self.check_decl_no_pat(decl, |span, is_recent| {
270                     let mut err = struct_span_err!(self.session,
271                                                    span,
272                                                    E0130,
273                                                    "patterns aren't allowed in foreign function \
274                                                     declarations");
275                     err.span_label(span, &format!("pattern not allowed in foreign function"));
276                     if is_recent {
277                         err.span_note(span,
278                                       "this is a recent error, see issue #35203 for more details");
279                     }
280                     err.emit();
281                 });
282             }
283             ForeignItemKind::Static(..) => {}
284         }
285
286         visit::walk_foreign_item(self, fi)
287     }
288
289     fn visit_vis(&mut self, vis: &'a Visibility) {
290         match *vis {
291             Visibility::Restricted { ref path, .. } => {
292                 if !path.segments.iter().all(|segment| segment.parameters.is_none()) {
293                     self.err_handler()
294                         .span_err(path.span, "type or lifetime parameters in visibility path");
295                 }
296             }
297             _ => {}
298         }
299
300         visit::walk_vis(self, vis)
301     }
302
303     fn visit_generics(&mut self, g: &'a Generics) {
304         let mut seen_default = None;
305         for ty_param in &g.ty_params {
306             if ty_param.default.is_some() {
307                 seen_default = Some(ty_param.span);
308             } else if let Some(span) = seen_default {
309                 self.err_handler()
310                     .span_err(span, "type parameters with a default must be trailing");
311                 break
312             }
313         }
314         for predicate in &g.where_clause.predicates {
315             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
316                 self.err_handler().span_err(predicate.span, "equality constraints are not yet \
317                                                              supported in where clauses (#20041)");
318             }
319         }
320         visit::walk_generics(self, g)
321     }
322 }
323
324 pub fn check_crate(session: &Session, krate: &Crate) {
325     visit::walk_crate(&mut AstValidator { session: session }, krate)
326 }