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