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