]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/no_effect.rs
Auto merge of #3845 - euclio:unused-comments, r=phansch
[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 declare_clippy_lint! {
10     /// **What it does:** Checks for statements which have no effect.
11     ///
12     /// **Why is this bad?** Similar to dead code, these statements are actually
13     /// executed. However, as they have no effect, all they do is make the code less
14     /// readable.
15     ///
16     /// **Known problems:** None.
17     ///
18     /// **Example:**
19     /// ```rust
20     /// 0;
21     /// ```
22     pub NO_EFFECT,
23     complexity,
24     "statements with no effect"
25 }
26
27 declare_clippy_lint! {
28     /// **What it does:** Checks for expression statements that can be reduced to a
29     /// sub-expression.
30     ///
31     /// **Why is this bad?** Expressions by themselves often have no side-effects.
32     /// Having such expressions reduces readability.
33     ///
34     /// **Known problems:** None.
35     ///
36     /// **Example:**
37     /// ```rust
38     /// compute_array()[0];
39     /// ```
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     fn name(&self) -> &'static str {
105         "NoEffect"
106     }
107 }
108
109 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
110     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
111         if let StmtKind::Semi(ref expr) = stmt.node {
112             if has_no_effect(cx, expr) {
113                 span_lint(cx, NO_EFFECT, stmt.span, "statement with no effect");
114             } else if let Some(reduced) = reduce_expression(cx, expr) {
115                 let mut snippet = String::new();
116                 for e in reduced {
117                     if in_macro(e.span) {
118                         return;
119                     }
120                     if let Some(snip) = snippet_opt(cx, e.span) {
121                         snippet.push_str(&snip);
122                         snippet.push(';');
123                     } else {
124                         return;
125                     }
126                 }
127                 span_lint_and_sugg(
128                     cx,
129                     UNNECESSARY_OPERATION,
130                     stmt.span,
131                     "statement can be reduced",
132                     "replace it with",
133                     snippet,
134                     Applicability::MachineApplicable,
135                 );
136             }
137         }
138     }
139 }
140
141 fn reduce_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<Vec<&'a Expr>> {
142     if in_macro(expr.span) {
143         return None;
144     }
145     match expr.node {
146         ExprKind::Index(ref a, ref b) => Some(vec![&**a, &**b]),
147         ExprKind::Binary(ref binop, ref a, ref b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
148             Some(vec![&**a, &**b])
149         },
150         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => Some(v.iter().collect()),
151         ExprKind::Repeat(ref inner, _)
152         | ExprKind::Cast(ref inner, _)
153         | ExprKind::Type(ref inner, _)
154         | ExprKind::Unary(_, ref inner)
155         | ExprKind::Field(ref inner, _)
156         | ExprKind::AddrOf(_, ref inner)
157         | ExprKind::Box(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
158         ExprKind::Struct(_, ref fields, ref base) => {
159             if has_drop(cx, cx.tables.expr_ty(expr)) {
160                 None
161             } else {
162                 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
163             }
164         },
165         ExprKind::Call(ref callee, ref args) => {
166             if let ExprKind::Path(ref qpath) = callee.node {
167                 let def = cx.tables.qpath_def(qpath, callee.hir_id);
168                 match def {
169                     Def::Struct(..) | Def::Variant(..) | Def::StructCtor(..) | Def::VariantCtor(..)
170                         if !has_drop(cx, cx.tables.expr_ty(expr)) =>
171                     {
172                         Some(args.iter().collect())
173                     },
174                     _ => None,
175                 }
176             } else {
177                 None
178             }
179         },
180         ExprKind::Block(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 }