]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/ast_validation.rs
Changed issue number to 36105
[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::parse::token::{self, keywords};
24 use syntax::visit::{self, Visitor};
25 use syntax_pos::Span;
26 use errors;
27
28 struct AstValidator<'a> {
29     session: &'a Session,
30 }
31
32 impl<'a> AstValidator<'a> {
33     fn err_handler(&self) -> &errors::Handler {
34         &self.session.parse_sess.span_diagnostic
35     }
36
37     fn check_label(&self, label: Ident, span: Span, id: NodeId) {
38         if label.name == keywords::StaticLifetime.name() {
39             self.err_handler().span_err(span, &format!("invalid label name `{}`", label.name));
40         }
41         if label.name.as_str() == "'_" {
42             self.session.add_lint(lint::builtin::LIFETIME_UNDERSCORE,
43                                   id,
44                                   span,
45                                   format!("invalid label name `{}`", label.name));
46         }
47     }
48
49     fn invalid_visibility(&self, vis: &Visibility, span: Span, note: Option<&str>) {
50         if vis != &Visibility::Inherited {
51             let mut err = struct_span_err!(self.session,
52                                            span,
53                                            E0449,
54                                            "unnecessary visibility qualifier");
55             if let Some(note) = note {
56                 err.span_note(span, note);
57             }
58             err.emit();
59         }
60     }
61
62     fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
63         for arg in &decl.inputs {
64             match arg.pat.node {
65                 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
66                 PatKind::Wild => {}
67                 PatKind::Ident(..) => report_err(arg.pat.span, true),
68                 _ => report_err(arg.pat.span, false),
69             }
70         }
71     }
72 }
73
74 impl<'a> Visitor for AstValidator<'a> {
75     fn visit_lifetime(&mut self, lt: &Lifetime) {
76         if lt.name.as_str() == "'_" {
77             self.session.add_lint(lint::builtin::LIFETIME_UNDERSCORE,
78                                   lt.id,
79                                   lt.span,
80                                   format!("invalid lifetime name `{}`", lt.name));
81         }
82
83         visit::walk_lifetime(self, lt)
84     }
85
86     fn visit_expr(&mut self, expr: &Expr) {
87         match expr.node {
88             ExprKind::While(_, _, Some(ident)) |
89             ExprKind::Loop(_, Some(ident)) |
90             ExprKind::WhileLet(_, _, _, Some(ident)) |
91             ExprKind::ForLoop(_, _, _, Some(ident)) |
92             ExprKind::Break(Some(ident)) |
93             ExprKind::Continue(Some(ident)) => {
94                 self.check_label(ident.node, ident.span, expr.id);
95             }
96             _ => {}
97         }
98
99         visit::walk_expr(self, expr)
100     }
101
102     fn visit_ty(&mut self, ty: &Ty) {
103         match ty.node {
104             TyKind::BareFn(ref bfty) => {
105                 self.check_decl_no_pat(&bfty.decl, |span, _| {
106                     let mut err = struct_span_err!(self.session,
107                                                    span,
108                                                    E0561,
109                                                    "patterns aren't allowed in function pointer \
110                                                     types");
111                     err.span_note(span,
112                                   "this is a recent error, see issue #35203 for more details");
113                     err.emit();
114                 });
115             }
116             _ => {}
117         }
118
119         visit::walk_ty(self, ty)
120     }
121
122     fn visit_path(&mut self, path: &Path, id: NodeId) {
123         if path.global && path.segments.len() > 0 {
124             let ident = path.segments[0].identifier;
125             if token::Ident(ident).is_path_segment_keyword() {
126                 self.session.add_lint(lint::builtin::SUPER_OR_SELF_IN_GLOBAL_PATH,
127                                       id,
128                                       path.span,
129                                       format!("global paths cannot start with `{}`", ident));
130             }
131         }
132
133         visit::walk_path(self, path)
134     }
135
136     fn visit_item(&mut self, item: &Item) {
137         match item.node {
138             ItemKind::Use(ref view_path) => {
139                 let path = view_path.node.path();
140                 if !path.segments.iter().all(|segment| segment.parameters.is_empty()) {
141                     self.err_handler()
142                         .span_err(path.span, "type or lifetime parameters in import path");
143                 }
144             }
145             ItemKind::Impl(_, _, _, Some(..), _, ref impl_items) => {
146                 self.invalid_visibility(&item.vis, item.span, None);
147                 for impl_item in impl_items {
148                     self.invalid_visibility(&impl_item.vis, impl_item.span, None);
149                 }
150             }
151             ItemKind::Impl(_, _, _, None, _, _) => {
152                 self.invalid_visibility(&item.vis,
153                                         item.span,
154                                         Some("place qualifiers on individual impl items instead"));
155             }
156             ItemKind::DefaultImpl(..) => {
157                 self.invalid_visibility(&item.vis, item.span, None);
158             }
159             ItemKind::ForeignMod(..) => {
160                 self.invalid_visibility(&item.vis,
161                                         item.span,
162                                         Some("place qualifiers on individual foreign items \
163                                               instead"));
164             }
165             ItemKind::Enum(ref def, _) => {
166                 for variant in &def.variants {
167                     for field in variant.node.data.fields() {
168                         self.invalid_visibility(&field.vis, field.span, None);
169                     }
170                 }
171             }
172             ItemKind::Mod(_) => {
173                 // Ensure that `path` attributes on modules are recorded as used (c.f. #35584).
174                 attr::first_attr_value_str_by_name(&item.attrs, "path");
175             }
176             _ => {}
177         }
178
179         visit::walk_item(self, item)
180     }
181
182     fn visit_foreign_item(&mut self, fi: &ForeignItem) {
183         match fi.node {
184             ForeignItemKind::Fn(ref decl, _) => {
185                 self.check_decl_no_pat(decl, |span, is_recent| {
186                     let mut err = struct_span_err!(self.session,
187                                                    span,
188                                                    E0130,
189                                                    "patterns aren't allowed in foreign function \
190                                                     declarations");
191                     err.span_label(span, &format!("pattern not allowed in foreign function"));
192                     if is_recent {
193                         err.span_note(span,
194                                       "this is a recent error, see issue #35203 for more details");
195                     }
196                     err.emit();
197                 });
198             }
199             ForeignItemKind::Static(..) => {}
200         }
201
202         visit::walk_foreign_item(self, fi)
203     }
204
205     fn visit_vis(&mut self, vis: &Visibility) {
206         match *vis {
207             Visibility::Restricted { ref path, .. } => {
208                 if !path.segments.iter().all(|segment| segment.parameters.is_empty()) {
209                     self.err_handler()
210                         .span_err(path.span, "type or lifetime parameters in visibility path");
211                 }
212             }
213             _ => {}
214         }
215
216         visit::walk_vis(self, vis)
217     }
218 }
219
220 pub fn check_crate(session: &Session, krate: &Crate) {
221     visit::walk_crate(&mut AstValidator { session: session }, krate)
222 }