1 use clippy_utils::diagnostics::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::{differing_macro_contexts, eq_expr_value};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{Block, Expr, ExprKind, PatKind, QPath, StmtKind};
9 use rustc_lint::{LateContext, LateLintPass};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for manual swapping.
17 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
18 /// without deinitializing or copying either variable.
20 /// **Known problems:** None.
31 /// Use std::mem::swap():
35 /// std::mem::swap(&mut a, &mut b);
39 "manual swap of two variables"
42 declare_clippy_lint! {
43 /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
45 /// **Why is this bad?** This looks like a failed attempt to swap.
47 /// **Known problems:** None.
56 /// If swapping is intended, use `swap()` instead:
60 /// std::mem::swap(&mut a, &mut b);
64 "`foo = bar; bar = foo` sequence"
67 declare_lint_pass!(Swap => [MANUAL_SWAP, ALMOST_SWAPPED]);
69 impl<'tcx> LateLintPass<'tcx> for Swap {
70 fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'_>) {
71 check_manual_swap(cx, block);
72 check_suspicious_swap(cx, block);
76 /// Implementation of the `MANUAL_SWAP` lint.
77 fn check_manual_swap(cx: &LateContext<'_>, block: &Block<'_>) {
78 for w in block.stmts.windows(3) {
81 if let StmtKind::Local(tmp) = w[0].kind;
82 if let Some(tmp_init) = tmp.init;
83 if let PatKind::Binding(.., ident, None) = tmp.pat.kind;
86 if let StmtKind::Semi(first) = w[1].kind;
87 if let ExprKind::Assign(lhs1, rhs1, _) = first.kind;
90 if let StmtKind::Semi(second) = w[2].kind;
91 if let ExprKind::Assign(lhs2, rhs2, _) = second.kind;
92 if let ExprKind::Path(QPath::Resolved(None, rhs2)) = rhs2.kind;
93 if rhs2.segments.len() == 1;
95 if ident.name == rhs2.segments[0].ident.name;
96 if eq_expr_value(cx, tmp_init, lhs1);
97 if eq_expr_value(cx, rhs1, lhs2);
99 if let ExprKind::Field(lhs1, _) = lhs1.kind {
100 if let ExprKind::Field(lhs2, _) = lhs2.kind {
101 if lhs1.hir_id.owner == lhs2.hir_id.owner {
107 let mut applicability = Applicability::MachineApplicable;
109 let slice = check_for_slice(cx, lhs1, lhs2);
110 let (replace, what, sugg) = if let Slice::NotSwappable = slice {
112 } else if let Slice::Swappable(slice, idx1, idx2) = slice {
113 if let Some(slice) = Sugg::hir_opt(cx, slice) {
116 format!(" elements of `{}`", slice),
120 snippet_with_applicability(cx, idx1.span, "..", &mut applicability),
121 snippet_with_applicability(cx, idx2.span, "..", &mut applicability),
125 (false, String::new(), String::new())
127 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
130 format!(" `{}` and `{}`", first, second),
131 format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()),
134 (true, String::new(), String::new())
137 let span = w[0].span.to(second.span);
143 &format!("this looks like you are swapping{} manually", what),
145 if !sugg.is_empty() {
146 diag.span_suggestion(
154 diag.note("or maybe you should use `std::mem::replace`?");
165 /// `slice.swap(idx1, idx2)` can be used
170 /// # let mut a = vec![0, 1];
174 /// // can be written as
177 Swappable(&'a Expr<'a>, &'a Expr<'a>, &'a Expr<'a>),
178 /// The `swap` function cannot be used.
183 /// # let mut a = [vec![1, 2], vec![3, 4]];
185 /// a[0][1] = a[1][0];
193 /// Checks if both expressions are index operations into "slice-like" types.
194 fn check_for_slice<'a>(cx: &LateContext<'_>, lhs1: &'a Expr<'_>, lhs2: &'a Expr<'_>) -> Slice<'a> {
195 if let ExprKind::Index(lhs1, idx1) = lhs1.kind {
196 if let ExprKind::Index(lhs2, idx2) = lhs2.kind {
197 if eq_expr_value(cx, lhs1, lhs2) {
198 let ty = cx.typeck_results().expr_ty(lhs1).peel_refs();
200 if matches!(ty.kind(), ty::Slice(_))
201 || matches!(ty.kind(), ty::Array(_, _))
202 || is_type_diagnostic_item(cx, ty, sym::vec_type)
203 || is_type_diagnostic_item(cx, ty, sym::vecdeque_type)
205 return Slice::Swappable(lhs1, idx1, idx2);
208 return Slice::NotSwappable;
216 /// Implementation of the `ALMOST_SWAPPED` lint.
217 fn check_suspicious_swap(cx: &LateContext<'_>, block: &Block<'_>) {
218 for w in block.stmts.windows(2) {
220 if let StmtKind::Semi(first) = w[0].kind;
221 if let StmtKind::Semi(second) = w[1].kind;
222 if !differing_macro_contexts(first.span, second.span);
223 if let ExprKind::Assign(lhs0, rhs0, _) = first.kind;
224 if let ExprKind::Assign(lhs1, rhs1, _) = second.kind;
225 if eq_expr_value(cx, lhs0, rhs1);
226 if eq_expr_value(cx, lhs1, rhs0);
228 let lhs0 = Sugg::hir_opt(cx, lhs0);
229 let rhs0 = Sugg::hir_opt(cx, rhs0);
230 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
232 format!(" `{}` and `{}`", first, second),
233 first.mut_addr().to_string(),
234 second.mut_addr().to_string(),
237 (String::new(), String::new(), String::new())
240 let span = first.span.to(second.span);
242 span_lint_and_then(cx,
245 &format!("this looks like you are trying to swap{}", what),
247 if !what.is_empty() {
248 diag.span_suggestion(
252 "std::mem::swap({}, {})",
256 Applicability::MaybeIncorrect,
258 diag.note("or maybe you should use `std::mem::replace`?");