]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/no_effect.rs
Rustup (fixes #2002)
[rust.git] / clippy_lints / src / no_effect.rs
1 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
2 use rustc::hir::def::Def;
3 use rustc::hir::{Expr, Expr_, Stmt, StmtSemi, BlockCheckMode, UnsafeSource, BiAnd, BiOr};
4 use utils::{in_macro, span_lint, snippet_opt, span_lint_and_sugg};
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(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             if let Expr_::ExprPath(ref qpath) = callee.node {
72                 let def = cx.tables.qpath_def(qpath, callee.hir_id);
73                 match def {
74                     Def::Struct(..) |
75                     Def::Variant(..) |
76                     Def::StructCtor(..) |
77                     Def::VariantCtor(..) => args.iter().all(|arg| has_no_effect(cx, arg)),
78                     _ => false,
79                 }
80             } else {
81                 false
82             }
83         },
84         Expr_::ExprBlock(ref block) => {
85             block.stmts.is_empty() &&
86                 if let Some(ref expr) = block.expr {
87                     has_no_effect(cx, expr)
88                 } else {
89                     false
90                 }
91         },
92         _ => false,
93     }
94 }
95
96 #[derive(Copy, Clone)]
97 pub struct Pass;
98
99 impl LintPass for Pass {
100     fn get_lints(&self) -> LintArray {
101         lint_array!(NO_EFFECT, UNNECESSARY_OPERATION)
102     }
103 }
104
105 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
106     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
107         if let StmtSemi(ref expr, _) = stmt.node {
108             if has_no_effect(cx, expr) {
109                 span_lint(cx, NO_EFFECT, stmt.span, "statement with no effect");
110             } else if let Some(reduced) = reduce_expression(cx, expr) {
111                 let mut snippet = String::new();
112                 for e in reduced {
113                     if in_macro(e.span) {
114                         return;
115                     }
116                     if let Some(snip) = snippet_opt(cx, e.span) {
117                         snippet.push_str(&snip);
118                         snippet.push(';');
119                     } else {
120                         return;
121                     }
122                 }
123                 span_lint_and_sugg(
124                     cx,
125                     UNNECESSARY_OPERATION,
126                     stmt.span,
127                     "statement can be reduced",
128                     "replace it with",
129                     snippet,
130                 );
131             }
132         }
133     }
134 }
135
136
137 fn reduce_expression<'a>(cx: &LateContext, expr: &'a Expr) -> Option<Vec<&'a Expr>> {
138     if in_macro(expr.span) {
139         return None;
140     }
141     match expr.node {
142         Expr_::ExprIndex(ref a, ref b) => Some(vec![&**a, &**b]),
143         Expr_::ExprBinary(ref binop, ref a, ref b) if binop.node != BiAnd && binop.node != BiOr => {
144             Some(vec![&**a, &**b])
145         },
146         Expr_::ExprArray(ref v) |
147         Expr_::ExprTup(ref v) => Some(v.iter().collect()),
148         Expr_::ExprRepeat(ref inner, _) |
149         Expr_::ExprCast(ref inner, _) |
150         Expr_::ExprType(ref inner, _) |
151         Expr_::ExprUnary(_, ref inner) |
152         Expr_::ExprField(ref inner, _) |
153         Expr_::ExprTupField(ref inner, _) |
154         Expr_::ExprAddrOf(_, ref inner) |
155         Expr_::ExprBox(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
156         Expr_::ExprStruct(_, ref fields, ref base) => {
157             Some(
158                 fields
159                     .iter()
160                     .map(|f| &f.expr)
161                     .chain(base)
162                     .map(Deref::deref)
163                     .collect(),
164             )
165         },
166         Expr_::ExprCall(ref callee, ref args) => {
167             if let Expr_::ExprPath(ref qpath) = callee.node {
168                 let def = cx.tables.qpath_def(qpath, callee.hir_id);
169                 match def {
170                     Def::Struct(..) |
171                     Def::Variant(..) |
172                     Def::StructCtor(..) |
173                     Def::VariantCtor(..) => Some(args.iter().collect()),
174                     _ => None,
175                 }
176             } else {
177                 None
178             }
179         },
180         Expr_::ExprBlock(ref block) => {
181             if block.stmts.is_empty() {
182                 block.expr.as_ref().and_then(|e| {
183                     match block.rules {
184                         BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
185                         BlockCheckMode::DefaultBlock => Some(vec![&**e]),
186                         // in case of compiler-inserted signaling blocks
187                         _ => reduce_expression(cx, e),
188                     }
189                 })
190             } else {
191                 None
192             }
193         },
194         _ => None,
195     }
196 }