]> git.lizzy.rs Git - rust.git/blob - src/swap.rs
Rustup to *1.10.0-nightly (9c6904ca1 2016-05-18)*
[rust.git] / src / swap.rs
1 use rustc::lint::*;
2 use rustc::hir::*;
3 use syntax::codemap::mk_sp;
4 use utils::{differing_macro_contexts, snippet_opt, span_lint_and_then, SpanlessEq};
5
6 /// **What it does:** This lints manual swapping.
7 ///
8 /// **Why is this bad?** The `std::mem::swap` function exposes the intent better without
9 /// deinitializing or copying either variable.
10 ///
11 /// **Known problems:** None.
12 ///
13 /// **Example:**
14 /// ```rust,ignore
15 /// let t = b;
16 /// b = a;
17 /// a = t;
18 /// ```
19 declare_lint! {
20     pub MANUAL_SWAP,
21     Warn,
22     "manual swap"
23 }
24
25 /// **What it does:** This lints `foo = bar; bar = foo` sequences.
26 ///
27 /// **Why is this bad?** This looks like a failed attempt to swap.
28 ///
29 /// **Known problems:** None.
30 ///
31 /// **Example:**
32 /// ```rust,ignore
33 /// a = b;
34 /// b = a;
35 /// ```
36 declare_lint! {
37     pub ALMOST_SWAPPED,
38     Warn,
39     "`foo = bar; bar = foo` sequence"
40 }
41
42 #[derive(Copy,Clone)]
43 pub struct Swap;
44
45 impl LintPass for Swap {
46     fn get_lints(&self) -> LintArray {
47         lint_array![MANUAL_SWAP, ALMOST_SWAPPED]
48     }
49 }
50
51 impl LateLintPass for Swap {
52     fn check_block(&mut self, cx: &LateContext, block: &Block) {
53         check_manual_swap(cx, block);
54         check_suspicious_swap(cx, block);
55     }
56 }
57
58 /// Implementation of the `MANUAL_SWAP` lint.
59 fn check_manual_swap(cx: &LateContext, block: &Block) {
60     for w in block.stmts.windows(3) {
61         if_let_chain!{[
62             // let t = foo();
63             let StmtDecl(ref tmp, _) = w[0].node,
64             let DeclLocal(ref tmp) = tmp.node,
65             let Some(ref tmp_init) = tmp.init,
66             let PatKind::Ident(_, ref tmp_name, None) = tmp.pat.node,
67
68             // foo() = bar();
69             let StmtSemi(ref first, _) = w[1].node,
70             let ExprAssign(ref lhs1, ref rhs1) = first.node,
71
72             // bar() = t;
73             let StmtSemi(ref second, _) = w[2].node,
74             let ExprAssign(ref lhs2, ref rhs2) = second.node,
75             let ExprPath(None, ref rhs2) = rhs2.node,
76             rhs2.segments.len() == 1,
77
78             tmp_name.node.as_str() == rhs2.segments[0].name.as_str(),
79             SpanlessEq::new(cx).ignore_fn().eq_expr(tmp_init, lhs1),
80             SpanlessEq::new(cx).ignore_fn().eq_expr(rhs1, lhs2)
81         ], {
82             let (what, lhs, rhs) = if let (Some(first), Some(second)) = (snippet_opt(cx, lhs1.span), snippet_opt(cx, rhs1.span)) {
83                 (format!(" `{}` and `{}`", first, second), first, second)
84             } else {
85                 ("".to_owned(), "".to_owned(), "".to_owned())
86             };
87
88             let span = mk_sp(tmp.span.lo, second.span.hi);
89
90             span_lint_and_then(cx,
91                                MANUAL_SWAP,
92                                span,
93                                &format!("this looks like you are swapping{} manually", what),
94                                |db| {
95                                    if !what.is_empty() {
96                                        db.span_suggestion(span, "try",
97                                                           format!("std::mem::swap(&mut {}, &mut {})", lhs, rhs));
98                                        db.note("or maybe you should use `std::mem::replace`?");
99                                    }
100                                });
101         }}
102     }
103 }
104
105 /// Implementation of the `ALMOST_SWAPPED` lint.
106 fn check_suspicious_swap(cx: &LateContext, block: &Block) {
107     for w in block.stmts.windows(2) {
108         if_let_chain!{[
109             let StmtSemi(ref first, _) = w[0].node,
110             let StmtSemi(ref second, _) = w[1].node,
111             !differing_macro_contexts(first.span, second.span),
112             let ExprAssign(ref lhs0, ref rhs0) = first.node,
113             let ExprAssign(ref lhs1, ref rhs1) = second.node,
114             SpanlessEq::new(cx).ignore_fn().eq_expr(lhs0, rhs1),
115             SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, rhs0)
116         ], {
117             let (what, lhs, rhs) = if let (Some(first), Some(second)) = (snippet_opt(cx, lhs0.span), snippet_opt(cx, rhs0.span)) {
118                 (format!(" `{}` and `{}`", first, second), first, second)
119             } else {
120                 ("".to_owned(), "".to_owned(), "".to_owned())
121             };
122
123             let span = mk_sp(first.span.lo, second.span.hi);
124
125             span_lint_and_then(cx,
126                                ALMOST_SWAPPED,
127                                span,
128                                &format!("this looks like you are trying to swap{}", what),
129                                |db| {
130                                    if !what.is_empty() {
131                                        db.span_suggestion(span, "try",
132                                                           format!("std::mem::swap(&mut {}, &mut {})", lhs, rhs));
133                                        db.note("or maybe you should use `std::mem::replace`?");
134                                    }
135                                });
136         }}
137     }
138 }