]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/loops.rs
Auto merge of #38436 - bluecereal:patch-1, r=frewsxcv
[rust.git] / src / librustc_passes / loops.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 use self::Context::*;
11
12 use rustc::session::Session;
13
14 use rustc::dep_graph::DepNode;
15 use rustc::hir::map::Map;
16 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
17 use rustc::hir;
18 use syntax::ast;
19 use syntax_pos::Span;
20
21 #[derive(Clone, Copy, PartialEq)]
22 enum LoopKind {
23     Loop(hir::LoopSource),
24     WhileLoop,
25 }
26
27 impl LoopKind {
28     fn name(self) -> &'static str {
29         match self {
30             LoopKind::Loop(hir::LoopSource::Loop) => "loop",
31             LoopKind::Loop(hir::LoopSource::WhileLet) => "while let",
32             LoopKind::Loop(hir::LoopSource::ForLoop) => "for",
33             LoopKind::WhileLoop => "while",
34         }
35     }
36 }
37
38 #[derive(Clone, Copy, PartialEq)]
39 enum Context {
40     Normal,
41     Loop(LoopKind),
42     Closure,
43 }
44
45 #[derive(Copy, Clone)]
46 struct CheckLoopVisitor<'a, 'hir: 'a> {
47     sess: &'a Session,
48     hir_map: &'a Map<'hir>,
49     cx: Context,
50 }
51
52 pub fn check_crate(sess: &Session, map: &Map) {
53     let _task = map.dep_graph.in_task(DepNode::CheckLoops);
54     let krate = map.krate();
55     krate.visit_all_item_likes(&mut CheckLoopVisitor {
56         sess: sess,
57         hir_map: map,
58         cx: Normal,
59     }.as_deep_visitor());
60 }
61
62 impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
63     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
64         NestedVisitorMap::OnlyBodies(&self.hir_map)
65     }
66
67     fn visit_item(&mut self, i: &'hir hir::Item) {
68         self.with_context(Normal, |v| intravisit::walk_item(v, i));
69     }
70
71     fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) {
72         self.with_context(Normal, |v| intravisit::walk_impl_item(v, i));
73     }
74
75     fn visit_expr(&mut self, e: &'hir hir::Expr) {
76         match e.node {
77             hir::ExprWhile(ref e, ref b, _) => {
78                 self.with_context(Loop(LoopKind::WhileLoop), |v| {
79                     v.visit_expr(&e);
80                     v.visit_block(&b);
81                 });
82             }
83             hir::ExprLoop(ref b, _, source) => {
84                 self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b));
85             }
86             hir::ExprClosure(.., b, _) => {
87                 self.with_context(Closure, |v| v.visit_nested_body(b));
88             }
89             hir::ExprBreak(label, ref opt_expr) => {
90                 if opt_expr.is_some() {
91                     let loop_kind = if let Some(label) = label {
92                         if label.loop_id == ast::DUMMY_NODE_ID {
93                             None
94                         } else {
95                             Some(match self.hir_map.expect_expr(label.loop_id).node {
96                                 hir::ExprWhile(..) => LoopKind::WhileLoop,
97                                 hir::ExprLoop(_, _, source) => LoopKind::Loop(source),
98                                 ref r => span_bug!(e.span,
99                                                    "break label resolved to a non-loop: {:?}", r),
100                             })
101                         }
102                     } else if let Loop(kind) = self.cx {
103                         Some(kind)
104                     } else {
105                         // `break` outside a loop - caught below
106                         None
107                     };
108                     match loop_kind {
109                         None | Some(LoopKind::Loop(hir::LoopSource::Loop)) => (),
110                         Some(kind) => {
111                             struct_span_err!(self.sess, e.span, E0571,
112                                              "`break` with value from a `{}` loop",
113                                              kind.name())
114                                 .span_label(e.span,
115                                             &format!("can only break with a value inside `loop`"))
116                                 .emit();
117                         }
118                     }
119                 }
120                 self.require_loop("break", e.span);
121             }
122             hir::ExprAgain(_) => self.require_loop("continue", e.span),
123             _ => intravisit::walk_expr(self, e),
124         }
125     }
126 }
127
128 impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
129     fn with_context<F>(&mut self, cx: Context, f: F)
130         where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
131     {
132         let old_cx = self.cx;
133         self.cx = cx;
134         f(self);
135         self.cx = old_cx;
136     }
137
138     fn require_loop(&self, name: &str, span: Span) {
139         match self.cx {
140             Loop(_) => {}
141             Closure => {
142                 struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
143                 .span_label(span, &format!("cannot break inside of a closure"))
144                 .emit();
145             }
146             Normal => {
147                 struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
148                 .span_label(span, &format!("cannot break outside of a loop"))
149                 .emit();
150             }
151         }
152     }
153 }