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;
8 use rustc::declare_lint_pass;
10 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use rustc_errors::Applicability;
13 use rustc_session::declare_tool_lint;
14 use syntax_pos::Symbol;
16 declare_clippy_lint! {
17 /// **What it does:** Checks for manual swapping.
19 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
20 /// without deinitializing or copying either variable.
22 /// **Known problems:** None.
33 /// Use std::mem::swap():
37 /// std::mem::swap(&mut a, &mut b);
41 "manual swap of two variables"
44 declare_clippy_lint! {
45 /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
47 /// **Why is this bad?** This looks like a failed attempt to swap.
49 /// **Known problems:** None.
58 /// Could be written as:
62 /// std::mem::swap(&mut a, &mut b);
66 "`foo = bar; bar = foo` sequence"
69 declare_lint_pass!(Swap => [MANUAL_SWAP, ALMOST_SWAPPED]);
71 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Swap {
72 fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block) {
73 check_manual_swap(cx, block);
74 check_suspicious_swap(cx, block);
78 /// Implementation of the `MANUAL_SWAP` lint.
79 fn check_manual_swap(cx: &LateContext<'_, '_>, block: &Block) {
80 for w in block.stmts.windows(3) {
83 if let StmtKind::Local(ref tmp) = w[0].kind;
84 if let Some(ref tmp_init) = tmp.init;
85 if let PatKind::Binding(.., ident, None) = tmp.pat.kind;
88 if let StmtKind::Semi(ref first) = w[1].kind;
89 if let ExprKind::Assign(ref lhs1, ref rhs1) = first.kind;
92 if let StmtKind::Semi(ref second) = w[2].kind;
93 if let ExprKind::Assign(ref lhs2, ref rhs2) = second.kind;
94 if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.kind;
95 if rhs2.segments.len() == 1;
97 if ident.as_str() == rhs2.segments[0].ident.as_str();
98 if SpanlessEq::new(cx).ignore_fn().eq_expr(tmp_init, lhs1);
99 if SpanlessEq::new(cx).ignore_fn().eq_expr(rhs1, lhs2);
101 if let ExprKind::Field(ref lhs1, _) = lhs1.kind {
102 if let ExprKind::Field(ref lhs2, _) = lhs2.kind {
103 if lhs1.hir_id.owner_def_id() == lhs2.hir_id.owner_def_id() {
109 let mut applicability = Applicability::MachineApplicable;
111 let slice = check_for_slice(cx, lhs1, lhs2);
112 let (replace, what, sugg) = if let Slice::NotSwappable = slice {
114 } else if let Slice::Swappable(slice, idx1, idx2) = slice {
115 if let Some(slice) = Sugg::hir_opt(cx, slice) {
118 format!(" elements of `{}`", slice),
122 snippet_with_applicability(cx, idx1.span, "..", &mut applicability),
123 snippet_with_applicability(cx, idx2.span, "..", &mut applicability),
127 (false, String::new(), String::new())
129 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
132 format!(" `{}` and `{}`", first, second),
133 format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()),
136 (true, String::new(), String::new())
139 let span = w[0].span.to(second.span);
145 &format!("this looks like you are swapping{} manually", what),
147 if !sugg.is_empty() {
156 db.note("or maybe you should use `std::mem::replace`?");
167 /// `slice.swap(idx1, idx2)` can be used
172 /// # let mut a = vec![0, 1];
176 /// // can be written as
179 Swappable(&'a Expr, &'a Expr, &'a Expr),
180 /// The `swap` function cannot be used.
185 /// # let mut a = [vec![1, 2], vec![3, 4]];
187 /// a[0][1] = a[1][0];
195 /// Checks if both expressions are index operations into "slice-like" types.
196 fn check_for_slice<'a>(cx: &LateContext<'_, '_>, lhs1: &'a Expr, lhs2: &'a Expr) -> Slice<'a> {
197 if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.kind {
198 if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.kind {
199 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
200 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
202 if matches!(ty.kind, ty::Slice(_))
203 || matches!(ty.kind, ty::Array(_, _))
204 || is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type"))
205 || match_type(cx, ty, &paths::VEC_DEQUE)
207 return Slice::Swappable(lhs1, idx1, idx2);
210 return Slice::NotSwappable;
218 /// Implementation of the `ALMOST_SWAPPED` lint.
219 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block) {
220 for w in block.stmts.windows(2) {
222 if let StmtKind::Semi(ref first) = w[0].kind;
223 if let StmtKind::Semi(ref second) = w[1].kind;
224 if !differing_macro_contexts(first.span, second.span);
225 if let ExprKind::Assign(ref lhs0, ref rhs0) = first.kind;
226 if let ExprKind::Assign(ref lhs1, ref rhs1) = second.kind;
227 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
228 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
230 let lhs0 = Sugg::hir_opt(cx, lhs0);
231 let rhs0 = Sugg::hir_opt(cx, rhs0);
232 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
234 format!(" `{}` and `{}`", first, second),
235 first.mut_addr().to_string(),
236 second.mut_addr().to_string(),
239 (String::new(), String::new(), String::new())
242 let span = first.span.to(second.span);
244 span_lint_and_then(cx,
247 &format!("this looks like you are trying to swap{}", what),
249 if !what.is_empty() {
254 "std::mem::swap({}, {})",
258 Applicability::MaybeIncorrect,
260 db.note("or maybe you should use `std::mem::replace`?");