2 use rustc_front::hir::*;
3 use utils::{get_parent_expr, in_macro, is_block_equal, is_exp_equal, 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 if let ExprBlock(ref else_block) = else_expr.node {
58 if is_block_equal(cx, &then_block, &else_block, false) {
59 span_lint(cx, IF_SAME_THEN_ELSE, expr.span, "this if has the same then and else blocks");
65 /// Implementation of `IFS_SAME_COND`.
66 fn lint_same_cond(cx: &LateContext, expr: &Expr) {
67 // skip ifs directly in else, it will be checked in the parent if
68 if let Some(&Expr{node: ExprIf(_, _, Some(ref else_expr)), ..}) = get_parent_expr(cx, expr) {
69 if else_expr.id == expr.id {
74 let conds = condition_sequence(expr);
76 for (n, i) in conds.iter().enumerate() {
77 for j in conds.iter().skip(n+1) {
78 if is_exp_equal(cx, i, j, true) {
79 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");
85 /// Return the list of condition expressions in a sequence of `if/else`.
86 /// Eg. would return `[a, b]` for the expression `if a {..} else if b {..}`.
87 fn condition_sequence(mut expr: &Expr) -> Vec<&Expr> {
88 let mut result = vec![];
90 while let ExprIf(ref cond, _, ref else_expr) = expr.node {
93 if let Some(ref else_expr) = *else_expr {