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