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