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_lint_pass, declare_tool_lint};
11 use rustc_errors::Applicability;
13 declare_clippy_lint! {
14 /// **What it does:** Checks for manual swapping.
16 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
17 /// without deinitializing or copying either variable.
19 /// **Known problems:** None.
30 /// Use std::mem::swap():
34 /// std::mem::swap(&mut a, &mut b);
38 "manual swap of two variables"
41 declare_clippy_lint! {
42 /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
44 /// **Why is this bad?** This looks like a failed attempt to swap.
46 /// **Known problems:** None.
57 "`foo = bar; bar = foo` sequence"
60 declare_lint_pass!(Swap => [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::Local(ref tmp) = w[0].node;
75 if let Some(ref tmp_init) = tmp.init;
76 if let PatKind::Binding(.., ident, None) = tmp.pat.node;
79 if let StmtKind::Semi(ref first) = w[1].node;
80 if let ExprKind::Assign(ref lhs1, ref rhs1) = first.node;
83 if let StmtKind::Semi(ref second) = w[2].node;
84 if let ExprKind::Assign(ref lhs2, ref rhs2) = second.node;
85 if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.node;
86 if rhs2.segments.len() == 1;
88 if ident.as_str() == rhs2.segments[0].ident.as_str();
89 if SpanlessEq::new(cx).ignore_fn().eq_expr(tmp_init, lhs1);
90 if SpanlessEq::new(cx).ignore_fn().eq_expr(rhs1, lhs2);
92 fn check_for_slice<'a>(
93 cx: &LateContext<'_, '_>,
96 ) -> Option<(&'a Expr, &'a Expr, &'a Expr)> {
97 if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.node {
98 if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.node {
99 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
100 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
102 if matches!(ty.sty, ty::Slice(_)) ||
103 matches!(ty.sty, ty::Array(_, _)) ||
104 match_type(cx, ty, &paths::VEC) ||
105 match_type(cx, ty, &paths::VEC_DEQUE) {
106 return Some((lhs1, idx1, idx2));
115 let (replace, what, sugg) = if let Some((slice, idx1, idx2)) = check_for_slice(cx, lhs1, lhs2) {
116 if let Some(slice) = Sugg::hir_opt(cx, slice) {
118 format!(" elements of `{}`", slice),
119 format!("{}.swap({}, {})",
121 snippet(cx, idx1.span, ".."),
122 snippet(cx, idx2.span, "..")))
124 (false, String::new(), String::new())
126 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
127 (true, format!(" `{}` and `{}`", first, second),
128 format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()))
130 (true, String::new(), String::new())
133 let span = w[0].span.to(second.span);
135 span_lint_and_then(cx,
138 &format!("this looks like you are swapping{} manually", what),
140 if !sugg.is_empty() {
145 Applicability::Unspecified,
149 db.note("or maybe you should use `std::mem::replace`?");
158 /// Implementation of the `ALMOST_SWAPPED` lint.
159 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block) {
160 for w in block.stmts.windows(2) {
162 if let StmtKind::Semi(ref first) = w[0].node;
163 if let StmtKind::Semi(ref second) = w[1].node;
164 if !differing_macro_contexts(first.span, second.span);
165 if let ExprKind::Assign(ref lhs0, ref rhs0) = first.node;
166 if let ExprKind::Assign(ref lhs1, ref rhs1) = second.node;
167 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
168 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
170 let lhs0 = Sugg::hir_opt(cx, lhs0);
171 let rhs0 = Sugg::hir_opt(cx, rhs0);
172 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
174 format!(" `{}` and `{}`", first, second),
175 first.mut_addr().to_string(),
176 second.mut_addr().to_string(),
179 (String::new(), String::new(), String::new())
182 let span = first.span.to(second.span);
184 span_lint_and_then(cx,
187 &format!("this looks like you are trying to swap{}", what),
189 if !what.is_empty() {
194 "std::mem::swap({}, {})",
198 Applicability::MaybeIncorrect,
200 db.note("or maybe you should use `std::mem::replace`?");