use rustc::lint::*;
use syntax::ast;
use syntax::codemap::{original_sp, DUMMY_SP};
use std::borrow::Cow;
use utils::{in_macro, span_help_and_lint, snippet_block, snippet, trim_multiline};
declare_lint! {
pub NEEDLESS_CONTINUE,
Warn,
"`continue` statements that can be replaced by a rearrangement of code"
}
#[derive(Copy, Clone)]
pub struct NeedlessContinue;
impl LintPass for NeedlessContinue {
fn get_lints(&self) -> LintArray {
lint_array!(NEEDLESS_CONTINUE)
}
}
impl EarlyLintPass for NeedlessContinue {
fn check_expr(&mut self, ctx: &EarlyContext, expr: &ast::Expr) {
if !in_macro(expr.span) {
check_and_warn(ctx, expr);
}
}
}
fn needless_continue_in_else(else_expr: &ast::Expr) -> bool {
match else_expr.node {
ast::ExprKind::Block(ref else_block) => is_first_block_stmt_continue(else_block),
ast::ExprKind::Continue(_) => true,
_ => false,
}
}
fn is_first_block_stmt_continue(block: &ast::Block) -> bool {
block.stmts.get(0).map_or(false, |stmt| match stmt.node {
ast::StmtKind::Semi(ref e) |
ast::StmtKind::Expr(ref e) => {
if let ast::ExprKind::Continue(_) = e.node {
true
} else {
false
}
},
_ => false,
})
}
fn with_loop_block<F>(expr: &ast::Expr, mut func: F)
where
F: FnMut(&ast::Block),
{
match expr.node {
ast::ExprKind::While(_, ref loop_block, _) |
ast::ExprKind::WhileLet(_, _, ref loop_block, _) |
ast::ExprKind::ForLoop(_, _, ref loop_block, _) |
ast::ExprKind::Loop(ref loop_block, _) => func(loop_block),
_ => {},
}
}
fn with_if_expr<F>(stmt: &ast::Stmt, mut func: F)
where
F: FnMut(&ast::Expr, &ast::Expr, &ast::Block, &ast::Expr),
{
match stmt.node {
ast::StmtKind::Semi(ref e) |
ast::StmtKind::Expr(ref e) => {
if let ast::ExprKind::If(ref cond, ref if_block, Some(ref else_expr)) = e.node {
func(e, cond, if_block, else_expr);
}
},
_ => {},
}
}
#[derive(Copy, Clone, Debug)]
enum LintType {
ContinueInsideElseBlock,
ContinueInsideThenBlock,
}
struct LintData<'a> {
if_expr: &'a ast::Expr,
if_cond: &'a ast::Expr,
if_block: &'a ast::Block,
else_expr: &'a ast::Expr,
stmt_idx: usize,
block_stmts: &'a [ast::Stmt],
}
const MSG_REDUNDANT_ELSE_BLOCK: &'static str = "This else block is redundant.\n";
const MSG_ELSE_BLOCK_NOT_NEEDED: &'static str = "There is no need for an explicit `else` block for this `if` \
expression\n";
const DROP_ELSE_BLOCK_AND_MERGE_MSG: &'static str = "Consider dropping the else clause and merging the code that \
follows (in the loop) with the if block, like so:\n";
const DROP_ELSE_BLOCK_MSG: &'static str = "Consider dropping the else clause, and moving out the code in the else \
block, like so:\n";
fn emit_warning<'a>(ctx: &EarlyContext, data: &'a LintData, header: &str, typ: LintType) {
let (snip, message, expr) = match typ {
LintType::ContinueInsideElseBlock => {
(
suggestion_snippet_for_continue_inside_else(ctx, data, header),
MSG_REDUNDANT_ELSE_BLOCK,
data.else_expr,
)
},
LintType::ContinueInsideThenBlock => {
(
suggestion_snippet_for_continue_inside_if(ctx, data, header),
MSG_ELSE_BLOCK_NOT_NEEDED,
data.if_expr,
)
},
};
span_help_and_lint(ctx, NEEDLESS_CONTINUE, expr.span, message, &snip);
}
fn suggestion_snippet_for_continue_inside_if<'a>(ctx: &EarlyContext, data: &'a LintData, header: &str) -> String {
let cond_code = snippet(ctx, data.if_cond.span, "..");
let if_code = format!("if {} {{\n continue;\n}}\n", cond_code);
let else_code = snippet(ctx, data.else_expr.span, "..").into_owned();
let else_code = erode_block(&else_code);
let else_code = trim_multiline(Cow::from(else_code), false);
let mut ret = String::from(header);
ret.push_str(&if_code);
ret.push_str(&else_code);
ret.push_str("\n...");
ret
}
fn suggestion_snippet_for_continue_inside_else<'a>(ctx: &EarlyContext, data: &'a LintData, header: &str) -> String {
let cond_code = snippet(ctx, data.if_cond.span, "..");
let mut if_code = format!("if {} {{\n", cond_code);
let block_code = &snippet(ctx, data.if_block.span, "..").into_owned();
let block_code = erode_block(block_code);
let block_code = trim_multiline(Cow::from(block_code), false);
if_code.push_str(&block_code);
let to_annex = data.block_stmts[data.stmt_idx + 1..]
.iter()
.map(|stmt| original_sp(stmt.span, DUMMY_SP))
.map(|span| snippet_block(ctx, span, "..").into_owned())
.collect::<Vec<_>>()
.join("\n");
let mut ret = String::from(header);
ret.push_str(&if_code);
ret.push_str("\n// Merged code follows...");
ret.push_str(&to_annex);
ret.push_str("\n}\n");
ret
}
fn check_and_warn<'a>(ctx: &EarlyContext, expr: &'a ast::Expr) {
with_loop_block(expr, |loop_block| for (i, stmt) in loop_block.stmts.iter().enumerate() {
with_if_expr(stmt, |if_expr, cond, then_block, else_expr| {
let data = &LintData {
stmt_idx: i,
if_expr: if_expr,
if_cond: cond,
if_block: then_block,
else_expr: else_expr,
block_stmts: &loop_block.stmts,
};
if needless_continue_in_else(else_expr) {
emit_warning(ctx, data, DROP_ELSE_BLOCK_AND_MERGE_MSG, LintType::ContinueInsideElseBlock);
} else if is_first_block_stmt_continue(then_block) {
emit_warning(ctx, data, DROP_ELSE_BLOCK_MSG, LintType::ContinueInsideThenBlock);
}
});
});
}
pub fn erode_from_back(s: &str) -> String {
let mut ret = String::from(s);
while ret.pop().map_or(false, |c| c != '}') {}
while let Some(c) = ret.pop() {
if !c.is_whitespace() {
ret.push(c);
break;
}
}
ret
}
pub fn erode_from_front(s: &str) -> String {
s.chars()
.skip_while(|c| c.is_whitespace())
.skip_while(|c| *c == '{')
.skip_while(|c| *c == '\n')
.collect::<String>()
}
pub fn erode_block(s: &str) -> String {
erode_from_back(&erode_from_front(s))
}