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