]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/loops.rs
Rollup merge of #88789 - the8472:rm-zip-bound, r=JohnTitor
[rust.git] / compiler / rustc_passes / src / loops.rs
1 use Context::*;
2
3 use rustc_errors::{struct_span_err, Applicability};
4 use rustc_hir as hir;
5 use rustc_hir::def_id::LocalDefId;
6 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
7 use rustc_hir::{Destination, Movability, Node};
8 use rustc_middle::hir::map::Map;
9 use rustc_middle::ty::query::Providers;
10 use rustc_middle::ty::TyCtxt;
11 use rustc_session::Session;
12 use rustc_span::hygiene::DesugaringKind;
13 use rustc_span::Span;
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: Map<'hir>,
29     cx: Context,
30 }
31
32 fn check_mod_loops(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
33     tcx.hir().visit_item_likes_in_module(
34         module_def_id,
35         &mut CheckLoopVisitor { sess: &tcx.sess, hir_map: tcx.hir(), cx: Normal }.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(break_label, ref opt_expr) => {
72                 if let Some(e) = opt_expr {
73                     self.visit_expr(e);
74                 }
75
76                 if self.require_label_in_labeled_block(e.span, &break_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 break_label.target_id {
83                     Ok(loop_id) => Some(loop_id),
84                     Err(hir::LoopIdError::OutsideLoopScope) => None,
85                     Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
86                         self.emit_unlabled_cf_in_while_condition(e.span, "break");
87                         None
88                     }
89                     Err(hir::LoopIdError::UnresolvedLabel) => None,
90                 };
91
92                 if let Some(Node::Block(_)) = loop_id.and_then(|id| self.hir_map.find(id)) {
93                     return;
94                 }
95
96                 if let Some(break_expr) = opt_expr {
97                     let (head, loop_label, loop_kind) = if let Some(loop_id) = loop_id {
98                         match self.hir_map.expect_expr(loop_id).kind {
99                             hir::ExprKind::Loop(_, label, source, sp) => {
100                                 (Some(sp), label, Some(source))
101                             }
102                             ref r => {
103                                 span_bug!(e.span, "break label resolved to a non-loop: {:?}", r)
104                             }
105                         }
106                     } else {
107                         (None, None, None)
108                     };
109                     match loop_kind {
110                         None | Some(hir::LoopSource::Loop) => (),
111                         Some(kind) => {
112                             let mut err = struct_span_err!(
113                                 self.sess,
114                                 e.span,
115                                 E0571,
116                                 "`break` with value from a `{}` loop",
117                                 kind.name()
118                             );
119                             err.span_label(
120                                 e.span,
121                                 "can only break with a value inside `loop` or breakable block",
122                             );
123                             if let Some(head) = head {
124                                 err.span_label(
125                                     head,
126                                     &format!(
127                                         "you can't `break` with a value in a `{}` loop",
128                                         kind.name()
129                                     ),
130                                 );
131                             }
132                             err.span_suggestion(
133                                 e.span,
134                                 &format!(
135                                     "use `break` on its own without a value inside this `{}` loop",
136                                     kind.name(),
137                                 ),
138                                 format!(
139                                     "break{}",
140                                     break_label
141                                         .label
142                                         .map_or_else(String::new, |l| format!(" {}", l.ident))
143                                 ),
144                                 Applicability::MaybeIncorrect,
145                             );
146                             if let (Some(label), None) = (loop_label, break_label.label) {
147                                 match break_expr.kind {
148                                     hir::ExprKind::Path(hir::QPath::Resolved(
149                                         None,
150                                         hir::Path {
151                                             segments: [segment],
152                                             res: hir::def::Res::Err,
153                                             ..
154                                         },
155                                     )) if label.ident.to_string()
156                                         == format!("'{}", segment.ident) =>
157                                     {
158                                         // This error is redundant, we will have already emitted a
159                                         // suggestion to use the label when `segment` wasn't found
160                                         // (hence the `Res::Err` check).
161                                         err.delay_as_bug();
162                                     }
163                                     _ => {
164                                         err.span_suggestion(
165                                             break_expr.span,
166                                             "alternatively, you might have meant to use the \
167                                              available loop label",
168                                             label.ident.to_string(),
169                                             Applicability::MaybeIncorrect,
170                                         );
171                                     }
172                                 }
173                             }
174                             err.emit();
175                         }
176                     }
177                 }
178
179                 self.require_break_cx("break", e.span);
180             }
181             hir::ExprKind::Continue(destination) => {
182                 self.require_label_in_labeled_block(e.span, &destination, "continue");
183
184                 match destination.target_id {
185                     Ok(loop_id) => {
186                         if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() {
187                             struct_span_err!(
188                                 self.sess,
189                                 e.span,
190                                 E0696,
191                                 "`continue` pointing to a labeled block"
192                             )
193                             .span_label(e.span, "labeled blocks cannot be `continue`'d")
194                             .span_label(block.span, "labeled block the `continue` points to")
195                             .emit();
196                         }
197                     }
198                     Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
199                         self.emit_unlabled_cf_in_while_condition(e.span, "continue");
200                     }
201                     Err(_) => {}
202                 }
203                 self.require_break_cx("continue", e.span)
204             }
205             _ => intravisit::walk_expr(self, e),
206         }
207     }
208 }
209
210 impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
211     fn with_context<F>(&mut self, cx: Context, f: F)
212     where
213         F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>),
214     {
215         let old_cx = self.cx;
216         self.cx = cx;
217         f(self);
218         self.cx = old_cx;
219     }
220
221     fn require_break_cx(&self, name: &str, span: Span) {
222         let err_inside_of = |article, ty, closure_span| {
223             struct_span_err!(self.sess, span, E0267, "`{}` inside of {} {}", name, article, ty)
224                 .span_label(span, format!("cannot `{}` inside of {} {}", name, article, ty))
225                 .span_label(closure_span, &format!("enclosing {}", ty))
226                 .emit();
227         };
228
229         match self.cx {
230             LabeledBlock | Loop(_) => {}
231             Closure(closure_span) => err_inside_of("a", "closure", closure_span),
232             AsyncClosure(closure_span) => err_inside_of("an", "`async` block", closure_span),
233             Normal | AnonConst => {
234                 struct_span_err!(self.sess, span, E0268, "`{}` outside of a loop", name)
235                     .span_label(span, format!("cannot `{}` outside of a loop", name))
236                     .emit();
237             }
238         }
239     }
240
241     fn require_label_in_labeled_block(
242         &mut self,
243         span: Span,
244         label: &Destination,
245         cf_type: &str,
246     ) -> bool {
247         if !span.is_desugaring(DesugaringKind::QuestionMark) && self.cx == LabeledBlock {
248             if label.label.is_none() {
249                 struct_span_err!(
250                     self.sess,
251                     span,
252                     E0695,
253                     "unlabeled `{}` inside of a labeled block",
254                     cf_type
255                 )
256                 .span_label(
257                     span,
258                     format!(
259                         "`{}` statements that would diverge to or through \
260                                 a labeled block need to bear a label",
261                         cf_type
262                     ),
263                 )
264                 .emit();
265                 return true;
266             }
267         }
268         false
269     }
270     fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
271         struct_span_err!(
272             self.sess,
273             span,
274             E0590,
275             "`break` or `continue` with no label in the condition of a `while` loop"
276         )
277         .span_label(span, format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
278         .emit();
279     }
280 }