]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/no_effect.rs
Add applicability level to (nearly) every span_lint_and_sugg function
[rust.git] / clippy_lints / src / no_effect.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 use crate::rustc::hir::def::Def;
12 use crate::rustc::hir::{BinOpKind, BlockCheckMode, Expr, ExprKind, Stmt, StmtKind, UnsafeSource};
13 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc_errors::Applicability;
16 use crate::utils::{has_drop, in_macro, snippet_opt, span_lint, span_lint_and_sugg};
17 use std::ops::Deref;
18
19 /// **What it does:** Checks for statements which have no effect.
20 ///
21 /// **Why is this bad?** Similar to dead code, these statements are actually
22 /// executed. However, as they have no effect, all they do is make the code less
23 /// readable.
24 ///
25 /// **Known problems:** None.
26 ///
27 /// **Example:**
28 /// ```rust
29 /// 0;
30 /// ```
31 declare_clippy_lint! {
32     pub NO_EFFECT,
33     complexity,
34     "statements with no effect"
35 }
36
37 /// **What it does:** Checks for expression statements that can be reduced to a
38 /// sub-expression.
39 ///
40 /// **Why is this bad?** Expressions by themselves often have no side-effects.
41 /// Having such expressions reduces readability.
42 ///
43 /// **Known problems:** None.
44 ///
45 /// **Example:**
46 /// ```rust
47 /// compute_array()[0];
48 /// ```
49 declare_clippy_lint! {
50     pub UNNECESSARY_OPERATION,
51     complexity,
52     "outer expressions with no effect"
53 }
54
55 fn has_no_effect(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
56     if in_macro(expr.span) {
57         return false;
58     }
59     match expr.node {
60         ExprKind::Lit(..) | ExprKind::Closure(.., _) => true,
61         ExprKind::Path(..) => !has_drop(cx, expr),
62         ExprKind::Index(ref a, ref b) | ExprKind::Binary(_, ref a, ref b) => {
63             has_no_effect(cx, a) && has_no_effect(cx, b)
64         },
65         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => v.iter().all(|val| has_no_effect(cx, val)),
66         ExprKind::Repeat(ref inner, _) |
67         ExprKind::Cast(ref inner, _) |
68         ExprKind::Type(ref inner, _) |
69         ExprKind::Unary(_, ref inner) |
70         ExprKind::Field(ref inner, _) |
71         ExprKind::AddrOf(_, ref inner) |
72         ExprKind::Box(ref inner) => has_no_effect(cx, inner),
73         ExprKind::Struct(_, ref fields, ref base) => {
74             !has_drop(cx, expr) && fields.iter().all(|field| has_no_effect(cx, &field.expr)) && match *base {
75                 Some(ref base) => has_no_effect(cx, base),
76                 None => true,
77             }
78         },
79         ExprKind::Call(ref callee, ref args) => if let ExprKind::Path(ref qpath) = callee.node {
80             let def = cx.tables.qpath_def(qpath, callee.hir_id);
81             match def {
82                 Def::Struct(..) | Def::Variant(..) | Def::StructCtor(..) | Def::VariantCtor(..) => {
83                     !has_drop(cx, expr) && args.iter().all(|arg| has_no_effect(cx, arg))
84                 },
85                 _ => false,
86             }
87         } else {
88             false
89         },
90         ExprKind::Block(ref block, _) => {
91             block.stmts.is_empty() && if let Some(ref expr) = block.expr {
92                 has_no_effect(cx, expr)
93             } else {
94                 false
95             }
96         },
97         _ => false,
98     }
99 }
100
101 #[derive(Copy, Clone)]
102 pub struct Pass;
103
104 impl LintPass for Pass {
105     fn get_lints(&self) -> LintArray {
106         lint_array!(NO_EFFECT, UNNECESSARY_OPERATION)
107     }
108 }
109
110 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
111     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
112         if let StmtKind::Semi(ref expr, _) = stmt.node {
113             if has_no_effect(cx, expr) {
114                 span_lint(cx, NO_EFFECT, stmt.span, "statement with no effect");
115             } else if let Some(reduced) = reduce_expression(cx, expr) {
116                 let mut snippet = String::new();
117                 for e in reduced {
118                     if in_macro(e.span) {
119                         return;
120                     }
121                     if let Some(snip) = snippet_opt(cx, e.span) {
122                         snippet.push_str(&snip);
123                         snippet.push(';');
124                     } else {
125                         return;
126                     }
127                 }
128                 span_lint_and_sugg(
129                     cx,
130                     UNNECESSARY_OPERATION,
131                     stmt.span,
132                     "statement can be reduced",
133                     "replace it with",
134                     snippet,
135                     Applicability::MachineApplicable,
136                 );
137             }
138         }
139     }
140 }
141
142
143 fn reduce_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<Vec<&'a Expr>> {
144     if in_macro(expr.span) {
145         return None;
146     }
147     match expr.node {
148         ExprKind::Index(ref a, ref b) => Some(vec![&**a, &**b]),
149         ExprKind::Binary(ref binop, ref a, ref b) if binop.node != BinOpKind::And && binop.node != BinOpKind::Or => {
150             Some(vec![&**a, &**b])
151         },
152         ExprKind::Array(ref v) | ExprKind::Tup(ref v) => Some(v.iter().collect()),
153         ExprKind::Repeat(ref inner, _) |
154         ExprKind::Cast(ref inner, _) |
155         ExprKind::Type(ref inner, _) |
156         ExprKind::Unary(_, ref inner) |
157         ExprKind::Field(ref inner, _) |
158         ExprKind::AddrOf(_, ref inner) |
159         ExprKind::Box(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])),
160         ExprKind::Struct(_, ref fields, ref base) => if has_drop(cx, expr) {
161             None
162         } else {
163             Some(
164                 fields
165                     .iter()
166                     .map(|f| &f.expr)
167                     .chain(base)
168                     .map(Deref::deref)
169                     .collect(),
170             )
171         },
172         ExprKind::Call(ref callee, ref args) => if let ExprKind::Path(ref qpath) = callee.node {
173             let def = cx.tables.qpath_def(qpath, callee.hir_id);
174             match def {
175                 Def::Struct(..) | Def::Variant(..) | Def::StructCtor(..) | Def::VariantCtor(..)
176                     if !has_drop(cx, expr) =>
177                 {
178                     Some(args.iter().collect())
179                 },
180                 _ => None,
181             }
182         } else {
183             None
184         },
185         ExprKind::Block(ref block, _) => {
186             if block.stmts.is_empty() {
187                 block.expr.as_ref().and_then(|e| {
188                     match block.rules {
189                         BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) => None,
190                         BlockCheckMode::DefaultBlock => Some(vec![&**e]),
191                         // in case of compiler-inserted signaling blocks
192                         _ => reduce_expression(cx, e),
193                     }
194                 })
195             } else {
196                 None
197             }
198         },
199         _ => None,
200     }
201 }