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