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