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