]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/ast_validation.rs
Rollup merge of #34316 - jseyfried:refactor_ast_stmt, r=eddyb
[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::parse::token::{self, keywords};
23 use syntax::visit::{self, Visitor};
24 use syntax_pos::Span;
25 use errors;
26
27 struct AstValidator<'a> {
28     session: &'a Session,
29 }
30
31 impl<'a> AstValidator<'a> {
32     fn err_handler(&self) -> &errors::Handler {
33         &self.session.parse_sess.span_diagnostic
34     }
35
36     fn check_label(&self, label: Ident, span: Span, id: NodeId) {
37         if label.name == keywords::StaticLifetime.name() {
38             self.err_handler().span_err(span, &format!("invalid label name `{}`", label.name));
39         }
40         if label.name.as_str() == "'_" {
41             self.session.add_lint(
42                 lint::builtin::LIFETIME_UNDERSCORE, id, span,
43                 format!("invalid label name `{}`", label.name)
44             );
45         }
46     }
47
48     fn invalid_visibility(&self, vis: &Visibility, span: Span, note: Option<&str>) {
49         if vis != &Visibility::Inherited {
50             let mut err = struct_span_err!(self.session, span, E0449,
51                                            "unnecessary visibility qualifier");
52             if let Some(note) = note {
53                 err.span_note(span, note);
54             }
55             err.emit();
56         }
57     }
58 }
59
60 impl<'a> Visitor for AstValidator<'a> {
61     fn visit_lifetime(&mut self, lt: &Lifetime) {
62         if lt.name.as_str() == "'_" {
63             self.session.add_lint(
64                 lint::builtin::LIFETIME_UNDERSCORE, lt.id, lt.span,
65                 format!("invalid lifetime name `{}`", lt.name)
66             );
67         }
68
69         visit::walk_lifetime(self, lt)
70     }
71
72     fn visit_expr(&mut self, expr: &Expr) {
73         match expr.node {
74             ExprKind::While(_, _, Some(ident)) | ExprKind::Loop(_, Some(ident)) |
75             ExprKind::WhileLet(_, _, _, Some(ident)) | ExprKind::ForLoop(_, _, _, Some(ident)) |
76             ExprKind::Break(Some(ident)) | ExprKind::Continue(Some(ident)) => {
77                 self.check_label(ident.node, ident.span, expr.id);
78             }
79             _ => {}
80         }
81
82         visit::walk_expr(self, expr)
83     }
84
85     fn visit_path(&mut self, path: &Path, id: NodeId) {
86         if path.global && path.segments.len() > 0 {
87             let ident = path.segments[0].identifier;
88             if token::Ident(ident).is_path_segment_keyword() {
89                 self.session.add_lint(
90                     lint::builtin::SUPER_OR_SELF_IN_GLOBAL_PATH, id, path.span,
91                     format!("global paths cannot start with `{}`", ident)
92                 );
93             }
94         }
95
96         visit::walk_path(self, path)
97     }
98
99     fn visit_item(&mut self, item: &Item) {
100         match item.node {
101             ItemKind::Use(ref view_path) => {
102                 let path = view_path.node.path();
103                 if !path.segments.iter().all(|segment| segment.parameters.is_empty()) {
104                     self.err_handler().span_err(path.span, "type or lifetime parameters \
105                                                             in import path");
106                 }
107             }
108             ItemKind::Impl(_, _, _, Some(..), _, ref impl_items) => {
109                 self.invalid_visibility(&item.vis, item.span, None);
110                 for impl_item in impl_items {
111                     self.invalid_visibility(&impl_item.vis, impl_item.span, None);
112                 }
113             }
114             ItemKind::Impl(_, _, _, None, _, _) => {
115                 self.invalid_visibility(&item.vis, item.span, Some("place qualifiers on individual \
116                                                                     impl items instead"));
117             }
118             ItemKind::DefaultImpl(..) => {
119                 self.invalid_visibility(&item.vis, item.span, None);
120             }
121             ItemKind::ForeignMod(..) => {
122                 self.invalid_visibility(&item.vis, item.span, Some("place qualifiers on individual \
123                                                                     foreign items instead"));
124             }
125             ItemKind::Enum(ref def, _) => {
126                 for variant in &def.variants {
127                     for field in variant.node.data.fields() {
128                         self.invalid_visibility(&field.vis, field.span, None);
129                     }
130                 }
131             }
132             _ => {}
133         }
134
135         visit::walk_item(self, item)
136     }
137
138     fn visit_variant_data(&mut self, vdata: &VariantData, _: Ident,
139                           _: &Generics, _: NodeId, span: Span) {
140         if vdata.fields().is_empty() {
141             if vdata.is_tuple() {
142                 self.err_handler().struct_span_err(span, "empty tuple structs and enum variants \
143                                                           are not allowed, use unit structs and \
144                                                           enum variants instead")
145                                          .span_help(span, "remove trailing `()` to make a unit \
146                                                            struct or unit enum variant")
147                                          .emit();
148             }
149         }
150
151         visit::walk_struct_def(self, vdata)
152     }
153
154     fn visit_vis(&mut self, vis: &Visibility) {
155         match *vis {
156             Visibility::Restricted{ref path, ..} => {
157                 if !path.segments.iter().all(|segment| segment.parameters.is_empty()) {
158                     self.err_handler().span_err(path.span, "type or lifetime parameters \
159                                                             in visibility path");
160                 }
161             }
162             _ => {}
163         }
164
165         visit::walk_vis(self, vis)
166     }
167 }
168
169 pub fn check_crate(session: &Session, krate: &Crate) {
170     visit::walk_crate(&mut AstValidator { session: session }, krate)
171 }