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