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