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