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.els.is_none();
96 if !local.pat.span.from_expansion();
97 if has_no_effect(cx, init);
98 if let PatKind::Binding(_, _, ident, _) = local.pat.kind;
99 if ident.name.to_ident_string().starts_with('_');
103 NO_EFFECT_UNDERSCORE_BINDING,
106 "binding to `_` prefixed variable with no side-effect"
115 fn has_no_effect(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
116 if expr.span.from_expansion() {
119 match peel_blocks(expr).kind {
120 ExprKind::Lit(..) | ExprKind::Closure { .. } => true,
121 ExprKind::Path(..) => !has_drop(cx, cx.typeck_results().expr_ty(expr)),
122 ExprKind::Index(a, b) | ExprKind::Binary(_, a, b) => has_no_effect(cx, a) && has_no_effect(cx, b),
123 ExprKind::Array(v) | ExprKind::Tup(v) => v.iter().all(|val| has_no_effect(cx, val)),
124 ExprKind::Repeat(inner, _)
125 | ExprKind::Cast(inner, _)
126 | ExprKind::Type(inner, _)
127 | ExprKind::Unary(_, inner)
128 | ExprKind::Field(inner, _)
129 | ExprKind::AddrOf(_, _, inner)
130 | ExprKind::Box(inner) => has_no_effect(cx, inner),
131 ExprKind::Struct(_, fields, ref base) => {
132 !has_drop(cx, cx.typeck_results().expr_ty(expr))
133 && fields.iter().all(|field| has_no_effect(cx, field.expr))
134 && base.as_ref().map_or(true, |base| has_no_effect(cx, base))
136 ExprKind::Call(callee, args) => {
137 if let ExprKind::Path(ref qpath) = callee.kind {
138 if cx.typeck_results().type_dependent_def(expr.hir_id).is_some() {
139 // type-dependent function call like `impl FnOnce for X`
142 let def_matched = matches!(
143 cx.qpath_res(qpath, callee.hir_id),
144 Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
146 if def_matched || is_range_literal(expr) {
147 !has_drop(cx, cx.typeck_results().expr_ty(expr)) && args.iter().all(|arg| has_no_effect(cx, arg))
159 fn check_unnecessary_operation(cx: &LateContext<'_>, stmt: &Stmt<'_>) {
161 if let StmtKind::Semi(expr) = stmt.kind;
162 if let Some(reduced) = reduce_expression(cx, expr);
163 if !&reduced.iter().any(|e| e.span.from_expansion());
165 if let ExprKind::Index(..) = &expr.kind {
166 let snippet = if let (Some(arr), Some(func)) =
167 (snippet_opt(cx, reduced[0].span), snippet_opt(cx, reduced[1].span))
169 format!("assert!({}.len() > {});", &arr, &func)
173 span_lint_hir_and_then(
175 UNNECESSARY_OPERATION,
178 "unnecessary operation",
180 diag.span_suggestion(
182 "statement can be written as",
184 Applicability::MaybeIncorrect,
189 let mut snippet = String::new();
191 if let Some(snip) = snippet_opt(cx, e.span) {
192 snippet.push_str(&snip);
198 span_lint_hir_and_then(
200 UNNECESSARY_OPERATION,
203 "unnecessary operation",
205 diag.span_suggestion(
207 "statement can be reduced to",
209 Applicability::MachineApplicable,
218 fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
219 if expr.span.from_expansion() {
223 ExprKind::Index(a, b) => Some(vec![a, b]),
224 ExprKind::Binary(ref binop, a, b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
227 ExprKind::Array(v) | ExprKind::Tup(v) => Some(v.iter().collect()),
228 ExprKind::Repeat(inner, _)
229 | ExprKind::Cast(inner, _)
230 | ExprKind::Type(inner, _)
231 | ExprKind::Unary(_, inner)
232 | ExprKind::Field(inner, _)
233 | ExprKind::AddrOf(_, _, inner)
234 | ExprKind::Box(inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
235 ExprKind::Struct(_, fields, ref base) => {
236 if has_drop(cx, cx.typeck_results().expr_ty(expr)) {
239 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
242 ExprKind::Call(callee, args) => {
243 if let ExprKind::Path(ref qpath) = callee.kind {
244 if cx.typeck_results().type_dependent_def(expr.hir_id).is_some() {
245 // type-dependent function call like `impl FnOnce for X`
248 let res = cx.qpath_res(qpath, callee.hir_id);
250 Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
251 if !has_drop(cx, cx.typeck_results().expr_ty(expr)) =>
253 Some(args.iter().collect())
261 ExprKind::Block(block, _) => {
262 if block.stmts.is_empty() {
263 block.expr.as_ref().and_then(|e| {
265 BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
266 BlockCheckMode::DefaultBlock => Some(vec![&**e]),
267 // in case of compiler-inserted signaling blocks
268 BlockCheckMode::UnsafeBlock(_) => reduce_expression(cx, e),