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