]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/swap.rs
Rollup merge of #105123 - BlackHoleFox:fixing-the-macos-deployment, r=oli-obk
[rust.git] / src / tools / clippy / clippy_lints / src / swap.rs
1 use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
2 use clippy_utils::source::snippet_with_applicability;
3 use clippy_utils::sugg::Sugg;
4 use clippy_utils::ty::is_type_diagnostic_item;
5 use clippy_utils::{can_mut_borrow_both, eq_expr_value, in_constant, std_or_core};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{BinOpKind, Block, Expr, ExprKind, PatKind, QPath, Stmt, StmtKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_middle::ty;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::source_map::Spanned;
13 use rustc_span::{sym, Span};
14
15 declare_clippy_lint! {
16     /// ### What it does
17     /// Checks for manual swapping.
18     ///
19     /// Note that the lint will not be emitted in const blocks, as the suggestion would not be applicable.
20     ///
21     /// ### Why is this bad?
22     /// The `std::mem::swap` function exposes the intent better
23     /// without deinitializing or copying either variable.
24     ///
25     /// ### Example
26     /// ```rust
27     /// let mut a = 42;
28     /// let mut b = 1337;
29     ///
30     /// let t = b;
31     /// b = a;
32     /// a = t;
33     /// ```
34     /// Use std::mem::swap():
35     /// ```rust
36     /// let mut a = 1;
37     /// let mut b = 2;
38     /// std::mem::swap(&mut a, &mut b);
39     /// ```
40     #[clippy::version = "pre 1.29.0"]
41     pub MANUAL_SWAP,
42     complexity,
43     "manual swap of two variables"
44 }
45
46 declare_clippy_lint! {
47     /// ### What it does
48     /// Checks for `foo = bar; bar = foo` sequences.
49     ///
50     /// ### Why is this bad?
51     /// This looks like a failed attempt to swap.
52     ///
53     /// ### Example
54     /// ```rust
55     /// # let mut a = 1;
56     /// # let mut b = 2;
57     /// a = b;
58     /// b = a;
59     /// ```
60     /// If swapping is intended, use `swap()` instead:
61     /// ```rust
62     /// # let mut a = 1;
63     /// # let mut b = 2;
64     /// std::mem::swap(&mut a, &mut b);
65     /// ```
66     #[clippy::version = "pre 1.29.0"]
67     pub ALMOST_SWAPPED,
68     correctness,
69     "`foo = bar; bar = foo` sequence"
70 }
71
72 declare_lint_pass!(Swap => [MANUAL_SWAP, ALMOST_SWAPPED]);
73
74 impl<'tcx> LateLintPass<'tcx> for Swap {
75     fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'_>) {
76         check_manual_swap(cx, block);
77         check_suspicious_swap(cx, block);
78         check_xor_swap(cx, block);
79     }
80 }
81
82 fn generate_swap_warning(cx: &LateContext<'_>, e1: &Expr<'_>, e2: &Expr<'_>, span: Span, is_xor_based: bool) {
83     let mut applicability = Applicability::MachineApplicable;
84
85     if !can_mut_borrow_both(cx, e1, e2) {
86         if let ExprKind::Index(lhs1, idx1) = e1.kind {
87             if let ExprKind::Index(lhs2, idx2) = e2.kind {
88                 if eq_expr_value(cx, lhs1, lhs2) {
89                     let ty = cx.typeck_results().expr_ty(lhs1).peel_refs();
90
91                     if matches!(ty.kind(), ty::Slice(_))
92                         || matches!(ty.kind(), ty::Array(_, _))
93                         || is_type_diagnostic_item(cx, ty, sym::Vec)
94                         || is_type_diagnostic_item(cx, ty, sym::VecDeque)
95                     {
96                         let slice = Sugg::hir_with_applicability(cx, lhs1, "<slice>", &mut applicability);
97                         span_lint_and_sugg(
98                             cx,
99                             MANUAL_SWAP,
100                             span,
101                             &format!("this looks like you are swapping elements of `{slice}` manually"),
102                             "try",
103                             format!(
104                                 "{}.swap({}, {})",
105                                 slice.maybe_par(),
106                                 snippet_with_applicability(cx, idx1.span, "..", &mut applicability),
107                                 snippet_with_applicability(cx, idx2.span, "..", &mut applicability),
108                             ),
109                             applicability,
110                         );
111                     }
112                 }
113             }
114         }
115         return;
116     }
117
118     let first = Sugg::hir_with_applicability(cx, e1, "..", &mut applicability);
119     let second = Sugg::hir_with_applicability(cx, e2, "..", &mut applicability);
120     let Some(sugg) = std_or_core(cx) else { return };
121
122     span_lint_and_then(
123         cx,
124         MANUAL_SWAP,
125         span,
126         &format!("this looks like you are swapping `{first}` and `{second}` manually"),
127         |diag| {
128             diag.span_suggestion(
129                 span,
130                 "try",
131                 format!("{sugg}::mem::swap({}, {})", first.mut_addr(), second.mut_addr()),
132                 applicability,
133             );
134             if !is_xor_based {
135                 diag.note(&format!("or maybe you should use `{sugg}::mem::replace`?"));
136             }
137         },
138     );
139 }
140
141 /// Implementation of the `MANUAL_SWAP` lint.
142 fn check_manual_swap(cx: &LateContext<'_>, block: &Block<'_>) {
143     if in_constant(cx, block.hir_id) {
144         return;
145     }
146
147     for w in block.stmts.windows(3) {
148         if_chain! {
149             // let t = foo();
150             if let StmtKind::Local(tmp) = w[0].kind;
151             if let Some(tmp_init) = tmp.init;
152             if let PatKind::Binding(.., ident, None) = tmp.pat.kind;
153
154             // foo() = bar();
155             if let StmtKind::Semi(first) = w[1].kind;
156             if let ExprKind::Assign(lhs1, rhs1, _) = first.kind;
157
158             // bar() = t;
159             if let StmtKind::Semi(second) = w[2].kind;
160             if let ExprKind::Assign(lhs2, rhs2, _) = second.kind;
161             if let ExprKind::Path(QPath::Resolved(None, rhs2)) = rhs2.kind;
162             if rhs2.segments.len() == 1;
163
164             if ident.name == rhs2.segments[0].ident.name;
165             if eq_expr_value(cx, tmp_init, lhs1);
166             if eq_expr_value(cx, rhs1, lhs2);
167             then {
168                 let span = w[0].span.to(second.span);
169                 generate_swap_warning(cx, lhs1, lhs2, span, false);
170             }
171         }
172     }
173 }
174
175 /// Implementation of the `ALMOST_SWAPPED` lint.
176 fn check_suspicious_swap(cx: &LateContext<'_>, block: &Block<'_>) {
177     for w in block.stmts.windows(2) {
178         if_chain! {
179             if let StmtKind::Semi(first) = w[0].kind;
180             if let StmtKind::Semi(second) = w[1].kind;
181             if first.span.ctxt() == second.span.ctxt();
182             if let ExprKind::Assign(lhs0, rhs0, _) = first.kind;
183             if let ExprKind::Assign(lhs1, rhs1, _) = second.kind;
184             if eq_expr_value(cx, lhs0, rhs1);
185             if eq_expr_value(cx, lhs1, rhs0);
186             then {
187                 let lhs0 = Sugg::hir_opt(cx, lhs0);
188                 let rhs0 = Sugg::hir_opt(cx, rhs0);
189                 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
190                     (
191                         format!(" `{first}` and `{second}`"),
192                         first.mut_addr().to_string(),
193                         second.mut_addr().to_string(),
194                     )
195                 } else {
196                     (String::new(), String::new(), String::new())
197                 };
198
199                 let span = first.span.to(second.span);
200                 let Some(sugg) = std_or_core(cx) else { return };
201
202                 span_lint_and_then(cx,
203                     ALMOST_SWAPPED,
204                     span,
205                     &format!("this looks like you are trying to swap{what}"),
206                     |diag| {
207                         if !what.is_empty() {
208                             diag.span_suggestion(
209                                 span,
210                                 "try",
211                                 format!(
212                                     "{sugg}::mem::swap({lhs}, {rhs})",
213                                 ),
214                                 Applicability::MaybeIncorrect,
215                             );
216                             diag.note(
217                                 &format!("or maybe you should use `{sugg}::mem::replace`?")
218                             );
219                         }
220                     });
221             }
222         }
223     }
224 }
225
226 /// Implementation of the xor case for `MANUAL_SWAP` lint.
227 fn check_xor_swap(cx: &LateContext<'_>, block: &Block<'_>) {
228     for window in block.stmts.windows(3) {
229         if_chain! {
230             if let Some((lhs0, rhs0)) = extract_sides_of_xor_assign(&window[0]);
231             if let Some((lhs1, rhs1)) = extract_sides_of_xor_assign(&window[1]);
232             if let Some((lhs2, rhs2)) = extract_sides_of_xor_assign(&window[2]);
233             if eq_expr_value(cx, lhs0, rhs1);
234             if eq_expr_value(cx, lhs2, rhs1);
235             if eq_expr_value(cx, lhs1, rhs0);
236             if eq_expr_value(cx, lhs1, rhs2);
237             then {
238                 let span = window[0].span.to(window[2].span);
239                 generate_swap_warning(cx, lhs0, rhs0, span, true);
240             }
241         };
242     }
243 }
244
245 /// Returns the lhs and rhs of an xor assignment statement.
246 fn extract_sides_of_xor_assign<'a, 'hir>(stmt: &'a Stmt<'hir>) -> Option<(&'a Expr<'hir>, &'a Expr<'hir>)> {
247     if let StmtKind::Semi(expr) = stmt.kind {
248         if let ExprKind::AssignOp(
249             Spanned {
250                 node: BinOpKind::BitXor,
251                 ..
252             },
253             lhs,
254             rhs,
255         ) = expr.kind
256         {
257             return Some((lhs, rhs));
258         }
259     }
260     None
261 }