]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/no_effect.rs
Rustup to rustc 1.36.0-nightly (13fde05b1 2019-05-03)
[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::{DefKind, Res};
3 use rustc::hir::{BinOpKind, BlockCheckMode, Expr, ExprKind, Stmt, StmtKind, UnsafeSource};
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_lint_pass, declare_tool_lint};
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 res = cx.tables.qpath_res(qpath, callee.hir_id);
74                 match res {
75                     Res::Def(DefKind::Struct, ..) | Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(..), _) => {
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 declare_lint_pass!(NoEffect => [NO_EFFECT, UNNECESSARY_OPERATION]);
97
98 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoEffect {
99     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
100         if let StmtKind::Semi(ref expr) = stmt.node {
101             if has_no_effect(cx, expr) {
102                 span_lint(cx, NO_EFFECT, stmt.span, "statement with no effect");
103             } else if let Some(reduced) = reduce_expression(cx, expr) {
104                 let mut snippet = String::new();
105                 for e in reduced {
106                     if in_macro(e.span) {
107                         return;
108                     }
109                     if let Some(snip) = snippet_opt(cx, e.span) {
110                         snippet.push_str(&snip);
111                         snippet.push(';');
112                     } else {
113                         return;
114                     }
115                 }
116                 span_lint_and_sugg(
117                     cx,
118                     UNNECESSARY_OPERATION,
119                     stmt.span,
120                     "statement can be reduced",
121                     "replace it with",
122                     snippet,
123                     Applicability::MachineApplicable,
124                 );
125             }
126         }
127     }
128 }
129
130 fn reduce_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<Vec<&'a Expr>> {
131     if in_macro(expr.span) {
132         return None;
133     }
134     match expr.node {
135         ExprKind::Index(ref a, ref b) => Some(vec![&**a, &**b]),
136         ExprKind::Binary(ref binop, ref a, ref b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
137             Some(vec![&**a, &**b])
138         },
139         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => Some(v.iter().collect()),
140         ExprKind::Repeat(ref inner, _)
141         | ExprKind::Cast(ref inner, _)
142         | ExprKind::Type(ref inner, _)
143         | ExprKind::Unary(_, ref inner)
144         | ExprKind::Field(ref inner, _)
145         | ExprKind::AddrOf(_, ref inner)
146         | ExprKind::Box(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
147         ExprKind::Struct(_, ref fields, ref base) => {
148             if has_drop(cx, cx.tables.expr_ty(expr)) {
149                 None
150             } else {
151                 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
152             }
153         },
154         ExprKind::Call(ref callee, ref args) => {
155             if let ExprKind::Path(ref qpath) = callee.node {
156                 let res = cx.tables.qpath_res(qpath, callee.hir_id);
157                 match res {
158                     Res::Def(DefKind::Struct, ..) | Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(..), _)
159                         if !has_drop(cx, cx.tables.expr_ty(expr)) =>
160                     {
161                         Some(args.iter().collect())
162                     },
163                     _ => None,
164                 }
165             } else {
166                 None
167             }
168         },
169         ExprKind::Block(ref block, _) => {
170             if block.stmts.is_empty() {
171                 block.expr.as_ref().and_then(|e| {
172                     match block.rules {
173                         BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
174                         BlockCheckMode::DefaultBlock => Some(vec![&**e]),
175                         // in case of compiler-inserted signaling blocks
176                         _ => reduce_expression(cx, e),
177                     }
178                 })
179             } else {
180                 None
181             }
182         },
183         _ => None,
184     }
185 }