2 use rustc_front::hir::*;
3 use utils::{get_parent_expr, is_exp_equal, span_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 #[derive(Copy, Clone, Debug)]
20 pub struct CopyAndPaste;
22 impl LintPass for CopyAndPaste {
23 fn get_lints(&self) -> LintArray {
30 impl LateLintPass for CopyAndPaste {
31 fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
32 // skip ifs directly in else, it will be checked in the parent if
33 if let Some(&Expr{node: ExprIf(_, _, Some(ref else_expr)), ..}) = get_parent_expr(cx, expr) {
34 if else_expr.id == expr.id {
39 let conds = condition_sequence(expr);
41 for (n, i) in conds.iter().enumerate() {
42 for j in conds.iter().skip(n+1) {
43 if is_exp_equal(cx, i, j) {
44 span_lint(cx, IFS_SAME_COND, j.span, "this if as the same condition as a previous if");
51 /// Return the list of conditions expression in a sequence of `if/else`.
52 /// Eg. would return `[a, b]` for the expression `if a {..} else if b {..}`.
53 fn condition_sequence(mut expr: &Expr) -> Vec<&Expr> {
54 let mut result = vec![];
56 while let ExprIf(ref cond, _, ref else_expr) = expr.node {
59 if let Some(ref else_expr) = *else_expr {