]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/no_effect.rs
Auto merge of #3675 - mikerite:fix-build-20190120, r=matthiaskrgr
[rust.git] / clippy_lints / src / no_effect.rs
1 use crate::utils::{has_drop, in_macro, snippet_opt, span_lint, span_lint_and_sugg};
2 use rustc::hir::def::Def;
3 use rustc::hir::{BinOpKind, BlockCheckMode, Expr, ExprKind, Stmt, StmtKind, UnsafeSource};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_errors::Applicability;
7 use std::ops::Deref;
8
9 /// **What it does:** Checks for statements which have no effect.
10 ///
11 /// **Why is this bad?** Similar to dead code, these statements are actually
12 /// executed. However, as they have no effect, all they do is make the code less
13 /// readable.
14 ///
15 /// **Known problems:** None.
16 ///
17 /// **Example:**
18 /// ```rust
19 /// 0;
20 /// ```
21 declare_clippy_lint! {
22     pub NO_EFFECT,
23     complexity,
24     "statements with no effect"
25 }
26
27 /// **What it does:** Checks for expression statements that can be reduced to a
28 /// sub-expression.
29 ///
30 /// **Why is this bad?** Expressions by themselves often have no side-effects.
31 /// Having such expressions reduces readability.
32 ///
33 /// **Known problems:** None.
34 ///
35 /// **Example:**
36 /// ```rust
37 /// compute_array()[0];
38 /// ```
39 declare_clippy_lint! {
40     pub UNNECESSARY_OPERATION,
41     complexity,
42     "outer expressions with no effect"
43 }
44
45 fn has_no_effect(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
46     if in_macro(expr.span) {
47         return false;
48     }
49     match expr.node {
50         ExprKind::Lit(..) | ExprKind::Closure(.., _) => true,
51         ExprKind::Path(..) => !has_drop(cx, cx.tables.expr_ty(expr)),
52         ExprKind::Index(ref a, ref b) | ExprKind::Binary(_, ref a, ref b) => {
53             has_no_effect(cx, a) && has_no_effect(cx, b)
54         },
55         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => v.iter().all(|val| has_no_effect(cx, val)),
56         ExprKind::Repeat(ref inner, _)
57         | ExprKind::Cast(ref inner, _)
58         | ExprKind::Type(ref inner, _)
59         | ExprKind::Unary(_, ref inner)
60         | ExprKind::Field(ref inner, _)
61         | ExprKind::AddrOf(_, ref inner)
62         | ExprKind::Box(ref inner) => has_no_effect(cx, inner),
63         ExprKind::Struct(_, ref fields, ref base) => {
64             !has_drop(cx, cx.tables.expr_ty(expr))
65                 && fields.iter().all(|field| has_no_effect(cx, &field.expr))
66                 && match *base {
67                     Some(ref base) => has_no_effect(cx, base),
68                     None => true,
69                 }
70         },
71         ExprKind::Call(ref callee, ref args) => {
72             if let ExprKind::Path(ref qpath) = callee.node {
73                 let def = cx.tables.qpath_def(qpath, callee.hir_id);
74                 match def {
75                     Def::Struct(..) | Def::Variant(..) | Def::StructCtor(..) | Def::VariantCtor(..) => {
76                         !has_drop(cx, cx.tables.expr_ty(expr)) && args.iter().all(|arg| has_no_effect(cx, arg))
77                     },
78                     _ => false,
79                 }
80             } else {
81                 false
82             }
83         },
84         ExprKind::Block(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 StmtKind::Semi(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                     Applicability::MachineApplicable,
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         ExprKind::Index(ref a, ref b) => Some(vec![&**a, &**b]),
143         ExprKind::Binary(ref binop, ref a, ref b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
144             Some(vec![&**a, &**b])
145         },
146         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => Some(v.iter().collect()),
147         ExprKind::Repeat(ref inner, _)
148         | ExprKind::Cast(ref inner, _)
149         | ExprKind::Type(ref inner, _)
150         | ExprKind::Unary(_, ref inner)
151         | ExprKind::Field(ref inner, _)
152         | ExprKind::AddrOf(_, ref inner)
153         | ExprKind::Box(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
154         ExprKind::Struct(_, ref fields, ref base) => {
155             if has_drop(cx, cx.tables.expr_ty(expr)) {
156                 None
157             } else {
158                 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
159             }
160         },
161         ExprKind::Call(ref callee, ref args) => {
162             if let ExprKind::Path(ref qpath) = callee.node {
163                 let def = cx.tables.qpath_def(qpath, callee.hir_id);
164                 match def {
165                     Def::Struct(..) | Def::Variant(..) | Def::StructCtor(..) | Def::VariantCtor(..)
166                         if !has_drop(cx, cx.tables.expr_ty(expr)) =>
167                     {
168                         Some(args.iter().collect())
169                     },
170                     _ => None,
171                 }
172             } else {
173                 None
174             }
175         },
176         ExprKind::Block(ref block, _) => {
177             if block.stmts.is_empty() {
178                 block.expr.as_ref().and_then(|e| {
179                     match block.rules {
180                         BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
181                         BlockCheckMode::DefaultBlock => Some(vec![&**e]),
182                         // in case of compiler-inserted signaling blocks
183                         _ => reduce_expression(cx, e),
184                     }
185                 })
186             } else {
187                 None
188             }
189         },
190         _ => None,
191     }
192 }