]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/swap.rs
Add license header to Rust files
[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
11 use matches::matches;
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;
16 use crate::rustc::ty;
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;
20
21 /// **What it does:** Checks for manual swapping.
22 ///
23 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
24 /// without deinitializing or copying either variable.
25 ///
26 /// **Known problems:** None.
27 ///
28 /// **Example:**
29 /// ```rust,ignore
30 /// let t = b;
31 /// b = a;
32 /// a = t;
33 /// ```
34 /// Use std::mem::swap():
35 /// ```rust
36 /// std::mem::swap(&mut a, &mut b);
37 /// ```
38 declare_clippy_lint! {
39     pub MANUAL_SWAP,
40     complexity,
41     "manual swap of two variables"
42 }
43
44 /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
45 ///
46 /// **Why is this bad?** This looks like a failed attempt to swap.
47 ///
48 /// **Known problems:** None.
49 ///
50 /// **Example:**
51 /// ```rust,ignore
52 /// a = b;
53 /// b = a;
54 /// ```
55 declare_clippy_lint! {
56     pub ALMOST_SWAPPED,
57     correctness,
58     "`foo = bar; bar = foo` sequence"
59 }
60
61 #[derive(Copy, Clone)]
62 pub struct Swap;
63
64 impl LintPass for Swap {
65     fn get_lints(&self) -> LintArray {
66         lint_array![MANUAL_SWAP, ALMOST_SWAPPED]
67     }
68 }
69
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);
74     }
75 }
76
77 /// Implementation of the `MANUAL_SWAP` lint.
78 fn check_manual_swap(cx: &LateContext<'_, '_>, block: &Block) {
79     for w in block.stmts.windows(3) {
80         if_chain! {
81             // let t = foo();
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;
86
87             // foo() = bar();
88             if let StmtKind::Semi(ref first, _) = w[1].node;
89             if let ExprKind::Assign(ref lhs1, ref rhs1) = first.node;
90
91             // bar() = t;
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;
96
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);
100             then {
101                 fn check_for_slice<'a>(
102                     cx: &LateContext<'_, '_>,
103                     lhs1: &'a Expr,
104                     lhs2: &'a Expr,
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));
110
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));
116                                 }
117                             }
118                         }
119                     }
120
121                     None
122                 }
123
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) {
126                         (false,
127                          format!(" elements of `{}`", slice),
128                          format!("{}.swap({}, {})",
129                                  slice.maybe_par(),
130                                  snippet(cx, idx1.span, ".."),
131                                  snippet(cx, idx2.span, "..")))
132                     } else {
133                         (false, String::new(), String::new())
134                     }
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()))
138                 } else {
139                     (true, String::new(), String::new())
140                 };
141
142                 let span = w[0].span.to(second.span);
143
144                 span_lint_and_then(cx,
145                                    MANUAL_SWAP,
146                                    span,
147                                    &format!("this looks like you are swapping{} manually", what),
148                                    |db| {
149                                        if !sugg.is_empty() {
150                                            db.span_suggestion_with_applicability(
151                                                span,
152                                                "try",
153                                                sugg,
154                                                Applicability::Unspecified,
155                                            );
156
157                                            if replace {
158                                                db.note("or maybe you should use `std::mem::replace`?");
159                                            }
160                                        }
161                                    });
162             }
163         }
164     }
165 }
166
167 /// Implementation of the `ALMOST_SWAPPED` lint.
168 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block) {
169     for w in block.stmts.windows(2) {
170         if_chain! {
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);
178             then {
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) {
182                     (
183                         format!(" `{}` and `{}`", first, second),
184                         first.mut_addr().to_string(),
185                         second.mut_addr().to_string(),
186                     )
187                 } else {
188                     (String::new(), String::new(), String::new())
189                 };
190
191                 let span = first.span.to(second.span);
192
193                 span_lint_and_then(cx,
194                                    ALMOST_SWAPPED,
195                                    span,
196                                    &format!("this looks like you are trying to swap{}", what),
197                                    |db| {
198                                        if !what.is_empty() {
199                                            db.span_suggestion_with_applicability(
200                                                span,
201                                                "try",
202                                                format!(
203                                                    "std::mem::swap({}, {})",
204                                                    lhs,
205                                                    rhs,
206                                                ),
207                                                Applicability::MaybeIncorrect,
208                                            );
209                                            db.note("or maybe you should use `std::mem::replace`?");
210                                        }
211                                    });
212             }
213         }
214     }
215 }