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};
12 declare_clippy_lint! {
14 /// Checks for statements which have no effect.
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
25 #[clippy::version = "pre 1.29.0"]
28 "statements with no effect"
31 declare_clippy_lint! {
33 /// Checks for binding to underscore prefixed variable without side-effects.
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.
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.
46 /// let _i_serve_no_purpose = 1;
48 #[clippy::version = "1.58.0"]
49 pub NO_EFFECT_UNDERSCORE_BINDING,
51 "binding to `_` prefixed variable with no side-effect"
54 declare_clippy_lint! {
56 /// Checks for expression statements that can be reduced to a
59 /// ### Why is this bad?
60 /// Expressions by themselves often have no side-effects.
61 /// Having such expressions reduces readability.
65 /// compute_array()[0];
67 #[clippy::version = "pre 1.29.0"]
68 pub UNNECESSARY_OPERATION,
70 "outer expressions with no effect"
73 declare_lint_pass!(NoEffect => [NO_EFFECT, UNNECESSARY_OPERATION, NO_EFFECT_UNDERSCORE_BINDING]);
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) {
80 check_unnecessary_operation(cx, stmt);
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");
90 } else if let StmtKind::Local(local) = stmt.kind {
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('_');
101 NO_EFFECT_UNDERSCORE_BINDING,
104 "binding to `_` prefixed variable with no side-effect"
113 fn has_no_effect(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
114 if expr.span.from_expansion() {
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))
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`
140 let def_matched = matches!(
141 cx.qpath_res(qpath, callee.hir_id),
142 Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
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))
153 ExprKind::Block(block, _) => {
154 block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| has_no_effect(cx, expr))
160 fn check_unnecessary_operation(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
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());
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))
170 format!("assert!({}.len() > {});", &arr, &func)
174 span_lint_hir_and_then(
176 UNNECESSARY_OPERATION,
179 "unnecessary operation",
181 diag.span_suggestion(
183 "statement can be written as",
185 Applicability::MaybeIncorrect,
190 let mut snippet = String::new();
192 if let Some(snip) = snippet_opt(cx, e.span) {
193 snippet.push_str(&snip);
199 span_lint_hir_and_then(
201 UNNECESSARY_OPERATION,
204 "unnecessary operation",
206 diag.span_suggestion(
208 "statement can be reduced to",
210 Applicability::MachineApplicable,
219 fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
220 if expr.span.from_expansion() {
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 => {
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)) {
240 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
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`
249 let res = cx.qpath_res(qpath, callee.hir_id);
251 Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
252 if !has_drop(cx, cx.typeck_results().expr_ty(expr)) =>
254 Some(args.iter().collect())
262 ExprKind::Block(block, _) => {
263 if block.stmts.is_empty() {
264 block.expr.as_ref().and_then(|e| {
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),