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