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