]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/loops.rs
Rollup merge of #39888 - nagisa:on-fail-bootstrap, r=alexcrichton
[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                 let loop_id = match label.loop_id.into() {
91                     Ok(loop_id) => loop_id,
92                     Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID,
93                     Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
94                         self.emit_unlabled_cf_in_while_condition(e.span, "break");
95                         ast::DUMMY_NODE_ID
96                     },
97                     Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID,
98                 };
99
100                 if opt_expr.is_some() {
101                     let loop_kind = if loop_id == ast::DUMMY_NODE_ID {
102                         None
103                     } else {
104                         Some(match self.hir_map.expect_expr(loop_id).node {
105                             hir::ExprWhile(..) => LoopKind::WhileLoop,
106                             hir::ExprLoop(_, _, source) => LoopKind::Loop(source),
107                             ref r => span_bug!(e.span,
108                                                "break label resolved to a non-loop: {:?}", r),
109                         })
110                     };
111                     match loop_kind {
112                         None | Some(LoopKind::Loop(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                                             &format!("can only break with a value inside `loop`"))
119                                 .emit();
120                         }
121                     }
122                 }
123
124                 self.require_loop("break", e.span);
125             }
126             hir::ExprAgain(label) => {
127                 if let Err(hir::LoopIdError::UnlabeledCfInWhileCondition) = label.loop_id.into() {
128                     self.emit_unlabled_cf_in_while_condition(e.span, "continue");
129                 }
130                 self.require_loop("continue", e.span)
131             },
132             _ => intravisit::walk_expr(self, e),
133         }
134     }
135 }
136
137 impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
138     fn with_context<F>(&mut self, cx: Context, f: F)
139         where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
140     {
141         let old_cx = self.cx;
142         self.cx = cx;
143         f(self);
144         self.cx = old_cx;
145     }
146
147     fn require_loop(&self, name: &str, span: Span) {
148         match self.cx {
149             Loop(_) => {}
150             Closure => {
151                 struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
152                 .span_label(span, &format!("cannot break inside of a closure"))
153                 .emit();
154             }
155             Normal => {
156                 struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
157                 .span_label(span, &format!("cannot break outside of a loop"))
158                 .emit();
159             }
160         }
161     }
162
163     fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
164         struct_span_err!(self.sess, span, E0590,
165                          "`break` or `continue` with no label in the condition of a `while` loop")
166             .span_label(span,
167                         &format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
168             .emit();
169     }
170 }