]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/no_effect.rs
Merge commit 'a5d597637dcb78dc73f93561ce474f23d4177c35' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / no_effect.rs
1 use clippy_utils::diagnostics::{span_lint_hir, span_lint_hir_and_then};
2 use clippy_utils::is_lint_allowed;
3 use clippy_utils::source::snippet_opt;
4 use clippy_utils::ty::has_drop;
5 use rustc_errors::Applicability;
6 use rustc_hir::def::{DefKind, Res};
7 use rustc_hir::{is_range_literal, BinOpKind, BlockCheckMode, Expr, ExprKind, PatKind, Stmt, StmtKind, UnsafeSource};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use std::ops::Deref;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Checks for statements which have no effect.
15     ///
16     /// ### Why is this bad?
17     /// Unlike dead code, these statements are actually
18     /// executed. However, as they have no effect, all they do is make the code less
19     /// readable.
20     ///
21     /// ### Example
22     /// ```rust
23     /// 0;
24     /// ```
25     #[clippy::version = "pre 1.29.0"]
26     pub NO_EFFECT,
27     complexity,
28     "statements with no effect"
29 }
30
31 declare_clippy_lint! {
32     /// ### What it does
33     /// Checks for binding to underscore prefixed variable without side-effects.
34     ///
35     /// ### Why is this bad?
36     /// Unlike dead code, these bindings are actually
37     /// executed. However, as they have no effect and shouldn't be used further on, all they
38     /// do is make the code less readable.
39     ///
40     /// ### Known problems
41     /// Further usage of this variable is not checked, which can lead to false positives if it is
42     /// used later in the code.
43     ///
44     /// ### Example
45     /// ```rust,ignore
46     /// let _i_serve_no_purpose = 1;
47     /// ```
48     #[clippy::version = "1.58.0"]
49     pub NO_EFFECT_UNDERSCORE_BINDING,
50     pedantic,
51     "binding to `_` prefixed variable with no side-effect"
52 }
53
54 declare_clippy_lint! {
55     /// ### What it does
56     /// Checks for expression statements that can be reduced to a
57     /// sub-expression.
58     ///
59     /// ### Why is this bad?
60     /// Expressions by themselves often have no side-effects.
61     /// Having such expressions reduces readability.
62     ///
63     /// ### Example
64     /// ```rust,ignore
65     /// compute_array()[0];
66     /// ```
67     #[clippy::version = "pre 1.29.0"]
68     pub UNNECESSARY_OPERATION,
69     complexity,
70     "outer expressions with no effect"
71 }
72
73 declare_lint_pass!(NoEffect => [NO_EFFECT, UNNECESSARY_OPERATION, NO_EFFECT_UNDERSCORE_BINDING]);
74
75 impl<'tcx> LateLintPass<'tcx> for NoEffect {
76     fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
77         if check_no_effect(cx, stmt) {
78             return;
79         }
80         check_unnecessary_operation(cx, stmt);
81     }
82 }
83
84 fn check_no_effect(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) -> bool {
85     if let StmtKind::Semi(expr) = stmt.kind {
86         if has_no_effect(cx, expr) {
87             span_lint_hir(cx, NO_EFFECT, expr.hir_id, stmt.span, "statement with no effect");
88             return true;
89         }
90     } else if let StmtKind::Local(local) = stmt.kind {
91         if_chain! {
92             if !is_lint_allowed(cx, NO_EFFECT_UNDERSCORE_BINDING, local.hir_id);
93             if let Some(init) = local.init;
94             if !local.pat.span.from_expansion();
95             if has_no_effect(cx, init);
96             if let PatKind::Binding(_, _, ident, _) = local.pat.kind;
97             if ident.name.to_ident_string().starts_with('_');
98             then {
99                 span_lint_hir(
100                     cx,
101                     NO_EFFECT_UNDERSCORE_BINDING,
102                     init.hir_id,
103                     stmt.span,
104                     "binding to `_` prefixed variable with no side-effect"
105                 );
106                 return true;
107             }
108         }
109     }
110     false
111 }
112
113 fn has_no_effect(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
114     if expr.span.from_expansion() {
115         return false;
116     }
117     match expr.kind {
118         ExprKind::Lit(..) | ExprKind::Closure(..) => true,
119         ExprKind::Path(..) => !has_drop(cx, cx.typeck_results().expr_ty(expr)),
120         ExprKind::Index(a, b) | ExprKind::Binary(_, a, b) => has_no_effect(cx, a) && has_no_effect(cx, b),
121         ExprKind::Array(v) | ExprKind::Tup(v) => v.iter().all(|val| has_no_effect(cx, val)),
122         ExprKind::Repeat(inner, _)
123         | ExprKind::Cast(inner, _)
124         | ExprKind::Type(inner, _)
125         | ExprKind::Unary(_, inner)
126         | ExprKind::Field(inner, _)
127         | ExprKind::AddrOf(_, _, inner)
128         | ExprKind::Box(inner) => has_no_effect(cx, inner),
129         ExprKind::Struct(_, fields, ref base) => {
130             !has_drop(cx, cx.typeck_results().expr_ty(expr))
131                 && fields.iter().all(|field| has_no_effect(cx, field.expr))
132                 && base.as_ref().map_or(true, |base| has_no_effect(cx, base))
133         },
134         ExprKind::Call(callee, args) => {
135             if let ExprKind::Path(ref qpath) = callee.kind {
136                 if cx.typeck_results().type_dependent_def(expr.hir_id).is_some() {
137                     // type-dependent function call like `impl FnOnce for X`
138                     return false;
139                 }
140                 let def_matched = matches!(
141                     cx.qpath_res(qpath, callee.hir_id),
142                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
143                 );
144                 if def_matched || is_range_literal(expr) {
145                     !has_drop(cx, cx.typeck_results().expr_ty(expr)) && args.iter().all(|arg| has_no_effect(cx, arg))
146                 } else {
147                     false
148                 }
149             } else {
150                 false
151             }
152         },
153         ExprKind::Block(block, _) => {
154             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| has_no_effect(cx, expr))
155         },
156         _ => false,
157     }
158 }
159
160 fn check_unnecessary_operation(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
161     if_chain! {
162         if let StmtKind::Semi(expr) = stmt.kind;
163         if let Some(reduced) = reduce_expression(cx, expr);
164         if !&reduced.iter().any(|e| e.span.from_expansion());
165         then {
166             if let ExprKind::Index(..) = &expr.kind {
167                 let snippet = if let (Some(arr), Some(func)) =
168                     (snippet_opt(cx, reduced[0].span), snippet_opt(cx, reduced[1].span))
169                 {
170                     format!("assert!({}.len() > {});", &arr, &func)
171                 } else {
172                     return;
173                 };
174                 span_lint_hir_and_then(
175                     cx,
176                     UNNECESSARY_OPERATION,
177                     expr.hir_id,
178                     stmt.span,
179                     "unnecessary operation",
180                     |diag| {
181                         diag.span_suggestion(
182                             stmt.span,
183                             "statement can be written as",
184                             snippet,
185                             Applicability::MaybeIncorrect,
186                         );
187                     },
188                 );
189             } else {
190                 let mut snippet = String::new();
191                 for e in reduced {
192                     if let Some(snip) = snippet_opt(cx, e.span) {
193                         snippet.push_str(&snip);
194                         snippet.push(';');
195                     } else {
196                         return;
197                     }
198                 }
199                 span_lint_hir_and_then(
200                     cx,
201                     UNNECESSARY_OPERATION,
202                     expr.hir_id,
203                     stmt.span,
204                     "unnecessary operation",
205                     |diag| {
206                         diag.span_suggestion(
207                             stmt.span,
208                             "statement can be reduced to",
209                             snippet,
210                             Applicability::MachineApplicable,
211                         );
212                     },
213                 );
214             }
215         }
216     }
217 }
218
219 fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
220     if expr.span.from_expansion() {
221         return None;
222     }
223     match expr.kind {
224         ExprKind::Index(a, b) => Some(vec![a, b]),
225         ExprKind::Binary(ref binop, a, b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
226             Some(vec![a, b])
227         },
228         ExprKind::Array(v) | ExprKind::Tup(v) => Some(v.iter().collect()),
229         ExprKind::Repeat(inner, _)
230         | ExprKind::Cast(inner, _)
231         | ExprKind::Type(inner, _)
232         | ExprKind::Unary(_, inner)
233         | ExprKind::Field(inner, _)
234         | ExprKind::AddrOf(_, _, inner)
235         | ExprKind::Box(inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
236         ExprKind::Struct(_, fields, ref base) => {
237             if has_drop(cx, cx.typeck_results().expr_ty(expr)) {
238                 None
239             } else {
240                 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
241             }
242         },
243         ExprKind::Call(callee, args) => {
244             if let ExprKind::Path(ref qpath) = callee.kind {
245                 if cx.typeck_results().type_dependent_def(expr.hir_id).is_some() {
246                     // type-dependent function call like `impl FnOnce for X`
247                     return None;
248                 }
249                 let res = cx.qpath_res(qpath, callee.hir_id);
250                 match res {
251                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
252                         if !has_drop(cx, cx.typeck_results().expr_ty(expr)) =>
253                     {
254                         Some(args.iter().collect())
255                     },
256                     _ => None,
257                 }
258             } else {
259                 None
260             }
261         },
262         ExprKind::Block(block, _) => {
263             if block.stmts.is_empty() {
264                 block.expr.as_ref().and_then(|e| {
265                     match block.rules {
266                         BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
267                         BlockCheckMode::DefaultBlock => Some(vec![&**e]),
268                         // in case of compiler-inserted signaling blocks
269                         BlockCheckMode::UnsafeBlock(_) => reduce_expression(cx, e),
270                     }
271                 })
272             } else {
273                 None
274             }
275         },
276         _ => None,
277     }
278 }