]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/no_effect.rs
Rustup to *rustc 1.15.0-nightly (3bf2be9ce 2016-11-22)*
[rust.git] / clippy_lints / src / no_effect.rs
1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::hir::def::{Def, PathResolution};
3 use rustc::hir::{Expr, Expr_, Stmt, StmtSemi, BlockCheckMode, UnsafeSource};
4 use utils::{in_macro, span_lint, snippet_opt, span_lint_and_then};
5 use std::ops::Deref;
6
7 /// **What it does:** Checks for statements which have no effect.
8 ///
9 /// **Why is this bad?** Similar to dead code, these statements are actually
10 /// executed. However, as they have no effect, all they do is make the code less
11 /// readable.
12 ///
13 /// **Known problems:** None.
14 ///
15 /// **Example:**
16 /// ```rust
17 /// 0;
18 /// ```
19 declare_lint! {
20     pub NO_EFFECT,
21     Warn,
22     "statements with no effect"
23 }
24
25 /// **What it does:** Checks for expression statements that can be reduced to a
26 /// sub-expression.
27 ///
28 /// **Why is this bad?** Expressions by themselves often have no side-effects.
29 /// Having such expressions reduces readability.
30 ///
31 /// **Known problems:** None.
32 ///
33 /// **Example:**
34 /// ```rust
35 /// compute_array()[0];
36 /// ```
37 declare_lint! {
38     pub UNNECESSARY_OPERATION,
39     Warn,
40     "outer expressions with no effect"
41 }
42
43 fn has_no_effect(cx: &LateContext, expr: &Expr) -> bool {
44     if in_macro(cx, expr.span) {
45         return false;
46     }
47     match expr.node {
48         Expr_::ExprLit(..) |
49         Expr_::ExprClosure(..) |
50         Expr_::ExprPath(..) => true,
51         Expr_::ExprIndex(ref a, ref b) |
52         Expr_::ExprBinary(_, ref a, ref b) => has_no_effect(cx, a) && has_no_effect(cx, b),
53         Expr_::ExprArray(ref v) |
54         Expr_::ExprTup(ref v) => v.iter().all(|val| has_no_effect(cx, val)),
55         Expr_::ExprRepeat(ref inner, _) |
56         Expr_::ExprCast(ref inner, _) |
57         Expr_::ExprType(ref inner, _) |
58         Expr_::ExprUnary(_, ref inner) |
59         Expr_::ExprField(ref inner, _) |
60         Expr_::ExprTupField(ref inner, _) |
61         Expr_::ExprAddrOf(_, ref inner) |
62         Expr_::ExprBox(ref inner) => has_no_effect(cx, inner),
63         Expr_::ExprStruct(_, ref fields, ref base) => {
64             fields.iter().all(|field| has_no_effect(cx, &field.expr)) &&
65             match *base {
66                 Some(ref base) => has_no_effect(cx, base),
67                 None => true,
68             }
69         }
70         Expr_::ExprCall(ref callee, ref args) => {
71             let def = cx.tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def());
72             match def {
73                 Some(Def::Struct(..)) |
74                 Some(Def::Variant(..)) |
75                 Some(Def::StructCtor(..)) |
76                 Some(Def::VariantCtor(..)) => args.iter().all(|arg| has_no_effect(cx, arg)),
77                 _ => false,
78             }
79         }
80         Expr_::ExprBlock(ref block) => {
81             block.stmts.is_empty() &&
82             if let Some(ref expr) = block.expr {
83                 has_no_effect(cx, expr)
84             } else {
85                 false
86             }
87         }
88         _ => false,
89     }
90 }
91
92 #[derive(Copy, Clone)]
93 pub struct Pass;
94
95 impl LintPass for Pass {
96     fn get_lints(&self) -> LintArray {
97         lint_array!(NO_EFFECT, UNNECESSARY_OPERATION)
98     }
99 }
100
101 impl LateLintPass for Pass {
102     fn check_stmt(&mut self, cx: &LateContext, stmt: &Stmt) {
103         if let StmtSemi(ref expr, _) = stmt.node {
104             if has_no_effect(cx, expr) {
105                 span_lint(cx, NO_EFFECT, stmt.span, "statement with no effect");
106             } else if let Some(reduced) = reduce_expression(cx, expr) {
107                 let mut snippet = String::new();
108                 for e in reduced {
109                     if in_macro(cx, e.span) {
110                         return;
111                     }
112                     if let Some(snip) = snippet_opt(cx, e.span) {
113                         snippet.push_str(&snip);
114                         snippet.push(';');
115                     } else {
116                         return;
117                     }
118                 }
119                 span_lint_and_then(cx, UNNECESSARY_OPERATION, stmt.span, "statement can be reduced", |db| {
120                     db.span_suggestion(stmt.span, "replace it with", snippet);
121                 });
122             }
123         }
124     }
125 }
126
127
128 fn reduce_expression<'a>(cx: &LateContext, expr: &'a Expr) -> Option<Vec<&'a Expr>> {
129     if in_macro(cx, expr.span) {
130         return None;
131     }
132     match expr.node {
133         Expr_::ExprIndex(ref a, ref b) |
134         Expr_::ExprBinary(_, ref a, ref b) => Some(vec![&**a, &**b]),
135         Expr_::ExprArray(ref v) |
136         Expr_::ExprTup(ref v) => Some(v.iter().collect()),
137         Expr_::ExprRepeat(ref inner, _) |
138         Expr_::ExprCast(ref inner, _) |
139         Expr_::ExprType(ref inner, _) |
140         Expr_::ExprUnary(_, ref inner) |
141         Expr_::ExprField(ref inner, _) |
142         Expr_::ExprTupField(ref inner, _) |
143         Expr_::ExprAddrOf(_, ref inner) |
144         Expr_::ExprBox(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
145         Expr_::ExprStruct(_, ref fields, ref base) => {
146             Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
147         }
148         Expr_::ExprCall(ref callee, ref args) => {
149             match cx.tcx.def_map.borrow().get(&callee.id).map(PathResolution::full_def) {
150                 Some(Def::Struct(..)) |
151                 Some(Def::Variant(..)) |
152                 Some(Def::StructCtor(..)) |
153                 Some(Def::VariantCtor(..)) => Some(args.iter().collect()),
154                 _ => None,
155             }
156         }
157         Expr_::ExprBlock(ref block) => {
158             if block.stmts.is_empty() {
159                 block.expr.as_ref().and_then(|e| {
160                     match block.rules {
161                         BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
162                         BlockCheckMode::DefaultBlock => Some(vec![&**e]),
163                         // in case of compiler-inserted signaling blocks
164                         _ => reduce_expression(cx, e),
165                     }
166                 })
167             } else {
168                 None
169             }
170         }
171         _ => None,
172     }
173 }