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, LintContext};
10 use rustc_middle::lint::in_external_macro;
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
14 declare_clippy_lint! {
16 /// Checks for statements which have no effect.
18 /// ### Why is this bad?
19 /// Unlike dead code, these statements are actually
20 /// executed. However, as they have no effect, all they do is make the code less
27 #[clippy::version = "pre 1.29.0"]
30 "statements with no effect"
33 declare_clippy_lint! {
35 /// Checks for binding to underscore prefixed variable without side-effects.
37 /// ### Why is this bad?
38 /// Unlike dead code, these bindings are actually
39 /// executed. However, as they have no effect and shouldn't be used further on, all they
40 /// do is make the code less readable.
42 /// ### Known problems
43 /// Further usage of this variable is not checked, which can lead to false positives if it is
44 /// used later in the code.
48 /// let _i_serve_no_purpose = 1;
50 #[clippy::version = "1.58.0"]
51 pub NO_EFFECT_UNDERSCORE_BINDING,
53 "binding to `_` prefixed variable with no side-effect"
56 declare_clippy_lint! {
58 /// Checks for expression statements that can be reduced to a
61 /// ### Why is this bad?
62 /// Expressions by themselves often have no side-effects.
63 /// Having such expressions reduces readability.
67 /// compute_array()[0];
69 #[clippy::version = "pre 1.29.0"]
70 pub UNNECESSARY_OPERATION,
72 "outer expressions with no effect"
75 declare_lint_pass!(NoEffect => [NO_EFFECT, UNNECESSARY_OPERATION, NO_EFFECT_UNDERSCORE_BINDING]);
77 impl<'tcx> LateLintPass<'tcx> for NoEffect {
78 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
79 if check_no_effect(cx, stmt) {
82 check_unnecessary_operation(cx, stmt);
86 fn check_no_effect(cx: &LateContext<'_>, stmt: &Stmt<'_>) -> bool {
87 if let StmtKind::Semi(expr) = stmt.kind {
88 if has_no_effect(cx, expr) {
89 span_lint_hir(cx, NO_EFFECT, expr.hir_id, stmt.span, "statement with no effect");
92 } else if let StmtKind::Local(local) = stmt.kind {
94 if !is_lint_allowed(cx, NO_EFFECT_UNDERSCORE_BINDING, local.hir_id);
95 if let Some(init) = local.init;
96 if local.els.is_none();
97 if !local.pat.span.from_expansion();
98 if has_no_effect(cx, init);
99 if let PatKind::Binding(_, _, ident, _) = local.pat.kind;
100 if ident.name.to_ident_string().starts_with('_');
104 NO_EFFECT_UNDERSCORE_BINDING,
107 "binding to `_` prefixed variable with no side-effect"
116 fn has_no_effect(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
117 if expr.span.from_expansion() {
120 match peel_blocks(expr).kind {
121 ExprKind::Lit(..) | ExprKind::Closure { .. } => true,
122 ExprKind::Path(..) => !has_drop(cx, cx.typeck_results().expr_ty(expr)),
123 ExprKind::Index(a, b) | ExprKind::Binary(_, a, b) => has_no_effect(cx, a) && has_no_effect(cx, b),
124 ExprKind::Array(v) | ExprKind::Tup(v) => v.iter().all(|val| has_no_effect(cx, val)),
125 ExprKind::Repeat(inner, _)
126 | ExprKind::Cast(inner, _)
127 | ExprKind::Type(inner, _)
128 | ExprKind::Unary(_, inner)
129 | ExprKind::Field(inner, _)
130 | ExprKind::AddrOf(_, _, inner)
131 | ExprKind::Box(inner) => has_no_effect(cx, inner),
132 ExprKind::Struct(_, fields, ref base) => {
133 !has_drop(cx, cx.typeck_results().expr_ty(expr))
134 && fields.iter().all(|field| has_no_effect(cx, field.expr))
135 && base.as_ref().map_or(true, |base| has_no_effect(cx, base))
137 ExprKind::Call(callee, args) => {
138 if let ExprKind::Path(ref qpath) = callee.kind {
139 if cx.typeck_results().type_dependent_def(expr.hir_id).is_some() {
140 // type-dependent function call like `impl FnOnce for X`
143 let def_matched = matches!(
144 cx.qpath_res(qpath, callee.hir_id),
145 Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
147 if def_matched || is_range_literal(expr) {
148 !has_drop(cx, cx.typeck_results().expr_ty(expr)) && args.iter().all(|arg| has_no_effect(cx, arg))
160 fn check_unnecessary_operation(cx: &LateContext<'_>, stmt: &Stmt<'_>) {
162 if let StmtKind::Semi(expr) = stmt.kind;
163 let ctxt = stmt.span.ctxt();
164 if expr.span.ctxt() == ctxt;
165 if let Some(reduced) = reduce_expression(cx, expr);
166 if !in_external_macro(cx.sess(), stmt.span);
167 if reduced.iter().all(|e| e.span.ctxt() == ctxt);
169 if let ExprKind::Index(..) = &expr.kind {
170 let snippet = if let (Some(arr), Some(func)) =
171 (snippet_opt(cx, reduced[0].span), snippet_opt(cx, reduced[1].span))
173 format!("assert!({}.len() > {});", &arr, &func)
177 span_lint_hir_and_then(
179 UNNECESSARY_OPERATION,
182 "unnecessary operation",
184 diag.span_suggestion(
186 "statement can be written as",
188 Applicability::MaybeIncorrect,
193 let mut snippet = String::new();
195 if let Some(snip) = snippet_opt(cx, e.span) {
196 snippet.push_str(&snip);
202 span_lint_hir_and_then(
204 UNNECESSARY_OPERATION,
207 "unnecessary operation",
209 diag.span_suggestion(
211 "statement can be reduced to",
213 Applicability::MachineApplicable,
222 fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
223 if expr.span.from_expansion() {
227 ExprKind::Index(a, b) => Some(vec![a, b]),
228 ExprKind::Binary(ref binop, a, b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
231 ExprKind::Array(v) | ExprKind::Tup(v) => Some(v.iter().collect()),
232 ExprKind::Repeat(inner, _)
233 | ExprKind::Cast(inner, _)
234 | ExprKind::Type(inner, _)
235 | ExprKind::Unary(_, inner)
236 | ExprKind::Field(inner, _)
237 | ExprKind::AddrOf(_, _, inner)
238 | ExprKind::Box(inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
239 ExprKind::Struct(_, fields, ref base) => {
240 if has_drop(cx, cx.typeck_results().expr_ty(expr)) {
243 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
246 ExprKind::Call(callee, args) => {
247 if let ExprKind::Path(ref qpath) = callee.kind {
248 if cx.typeck_results().type_dependent_def(expr.hir_id).is_some() {
249 // type-dependent function call like `impl FnOnce for X`
252 let res = cx.qpath_res(qpath, callee.hir_id);
254 Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
255 if !has_drop(cx, cx.typeck_results().expr_ty(expr)) =>
257 Some(args.iter().collect())
265 ExprKind::Block(block, _) => {
266 if block.stmts.is_empty() {
267 block.expr.as_ref().and_then(|e| {
269 BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
270 BlockCheckMode::DefaultBlock => Some(vec![&**e]),
271 // in case of compiler-inserted signaling blocks
272 BlockCheckMode::UnsafeBlock(_) => reduce_expression(cx, e),