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