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