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