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