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