]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/copies.rs
Rollup merge of #73655 - JamieCunliffe:jamie_va-args-c, r=nikic
[rust.git] / src / tools / clippy / clippy_lints / src / copies.rs
1 use crate::utils::{get_parent_expr, higher, if_sequence, snippet, span_lint_and_note, span_lint_and_then};
2 use crate::utils::{SpanlessEq, SpanlessHash};
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_hir::{Arm, Block, Expr, ExprKind, MatchSource, Pat, PatKind};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_middle::ty::{Ty, TyS};
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
8 use rustc_span::symbol::Symbol;
9 use std::collections::hash_map::Entry;
10 use std::hash::BuildHasherDefault;
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for consecutive `if`s with the same condition.
14     ///
15     /// **Why is this bad?** This is probably a copy & paste error.
16     ///
17     /// **Known problems:** Hopefully none.
18     ///
19     /// **Example:**
20     /// ```ignore
21     /// if a == b {
22     ///     …
23     /// } else if a == b {
24     ///     …
25     /// }
26     /// ```
27     ///
28     /// Note that this lint ignores all conditions with a function call as it could
29     /// have side effects:
30     ///
31     /// ```ignore
32     /// if foo() {
33     ///     …
34     /// } else if foo() { // not linted
35     ///     …
36     /// }
37     /// ```
38     pub IFS_SAME_COND,
39     correctness,
40     "consecutive `if`s with the same condition"
41 }
42
43 declare_clippy_lint! {
44     /// **What it does:** Checks for consecutive `if`s with the same function call.
45     ///
46     /// **Why is this bad?** This is probably a copy & paste error.
47     /// Despite the fact that function can have side effects and `if` works as
48     /// intended, such an approach is implicit and can be considered a "code smell".
49     ///
50     /// **Known problems:** Hopefully none.
51     ///
52     /// **Example:**
53     /// ```ignore
54     /// if foo() == bar {
55     ///     …
56     /// } else if foo() == bar {
57     ///     …
58     /// }
59     /// ```
60     ///
61     /// This probably should be:
62     /// ```ignore
63     /// if foo() == bar {
64     ///     …
65     /// } else if foo() == baz {
66     ///     …
67     /// }
68     /// ```
69     ///
70     /// or if the original code was not a typo and called function mutates a state,
71     /// consider move the mutation out of the `if` condition to avoid similarity to
72     /// a copy & paste error:
73     ///
74     /// ```ignore
75     /// let first = foo();
76     /// if first == bar {
77     ///     …
78     /// } else {
79     ///     let second = foo();
80     ///     if second == bar {
81     ///     …
82     ///     }
83     /// }
84     /// ```
85     pub SAME_FUNCTIONS_IN_IF_CONDITION,
86     pedantic,
87     "consecutive `if`s with the same function call"
88 }
89
90 declare_clippy_lint! {
91     /// **What it does:** Checks for `if/else` with the same body as the *then* part
92     /// and the *else* part.
93     ///
94     /// **Why is this bad?** This is probably a copy & paste error.
95     ///
96     /// **Known problems:** Hopefully none.
97     ///
98     /// **Example:**
99     /// ```ignore
100     /// let foo = if … {
101     ///     42
102     /// } else {
103     ///     42
104     /// };
105     /// ```
106     pub IF_SAME_THEN_ELSE,
107     correctness,
108     "`if` with the same `then` and `else` blocks"
109 }
110
111 declare_clippy_lint! {
112     /// **What it does:** Checks for `match` with identical arm bodies.
113     ///
114     /// **Why is this bad?** This is probably a copy & paste error. If arm bodies
115     /// are the same on purpose, you can factor them
116     /// [using `|`](https://doc.rust-lang.org/book/patterns.html#multiple-patterns).
117     ///
118     /// **Known problems:** False positive possible with order dependent `match`
119     /// (see issue
120     /// [#860](https://github.com/rust-lang/rust-clippy/issues/860)).
121     ///
122     /// **Example:**
123     /// ```rust,ignore
124     /// match foo {
125     ///     Bar => bar(),
126     ///     Quz => quz(),
127     ///     Baz => bar(), // <= oops
128     /// }
129     /// ```
130     ///
131     /// This should probably be
132     /// ```rust,ignore
133     /// match foo {
134     ///     Bar => bar(),
135     ///     Quz => quz(),
136     ///     Baz => baz(), // <= fixed
137     /// }
138     /// ```
139     ///
140     /// or if the original code was not a typo:
141     /// ```rust,ignore
142     /// match foo {
143     ///     Bar | Baz => bar(), // <= shows the intent better
144     ///     Quz => quz(),
145     /// }
146     /// ```
147     pub MATCH_SAME_ARMS,
148     pedantic,
149     "`match` with identical arm bodies"
150 }
151
152 declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, SAME_FUNCTIONS_IN_IF_CONDITION, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]);
153
154 impl<'tcx> LateLintPass<'tcx> for CopyAndPaste {
155     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
156         if !expr.span.from_expansion() {
157             // skip ifs directly in else, it will be checked in the parent if
158             if let Some(expr) = get_parent_expr(cx, expr) {
159                 if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) {
160                     if else_expr.hir_id == expr.hir_id {
161                         return;
162                     }
163                 }
164             }
165
166             let (conds, blocks) = if_sequence(expr);
167             lint_same_then_else(cx, &blocks);
168             lint_same_cond(cx, &conds);
169             lint_same_fns_in_if_cond(cx, &conds);
170             lint_match_arms(cx, expr);
171         }
172     }
173 }
174
175 /// Implementation of `IF_SAME_THEN_ELSE`.
176 fn lint_same_then_else(cx: &LateContext<'_>, blocks: &[&Block<'_>]) {
177     let eq: &dyn Fn(&&Block<'_>, &&Block<'_>) -> bool =
178         &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) };
179
180     if let Some((i, j)) = search_same_sequenced(blocks, eq) {
181         span_lint_and_note(
182             cx,
183             IF_SAME_THEN_ELSE,
184             j.span,
185             "this `if` has identical blocks",
186             Some(i.span),
187             "same as this",
188         );
189     }
190 }
191
192 /// Implementation of `IFS_SAME_COND`.
193 fn lint_same_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
194     let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 {
195         let mut h = SpanlessHash::new(cx);
196         h.hash_expr(expr);
197         h.finish()
198     };
199
200     let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool =
201         &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) };
202
203     for (i, j) in search_same(conds, hash, eq) {
204         span_lint_and_note(
205             cx,
206             IFS_SAME_COND,
207             j.span,
208             "this `if` has the same condition as a previous `if`",
209             Some(i.span),
210             "same as this",
211         );
212     }
213 }
214
215 /// Implementation of `SAME_FUNCTIONS_IN_IF_CONDITION`.
216 fn lint_same_fns_in_if_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
217     let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 {
218         let mut h = SpanlessHash::new(cx);
219         h.hash_expr(expr);
220         h.finish()
221     };
222
223     let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool {
224         // Do not spawn warning if `IFS_SAME_COND` already produced it.
225         if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) {
226             return false;
227         }
228         SpanlessEq::new(cx).eq_expr(lhs, rhs)
229     };
230
231     for (i, j) in search_same(conds, hash, eq) {
232         span_lint_and_note(
233             cx,
234             SAME_FUNCTIONS_IN_IF_CONDITION,
235             j.span,
236             "this `if` has the same function call as a previous `if`",
237             Some(i.span),
238             "same as this",
239         );
240     }
241 }
242
243 /// Implementation of `MATCH_SAME_ARMS`.
244 fn lint_match_arms<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) {
245     fn same_bindings<'tcx>(lhs: &FxHashMap<Symbol, Ty<'tcx>>, rhs: &FxHashMap<Symbol, Ty<'tcx>>) -> bool {
246         lhs.len() == rhs.len()
247             && lhs
248                 .iter()
249                 .all(|(name, l_ty)| rhs.get(name).map_or(false, |r_ty| TyS::same_type(l_ty, r_ty)))
250     }
251
252     if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind {
253         let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 {
254             let mut h = SpanlessHash::new(cx);
255             h.hash_expr(&arm.body);
256             h.finish()
257         };
258
259         let eq = |&(lindex, lhs): &(usize, &Arm<'_>), &(rindex, rhs): &(usize, &Arm<'_>)| -> bool {
260             let min_index = usize::min(lindex, rindex);
261             let max_index = usize::max(lindex, rindex);
262
263             // Arms with a guard are ignored, those can’t always be merged together
264             // This is also the case for arms in-between each there is an arm with a guard
265             (min_index..=max_index).all(|index| arms[index].guard.is_none()) &&
266                 SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) &&
267                 // all patterns should have the same bindings
268                 same_bindings(&bindings(cx, &lhs.pat), &bindings(cx, &rhs.pat))
269         };
270
271         let indexed_arms: Vec<(usize, &Arm<'_>)> = arms.iter().enumerate().collect();
272         for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) {
273             span_lint_and_then(
274                 cx,
275                 MATCH_SAME_ARMS,
276                 j.body.span,
277                 "this `match` has identical arm bodies",
278                 |diag| {
279                     diag.span_note(i.body.span, "same as this");
280
281                     // Note: this does not use `span_suggestion` on purpose:
282                     // there is no clean way
283                     // to remove the other arm. Building a span and suggest to replace it to ""
284                     // makes an even more confusing error message. Also in order not to make up a
285                     // span for the whole pattern, the suggestion is only shown when there is only
286                     // one pattern. The user should know about `|` if they are already using it…
287
288                     let lhs = snippet(cx, i.pat.span, "<pat1>");
289                     let rhs = snippet(cx, j.pat.span, "<pat2>");
290
291                     if let PatKind::Wild = j.pat.kind {
292                         // if the last arm is _, then i could be integrated into _
293                         // note that i.pat cannot be _, because that would mean that we're
294                         // hiding all the subsequent arms, and rust won't compile
295                         diag.span_note(
296                             i.body.span,
297                             &format!(
298                                 "`{}` has the same arm body as the `_` wildcard, consider removing it",
299                                 lhs
300                             ),
301                         );
302                     } else {
303                         diag.span_help(i.pat.span, &format!("consider refactoring into `{} | {}`", lhs, rhs));
304                     }
305                 },
306             );
307         }
308     }
309 }
310
311 /// Returns the list of bindings in a pattern.
312 fn bindings<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>) -> FxHashMap<Symbol, Ty<'tcx>> {
313     fn bindings_impl<'tcx>(cx: &LateContext<'tcx>, pat: &Pat<'_>, map: &mut FxHashMap<Symbol, Ty<'tcx>>) {
314         match pat.kind {
315             PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map),
316             PatKind::TupleStruct(_, pats, _) => {
317                 for pat in pats {
318                     bindings_impl(cx, pat, map);
319                 }
320             },
321             PatKind::Binding(.., ident, ref as_pat) => {
322                 if let Entry::Vacant(v) = map.entry(ident.name) {
323                     v.insert(cx.typeck_results().pat_ty(pat));
324                 }
325                 if let Some(ref as_pat) = *as_pat {
326                     bindings_impl(cx, as_pat, map);
327                 }
328             },
329             PatKind::Or(fields) | PatKind::Tuple(fields, _) => {
330                 for pat in fields {
331                     bindings_impl(cx, pat, map);
332                 }
333             },
334             PatKind::Struct(_, fields, _) => {
335                 for pat in fields {
336                     bindings_impl(cx, &pat.pat, map);
337                 }
338             },
339             PatKind::Slice(lhs, ref mid, rhs) => {
340                 for pat in lhs {
341                     bindings_impl(cx, pat, map);
342                 }
343                 if let Some(ref mid) = *mid {
344                     bindings_impl(cx, mid, map);
345                 }
346                 for pat in rhs {
347                     bindings_impl(cx, pat, map);
348                 }
349             },
350             PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (),
351         }
352     }
353
354     let mut result = FxHashMap::default();
355     bindings_impl(cx, pat, &mut result);
356     result
357 }
358
359 fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)>
360 where
361     Eq: Fn(&T, &T) -> bool,
362 {
363     for win in exprs.windows(2) {
364         if eq(&win[0], &win[1]) {
365             return Some((&win[0], &win[1]));
366         }
367     }
368     None
369 }
370
371 fn search_common_cases<'a, T, Eq>(exprs: &'a [T], eq: &Eq) -> Option<(&'a T, &'a T)>
372 where
373     Eq: Fn(&T, &T) -> bool,
374 {
375     if exprs.len() == 2 && eq(&exprs[0], &exprs[1]) {
376         Some((&exprs[0], &exprs[1]))
377     } else {
378         None
379     }
380 }
381
382 fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)>
383 where
384     Hash: Fn(&T) -> u64,
385     Eq: Fn(&T, &T) -> bool,
386 {
387     if let Some(expr) = search_common_cases(&exprs, &eq) {
388         return vec![expr];
389     }
390
391     let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
392
393     let mut map: FxHashMap<_, Vec<&_>> =
394         FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
395
396     for expr in exprs {
397         match map.entry(hash(expr)) {
398             Entry::Occupied(mut o) => {
399                 for o in o.get() {
400                     if eq(o, expr) {
401                         match_expr_list.push((o, expr));
402                     }
403                 }
404                 o.get_mut().push(expr);
405             },
406             Entry::Vacant(v) => {
407                 v.insert(vec![expr]);
408             },
409         }
410     }
411
412     match_expr_list
413 }