]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/swap.rs
Rustup to rust-lang/rust#64813
[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, span_lint_and_then, walk_ptrs_ty,
4     SpanlessEq,
5 };
6 use if_chain::if_chain;
7 use matches::matches;
8 use rustc::hir::*;
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::ty;
11 use rustc::{declare_lint_pass, declare_tool_lint};
12 use rustc_errors::Applicability;
13 use syntax_pos::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                 fn check_for_slice<'a>(
101                     cx: &LateContext<'_, '_>,
102                     lhs1: &'a Expr,
103                     lhs2: &'a Expr,
104                 ) -> Option<(&'a Expr, &'a Expr, &'a Expr)> {
105                     if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.kind {
106                         if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.kind {
107                             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) {
108                                 let ty = walk_ptrs_ty(cx.tables.expr_ty(lhs1));
109
110                                 if matches!(ty.kind, ty::Slice(_)) ||
111                                     matches!(ty.kind, ty::Array(_, _)) ||
112                                     is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type")) ||
113                                     match_type(cx, ty, &paths::VEC_DEQUE) {
114                                         return Some((lhs1, idx1, idx2));
115                                 }
116                             }
117                         }
118                     }
119
120                     None
121                 }
122
123                 if let ExprKind::Field(ref lhs1, _) = lhs1.kind {
124                     if let ExprKind::Field(ref lhs2, _) = lhs2.kind {
125                         if lhs1.hir_id.owner_def_id() == lhs2.hir_id.owner_def_id() {
126                             return;
127                         }
128                     }
129                 }
130
131                 let (replace, what, sugg) = if let Some((slice, idx1, idx2)) = check_for_slice(cx, lhs1, lhs2) {
132                     if let Some(slice) = Sugg::hir_opt(cx, slice) {
133                         (false,
134                          format!(" elements of `{}`", slice),
135                          format!("{}.swap({}, {})",
136                                  slice.maybe_par(),
137                                  snippet(cx, idx1.span, ".."),
138                                  snippet(cx, idx2.span, "..")))
139                     } else {
140                         (false, String::new(), String::new())
141                     }
142                 } else if let (Some(first), Some(second)) = (Sugg::hir_opt(cx, lhs1), Sugg::hir_opt(cx, rhs1)) {
143                     (true, format!(" `{}` and `{}`", first, second),
144                         format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()))
145                 } else {
146                     (true, String::new(), String::new())
147                 };
148
149                 let span = w[0].span.to(second.span);
150
151                 span_lint_and_then(cx,
152                                    MANUAL_SWAP,
153                                    span,
154                                    &format!("this looks like you are swapping{} manually", what),
155                                    |db| {
156                                        if !sugg.is_empty() {
157                                            db.span_suggestion(
158                                                span,
159                                                "try",
160                                                sugg,
161                                                Applicability::Unspecified,
162                                            );
163
164                                            if replace {
165                                                db.note("or maybe you should use `std::mem::replace`?");
166                                            }
167                                        }
168                                    });
169             }
170         }
171     }
172 }
173
174 /// Implementation of the `ALMOST_SWAPPED` lint.
175 fn check_suspicious_swap(cx: &LateContext<'_, '_>, block: &Block) {
176     for w in block.stmts.windows(2) {
177         if_chain! {
178             if let StmtKind::Semi(ref first) = w[0].kind;
179             if let StmtKind::Semi(ref second) = w[1].kind;
180             if !differing_macro_contexts(first.span, second.span);
181             if let ExprKind::Assign(ref lhs0, ref rhs0) = first.kind;
182             if let ExprKind::Assign(ref lhs1, ref rhs1) = second.kind;
183             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1);
184             if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0);
185             then {
186                 let lhs0 = Sugg::hir_opt(cx, lhs0);
187                 let rhs0 = Sugg::hir_opt(cx, rhs0);
188                 let (what, lhs, rhs) = if let (Some(first), Some(second)) = (lhs0, rhs0) {
189                     (
190                         format!(" `{}` and `{}`", first, second),
191                         first.mut_addr().to_string(),
192                         second.mut_addr().to_string(),
193                     )
194                 } else {
195                     (String::new(), String::new(), String::new())
196                 };
197
198                 let span = first.span.to(second.span);
199
200                 span_lint_and_then(cx,
201                                    ALMOST_SWAPPED,
202                                    span,
203                                    &format!("this looks like you are trying to swap{}", what),
204                                    |db| {
205                                        if !what.is_empty() {
206                                            db.span_suggestion(
207                                                span,
208                                                "try",
209                                                format!(
210                                                    "std::mem::swap({}, {})",
211                                                    lhs,
212                                                    rhs,
213                                                ),
214                                                Applicability::MaybeIncorrect,
215                                            );
216                                            db.note("or maybe you should use `std::mem::replace`?");
217                                        }
218                                    });
219             }
220         }
221     }
222 }