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