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