1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 //! Checks for if expressions that contain only an if expression.
12 //! For example, the lint would catch:
17 //! println!("Hello world");
22 //! This lint is **warn** by default
24 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
25 use crate::rustc::{declare_tool_lint, lint_array};
26 use crate::syntax::ast;
27 use if_chain::if_chain;
29 use crate::rustc_errors::Applicability;
30 use crate::utils::sugg::Sugg;
31 use crate::utils::{in_macro, snippet_block, snippet_block_with_applicability, span_lint_and_sugg, span_lint_and_then};
33 /// **What it does:** Checks for nested `if` statements which can be collapsed
34 /// by `&&`-combining their conditions and for `else { if ... }` expressions
36 /// can be collapsed to `else if ...`.
38 /// **Why is this bad?** Each `if`-statement adds one level of nesting, which
39 /// makes code look more complex than it really is.
41 /// **Known problems:** None.
62 /// Should be written:
77 declare_clippy_lint! {
80 "`if`s that can be collapsed (e.g. `if x { if y { ... } }` and `else { if x { ... } }`)"
83 #[derive(Copy, Clone)]
84 pub struct CollapsibleIf;
86 impl LintPass for CollapsibleIf {
87 fn get_lints(&self) -> LintArray {
88 lint_array!(COLLAPSIBLE_IF)
92 impl EarlyLintPass for CollapsibleIf {
93 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
94 if !in_macro(expr.span) {
100 fn check_if(cx: &EarlyContext<'_>, expr: &ast::Expr) {
102 ast::ExprKind::If(ref check, ref then, ref else_) => {
103 if let Some(ref else_) = *else_ {
104 check_collapsible_maybe_if_let(cx, else_);
106 check_collapsible_no_if_let(cx, expr, check, then);
109 ast::ExprKind::IfLet(_, _, _, Some(ref else_)) => {
110 check_collapsible_maybe_if_let(cx, else_);
116 fn block_starts_with_comment(cx: &EarlyContext<'_>, expr: &ast::Block) -> bool {
117 // We trim all opening braces and whitespaces and then check if the next string is a comment.
118 let trimmed_block_text = snippet_block(cx, expr.span, "..")
119 .trim_left_matches(|c: char| c.is_whitespace() || c == '{')
121 trimmed_block_text.starts_with("//") || trimmed_block_text.starts_with("/*")
124 fn check_collapsible_maybe_if_let(cx: &EarlyContext<'_>, else_: &ast::Expr) {
126 if let ast::ExprKind::Block(ref block, _) = else_.node;
127 if !block_starts_with_comment(cx, block);
128 if let Some(else_) = expr_block(block);
129 if !in_macro(else_.span);
132 ast::ExprKind::If(..) | ast::ExprKind::IfLet(..) => {
133 let mut applicability = Applicability::MachineApplicable;
138 "this `else { if .. }` block can be collapsed",
140 snippet_block_with_applicability(cx, else_.span, "..", &mut applicability).into_owned(),
150 fn check_collapsible_no_if_let(cx: &EarlyContext<'_>, expr: &ast::Expr, check: &ast::Expr, then: &ast::Block) {
152 if !block_starts_with_comment(cx, then);
153 if let Some(inner) = expr_block(then);
154 if let ast::ExprKind::If(ref check_inner, ref content, None) = inner.node;
156 if expr.span.ctxt() != inner.span.ctxt() {
159 span_lint_and_then(cx, COLLAPSIBLE_IF, expr.span, "this if statement can be collapsed", |db| {
160 let lhs = Sugg::ast(cx, check, "..");
161 let rhs = Sugg::ast(cx, check_inner, "..");
162 db.span_suggestion_with_applicability(
168 snippet_block(cx, content.span, ".."),
170 Applicability::MachineApplicable, // snippet
177 /// If the block contains only one expression, return it.
178 fn expr_block(block: &ast::Block) -> Option<&ast::Expr> {
179 let mut it = block.stmts.iter();
181 if let (Some(stmt), None) = (it.next(), it.next()) {
183 ast::StmtKind::Expr(ref expr) | ast::StmtKind::Semi(ref expr) => Some(expr),