]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/no_effect.rs
Auto merge of #5680 - ebroto:3792_let_return, r=Manishearth
[rust.git] / clippy_lints / src / no_effect.rs
1 use crate::utils::{has_drop, qpath_res, snippet_opt, span_lint, span_lint_and_sugg};
2 use rustc_errors::Applicability;
3 use rustc_hir::def::{DefKind, Res};
4 use rustc_hir::{BinOpKind, BlockCheckMode, Expr, ExprKind, Stmt, StmtKind, UnsafeSource};
5 use rustc_lint::{LateContext, LateLintPass};
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
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,ignore
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 expr.span.from_expansion() {
47         return false;
48     }
49     match expr.kind {
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                 && base.as_ref().map_or(true, |base| has_no_effect(cx, base))
67         },
68         ExprKind::Call(ref callee, ref args) => {
69             if let ExprKind::Path(ref qpath) = callee.kind {
70                 let res = qpath_res(cx, qpath, callee.hir_id);
71                 match res {
72                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..) => {
73                         !has_drop(cx, cx.tables.expr_ty(expr)) && args.iter().all(|arg| has_no_effect(cx, arg))
74                     },
75                     _ => false,
76                 }
77             } else {
78                 false
79             }
80         },
81         ExprKind::Block(ref block, _) => {
82             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| has_no_effect(cx, expr))
83         },
84         _ => false,
85     }
86 }
87
88 declare_lint_pass!(NoEffect => [NO_EFFECT, UNNECESSARY_OPERATION]);
89
90 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoEffect {
91     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt<'_>) {
92         if let StmtKind::Semi(ref expr) = stmt.kind {
93             if has_no_effect(cx, expr) {
94                 span_lint(cx, NO_EFFECT, stmt.span, "statement with no effect");
95             } else if let Some(reduced) = reduce_expression(cx, expr) {
96                 let mut snippet = String::new();
97                 for e in reduced {
98                     if e.span.from_expansion() {
99                         return;
100                     }
101                     if let Some(snip) = snippet_opt(cx, e.span) {
102                         snippet.push_str(&snip);
103                         snippet.push(';');
104                     } else {
105                         return;
106                     }
107                 }
108                 span_lint_and_sugg(
109                     cx,
110                     UNNECESSARY_OPERATION,
111                     stmt.span,
112                     "statement can be reduced",
113                     "replace it with",
114                     snippet,
115                     Applicability::MachineApplicable,
116                 );
117             }
118         }
119     }
120 }
121
122 fn reduce_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
123     if expr.span.from_expansion() {
124         return None;
125     }
126     match expr.kind {
127         ExprKind::Index(ref a, ref b) => Some(vec![&**a, &**b]),
128         ExprKind::Binary(ref binop, ref a, ref b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
129             Some(vec![&**a, &**b])
130         },
131         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => Some(v.iter().collect()),
132         ExprKind::Repeat(ref inner, _)
133         | ExprKind::Cast(ref inner, _)
134         | ExprKind::Type(ref inner, _)
135         | ExprKind::Unary(_, ref inner)
136         | ExprKind::Field(ref inner, _)
137         | ExprKind::AddrOf(_, _, ref inner)
138         | ExprKind::Box(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
139         ExprKind::Struct(_, ref fields, ref base) => {
140             if has_drop(cx, cx.tables.expr_ty(expr)) {
141                 None
142             } else {
143                 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
144             }
145         },
146         ExprKind::Call(ref callee, ref args) => {
147             if let ExprKind::Path(ref qpath) = callee.kind {
148                 let res = qpath_res(cx, qpath, callee.hir_id);
149                 match res {
150                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
151                         if !has_drop(cx, cx.tables.expr_ty(expr)) =>
152                     {
153                         Some(args.iter().collect())
154                     },
155                     _ => None,
156                 }
157             } else {
158                 None
159             }
160         },
161         ExprKind::Block(ref block, _) => {
162             if block.stmts.is_empty() {
163                 block.expr.as_ref().and_then(|e| {
164                     match block.rules {
165                         BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
166                         BlockCheckMode::DefaultBlock => Some(vec![&**e]),
167                         // in case of compiler-inserted signaling blocks
168                         _ => reduce_expression(cx, e),
169                     }
170                 })
171             } else {
172                 None
173             }
174         },
175         _ => None,
176     }
177 }