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;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
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.
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.
18 /// **Known problems:** Code which intentionally depends on the evaluation
19 /// order, or which is correct for any evaluation order.
30 /// // Unclear whether a is 1 or 2.
39 pub EVAL_ORDER_DEPENDENCE,
41 "whether a variable read occurs before a write depends on sub-expression evaluation order"
44 declare_clippy_lint! {
45 /// **What it does:** Checks for diverging calls that are not match arms or
48 /// **Why is this bad?** It is often confusing to read. In addition, the
49 /// sub-expression evaluation order for Rust is not well documented.
51 /// **Known problems:** Someone might want to use `some_bool || panic!()` as a
56 /// # fn b() -> bool { true }
57 /// # fn c() -> bool { true }
58 /// let a = b() || panic!() || c();
59 /// // `c()` is dead, `panic!()` is only called if `b()` returns `false`
60 /// let x = (a, b, c, panic!());
61 /// // can simply be replaced by `panic!()`
63 pub DIVERGING_SUB_EXPRESSION,
65 "whether an expression contains a diverging sub expression"
68 declare_lint_pass!(EvalOrderDependence => [EVAL_ORDER_DEPENDENCE, DIVERGING_SUB_EXPRESSION]);
70 impl<'tcx> LateLintPass<'tcx> for EvalOrderDependence {
71 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
72 // Find a write to a local variable.
74 ExprKind::Assign(ref lhs, ..) | ExprKind::AssignOp(_, ref lhs, _) => {
75 if let ExprKind::Path(ref qpath) = lhs.kind {
76 if let QPath::Resolved(_, ref path) = *qpath {
77 if path.segments.len() == 1 {
78 if let def::Res::Local(var) = cx.qpath_res(qpath, lhs.hir_id) {
79 let mut visitor = ReadVisitor {
85 check_for_unsequenced_reads(&mut visitor);
94 fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
96 StmtKind::Local(ref local) => {
97 if let Local { init: Some(ref e), .. } = **local {
98 DivergenceVisitor { cx }.visit_expr(e);
101 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => DivergenceVisitor { cx }.maybe_walk_expr(e),
102 StmtKind::Item(..) => {},
107 struct DivergenceVisitor<'a, 'tcx> {
108 cx: &'a LateContext<'tcx>,
111 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
112 fn maybe_walk_expr(&mut self, e: &'tcx Expr<'_>) {
114 ExprKind::Closure(..) => {},
115 ExprKind::Match(ref e, arms, _) => {
118 if let Some(Guard::If(if_expr)) = arm.guard {
119 self.visit_expr(if_expr)
121 // make sure top level arm expressions aren't linted
122 self.maybe_walk_expr(&*arm.body);
125 _ => walk_expr(self, e),
128 fn report_diverging_sub_expr(&mut self, e: &Expr<'_>) {
129 span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges");
133 impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> {
134 type Map = Map<'tcx>;
136 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
138 ExprKind::Continue(_) | ExprKind::Break(_, _) | ExprKind::Ret(_) => self.report_diverging_sub_expr(e),
139 ExprKind::Call(ref func, _) => {
140 let typ = self.cx.typeck_results().expr_ty(func);
142 ty::FnDef(..) | ty::FnPtr(_) => {
143 let sig = typ.fn_sig(self.cx.tcx);
144 if let ty::Never = self.cx.tcx.erase_late_bound_regions(&sig).output().kind() {
145 self.report_diverging_sub_expr(e);
151 ExprKind::MethodCall(..) => {
152 let borrowed_table = self.cx.typeck_results();
153 if borrowed_table.expr_ty(e).is_never() {
154 self.report_diverging_sub_expr(e);
158 // do not lint expressions referencing objects of type `!`, as that required a
159 // diverging expression
163 self.maybe_walk_expr(e);
165 fn visit_block(&mut self, _: &'tcx Block<'_>) {
166 // don't continue over blocks, LateLintPass already does that
168 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
169 NestedVisitorMap::None
173 /// Walks up the AST from the given write expression (`vis.write_expr`) looking
174 /// for reads to the same variable that are unsequenced relative to the write.
176 /// This means reads for which there is a common ancestor between the read and
177 /// the write such that
179 /// * evaluating the ancestor necessarily evaluates both the read and the write (for example, `&x`
180 /// and `|| x = 1` don't necessarily evaluate `x`), and
182 /// * which one is evaluated first depends on the order of sub-expression evaluation. Blocks, `if`s,
183 /// loops, `match`es, and the short-circuiting logical operators are considered to have a defined
184 /// evaluation order.
186 /// When such a read is found, the lint is triggered.
187 fn check_for_unsequenced_reads(vis: &mut ReadVisitor<'_, '_>) {
188 let map = &vis.cx.tcx.hir();
189 let mut cur_id = vis.write_expr.hir_id;
191 let parent_id = map.get_parent_node(cur_id);
192 if parent_id == cur_id {
195 let parent_node = match map.find(parent_id) {
196 Some(parent) => parent,
200 let stop_early = match parent_node {
201 Node::Expr(expr) => check_expr(vis, expr),
202 Node::Stmt(stmt) => check_stmt(vis, stmt),
204 // We reached the top of the function, stop.
207 _ => StopEarly::KeepGoing,
210 StopEarly::Stop => break,
211 StopEarly::KeepGoing => {},
218 /// Whether to stop early for the loop in `check_for_unsequenced_reads`. (If
219 /// `check_expr` weren't an independent function, this would be unnecessary and
220 /// we could just use `break`).
226 fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr<'_>) -> StopEarly {
227 if expr.hir_id == vis.last_expr.hir_id {
228 return StopEarly::KeepGoing;
234 | ExprKind::MethodCall(..)
235 | ExprKind::Call(_, _)
236 | ExprKind::Assign(..)
237 | ExprKind::Index(_, _)
238 | ExprKind::Repeat(_, _)
239 | ExprKind::Struct(_, _, _) => {
240 walk_expr(vis, expr);
242 ExprKind::Binary(op, _, _) | ExprKind::AssignOp(op, _, _) => {
243 if op.node == BinOpKind::And || op.node == BinOpKind::Or {
244 // x && y and x || y always evaluate x first, so these are
245 // strictly sequenced.
247 walk_expr(vis, expr);
250 ExprKind::Closure(_, _, _, _, _) => {
253 // * `var` is defined in the closure body, in which case we've reached the top of the enclosing
254 // function and can stop, or
256 // * `var` is captured by the closure, in which case, because evaluating a closure does not evaluate
257 // its body, we don't necessarily have a write, so we need to stop to avoid generating false
260 // This is also the only place we need to stop early (grrr).
261 return StopEarly::Stop;
263 // All other expressions either have only one child or strictly
264 // sequence the evaluation order of their sub-expressions.
268 vis.last_expr = expr;
273 fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt<'_>) -> StopEarly {
275 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => check_expr(vis, expr),
276 // If the declaration is of a local variable, check its initializer
277 // expression if it has one. Otherwise, keep going.
278 StmtKind::Local(ref local) => local
281 .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr)),
282 _ => StopEarly::KeepGoing,
286 /// A visitor that looks for reads from a variable.
287 struct ReadVisitor<'a, 'tcx> {
288 cx: &'a LateContext<'tcx>,
289 /// The ID of the variable we're looking for.
291 /// The expressions where the write to the variable occurred (for reporting
293 write_expr: &'tcx Expr<'tcx>,
294 /// The last (highest in the AST) expression we've checked, so we know not
296 last_expr: &'tcx Expr<'tcx>,
299 impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> {
300 type Map = Map<'tcx>;
302 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
303 if expr.hir_id == self.last_expr.hir_id {
308 ExprKind::Path(ref qpath) => {
310 if let QPath::Resolved(None, ref path) = *qpath;
311 if path.segments.len() == 1;
312 if let def::Res::Local(local_id) = self.cx.qpath_res(qpath, expr.hir_id);
313 if local_id == self.var;
314 // Check that this is a read, not a write.
315 if !is_in_assignment_position(self.cx, expr);
319 EVAL_ORDER_DEPENDENCE,
321 "unsequenced read of a variable",
322 Some(self.write_expr.span),
323 "whether read occurs before this write depends on evaluation order"
328 // We're about to descend a closure. Since we don't know when (or
329 // if) the closure will be evaluated, any reads in it might not
330 // occur here (or ever). Like above, bail to avoid false positives.
331 ExprKind::Closure(_, _, _, _, _) |
333 // We want to avoid a false positive when a variable name occurs
334 // only to have its address taken, so we stop here. Technically,
335 // this misses some weird cases, eg.
339 // let a = foo(&{x = 1; x}, x);
343 ExprKind::AddrOf(_, _, _) => {
349 walk_expr(self, expr);
351 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
352 NestedVisitorMap::None
356 /// Returns `true` if `expr` is the LHS of an assignment, like `expr = ...`.
357 fn is_in_assignment_position(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
358 if let Some(parent) = get_parent_expr(cx, expr) {
359 if let ExprKind::Assign(ref lhs, ..) = parent.kind {
360 return lhs.hir_id == expr.hir_id;