]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/no_effect.rs
Auto merge of #82864 - jyn514:short-circuit, r=GuillaumeGomez
[rust.git] / src / tools / clippy / clippy_lints / src / no_effect.rs
1 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg};
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::{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:** Checks for statements which have no effect.
13     ///
14     /// **Why is this bad?** Similar to dead code, these statements are actually
15     /// executed. However, as they have no effect, all they do is make the code less
16     /// readable.
17     ///
18     /// **Known problems:** None.
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:** Checks for expression statements that can be reduced to a
31     /// sub-expression.
32     ///
33     /// **Why is this bad?** Expressions by themselves often have no side-effects.
34     /// Having such expressions reduces readability.
35     ///
36     /// **Known problems:** None.
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(ref a, ref b) | ExprKind::Binary(_, ref a, ref b) => {
55             has_no_effect(cx, a) && has_no_effect(cx, b)
56         },
57         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => v.iter().all(|val| has_no_effect(cx, val)),
58         ExprKind::Repeat(ref inner, _)
59         | ExprKind::Cast(ref inner, _)
60         | ExprKind::Type(ref inner, _)
61         | ExprKind::Unary(_, ref inner)
62         | ExprKind::Field(ref inner, _)
63         | ExprKind::AddrOf(_, _, ref inner)
64         | ExprKind::Box(ref inner) => has_no_effect(cx, inner),
65         ExprKind::Struct(_, ref fields, ref base) => {
66             !has_drop(cx, cx.typeck_results().expr_ty(expr))
67                 && fields.iter().all(|field| has_no_effect(cx, &field.expr))
68                 && base.as_ref().map_or(true, |base| has_no_effect(cx, base))
69         },
70         ExprKind::Call(ref callee, ref args) => {
71             if let ExprKind::Path(ref qpath) = callee.kind {
72                 let res = cx.qpath_res(qpath, callee.hir_id);
73                 match res {
74                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..) => {
75                         !has_drop(cx, cx.typeck_results().expr_ty(expr))
76                             && args.iter().all(|arg| has_no_effect(cx, arg))
77                     },
78                     _ => false,
79                 }
80             } else {
81                 false
82             }
83         },
84         ExprKind::Block(ref 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(ref expr) = stmt.kind {
96             if has_no_effect(cx, expr) {
97                 span_lint(cx, NO_EFFECT, stmt.span, "statement with no effect");
98             } else if let Some(reduced) = reduce_expression(cx, expr) {
99                 let mut snippet = String::new();
100                 for e in reduced {
101                     if e.span.from_expansion() {
102                         return;
103                     }
104                     if let Some(snip) = snippet_opt(cx, e.span) {
105                         snippet.push_str(&snip);
106                         snippet.push(';');
107                     } else {
108                         return;
109                     }
110                 }
111                 span_lint_and_sugg(
112                     cx,
113                     UNNECESSARY_OPERATION,
114                     stmt.span,
115                     "statement can be reduced",
116                     "replace it with",
117                     snippet,
118                     Applicability::MachineApplicable,
119                 );
120             }
121         }
122     }
123 }
124
125 fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
126     if expr.span.from_expansion() {
127         return None;
128     }
129     match expr.kind {
130         ExprKind::Index(ref a, ref b) => Some(vec![&**a, &**b]),
131         ExprKind::Binary(ref binop, ref a, ref b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
132             Some(vec![&**a, &**b])
133         },
134         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => Some(v.iter().collect()),
135         ExprKind::Repeat(ref inner, _)
136         | ExprKind::Cast(ref inner, _)
137         | ExprKind::Type(ref inner, _)
138         | ExprKind::Unary(_, ref inner)
139         | ExprKind::Field(ref inner, _)
140         | ExprKind::AddrOf(_, _, ref inner)
141         | ExprKind::Box(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
142         ExprKind::Struct(_, ref fields, ref base) => {
143             if has_drop(cx, cx.typeck_results().expr_ty(expr)) {
144                 None
145             } else {
146                 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
147             }
148         },
149         ExprKind::Call(ref callee, ref args) => {
150             if let ExprKind::Path(ref qpath) = callee.kind {
151                 let res = cx.qpath_res(qpath, callee.hir_id);
152                 match res {
153                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
154                         if !has_drop(cx, cx.typeck_results().expr_ty(expr)) =>
155                     {
156                         Some(args.iter().collect())
157                     },
158                     _ => None,
159                 }
160             } else {
161                 None
162             }
163         },
164         ExprKind::Block(ref block, _) => {
165             if block.stmts.is_empty() {
166                 block.expr.as_ref().and_then(|e| {
167                     match block.rules {
168                         BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
169                         BlockCheckMode::DefaultBlock => Some(vec![&**e]),
170                         // in case of compiler-inserted signaling blocks
171                         _ => reduce_expression(cx, e),
172                     }
173                 })
174             } else {
175                 None
176             }
177         },
178         _ => None,
179     }
180 }