]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/loops.rs
Remove need for &format!(...) or &&"" dances in `span_label` calls
[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::hir::map::Map;
15 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
16 use rustc::hir;
17 use syntax::ast;
18 use syntax_pos::Span;
19
20 #[derive(Clone, Copy, PartialEq)]
21 enum LoopKind {
22     Loop(hir::LoopSource),
23     WhileLoop,
24 }
25
26 impl LoopKind {
27     fn name(self) -> &'static str {
28         match self {
29             LoopKind::Loop(hir::LoopSource::Loop) => "loop",
30             LoopKind::Loop(hir::LoopSource::WhileLet) => "while let",
31             LoopKind::Loop(hir::LoopSource::ForLoop) => "for",
32             LoopKind::WhileLoop => "while",
33         }
34     }
35 }
36
37 #[derive(Clone, Copy, PartialEq)]
38 enum Context {
39     Normal,
40     Loop(LoopKind),
41     Closure,
42 }
43
44 #[derive(Copy, Clone)]
45 struct CheckLoopVisitor<'a, 'hir: 'a> {
46     sess: &'a Session,
47     hir_map: &'a Map<'hir>,
48     cx: Context,
49 }
50
51 pub fn check_crate(sess: &Session, map: &Map) {
52     let krate = map.krate();
53     krate.visit_all_item_likes(&mut CheckLoopVisitor {
54         sess: sess,
55         hir_map: map,
56         cx: Normal,
57     }.as_deep_visitor());
58 }
59
60 impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
61     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
62         NestedVisitorMap::OnlyBodies(&self.hir_map)
63     }
64
65     fn visit_item(&mut self, i: &'hir hir::Item) {
66         self.with_context(Normal, |v| intravisit::walk_item(v, i));
67     }
68
69     fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) {
70         self.with_context(Normal, |v| intravisit::walk_impl_item(v, i));
71     }
72
73     fn visit_expr(&mut self, e: &'hir hir::Expr) {
74         match e.node {
75             hir::ExprWhile(ref e, ref b, _) => {
76                 self.with_context(Loop(LoopKind::WhileLoop), |v| {
77                     v.visit_expr(&e);
78                     v.visit_block(&b);
79                 });
80             }
81             hir::ExprLoop(ref b, _, source) => {
82                 self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b));
83             }
84             hir::ExprClosure(.., b, _) => {
85                 self.with_context(Closure, |v| v.visit_nested_body(b));
86             }
87             hir::ExprBreak(label, ref opt_expr) => {
88                 let loop_id = match label.target_id {
89                     hir::ScopeTarget::Block(_) => return,
90                     hir::ScopeTarget::Loop(loop_res) => {
91                         match loop_res.into() {
92                             Ok(loop_id) => loop_id,
93                             Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID,
94                             Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
95                                 self.emit_unlabled_cf_in_while_condition(e.span, "break");
96                                 ast::DUMMY_NODE_ID
97                             },
98                             Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID,
99                         }
100                     }
101                 };
102
103                 if opt_expr.is_some() {
104                     let loop_kind = if loop_id == ast::DUMMY_NODE_ID {
105                         None
106                     } else {
107                         Some(match self.hir_map.expect_expr(loop_id).node {
108                             hir::ExprWhile(..) => LoopKind::WhileLoop,
109                             hir::ExprLoop(_, _, source) => LoopKind::Loop(source),
110                             ref r => span_bug!(e.span,
111                                                "break label resolved to a non-loop: {:?}", r),
112                         })
113                     };
114                     match loop_kind {
115                         None | Some(LoopKind::Loop(hir::LoopSource::Loop)) => (),
116                         Some(kind) => {
117                             struct_span_err!(self.sess, e.span, E0571,
118                                              "`break` with value from a `{}` loop",
119                                              kind.name())
120                                 .span_label(e.span,
121                                             "can only break with a value inside `loop`")
122                                 .emit();
123                         }
124                     }
125                 }
126
127                 self.require_loop("break", e.span);
128             }
129             hir::ExprAgain(label) => {
130                 if let hir::ScopeTarget::Loop(
131                     hir::LoopIdResult::Err(
132                         hir::LoopIdError::UnlabeledCfInWhileCondition)) = label.target_id {
133                     self.emit_unlabled_cf_in_while_condition(e.span, "continue");
134                 }
135                 self.require_loop("continue", e.span)
136             },
137             _ => intravisit::walk_expr(self, e),
138         }
139     }
140 }
141
142 impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
143     fn with_context<F>(&mut self, cx: Context, f: F)
144         where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
145     {
146         let old_cx = self.cx;
147         self.cx = cx;
148         f(self);
149         self.cx = old_cx;
150     }
151
152     fn require_loop(&self, name: &str, span: Span) {
153         match self.cx {
154             Loop(_) => {}
155             Closure => {
156                 struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
157                 .span_label(span, "cannot break inside of a closure")
158                 .emit();
159             }
160             Normal => {
161                 struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
162                 .span_label(span, "cannot break outside of a loop")
163                 .emit();
164             }
165         }
166     }
167
168     fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
169         struct_span_err!(self.sess, span, E0590,
170                          "`break` or `continue` with no label in the condition of a `while` loop")
171             .span_label(span,
172                         format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
173             .emit();
174     }
175 }