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