1 use rustc_front::hir::*;
2 use rustc::lint::{LateLintPass, LateContext, LintArray, LintPass};
3 use rustc_front::intravisit::{Visitor, walk_expr};
6 /// **What it does:** This lint checks for `if` conditions that use blocks to contain an expression.
8 /// **Why is this bad?** It isn't really rust style, same as using parentheses to contain expressions.
10 /// **Known problems:** None
12 /// **Example:** `if { true } ..`
14 pub BLOCK_IN_IF_CONDITION_EXPR, Warn,
15 "braces can be eliminated in conditions that are expressions, e.g `if { true } ...`"
18 /// **What it does:** This lint checks for `if` conditions that use blocks containing statements, or conditions that use closures with blocks.
20 /// **Why is this bad?** Using blocks in the condition makes it hard to read.
22 /// **Known problems:** None
24 /// **Example:** `if { let x = somefunc(); x } ..` or `if somefunc(|x| { x == 47 }) ..`
26 pub BLOCK_IN_IF_CONDITION_STMT, Warn,
27 "avoid complex blocks in conditions, instead move the block higher and bind it \
28 with 'let'; e.g: `if { let x = true; x } ...`"
32 pub struct BlockInIfCondition;
34 impl LintPass for BlockInIfCondition {
35 fn get_lints(&self) -> LintArray {
36 lint_array!(BLOCK_IN_IF_CONDITION_EXPR, BLOCK_IN_IF_CONDITION_STMT)
40 struct ExVisitor<'v> {
41 found_block: Option<&'v Expr>
44 impl<'v> Visitor<'v> for ExVisitor<'v> {
45 fn visit_expr(&mut self, expr: &'v Expr) {
46 if let ExprClosure(_, _, ref block) = expr.node {
48 if !block.stmts.is_empty() {
51 if let Some(ref ex) = block.expr {
62 self.found_block = Some(& expr);
66 walk_expr(self, expr);
70 const BRACED_EXPR_MESSAGE:&'static str = "omit braces around single expression condition";
71 const COMPLEX_BLOCK_MESSAGE:&'static str = "in an 'if' condition, avoid complex blocks or closures with blocks; instead, move the block or closure higher and bind it with a 'let'";
73 impl LateLintPass for BlockInIfCondition {
74 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
75 if let ExprIf(ref check, ref then, _) = expr.node {
76 if let ExprBlock(ref block) = check.node {
77 if block.rules == DefaultBlock {
78 if block.stmts.is_empty() {
79 if let Some(ref ex) = block.expr {
80 // don't dig into the expression here, just suggest that they remove
83 span_help_and_lint(cx, BLOCK_IN_IF_CONDITION_EXPR, check.span,
85 &format!("try\nif {} {} ... ", snippet_block(cx, ex.span, ".."),
86 snippet_block(cx, then.span, "..")));
90 span_help_and_lint(cx, BLOCK_IN_IF_CONDITION_STMT, check.span,
91 COMPLEX_BLOCK_MESSAGE,
92 &format!("try\nlet res = {};\nif res {} ... ",
93 snippet_block(cx, block.span, ".."),
94 snippet_block(cx, then.span, "..")));
98 let mut visitor = ExVisitor { found_block: None };
99 walk_expr(&mut visitor, check);
100 if let Some(ref block) = visitor.found_block {
101 span_help_and_lint(cx, BLOCK_IN_IF_CONDITION_STMT, block.span,
102 COMPLEX_BLOCK_MESSAGE, "");