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
15 use if_chain::if_chain;
16 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
17 use rustc::{declare_tool_lint, lint_array};
20 use crate::utils::sugg::Sugg;
21 use crate::utils::{in_macro, snippet_block, snippet_block_with_applicability, span_lint_and_sugg, span_lint_and_then};
22 use rustc_errors::Applicability;
24 /// **What it does:** Checks for nested `if` statements which can be collapsed
25 /// by `&&`-combining their conditions and for `else { if ... }` expressions
27 /// can be collapsed to `else if ...`.
29 /// **Why is this bad?** Each `if`-statement adds one level of nesting, which
30 /// makes code look more complex than it really is.
32 /// **Known problems:** None.
53 /// Should be written:
68 declare_clippy_lint! {
71 "`if`s that can be collapsed (e.g. `if x { if y { ... } }` and `else { if x { ... } }`)"
74 #[derive(Copy, Clone)]
75 pub struct CollapsibleIf;
77 impl LintPass for CollapsibleIf {
78 fn get_lints(&self) -> LintArray {
79 lint_array!(COLLAPSIBLE_IF)
83 impl EarlyLintPass for CollapsibleIf {
84 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
85 if !in_macro(expr.span) {
91 fn check_if(cx: &EarlyContext<'_>, expr: &ast::Expr) {
93 ast::ExprKind::If(ref check, ref then, ref else_) => {
94 if let Some(ref else_) = *else_ {
95 check_collapsible_maybe_if_let(cx, else_);
97 check_collapsible_no_if_let(cx, expr, check, then);
100 ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
101 check_collapsible_maybe_if_let(cx, else_);
107 fn block_starts_with_comment(cx: &EarlyContext<'_>, expr: &ast::Block) -> bool {
108 // We trim all opening braces and whitespaces and then check if the next string is a comment.
109 let trimmed_block_text = snippet_block(cx, expr.span, "..")
110 .trim_start_matches(|c: char| c.is_whitespace() || c == '{')
112 trimmed_block_text.starts_with("//") || trimmed_block_text.starts_with("/*")
115 fn check_collapsible_maybe_if_let(cx: &EarlyContext<'_>, else_: &ast::Expr) {
117 if let ast::ExprKind::Block(ref block, _) = else_.node;
118 if !block_starts_with_comment(cx, block);
119 if let Some(else_) = expr_block(block);
120 if !in_macro(else_.span);
123 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
124 let mut applicability = Applicability::MachineApplicable;
129 "this `else { if .. }` block can be collapsed",
131 snippet_block_with_applicability(cx, else_.span, "..", &mut applicability).into_owned(),
141 fn check_collapsible_no_if_let(cx: &EarlyContext<'_>, expr: &ast::Expr, check: &ast::Expr, then: &ast::Block) {
143 if !block_starts_with_comment(cx, then);
144 if let Some(inner) = expr_block(then);
145 if let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node;
147 if expr.span.ctxt() != inner.span.ctxt() {
150 span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this if statement can be collapsed", |db| {
151 let lhs = Sugg::ast(cx, check, "..");
152 let rhs = Sugg::ast(cx, check_inner, "..");
153 db.span_suggestion_with_applicability(
159 snippet_block(cx, content.span, ".."),
161 Applicability::MachineApplicable, // snippet
168 /// If the block contains only one expression, return it.
169 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
170 let mut it = block.stmts.iter();
172 if let (Some(stmt), None) = (it.next(), it.next()) {
174 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),