Skip to content

Commit fedc0f8

Browse files
committed
Auto merge of #33794 - petrochenkov:sanity, r=nrc
Add AST validation pass and move some checks to it The purpose of this pass is to catch constructions that fit into AST data structures, but not permitted by the language. As an example, `impl`s don't have visibilities, but for convenience and uniformity with other items they are represented with a structure `Item` which has `Visibility` field. This pass is intended to run after expansion of macros and syntax extensions (and before lowering to HIR), so it can catch erroneous constructions that were generated by them. This pass allows to remove ad hoc semantic checks from the parser, which can be overruled by syntax extensions and occasionally macros. The checks can be put here if they are simple, local, don't require results of any complex analysis like name resolution or type checking and maybe don't logically fall into other passes. I expect most of errors generated by this pass to be non-fatal and allowing the compilation to proceed. I intend to move some more checks to this pass later and maybe extend it with new checks, like, for example, identifier validity. Given that syntax extensions are going to be stabilized in the measurable future, it's important that they would not be able to subvert usual language rules. In this patch I've added two new checks - a check for labels named `'static` and a check for lifetimes and labels named `'_`. The first one gives a hard error, the second one - a future compatibility warning. Fixes #33059 ([breaking-change]) cc rust-lang/rfcs#1177 r? @nrc
2 parents 97e3a24 + 91d8a4f commit fedc0f8

File tree

20 files changed

+326
-214
lines changed

20 files changed

+326
-214
lines changed

src/librustc/lint/builtin.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,12 @@ declare_lint! {
204204
"object-unsafe non-principal fragments in object types were erroneously allowed"
205205
}
206206

207+
declare_lint! {
208+
pub LIFETIME_UNDERSCORE,
209+
Warn,
210+
"lifetimes or labels named `'_` were erroneously allowed"
211+
}
212+
207213
/// Does nothing as a lint pass, but registers some `Lint`s
208214
/// which are used by other parts of the compiler.
209215
#[derive(Copy, Clone)]
@@ -242,7 +248,8 @@ impl LintPass for HardwiredLints {
242248
SUPER_OR_SELF_IN_GLOBAL_PATH,
243249
UNSIZED_IN_TUPLE,
244250
OBJECT_UNSAFE_FRAGMENT,
245-
HR_LIFETIME_IN_ASSOC_TYPE
251+
HR_LIFETIME_IN_ASSOC_TYPE,
252+
LIFETIME_UNDERSCORE
246253
)
247254
}
248255
}

src/librustc_driver/driver.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ use rustc_privacy;
3838
use rustc_plugin::registry::Registry;
3939
use rustc_plugin as plugin;
4040
use rustc::hir::lowering::lower_crate;
41-
use rustc_passes::{no_asm, loops, consts, rvalues, static_recursion};
41+
use rustc_passes::{ast_validation, no_asm, loops, consts, rvalues, static_recursion};
4242
use rustc_const_eval::check_match;
4343
use super::Compilation;
4444

@@ -166,6 +166,10 @@ pub fn compile_input(sess: &Session,
166166
"early lint checks",
167167
|| lint::check_ast_crate(sess, &expanded_crate));
168168

169+
time(sess.time_passes(),
170+
"AST validation",
171+
|| ast_validation::check_crate(sess, &expanded_crate));
172+
169173
let (analysis, resolutions, mut hir_forest) = {
170174
lower_and_resolve(sess, &id, &mut defs, &expanded_crate,
171175
&sess.dep_graph, control.make_glob_map)

src/librustc_lint/lib.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,10 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
202202
id: LintId::of(HR_LIFETIME_IN_ASSOC_TYPE),
203203
reference: "issue #33685 <https://github.com/rust-lang/rust/issues/33685>",
204204
},
205+
FutureIncompatibleInfo {
206+
id: LintId::of(LIFETIME_UNDERSCORE),
207+
reference: "RFC 1177 <https://github.com/rust-lang/rfcs/pull/1177>",
208+
},
205209
]);
206210

207211
// We have one lint pass defined specially

src/librustc_passes/ast_validation.rs

Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
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::codemap::Span;
23+
use syntax::errors;
24+
use syntax::parse::token::{self, keywords};
25+
use syntax::visit::{self, Visitor};
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+
fn check_path(&self, path: &Path, id: NodeId) {
60+
if path.global && path.segments.len() > 0 {
61+
let ident = path.segments[0].identifier;
62+
if token::Ident(ident).is_path_segment_keyword() {
63+
self.session.add_lint(
64+
lint::builtin::SUPER_OR_SELF_IN_GLOBAL_PATH, id, path.span,
65+
format!("global paths cannot start with `{}`", ident)
66+
);
67+
}
68+
}
69+
}
70+
}
71+
72+
impl<'a, 'v> Visitor<'v> for AstValidator<'a> {
73+
fn visit_lifetime(&mut self, lt: &Lifetime) {
74+
if lt.name.as_str() == "'_" {
75+
self.session.add_lint(
76+
lint::builtin::LIFETIME_UNDERSCORE, lt.id, lt.span,
77+
format!("invalid lifetime name `{}`", lt.name)
78+
);
79+
}
80+
81+
visit::walk_lifetime(self, lt)
82+
}
83+
84+
fn visit_expr(&mut self, expr: &Expr) {
85+
match expr.node {
86+
ExprKind::While(_, _, Some(ident)) | ExprKind::Loop(_, Some(ident)) |
87+
ExprKind::WhileLet(_, _, _, Some(ident)) | ExprKind::ForLoop(_, _, _, Some(ident)) => {
88+
self.check_label(ident, expr.span, expr.id);
89+
}
90+
ExprKind::Break(Some(ident)) | ExprKind::Again(Some(ident)) => {
91+
self.check_label(ident.node, ident.span, expr.id);
92+
}
93+
_ => {}
94+
}
95+
96+
visit::walk_expr(self, expr)
97+
}
98+
99+
fn visit_path(&mut self, path: &Path, id: NodeId) {
100+
self.check_path(path, id);
101+
102+
visit::walk_path(self, path)
103+
}
104+
105+
fn visit_path_list_item(&mut self, prefix: &Path, item: &PathListItem) {
106+
self.check_path(prefix, item.node.id());
107+
108+
visit::walk_path_list_item(self, prefix, item)
109+
}
110+
111+
fn visit_item(&mut self, item: &Item) {
112+
match item.node {
113+
ItemKind::Use(ref view_path) => {
114+
let path = view_path.node.path();
115+
if !path.segments.iter().all(|segment| segment.parameters.is_empty()) {
116+
self.err_handler().span_err(path.span, "type or lifetime parameters \
117+
in import path");
118+
}
119+
}
120+
ItemKind::Impl(_, _, _, Some(..), _, ref impl_items) => {
121+
self.invalid_visibility(&item.vis, item.span, None);
122+
for impl_item in impl_items {
123+
self.invalid_visibility(&impl_item.vis, impl_item.span, None);
124+
}
125+
}
126+
ItemKind::Impl(_, _, _, None, _, _) => {
127+
self.invalid_visibility(&item.vis, item.span, Some("place qualifiers on individual \
128+
impl items instead"));
129+
}
130+
ItemKind::DefaultImpl(..) => {
131+
self.invalid_visibility(&item.vis, item.span, None);
132+
}
133+
ItemKind::ForeignMod(..) => {
134+
self.invalid_visibility(&item.vis, item.span, Some("place qualifiers on individual \
135+
foreign items instead"));
136+
}
137+
ItemKind::Enum(ref def, _) => {
138+
for variant in &def.variants {
139+
for field in variant.node.data.fields() {
140+
self.invalid_visibility(&field.vis, field.span, None);
141+
}
142+
}
143+
}
144+
_ => {}
145+
}
146+
147+
visit::walk_item(self, item)
148+
}
149+
150+
fn visit_variant_data(&mut self, vdata: &VariantData, _: Ident,
151+
_: &Generics, _: NodeId, span: Span) {
152+
if vdata.fields().is_empty() {
153+
if vdata.is_tuple() {
154+
self.err_handler().struct_span_err(span, "empty tuple structs and enum variants \
155+
are not allowed, use unit structs and \
156+
enum variants instead")
157+
.span_help(span, "remove trailing `()` to make a unit \
158+
struct or unit enum variant")
159+
.emit();
160+
}
161+
}
162+
163+
visit::walk_struct_def(self, vdata)
164+
}
165+
166+
fn visit_vis(&mut self, vis: &Visibility) {
167+
match *vis {
168+
Visibility::Restricted{ref path, ..} => {
169+
if !path.segments.iter().all(|segment| segment.parameters.is_empty()) {
170+
self.err_handler().span_err(path.span, "type or lifetime parameters \
171+
in visibility path");
172+
}
173+
}
174+
_ => {}
175+
}
176+
177+
visit::walk_vis(self, vis)
178+
}
179+
}
180+
181+
pub fn check_crate(session: &Session, krate: &Crate) {
182+
visit::walk_crate(&mut AstValidator { session: session }, krate)
183+
}

src/librustc_passes/diagnostics.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,46 @@ fn some_func() {
118118
```
119119
"##,
120120

121+
E0449: r##"
122+
A visibility qualifier was used when it was unnecessary. Erroneous code
123+
examples:
124+
125+
```compile_fail
126+
struct Bar;
127+
128+
trait Foo {
129+
fn foo();
130+
}
131+
132+
pub impl Bar {} // error: unnecessary visibility qualifier
133+
134+
pub impl Foo for Bar { // error: unnecessary visibility qualifier
135+
pub fn foo() {} // error: unnecessary visibility qualifier
136+
}
137+
```
138+
139+
To fix this error, please remove the visibility qualifier when it is not
140+
required. Example:
141+
142+
```ignore
143+
struct Bar;
144+
145+
trait Foo {
146+
fn foo();
147+
}
148+
149+
// Directly implemented methods share the visibility of the type itself,
150+
// so `pub` is unnecessary here
151+
impl Bar {}
152+
153+
// Trait methods share the visibility of the trait, so `pub` is
154+
// unnecessary in either case
155+
pub impl Foo for Bar {
156+
pub fn foo() {}
157+
}
158+
```
159+
"##,
160+
121161
}
122162

123163
register_diagnostics! {

src/librustc_passes/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ extern crate rustc_const_math;
3737

3838
pub mod diagnostics;
3939

40+
pub mod ast_validation;
4041
pub mod consts;
4142
pub mod loops;
4243
pub mod no_asm;

src/librustc_privacy/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,5 @@ path = "lib.rs"
99
crate-type = ["dylib"]
1010

1111
[dependencies]
12-
log = { path = "../liblog" }
1312
rustc = { path = "../librustc" }
1413
syntax = { path = "../libsyntax" }

src/librustc_privacy/diagnostics.rs

Lines changed: 0 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -111,46 +111,6 @@ pub enum Foo {
111111
```
112112
"##,
113113

114-
E0449: r##"
115-
A visibility qualifier was used when it was unnecessary. Erroneous code
116-
examples:
117-
118-
```compile_fail
119-
struct Bar;
120-
121-
trait Foo {
122-
fn foo();
123-
}
124-
125-
pub impl Bar {} // error: unnecessary visibility qualifier
126-
127-
pub impl Foo for Bar { // error: unnecessary visibility qualifier
128-
pub fn foo() {} // error: unnecessary visibility qualifier
129-
}
130-
```
131-
132-
To fix this error, please remove the visibility qualifier when it is not
133-
required. Example:
134-
135-
```ignore
136-
struct Bar;
137-
138-
trait Foo {
139-
fn foo();
140-
}
141-
142-
// Directly implemented methods share the visibility of the type itself,
143-
// so `pub` is unnecessary here
144-
impl Bar {}
145-
146-
// Trait methods share the visibility of the trait, so `pub` is
147-
// unnecessary in either case
148-
pub impl Foo for Bar {
149-
pub fn foo() {}
150-
}
151-
```
152-
"##,
153-
154114
E0450: r##"
155115
A tuple constructor was invoked while some of its fields are private. Erroneous
156116
code example:

0 commit comments

Comments
 (0)