1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
12 use crate::rustc::hir::*;
13 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use if_chain::if_chain;
17 use crate::utils::{differing_macro_contexts, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty, SpanlessEq};
18 use crate::utils::sugg::Sugg;
19 use crate::rustc_errors::Applicability;
21 /// **What it does:** Checks for manual swapping.
23 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
24 /// without deinitializing or copying either variable.
26 /// **Known problems:** None.
34 /// Use std::mem::swap():
36 /// std::mem::swap(&mut a, &mut b);
38 declare_clippy_lint! {
41 "manual swap of two variables"
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.
55 declare_clippy_lint! {
58 "`foo = bar; bar = foo` sequence"
61 #[derive(Copy, Clone)]
64 impl LintPass for Swap {
65 fn get_lints(&self) -> LintArray {
66 lint_array![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::Decl(ref tmp, _) = w[0].node;
83 if let DeclKind::Local(ref tmp) = tmp.node;
84 if let Some(ref tmp_init) = tmp.init;
85 if let PatKind::Binding(_, _, ident, None) = tmp.pat.node;
88 if let StmtKind::Semi(ref first, _) = w[1].node;
89 if let ExprKind::Assign(ref lhs1, ref rhs1) = first.node;
92 if let StmtKind::Semi(ref second, _) = w[2].node;
93 if let ExprKind::Assign(ref lhs2, ref rhs2) = second.node;
94 if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.node;
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 fn check_for_slice<'a>(
102 cx: &LateContext<'_, '_>,
105 ) -> Option<(&'a Expr, &'a Expr, &'a Expr)> {
106 if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.node {
107 if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.node {
108 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
109 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
111 if matches!(ty.sty, ty::Slice(_)) ||
112 matches!(ty.sty, ty::Array(_, _)) ||
113 match_type(cx, ty, &paths::VEC) ||
114 match_type(cx, ty, &paths::VEC_DEQUE) {
115 return Some((lhs1, idx1, idx2));
124 let (replace, what, sugg) = if let Some((slice, idx1, idx2)) = check_for_slice(cx, lhs1, lhs2) {
125 if let Some(slice) = Sugg::hir_opt(cx, slice) {
127 format!(" elements of `{}`", slice),
128 format!("{}.swap({}, {})",
130 snippet(cx, idx1.span, ".."),
131 snippet(cx, idx2.span, "..")))
133 (false, String::new(), String::new())
135 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
136 (true, format!(" `{}` and `{}`", first, second),
137 format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()))
139 (true, String::new(), String::new())
142 let span = w[0].span.to(second.span);
144 span_lint_and_then(cx,
147 &format!("this looks like you are swapping{} manually", what),
149 if !sugg.is_empty() {
150 db.span_suggestion_with_applicability(
154 Applicability::Unspecified,
158 db.note("or maybe you should use `std::mem::replace`?");
167 /// Implementation of the `ALMOST_SWAPPED` lint.
168 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block) {
169 for w in block.stmts.windows(2) {
171 if let StmtKind::Semi(ref first, _) = w[0].node;
172 if let StmtKind::Semi(ref second, _) = w[1].node;
173 if !differing_macro_contexts(first.span, second.span);
174 if let ExprKind::Assign(ref lhs0, ref rhs0) = first.node;
175 if let ExprKind::Assign(ref lhs1, ref rhs1) = second.node;
176 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
177 if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
179 let lhs0 = Sugg::hir_opt(cx, lhs0);
180 let rhs0 = Sugg::hir_opt(cx, rhs0);
181 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
183 format!(" `{}` and `{}`", first, second),
184 first.mut_addr().to_string(),
185 second.mut_addr().to_string(),
188 (String::new(), String::new(), String::new())
191 let span = first.span.to(second.span);
193 span_lint_and_then(cx,
196 &format!("this looks like you are trying to swap{}", what),
198 if !what.is_empty() {
199 db.span_suggestion_with_applicability(
203 "std::mem::swap({}, {})",
207 Applicability::MaybeIncorrect,
209 db.note("or maybe you should use `std::mem::replace`?");