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