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