]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/loops.rs
34a3f5e54b8a23708ad83904af513c89062b7e76
[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                     return;
113                 }
114
115                 if opt_expr.is_some() {
116                     let loop_kind = if loop_id == ast::DUMMY_NODE_ID {
117                         None
118                     } else {
119                         Some(match self.hir_map.expect_expr(loop_id).node {
120                             hir::ExprWhile(..) => LoopKind::WhileLoop,
121                             hir::ExprLoop(_, _, source) => LoopKind::Loop(source),
122                             hir::ExprBlock(..) => LoopKind::Block,
123                             ref r => span_bug!(e.span,
124                                                "break label resolved to a non-loop: {:?}", r),
125                         })
126                     };
127                     match loop_kind {
128                         None |
129                         Some(LoopKind::Loop(hir::LoopSource::Loop)) |
130                         Some(LoopKind::Block) => (),
131                         Some(kind) => {
132                             struct_span_err!(self.sess, e.span, E0571,
133                                              "`break` with value from a `{}` loop",
134                                              kind.name())
135                                 .span_label(e.span,
136                                             "can only break with a value inside \
137                                             `loop` or breakable block")
138                                 .span_suggestion(e.span,
139                                                  &format!("instead, use `break` on its own \
140                                                            without a value inside this `{}` loop",
141                                                           kind.name()),
142                                                  "break".to_string())
143                                 .emit();
144                         }
145                     }
146                 }
147
148                 self.require_break_cx("break", e.span);
149             }
150             hir::ExprAgain(label) => {
151                 if let Err(hir::LoopIdError::UnlabeledCfInWhileCondition) = label.target_id {
152                     self.emit_unlabled_cf_in_while_condition(e.span, "continue");
153                 }
154                 self.require_break_cx("continue", e.span)
155             },
156             _ => intravisit::walk_expr(self, e),
157         }
158     }
159 }
160
161 impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
162     fn with_context<F>(&mut self, cx: Context, f: F)
163         where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
164     {
165         let old_cx = self.cx;
166         self.cx = cx;
167         f(self);
168         self.cx = old_cx;
169     }
170
171     fn require_break_cx(&self, name: &str, span: Span) {
172         match self.cx {
173             LabeledBlock |
174             Loop(_) => {}
175             Closure => {
176                 struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
177                 .span_label(span, "cannot break inside of a closure")
178                 .emit();
179             }
180             Normal => {
181                 struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
182                 .span_label(span, "cannot break outside of a loop")
183                 .emit();
184             }
185         }
186     }
187
188     fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
189         struct_span_err!(self.sess, span, E0590,
190                          "`break` or `continue` with no label in the condition of a `while` loop")
191             .span_label(span,
192                         format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
193             .emit();
194     }
195 }