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