]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/swap.rs
Auto merge of #3597 - xfix:match-ergonomics, r=phansch
[rust.git] / clippy_lints / src / swap.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
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.
9
10 use crate::utils::sugg::Sugg;
11 use crate::utils::{
12     differing_macro_contexts, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty, SpanlessEq,
13 };
14 use if_chain::if_chain;
15 use matches::matches;
16 use rustc::hir::*;
17 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
18 use rustc::ty;
19 use rustc::{declare_tool_lint, lint_array};
20 use rustc_errors::Applicability;
21
22 /// **What it does:** Checks for manual swapping.
23 ///
24 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
25 /// without deinitializing or copying either variable.
26 ///
27 /// **Known problems:** None.
28 ///
29 /// **Example:**
30 /// ```rust,ignore
31 /// let t = b;
32 /// b = a;
33 /// a = t;
34 /// ```
35 /// Use std::mem::swap():
36 /// ```rust
37 /// std::mem::swap(&mut a, &mut b);
38 /// ```
39 declare_clippy_lint! {
40     pub MANUAL_SWAP,
41     complexity,
42     "manual swap of two variables"
43 }
44
45 /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
46 ///
47 /// **Why is this bad?** This looks like a failed attempt to swap.
48 ///
49 /// **Known problems:** None.
50 ///
51 /// **Example:**
52 /// ```rust,ignore
53 /// a = b;
54 /// b = a;
55 /// ```
56 declare_clippy_lint! {
57     pub ALMOST_SWAPPED,
58     correctness,
59     "`foo = bar; bar = foo` sequence"
60 }
61
62 #[derive(Copy, Clone)]
63 pub struct Swap;
64
65 impl LintPass for Swap {
66     fn get_lints(&self) -> LintArray {
67         lint_array![MANUAL_SWAP, ALMOST_SWAPPED]
68     }
69 }
70
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);
75     }
76 }
77
78 /// Implementation of the `MANUAL_SWAP` lint.
79 fn check_manual_swap(cx: &LateContext<'_, '_>, block: &Block) {
80     for w in block.stmts.windows(3) {
81         if_chain! {
82             // let t = foo();
83             if let StmtKind::Decl(ref tmp, _) = w[0].node;
84             if let DeclKind::Local(ref tmp) = tmp.node;
85             if let Some(ref tmp_init) = tmp.init;
86             if let PatKind::Binding(_, _, ident, None) = tmp.pat.node;
87
88             // foo() = bar();
89             if let StmtKind::Semi(ref first, _) = w[1].node;
90             if let ExprKind::Assign(ref lhs1, ref rhs1) = first.node;
91
92             // bar() = t;
93             if let StmtKind::Semi(ref second, _) = w[2].node;
94             if let ExprKind::Assign(ref lhs2, ref rhs2) = second.node;
95             if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.node;
96             if rhs2.segments.len() == 1;
97
98             if ident.as_str() == rhs2.segments[0].ident.as_str();
99             if SpanlessEq::new(cx).ignore_fn().eq_expr(tmp_init, lhs1);
100             if SpanlessEq::new(cx).ignore_fn().eq_expr(rhs1, lhs2);
101             then {
102                 fn check_for_slice<'a>(
103                     cx: &LateContext<'_, '_>,
104                     lhs1: &'a Expr,
105                     lhs2: &'a Expr,
106                 ) -> Option<(&'a Expr, &'a Expr, &'a Expr)> {
107                     if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.node {
108                         if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.node {
109                             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
110                                 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
111
112                                 if matches!(ty.sty, ty::Slice(_)) ||
113                                     matches!(ty.sty, ty::Array(_, _)) ||
114                                     match_type(cx, ty, &paths::VEC) ||
115                                     match_type(cx, ty, &paths::VEC_DEQUE) {
116                                         return Some((lhs1, idx1, idx2));
117                                 }
118                             }
119                         }
120                     }
121
122                     None
123                 }
124
125                 let (replace, what, sugg) = if let Some((slice, idx1, idx2)) = check_for_slice(cx, lhs1, lhs2) {
126                     if let Some(slice) = Sugg::hir_opt(cx, slice) {
127                         (false,
128                          format!(" elements of `{}`", slice),
129                          format!("{}.swap({}, {})",
130                                  slice.maybe_par(),
131                                  snippet(cx, idx1.span, ".."),
132                                  snippet(cx, idx2.span, "..")))
133                     } else {
134                         (false, String::new(), String::new())
135                     }
136                 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
137                     (true, format!(" `{}` and `{}`", first, second),
138                         format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()))
139                 } else {
140                     (true, String::new(), String::new())
141                 };
142
143                 let span = w[0].span.to(second.span);
144
145                 span_lint_and_then(cx,
146                                    MANUAL_SWAP,
147                                    span,
148                                    &format!("this looks like you are swapping{} manually", what),
149                                    |db| {
150                                        if !sugg.is_empty() {
151                                            db.span_suggestion_with_applicability(
152                                                span,
153                                                "try",
154                                                sugg,
155                                                Applicability::Unspecified,
156                                            );
157
158                                            if replace {
159                                                db.note("or maybe you should use `std::mem::replace`?");
160                                            }
161                                        }
162                                    });
163             }
164         }
165     }
166 }
167
168 /// Implementation of the `ALMOST_SWAPPED` lint.
169 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block) {
170     for w in block.stmts.windows(2) {
171         if_chain! {
172             if let StmtKind::Semi(ref first, _) = w[0].node;
173             if let StmtKind::Semi(ref second, _) = w[1].node;
174             if !differing_macro_contexts(first.span, second.span);
175             if let ExprKind::Assign(ref lhs0, ref rhs0) = first.node;
176             if let ExprKind::Assign(ref lhs1, ref rhs1) = second.node;
177             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
178             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
179             then {
180                 let lhs0 = Sugg::hir_opt(cx, lhs0);
181                 let rhs0 = Sugg::hir_opt(cx, rhs0);
182                 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
183                     (
184                         format!(" `{}` and `{}`", first, second),
185                         first.mut_addr().to_string(),
186                         second.mut_addr().to_string(),
187                     )
188                 } else {
189                     (String::new(), String::new(), String::new())
190                 };
191
192                 let span = first.span.to(second.span);
193
194                 span_lint_and_then(cx,
195                                    ALMOST_SWAPPED,
196                                    span,
197                                    &format!("this looks like you are trying to swap{}", what),
198                                    |db| {
199                                        if !what.is_empty() {
200                                            db.span_suggestion_with_applicability(
201                                                span,
202                                                "try",
203                                                format!(
204                                                    "std::mem::swap({}, {})",
205                                                    lhs,
206                                                    rhs,
207                                                ),
208                                                Applicability::MaybeIncorrect,
209                                            );
210                                            db.note("or maybe you should use `std::mem::replace`?");
211                                        }
212                                    });
213             }
214         }
215     }
216 }