]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/copies.rs
Auto merge of #85556 - FabianWolff:issue-85071, r=estebank,jackh726
[rust.git] / src / tools / clippy / clippy_lints / src / copies.rs
1 use clippy_utils::diagnostics::{span_lint_and_note, span_lint_and_then};
2 use clippy_utils::source::{first_line_of_span, indent_of, reindent_multiline, snippet, snippet_opt};
3 use clippy_utils::{
4     both, count_eq, eq_expr_value, get_enclosing_block, get_parent_expr, if_sequence, in_macro, is_else_clause,
5     is_lint_allowed, search_same, ContainsName, SpanlessEq, SpanlessHash,
6 };
7 use if_chain::if_chain;
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::{Applicability, DiagnosticBuilder};
10 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
11 use rustc_hir::{Block, Expr, ExprKind, HirId};
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::hir::map::Map;
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::{source_map::Span, symbol::Symbol, BytePos};
16 use std::borrow::Cow;
17
18 declare_clippy_lint! {
19     /// ### What it does
20     /// Checks for consecutive `if`s with the same condition.
21     ///
22     /// ### Why is this bad?
23     /// This is probably a copy & paste error.
24     ///
25     /// ### Example
26     /// ```ignore
27     /// if a == b {
28     ///     …
29     /// } else if a == b {
30     ///     …
31     /// }
32     /// ```
33     ///
34     /// Note that this lint ignores all conditions with a function call as it could
35     /// have side effects:
36     ///
37     /// ```ignore
38     /// if foo() {
39     ///     …
40     /// } else if foo() { // not linted
41     ///     …
42     /// }
43     /// ```
44     pub IFS_SAME_COND,
45     correctness,
46     "consecutive `if`s with the same condition"
47 }
48
49 declare_clippy_lint! {
50     /// ### What it does
51     /// Checks for consecutive `if`s with the same function call.
52     ///
53     /// ### Why is this bad?
54     /// This is probably a copy & paste error.
55     /// Despite the fact that function can have side effects and `if` works as
56     /// intended, such an approach is implicit and can be considered a "code smell".
57     ///
58     /// ### Example
59     /// ```ignore
60     /// if foo() == bar {
61     ///     …
62     /// } else if foo() == bar {
63     ///     …
64     /// }
65     /// ```
66     ///
67     /// This probably should be:
68     /// ```ignore
69     /// if foo() == bar {
70     ///     …
71     /// } else if foo() == baz {
72     ///     …
73     /// }
74     /// ```
75     ///
76     /// or if the original code was not a typo and called function mutates a state,
77     /// consider move the mutation out of the `if` condition to avoid similarity to
78     /// a copy & paste error:
79     ///
80     /// ```ignore
81     /// let first = foo();
82     /// if first == bar {
83     ///     …
84     /// } else {
85     ///     let second = foo();
86     ///     if second == bar {
87     ///     …
88     ///     }
89     /// }
90     /// ```
91     pub SAME_FUNCTIONS_IN_IF_CONDITION,
92     pedantic,
93     "consecutive `if`s with the same function call"
94 }
95
96 declare_clippy_lint! {
97     /// ### What it does
98     /// Checks for `if/else` with the same body as the *then* part
99     /// and the *else* part.
100     ///
101     /// ### Why is this bad?
102     /// This is probably a copy & paste error.
103     ///
104     /// ### Example
105     /// ```ignore
106     /// let foo = if … {
107     ///     42
108     /// } else {
109     ///     42
110     /// };
111     /// ```
112     pub IF_SAME_THEN_ELSE,
113     correctness,
114     "`if` with the same `then` and `else` blocks"
115 }
116
117 declare_clippy_lint! {
118     /// ### What it does
119     /// Checks if the `if` and `else` block contain shared code that can be
120     /// moved out of the blocks.
121     ///
122     /// ### Why is this bad?
123     /// Duplicate code is less maintainable.
124     ///
125     /// ### Known problems
126     /// * The lint doesn't check if the moved expressions modify values that are beeing used in
127     ///   the if condition. The suggestion can in that case modify the behavior of the program.
128     ///   See [rust-clippy#7452](https://github.com/rust-lang/rust-clippy/issues/7452)
129     ///
130     /// ### Example
131     /// ```ignore
132     /// let foo = if … {
133     ///     println!("Hello World");
134     ///     13
135     /// } else {
136     ///     println!("Hello World");
137     ///     42
138     /// };
139     /// ```
140     ///
141     /// Could be written as:
142     /// ```ignore
143     /// println!("Hello World");
144     /// let foo = if … {
145     ///     13
146     /// } else {
147     ///     42
148     /// };
149     /// ```
150     pub BRANCHES_SHARING_CODE,
151     complexity,
152     "`if` statement with shared code in all blocks"
153 }
154
155 declare_lint_pass!(CopyAndPaste => [
156     IFS_SAME_COND,
157     SAME_FUNCTIONS_IN_IF_CONDITION,
158     IF_SAME_THEN_ELSE,
159     BRANCHES_SHARING_CODE
160 ]);
161
162 impl<'tcx> LateLintPass<'tcx> for CopyAndPaste {
163     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
164         if !expr.span.from_expansion() {
165             if let ExprKind::If(_, _, _) = expr.kind {
166                 // skip ifs directly in else, it will be checked in the parent if
167                 if let Some(&Expr {
168                     kind: ExprKind::If(_, _, Some(else_expr)),
169                     ..
170                 }) = get_parent_expr(cx, expr)
171                 {
172                     if else_expr.hir_id == expr.hir_id {
173                         return;
174                     }
175                 }
176
177                 let (conds, blocks) = if_sequence(expr);
178                 // Conditions
179                 lint_same_cond(cx, &conds);
180                 lint_same_fns_in_if_cond(cx, &conds);
181                 // Block duplication
182                 lint_same_then_else(cx, &blocks, conds.len() == blocks.len(), expr);
183             }
184         }
185     }
186 }
187
188 /// Implementation of `BRANCHES_SHARING_CODE` and `IF_SAME_THEN_ELSE` if the blocks are equal.
189 fn lint_same_then_else<'tcx>(
190     cx: &LateContext<'tcx>,
191     blocks: &[&Block<'tcx>],
192     has_conditional_else: bool,
193     expr: &'tcx Expr<'_>,
194 ) {
195     // We only lint ifs with multiple blocks
196     if blocks.len() < 2 || is_else_clause(cx.tcx, expr) {
197         return;
198     }
199
200     // Check if each block has shared code
201     let has_expr = blocks[0].expr.is_some();
202
203     let (start_eq, mut end_eq, expr_eq) = if let Some(block_eq) = scan_block_for_eq(cx, blocks) {
204         (block_eq.start_eq, block_eq.end_eq, block_eq.expr_eq)
205     } else {
206         return;
207     };
208
209     // BRANCHES_SHARING_CODE prerequisites
210     if has_conditional_else || (start_eq == 0 && end_eq == 0 && (has_expr && !expr_eq)) {
211         return;
212     }
213
214     // Only the start is the same
215     if start_eq != 0 && end_eq == 0 && (!has_expr || !expr_eq) {
216         let block = blocks[0];
217         let start_stmts = block.stmts.split_at(start_eq).0;
218
219         let mut start_walker = UsedValueFinderVisitor::new(cx);
220         for stmt in start_stmts {
221             intravisit::walk_stmt(&mut start_walker, stmt);
222         }
223
224         emit_branches_sharing_code_lint(
225             cx,
226             start_eq,
227             0,
228             false,
229             check_for_warn_of_moved_symbol(cx, &start_walker.def_symbols, expr),
230             blocks,
231             expr,
232         );
233     } else if end_eq != 0 || (has_expr && expr_eq) {
234         let block = blocks[blocks.len() - 1];
235         let (start_stmts, block_stmts) = block.stmts.split_at(start_eq);
236         let (block_stmts, end_stmts) = block_stmts.split_at(block_stmts.len() - end_eq);
237
238         // Scan start
239         let mut start_walker = UsedValueFinderVisitor::new(cx);
240         for stmt in start_stmts {
241             intravisit::walk_stmt(&mut start_walker, stmt);
242         }
243         let mut moved_syms = start_walker.def_symbols;
244
245         // Scan block
246         let mut block_walker = UsedValueFinderVisitor::new(cx);
247         for stmt in block_stmts {
248             intravisit::walk_stmt(&mut block_walker, stmt);
249         }
250         let mut block_defs = block_walker.defs;
251
252         // Scan moved stmts
253         let mut moved_start: Option<usize> = None;
254         let mut end_walker = UsedValueFinderVisitor::new(cx);
255         for (index, stmt) in end_stmts.iter().enumerate() {
256             intravisit::walk_stmt(&mut end_walker, stmt);
257
258             for value in &end_walker.uses {
259                 // Well we can't move this and all prev statements. So reset
260                 if block_defs.contains(value) {
261                     moved_start = Some(index + 1);
262                     end_walker.defs.drain().for_each(|x| {
263                         block_defs.insert(x);
264                     });
265
266                     end_walker.def_symbols.clear();
267                 }
268             }
269
270             end_walker.uses.clear();
271         }
272
273         if let Some(moved_start) = moved_start {
274             end_eq -= moved_start;
275         }
276
277         let end_linable = block.expr.map_or_else(
278             || end_eq != 0,
279             |expr| {
280                 intravisit::walk_expr(&mut end_walker, expr);
281                 end_walker.uses.iter().any(|x| !block_defs.contains(x))
282             },
283         );
284
285         if end_linable {
286             end_walker.def_symbols.drain().for_each(|x| {
287                 moved_syms.insert(x);
288             });
289         }
290
291         emit_branches_sharing_code_lint(
292             cx,
293             start_eq,
294             end_eq,
295             end_linable,
296             check_for_warn_of_moved_symbol(cx, &moved_syms, expr),
297             blocks,
298             expr,
299         );
300     }
301 }
302
303 struct BlockEqual {
304     /// The amount statements that are equal from the start
305     start_eq: usize,
306     /// The amount statements that are equal from the end
307     end_eq: usize,
308     ///  An indication if the block expressions are the same. This will also be true if both are
309     /// `None`
310     expr_eq: bool,
311 }
312
313 /// This function can also trigger the `IF_SAME_THEN_ELSE` in which case it'll return `None` to
314 /// abort any further processing and avoid duplicate lint triggers.
315 fn scan_block_for_eq(cx: &LateContext<'tcx>, blocks: &[&Block<'tcx>]) -> Option<BlockEqual> {
316     let mut start_eq = usize::MAX;
317     let mut end_eq = usize::MAX;
318     let mut expr_eq = true;
319     let mut iter = blocks.windows(2);
320     while let Some(&[win0, win1]) = iter.next() {
321         let l_stmts = win0.stmts;
322         let r_stmts = win1.stmts;
323
324         // `SpanlessEq` now keeps track of the locals and is therefore context sensitive clippy#6752.
325         // The comparison therefore needs to be done in a way that builds the correct context.
326         let mut evaluator = SpanlessEq::new(cx);
327         let mut evaluator = evaluator.inter_expr();
328
329         let current_start_eq = count_eq(&mut l_stmts.iter(), &mut r_stmts.iter(), |l, r| evaluator.eq_stmt(l, r));
330
331         let current_end_eq = {
332             // We skip the middle statements which can't be equal
333             let end_comparison_count = l_stmts.len().min(r_stmts.len()) - current_start_eq;
334             let it1 = l_stmts.iter().skip(l_stmts.len() - end_comparison_count);
335             let it2 = r_stmts.iter().skip(r_stmts.len() - end_comparison_count);
336             it1.zip(it2)
337                 .fold(0, |acc, (l, r)| if evaluator.eq_stmt(l, r) { acc + 1 } else { 0 })
338         };
339         let block_expr_eq = both(&win0.expr, &win1.expr, |l, r| evaluator.eq_expr(l, r));
340
341         // IF_SAME_THEN_ELSE
342         if_chain! {
343             if block_expr_eq;
344             if l_stmts.len() == r_stmts.len();
345             if l_stmts.len() == current_start_eq;
346             if !is_lint_allowed(cx, IF_SAME_THEN_ELSE, win0.hir_id);
347             if !is_lint_allowed(cx, IF_SAME_THEN_ELSE, win1.hir_id);
348             then {
349                 span_lint_and_note(
350                     cx,
351                     IF_SAME_THEN_ELSE,
352                     win0.span,
353                     "this `if` has identical blocks",
354                     Some(win1.span),
355                     "same as this",
356                 );
357
358                 return None;
359             }
360         }
361
362         start_eq = start_eq.min(current_start_eq);
363         end_eq = end_eq.min(current_end_eq);
364         expr_eq &= block_expr_eq;
365     }
366
367     if !expr_eq {
368         end_eq = 0;
369     }
370
371     // Check if the regions are overlapping. Set `end_eq` to prevent the overlap
372     let min_block_size = blocks.iter().map(|x| x.stmts.len()).min().unwrap();
373     if (start_eq + end_eq) > min_block_size {
374         end_eq = min_block_size - start_eq;
375     }
376
377     Some(BlockEqual {
378         start_eq,
379         end_eq,
380         expr_eq,
381     })
382 }
383
384 fn check_for_warn_of_moved_symbol(
385     cx: &LateContext<'tcx>,
386     symbols: &FxHashSet<Symbol>,
387     if_expr: &'tcx Expr<'_>,
388 ) -> bool {
389     get_enclosing_block(cx, if_expr.hir_id).map_or(false, |block| {
390         let ignore_span = block.span.shrink_to_lo().to(if_expr.span);
391
392         symbols
393             .iter()
394             .filter(|sym| !sym.as_str().starts_with('_'))
395             .any(move |sym| {
396                 let mut walker = ContainsName {
397                     name: *sym,
398                     result: false,
399                 };
400
401                 // Scan block
402                 block
403                     .stmts
404                     .iter()
405                     .filter(|stmt| !ignore_span.overlaps(stmt.span))
406                     .for_each(|stmt| intravisit::walk_stmt(&mut walker, stmt));
407
408                 if let Some(expr) = block.expr {
409                     intravisit::walk_expr(&mut walker, expr);
410                 }
411
412                 walker.result
413             })
414     })
415 }
416
417 fn emit_branches_sharing_code_lint(
418     cx: &LateContext<'tcx>,
419     start_stmts: usize,
420     end_stmts: usize,
421     lint_end: bool,
422     warn_about_moved_symbol: bool,
423     blocks: &[&Block<'tcx>],
424     if_expr: &'tcx Expr<'_>,
425 ) {
426     if start_stmts == 0 && !lint_end {
427         return;
428     }
429
430     // (help, span, suggestion)
431     let mut suggestions: Vec<(&str, Span, String)> = vec![];
432     let mut add_expr_note = false;
433
434     // Construct suggestions
435     if start_stmts > 0 {
436         let block = blocks[0];
437         let span_start = first_line_of_span(cx, if_expr.span).shrink_to_lo();
438         let span_end = block.stmts[start_stmts - 1].span.source_callsite();
439
440         let cond_span = first_line_of_span(cx, if_expr.span).until(block.span);
441         let cond_snippet = reindent_multiline(snippet(cx, cond_span, "_"), false, None);
442         let cond_indent = indent_of(cx, cond_span);
443         let moved_span = block.stmts[0].span.source_callsite().to(span_end);
444         let moved_snippet = reindent_multiline(snippet(cx, moved_span, "_"), true, None);
445         let suggestion = moved_snippet.to_string() + "\n" + &cond_snippet + "{";
446         let suggestion = reindent_multiline(Cow::Borrowed(&suggestion), true, cond_indent);
447
448         let span = span_start.to(span_end);
449         suggestions.push(("start", span, suggestion.to_string()));
450     }
451
452     if lint_end {
453         let block = blocks[blocks.len() - 1];
454         let span_end = block.span.shrink_to_hi();
455
456         let moved_start = if end_stmts == 0 && block.expr.is_some() {
457             block.expr.unwrap().span
458         } else {
459             block.stmts[block.stmts.len() - end_stmts].span
460         }
461         .source_callsite();
462         let moved_end = block
463             .expr
464             .map_or_else(|| block.stmts[block.stmts.len() - 1].span, |expr| expr.span)
465             .source_callsite();
466
467         let moved_span = moved_start.to(moved_end);
468         let moved_snipped = reindent_multiline(snippet(cx, moved_span, "_"), true, None);
469         let indent = indent_of(cx, if_expr.span.shrink_to_hi());
470         let suggestion = "}\n".to_string() + &moved_snipped;
471         let suggestion = reindent_multiline(Cow::Borrowed(&suggestion), true, indent);
472
473         let mut span = moved_start.to(span_end);
474         // Improve formatting if the inner block has indention (i.e. normal Rust formatting)
475         let test_span = Span::new(span.lo() - BytePos(4), span.lo(), span.ctxt());
476         if snippet_opt(cx, test_span)
477             .map(|snip| snip == "    ")
478             .unwrap_or_default()
479         {
480             span = span.with_lo(test_span.lo());
481         }
482
483         suggestions.push(("end", span, suggestion.to_string()));
484         add_expr_note = !cx.typeck_results().expr_ty(if_expr).is_unit();
485     }
486
487     let add_optional_msgs = |diag: &mut DiagnosticBuilder<'_>| {
488         if add_expr_note {
489             diag.note("The end suggestion probably needs some adjustments to use the expression result correctly");
490         }
491
492         if warn_about_moved_symbol {
493             diag.warn("Some moved values might need to be renamed to avoid wrong references");
494         }
495     };
496
497     // Emit lint
498     if suggestions.len() == 1 {
499         let (place_str, span, sugg) = suggestions.pop().unwrap();
500         let msg = format!("all if blocks contain the same code at the {}", place_str);
501         let help = format!("consider moving the {} statements out like this", place_str);
502         span_lint_and_then(cx, BRANCHES_SHARING_CODE, span, msg.as_str(), |diag| {
503             diag.span_suggestion(span, help.as_str(), sugg, Applicability::Unspecified);
504
505             add_optional_msgs(diag);
506         });
507     } else if suggestions.len() == 2 {
508         let (_, end_span, end_sugg) = suggestions.pop().unwrap();
509         let (_, start_span, start_sugg) = suggestions.pop().unwrap();
510         span_lint_and_then(
511             cx,
512             BRANCHES_SHARING_CODE,
513             start_span,
514             "all if blocks contain the same code at the start and the end. Here at the start",
515             move |diag| {
516                 diag.span_note(end_span, "and here at the end");
517
518                 diag.span_suggestion(
519                     start_span,
520                     "consider moving the start statements out like this",
521                     start_sugg,
522                     Applicability::Unspecified,
523                 );
524
525                 diag.span_suggestion(
526                     end_span,
527                     "and consider moving the end statements out like this",
528                     end_sugg,
529                     Applicability::Unspecified,
530                 );
531
532                 add_optional_msgs(diag);
533             },
534         );
535     }
536 }
537
538 /// This visitor collects `HirId`s and Symbols of defined symbols and `HirId`s of used values.
539 struct UsedValueFinderVisitor<'a, 'tcx> {
540     cx: &'a LateContext<'tcx>,
541
542     /// The `HirId`s of defined values in the scanned statements
543     defs: FxHashSet<HirId>,
544
545     /// The Symbols of the defined symbols in the scanned statements
546     def_symbols: FxHashSet<Symbol>,
547
548     /// The `HirId`s of the used values
549     uses: FxHashSet<HirId>,
550 }
551
552 impl<'a, 'tcx> UsedValueFinderVisitor<'a, 'tcx> {
553     fn new(cx: &'a LateContext<'tcx>) -> Self {
554         UsedValueFinderVisitor {
555             cx,
556             defs: FxHashSet::default(),
557             def_symbols: FxHashSet::default(),
558             uses: FxHashSet::default(),
559         }
560     }
561 }
562
563 impl<'a, 'tcx> Visitor<'tcx> for UsedValueFinderVisitor<'a, 'tcx> {
564     type Map = Map<'tcx>;
565
566     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
567         NestedVisitorMap::All(self.cx.tcx.hir())
568     }
569
570     fn visit_local(&mut self, l: &'tcx rustc_hir::Local<'tcx>) {
571         let local_id = l.pat.hir_id;
572         self.defs.insert(local_id);
573
574         if let Some(sym) = l.pat.simple_ident() {
575             self.def_symbols.insert(sym.name);
576         }
577
578         if let Some(expr) = l.init {
579             intravisit::walk_expr(self, expr);
580         }
581     }
582
583     fn visit_qpath(&mut self, qpath: &'tcx rustc_hir::QPath<'tcx>, id: HirId, _span: rustc_span::Span) {
584         if let rustc_hir::QPath::Resolved(_, path) = *qpath {
585             if path.segments.len() == 1 {
586                 if let rustc_hir::def::Res::Local(var) = self.cx.qpath_res(qpath, id) {
587                     self.uses.insert(var);
588                 }
589             }
590         }
591     }
592 }
593
594 /// Implementation of `IFS_SAME_COND`.
595 fn lint_same_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
596     let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 {
597         let mut h = SpanlessHash::new(cx);
598         h.hash_expr(expr);
599         h.finish()
600     };
601
602     let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool { eq_expr_value(cx, lhs, rhs) };
603
604     for (i, j) in search_same(conds, hash, eq) {
605         span_lint_and_note(
606             cx,
607             IFS_SAME_COND,
608             j.span,
609             "this `if` has the same condition as a previous `if`",
610             Some(i.span),
611             "same as this",
612         );
613     }
614 }
615
616 /// Implementation of `SAME_FUNCTIONS_IN_IF_CONDITION`.
617 fn lint_same_fns_in_if_cond(cx: &LateContext<'_>, conds: &[&Expr<'_>]) {
618     let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 {
619         let mut h = SpanlessHash::new(cx);
620         h.hash_expr(expr);
621         h.finish()
622     };
623
624     let eq: &dyn Fn(&&Expr<'_>, &&Expr<'_>) -> bool = &|&lhs, &rhs| -> bool {
625         // Do not lint if any expr originates from a macro
626         if in_macro(lhs.span) || in_macro(rhs.span) {
627             return false;
628         }
629         // Do not spawn warning if `IFS_SAME_COND` already produced it.
630         if eq_expr_value(cx, lhs, rhs) {
631             return false;
632         }
633         SpanlessEq::new(cx).eq_expr(lhs, rhs)
634     };
635
636     for (i, j) in search_same(conds, hash, eq) {
637         span_lint_and_note(
638             cx,
639             SAME_FUNCTIONS_IN_IF_CONDITION,
640             j.span,
641             "this `if` has the same function call as a previous `if`",
642             Some(i.span),
643             "same as this",
644         );
645     }
646 }