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