]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/swap.rs
Auto merge of #4543 - xiongmao86:issue4503, r=flip1995
[rust.git] / clippy_lints / src / swap.rs
1 use crate::utils::sugg::Sugg;
2 use crate::utils::{
3     differing_macro_contexts, is_type_diagnostic_item, match_type, paths, snippet_with_applicability,
4     span_lint_and_then, walk_ptrs_ty, SpanlessEq,
5 };
6 use if_chain::if_chain;
7 use matches::matches;
8 use rustc::ty;
9 use rustc_errors::Applicability;
10 use rustc_hir::*;
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::Symbol;
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for manual swapping.
17     ///
18     /// **Why is this bad?** The `std::mem::swap` function exposes the intent better
19     /// without deinitializing or copying either variable.
20     ///
21     /// **Known problems:** None.
22     ///
23     /// **Example:**
24     /// ```rust
25     /// let mut a = 42;
26     /// let mut b = 1337;
27     ///
28     /// let t = b;
29     /// b = a;
30     /// a = t;
31     /// ```
32     /// Use std::mem::swap():
33     /// ```rust
34     /// let mut a = 1;
35     /// let mut b = 2;
36     /// std::mem::swap(&mut a, &mut b);
37     /// ```
38     pub MANUAL_SWAP,
39     complexity,
40     "manual swap of two variables"
41 }
42
43 declare_clippy_lint! {
44     /// **What it does:** Checks for `foo = bar; bar = foo` sequences.
45     ///
46     /// **Why is this bad?** This looks like a failed attempt to swap.
47     ///
48     /// **Known problems:** None.
49     ///
50     /// **Example:**
51     /// ```rust
52     /// # let mut a = 1;
53     /// # let mut b = 2;
54     /// a = b;
55     /// b = a;
56     /// ```
57     /// Could be written as:
58     /// ```rust
59     /// # let mut a = 1;
60     /// # let mut b = 2;
61     /// std::mem::swap(&mut a, &mut b);
62     /// ```
63     pub ALMOST_SWAPPED,
64     correctness,
65     "`foo = bar; bar = foo` sequence"
66 }
67
68 declare_lint_pass!(Swap => [MANUAL_SWAP, ALMOST_SWAPPED]);
69
70 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Swap {
71     fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx Block<'_>) {
72         check_manual_swap(cx, block);
73         check_suspicious_swap(cx, block);
74     }
75 }
76
77 /// Implementation of the `MANUAL_SWAP` lint.
78 fn check_manual_swap(cx: &LateContext<'_, '_>, block: &Block<'_>) {
79     for w in block.stmts.windows(3) {
80         if_chain! {
81             // let t = foo();
82             if let StmtKind::Local(ref tmp) = w[0].kind;
83             if let Some(ref tmp_init) = tmp.init;
84             if let PatKind::Binding(.., ident, None) = tmp.pat.kind;
85
86             // foo() = bar();
87             if let StmtKind::Semi(ref first) = w[1].kind;
88             if let ExprKind::Assign(ref lhs1, ref rhs1, _) = first.kind;
89
90             // bar() = t;
91             if let StmtKind::Semi(ref second) = w[2].kind;
92             if let ExprKind::Assign(ref lhs2, ref rhs2, _) = second.kind;
93             if let ExprKind::Path(QPath::Resolved(None, ref rhs2)) = rhs2.kind;
94             if rhs2.segments.len() == 1;
95
96             if ident.as_str() == rhs2.segments[0].ident.as_str();
97             if SpanlessEq::new(cx).ignore_fn().eq_expr(tmp_init, lhs1);
98             if SpanlessEq::new(cx).ignore_fn().eq_expr(rhs1, lhs2);
99             then {
100                 if let ExprKind::Field(ref lhs1, _) = lhs1.kind {
101                     if let ExprKind::Field(ref lhs2, _) = lhs2.kind {
102                         if lhs1.hir_id.owner_def_id() == lhs2.hir_id.owner_def_id() {
103                             return;
104                         }
105                     }
106                 }
107
108                 let mut applicability = Applicability::MachineApplicable;
109
110                 let slice = check_for_slice(cx, lhs1, lhs2);
111                 let (replace, what, sugg) = if let Slice::NotSwappable = slice {
112                     return;
113                 } else if let Slice::Swappable(slice, idx1, idx2) = slice {
114                     if let Some(slice) = Sugg::hir_opt(cx, slice) {
115                         (
116                             false,
117                             format!(" elements of `{}`", slice),
118                             format!(
119                                 "{}.swap({}, {})",
120                                 slice.maybe_par(),
121                                 snippet_with_applicability(cx, idx1.span, "..", &mut applicability),
122                                 snippet_with_applicability(cx, idx2.span, "..", &mut applicability),
123                             ),
124                         )
125                     } else {
126                         (false, String::new(), String::new())
127                     }
128                 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
129                     (
130                         true,
131                         format!(" `{}` and `{}`", first, second),
132                         format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()),
133                     )
134                 } else {
135                     (true, String::new(), String::new())
136                 };
137
138                 let span = w[0].span.to(second.span);
139
140                 span_lint_and_then(
141                     cx,
142                     MANUAL_SWAP,
143                     span,
144                     &format!("this looks like you are swapping{} manually", what),
145                     |db| {
146                         if !sugg.is_empty() {
147                             db.span_suggestion(
148                                 span,
149                                 "try",
150                                 sugg,
151                                 applicability,
152                             );
153
154                             if replace {
155                                 db.note("or maybe you should use `std::mem::replace`?");
156                             }
157                         }
158                     }
159                 );
160             }
161         }
162     }
163 }
164
165 enum Slice<'a> {
166     /// `slice.swap(idx1, idx2)` can be used
167     ///
168     /// ## Example
169     ///
170     /// ```rust
171     /// # let mut a = vec![0, 1];
172     /// let t = a[1];
173     /// a[1] = a[0];
174     /// a[0] = t;
175     /// // can be written as
176     /// a.swap(0, 1);
177     /// ```
178     Swappable(&'a Expr<'a>, &'a Expr<'a>, &'a Expr<'a>),
179     /// The `swap` function cannot be used.
180     ///
181     /// ## Example
182     ///
183     /// ```rust
184     /// # let mut a = [vec![1, 2], vec![3, 4]];
185     /// let t = a[0][1];
186     /// a[0][1] = a[1][0];
187     /// a[1][0] = t;
188     /// ```
189     NotSwappable,
190     /// Not a slice
191     None,
192 }
193
194 /// Checks if both expressions are index operations into "slice-like" types.
195 fn check_for_slice<'a>(cx: &LateContext<'_, '_>, lhs1: &'a Expr<'_>, lhs2: &'a Expr<'_>) -> Slice<'a> {
196     if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.kind {
197         if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.kind {
198             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
199                 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
200
201                 if matches!(ty.kind, ty::Slice(_))
202                     || matches!(ty.kind, ty::Array(_, _))
203                     || is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type"))
204                     || match_type(cx, ty, &paths::VEC_DEQUE)
205                 {
206                     return Slice::Swappable(lhs1, idx1, idx2);
207                 }
208             } else {
209                 return Slice::NotSwappable;
210             }
211         }
212     }
213
214     Slice::None
215 }
216
217 /// Implementation of the `ALMOST_SWAPPED` lint.
218 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block<'_>) {
219     for w in block.stmts.windows(2) {
220         if_chain! {
221             if let StmtKind::Semi(ref first) = w[0].kind;
222             if let StmtKind::Semi(ref second) = w[1].kind;
223             if !differing_macro_contexts(first.span, second.span);
224             if let ExprKind::Assign(ref lhs0, ref rhs0, _) = first.kind;
225             if let ExprKind::Assign(ref lhs1, ref rhs1, _) = second.kind;
226             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
227             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
228             then {
229                 let lhs0 = Sugg::hir_opt(cx, lhs0);
230                 let rhs0 = Sugg::hir_opt(cx, rhs0);
231                 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
232                     (
233                         format!(" `{}` and `{}`", first, second),
234                         first.mut_addr().to_string(),
235                         second.mut_addr().to_string(),
236                     )
237                 } else {
238                     (String::new(), String::new(), String::new())
239                 };
240
241                 let span = first.span.to(second.span);
242
243                 span_lint_and_then(cx,
244                                    ALMOST_SWAPPED,
245                                    span,
246                                    &format!("this looks like you are trying to swap{}", what),
247                                    |db| {
248                                        if !what.is_empty() {
249                                            db.span_suggestion(
250                                                span,
251                                                "try",
252                                                format!(
253                                                    "std::mem::swap({}, {})",
254                                                    lhs,
255                                                    rhs,
256                                                ),
257                                                Applicability::MaybeIncorrect,
258                                            );
259                                            db.note("or maybe you should use `std::mem::replace`?");
260                                        }
261                                    });
262             }
263         }
264     }
265 }