]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/swap.rs
Remove import of rustc
[rust.git] / clippy_lints / src / swap.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use rustc::{declare_lint, lint_array};
4 use rustc::ty;
5 use crate::utils::{differing_macro_contexts, match_type, paths, snippet, span_lint_and_then, walk_ptrs_ty, SpanlessEq};
6 use crate::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_clippy_lint! {
22     pub MANUAL_SWAP,
23     complexity,
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_clippy_lint! {
39     pub ALMOST_SWAPPED,
40     correctness,
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<'a, 'tcx> LateLintPass<'a, 'tcx> for Swap {
54     fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx 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_chain! {
64             // let t = foo();
65             if let StmtKind::Decl(ref tmp, _) = w[0].node;
66             if let DeclKind::Local(ref tmp) = tmp.node;
67             if let Some(ref tmp_init) = tmp.init;
68             if let PatKind::Binding(_, _, ident, None) = tmp.pat.node;
69
70             // foo() = bar();
71             if let StmtKind::Semi(ref first, _) = w[1].node;
72             if let ExprKind::Assign(ref lhs1, ref rhs1) = first.node;
73
74             // bar() = t;
75             if let StmtKind::Semi(ref second, _) = w[2].node;
76             if let ExprKind::Assign(ref lhs2, ref rhs2) = second.node;
77             if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.node;
78             if rhs2.segments.len() == 1;
79
80             if ident.as_str() == rhs2.segments[0].ident.as_str();
81             if SpanlessEq::new(cx).ignore_fn().eq_expr(tmp_init, lhs1);
82             if SpanlessEq::new(cx).ignore_fn().eq_expr(rhs1, lhs2);
83             then {
84                 fn check_for_slice<'a>(
85                     cx: &LateContext,
86                     lhs1: &'a Expr,
87                     lhs2: &'a Expr,
88                 ) -> Option<(&'a Expr, &'a Expr, &'a Expr)> {
89                     if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.node {
90                         if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.node {
91                             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
92                                 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
93
94                                 if matches!(ty.sty, ty::TySlice(_)) ||
95                                     matches!(ty.sty, ty::TyArray(_, _)) ||
96                                     match_type(cx, ty, &paths::VEC) ||
97                                     match_type(cx, ty, &paths::VEC_DEQUE) {
98                                         return Some((lhs1, idx1, idx2));
99                                 }
100                             }
101                         }
102                     }
103
104                     None
105                 }
106
107                 let (replace, what, sugg) = if let Some((slice, idx1, idx2)) = check_for_slice(cx, lhs1, lhs2) {
108                     if let Some(slice) = Sugg::hir_opt(cx, slice) {
109                         (false,
110                          format!(" elements of `{}`", slice),
111                          format!("{}.swap({}, {})",
112                                  slice.maybe_par(),
113                                  snippet(cx, idx1.span, ".."),
114                                  snippet(cx, idx2.span, "..")))
115                     } else {
116                         (false, "".to_owned(), "".to_owned())
117                     }
118                 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
119                     (true, format!(" `{}` and `{}`", first, second),
120                         format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()))
121                 } else {
122                     (true, "".to_owned(), "".to_owned())
123                 };
124
125                 let span = w[0].span.to(second.span);
126
127                 span_lint_and_then(cx,
128                                    MANUAL_SWAP,
129                                    span,
130                                    &format!("this looks like you are swapping{} manually", what),
131                                    |db| {
132                                        if !sugg.is_empty() {
133                                            db.span_suggestion(span, "try", sugg);
134
135                                            if replace {
136                                                db.note("or maybe you should use `std::mem::replace`?");
137                                            }
138                                        }
139                                    });
140             }
141         }
142     }
143 }
144
145 /// Implementation of the `ALMOST_SWAPPED` lint.
146 fn check_suspicious_swap(cx: &LateContext, block: &Block) {
147     for w in block.stmts.windows(2) {
148         if_chain! {
149             if let StmtKind::Semi(ref first, _) = w[0].node;
150             if let StmtKind::Semi(ref second, _) = w[1].node;
151             if !differing_macro_contexts(first.span, second.span);
152             if let ExprKind::Assign(ref lhs0, ref rhs0) = first.node;
153             if let ExprKind::Assign(ref lhs1, ref rhs1) = second.node;
154             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
155             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
156             then {
157                 let lhs0 = Sugg::hir_opt(cx, lhs0);
158                 let rhs0 = Sugg::hir_opt(cx, rhs0);
159                 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
160                     (
161                         format!(" `{}` and `{}`", first, second),
162                         first.mut_addr().to_string(),
163                         second.mut_addr().to_string(),
164                     )
165                 } else {
166                     ("".to_owned(), "".to_owned(), "".to_owned())
167                 };
168
169                 let span = first.span.to(second.span);
170
171                 span_lint_and_then(cx,
172                                    ALMOST_SWAPPED,
173                                    span,
174                                    &format!("this looks like you are trying to swap{}", what),
175                                    |db| {
176                                        if !what.is_empty() {
177                                            db.span_suggestion(span, "try",
178                                                               format!("std::mem::swap({}, {})", lhs, rhs));
179                                            db.note("or maybe you should use `std::mem::replace`?");
180                                        }
181                                    });
182             }
183         }
184     }
185 }