]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/no_effect.rs
Use `CountIsStart` in clippy
[rust.git] / clippy_lints / src / no_effect.rs
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};
11 use std::ops::Deref;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for statements which have no effect.
16     ///
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
20     /// readable.
21     ///
22     /// ### Example
23     /// ```rust
24     /// 0;
25     /// ```
26     #[clippy::version = "pre 1.29.0"]
27     pub NO_EFFECT,
28     complexity,
29     "statements with no effect"
30 }
31
32 declare_clippy_lint! {
33     /// ### What it does
34     /// Checks for binding to underscore prefixed variable without side-effects.
35     ///
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.
40     ///
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.
44     ///
45     /// ### Example
46     /// ```rust,ignore
47     /// let _i_serve_no_purpose = 1;
48     /// ```
49     #[clippy::version = "1.58.0"]
50     pub NO_EFFECT_UNDERSCORE_BINDING,
51     pedantic,
52     "binding to `_` prefixed variable with no side-effect"
53 }
54
55 declare_clippy_lint! {
56     /// ### What it does
57     /// Checks for expression statements that can be reduced to a
58     /// sub-expression.
59     ///
60     /// ### Why is this bad?
61     /// Expressions by themselves often have no side-effects.
62     /// Having such expressions reduces readability.
63     ///
64     /// ### Example
65     /// ```rust,ignore
66     /// compute_array()[0];
67     /// ```
68     #[clippy::version = "pre 1.29.0"]
69     pub UNNECESSARY_OPERATION,
70     complexity,
71     "outer expressions with no effect"
72 }
73
74 declare_lint_pass!(NoEffect => [NO_EFFECT, UNNECESSARY_OPERATION, NO_EFFECT_UNDERSCORE_BINDING]);
75
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) {
79             return;
80         }
81         check_unnecessary_operation(cx, stmt);
82     }
83 }
84
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");
89             return true;
90         }
91     } else if let StmtKind::Local(local) = stmt.kind {
92         if_chain! {
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('_');
100             then {
101                 span_lint_hir(
102                     cx,
103                     NO_EFFECT_UNDERSCORE_BINDING,
104                     init.hir_id,
105                     stmt.span,
106                     "binding to `_` prefixed variable with no side-effect"
107                 );
108                 return true;
109             }
110         }
111     }
112     false
113 }
114
115 fn has_no_effect(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
116     if expr.span.from_expansion() {
117         return false;
118     }
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))
135         },
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`
140                     return false;
141                 }
142                 let def_matched = matches!(
143                     cx.qpath_res(qpath, callee.hir_id),
144                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
145                 );
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))
148                 } else {
149                     false
150                 }
151             } else {
152                 false
153             }
154         },
155         _ => false,
156     }
157 }
158
159 fn check_unnecessary_operation(cx: &LateContext<'_>, stmt: &Stmt<'_>) {
160     if_chain! {
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());
164         then {
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))
168                 {
169                     format!("assert!({}.len() > {});", &arr, &func)
170                 } else {
171                     return;
172                 };
173                 span_lint_hir_and_then(
174                     cx,
175                     UNNECESSARY_OPERATION,
176                     expr.hir_id,
177                     stmt.span,
178                     "unnecessary operation",
179                     |diag| {
180                         diag.span_suggestion(
181                             stmt.span,
182                             "statement can be written as",
183                             snippet,
184                             Applicability::MaybeIncorrect,
185                         );
186                     },
187                 );
188             } else {
189                 let mut snippet = String::new();
190                 for e in reduced {
191                     if let Some(snip) = snippet_opt(cx, e.span) {
192                         snippet.push_str(&snip);
193                         snippet.push(';');
194                     } else {
195                         return;
196                     }
197                 }
198                 span_lint_hir_and_then(
199                     cx,
200                     UNNECESSARY_OPERATION,
201                     expr.hir_id,
202                     stmt.span,
203                     "unnecessary operation",
204                     |diag| {
205                         diag.span_suggestion(
206                             stmt.span,
207                             "statement can be reduced to",
208                             snippet,
209                             Applicability::MachineApplicable,
210                         );
211                     },
212                 );
213             }
214         }
215     }
216 }
217
218 fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
219     if expr.span.from_expansion() {
220         return None;
221     }
222     match expr.kind {
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 => {
225             Some(vec![a, b])
226         },
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)) {
237                 None
238             } else {
239                 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
240             }
241         },
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`
246                     return None;
247                 }
248                 let res = cx.qpath_res(qpath, callee.hir_id);
249                 match res {
250                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
251                         if !has_drop(cx, cx.typeck_results().expr_ty(expr)) =>
252                     {
253                         Some(args.iter().collect())
254                     },
255                     _ => None,
256                 }
257             } else {
258                 None
259             }
260         },
261         ExprKind::Block(block, _) => {
262             if block.stmts.is_empty() {
263                 block.expr.as_ref().and_then(|e| {
264                     match block.rules {
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),
269                     }
270                 })
271             } else {
272                 None
273             }
274         },
275         _ => None,
276     }
277 }