2 use rustc_front::hir::*;
3 use utils::{get_parent_expr, in_macro, is_exp_equal, is_stmt_equal, over, span_lint, span_note_and_lint};
5 /// **What it does:** This lint checks for consecutive `ifs` with the same condition. This lint is
8 /// **Why is this bad?** This is probably a copy & paste error.
10 /// **Known problems:** Hopefully none.
12 /// **Example:** `if a == b { .. } else if a == b { .. }`
16 "consecutive `ifs` with the same condition"
19 /// **What it does:** This lint checks for `if/else` with the same body as the *then* part and the
20 /// *else* part. This lint is `Warn` by default.
22 /// **Why is this bad?** This is probably a copy & paste error.
24 /// **Known problems:** Hopefully none.
26 /// **Example:** `if .. { 42 } else { 42 }`
28 pub IF_SAME_THEN_ELSE,
30 "if with the same *then* and *else* blocks"
33 #[derive(Copy, Clone, Debug)]
34 pub struct CopyAndPaste;
36 impl LintPass for CopyAndPaste {
37 fn get_lints(&self) -> LintArray {
45 impl LateLintPass for CopyAndPaste {
46 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
47 if !in_macro(cx, expr.span) {
48 lint_same_then_else(cx, expr);
49 lint_same_cond(cx, expr);
54 /// Implementation of `IF_SAME_THEN_ELSE`.
55 fn lint_same_then_else(cx: &LateContext, expr: &Expr) {
56 if let ExprIf(_, ref then_block, Some(ref else_expr)) = expr.node {
57 let must_lint = if let ExprBlock(ref else_block) = else_expr.node {
58 over(&then_block.stmts, &else_block.stmts, |l, r| is_stmt_equal(cx, l, r)) &&
59 match (&then_block.expr, &else_block.expr) {
60 (&Some(ref then_expr), &Some(ref else_expr)) => {
61 is_exp_equal(cx, &then_expr, &else_expr)
63 (&None, &None) => true,
72 span_lint(cx, IF_SAME_THEN_ELSE, expr.span, "this if has the same then and else blocks");
77 /// Implementation of `IFS_SAME_COND`.
78 fn lint_same_cond(cx: &LateContext, expr: &Expr) {
79 // skip ifs directly in else, it will be checked in the parent if
80 if let Some(&Expr{node: ExprIf(_, _, Some(ref else_expr)), ..}) = get_parent_expr(cx, expr) {
81 if else_expr.id == expr.id {
86 let conds = condition_sequence(expr);
88 for (n, i) in conds.iter().enumerate() {
89 for j in conds.iter().skip(n+1) {
90 if is_exp_equal(cx, i, j) {
91 span_note_and_lint(cx, IFS_SAME_COND, j.span, "this if has the same condition as a previous if", i.span, "same as this");
97 /// Return the list of conditions expression in a sequence of `if/else`.
98 /// Eg. would return `[a, b]` for the expression `if a {..} else if b {..}`.
99 fn condition_sequence(mut expr: &Expr) -> Vec<&Expr> {
100 let mut result = vec![];
102 while let ExprIf(ref cond, _, ref else_expr) = expr.node {
103 result.push(&**cond);
105 if let Some(ref else_expr) = *else_expr {