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