4 use rustc::{declare_lint, lint_array};
5 use if_chain::if_chain;
7 use crate::utils::{differing_macro_contexts, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty, SpanlessEq};
8 use crate::utils::sugg::Sugg;
10 /// **What it does:** Checks for manual swapping.
12 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
13 /// without deinitializing or copying either variable.
15 /// **Known problems:** None.
23 declare_clippy_lint! {
26 "manual swap of two variables"
29 /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
31 /// **Why is this bad?** This looks like a failed attempt to swap.
33 /// **Known problems:** None.
40 declare_clippy_lint! {
43 "`foo = bar; bar = foo` sequence"
46 #[derive(Copy, Clone)]
49 impl LintPass for Swap {
50 fn get_lints(&self) -> LintArray {
51 lint_array![MANUAL_SWAP, ALMOST_SWAPPED]
55 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Swap {
56 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
57 check_manual_swap(cx, block);
58 check_suspicious_swap(cx, block);
62 /// Implementation of the `MANUAL_SWAP` lint.
63 fn check_manual_swap(cx: &LateContext<'_, '_>, block: &Block) {
64 for w in block.stmts.windows(3) {
67 if let StmtKind::Decl(ref tmp, _) = w[0].node;
68 if let DeclKind::Local(ref tmp) = tmp.node;
69 if let Some(ref tmp_init) = tmp.init;
70 if let PatKind::Binding(_, _, ident, None) = tmp.pat.node;
73 if let StmtKind::Semi(ref first, _) = w[1].node;
74 if let ExprKind::Assign(ref lhs1, ref rhs1) = first.node;
77 if let StmtKind::Semi(ref second, _) = w[2].node;
78 if let ExprKind::Assign(ref lhs2, ref rhs2) = second.node;
79 if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.node;
80 if rhs2.segments.len() == 1;
82 if ident.as_str() == rhs2.segments[0].ident.as_str();
83 if SpanlessEq::new(cx).ignore_fn().eq_expr(tmp_init, lhs1);
84 if SpanlessEq::new(cx).ignore_fn().eq_expr(rhs1, lhs2);
86 fn check_for_slice<'a>(
87 cx: &LateContext<'_, '_>,
90 ) -> Option<(&'a Expr, &'a Expr, &'a Expr)> {
91 if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.node {
92 if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.node {
93 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
94 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
96 if matches!(ty.sty, ty::TySlice(_)) ||
97 matches!(ty.sty, ty::TyArray(_, _)) ||
98 match_type(cx, ty, &paths::VEC) ||
99 match_type(cx, ty, &paths::VEC_DEQUE) {
100 return Some((lhs1, idx1, idx2));
109 let (replace, what, sugg) = if let Some((slice, idx1, idx2)) = check_for_slice(cx, lhs1, lhs2) {
110 if let Some(slice) = Sugg::hir_opt(cx, slice) {
112 format!(" elements of `{}`", slice),
113 format!("{}.swap({}, {})",
115 snippet(cx, idx1.span, ".."),
116 snippet(cx, idx2.span, "..")))
118 (false, "".to_owned(), "".to_owned())
120 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
121 (true, format!(" `{}` and `{}`", first, second),
122 format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()))
124 (true, "".to_owned(), "".to_owned())
127 let span = w[0].span.to(second.span);
129 span_lint_and_then(cx,
132 &format!("this looks like you are swapping{} manually", what),
134 if !sugg.is_empty() {
135 db.span_suggestion(span, "try", sugg);
138 db.note("or maybe you should use `std::mem::replace`?");
147 /// Implementation of the `ALMOST_SWAPPED` lint.
148 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block) {
149 for w in block.stmts.windows(2) {
151 if let StmtKind::Semi(ref first, _) = w[0].node;
152 if let StmtKind::Semi(ref second, _) = w[1].node;
153 if !differing_macro_contexts(first.span, second.span);
154 if let ExprKind::Assign(ref lhs0, ref rhs0) = first.node;
155 if let ExprKind::Assign(ref lhs1, ref rhs1) = second.node;
156 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
157 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
159 let lhs0 = Sugg::hir_opt(cx, lhs0);
160 let rhs0 = Sugg::hir_opt(cx, rhs0);
161 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
163 format!(" `{}` and `{}`", first, second),
164 first.mut_addr().to_string(),
165 second.mut_addr().to_string(),
168 ("".to_owned(), "".to_owned(), "".to_owned())
171 let span = first.span.to(second.span);
173 span_lint_and_then(cx,
176 &format!("this looks like you are trying to swap{}", what),
178 if !what.is_empty() {
179 db.span_suggestion(span, "try",
180 format!("std::mem::swap({}, {})", lhs, rhs));
181 db.note("or maybe you should use `std::mem::replace`?");