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