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