1 //! Checks for if expressions that contain only an if expression.
3 //! For example, the lint would catch:
8 //! println!("Hello world");
13 //! This lint is **warn** by default
18 use syntax::codemap::Spanned;
20 use utils::{in_macro, snippet, snippet_block, span_lint_and_then};
22 /// **What it does:** This lint checks for nested `if`-statements which can be collapsed by
23 /// `&&`-combining their conditions and for `else { if .. }` expressions that can be collapsed to
26 /// **Why is this bad?** Each `if`-statement adds one level of nesting, which makes code look more complex than it really is.
28 /// **Known problems:** None
30 /// **Example:** `if x { if y { .. } }`
34 "two nested `if`-expressions can be collapsed into one, e.g. `if x { if y { foo() } }` \
35 can be written as `if x && y { foo() }` and an `else { if .. } expression can be collapsed to \
40 pub struct CollapsibleIf;
42 impl LintPass for CollapsibleIf {
43 fn get_lints(&self) -> LintArray {
44 lint_array!(COLLAPSIBLE_IF)
48 impl LateLintPass for CollapsibleIf {
49 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
50 if !in_macro(cx, expr.span) {
56 fn check_if(cx: &LateContext, e: &Expr) {
57 if let ExprIf(ref check, ref then, ref else_) = e.node {
58 if let Some(ref else_) = *else_ {
60 let ExprBlock(ref block) = else_.node,
61 block.stmts.is_empty(),
62 block.rules == BlockCheckMode::DefaultBlock,
63 let Some(ref else_) = block.expr,
64 let ExprIf(_, _, _) = else_.node
66 span_lint_and_then(cx,
69 "this `else { if .. }` block can be collapsed", |db| {
70 db.span_suggestion(block.span, "try", snippet_block(cx, else_.span, "..").into_owned());
73 } else if let Some(&Expr { node: ExprIf(ref check_inner, ref content, None), span: sp, .. }) =
74 single_stmt_of_block(then) {
75 if e.span.expn_id != sp.expn_id {
78 span_lint_and_then(cx, COLLAPSIBLE_IF, e.span, "this if statement can be collapsed", |db| {
79 db.span_suggestion(e.span,
81 format!("if {} && {} {}",
82 check_to_string(cx, check),
83 check_to_string(cx, check_inner),
84 snippet_block(cx, content.span, "..")));
90 fn requires_brackets(e: &Expr) -> bool {
92 ExprBinary(Spanned { node: n, .. }, _, _) if n == BiEq => false,
97 fn check_to_string(cx: &LateContext, e: &Expr) -> Cow<'static, str> {
98 if requires_brackets(e) {
99 format!("({})", snippet(cx, e.span, "..")).into()
101 snippet(cx, e.span, "..")
105 fn single_stmt_of_block(block: &Block) -> Option<&Expr> {
106 if block.stmts.len() == 1 && block.expr.is_none() {
107 if let StmtExpr(ref expr, _) = block.stmts[0].node {
108 single_stmt_of_expr(expr)
112 } else if block.stmts.is_empty() {
113 if let Some(ref p) = block.expr {
123 fn single_stmt_of_expr(expr: &Expr) -> Option<&Expr> {
124 if let ExprBlock(ref block) = expr.node {
125 single_stmt_of_block(block)