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};
13 declare_clippy_lint! {
15 /// Checks for statements which have no effect.
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
26 #[clippy::version = "pre 1.29.0"]
29 "statements with no effect"
32 declare_clippy_lint! {
34 /// Checks for binding to underscore prefixed variable without side-effects.
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.
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.
47 /// let _i_serve_no_purpose = 1;
49 #[clippy::version = "1.58.0"]
50 pub NO_EFFECT_UNDERSCORE_BINDING,
52 "binding to `_` prefixed variable with no side-effect"
55 declare_clippy_lint! {
57 /// Checks for expression statements that can be reduced to a
60 /// ### Why is this bad?
61 /// Expressions by themselves often have no side-effects.
62 /// Having such expressions reduces readability.
66 /// compute_array()[0];
68 #[clippy::version = "pre 1.29.0"]
69 pub UNNECESSARY_OPERATION,
71 "outer expressions with no effect"
74 declare_lint_pass!(NoEffect => [NO_EFFECT, UNNECESSARY_OPERATION, NO_EFFECT_UNDERSCORE_BINDING]);
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) {
81 check_unnecessary_operation(cx, stmt);
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");
91 } else if let StmtKind::Local(local) = stmt.kind {
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('_');
102 NO_EFFECT_UNDERSCORE_BINDING,
105 "binding to `_` prefixed variable with no side-effect"
114 fn has_no_effect(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
115 if expr.span.from_expansion() {
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))
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`
141 let def_matched = matches!(
142 cx.qpath_res(qpath, callee.hir_id),
143 Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
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))
158 fn check_unnecessary_operation(cx: &LateContext<'_>, stmt: &Stmt<'_>) {
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());
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))
168 format!("assert!({}.len() > {});", &arr, &func)
172 span_lint_hir_and_then(
174 UNNECESSARY_OPERATION,
177 "unnecessary operation",
179 diag.span_suggestion(
181 "statement can be written as",
183 Applicability::MaybeIncorrect,
188 let mut snippet = String::new();
190 if let Some(snip) = snippet_opt(cx, e.span) {
191 snippet.push_str(&snip);
197 span_lint_hir_and_then(
199 UNNECESSARY_OPERATION,
202 "unnecessary operation",
204 diag.span_suggestion(
206 "statement can be reduced to",
208 Applicability::MachineApplicable,
217 fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
218 if expr.span.from_expansion() {
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 => {
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)) {
238 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
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`
247 let res = cx.qpath_res(qpath, callee.hir_id);
249 Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
250 if !has_drop(cx, cx.typeck_results().expr_ty(expr)) =>
252 Some(args.iter().collect())
260 ExprKind::Block(block, _) => {
261 if block.stmts.is_empty() {
262 block.expr.as_ref().and_then(|e| {
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),