]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/loops.rs
533e043efa9d223f4f3f1addc239f21a25d58b46
[rust.git] / src / librustc_passes / loops.rs
1 use Context::*;
2
3 use rustc::session::Session;
4
5 use rustc::ty::query::Providers;
6 use rustc::ty::TyCtxt;
7 use rustc::hir::def_id::DefId;
8 use rustc::hir::map::Map;
9 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
10 use rustc::hir::{self, Node, Destination};
11 use syntax::ast;
12 use syntax::struct_span_err;
13 use syntax_pos::Span;
14 use errors::Applicability;
15
16 #[derive(Clone, Copy, Debug, PartialEq)]
17 enum LoopKind {
18     Loop(hir::LoopSource),
19     WhileLoop,
20 }
21
22 impl LoopKind {
23     fn name(self) -> &'static str {
24         match self {
25             LoopKind::Loop(hir::LoopSource::Loop) => "loop",
26             LoopKind::Loop(hir::LoopSource::WhileLet) => "while let",
27             LoopKind::Loop(hir::LoopSource::ForLoop) => "for",
28             LoopKind::WhileLoop => "while",
29         }
30     }
31 }
32
33 #[derive(Clone, Copy, Debug, PartialEq)]
34 enum Context {
35     Normal,
36     Loop(LoopKind),
37     Closure,
38     LabeledBlock,
39     AnonConst,
40 }
41
42 #[derive(Copy, Clone)]
43 struct CheckLoopVisitor<'a, 'hir: 'a> {
44     sess: &'a Session,
45     hir_map: &'a Map<'hir>,
46     cx: Context,
47 }
48
49 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
50     for &module in tcx.hir().krate().modules.keys() {
51         tcx.ensure().check_mod_loops(tcx.hir().local_def_id(module));
52     }
53 }
54
55 fn check_mod_loops<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>, module_def_id: DefId) {
56     tcx.hir().visit_item_likes_in_module(module_def_id, &mut CheckLoopVisitor {
57         sess: &tcx.sess,
58         hir_map: &tcx.hir(),
59         cx: Normal,
60     }.as_deep_visitor());
61 }
62
63 pub(crate) fn provide(providers: &mut Providers<'_>) {
64     *providers = Providers {
65         check_mod_loops,
66         ..*providers
67     };
68 }
69
70 impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
71     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
72         NestedVisitorMap::OnlyBodies(&self.hir_map)
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(
144                                     e.span,
145                                     &format!(
146                                         "instead, use `break` on its own \
147                                         without a value inside this `{}` loop",
148                                         kind.name()
149                                     ),
150                                     "break".to_string(),
151                                     Applicability::MaybeIncorrect,
152                                 )
153                                 .emit();
154                         }
155                     }
156                 }
157
158                 self.require_break_cx("break", e.span);
159             }
160             hir::ExprKind::Continue(destination) => {
161                 self.require_label_in_labeled_block(e.span, &destination, "continue");
162
163                 match destination.target_id {
164                     Ok(loop_id) => {
165                         if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() {
166                             struct_span_err!(self.sess, e.span, E0696,
167                                             "`continue` pointing to a labeled block")
168                                 .span_label(e.span,
169                                             "labeled blocks cannot be `continue`'d")
170                                 .span_note(block.span,
171                                             "labeled block the continue points to")
172                                 .emit();
173                         }
174                     }
175                     Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
176                         self.emit_unlabled_cf_in_while_condition(e.span, "continue");
177                     }
178                     Err(_) => {}
179                 }
180                 self.require_break_cx("continue", e.span)
181             },
182             _ => intravisit::walk_expr(self, e),
183         }
184     }
185 }
186
187 impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
188     fn with_context<F>(&mut self, cx: Context, f: F)
189         where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
190     {
191         let old_cx = self.cx;
192         self.cx = cx;
193         f(self);
194         self.cx = old_cx;
195     }
196
197     fn require_break_cx(&self, name: &str, span: Span) {
198         match self.cx {
199             LabeledBlock | Loop(_) => {}
200             Closure => {
201                 struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
202                 .span_label(span, "cannot break inside of a closure")
203                 .emit();
204             }
205             Normal | AnonConst => {
206                 struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
207                 .span_label(span, "cannot break outside of a loop")
208                 .emit();
209             }
210         }
211     }
212
213     fn require_label_in_labeled_block(&mut self, span: Span, label: &Destination, cf_type: &str)
214         -> bool
215     {
216         if self.cx == LabeledBlock {
217             if label.label.is_none() {
218                 struct_span_err!(self.sess, span, E0695,
219                                 "unlabeled `{}` inside of a labeled block", cf_type)
220                     .span_label(span,
221                                 format!("`{}` statements that would diverge to or through \
222                                 a labeled block need to bear a label", cf_type))
223                     .emit();
224                 return true;
225             }
226         }
227         return false;
228     }
229     fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
230         struct_span_err!(self.sess, span, E0590,
231                          "`break` or `continue` with no label in the condition of a `while` loop")
232             .span_label(span,
233                         format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
234             .emit();
235     }
236 }