]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eval_order_dependence.rs
Merge pull request #1729 from luisbg/lbg-typo
[rust.git] / clippy_lints / src / eval_order_dependence.rs
1 use rustc::hir::def_id::DefId;
2 use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap};
3 use rustc::hir::*;
4 use rustc::ty;
5 use rustc::lint::*;
6 use utils::{get_parent_expr, span_note_and_lint, span_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_lint! {
25     pub EVAL_ORDER_DEPENDENCE,
26     Warn,
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 statements.
31 ///
32 /// **Why is this bad?** It is often confusing to read. In addition, the
33 /// sub-expression evaluation order for Rust is not well documented.
34 ///
35 /// **Known problems:** Someone might want to use `some_bool || panic!()` as a shorthand.
36 ///
37 /// **Example:**
38 /// ```rust
39 /// let a = b() || panic!() || c();
40 /// // `c()` is dead, `panic!()` is only called if `b()` returns `false`
41 /// let x = (a, b, c, panic!());
42 /// // can simply be replaced by `panic!()`
43 /// ```
44 declare_lint! {
45     pub DIVERGING_SUB_EXPRESSION,
46     Warn,
47     "whether an expression contains a diverging sub expression"
48 }
49
50 #[derive(Copy,Clone)]
51 pub struct EvalOrderDependence;
52
53 impl LintPass for EvalOrderDependence {
54     fn get_lints(&self) -> LintArray {
55         lint_array!(EVAL_ORDER_DEPENDENCE, DIVERGING_SUB_EXPRESSION)
56     }
57 }
58
59 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EvalOrderDependence {
60     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
61         // Find a write to a local variable.
62         match expr.node {
63             ExprAssign(ref lhs, _) |
64             ExprAssignOp(_, ref lhs, _) => {
65                 if let ExprPath(ref qpath) = lhs.node {
66                     if let QPath::Resolved(_, ref path) = *qpath {
67                         if path.segments.len() == 1 {
68                             let var = cx.tables.qpath_def(qpath, lhs.id).def_id();
69                             let mut visitor = ReadVisitor {
70                                 cx: cx,
71                                 var: 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, _) |
86             StmtSemi(ref e, _) => DivergenceVisitor { cx: cx }.maybe_walk_expr(e),
87             StmtDecl(ref d, _) => {
88                 if let DeclLocal(ref local) = d.node {
89                     if let Local { init: Some(ref e), .. } = **local {
90                         DivergenceVisitor { cx: cx }.visit_expr(e);
91                     }
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             ExprClosure(..) => {},
106             ExprMatch(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             ExprAgain(_) | ExprBreak(_, _) | ExprRet(_) => self.report_diverging_sub_expr(e),
128             ExprCall(ref func, _) => {
129                 match self.cx.tables.expr_ty(func).sty {
130                     ty::TyFnDef(_, _, fn_ty) |
131                     ty::TyFnPtr(fn_ty) => {
132                         if let ty::TyNever = self.cx.tcx.erase_late_bound_regions(&fn_ty).output().sty {
133                             self.report_diverging_sub_expr(e);
134                         }
135                     },
136                     _ => {},
137                 }
138             },
139             ExprMethodCall(..) => {
140                 let method_call = ty::MethodCall::expr(e.id);
141                 let borrowed_table = self.cx.tables;
142                 let method_type = borrowed_table.method_map.get(&method_call).expect("This should never happen.");
143                 let result_ty = method_type.ty.fn_ret();
144                 if let ty::TyNever = self.cx.tcx.erase_late_bound_regions(&result_ty).sty {
145                     self.report_diverging_sub_expr(e);
146                 }
147             },
148             _ => {
149                 // do not lint expressions referencing objects of type `!`, as that required a diverging expression
150                 // to begin with
151             },
152         }
153         self.maybe_walk_expr(e);
154     }
155     fn visit_block(&mut self, _: &'tcx Block) {
156         // don't continue over blocks, LateLintPass already does that
157     }
158     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
159         NestedVisitorMap::All(&self.cx.tcx.hir)
160     }
161 }
162
163 /// Walks up the AST from the given write expression (`vis.write_expr`) looking
164 /// for reads to the same variable that are unsequenced relative to the write.
165 ///
166 /// This means reads for which there is a common ancestor between the read and
167 /// the write such that
168 ///
169 /// * evaluating the ancestor necessarily evaluates both the read and the write
170 ///   (for example, `&x` and `|| x = 1` don't necessarily evaluate `x`), and
171 ///
172 /// * which one is evaluated first depends on the order of sub-expression
173 ///   evaluation. Blocks, `if`s, loops, `match`es, and the short-circuiting
174 ///   logical operators are considered to have a defined evaluation order.
175 ///
176 /// When such a read is found, the lint is triggered.
177 fn check_for_unsequenced_reads(vis: &mut ReadVisitor) {
178     let map = &vis.cx.tcx.hir;
179     let mut cur_id = vis.write_expr.id;
180     loop {
181         let parent_id = map.get_parent_node(cur_id);
182         if parent_id == cur_id {
183             break;
184         }
185         let parent_node = match map.find(parent_id) {
186             Some(parent) => parent,
187             None => break,
188         };
189
190         let stop_early = match parent_node {
191             map::Node::NodeExpr(expr) => check_expr(vis, expr),
192             map::Node::NodeStmt(stmt) => check_stmt(vis, stmt),
193             map::Node::NodeItem(_) => {
194                 // We reached the top of the function, stop.
195                 break;
196             },
197             _ => StopEarly::KeepGoing,
198         };
199         match stop_early {
200             StopEarly::Stop => break,
201             StopEarly::KeepGoing => {},
202         }
203
204         cur_id = parent_id;
205     }
206 }
207
208 /// Whether to stop early for the loop in `check_for_unsequenced_reads`. (If
209 /// `check_expr` weren't an independent function, this would be unnecessary and
210 /// we could just use `break`).
211 enum StopEarly {
212     KeepGoing,
213     Stop,
214 }
215
216 fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr) -> StopEarly {
217     if expr.id == vis.last_expr.id {
218         return StopEarly::KeepGoing;
219     }
220
221     match expr.node {
222         ExprArray(_) |
223         ExprTup(_) |
224         ExprMethodCall(_, _, _) |
225         ExprCall(_, _) |
226         ExprAssign(_, _) |
227         ExprIndex(_, _) |
228         ExprRepeat(_, _) |
229         ExprStruct(_, _, _) => {
230             walk_expr(vis, expr);
231         },
232         ExprBinary(op, _, _) |
233         ExprAssignOp(op, _, _) => {
234             if op.node == BiAnd || op.node == BiOr {
235                 // x && y and x || y always evaluate x first, so these are
236                 // strictly sequenced.
237             } else {
238                 walk_expr(vis, expr);
239             }
240         },
241         ExprClosure(_, _, _, _) => {
242             // Either
243             //
244             // * `var` is defined in the closure body, in which case we've
245             //   reached the top of the enclosing function and can stop, or
246             //
247             // * `var` is captured by the closure, in which case, because
248             //   evaluating a closure does not evaluate its body, we don't
249             //   necessarily have a write, so we need to stop to avoid
250             //   generating false positives.
251             //
252             // This is also the only place we need to stop early (grrr).
253             return StopEarly::Stop;
254         },
255         // All other expressions either have only one child or strictly
256         // sequence the evaluation order of their sub-expressions.
257         _ => {},
258     }
259
260     vis.last_expr = expr;
261
262     StopEarly::KeepGoing
263 }
264
265 fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt) -> StopEarly {
266     match stmt.node {
267         StmtExpr(ref expr, _) |
268         StmtSemi(ref expr, _) => check_expr(vis, expr),
269         StmtDecl(ref decl, _) => {
270             // If the declaration is of a local variable, check its initializer
271             // expression if it has one. Otherwise, keep going.
272             let local = match decl.node {
273                 DeclLocal(ref local) => Some(local),
274                 _ => None,
275             };
276             local.and_then(|local| local.init.as_ref())
277                 .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr))
278         },
279     }
280 }
281
282 /// A visitor that looks for reads from a variable.
283 struct ReadVisitor<'a, 'tcx: 'a> {
284     cx: &'a LateContext<'a, 'tcx>,
285     /// The id of the variable we're looking for.
286     var: DefId,
287     /// The expressions where the write to the variable occurred (for reporting
288     /// in the lint).
289     write_expr: &'tcx Expr,
290     /// The last (highest in the AST) expression we've checked, so we know not
291     /// to recheck it.
292     last_expr: &'tcx Expr,
293 }
294
295 impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> {
296     fn visit_expr(&mut self, expr: &'tcx Expr) {
297         if expr.id == self.last_expr.id {
298             return;
299         }
300
301         match expr.node {
302             ExprPath(ref qpath) => {
303                 if let QPath::Resolved(None, ref path) = *qpath {
304                     if path.segments.len() == 1 && self.cx.tables.qpath_def(qpath, expr.id).def_id() == self.var {
305                         if is_in_assignment_position(self.cx, expr) {
306                             // This is a write, not a read.
307                         } else {
308                             span_note_and_lint(
309                                 self.cx,
310                                 EVAL_ORDER_DEPENDENCE,
311                                 expr.span,
312                                 "unsequenced read of a variable",
313                                 self.write_expr.span,
314                                 "whether read occurs before this write depends on evaluation order"
315                             );
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             ExprClosure(_, _, _, _) |
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             ExprAddrOf(_, _) => {
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::All(&self.cx.tcx.hir)
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 ExprAssign(ref lhs, _) = parent.node {
352             return lhs.id == expr.id;
353         }
354     }
355     false
356 }