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