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