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