1 use crate::utils::sugg::Sugg;
2 use crate::utils::{differing_macro_contexts, eq_expr_value, snippet_with_applicability, span_lint_and_then};
3 use clippy_utils::ty::is_type_diagnostic_item;
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Block, Expr, ExprKind, PatKind, QPath, StmtKind};
7 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 declare_clippy_lint! {
13 /// **What it does:** Checks for manual swapping.
15 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
16 /// without deinitializing or copying either variable.
18 /// **Known problems:** None.
29 /// Use std::mem::swap():
33 /// std::mem::swap(&mut a, &mut b);
37 "manual swap of two variables"
40 declare_clippy_lint! {
41 /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
43 /// **Why is this bad?** This looks like a failed attempt to swap.
45 /// **Known problems:** None.
54 /// If swapping is intended, use `swap()` instead:
58 /// std::mem::swap(&mut a, &mut b);
62 "`foo = bar; bar = foo` sequence"
65 declare_lint_pass!(Swap => [MANUAL_SWAP, ALMOST_SWAPPED]);
67 impl<'tcx> LateLintPass<'tcx> for Swap {
68 fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'_>) {
69 check_manual_swap(cx, block);
70 check_suspicious_swap(cx, block);
74 /// Implementation of the `MANUAL_SWAP` lint.
75 fn check_manual_swap(cx: &LateContext<'_>, block: &Block<'_>) {
76 for w in block.stmts.windows(3) {
79 if let StmtKind::Local(ref tmp) = w[0].kind;
80 if let Some(ref tmp_init) = tmp.init;
81 if let PatKind::Binding(.., ident, None) = tmp.pat.kind;
84 if let StmtKind::Semi(ref first) = w[1].kind;
85 if let ExprKind::Assign(ref lhs1, ref rhs1, _) = first.kind;
88 if let StmtKind::Semi(ref second) = w[2].kind;
89 if let ExprKind::Assign(ref lhs2, ref rhs2, _) = second.kind;
90 if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.kind;
91 if rhs2.segments.len() == 1;
93 if ident.name == rhs2.segments[0].ident.name;
94 if eq_expr_value(cx, tmp_init, lhs1);
95 if eq_expr_value(cx, rhs1, lhs2);
97 if let ExprKind::Field(ref lhs1, _) = lhs1.kind {
98 if let ExprKind::Field(ref lhs2, _) = lhs2.kind {
99 if lhs1.hir_id.owner == lhs2.hir_id.owner {
105 let mut applicability = Applicability::MachineApplicable;
107 let slice = check_for_slice(cx, lhs1, lhs2);
108 let (replace, what, sugg) = if let Slice::NotSwappable = slice {
110 } else if let Slice::Swappable(slice, idx1, idx2) = slice {
111 if let Some(slice) = Sugg::hir_opt(cx, slice) {
114 format!(" elements of `{}`", slice),
118 snippet_with_applicability(cx, idx1.span, "..", &mut applicability),
119 snippet_with_applicability(cx, idx2.span, "..", &mut applicability),
123 (false, String::new(), String::new())
125 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
128 format!(" `{}` and `{}`", first, second),
129 format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()),
132 (true, String::new(), String::new())
135 let span = w[0].span.to(second.span);
141 &format!("this looks like you are swapping{} manually", what),
143 if !sugg.is_empty() {
144 diag.span_suggestion(
152 diag.note("or maybe you should use `std::mem::replace`?");
163 /// `slice.swap(idx1, idx2)` can be used
168 /// # let mut a = vec![0, 1];
172 /// // can be written as
175 Swappable(&'a Expr<'a>, &'a Expr<'a>, &'a Expr<'a>),
176 /// The `swap` function cannot be used.
181 /// # let mut a = [vec![1, 2], vec![3, 4]];
183 /// a[0][1] = a[1][0];
191 /// Checks if both expressions are index operations into "slice-like" types.
192 fn check_for_slice<'a>(cx: &LateContext<'_>, lhs1: &'a Expr<'_>, lhs2: &'a Expr<'_>) -> Slice<'a> {
193 if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.kind {
194 if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.kind {
195 if eq_expr_value(cx, lhs1, lhs2) {
196 let ty = cx.typeck_results().expr_ty(lhs1).peel_refs();
198 if matches!(ty.kind(), ty::Slice(_))
199 || matches!(ty.kind(), ty::Array(_, _))
200 || is_type_diagnostic_item(cx, ty, sym::vec_type)
201 || is_type_diagnostic_item(cx, ty, sym::vecdeque_type)
203 return Slice::Swappable(lhs1, idx1, idx2);
206 return Slice::NotSwappable;
214 /// Implementation of the `ALMOST_SWAPPED` lint.
215 fn check_suspicious_swap(cx: &LateContext<'_>, block: &Block<'_>) {
216 for w in block.stmts.windows(2) {
218 if let StmtKind::Semi(ref first) = w[0].kind;
219 if let StmtKind::Semi(ref second) = w[1].kind;
220 if !differing_macro_contexts(first.span, second.span);
221 if let ExprKind::Assign(ref lhs0, ref rhs0, _) = first.kind;
222 if let ExprKind::Assign(ref lhs1, ref rhs1, _) = second.kind;
223 if eq_expr_value(cx, lhs0, rhs1);
224 if eq_expr_value(cx, lhs1, rhs0);
226 let lhs0 = Sugg::hir_opt(cx, lhs0);
227 let rhs0 = Sugg::hir_opt(cx, rhs0);
228 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
230 format!(" `{}` and `{}`", first, second),
231 first.mut_addr().to_string(),
232 second.mut_addr().to_string(),
235 (String::new(), String::new(), String::new())
238 let span = first.span.to(second.span);
240 span_lint_and_then(cx,
243 &format!("this looks like you are trying to swap{}", what),
245 if !what.is_empty() {
246 diag.span_suggestion(
250 "std::mem::swap({}, {})",
254 Applicability::MaybeIncorrect,
256 diag.note("or maybe you should use `std::mem::replace`?");