]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/loops.rs
Rollup merge of #67877 - dtolnay:const-_, r=nagisa
[rust.git] / src / librustc_passes / loops.rs
1 use Context::*;
2
3 use rustc::session::Session;
4
5 use errors::Applicability;
6 use rustc::hir::intravisit::{self, NestedVisitorMap, Visitor};
7 use rustc::hir::map::Map;
8 use rustc::ty::query::Providers;
9 use rustc::ty::TyCtxt;
10 use rustc_hir as hir;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::{Destination, Movability, Node};
13 use rustc_span::Span;
14 use syntax::struct_span_err;
15
16 use rustc_error_codes::*;
17
18 #[derive(Clone, Copy, Debug, PartialEq)]
19 enum Context {
20     Normal,
21     Loop(hir::LoopSource),
22     Closure(Span),
23     AsyncClosure(Span),
24     LabeledBlock,
25     AnonConst,
26 }
27
28 #[derive(Copy, Clone)]
29 struct CheckLoopVisitor<'a, 'hir> {
30     sess: &'a Session,
31     hir_map: &'a Map<'hir>,
32     cx: Context,
33 }
34
35 fn check_mod_loops(tcx: TyCtxt<'_>, module_def_id: DefId) {
36     tcx.hir().visit_item_likes_in_module(
37         module_def_id,
38         &mut CheckLoopVisitor { sess: &tcx.sess, hir_map: &tcx.hir(), cx: Normal }
39             .as_deep_visitor(),
40     );
41 }
42
43 pub(crate) fn provide(providers: &mut Providers<'_>) {
44     *providers = Providers { check_mod_loops, ..*providers };
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<'hir>) {
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(Movability::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 => {
105                                 span_bug!(e.span, "break label resolved to a non-loop: {:?}", r)
106                             }
107                         })
108                     };
109                     match loop_kind {
110                         None | Some(hir::LoopSource::Loop) => (),
111                         Some(kind) => {
112                             struct_span_err!(
113                                 self.sess,
114                                 e.span,
115                                 E0571,
116                                 "`break` with value from a `{}` loop",
117                                 kind.name()
118                             )
119                             .span_label(
120                                 e.span,
121                                 "can only break with a value inside \
122                                             `loop` or breakable block",
123                             )
124                             .span_suggestion(
125                                 e.span,
126                                 &format!(
127                                     "instead, use `break` on its own \
128                                         without a value inside this `{}` loop",
129                                     kind.name()
130                                 ),
131                                 "break".to_string(),
132                                 Applicability::MaybeIncorrect,
133                             )
134                             .emit();
135                         }
136                     }
137                 }
138
139                 self.require_break_cx("break", e.span);
140             }
141             hir::ExprKind::Continue(destination) => {
142                 self.require_label_in_labeled_block(e.span, &destination, "continue");
143
144                 match destination.target_id {
145                     Ok(loop_id) => {
146                         if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() {
147                             struct_span_err!(
148                                 self.sess,
149                                 e.span,
150                                 E0696,
151                                 "`continue` pointing to a labeled block"
152                             )
153                             .span_label(e.span, "labeled blocks cannot be `continue`'d")
154                             .span_label(block.span, "labeled block the `continue` points to")
155                             .emit();
156                         }
157                     }
158                     Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
159                         self.emit_unlabled_cf_in_while_condition(e.span, "continue");
160                     }
161                     Err(_) => {}
162                 }
163                 self.require_break_cx("continue", e.span)
164             }
165             _ => intravisit::walk_expr(self, e),
166         }
167     }
168 }
169
170 impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
171     fn with_context<F>(&mut self, cx: Context, f: F)
172     where
173         F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>),
174     {
175         let old_cx = self.cx;
176         self.cx = cx;
177         f(self);
178         self.cx = old_cx;
179     }
180
181     fn require_break_cx(&self, name: &str, span: Span) {
182         let err_inside_of = |article, ty, closure_span| {
183             struct_span_err!(self.sess, span, E0267, "`{}` inside of {} {}", name, article, ty)
184                 .span_label(span, format!("cannot `{}` inside of {} {}", name, article, ty))
185                 .span_label(closure_span, &format!("enclosing {}", ty))
186                 .emit();
187         };
188
189         match self.cx {
190             LabeledBlock | Loop(_) => {}
191             Closure(closure_span) => err_inside_of("a", "closure", closure_span),
192             AsyncClosure(closure_span) => err_inside_of("an", "`async` block", closure_span),
193             Normal | AnonConst => {
194                 struct_span_err!(self.sess, span, E0268, "`{}` outside of a loop", name)
195                     .span_label(span, format!("cannot `{}` outside of a loop", name))
196                     .emit();
197             }
198         }
199     }
200
201     fn require_label_in_labeled_block(
202         &mut self,
203         span: Span,
204         label: &Destination,
205         cf_type: &str,
206     ) -> bool {
207         if self.cx == LabeledBlock {
208             if label.label.is_none() {
209                 struct_span_err!(
210                     self.sess,
211                     span,
212                     E0695,
213                     "unlabeled `{}` inside of a labeled block",
214                     cf_type
215                 )
216                 .span_label(
217                     span,
218                     format!(
219                         "`{}` statements that would diverge to or through \
220                                 a labeled block need to bear a label",
221                         cf_type
222                     ),
223                 )
224                 .emit();
225                 return true;
226             }
227         }
228         return false;
229     }
230     fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
231         struct_span_err!(
232             self.sess,
233             span,
234             E0590,
235             "`break` or `continue` with no label in the condition of a `while` loop"
236         )
237         .span_label(span, format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
238         .emit();
239     }
240 }