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