]> git.proxmox.com Git - rustc.git/blob - src/librustc_passes/ast_validation.rs
New upstream version 1.19.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;
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) {
40 if label.name == keywords::StaticLifetime.name() || label.name == "'_" {
41 self.err_handler().span_err(span, &format!("invalid label name `{}`", label.name));
42 }
43 }
44
45 fn invalid_visibility(&self, vis: &Visibility, span: Span, note: Option<&str>) {
46 if vis != &Visibility::Inherited {
47 let mut err = struct_span_err!(self.session,
48 span,
49 E0449,
50 "unnecessary visibility qualifier");
51 if vis == &Visibility::Public {
52 err.span_label(span, "`pub` not needed here");
53 }
54 if let Some(note) = note {
55 err.note(note);
56 }
57 err.emit();
58 }
59 }
60
61 fn check_decl_no_pat<ReportFn: Fn(Span, bool)>(&self, decl: &FnDecl, report_err: ReportFn) {
62 for arg in &decl.inputs {
63 match arg.pat.node {
64 PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), _, None) |
65 PatKind::Wild => {}
66 PatKind::Ident(..) => report_err(arg.pat.span, true),
67 _ => report_err(arg.pat.span, false),
68 }
69 }
70 }
71
72 fn check_trait_fn_not_const(&self, constness: Spanned<Constness>) {
73 match constness.node {
74 Constness::Const => {
75 struct_span_err!(self.session, constness.span, E0379,
76 "trait fns cannot be declared const")
77 .span_label(constness.span, "trait fns cannot be const")
78 .emit();
79 }
80 _ => {}
81 }
82 }
83
84 fn no_questions_in_bounds(&self, bounds: &TyParamBounds, where_: &str, is_trait: bool) {
85 for bound in bounds {
86 if let TraitTyParamBound(ref poly, TraitBoundModifier::Maybe) = *bound {
87 let mut err = self.err_handler().struct_span_err(poly.span,
88 &format!("`?Trait` is not permitted in {}", where_));
89 if is_trait {
90 err.note(&format!("traits are `?{}` by default", poly.trait_ref.path));
91 }
92 err.emit();
93 }
94 }
95 }
96 }
97
98 impl<'a> Visitor<'a> for AstValidator<'a> {
99 fn visit_lifetime(&mut self, lt: &'a Lifetime) {
100 if lt.ident.name == "'_" {
101 self.err_handler().span_err(lt.span, &format!("invalid lifetime name `{}`", lt.ident));
102 }
103
104 visit::walk_lifetime(self, lt)
105 }
106
107 fn visit_expr(&mut self, expr: &'a Expr) {
108 match expr.node {
109 ExprKind::While(.., Some(ident)) |
110 ExprKind::Loop(_, Some(ident)) |
111 ExprKind::WhileLet(.., Some(ident)) |
112 ExprKind::ForLoop(.., Some(ident)) |
113 ExprKind::Break(Some(ident), _) |
114 ExprKind::Continue(Some(ident)) => {
115 self.check_label(ident.node, ident.span);
116 }
117 _ => {}
118 }
119
120 visit::walk_expr(self, expr)
121 }
122
123 fn visit_ty(&mut self, ty: &'a Ty) {
124 match ty.node {
125 TyKind::BareFn(ref bfty) => {
126 self.check_decl_no_pat(&bfty.decl, |span, _| {
127 let mut err = struct_span_err!(self.session,
128 span,
129 E0561,
130 "patterns aren't allowed in function pointer \
131 types");
132 err.span_note(span,
133 "this is a recent error, see issue #35203 for more details");
134 err.emit();
135 });
136 }
137 TyKind::TraitObject(ref bounds) => {
138 let mut any_lifetime_bounds = false;
139 for bound in bounds {
140 if let RegionTyParamBound(ref lifetime) = *bound {
141 if any_lifetime_bounds {
142 span_err!(self.session, lifetime.span, E0226,
143 "only a single explicit lifetime bound is permitted");
144 break;
145 }
146 any_lifetime_bounds = true;
147 }
148 }
149 self.no_questions_in_bounds(bounds, "trait object types", false);
150 }
151 TyKind::ImplTrait(ref bounds) => {
152 if !bounds.iter()
153 .any(|b| if let TraitTyParamBound(..) = *b { true } else { false }) {
154 self.err_handler().span_err(ty.span, "at least one trait must be specified");
155 }
156 }
157 _ => {}
158 }
159
160 visit::walk_ty(self, ty)
161 }
162
163 fn visit_path(&mut self, path: &'a Path, _: NodeId) {
164 if path.segments.len() >= 2 && path.is_global() {
165 let ident = path.segments[1].identifier;
166 if token::Ident(ident).is_path_segment_keyword() {
167 self.err_handler()
168 .span_err(path.span, &format!("global paths cannot start with `{}`", ident));
169 }
170 }
171
172 visit::walk_path(self, path)
173 }
174
175 fn visit_item(&mut self, item: &'a Item) {
176 match item.node {
177 ItemKind::Use(ref view_path) => {
178 let path = view_path.node.path();
179 if path.segments.iter().any(|segment| segment.parameters.is_some()) {
180 self.err_handler()
181 .span_err(path.span, "type or lifetime parameters in import path");
182 }
183 }
184 ItemKind::Impl(.., Some(..), _, ref impl_items) => {
185 self.invalid_visibility(&item.vis, item.span, None);
186 for impl_item in impl_items {
187 self.invalid_visibility(&impl_item.vis, impl_item.span, None);
188 if let ImplItemKind::Method(ref sig, _) = impl_item.node {
189 self.check_trait_fn_not_const(sig.constness);
190 }
191 }
192 }
193 ItemKind::Impl(.., None, _, _) => {
194 self.invalid_visibility(&item.vis,
195 item.span,
196 Some("place qualifiers on individual impl items instead"));
197 }
198 ItemKind::DefaultImpl(..) => {
199 self.invalid_visibility(&item.vis, item.span, None);
200 }
201 ItemKind::ForeignMod(..) => {
202 self.invalid_visibility(&item.vis,
203 item.span,
204 Some("place qualifiers on individual foreign items \
205 instead"));
206 }
207 ItemKind::Enum(ref def, _) => {
208 for variant in &def.variants {
209 for field in variant.node.data.fields() {
210 self.invalid_visibility(&field.vis, field.span, None);
211 }
212 }
213 }
214 ItemKind::Trait(.., ref bounds, ref trait_items) => {
215 self.no_questions_in_bounds(bounds, "supertraits", true);
216 for trait_item in trait_items {
217 if let TraitItemKind::Method(ref sig, ref block) = trait_item.node {
218 self.check_trait_fn_not_const(sig.constness);
219 if block.is_none() {
220 self.check_decl_no_pat(&sig.decl, |span, _| {
221 self.session.add_lint(lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY,
222 trait_item.id, span,
223 "patterns aren't allowed in methods \
224 without bodies".to_string());
225 });
226 }
227 }
228 }
229 }
230 ItemKind::Mod(_) => {
231 // Ensure that `path` attributes on modules are recorded as used (c.f. #35584).
232 attr::first_attr_value_str_by_name(&item.attrs, "path");
233 if item.attrs.iter().any(|attr| attr.check_name("warn_directory_ownership")) {
234 let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP;
235 let msg = "cannot declare a new module at this location";
236 self.session.add_lint(lint, item.id, item.span, msg.to_string());
237 }
238 }
239 ItemKind::Union(ref vdata, _) => {
240 if !vdata.is_struct() {
241 self.err_handler().span_err(item.span,
242 "tuple and unit unions are not permitted");
243 }
244 if vdata.fields().len() == 0 {
245 self.err_handler().span_err(item.span,
246 "unions cannot have zero fields");
247 }
248 }
249 _ => {}
250 }
251
252 visit::walk_item(self, item)
253 }
254
255 fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
256 match fi.node {
257 ForeignItemKind::Fn(ref decl, _) => {
258 self.check_decl_no_pat(decl, |span, is_recent| {
259 let mut err = struct_span_err!(self.session,
260 span,
261 E0130,
262 "patterns aren't allowed in foreign function \
263 declarations");
264 err.span_label(span, "pattern not allowed in foreign function");
265 if is_recent {
266 err.span_note(span,
267 "this is a recent error, see issue #35203 for more details");
268 }
269 err.emit();
270 });
271 }
272 ForeignItemKind::Static(..) => {}
273 }
274
275 visit::walk_foreign_item(self, fi)
276 }
277
278 fn visit_vis(&mut self, vis: &'a Visibility) {
279 match *vis {
280 Visibility::Restricted { ref path, .. } => {
281 if !path.segments.iter().all(|segment| segment.parameters.is_none()) {
282 self.err_handler()
283 .span_err(path.span, "type or lifetime parameters in visibility path");
284 }
285 }
286 _ => {}
287 }
288
289 visit::walk_vis(self, vis)
290 }
291
292 fn visit_generics(&mut self, g: &'a Generics) {
293 let mut seen_default = None;
294 for ty_param in &g.ty_params {
295 if ty_param.default.is_some() {
296 seen_default = Some(ty_param.span);
297 } else if let Some(span) = seen_default {
298 self.err_handler()
299 .span_err(span, "type parameters with a default must be trailing");
300 break
301 }
302 }
303 for predicate in &g.where_clause.predicates {
304 if let WherePredicate::EqPredicate(ref predicate) = *predicate {
305 self.err_handler().span_err(predicate.span, "equality constraints are not yet \
306 supported in where clauses (#20041)");
307 }
308 }
309 visit::walk_generics(self, g)
310 }
311 }
312
313 pub fn check_crate(session: &Session, krate: &Crate) {
314 visit::walk_crate(&mut AstValidator { session: session }, krate)
315 }