]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/loops.rs
Rollup merge of #54370 - nnethercote:better-domain_size, r=nikomatsakis
[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 use errors::Applicability;
20
21 #[derive(Clone, Copy, Debug, PartialEq)]
22 enum LoopKind {
23     Loop(hir::LoopSource),
24     WhileLoop,
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         }
35     }
36 }
37
38 #[derive(Clone, Copy, Debug, PartialEq)]
39 enum Context {
40     Normal,
41     Loop(LoopKind),
42     Closure,
43     LabeledBlock,
44     AnonConst,
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_anon_const(&mut self, c: &'hir hir::AnonConst) {
77         self.with_context(AnonConst, |v| intravisit::walk_anon_const(v, c));
78     }
79
80     fn visit_expr(&mut self, e: &'hir hir::Expr) {
81         match e.node {
82             hir::ExprKind::While(ref e, ref b, _) => {
83                 self.with_context(Loop(LoopKind::WhileLoop), |v| {
84                     v.visit_expr(&e);
85                     v.visit_block(&b);
86                 });
87             }
88             hir::ExprKind::Loop(ref b, _, source) => {
89                 self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b));
90             }
91             hir::ExprKind::Closure(_, ref function_decl, b, _, _) => {
92                 self.visit_fn_decl(&function_decl);
93                 self.with_context(Closure, |v| v.visit_nested_body(b));
94             }
95             hir::ExprKind::Block(ref b, Some(_label)) => {
96                 self.with_context(LabeledBlock, |v| v.visit_block(&b));
97             }
98             hir::ExprKind::Break(label, ref opt_expr) => {
99                 opt_expr.as_ref().map(|e| self.visit_expr(e));
100
101                 if self.require_label_in_labeled_block(e.span, &label, "break") {
102                     // If we emitted an error about an unlabeled break in a labeled
103                     // block, we don't need any further checking for this break any more
104                     return;
105                 }
106
107                 let loop_id = match label.target_id.into() {
108                     Ok(loop_id) => loop_id,
109                     Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID,
110                     Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
111                         self.emit_unlabled_cf_in_while_condition(e.span, "break");
112                         ast::DUMMY_NODE_ID
113                     },
114                     Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID,
115                 };
116
117                 if loop_id != ast::DUMMY_NODE_ID {
118                     if let Node::Block(_) = self.hir_map.find(loop_id).unwrap() {
119                         return
120                     }
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::ExprKind::While(..) => LoopKind::WhileLoop,
129                             hir::ExprKind::Loop(_, _, source) => LoopKind::Loop(source),
130                             ref r => span_bug!(e.span,
131                                                "break label resolved to a non-loop: {:?}", r),
132                         })
133                     };
134                     match loop_kind {
135                         None |
136                         Some(LoopKind::Loop(hir::LoopSource::Loop)) => (),
137                         Some(kind) => {
138                             struct_span_err!(self.sess, e.span, E0571,
139                                              "`break` with value from a `{}` loop",
140                                              kind.name())
141                                 .span_label(e.span,
142                                             "can only break with a value inside \
143                                             `loop` or breakable block")
144                                 .span_suggestion_with_applicability(
145                                     e.span,
146                                     &format!(
147                                         "instead, use `break` on its own \
148                                         without a value inside this `{}` loop",
149                                         kind.name()
150                                     ),
151                                     "break".to_string(),
152                                     Applicability::MaybeIncorrect,
153                                 )
154                                 .emit();
155                         }
156                     }
157                 }
158
159                 self.require_break_cx("break", e.span);
160             }
161             hir::ExprKind::Continue(destination) => {
162                 self.require_label_in_labeled_block(e.span, &destination, "continue");
163
164                 match destination.target_id {
165                     Ok(loop_id) => {
166                         if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() {
167                             struct_span_err!(self.sess, e.span, E0696,
168                                             "`continue` pointing to a labeled block")
169                                 .span_label(e.span,
170                                             "labeled blocks cannot be `continue`'d")
171                                 .span_note(block.span,
172                                             "labeled block the continue points to")
173                                 .emit();
174                         }
175                     }
176                     Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
177                         self.emit_unlabled_cf_in_while_condition(e.span, "continue");
178                     }
179                     Err(_) => {}
180                 }
181                 self.require_break_cx("continue", e.span)
182             },
183             _ => intravisit::walk_expr(self, e),
184         }
185     }
186 }
187
188 impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
189     fn with_context<F>(&mut self, cx: Context, f: F)
190         where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
191     {
192         let old_cx = self.cx;
193         self.cx = cx;
194         f(self);
195         self.cx = old_cx;
196     }
197
198     fn require_break_cx(&self, name: &str, span: Span) {
199         match self.cx {
200             LabeledBlock | Loop(_) => {}
201             Closure => {
202                 struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
203                 .span_label(span, "cannot break inside of a closure")
204                 .emit();
205             }
206             Normal | AnonConst => {
207                 struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
208                 .span_label(span, "cannot break outside of a loop")
209                 .emit();
210             }
211         }
212     }
213
214     fn require_label_in_labeled_block(&mut self, span: Span, label: &Destination, cf_type: &str)
215         -> bool
216     {
217         if self.cx == LabeledBlock {
218             if label.label.is_none() {
219                 struct_span_err!(self.sess, span, E0695,
220                                 "unlabeled `{}` inside of a labeled block", cf_type)
221                     .span_label(span,
222                                 format!("`{}` statements that would diverge to or through \
223                                 a labeled block need to bear a label", cf_type))
224                     .emit();
225                 return true;
226             }
227         }
228         return false;
229     }
230     fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
231         struct_span_err!(self.sess, span, E0590,
232                          "`break` or `continue` with no label in the condition of a `while` loop")
233             .span_label(span,
234                         format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
235             .emit();
236     }
237 }