]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/copies.rs
Auto merge of #6200 - rail-rain:borrowed_box_invalid_sugg, r=phansch
[rust.git] / clippy_lints / src / copies.rs
1 use crate::utils::{eq_expr_value, in_macro, search_same, SpanlessEq, SpanlessHash};
2 use crate::utils::{get_parent_expr, higher, if_sequence, span_lint_and_note};
3 use rustc_hir::{Block, Expr};
4 use rustc_lint::{LateContext, LateLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6
7 declare_clippy_lint! {
8     /// **What it does:** Checks for consecutive `if`s with the same condition.
9     ///
10     /// **Why is this bad?** This is probably a copy & paste error.
11     ///
12     /// **Known problems:** Hopefully none.
13     ///
14     /// **Example:**
15     /// ```ignore
16     /// if a == b {
17     ///     …
18     /// } else if a == b {
19     ///     …
20     /// }
21     /// ```
22     ///
23     /// Note that this lint ignores all conditions with a function call as it could
24     /// have side effects:
25     ///
26     /// ```ignore
27     /// if foo() {
28     ///     …
29     /// } else if foo() { // not linted
30     ///     …
31     /// }
32     /// ```
33     pub IFS_SAME_COND,
34     correctness,
35     "consecutive `if`s with the same condition"
36 }
37
38 declare_clippy_lint! {
39     /// **What it does:** Checks for consecutive `if`s with the same function call.
40     ///
41     /// **Why is this bad?** This is probably a copy & paste error.
42     /// Despite the fact that function can have side effects and `if` works as
43     /// intended, such an approach is implicit and can be considered a "code smell".
44     ///
45     /// **Known problems:** Hopefully none.
46     ///
47     /// **Example:**
48     /// ```ignore
49     /// if foo() == bar {
50     ///     …
51     /// } else if foo() == bar {
52     ///     …
53     /// }
54     /// ```
55     ///
56     /// This probably should be:
57     /// ```ignore
58     /// if foo() == bar {
59     ///     …
60     /// } else if foo() == baz {
61     ///     …
62     /// }
63     /// ```
64     ///
65     /// or if the original code was not a typo and called function mutates a state,
66     /// consider move the mutation out of the `if` condition to avoid similarity to
67     /// a copy & paste error:
68     ///
69     /// ```ignore
70     /// let first = foo();
71     /// if first == bar {
72     ///     …
73     /// } else {
74     ///     let second = foo();
75     ///     if second == bar {
76     ///     …
77     ///     }
78     /// }
79     /// ```
80     pub SAME_FUNCTIONS_IN_IF_CONDITION,
81     pedantic,
82     "consecutive `if`s with the same function call"
83 }
84
85 declare_clippy_lint! {
86     /// **What it does:** Checks for `if/else` with the same body as the *then* part
87     /// and the *else* part.
88     ///
89     /// **Why is this bad?** This is probably a copy & paste error.
90     ///
91     /// **Known problems:** Hopefully none.
92     ///
93     /// **Example:**
94     /// ```ignore
95     /// let foo = if … {
96     ///     42
97     /// } else {
98     ///     42
99     /// };
100     /// ```
101     pub IF_SAME_THEN_ELSE,
102     correctness,
103     "`if` with the same `then` and `else` blocks"
104 }
105
106 declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, SAME_FUNCTIONS_IN_IF_CONDITION, IF_SAME_THEN_ELSE]);
107
108 impl<'tcx> LateLintPass<'tcx> for CopyAndPaste {
109     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
110         if !expr.span.from_expansion() {
111             // skip ifs directly in else, it will be checked in the parent if
112             if let Some(expr) = get_parent_expr(cx, expr) {
113                 if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) {
114                     if else_expr.hir_id == expr.hir_id {
115                         return;
116                     }
117                 }
118             }
119
120             let (conds, blocks) = if_sequence(expr);
121             lint_same_then_else(cx, &blocks);
122             lint_same_cond(cx, &conds);
123             lint_same_fns_in_if_cond(cx, &conds);
124         }
125     }
126 }
127
128 /// Implementation of `IF_SAME_THEN_ELSE`.
129 fn lint_same_then_else(cx: &LateContext<'_>, blocks: &[&Block<'_>]) {
130     let eq: &dyn Fn(&&Block<'_>, &&Block<'_>) -> bool =
131         &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
132
133     if let Some((i, j)) = search_same_sequenced(blocks, eq) {
134         span_lint_and_note(
135             cx,
136             IF_SAME_THEN_ELSE,
137             j.span,
138             "this `if` has identical blocks",
139             Some(i.span),
140             "same as this",
141         );
142     }
143 }
144
145 /// Implementation of `IFS_SAME_COND`.
146 fn lint_same_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
147     let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 {
148         let mut h = SpanlessHash::new(cx);
149         h.hash_expr(expr);
150         h.finish()
151     };
152
153     let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool { eq_expr_value(cx, lhs, rhs) };
154
155     for (i, j) in search_same(conds, hash, eq) {
156         span_lint_and_note(
157             cx,
158             IFS_SAME_COND,
159             j.span,
160             "this `if` has the same condition as a previous `if`",
161             Some(i.span),
162             "same as this",
163         );
164     }
165 }
166
167 /// Implementation of `SAME_FUNCTIONS_IN_IF_CONDITION`.
168 fn lint_same_fns_in_if_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
169     let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 {
170         let mut h = SpanlessHash::new(cx);
171         h.hash_expr(expr);
172         h.finish()
173     };
174
175     let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool {
176         // Do not lint if any expr originates from a macro
177         if in_macro(lhs.span) || in_macro(rhs.span) {
178             return false;
179         }
180         // Do not spawn warning if `IFS_SAME_COND` already produced it.
181         if eq_expr_value(cx, lhs, rhs) {
182             return false;
183         }
184         SpanlessEq::new(cx).eq_expr(lhs, rhs)
185     };
186
187     for (i, j) in search_same(conds, hash, eq) {
188         span_lint_and_note(
189             cx,
190             SAME_FUNCTIONS_IN_IF_CONDITION,
191             j.span,
192             "this `if` has the same function call as a previous `if`",
193             Some(i.span),
194             "same as this",
195         );
196     }
197 }
198
199 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
200 where
201     Eq: Fn(&T, &T) -> bool,
202 {
203     for win in exprs.windows(2) {
204         if eq(&win[0], &win[1]) {
205             return Some((&win[0], &win[1]));
206         }
207     }
208     None
209 }