1 use crate::utils::sugg::Sugg;
3 differing_macro_contexts, is_type_diagnostic_item, match_type, paths, snippet_with_applicability,
4 span_lint_and_then, walk_ptrs_ty, SpanlessEq,
6 use if_chain::if_chain;
9 use rustc_errors::Applicability;
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::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].kind;
83 if let Some(ref tmp_init) = tmp.init;
84 if let PatKind::Binding(.., ident, None) = tmp.pat.kind;
87 if let StmtKind::Semi(ref first) = w[1].kind;
88 if let ExprKind::Assign(ref lhs1, ref rhs1, _) = first.kind;
91 if let StmtKind::Semi(ref second) = w[2].kind;
92 if let ExprKind::Assign(ref lhs2, ref rhs2, _) = second.kind;
93 if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.kind;
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 if let ExprKind::Field(ref lhs1, _) = lhs1.kind {
101 if let ExprKind::Field(ref lhs2, _) = lhs2.kind {
102 if lhs1.hir_id.owner_def_id() == lhs2.hir_id.owner_def_id() {
108 let mut applicability = Applicability::MachineApplicable;
110 let slice = check_for_slice(cx, lhs1, lhs2);
111 let (replace, what, sugg) = if let Slice::NotSwappable = slice {
113 } else if let Slice::Swappable(slice, idx1, idx2) = slice {
114 if let Some(slice) = Sugg::hir_opt(cx, slice) {
117 format!(" elements of `{}`", slice),
121 snippet_with_applicability(cx, idx1.span, "..", &mut applicability),
122 snippet_with_applicability(cx, idx2.span, "..", &mut applicability),
126 (false, String::new(), String::new())
128 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
131 format!(" `{}` and `{}`", first, second),
132 format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()),
135 (true, String::new(), String::new())
138 let span = w[0].span.to(second.span);
144 &format!("this looks like you are swapping{} manually", what),
146 if !sugg.is_empty() {
155 db.note("or maybe you should use `std::mem::replace`?");
166 /// `slice.swap(idx1, idx2)` can be used
171 /// # let mut a = vec![0, 1];
175 /// // can be written as
178 Swappable(&'a Expr<'a>, &'a Expr<'a>, &'a Expr<'a>),
179 /// The `swap` function cannot be used.
184 /// # let mut a = [vec![1, 2], vec![3, 4]];
186 /// a[0][1] = a[1][0];
194 /// Checks if both expressions are index operations into "slice-like" types.
195 fn check_for_slice<'a>(cx: &LateContext<'_, '_>, lhs1: &'a Expr<'_>, lhs2: &'a Expr<'_>) -> Slice<'a> {
196 if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.kind {
197 if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.kind {
198 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
199 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
201 if matches!(ty.kind, ty::Slice(_))
202 || matches!(ty.kind, ty::Array(_, _))
203 || is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type"))
204 || match_type(cx, ty, &paths::VEC_DEQUE)
206 return Slice::Swappable(lhs1, idx1, idx2);
209 return Slice::NotSwappable;
217 /// Implementation of the `ALMOST_SWAPPED` lint.
218 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block<'_>) {
219 for w in block.stmts.windows(2) {
221 if let StmtKind::Semi(ref first) = w[0].kind;
222 if let StmtKind::Semi(ref second) = w[1].kind;
223 if !differing_macro_contexts(first.span, second.span);
224 if let ExprKind::Assign(ref lhs0, ref rhs0, _) = first.kind;
225 if let ExprKind::Assign(ref lhs1, ref rhs1, _) = second.kind;
226 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
227 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
229 let lhs0 = Sugg::hir_opt(cx, lhs0);
230 let rhs0 = Sugg::hir_opt(cx, rhs0);
231 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
233 format!(" `{}` and `{}`", first, second),
234 first.mut_addr().to_string(),
235 second.mut_addr().to_string(),
238 (String::new(), String::new(), String::new())
241 let span = first.span.to(second.span);
243 span_lint_and_then(cx,
246 &format!("this looks like you are trying to swap{}", what),
248 if !what.is_empty() {
253 "std::mem::swap({}, {})",
257 Applicability::MaybeIncorrect,
259 db.note("or maybe you should use `std::mem::replace`?");