1 use crate::utils::{get_parent_expr, span_lint, span_note_and_lint};
2 use if_chain::if_chain;
3 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_tool_lint, lint_array};
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.
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.
17 /// **Known problems:** Code which intentionally depends on the evaluation
18 /// order, or which is correct for any evaluation order.
27 /// // Unclear whether a is 1 or 2.
29 declare_clippy_lint! {
30 pub EVAL_ORDER_DEPENDENCE,
32 "whether a variable read occurs before a write depends on sub-expression evaluation order"
35 /// **What it does:** Checks for diverging calls that are not match arms or
38 /// **Why is this bad?** It is often confusing to read. In addition, the
39 /// sub-expression evaluation order for Rust is not well documented.
41 /// **Known problems:** Someone might want to use `some_bool || panic!()` as a
46 /// let a = b() || panic!() || c();
47 /// // `c()` is dead, `panic!()` is only called if `b()` returns `false`
48 /// let x = (a, b, c, panic!());
49 /// // can simply be replaced by `panic!()`
51 declare_clippy_lint! {
52 pub DIVERGING_SUB_EXPRESSION,
54 "whether an expression contains a diverging sub expression"
57 #[derive(Copy, Clone)]
58 pub struct EvalOrderDependence;
60 impl LintPass for EvalOrderDependence {
61 fn get_lints(&self) -> LintArray {
62 lint_array!(EVAL_ORDER_DEPENDENCE, DIVERGING_SUB_EXPRESSION)
66 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EvalOrderDependence {
67 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
68 // Find a write to a local variable.
70 ExprKind::Assign(ref lhs, _) | ExprKind::AssignOp(_, ref lhs, _) => {
71 if let ExprKind::Path(ref qpath) = lhs.node {
72 if let QPath::Resolved(_, ref path) = *qpath {
73 if path.segments.len() == 1 {
74 if let def::Def::Local(var) = cx.tables.qpath_def(qpath, lhs.hir_id) {
75 let mut visitor = ReadVisitor {
81 check_for_unsequenced_reads(&mut visitor);
90 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
92 StmtKind::Expr(ref e, _) | StmtKind::Semi(ref e, _) => DivergenceVisitor { cx }.maybe_walk_expr(e),
93 StmtKind::Decl(ref d, _) => {
94 if let DeclKind::Local(ref local) = d.node {
95 if let Local { init: Some(ref e), .. } = **local {
96 DivergenceVisitor { cx }.visit_expr(e);
104 struct DivergenceVisitor<'a, 'tcx: 'a> {
105 cx: &'a LateContext<'a, 'tcx>,
108 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
109 fn maybe_walk_expr(&mut self, e: &'tcx Expr) {
111 ExprKind::Closure(.., _) => {},
112 ExprKind::Match(ref e, ref arms, _) => {
115 if let Some(ref guard) = arm.guard {
117 Guard::If(if_expr) => self.visit_expr(if_expr),
120 // make sure top level arm expressions aren't linted
121 self.maybe_walk_expr(&*arm.body);
124 _ => walk_expr(self, e),
127 fn report_diverging_sub_expr(&mut self, e: &Expr) {
128 span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges");
132 impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> {
133 fn visit_expr(&mut self, e: &'tcx Expr) {
135 ExprKind::Continue(_) | ExprKind::Break(_, _) | ExprKind::Ret(_) => self.report_diverging_sub_expr(e),
136 ExprKind::Call(ref func, _) => {
137 let typ = self.cx.tables.expr_ty(func);
139 ty::FnDef(..) | ty::FnPtr(_) => {
140 let sig = typ.fn_sig(self.cx.tcx);
141 if let ty::Never = self.cx.tcx.erase_late_bound_regions(&sig).output().sty {
142 self.report_diverging_sub_expr(e);
148 ExprKind::MethodCall(..) => {
149 let borrowed_table = self.cx.tables;
150 if borrowed_table.expr_ty(e).is_never() {
151 self.report_diverging_sub_expr(e);
155 // do not lint expressions referencing objects of type `!`, as that required a
156 // diverging expression
160 self.maybe_walk_expr(e);
162 fn visit_block(&mut self, _: &'tcx Block) {
163 // don't continue over blocks, LateLintPass already does that
165 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
166 NestedVisitorMap::None
170 /// Walks up the AST from the given write expression (`vis.write_expr`) looking
171 /// for reads to the same variable that are unsequenced relative to the write.
173 /// This means reads for which there is a common ancestor between the read and
174 /// the write such that
176 /// * evaluating the ancestor necessarily evaluates both the read and the write (for example, `&x`
177 /// and `|| x = 1` don't necessarily evaluate `x`), and
179 /// * which one is evaluated first depends on the order of sub-expression evaluation. Blocks, `if`s,
180 /// loops, `match`es, and the short-circuiting logical operators are considered to have a defined
181 /// evaluation order.
183 /// When such a read is found, the lint is triggered.
184 fn check_for_unsequenced_reads(vis: &mut ReadVisitor<'_, '_>) {
185 let map = &vis.cx.tcx.hir();
186 let mut cur_id = vis.write_expr.id;
188 let parent_id = map.get_parent_node(cur_id);
189 if parent_id == cur_id {
192 let parent_node = match map.find(parent_id) {
193 Some(parent) => parent,
197 let stop_early = match parent_node {
198 Node::Expr(expr) => check_expr(vis, expr),
199 Node::Stmt(stmt) => check_stmt(vis, stmt),
201 // We reached the top of the function, stop.
204 _ => StopEarly::KeepGoing,
207 StopEarly::Stop => break,
208 StopEarly::KeepGoing => {},
215 /// Whether to stop early for the loop in `check_for_unsequenced_reads`. (If
216 /// `check_expr` weren't an independent function, this would be unnecessary and
217 /// we could just use `break`).
223 fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr) -> StopEarly {
224 if expr.id == vis.last_expr.id {
225 return StopEarly::KeepGoing;
231 | ExprKind::MethodCall(..)
232 | ExprKind::Call(_, _)
233 | ExprKind::Assign(_, _)
234 | ExprKind::Index(_, _)
235 | ExprKind::Repeat(_, _)
236 | ExprKind::Struct(_, _, _) => {
237 walk_expr(vis, expr);
239 ExprKind::Binary(op, _, _) | ExprKind::AssignOp(op, _, _) => {
240 if op.node == BinOpKind::And || op.node == BinOpKind::Or {
241 // x && y and x || y always evaluate x first, so these are
242 // strictly sequenced.
244 walk_expr(vis, expr);
247 ExprKind::Closure(_, _, _, _, _) => {
250 // * `var` is defined in the closure body, in which case we've reached the top of the enclosing
251 // function and can stop, or
253 // * `var` is captured by the closure, in which case, because evaluating a closure does not evaluate
254 // its body, we don't necessarily have a write, so we need to stop to avoid generating false
257 // This is also the only place we need to stop early (grrr).
258 return StopEarly::Stop;
260 // All other expressions either have only one child or strictly
261 // sequence the evaluation order of their sub-expressions.
265 vis.last_expr = expr;
270 fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt) -> StopEarly {
272 StmtKind::Expr(ref expr, _) | StmtKind::Semi(ref expr, _) => check_expr(vis, expr),
273 StmtKind::Decl(ref decl, _) => {
274 // If the declaration is of a local variable, check its initializer
275 // expression if it has one. Otherwise, keep going.
276 let local = match decl.node {
277 DeclKind::Local(ref local) => Some(local),
281 .and_then(|local| local.init.as_ref())
282 .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr))
287 /// A visitor that looks for reads from a variable.
288 struct ReadVisitor<'a, 'tcx: 'a> {
289 cx: &'a LateContext<'a, 'tcx>,
290 /// The id of the variable we're looking for.
292 /// The expressions where the write to the variable occurred (for reporting
294 write_expr: &'tcx Expr,
295 /// The last (highest in the AST) expression we've checked, so we know not
297 last_expr: &'tcx Expr,
300 impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> {
301 fn visit_expr(&mut self, expr: &'tcx Expr) {
302 if expr.id == self.last_expr.id {
307 ExprKind::Path(ref qpath) => {
309 if let QPath::Resolved(None, ref path) = *qpath;
310 if path.segments.len() == 1;
311 if let def::Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id);
312 if local_id == self.var;
313 // Check that this is a read, not a write.
314 if !is_in_assignment_position(self.cx, expr);
318 EVAL_ORDER_DEPENDENCE,
320 "unsequenced read of a variable",
321 self.write_expr.span,
322 "whether read occurs before this write depends on evaluation order"
327 // We're about to descend a closure. Since we don't know when (or
328 // if) the closure will be evaluated, any reads in it might not
329 // occur here (or ever). Like above, bail to avoid false positives.
330 ExprKind::Closure(_, _, _, _, _) |
332 // We want to avoid a false positive when a variable name occurs
333 // only to have its address taken, so we stop here. Technically,
334 // this misses some weird cases, eg.
338 // let a = foo(&{x = 1; x}, x);
342 ExprKind::AddrOf(_, _) => {
348 walk_expr(self, expr);
350 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
351 NestedVisitorMap::None
355 /// Returns true if `expr` is the LHS of an assignment, like `expr = ...`.
356 fn is_in_assignment_position(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
357 if let Some(parent) = get_parent_expr(cx, expr) {
358 if let ExprKind::Assign(ref lhs, _) = parent.node {
359 return lhs.id == expr.id;