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 utils::{in_macro, snippet_block, span_lint_and_then};
19 use utils::sugg::Sugg;
21 /// **What it does:** Checks for nested `if` statements which can be collapsed
22 /// by `&&`-combining their conditions and for `else { if ... }` expressions that
23 /// can be collapsed to `else if ...`.
25 /// **Why is this bad?** Each `if`-statement adds one level of nesting, which
26 /// makes code look more complex than it really is.
28 /// **Known problems:** None.
49 /// Should be written:
67 "`if`s that can be collapsed (e.g. `if x { if y { ... } }` and `else { if x { ... } }`)"
71 pub struct CollapsibleIf;
73 impl LintPass for CollapsibleIf {
74 fn get_lints(&self) -> LintArray {
75 lint_array!(COLLAPSIBLE_IF)
79 impl EarlyLintPass for CollapsibleIf {
80 fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
81 if !in_macro(cx, expr.span) {
87 fn check_if(cx: &EarlyContext, expr: &ast::Expr) {
89 ast::ExprKind::If(ref check, ref then, ref else_) => {
90 if let Some(ref else_) = *else_ {
91 check_collapsible_maybe_if_let(cx, else_);
93 check_collapsible_no_if_let(cx, expr, check, then);
96 ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
97 check_collapsible_maybe_if_let(cx, else_);
103 fn check_collapsible_maybe_if_let(cx: &EarlyContext, else_: &ast::Expr) {
105 let ast::ExprKind::Block(ref block) = else_.node,
106 let Some(ref else_) = expr_block(block),
107 !in_macro(cx, else_.span),
110 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
111 span_lint_and_then(cx,
114 "this `else { if .. }` block can be collapsed", |db| {
115 db.span_suggestion(block.span, "try", snippet_block(cx, else_.span, "..").into_owned());
123 fn check_collapsible_no_if_let(
130 let Some(inner) = expr_block(then),
131 let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node,
133 if expr.span.expn_id != inner.span.expn_id {
136 span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this if statement can be collapsed", |db| {
137 let lhs = Sugg::ast(cx, check, "..");
138 let rhs = Sugg::ast(cx, check_inner, "..");
139 db.span_suggestion(expr.span,
143 snippet_block(cx, content.span, "..")));
148 /// If the block contains only one expression, returns it.
149 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
150 let mut it = block.stmts.iter();
152 if let (Some(stmt), None) = (it.next(), it.next()) {
154 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),