1
Fork 0
rust/src/librustc_passes/loops.rs

234 lines
8.9 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;
2016-03-29 08:50:44 +03:00
use rustc::hir::map::Map;
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::{self, Destination};
use syntax::ast;
use syntax_pos::Span;
2012-03-26 12:54:06 +02:00
2018-07-01 23:40:03 +01:00
#[derive(Clone, Copy, Debug, PartialEq)]
enum LoopKind {
Loop(hir::LoopSource),
WhileLoop,
}
impl LoopKind {
fn name(self) -> &'static str {
match self {
LoopKind::Loop(hir::LoopSource::Loop) => "loop",
LoopKind::Loop(hir::LoopSource::WhileLet) => "while let",
LoopKind::Loop(hir::LoopSource::ForLoop) => "for",
LoopKind::WhileLoop => "while",
}
}
}
2018-07-01 23:40:03 +01:00
#[derive(Clone, Copy, Debug, PartialEq)]
enum Context {
2016-07-21 07:01:14 +05:30
Normal,
Loop(LoopKind),
2016-07-21 07:01:14 +05:30
Closure,
LabeledBlock,
AnonConst,
}
2012-03-26 12:54:06 +02:00
2015-03-30 09:38:44 -04:00
#[derive(Copy, Clone)]
2017-01-26 03:21:50 +02:00
struct CheckLoopVisitor<'a, 'hir: 'a> {
sess: &'a Session,
2017-01-26 03:21:50 +02:00
hir_map: &'a Map<'hir>,
2016-07-21 07:01:14 +05:30
cx: Context,
}
pub fn check_crate(sess: &Session, map: &Map) {
let krate = map.krate();
krate.visit_all_item_likes(&mut CheckLoopVisitor {
sess,
hir_map: map,
2016-07-21 07:01:14 +05:30
cx: Normal,
}.as_deep_visitor());
}
2017-01-26 03:21:50 +02:00
impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> {
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'hir> {
NestedVisitorMap::OnlyBodies(&self.hir_map)
2016-10-29 15:01:11 +02:00
}
2017-01-26 03:21:50 +02:00
fn visit_item(&mut self, i: &'hir hir::Item) {
self.with_context(Normal, |v| intravisit::walk_item(v, i));
}
2017-01-26 03:21:50 +02:00
fn visit_impl_item(&mut self, i: &'hir hir::ImplItem) {
self.with_context(Normal, |v| intravisit::walk_impl_item(v, i));
}
fn visit_anon_const(&mut self, c: &'hir hir::AnonConst) {
self.with_context(AnonConst, |v| intravisit::walk_anon_const(v, c));
}
2017-01-26 03:21:50 +02:00
fn visit_expr(&mut self, e: &'hir hir::Expr) {
match e.node {
2015-07-31 00:04:06 -07:00
hir::ExprWhile(ref e, ref b, _) => {
self.with_context(Loop(LoopKind::WhileLoop), |v| {
v.visit_expr(&e);
v.visit_block(&b);
});
}
hir::ExprLoop(ref b, _, source) => {
self.with_context(Loop(LoopKind::Loop(source)), |v| v.visit_block(&b));
}
hir::ExprClosure(_, ref function_decl, b, _, _) => {
self.visit_fn_decl(&function_decl);
self.with_context(Closure, |v| v.visit_nested_body(b));
}
hir::ExprBlock(ref b, Some(_label)) => {
self.with_context(LabeledBlock, |v| v.visit_block(&b));
}
hir::ExprBreak(label, ref opt_expr) => {
opt_expr.as_ref().map(|e| self.visit_expr(e));
2018-05-16 09:18:26 +02:00
if self.require_label_in_labeled_block(e.span, &label, "break") {
// If we emitted an error about an unlabeled break in a labeled
// block, we don't need any further checking for this break any more
return;
}
let loop_id = match label.target_id.into() {
Ok(loop_id) => loop_id,
Err(hir::LoopIdError::OutsideLoopScope) => ast::DUMMY_NODE_ID,
Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
self.emit_unlabled_cf_in_while_condition(e.span, "break");
ast::DUMMY_NODE_ID
},
Err(hir::LoopIdError::UnresolvedLabel) => ast::DUMMY_NODE_ID,
};
if loop_id != ast::DUMMY_NODE_ID {
match self.hir_map.find(loop_id).unwrap() {
hir::map::NodeBlock(_) => return,
_=> (),
}
}
if opt_expr.is_some() {
let loop_kind = if loop_id == ast::DUMMY_NODE_ID {
None
2017-02-15 14:52:27 -08:00
} else {
Some(match self.hir_map.expect_expr(loop_id).node {
2017-02-15 14:52:27 -08:00
hir::ExprWhile(..) => LoopKind::WhileLoop,
hir::ExprLoop(_, _, source) => LoopKind::Loop(source),
ref r => span_bug!(e.span,
"break label resolved to a non-loop: {:?}", r),
})
};
match loop_kind {
None |
2018-05-16 09:18:26 +02:00
Some(LoopKind::Loop(hir::LoopSource::Loop)) => (),
Some(kind) => {
struct_span_err!(self.sess, e.span, E0571,
"`break` with value from a `{}` loop",
kind.name())
.span_label(e.span,
"can only break with a value inside \
`loop` or breakable block")
.span_suggestion(e.span,
&format!("instead, use `break` on its own \
without a value inside this `{}` loop",
kind.name()),
"break".to_string())
.emit();
}
}
}
self.require_break_cx("break", e.span);
}
2018-06-23 10:51:01 +01:00
hir::ExprContinue(label) => {
self.require_label_in_labeled_block(e.span, &label, "continue");
match label.target_id {
Ok(loop_id) => {
if let hir::map::NodeBlock(block) = self.hir_map.find(loop_id).unwrap() {
struct_span_err!(self.sess, e.span, E0696,
"`continue` pointing to a labeled block")
.span_label(e.span,
"labeled blocks cannot be `continue`'d")
.span_note(block.span,
"labeled block the continue points to")
.emit();
}
}
Err(hir::LoopIdError::UnlabeledCfInWhileCondition) => {
self.emit_unlabled_cf_in_while_condition(e.span, "continue");
}
_ => {}
}
self.require_break_cx("continue", e.span)
},
2016-07-21 07:01:14 +05:30
_ => intravisit::walk_expr(self, e),
}
}
}
2017-01-26 03:21:50 +02:00
impl<'a, 'hir> CheckLoopVisitor<'a, 'hir> {
2016-07-21 07:01:14 +05:30
fn with_context<F>(&mut self, cx: Context, f: F)
2017-01-26 03:21:50 +02:00
where F: FnOnce(&mut CheckLoopVisitor<'a, 'hir>)
2014-12-08 20:26:43 -05:00
{
let old_cx = self.cx;
self.cx = cx;
f(self);
self.cx = old_cx;
}
fn require_break_cx(&self, name: &str, span: Span) {
match self.cx {
LabeledBlock |
Loop(_) => {}
Closure => {
struct_span_err!(self.sess, span, E0267, "`{}` inside of a closure", name)
.span_label(span, "cannot break inside of a closure")
.emit();
}
Normal | AnonConst => {
struct_span_err!(self.sess, span, E0268, "`{}` outside of loop", name)
.span_label(span, "cannot break outside of a loop")
.emit();
}
}
}
2018-05-16 09:18:26 +02:00
fn require_label_in_labeled_block(&mut self, span: Span, label: &Destination, cf_type: &str)
-> bool
{
if self.cx == LabeledBlock {
if label.label.is_none() {
struct_span_err!(self.sess, span, E0695,
"unlabeled `{}` inside of a labeled block", cf_type)
.span_label(span,
format!("`{}` statements that would diverge to or through \
a labeled block need to bear a label", cf_type))
.emit();
2018-05-16 09:18:26 +02:00
return true;
}
}
2018-05-16 09:18:26 +02:00
return false;
}
fn emit_unlabled_cf_in_while_condition(&mut self, span: Span, cf_type: &str) {
struct_span_err!(self.sess, span, E0590,
"`break` or `continue` with no label in the condition of a `while` loop")
.span_label(span,
format!("unlabeled `{}` in the condition of a `while` loop", cf_type))
.emit();
}
}