-
Notifications
You must be signed in to change notification settings - Fork 13.2k
/
Copy pathloops.rs
226 lines (207 loc) · 8.61 KB
/
loops.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use self::Context::*;
use rustc::session::Session;
use rustc::hir::map::Map;
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::{self, Destination};
use syntax::ast;
use syntax_pos::Span;
#[derive(Clone, Copy, PartialEq)]
enum LoopKind {
Loop(hir::LoopSource),
WhileLoop,
}
impl LoopKind {
fn name(self) -> &'static str {
match self {
LoopKind::Loop(hir::LoopSource::Loop) => "loop",
LoopKind::Loop(hir::LoopSource::WhileLet) => "while let",
LoopKind::Loop(hir::LoopSource::ForLoop) => "for",
LoopKind::WhileLoop => "while",
}
}
}
#[derive(Clone, Copy, PartialEq)]
enum Context {
Normal,
Loop(LoopKind),
Closure,
LabeledBlock,
}
#[derive(Copy, Clone)]
struct CheckLoopVisitor<'a, 'hir: 'a> {
sess: &'a Session,
hir_map: &'a Map<'hir>,
cx: Context,
}
pub fn check_crate(sess: &Session, map: &Map) {
let krate = map.krate();
krate.visit_all_item_likes(&mut CheckLoopVisitor {
sess,
hir_map: map,
cx: Normal,
}.as_deep_visitor());
}
impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
NestedVisitorMap::OnlyBodies(&self.hir_map)
}
fn visit_item(&mut self, i: &'hir hir::Item) {
self.with_context(Normal, |v| intravisit::walk_item(v, i));
}
fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) {
self.with_context(Normal, |v| intravisit::walk_impl_item(v, i));
}
fn visit_expr(&mut self, e: &'hir hir::Expr) {
match e.node {
hir::ExprWhile(ref e, ref b, _) => {
self.with_context(Loop(LoopKind::WhileLoop), |v| {
v.visit_expr(&e);
v.visit_block(&b);
});
}
hir::ExprLoop(ref b, _, source) => {
self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b));
}
hir::ExprClosure(_, ref function_decl, b, _, _) => {
self.visit_fn_decl(&function_decl);
self.with_context(Closure, |v| v.visit_nested_body(b));
}
hir::ExprBlock(ref b, Some(_label)) => {
self.with_context(LabeledBlock, |v| v.visit_block(&b));
}
hir::ExprBreak(label, ref opt_expr) => {
if self.require_label_in_labeled_block(e.span, &label, "break") {
// If we emitted an error about an unlabeled break in a labeled
// block, we don't need any further checking for this break any more
return;
}
let loop_id = match label.target_id.into() {
Ok(loop_id) => loop_id,
Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID,
Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
self.emit_unlabled_cf_in_while_condition(e.span, "break");
ast::DUMMY_NODE_ID
},
Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID,
};
if loop_id != ast::DUMMY_NODE_ID {
match self.hir_map.find(loop_id).unwrap() {
hir::map::NodeBlock(_) => return,
_=> (),
}
}
if opt_expr.is_some() {
let loop_kind = if loop_id == ast::DUMMY_NODE_ID {
None
} else {
Some(match self.hir_map.expect_expr(loop_id).node {
hir::ExprWhile(..) => LoopKind::WhileLoop,
hir::ExprLoop(_, _, source) => LoopKind::Loop(source),
ref r => span_bug!(e.span,
"break label resolved to a non-loop: {:?}", r),
})
};
match loop_kind {
None |
Some(LoopKind::Loop(hir::LoopSource::Loop)) => (),
Some(kind) => {
struct_span_err!(self.sess, e.span, E0571,
"`break` with value from a `{}` loop",
kind.name())
.span_label(e.span,
"can only break with a value inside \
`loop` or breakable block")
.span_suggestion(e.span,
&format!("instead, use `break` on its own \
without a value inside this `{}` loop",
kind.name()),
"break".to_string())
.emit();
}
}
}
self.require_break_cx("break", e.span);
}
hir::ExprAgain(label) => {
self.require_label_in_labeled_block(e.span, &label, "continue");
match label.target_id {
Ok(loop_id) => {
if let hir::map::NodeBlock(block) = self.hir_map.find(loop_id).unwrap() {
struct_span_err!(self.sess, e.span, E0696,
"`continue` pointing to a labeled block")
.span_label(e.span,
"labeled blocks cannot be `continue`'d")
.span_note(block.span,
"labeled block the continue points to")
.emit();
}
}
Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
self.emit_unlabled_cf_in_while_condition(e.span, "continue");
}
_ => {}
}
self.require_break_cx("continue", e.span)
},
_ => intravisit::walk_expr(self, e),
}
}
}
impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
fn with_context<F>(&mut self, cx: Context, f: F)
where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
{
let old_cx = self.cx;
self.cx = cx;
f(self);
self.cx = old_cx;
}
fn require_break_cx(&self, name: &str, span: Span) {
match self.cx {
LabeledBlock |
Loop(_) => {}
Closure => {
struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
.span_label(span, "cannot break inside of a closure")
.emit();
}
Normal => {
struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
.span_label(span, "cannot break outside of a loop")
.emit();
}
}
}
fn require_label_in_labeled_block(&mut self, span: Span, label: &Destination, cf_type: &str)
-> bool
{
if self.cx == LabeledBlock {
if label.label.is_none() {
struct_span_err!(self.sess, span, E0695,
"unlabeled `{}` inside of a labeled block", cf_type)
.span_label(span,
format!("`{}` statements that would diverge to or through \
a labeled block need to bear a label", cf_type))
.emit();
return true;
}
}
return false;
}
fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
struct_span_err!(self.sess, span, E0590,
"`break` or `continue` with no label in the condition of a `while` loop")
.span_label(span,
format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
.emit();
}
}