85 lines
2.5 KiB
Rust
Raw Normal View History

2014-07-27 07:50:46 -04:00
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use self::Context::*;
2016-01-21 10:52:37 +01:00
use rustc::session::Session;
use rustc::dep_graph::DepNode;
2016-03-29 08:50:44 +03:00
use rustc::hir::map::Map;
use rustc::hir::intravisit::{self, Visitor};
use rustc::hir;
use syntax::codemap::Span;
2012-03-26 12:54:06 +02:00
#[derive(Clone, Copy, PartialEq)]
enum Context {
Normal, Loop, Closure
}
2012-03-26 12:54:06 +02:00
2015-03-30 09:38:44 -04:00
#[derive(Copy, Clone)]
2014-03-06 05:07:47 +02:00
struct CheckLoopVisitor<'a> {
sess: &'a Session,
cx: Context
}
pub fn check_crate(sess: &Session, map: &Map) {
let _task = map.dep_graph.in_task(DepNode::CheckLoops);
let krate = map.krate();
krate.visit_all_items(&mut CheckLoopVisitor { sess: sess, cx: Normal });
}
impl<'a, 'v> Visitor<'v> for CheckLoopVisitor<'a> {
2015-07-31 00:04:06 -07:00
fn visit_item(&mut self, i: &hir::Item) {
self.with_context(Normal, |v| intravisit::walk_item(v, i));
}
2015-07-31 00:04:06 -07:00
fn visit_expr(&mut self, e: &hir::Expr) {
match e.node {
2015-07-31 00:04:06 -07:00
hir::ExprWhile(ref e, ref b, _) => {
2016-02-09 21:30:52 +01:00
self.visit_expr(&e);
self.with_context(Loop, |v| v.visit_block(&b));
}
2015-07-31 00:04:06 -07:00
hir::ExprLoop(ref b, _) => {
2016-02-09 21:30:52 +01:00
self.with_context(Loop, |v| v.visit_block(&b));
}
hir::ExprClosure(_, _, ref b, _) => {
2016-02-09 21:30:52 +01:00
self.with_context(Closure, |v| v.visit_block(&b));
}
2015-07-31 00:04:06 -07:00
hir::ExprBreak(_) => self.require_loop("break", e.span),
hir::ExprAgain(_) => self.require_loop("continue", e.span),
_ => intravisit::walk_expr(self, e)
}
}
}
2014-03-06 05:07:47 +02:00
impl<'a> CheckLoopVisitor<'a> {
2014-12-08 20:26:43 -05:00
fn with_context<F>(&mut self, cx: Context, f: F) where
F: FnOnce(&mut CheckLoopVisitor<'a>),
{
let old_cx = self.cx;
self.cx = cx;
f(self);
self.cx = old_cx;
}
fn require_loop(&self, name: &str, span: Span) {
match self.cx {
Loop => {}
Closure => {
2015-01-18 16:58:25 -08:00
span_err!(self.sess, span, E0267,
"`{}` inside of a closure", name);
}
Normal => {
2015-01-18 16:58:25 -08:00
span_err!(self.sess, span, E0268,
"`{}` outside of loop", name);
}
}
}
}