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, Visitor};
5 use rustc_hir::{BinOpKind, Block, Expr, ExprKind, Guard, HirId, Local, Node, Stmt, StmtKind};
6 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 declare_clippy_lint! {
12 /// Checks for a read and a write to the same variable where
13 /// whether the read occurs before or after the write depends on the evaluation
14 /// order of sub-expressions.
16 /// ### Why is this bad?
17 /// It is often confusing to read. As described [here](https://doc.rust-lang.org/reference/expressions.html?highlight=subexpression#evaluation-order-of-operands),
18 /// the operands of these expressions are evaluated before applying the effects of the expression.
20 /// ### Known problems
21 /// Code which intentionally depends on the evaluation
22 /// order, or which is correct for any evaluation order.
32 /// // Unclear whether a is 1 or 2.
44 #[clippy::version = "pre 1.29.0"]
45 pub MIXED_READ_WRITE_IN_EXPRESSION,
47 "whether a variable read occurs before a write depends on sub-expression evaluation order"
50 declare_clippy_lint! {
52 /// Checks for diverging calls that are not match arms or
55 /// ### Why is this bad?
56 /// It is often confusing to read. In addition, the
57 /// sub-expression evaluation order for Rust is not well documented.
59 /// ### Known problems
60 /// Someone might want to use `some_bool || panic!()` as a
65 /// # fn b() -> bool { true }
66 /// # fn c() -> bool { true }
67 /// let a = b() || panic!() || c();
68 /// // `c()` is dead, `panic!()` is only called if `b()` returns `false`
69 /// let x = (a, b, c, panic!());
70 /// // can simply be replaced by `panic!()`
72 #[clippy::version = "pre 1.29.0"]
73 pub DIVERGING_SUB_EXPRESSION,
75 "whether an expression contains a diverging sub expression"
78 declare_lint_pass!(EvalOrderDependence => [MIXED_READ_WRITE_IN_EXPRESSION, DIVERGING_SUB_EXPRESSION]);
80 impl<'tcx> LateLintPass<'tcx> for EvalOrderDependence {
81 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
82 // Find a write to a local variable.
84 if let ExprKind::Assign(lhs, ..) | ExprKind::AssignOp(_, lhs, _) = expr.kind;
85 if let Some(var) = path_to_local(lhs);
86 if expr.span.desugaring_kind().is_none();
87 then { var } else { return; }
89 let mut visitor = ReadVisitor {
95 check_for_unsequenced_reads(&mut visitor);
97 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
99 StmtKind::Local(local) => {
100 if let Local { init: Some(e), .. } = local {
101 DivergenceVisitor { cx }.visit_expr(e);
104 StmtKind::Expr(e) | StmtKind::Semi(e) => DivergenceVisitor { cx }.maybe_walk_expr(e),
105 StmtKind::Item(..) => {},
110 struct DivergenceVisitor<'a, 'tcx> {
111 cx: &'a LateContext<'tcx>,
114 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
115 fn maybe_walk_expr(&mut self, e: &'tcx Expr<'_>) {
117 ExprKind::Closure { .. } => {},
118 ExprKind::Match(e, arms, _) => {
121 if let Some(Guard::If(if_expr)) = arm.guard {
122 self.visit_expr(if_expr);
124 // make sure top level arm expressions aren't linted
125 self.maybe_walk_expr(arm.body);
128 _ => walk_expr(self, e),
131 fn report_diverging_sub_expr(&mut self, e: &Expr<'_>) {
132 span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges");
136 impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> {
137 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
139 ExprKind::Continue(_) | ExprKind::Break(_, _) | ExprKind::Ret(_) => self.report_diverging_sub_expr(e),
140 ExprKind::Call(func, _) => {
141 let typ = self.cx.typeck_results().expr_ty(func);
143 ty::FnDef(..) | ty::FnPtr(_) => {
144 let sig = typ.fn_sig(self.cx.tcx);
145 if self.cx.tcx.erase_late_bound_regions(sig).output().kind() == &ty::Never {
146 self.report_diverging_sub_expr(e);
152 ExprKind::MethodCall(..) => {
153 let borrowed_table = self.cx.typeck_results();
154 if borrowed_table.expr_ty(e).is_never() {
155 self.report_diverging_sub_expr(e);
159 // do not lint expressions referencing objects of type `!`, as that required a
160 // diverging expression
164 self.maybe_walk_expr(e);
166 fn visit_block(&mut self, _: &'tcx Block<'_>) {
167 // don't continue over blocks, LateLintPass already does that
171 /// Walks up the AST from the given write expression (`vis.write_expr`) looking
172 /// for reads to the same variable that are unsequenced relative to the write.
174 /// This means reads for which there is a common ancestor between the read and
175 /// the write such that
177 /// * evaluating the ancestor necessarily evaluates both the read and the write (for example, `&x`
178 /// and `|| x = 1` don't necessarily evaluate `x`), and
180 /// * which one is evaluated first depends on the order of sub-expression evaluation. Blocks, `if`s,
181 /// loops, `match`es, and the short-circuiting logical operators are considered to have a defined
182 /// evaluation order.
184 /// When such a read is found, the lint is triggered.
185 fn check_for_unsequenced_reads(vis: &mut ReadVisitor<'_, '_>) {
186 let map = &vis.cx.tcx.hir();
187 let mut cur_id = vis.write_expr.hir_id;
189 let parent_id = map.parent_id(cur_id);
190 if parent_id == cur_id {
193 let Some(parent_node) = map.find(parent_id) else { break };
195 let stop_early = match parent_node {
196 Node::Expr(expr) => check_expr(vis, expr),
197 Node::Stmt(stmt) => check_stmt(vis, stmt),
199 // We reached the top of the function, stop.
202 _ => StopEarly::KeepGoing,
205 StopEarly::Stop => break,
206 StopEarly::KeepGoing => {},
213 /// Whether to stop early for the loop in `check_for_unsequenced_reads`. (If
214 /// `check_expr` weren't an independent function, this would be unnecessary and
215 /// we could just use `break`).
221 fn check_expr<'tcx>(vis: &mut ReadVisitor<'_, 'tcx>, expr: &'tcx Expr<'_>) -> StopEarly {
222 if expr.hir_id == vis.last_expr.hir_id {
223 return StopEarly::KeepGoing;
229 | ExprKind::MethodCall(..)
230 | ExprKind::Call(_, _)
231 | ExprKind::Assign(..)
232 | ExprKind::Index(_, _)
233 | ExprKind::Repeat(_, _)
234 | ExprKind::Struct(_, _, _) => {
235 walk_expr(vis, expr);
237 ExprKind::Binary(op, _, _) | ExprKind::AssignOp(op, _, _) => {
238 if op.node == BinOpKind::And || op.node == BinOpKind::Or {
239 // x && y and x || y always evaluate x first, so these are
240 // strictly sequenced.
242 walk_expr(vis, expr);
245 ExprKind::Closure { .. } => {
248 // * `var` is defined in the closure body, in which case we've reached the top of the enclosing
249 // function and can stop, or
251 // * `var` is captured by the closure, in which case, because evaluating a closure does not evaluate
252 // its body, we don't necessarily have a write, so we need to stop to avoid generating false
255 // This is also the only place we need to stop early (grrr).
256 return StopEarly::Stop;
258 // All other expressions either have only one child or strictly
259 // sequence the evaluation order of their sub-expressions.
263 vis.last_expr = expr;
268 fn check_stmt<'tcx>(vis: &mut ReadVisitor<'_, 'tcx>, stmt: &'tcx Stmt<'_>) -> StopEarly {
270 StmtKind::Expr(expr) | StmtKind::Semi(expr) => check_expr(vis, expr),
271 // If the declaration is of a local variable, check its initializer
272 // expression if it has one. Otherwise, keep going.
273 StmtKind::Local(local) => local
276 .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr)),
277 StmtKind::Item(..) => StopEarly::KeepGoing,
281 /// A visitor that looks for reads from a variable.
282 struct ReadVisitor<'a, 'tcx> {
283 cx: &'a LateContext<'tcx>,
284 /// The ID of the variable we're looking for.
286 /// The expressions where the write to the variable occurred (for reporting
288 write_expr: &'tcx Expr<'tcx>,
289 /// The last (highest in the AST) expression we've checked, so we know not
291 last_expr: &'tcx Expr<'tcx>,
294 impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> {
295 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
296 if expr.hir_id == self.last_expr.hir_id {
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) {
305 MIXED_READ_WRITE_IN_EXPRESSION,
307 &format!("unsequenced read of `{}`", self.cx.tcx.hir().name(self.var)),
308 Some(self.write_expr.span),
309 "whether read occurs before this write depends on evaluation order",
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{..} |
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.
325 // let a = foo(&{x = 1; x}, x);
329 ExprKind::AddrOf(_, _, _) => {
335 walk_expr(self, expr);
339 /// Returns `true` if `expr` is the LHS of an assignment, like `expr = ...`.
340 fn is_in_assignment_position(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
341 if let Some(parent) = get_parent_expr(cx, expr) {
342 if let ExprKind::Assign(lhs, ..) = parent.kind {
343 return lhs.hir_id == expr.hir_id;