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;
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 declare_clippy_lint! {
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.
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.
21 /// ### Known problems
22 /// Code which intentionally depends on the evaluation
23 /// order, or which is correct for any evaluation order.
34 /// // Unclear whether a is 1 or 2.
43 #[clippy::version = "pre 1.29.0"]
44 pub EVAL_ORDER_DEPENDENCE,
46 "whether a variable read occurs before a write depends on sub-expression evaluation order"
49 declare_clippy_lint! {
51 /// Checks for diverging calls that are not match arms or
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.
58 /// ### Known problems
59 /// Someone might want to use `some_bool || panic!()` as a
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!()`
71 #[clippy::version = "pre 1.29.0"]
72 pub DIVERGING_SUB_EXPRESSION,
74 "whether an expression contains a diverging sub expression"
77 declare_lint_pass!(EvalOrderDependence => [EVAL_ORDER_DEPENDENCE, DIVERGING_SUB_EXPRESSION]);
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.
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; }
88 let mut visitor = ReadVisitor {
94 check_for_unsequenced_reads(&mut visitor);
96 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
98 StmtKind::Local(local) => {
99 if let Local { init: Some(e), .. } = local {
100 DivergenceVisitor { cx }.visit_expr(e);
103 StmtKind::Expr(e) | StmtKind::Semi(e) => DivergenceVisitor { cx }.maybe_walk_expr(e),
104 StmtKind::Item(..) => {},
109 struct DivergenceVisitor<'a, 'tcx> {
110 cx: &'a LateContext<'tcx>,
113 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
114 fn maybe_walk_expr(&mut self, e: &'tcx Expr<'_>) {
116 ExprKind::Closure(..) => {},
117 ExprKind::Match(e, arms, _) => {
120 if let Some(Guard::If(if_expr)) = arm.guard {
121 self.visit_expr(if_expr);
123 // make sure top level arm expressions aren't linted
124 self.maybe_walk_expr(&*arm.body);
127 _ => walk_expr(self, e),
130 fn report_diverging_sub_expr(&mut self, e: &Expr<'_>) {
131 span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges");
135 impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> {
136 type Map = Map<'tcx>;
138 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
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);
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);
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);
160 // do not lint expressions referencing objects of type `!`, as that required a
161 // diverging expression
165 self.maybe_walk_expr(e);
167 fn visit_block(&mut self, _: &'tcx Block<'_>) {
168 // don't continue over blocks, LateLintPass already does that
170 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
171 NestedVisitorMap::None
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.
178 /// This means reads for which there is a common ancestor between the read and
179 /// the write such that
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
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.
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;
193 let parent_id = map.get_parent_node(cur_id);
194 if parent_id == cur_id {
197 let parent_node = match map.find(parent_id) {
198 Some(parent) => parent,
202 let stop_early = match parent_node {
203 Node::Expr(expr) => check_expr(vis, expr),
204 Node::Stmt(stmt) => check_stmt(vis, stmt),
206 // We reached the top of the function, stop.
209 _ => StopEarly::KeepGoing,
212 StopEarly::Stop => break,
213 StopEarly::KeepGoing => {},
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`).
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;
236 | ExprKind::MethodCall(..)
237 | ExprKind::Call(_, _)
238 | ExprKind::Assign(..)
239 | ExprKind::Index(_, _)
240 | ExprKind::Repeat(_, _)
241 | ExprKind::Struct(_, _, _) => {
242 walk_expr(vis, expr);
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.
249 walk_expr(vis, expr);
252 ExprKind::Closure(_, _, _, _, _) => {
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
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
262 // This is also the only place we need to stop early (grrr).
263 return StopEarly::Stop;
265 // All other expressions either have only one child or strictly
266 // sequence the evaluation order of their sub-expressions.
270 vis.last_expr = expr;
275 fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt<'_>) -> StopEarly {
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
283 .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr)),
284 StmtKind::Item(..) => StopEarly::KeepGoing,
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.
293 /// The expressions where the write to the variable occurred (for reporting
295 write_expr: &'tcx Expr<'tcx>,
296 /// The last (highest in the AST) expression we've checked, so we know not
298 last_expr: &'tcx Expr<'tcx>,
301 impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> {
302 type Map = Map<'tcx>;
304 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
305 if expr.hir_id == self.last_expr.hir_id {
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) {
314 EVAL_ORDER_DEPENDENCE,
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",
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(_, _, _, _, _) |
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.
334 // let a = foo(&{x = 1; x}, x);
338 ExprKind::AddrOf(_, _, _) => {
344 walk_expr(self, expr);
346 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
347 NestedVisitorMap::None
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;