1 use crate::utils::sugg::Sugg;
3 differing_macro_contexts, match_type, is_type_diagnostic_item, paths, snippet,
4 span_lint_and_then, walk_ptrs_ty, SpanlessEq,
6 use if_chain::if_chain;
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
11 use rustc::{declare_lint_pass, declare_tool_lint};
12 use rustc_errors::Applicability;
13 use syntax_pos::Symbol;
15 declare_clippy_lint! {
16 /// **What it does:** Checks for manual swapping.
18 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
19 /// without deinitializing or copying either variable.
21 /// **Known problems:** None.
32 /// Use std::mem::swap():
36 /// std::mem::swap(&mut a, &mut b);
40 "manual swap of two variables"
43 declare_clippy_lint! {
44 /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
46 /// **Why is this bad?** This looks like a failed attempt to swap.
48 /// **Known problems:** None.
57 /// Could be written as:
61 /// std::mem::swap(&mut a, &mut b);
65 "`foo = bar; bar = foo` sequence"
68 declare_lint_pass!(Swap => [MANUAL_SWAP, ALMOST_SWAPPED]);
70 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Swap {
71 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
72 check_manual_swap(cx, block);
73 check_suspicious_swap(cx, block);
77 /// Implementation of the `MANUAL_SWAP` lint.
78 fn check_manual_swap(cx: &LateContext<'_, '_>, block: &Block) {
79 for w in block.stmts.windows(3) {
82 if let StmtKind::Local(ref tmp) = w[0].node;
83 if let Some(ref tmp_init) = tmp.init;
84 if let PatKind::Binding(.., ident, None) = tmp.pat.node;
87 if let StmtKind::Semi(ref first) = w[1].node;
88 if let ExprKind::Assign(ref lhs1, ref rhs1) = first.node;
91 if let StmtKind::Semi(ref second) = w[2].node;
92 if let ExprKind::Assign(ref lhs2, ref rhs2) = second.node;
93 if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.node;
94 if rhs2.segments.len() == 1;
96 if ident.as_str() == rhs2.segments[0].ident.as_str();
97 if SpanlessEq::new(cx).ignore_fn().eq_expr(tmp_init, lhs1);
98 if SpanlessEq::new(cx).ignore_fn().eq_expr(rhs1, lhs2);
100 fn check_for_slice<'a>(
101 cx: &LateContext<'_, '_>,
104 ) -> Option<(&'a Expr, &'a Expr, &'a Expr)> {
105 if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.node {
106 if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.node {
107 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
108 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
110 if matches!(ty.sty, ty::Slice(_)) ||
111 matches!(ty.sty, ty::Array(_, _)) ||
112 is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type")) ||
113 match_type(cx, ty, &paths::VEC_DEQUE) {
114 return Some((lhs1, idx1, idx2));
123 let (replace, what, sugg) = if let Some((slice, idx1, idx2)) = check_for_slice(cx, lhs1, lhs2) {
124 if let Some(slice) = Sugg::hir_opt(cx, slice) {
126 format!(" elements of `{}`", slice),
127 format!("{}.swap({}, {})",
129 snippet(cx, idx1.span, ".."),
130 snippet(cx, idx2.span, "..")))
132 (false, String::new(), String::new())
134 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
135 (true, format!(" `{}` and `{}`", first, second),
136 format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()))
138 (true, String::new(), String::new())
141 let span = w[0].span.to(second.span);
143 span_lint_and_then(cx,
146 &format!("this looks like you are swapping{} manually", what),
148 if !sugg.is_empty() {
153 Applicability::Unspecified,
157 db.note("or maybe you should use `std::mem::replace`?");
166 /// Implementation of the `ALMOST_SWAPPED` lint.
167 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block) {
168 for w in block.stmts.windows(2) {
170 if let StmtKind::Semi(ref first) = w[0].node;
171 if let StmtKind::Semi(ref second) = w[1].node;
172 if !differing_macro_contexts(first.span, second.span);
173 if let ExprKind::Assign(ref lhs0, ref rhs0) = first.node;
174 if let ExprKind::Assign(ref lhs1, ref rhs1) = second.node;
175 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
176 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
178 let lhs0 = Sugg::hir_opt(cx, lhs0);
179 let rhs0 = Sugg::hir_opt(cx, rhs0);
180 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
182 format!(" `{}` and `{}`", first, second),
183 first.mut_addr().to_string(),
184 second.mut_addr().to_string(),
187 (String::new(), String::new(), String::new())
190 let span = first.span.to(second.span);
192 span_lint_and_then(cx,
195 &format!("this looks like you are trying to swap{}", what),
197 if !what.is_empty() {
202 "std::mem::swap({}, {})",
206 Applicability::MaybeIncorrect,
208 db.note("or maybe you should use `std::mem::replace`?");