]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/loops.rs
Add E0695 for unlabeled breaks
[rust.git] / src / librustc_passes / loops.rs
1 // Copyright 2012-2014 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 use self::Context::*;
11
12 use rustc::session::Session;
13
14 use rustc::hir::map::Map;
15 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
16 use rustc::hir;
17 use syntax::ast;
18 use syntax_pos::Span;
19
20 #[derive(Clone, Copy, PartialEq)]
21 enum LoopKind {
22     Loop(hir::LoopSource),
23     WhileLoop,
24     Block,
25 }
26
27 impl LoopKind {
28     fn name(self) -> &'static str {
29         match self {
30             LoopKind::Loop(hir::LoopSource::Loop) => "loop",
31             LoopKind::Loop(hir::LoopSource::WhileLet) => "while let",
32             LoopKind::Loop(hir::LoopSource::ForLoop) => "for",
33             LoopKind::WhileLoop => "while",
34             LoopKind::Block => "block",
35         }
36     }
37 }
38
39 #[derive(Clone, Copy, PartialEq)]
40 enum Context {
41     Normal,
42     Loop(LoopKind),
43     Closure,
44     LabeledBlock,
45 }
46
47 #[derive(Copy, Clone)]
48 struct CheckLoopVisitor<'a, 'hir: 'a> {
49     sess: &'a Session,
50     hir_map: &'a Map<'hir>,
51     cx: Context,
52 }
53
54 pub fn check_crate(sess: &Session, map: &Map) {
55     let krate = map.krate();
56     krate.visit_all_item_likes(&mut CheckLoopVisitor {
57         sess,
58         hir_map: map,
59         cx: Normal,
60     }.as_deep_visitor());
61 }
62
63 impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
64     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
65         NestedVisitorMap::OnlyBodies(&self.hir_map)
66     }
67
68     fn visit_item(&mut self, i: &'hir hir::Item) {
69         self.with_context(Normal, |v| intravisit::walk_item(v, i));
70     }
71
72     fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) {
73         self.with_context(Normal, |v| intravisit::walk_impl_item(v, i));
74     }
75
76     fn visit_expr(&mut self, e: &'hir hir::Expr) {
77         match e.node {
78             hir::ExprWhile(ref e, ref b, _) => {
79                 self.with_context(Loop(LoopKind::WhileLoop), |v| {
80                     v.visit_expr(&e);
81                     v.visit_block(&b);
82                 });
83             }
84             hir::ExprLoop(ref b, _, source) => {
85                 self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b));
86             }
87             hir::ExprClosure(.., b, _, _) => {
88                 self.with_context(Closure, |v| v.visit_nested_body(b));
89             }
90             hir::ExprBlock(ref b, Some(_label)) => {
91                 self.with_context(LabeledBlock, |v| v.visit_block(&b));
92             }
93             hir::ExprBreak(label, ref opt_expr) => {
94                 let loop_id = match label.target_id.into() {
95                     Ok(loop_id) => loop_id,
96                     Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID,
97                     Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
98                         self.emit_unlabled_cf_in_while_condition(e.span, "break");
99                         ast::DUMMY_NODE_ID
100                     },
101                     Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID,
102                 };
103
104                 if loop_id != ast::DUMMY_NODE_ID {
105                     match self.hir_map.find(loop_id).unwrap() {
106                         hir::map::NodeBlock(_) => return,
107                         _=> (),
108                     }
109                 }
110
111                 if self.cx == LabeledBlock {
112                     if label.label.is_none() {
113                         struct_span_err!(self.sess, e.span, E0695,
114                                         "unlabeled `break` inside of a labeled block")
115                             .span_label(e.span,
116                                         "`break` statements that would diverge to or through \
117                                         a labeled block need to bear a label")
118                             .emit();
119                     }
120                     return;
121                 }
122
123                 if opt_expr.is_some() {
124                     let loop_kind = if loop_id == ast::DUMMY_NODE_ID {
125                         None
126                     } else {
127                         Some(match self.hir_map.expect_expr(loop_id).node {
128                             hir::ExprWhile(..) => LoopKind::WhileLoop,
129                             hir::ExprLoop(_, _, source) => LoopKind::Loop(source),
130                             hir::ExprBlock(..) => LoopKind::Block,
131                             ref r => span_bug!(e.span,
132                                                "break label resolved to a non-loop: {:?}", r),
133                         })
134                     };
135                     match loop_kind {
136                         None |
137                         Some(LoopKind::Loop(hir::LoopSource::Loop)) |
138                         Some(LoopKind::Block) => (),
139                         Some(kind) => {
140                             struct_span_err!(self.sess, e.span, E0571,
141                                              "`break` with value from a `{}` loop",
142                                              kind.name())
143                                 .span_label(e.span,
144                                             "can only break with a value inside \
145                                             `loop` or breakable block")
146                                 .span_suggestion(e.span,
147                                                  &format!("instead, use `break` on its own \
148                                                            without a value inside this `{}` loop",
149                                                           kind.name()),
150                                                  "break".to_string())
151                                 .emit();
152                         }
153                     }
154                 }
155
156                 self.require_break_cx("break", e.span);
157             }
158             hir::ExprAgain(label) => {
159                 if let Err(hir::LoopIdError::UnlabeledCfInWhileCondition) = label.target_id {
160                     self.emit_unlabled_cf_in_while_condition(e.span, "continue");
161                 }
162                 self.require_break_cx("continue", e.span)
163             },
164             _ => intravisit::walk_expr(self, e),
165         }
166     }
167 }
168
169 impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
170     fn with_context<F>(&mut self, cx: Context, f: F)
171         where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
172     {
173         let old_cx = self.cx;
174         self.cx = cx;
175         f(self);
176         self.cx = old_cx;
177     }
178
179     fn require_break_cx(&self, name: &str, span: Span) {
180         match self.cx {
181             LabeledBlock |
182             Loop(_) => {}
183             Closure => {
184                 struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
185                 .span_label(span, "cannot break inside of a closure")
186                 .emit();
187             }
188             Normal => {
189                 struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
190                 .span_label(span, "cannot break outside of a loop")
191                 .emit();
192             }
193         }
194     }
195
196     fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
197         struct_span_err!(self.sess, span, E0590,
198                          "`break` or `continue` with no label in the condition of a `while` loop")
199             .span_label(span,
200                         format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
201             .emit();
202     }
203 }