1 use crate::utils::sugg::Sugg;
3 differing_macro_contexts, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty, SpanlessEq,
5 use if_chain::if_chain;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::{declare_tool_lint, lint_array};
11 use rustc_errors::Applicability;
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.
26 /// Use std::mem::swap():
28 /// std::mem::swap(&mut a, &mut b);
30 declare_clippy_lint! {
33 "manual swap of two variables"
36 /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
38 /// **Why is this bad?** This looks like a failed attempt to swap.
40 /// **Known problems:** None.
47 declare_clippy_lint! {
50 "`foo = bar; bar = foo` sequence"
53 #[derive(Copy, Clone)]
56 impl LintPass for Swap {
57 fn get_lints(&self) -> LintArray {
58 lint_array![MANUAL_SWAP, ALMOST_SWAPPED]
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Swap {
63 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
64 check_manual_swap(cx, block);
65 check_suspicious_swap(cx, block);
69 /// Implementation of the `MANUAL_SWAP` lint.
70 fn check_manual_swap(cx: &LateContext<'_, '_>, block: &Block) {
71 for w in block.stmts.windows(3) {
74 if let StmtKind::Decl(ref tmp, _) = w[0].node;
75 if let DeclKind::Local(ref tmp) = tmp.node;
76 if let Some(ref tmp_init) = tmp.init;
77 if let PatKind::Binding(_, _, ident, None) = tmp.pat.node;
80 if let StmtKind::Semi(ref first, _) = w[1].node;
81 if let ExprKind::Assign(ref lhs1, ref rhs1) = first.node;
84 if let StmtKind::Semi(ref second, _) = w[2].node;
85 if let ExprKind::Assign(ref lhs2, ref rhs2) = second.node;
86 if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.node;
87 if rhs2.segments.len() == 1;
89 if ident.as_str() == rhs2.segments[0].ident.as_str();
90 if SpanlessEq::new(cx).ignore_fn().eq_expr(tmp_init, lhs1);
91 if SpanlessEq::new(cx).ignore_fn().eq_expr(rhs1, lhs2);
93 fn check_for_slice<'a>(
94 cx: &LateContext<'_, '_>,
97 ) -> Option<(&'a Expr, &'a Expr, &'a Expr)> {
98 if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.node {
99 if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.node {
100 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
101 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
103 if matches!(ty.sty, ty::Slice(_)) ||
104 matches!(ty.sty, ty::Array(_, _)) ||
105 match_type(cx, ty, &paths::VEC) ||
106 match_type(cx, ty, &paths::VEC_DEQUE) {
107 return Some((lhs1, idx1, idx2));
116 let (replace, what, sugg) = if let Some((slice, idx1, idx2)) = check_for_slice(cx, lhs1, lhs2) {
117 if let Some(slice) = Sugg::hir_opt(cx, slice) {
119 format!(" elements of `{}`", slice),
120 format!("{}.swap({}, {})",
122 snippet(cx, idx1.span, ".."),
123 snippet(cx, idx2.span, "..")))
125 (false, String::new(), String::new())
127 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
128 (true, format!(" `{}` and `{}`", first, second),
129 format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()))
131 (true, String::new(), String::new())
134 let span = w[0].span.to(second.span);
136 span_lint_and_then(cx,
139 &format!("this looks like you are swapping{} manually", what),
141 if !sugg.is_empty() {
142 db.span_suggestion_with_applicability(
146 Applicability::Unspecified,
150 db.note("or maybe you should use `std::mem::replace`?");
159 /// Implementation of the `ALMOST_SWAPPED` lint.
160 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block) {
161 for w in block.stmts.windows(2) {
163 if let StmtKind::Semi(ref first, _) = w[0].node;
164 if let StmtKind::Semi(ref second, _) = w[1].node;
165 if !differing_macro_contexts(first.span, second.span);
166 if let ExprKind::Assign(ref lhs0, ref rhs0) = first.node;
167 if let ExprKind::Assign(ref lhs1, ref rhs1) = second.node;
168 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
169 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
171 let lhs0 = Sugg::hir_opt(cx, lhs0);
172 let rhs0 = Sugg::hir_opt(cx, rhs0);
173 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
175 format!(" `{}` and `{}`", first, second),
176 first.mut_addr().to_string(),
177 second.mut_addr().to_string(),
180 (String::new(), String::new(), String::new())
183 let span = first.span.to(second.span);
185 span_lint_and_then(cx,
188 &format!("this looks like you are trying to swap{}", what),
190 if !what.is_empty() {
191 db.span_suggestion_with_applicability(
195 "std::mem::swap({}, {})",
199 Applicability::MaybeIncorrect,
201 db.note("or maybe you should use `std::mem::replace`?");