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