]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/eval_order_dependence.rs
Rustup to *rustc 1.14.0-nightly (144af3e97 2016-10-02)*
[rust.git] / clippy_lints / src / eval_order_dependence.rs
1 use rustc::hir::def_id::DefId;
2 use rustc::hir::intravisit::{Visitor, walk_expr};
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 LateLintPass for EvalOrderDependence {
60     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
61         // Find a write to a local variable.
62         match expr.node {
63             ExprAssign(ref lhs, _) | ExprAssignOp(_, ref lhs, _) => {
64                 if let ExprPath(None, ref path) = lhs.node {
65                     if path.segments.len() == 1 {
66                         let var = cx.tcx.expect_def(lhs.id).def_id();
67                         let mut visitor = ReadVisitor {
68                             cx: cx,
69                             var: var,
70                             write_expr: expr,
71                             last_expr: expr,
72                         };
73                         check_for_unsequenced_reads(&mut visitor);
74                     }
75                 }
76             }
77             _ => {}
78         }
79     }
80     fn check_stmt(&mut self, cx: &LateContext, stmt: &Stmt) {
81         match stmt.node {
82             StmtExpr(ref e, _) | StmtSemi(ref e, _) => DivergenceVisitor(cx).maybe_walk_expr(e),
83             StmtDecl(ref d, _) => {
84                 if let DeclLocal(ref local) = d.node {
85                     if let Local { init: Some(ref e), .. } = **local {
86                         DivergenceVisitor(cx).visit_expr(e);
87                     }
88                 }
89             },
90         }
91     }
92 }
93
94 struct DivergenceVisitor<'a, 'tcx: 'a>(&'a LateContext<'a, 'tcx>);
95
96 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
97     fn maybe_walk_expr(&mut self, e: &Expr) {
98         match e.node {
99             ExprClosure(..) => {},
100             ExprMatch(ref e, ref arms, _) => {
101                 self.visit_expr(e);
102                 for arm in arms {
103                     if let Some(ref guard) = arm.guard {
104                         self.visit_expr(guard);
105                     }
106                     // make sure top level arm expressions aren't linted
107                     self.maybe_walk_expr(&*arm.body);
108                 }
109             }
110             _ => walk_expr(self, e),
111         }
112     }
113     fn report_diverging_sub_expr(&mut self, e: &Expr) {
114         span_lint(
115             self.0,
116             DIVERGING_SUB_EXPRESSION,
117             e.span,
118             "sub-expression diverges",
119         );
120     }
121 }
122
123 impl<'a, 'tcx, 'v> Visitor<'v> for DivergenceVisitor<'a, 'tcx> {
124     fn visit_expr(&mut self, e: &'v Expr) {
125         match e.node {
126             ExprAgain(_) |
127             ExprBreak(_) |
128             ExprRet(_) => self.report_diverging_sub_expr(e),
129             ExprCall(ref func, _) => match self.0.tcx.expr_ty(func).sty {
130                 ty::TyFnDef(_, _, fn_ty) |
131                 ty::TyFnPtr(fn_ty) => if let ty::TyNever = self.0.tcx.erase_late_bound_regions(&fn_ty.sig).output.sty {
132                     self.report_diverging_sub_expr(e);
133                 },
134                 _ => {},
135             },
136             ExprMethodCall(..) => {
137                 let method_call = ty::MethodCall::expr(e.id);
138                 let borrowed_table = self.0.tcx.tables.borrow();
139                 let method_type = borrowed_table.method_map.get(&method_call).expect("This should never happen.");
140                 let result_ty = method_type.ty.fn_ret();
141                 if let ty::TyNever = self.0.tcx.erase_late_bound_regions(&result_ty).sty {
142                     self.report_diverging_sub_expr(e);
143                 }
144             },
145             _ => {
146                 // do not lint expressions referencing objects of type `!`, as that required a diverging expression to begin with
147             },
148         }
149         self.maybe_walk_expr(e);
150     }
151     fn visit_block(&mut self, _: &'v Block) {
152         // don't continue over blocks, LateLintPass already does that
153     }
154 }
155
156 /// Walks up the AST from the the given write expression (`vis.write_expr`)
157 /// looking for reads to the same variable that are unsequenced relative to the
158 /// write.
159 ///
160 /// This means reads for which there is a common ancestor between the read and
161 /// the write such that
162 ///
163 /// * evaluating the ancestor necessarily evaluates both the read and the write
164 ///   (for example, `&x` and `|| x = 1` don't necessarily evaluate `x`), and
165 ///
166 /// * which one is evaluated first depends on the order of sub-expression
167 ///   evaluation. Blocks, `if`s, loops, `match`es, and the short-circuiting
168 ///   logical operators are considered to have a defined evaluation order.
169 ///
170 /// When such a read is found, the lint is triggered.
171 fn check_for_unsequenced_reads(vis: &mut ReadVisitor) {
172     let map = &vis.cx.tcx.map;
173     let mut cur_id = vis.write_expr.id;
174     loop {
175         let parent_id = map.get_parent_node(cur_id);
176         if parent_id == cur_id {
177             break;
178         }
179         let parent_node = match map.find(parent_id) {
180             Some(parent) => parent,
181             None => break,
182         };
183
184         let stop_early = match parent_node {
185             map::Node::NodeExpr(expr) => check_expr(vis, expr),
186             map::Node::NodeStmt(stmt) => check_stmt(vis, stmt),
187             map::Node::NodeItem(_) => {
188                 // We reached the top of the function, stop.
189                 break;
190             },
191             _ => { StopEarly::KeepGoing }
192         };
193         match stop_early {
194             StopEarly::Stop => break,
195             StopEarly::KeepGoing => {},
196         }
197
198         cur_id = parent_id;
199     }
200 }
201
202 /// Whether to stop early for the loop in `check_for_unsequenced_reads`. (If
203 /// `check_expr` weren't an independent function, this would be unnecessary and
204 /// we could just use `break`).
205 enum StopEarly {
206     KeepGoing,
207     Stop,
208 }
209
210 fn check_expr<'v, 't>(vis: & mut ReadVisitor<'v, 't>, expr: &'v Expr) -> StopEarly {
211     if expr.id == vis.last_expr.id {
212         return StopEarly::KeepGoing;
213     }
214
215     match expr.node {
216         ExprArray(_) |
217         ExprTup(_) |
218         ExprMethodCall(_, _, _) |
219         ExprCall(_, _) |
220         ExprAssign(_, _) |
221         ExprIndex(_, _) |
222         ExprRepeat(_, _) |
223         ExprStruct(_, _, _) => {
224             walk_expr(vis, expr);
225         }
226         ExprBinary(op, _, _) |
227         ExprAssignOp(op, _, _) => {
228             if op.node == BiAnd || op.node == BiOr {
229                 // x && y and x || y always evaluate x first, so these are
230                 // strictly sequenced.
231             } else {
232                 walk_expr(vis, expr);
233             }
234         }
235         ExprClosure(_, _, _, _) => {
236             // Either
237             //
238             // * `var` is defined in the closure body, in which case we've
239             //   reached the top of the enclosing function and can stop, or
240             //
241             // * `var` is captured by the closure, in which case, because
242             //   evaluating a closure does not evaluate its body, we don't
243             //   necessarily have a write, so we need to stop to avoid
244             //   generating false positives.
245             //
246             // This is also the only place we need to stop early (grrr).
247             return StopEarly::Stop;
248         }
249         // All other expressions either have only one child or strictly
250         // sequence the evaluation order of their sub-expressions.
251         _ => {}
252     }
253
254     vis.last_expr = expr;
255
256     StopEarly::KeepGoing
257 }
258
259 fn check_stmt<'v, 't>(vis: &mut ReadVisitor<'v, 't>, stmt: &'v Stmt) -> StopEarly {
260     match stmt.node {
261         StmtExpr(ref expr, _) |
262         StmtSemi(ref expr, _) => check_expr(vis, expr),
263         StmtDecl(ref decl, _) => {
264             // If the declaration is of a local variable, check its initializer
265             // expression if it has one. Otherwise, keep going.
266             let local = match decl.node {
267                 DeclLocal(ref local) => Some(local),
268                 _ => None,
269             };
270             local.and_then(|local| local.init.as_ref())
271                 .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr))
272         }
273     }
274 }
275
276 /// A visitor that looks for reads from a variable.
277 struct ReadVisitor<'v, 't: 'v> {
278     cx: &'v LateContext<'v, 't>,
279     /// The id of the variable we're looking for.
280     var: DefId,
281     /// The expressions where the write to the variable occurred (for reporting
282     /// in the lint).
283     write_expr: &'v Expr,
284     /// The last (highest in the AST) expression we've checked, so we know not
285     /// to recheck it.
286     last_expr: &'v Expr,
287 }
288
289 impl<'v, 't> Visitor<'v> for ReadVisitor<'v, 't> {
290     fn visit_expr(&mut self, expr: &'v Expr) {
291         if expr.id == self.last_expr.id {
292             return;
293         }
294
295         match expr.node {
296             ExprPath(None, ref path) => {
297                 if path.segments.len() == 1 && self.cx.tcx.expect_def(expr.id).def_id() == self.var {
298                     if is_in_assignment_position(self.cx, expr) {
299                         // This is a write, not a read.
300                     } else {
301                         span_note_and_lint(
302                             self.cx,
303                             EVAL_ORDER_DEPENDENCE,
304                             expr.span,
305                             "unsequenced read of a variable",
306                             self.write_expr.span,
307                             "whether read occurs before this write depends on evaluation order"
308                         );
309                     }
310                 }
311             }
312             // We're about to descend a closure. Since we don't know when (or
313             // if) the closure will be evaluated, any reads in it might not
314             // occur here (or ever). Like above, bail to avoid false positives.
315             ExprClosure(_, _, _, _) |
316
317             // We want to avoid a false positive when a variable name occurs
318             // only to have its address taken, so we stop here. Technically,
319             // this misses some weird cases, eg.
320             //
321             // ```rust
322             // let mut x = 0;
323             // let a = foo(&{x = 1; x}, x);
324             // ```
325             //
326             // TODO: fix this
327             ExprAddrOf(_, _) => {
328                 return;
329             }
330             _ => {}
331         }
332
333         walk_expr(self, expr);
334     }
335 }
336
337 /// Returns true if `expr` is the LHS of an assignment, like `expr = ...`.
338 fn is_in_assignment_position(cx: &LateContext, expr: &Expr) -> bool {
339     if let Some(parent) = get_parent_expr(cx, expr) {
340         if let ExprAssign(ref lhs, _) = parent.node {
341             return lhs.id == expr.id;
342         }
343     }
344     false
345 }