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