]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/no_effect.rs
Rollup merge of #87528 - :stack_overflow_obsd, r=joshtriplett
[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::source::snippet_opt;
3 use clippy_utils::ty::has_drop;
4 use rustc_errors::Applicability;
5 use rustc_hir::def::{DefKind, Res};
6 use rustc_hir::{is_range_literal, BinOpKind, BlockCheckMode, Expr, ExprKind, Stmt, StmtKind, UnsafeSource};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use std::ops::Deref;
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Checks for statements which have no effect.
14     ///
15     /// ### Why is this bad?
16     /// Similar to dead code, these statements are actually
17     /// executed. However, as they have no effect, all they do is make the code less
18     /// readable.
19     ///
20     /// ### Example
21     /// ```rust
22     /// 0;
23     /// ```
24     pub NO_EFFECT,
25     complexity,
26     "statements with no effect"
27 }
28
29 declare_clippy_lint! {
30     /// ### What it does
31     /// Checks for expression statements that can be reduced to a
32     /// sub-expression.
33     ///
34     /// ### Why is this bad?
35     /// Expressions by themselves often have no side-effects.
36     /// Having such expressions reduces readability.
37     ///
38     /// ### Example
39     /// ```rust,ignore
40     /// compute_array()[0];
41     /// ```
42     pub UNNECESSARY_OPERATION,
43     complexity,
44     "outer expressions with no effect"
45 }
46
47 fn has_no_effect(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
48     if expr.span.from_expansion() {
49         return false;
50     }
51     match expr.kind {
52         ExprKind::Lit(..) | ExprKind::Closure(..) => true,
53         ExprKind::Path(..) => !has_drop(cx, cx.typeck_results().expr_ty(expr)),
54         ExprKind::Index(a, b) | ExprKind::Binary(_, a, b) => has_no_effect(cx, a) && has_no_effect(cx, b),
55         ExprKind::Array(v) | ExprKind::Tup(v) => v.iter().all(|val| has_no_effect(cx, val)),
56         ExprKind::Repeat(inner, _)
57         | ExprKind::Cast(inner, _)
58         | ExprKind::Type(inner, _)
59         | ExprKind::Unary(_, inner)
60         | ExprKind::Field(inner, _)
61         | ExprKind::AddrOf(_, _, inner)
62         | ExprKind::Box(inner) => has_no_effect(cx, inner),
63         ExprKind::Struct(_, fields, ref base) => {
64             !has_drop(cx, cx.typeck_results().expr_ty(expr))
65                 && fields.iter().all(|field| has_no_effect(cx, field.expr))
66                 && base.as_ref().map_or(true, |base| has_no_effect(cx, base))
67         },
68         ExprKind::Call(callee, args) => {
69             if let ExprKind::Path(ref qpath) = callee.kind {
70                 let res = cx.qpath_res(qpath, callee.hir_id);
71                 let def_matched = matches!(
72                     res,
73                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
74                 );
75                 if def_matched || is_range_literal(expr) {
76                     !has_drop(cx, cx.typeck_results().expr_ty(expr)) && args.iter().all(|arg| has_no_effect(cx, arg))
77                 } else {
78                     false
79                 }
80             } else {
81                 false
82             }
83         },
84         ExprKind::Block(block, _) => {
85             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| has_no_effect(cx, expr))
86         },
87         _ => false,
88     }
89 }
90
91 declare_lint_pass!(NoEffect => [NO_EFFECT, UNNECESSARY_OPERATION]);
92
93 impl<'tcx> LateLintPass<'tcx> for NoEffect {
94     fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
95         if let StmtKind::Semi(expr) = stmt.kind {
96             if has_no_effect(cx, expr) {
97                 span_lint_hir(cx, NO_EFFECT, expr.hir_id, stmt.span, "statement with no effect");
98             } else if let Some(reduced) = reduce_expression(cx, expr) {
99                 for e in &reduced {
100                     if e.span.from_expansion() {
101                         return;
102                     }
103                 }
104                 if let ExprKind::Index(..) = &expr.kind {
105                     let snippet;
106                     if_chain! {
107                         if let Some(arr) = snippet_opt(cx, reduced[0].span);
108                         if let Some(func) = snippet_opt(cx, reduced[1].span);
109                         then {
110                             snippet = format!("assert!({}.len() > {});", &arr, &func);
111                         } else {
112                             return;
113                         }
114                     }
115                     span_lint_hir_and_then(
116                         cx,
117                         UNNECESSARY_OPERATION,
118                         expr.hir_id,
119                         stmt.span,
120                         "unnecessary operation",
121                         |diag| {
122                             diag.span_suggestion(
123                                 stmt.span,
124                                 "statement can be written as",
125                                 snippet,
126                                 Applicability::MaybeIncorrect,
127                             );
128                         },
129                     );
130                 } else {
131                     let mut snippet = String::new();
132                     for e in reduced {
133                         if let Some(snip) = snippet_opt(cx, e.span) {
134                             snippet.push_str(&snip);
135                             snippet.push(';');
136                         } else {
137                             return;
138                         }
139                     }
140                     span_lint_hir_and_then(
141                         cx,
142                         UNNECESSARY_OPERATION,
143                         expr.hir_id,
144                         stmt.span,
145                         "unnecessary operation",
146                         |diag| {
147                             diag.span_suggestion(
148                                 stmt.span,
149                                 "statement can be reduced to",
150                                 snippet,
151                                 Applicability::MachineApplicable,
152                             );
153                         },
154                     );
155                 }
156             }
157         }
158     }
159 }
160
161 fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
162     if expr.span.from_expansion() {
163         return None;
164     }
165     match expr.kind {
166         ExprKind::Index(a, b) => Some(vec![a, b]),
167         ExprKind::Binary(ref binop, a, b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
168             Some(vec![a, b])
169         },
170         ExprKind::Array(v) | ExprKind::Tup(v) => Some(v.iter().collect()),
171         ExprKind::Repeat(inner, _)
172         | ExprKind::Cast(inner, _)
173         | ExprKind::Type(inner, _)
174         | ExprKind::Unary(_, inner)
175         | ExprKind::Field(inner, _)
176         | ExprKind::AddrOf(_, _, inner)
177         | ExprKind::Box(inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
178         ExprKind::Struct(_, fields, ref base) => {
179             if has_drop(cx, cx.typeck_results().expr_ty(expr)) {
180                 None
181             } else {
182                 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
183             }
184         },
185         ExprKind::Call(callee, args) => {
186             if let ExprKind::Path(ref qpath) = callee.kind {
187                 let res = cx.qpath_res(qpath, callee.hir_id);
188                 match res {
189                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
190                         if !has_drop(cx, cx.typeck_results().expr_ty(expr)) =>
191                     {
192                         Some(args.iter().collect())
193                     },
194                     _ => None,
195                 }
196             } else {
197                 None
198             }
199         },
200         ExprKind::Block(block, _) => {
201             if block.stmts.is_empty() {
202                 block.expr.as_ref().and_then(|e| {
203                     match block.rules {
204                         BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
205                         BlockCheckMode::DefaultBlock => Some(vec![&**e]),
206                         // in case of compiler-inserted signaling blocks
207                         BlockCheckMode::UnsafeBlock(_) => reduce_expression(cx, e),
208                     }
209                 })
210             } else {
211                 None
212             }
213         },
214         _ => None,
215     }
216 }