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