]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/swap.rs
584bcb0d866a76ea0b1d40c1485beb0a4a5f3120
[rust.git] / clippy_lints / src / swap.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use rustc::ty;
4 use syntax::codemap::mk_sp;
5 use utils::{differing_macro_contexts, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty, SpanlessEq};
6 use utils::sugg::Sugg;
7
8 /// **What it does:** Checks for manual swapping.
9 ///
10 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
11 /// without deinitializing or copying either variable.
12 ///
13 /// **Known problems:** None.
14 ///
15 /// **Example:**
16 /// ```rust,ignore
17 /// let t = b;
18 /// b = a;
19 /// a = t;
20 /// ```
21 declare_lint! {
22     pub MANUAL_SWAP,
23     Warn,
24     "manual swap of two variables"
25 }
26
27 /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
28 ///
29 /// **Why is this bad?** This looks like a failed attempt to swap.
30 ///
31 /// **Known problems:** None.
32 ///
33 /// **Example:**
34 /// ```rust,ignore
35 /// a = b;
36 /// b = a;
37 /// ```
38 declare_lint! {
39     pub ALMOST_SWAPPED,
40     Warn,
41     "`foo = bar; bar = foo` sequence"
42 }
43
44 #[derive(Copy,Clone)]
45 pub struct Swap;
46
47 impl LintPass for Swap {
48     fn get_lints(&self) -> LintArray {
49         lint_array![MANUAL_SWAP, ALMOST_SWAPPED]
50     }
51 }
52
53 impl LateLintPass for Swap {
54     fn check_block(&mut self, cx: &LateContext, block: &Block) {
55         check_manual_swap(cx, block);
56         check_suspicious_swap(cx, block);
57     }
58 }
59
60 /// Implementation of the `MANUAL_SWAP` lint.
61 fn check_manual_swap(cx: &LateContext, block: &Block) {
62     for w in block.stmts.windows(3) {
63         if_let_chain!{[
64             // let t = foo();
65             let StmtDecl(ref tmp, _) = w[0].node,
66             let DeclLocal(ref tmp) = tmp.node,
67             let Some(ref tmp_init) = tmp.init,
68             let PatKind::Binding(_, ref tmp_name, None) = tmp.pat.node,
69
70             // foo() = bar();
71             let StmtSemi(ref first, _) = w[1].node,
72             let ExprAssign(ref lhs1, ref rhs1) = first.node,
73
74             // bar() = t;
75             let StmtSemi(ref second, _) = w[2].node,
76             let ExprAssign(ref lhs2, ref rhs2) = second.node,
77             let ExprPath(None, ref rhs2) = rhs2.node,
78             rhs2.segments.len() == 1,
79
80             tmp_name.node.as_str() == rhs2.segments[0].name.as_str(),
81             SpanlessEq::new(cx).ignore_fn().eq_expr(tmp_init, lhs1),
82             SpanlessEq::new(cx).ignore_fn().eq_expr(rhs1, lhs2)
83         ], {
84             fn check_for_slice<'a>(cx: &LateContext, lhs1: &'a Expr, lhs2: &'a Expr) -> Option<(&'a Expr, &'a Expr, &'a Expr)> {
85                 if let ExprIndex(ref lhs1, ref idx1) = lhs1.node {
86                     if let ExprIndex(ref lhs2, ref idx2) = lhs2.node {
87                         if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
88                             let ty = walk_ptrs_ty(cx.tcx.expr_ty(lhs1));
89
90                             if matches!(ty.sty, ty::TySlice(_)) ||
91                                 matches!(ty.sty, ty::TyArray(_, _)) ||
92                                 match_type(cx, ty, &paths::VEC) ||
93                                 match_type(cx, ty, &paths::VEC_DEQUE) {
94                                     return Some((lhs1, idx1, idx2));
95                             }
96                         }
97                     }
98                 }
99
100                 None
101             }
102
103             let (replace, what, sugg) = if let Some((slice, idx1, idx2)) = check_for_slice(cx, lhs1, lhs2) {
104                 if let Some(slice) = Sugg::hir_opt(cx, slice) {
105                     (false,
106                      format!(" elements of `{}`", slice),
107                      format!("{}.swap({}, {})", slice.maybe_par(), snippet(cx, idx1.span, ".."), snippet(cx, idx2.span, "..")))
108                 } else {
109                     (false, "".to_owned(), "".to_owned())
110                 }
111             } else {
112                  if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
113                     (true, format!(" `{}` and `{}`", first, second),
114                      format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()))
115                 } else {
116                     (true, "".to_owned(), "".to_owned())
117                 }
118             };
119
120             let span = mk_sp(w[0].span.lo, second.span.hi);
121
122             span_lint_and_then(cx,
123                                MANUAL_SWAP,
124                                span,
125                                &format!("this looks like you are swapping{} manually", what),
126                                |db| {
127                                    if !sugg.is_empty() {
128                                        db.span_suggestion(span, "try", sugg);
129
130                                        if replace {
131                                            db.note("or maybe you should use `std::mem::replace`?");
132                                        }
133                                    }
134                                });
135         }}
136     }
137 }
138
139 /// Implementation of the `ALMOST_SWAPPED` lint.
140 fn check_suspicious_swap(cx: &LateContext, block: &Block) {
141     for w in block.stmts.windows(2) {
142         if_let_chain!{[
143             let StmtSemi(ref first, _) = w[0].node,
144             let StmtSemi(ref second, _) = w[1].node,
145             !differing_macro_contexts(first.span, second.span),
146             let ExprAssign(ref lhs0, ref rhs0) = first.node,
147             let ExprAssign(ref lhs1, ref rhs1) = second.node,
148             SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1),
149             SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0)
150         ], {
151             let (what, lhs, rhs) = if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs0), Sugg::hir_opt(cx, rhs0)) {
152                 (format!(" `{}` and `{}`", first, second), first.mut_addr().to_string(), second.mut_addr().to_string())
153             } else {
154                 ("".to_owned(), "".to_owned(), "".to_owned())
155             };
156
157             let span = mk_sp(first.span.lo, second.span.hi);
158
159             span_lint_and_then(cx,
160                                ALMOST_SWAPPED,
161                                span,
162                                &format!("this looks like you are trying to swap{}", what),
163                                |db| {
164                                    if !what.is_empty() {
165                                        db.span_suggestion(span, "try",
166                                                           format!("std::mem::swap({}, {})", lhs, rhs));
167                                        db.note("or maybe you should use `std::mem::replace`?");
168                                    }
169                                });
170         }}
171     }
172 }