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