]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/no_effect.rs
Auto merge of #7065 - rail-rain:warn_copy_pass_by_ref, r=Manishearth
[rust.git] / 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(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                 match res {
72                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..) => {
73                         !has_drop(cx, cx.typeck_results().expr_ty(expr))
74                             && args.iter().all(|arg| has_no_effect(cx, arg))
75                     },
76                     _ => false,
77                 }
78             } else {
79                 false
80             }
81         },
82         ExprKind::Block(block, _) => {
83             block.stmts.is_empty() && block.expr.as_ref().map_or(false, |expr| has_no_effect(cx, expr))
84         },
85         _ => false,
86     }
87 }
88
89 declare_lint_pass!(NoEffect => [NO_EFFECT, UNNECESSARY_OPERATION]);
90
91 impl<'tcx> LateLintPass<'tcx> for NoEffect {
92     fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
93         if let StmtKind::Semi(expr) = stmt.kind {
94             if has_no_effect(cx, expr) {
95                 span_lint(cx, NO_EFFECT, stmt.span, "statement with no effect");
96             } else if let Some(reduced) = reduce_expression(cx, expr) {
97                 let mut snippet = String::new();
98                 for e in reduced {
99                     if e.span.from_expansion() {
100                         return;
101                     }
102                     if let Some(snip) = snippet_opt(cx, e.span) {
103                         snippet.push_str(&snip);
104                         snippet.push(';');
105                     } else {
106                         return;
107                     }
108                 }
109                 span_lint_and_sugg(
110                     cx,
111                     UNNECESSARY_OPERATION,
112                     stmt.span,
113                     "statement can be reduced",
114                     "replace it with",
115                     snippet,
116                     Applicability::MachineApplicable,
117                 );
118             }
119         }
120     }
121 }
122
123 fn reduce_expression<'a>(cx: &LateContext<'_>, expr: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
124     if expr.span.from_expansion() {
125         return None;
126     }
127     match expr.kind {
128         ExprKind::Index(a, b) => Some(vec![a, b]),
129         ExprKind::Binary(ref binop, a, b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
130             Some(vec![a, b])
131         },
132         ExprKind::Array(v) | ExprKind::Tup(v) => Some(v.iter().collect()),
133         ExprKind::Repeat(inner, _)
134         | ExprKind::Cast(inner, _)
135         | ExprKind::Type(inner, _)
136         | ExprKind::Unary(_, inner)
137         | ExprKind::Field(inner, _)
138         | ExprKind::AddrOf(_, _, inner)
139         | ExprKind::Box(inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
140         ExprKind::Struct(_, fields, ref base) => {
141             if has_drop(cx, cx.typeck_results().expr_ty(expr)) {
142                 None
143             } else {
144                 Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect())
145             }
146         },
147         ExprKind::Call(callee, args) => {
148             if let ExprKind::Path(ref qpath) = callee.kind {
149                 let res = cx.qpath_res(qpath, callee.hir_id);
150                 match res {
151                     Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..)
152                         if !has_drop(cx, cx.typeck_results().expr_ty(expr)) =>
153                     {
154                         Some(args.iter().collect())
155                     },
156                     _ => None,
157                 }
158             } else {
159                 None
160             }
161         },
162         ExprKind::Block(block, _) => {
163             if block.stmts.is_empty() {
164                 block.expr.as_ref().and_then(|e| {
165                     match block.rules {
166                         BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
167                         BlockCheckMode::DefaultBlock => Some(vec![&**e]),
168                         // in case of compiler-inserted signaling blocks
169                         _ => reduce_expression(cx, e),
170                     }
171                 })
172             } else {
173                 None
174             }
175         },
176         _ => None,
177     }
178 }