]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eval_order_dependence.rs
ebbffc6680807ddacecd5df67e64289f422c5732
[rust.git] / clippy_lints / src / eval_order_dependence.rs
1 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
2 use rustc::hir::*;
3 use rustc::ty;
4 use rustc::lint::*;
5 use syntax::ast;
6 use crate::utils::{get_parent_expr, span_lint, span_note_and_lint};
7
8 /// **What it does:** Checks for a read and a write to the same variable where
9 /// whether the read occurs before or after the write depends on the evaluation
10 /// order of sub-expressions.
11 ///
12 /// **Why is this bad?** It is often confusing to read. In addition, the
13 /// sub-expression evaluation order for Rust is not well documented.
14 ///
15 /// **Known problems:** Code which intentionally depends on the evaluation
16 /// order, or which is correct for any evaluation order.
17 ///
18 /// **Example:**
19 /// ```rust
20 /// let mut x = 0;
21 /// let a = {x = 1; 1} + x;
22 /// // Unclear whether a is 1 or 2.
23 /// ```
24 declare_clippy_lint! {
25     pub EVAL_ORDER_DEPENDENCE,
26     complexity,
27     "whether a variable read occurs before a write depends on sub-expression evaluation order"
28 }
29
30 /// **What it does:** Checks for diverging calls that are not match arms or
31 /// statements.
32 ///
33 /// **Why is this bad?** It is often confusing to read. In addition, the
34 /// sub-expression evaluation order for Rust is not well documented.
35 ///
36 /// **Known problems:** Someone might want to use `some_bool || panic!()` as a
37 /// shorthand.
38 ///
39 /// **Example:**
40 /// ```rust
41 /// let a = b() || panic!() || c();
42 /// // `c()` is dead, `panic!()` is only called if `b()` returns `false`
43 /// let x = (a, b, c, panic!());
44 /// // can simply be replaced by `panic!()`
45 /// ```
46 declare_clippy_lint! {
47     pub DIVERGING_SUB_EXPRESSION,
48     complexity,
49     "whether an expression contains a diverging sub expression"
50 }
51
52 #[derive(Copy, Clone)]
53 pub struct EvalOrderDependence;
54
55 impl LintPass for EvalOrderDependence {
56     fn get_lints(&self) -> LintArray {
57         lint_array!(EVAL_ORDER_DEPENDENCE, DIVERGING_SUB_EXPRESSION)
58     }
59 }
60
61 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EvalOrderDependence {
62     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
63         // Find a write to a local variable.
64         match expr.node {
65             ExprKind::Assign(ref lhs, _) | ExprKind::AssignOp(_, ref lhs, _) => if let ExprKind::Path(ref qpath) = lhs.node {
66                 if let QPath::Resolved(_, ref path) = *qpath {
67                     if path.segments.len() == 1 {
68                         if let def::Def::Local(var) = cx.tables.qpath_def(qpath, lhs.hir_id) {
69                             let mut visitor = ReadVisitor {
70                                 cx,
71                                 var,
72                                 write_expr: expr,
73                                 last_expr: expr,
74                             };
75                             check_for_unsequenced_reads(&mut visitor);
76                         }
77                     }
78                 }
79             },
80             _ => {},
81         }
82     }
83     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
84         match stmt.node {
85             StmtExpr(ref e, _) | StmtSemi(ref e, _) => DivergenceVisitor { cx }.maybe_walk_expr(e),
86             StmtDecl(ref d, _) => if let DeclLocal(ref local) = d.node {
87                 if let Local {
88                     init: Some(ref e), ..
89                 } = **local
90                 {
91                     DivergenceVisitor { cx }.visit_expr(e);
92                 }
93             },
94         }
95     }
96 }
97
98 struct DivergenceVisitor<'a, 'tcx: 'a> {
99     cx: &'a LateContext<'a, 'tcx>,
100 }
101
102 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
103     fn maybe_walk_expr(&mut self, e: &'tcx Expr) {
104         match e.node {
105             ExprKind::Closure(.., _) => {},
106             ExprKind::Match(ref e, ref arms, _) => {
107                 self.visit_expr(e);
108                 for arm in arms {
109                     if let Some(ref guard) = arm.guard {
110                         self.visit_expr(guard);
111                     }
112                     // make sure top level arm expressions aren't linted
113                     self.maybe_walk_expr(&*arm.body);
114                 }
115             },
116             _ => walk_expr(self, e),
117         }
118     }
119     fn report_diverging_sub_expr(&mut self, e: &Expr) {
120         span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges");
121     }
122 }
123
124 impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> {
125     fn visit_expr(&mut self, e: &'tcx Expr) {
126         match e.node {
127             ExprKind::Continue(_) | ExprKind::Break(_, _) | ExprKind::Ret(_) => self.report_diverging_sub_expr(e),
128             ExprKind::Call(ref func, _) => {
129                 let typ = self.cx.tables.expr_ty(func);
130                 match typ.sty {
131                     ty::TyFnDef(..) | ty::TyFnPtr(_) => {
132                         let sig = typ.fn_sig(self.cx.tcx);
133                         if let ty::TyNever = self.cx.tcx.erase_late_bound_regions(&sig).output().sty {
134                             self.report_diverging_sub_expr(e);
135                         }
136                     },
137                     _ => {},
138                 }
139             },
140             ExprKind::MethodCall(..) => {
141                 let borrowed_table = self.cx.tables;
142                 if borrowed_table.expr_ty(e).is_never() {
143                     self.report_diverging_sub_expr(e);
144                 }
145             },
146             _ => {
147                 // do not lint expressions referencing objects of type `!`, as that required a
148                 // diverging expression
149                 // to begin with
150             },
151         }
152         self.maybe_walk_expr(e);
153     }
154     fn visit_block(&mut self, _: &'tcx Block) {
155         // don't continue over blocks, LateLintPass already does that
156     }
157     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
158         NestedVisitorMap::None
159     }
160 }
161
162 /// Walks up the AST from the given write expression (`vis.write_expr`) looking
163 /// for reads to the same variable that are unsequenced relative to the write.
164 ///
165 /// This means reads for which there is a common ancestor between the read and
166 /// the write such that
167 ///
168 /// * evaluating the ancestor necessarily evaluates both the read and the write
169 ///   (for example, `&x` and `|| x = 1` don't necessarily evaluate `x`), and
170 ///
171 /// * which one is evaluated first depends on the order of sub-expression
172 ///   evaluation. Blocks, `if`s, loops, `match`es, and the short-circuiting
173 ///   logical operators are considered to have a defined evaluation order.
174 ///
175 /// When such a read is found, the lint is triggered.
176 fn check_for_unsequenced_reads(vis: &mut ReadVisitor) {
177     let map = &vis.cx.tcx.hir;
178     let mut cur_id = vis.write_expr.id;
179     loop {
180         let parent_id = map.get_parent_node(cur_id);
181         if parent_id == cur_id {
182             break;
183         }
184         let parent_node = match map.find(parent_id) {
185             Some(parent) => parent,
186             None => break,
187         };
188
189         let stop_early = match parent_node {
190             map::Node::NodeExpr(expr) => check_expr(vis, expr),
191             map::Node::NodeStmt(stmt) => check_stmt(vis, stmt),
192             map::Node::NodeItem(_) => {
193                 // We reached the top of the function, stop.
194                 break;
195             },
196             _ => StopEarly::KeepGoing,
197         };
198         match stop_early {
199             StopEarly::Stop => break,
200             StopEarly::KeepGoing => {},
201         }
202
203         cur_id = parent_id;
204     }
205 }
206
207 /// Whether to stop early for the loop in `check_for_unsequenced_reads`. (If
208 /// `check_expr` weren't an independent function, this would be unnecessary and
209 /// we could just use `break`).
210 enum StopEarly {
211     KeepGoing,
212     Stop,
213 }
214
215 fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr) -> StopEarly {
216     if expr.id == vis.last_expr.id {
217         return StopEarly::KeepGoing;
218     }
219
220     match expr.node {
221         ExprKind::Array(_) |
222         ExprKind::Tup(_) |
223         ExprKind::MethodCall(..) |
224         ExprKind::Call(_, _) |
225         ExprKind::Assign(_, _) |
226         ExprKind::Index(_, _) |
227         ExprKind::Repeat(_, _) |
228         ExprKind::Struct(_, _, _) => {
229             walk_expr(vis, expr);
230         },
231         ExprKind::Binary(op, _, _) | ExprKind::AssignOp(op, _, _) => {
232             if op.node == BiAnd || op.node == BiOr {
233                 // x && y and x || y always evaluate x first, so these are
234                 // strictly sequenced.
235             } else {
236                 walk_expr(vis, expr);
237             }
238         },
239         ExprKind::Closure(_, _, _, _, _) => {
240             // Either
241             //
242             // * `var` is defined in the closure body, in which case we've
243             //   reached the top of the enclosing function and can stop, or
244             //
245             // * `var` is captured by the closure, in which case, because
246             //   evaluating a closure does not evaluate its body, we don't
247             //   necessarily have a write, so we need to stop to avoid
248             //   generating false positives.
249             //
250             // This is also the only place we need to stop early (grrr).
251             return StopEarly::Stop;
252         },
253         // All other expressions either have only one child or strictly
254         // sequence the evaluation order of their sub-expressions.
255         _ => {},
256     }
257
258     vis.last_expr = expr;
259
260     StopEarly::KeepGoing
261 }
262
263 fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt) -> StopEarly {
264     match stmt.node {
265         StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => check_expr(vis, expr),
266         StmtDecl(ref decl, _) => {
267             // If the declaration is of a local variable, check its initializer
268             // expression if it has one. Otherwise, keep going.
269             let local = match decl.node {
270                 DeclLocal(ref local) => Some(local),
271                 _ => None,
272             };
273             local
274                 .and_then(|local| local.init.as_ref())
275                 .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr))
276         },
277     }
278 }
279
280 /// A visitor that looks for reads from a variable.
281 struct ReadVisitor<'a, 'tcx: 'a> {
282     cx: &'a LateContext<'a, 'tcx>,
283     /// The id of the variable we're looking for.
284     var: ast::NodeId,
285     /// The expressions where the write to the variable occurred (for reporting
286     /// in the lint).
287     write_expr: &'tcx Expr,
288     /// The last (highest in the AST) expression we've checked, so we know not
289     /// to recheck it.
290     last_expr: &'tcx Expr,
291 }
292
293 impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> {
294     fn visit_expr(&mut self, expr: &'tcx Expr) {
295         if expr.id == self.last_expr.id {
296             return;
297         }
298
299         match expr.node {
300             ExprKind::Path(ref qpath) => {
301                 if_chain! {
302                     if let QPath::Resolved(None, ref path) = *qpath;
303                     if path.segments.len() == 1;
304                     if let def::Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id);
305                     if local_id == self.var;
306                     // Check that this is a read, not a write.
307                     if !is_in_assignment_position(self.cx, expr);
308                     then {
309                         span_note_and_lint(
310                             self.cx,
311                             EVAL_ORDER_DEPENDENCE,
312                             expr.span,
313                             "unsequenced read of a variable",
314                             self.write_expr.span,
315                             "whether read occurs before this write depends on evaluation order"
316                         );
317                     }
318                 }
319             }
320             // We're about to descend a closure. Since we don't know when (or
321             // if) the closure will be evaluated, any reads in it might not
322             // occur here (or ever). Like above, bail to avoid false positives.
323             ExprKind::Closure(_, _, _, _, _) |
324
325             // We want to avoid a false positive when a variable name occurs
326             // only to have its address taken, so we stop here. Technically,
327             // this misses some weird cases, eg.
328             //
329             // ```rust
330             // let mut x = 0;
331             // let a = foo(&{x = 1; x}, x);
332             // ```
333             //
334             // TODO: fix this
335             ExprKind::AddrOf(_, _) => {
336                 return;
337             }
338             _ => {}
339         }
340
341         walk_expr(self, expr);
342     }
343     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
344         NestedVisitorMap::None
345     }
346 }
347
348 /// Returns true if `expr` is the LHS of an assignment, like `expr = ...`.
349 fn is_in_assignment_position(cx: &LateContext, expr: &Expr) -> bool {
350     if let Some(parent) = get_parent_expr(cx, expr) {
351         if let ExprKind::Assign(ref lhs, _) = parent.node {
352             return lhs.id == expr.id;
353         }
354     }
355     false
356 }