1 use rustc::hir::def_id::DefId;
2 use rustc::hir::intravisit::{Visitor, walk_expr, NestedVisitorMap};
6 use utils::{get_parent_expr, span_note_and_lint, span_lint};
8 /// **What it does:** Checks for a read and a write to the same variable where
9 /// whether the read occurs before or after the write depends on the evaluation
10 /// order of sub-expressions.
12 /// **Why is this bad?** It is often confusing to read. In addition, the
13 /// sub-expression evaluation order for Rust is not well documented.
15 /// **Known problems:** Code which intentionally depends on the evaluation
16 /// order, or which is correct for any evaluation order.
21 /// let a = {x = 1; 1} + x;
22 /// // Unclear whether a is 1 or 2.
25 pub EVAL_ORDER_DEPENDENCE,
27 "whether a variable read occurs before a write depends on sub-expression evaluation order"
30 /// **What it does:** Checks for diverging calls that are not match arms or
33 /// **Why is this bad?** It is often confusing to read. In addition, the
34 /// sub-expression evaluation order for Rust is not well documented.
36 /// **Known problems:** Someone might want to use `some_bool || panic!()` as a
41 /// let a = b() || panic!() || c();
42 /// // `c()` is dead, `panic!()` is only called if `b()` returns `false`
43 /// let x = (a, b, c, panic!());
44 /// // can simply be replaced by `panic!()`
47 pub DIVERGING_SUB_EXPRESSION,
49 "whether an expression contains a diverging sub expression"
52 #[derive(Copy, Clone)]
53 pub struct EvalOrderDependence;
55 impl LintPass for EvalOrderDependence {
56 fn get_lints(&self) -> LintArray {
57 lint_array!(EVAL_ORDER_DEPENDENCE, DIVERGING_SUB_EXPRESSION)
61 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EvalOrderDependence {
62 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
63 // Find a write to a local variable.
65 ExprAssign(ref lhs, _) |
66 ExprAssignOp(_, ref lhs, _) => {
67 if let ExprPath(ref qpath) = lhs.node {
68 if let QPath::Resolved(_, ref path) = *qpath {
69 if path.segments.len() == 1 {
70 let var = cx.tables.qpath_def(qpath, lhs.hir_id).def_id();
71 let mut visitor = ReadVisitor {
77 check_for_unsequenced_reads(&mut visitor);
85 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
88 StmtSemi(ref e, _) => DivergenceVisitor { cx: cx }.maybe_walk_expr(e),
89 StmtDecl(ref d, _) => {
90 if let DeclLocal(ref local) = d.node {
91 if let Local { init: Some(ref e), .. } = **local {
92 DivergenceVisitor { cx: cx }.visit_expr(e);
100 struct DivergenceVisitor<'a, 'tcx: 'a> {
101 cx: &'a LateContext<'a, 'tcx>,
104 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
105 fn maybe_walk_expr(&mut self, e: &'tcx Expr) {
107 ExprClosure(..) => {},
108 ExprMatch(ref e, ref arms, _) => {
111 if let Some(ref guard) = arm.guard {
112 self.visit_expr(guard);
114 // make sure top level arm expressions aren't linted
115 self.maybe_walk_expr(&*arm.body);
118 _ => walk_expr(self, e),
121 fn report_diverging_sub_expr(&mut self, e: &Expr) {
122 span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges");
126 impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> {
127 fn visit_expr(&mut self, e: &'tcx Expr) {
129 ExprAgain(_) | ExprBreak(_, _) | ExprRet(_) => self.report_diverging_sub_expr(e),
130 ExprCall(ref func, _) => {
131 let typ = self.cx.tables.expr_ty(func);
133 ty::TyFnDef(..) | ty::TyFnPtr(_) => {
134 let sig = typ.fn_sig(self.cx.tcx);
135 if let ty::TyNever = self.cx.tcx.erase_late_bound_regions(&sig).output().sty {
136 self.report_diverging_sub_expr(e);
142 ExprMethodCall(..) => {
143 let borrowed_table = self.cx.tables;
144 if borrowed_table.expr_ty(e).is_never() {
145 self.report_diverging_sub_expr(e);
149 // do not lint expressions referencing objects of type `!`, as that required a
150 // diverging expression
154 self.maybe_walk_expr(e);
156 fn visit_block(&mut self, _: &'tcx Block) {
157 // don't continue over blocks, LateLintPass already does that
159 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
160 NestedVisitorMap::None
164 /// Walks up the AST from the given write expression (`vis.write_expr`) looking
165 /// for reads to the same variable that are unsequenced relative to the write.
167 /// This means reads for which there is a common ancestor between the read and
168 /// the write such that
170 /// * evaluating the ancestor necessarily evaluates both the read and the write
171 /// (for example, `&x` and `|| x = 1` don't necessarily evaluate `x`), and
173 /// * which one is evaluated first depends on the order of sub-expression
174 /// evaluation. Blocks, `if`s, loops, `match`es, and the short-circuiting
175 /// logical operators are considered to have a defined evaluation order.
177 /// When such a read is found, the lint is triggered.
178 fn check_for_unsequenced_reads(vis: &mut ReadVisitor) {
179 let map = &vis.cx.tcx.hir;
180 let mut cur_id = vis.write_expr.id;
182 let parent_id = map.get_parent_node(cur_id);
183 if parent_id == cur_id {
186 let parent_node = match map.find(parent_id) {
187 Some(parent) => parent,
191 let stop_early = match parent_node {
192 map::Node::NodeExpr(expr) => check_expr(vis, expr),
193 map::Node::NodeStmt(stmt) => check_stmt(vis, stmt),
194 map::Node::NodeItem(_) => {
195 // We reached the top of the function, stop.
198 _ => StopEarly::KeepGoing,
201 StopEarly::Stop => break,
202 StopEarly::KeepGoing => {},
209 /// Whether to stop early for the loop in `check_for_unsequenced_reads`. (If
210 /// `check_expr` weren't an independent function, this would be unnecessary and
211 /// we could just use `break`).
217 fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr) -> StopEarly {
218 if expr.id == vis.last_expr.id {
219 return StopEarly::KeepGoing;
230 ExprStruct(_, _, _) => {
231 walk_expr(vis, expr);
233 ExprBinary(op, _, _) |
234 ExprAssignOp(op, _, _) => {
235 if op.node == BiAnd || op.node == BiOr {
236 // x && y and x || y always evaluate x first, so these are
237 // strictly sequenced.
239 walk_expr(vis, expr);
242 ExprClosure(_, _, _, _) => {
245 // * `var` is defined in the closure body, in which case we've
246 // reached the top of the enclosing function and can stop, or
248 // * `var` is captured by the closure, in which case, because
249 // evaluating a closure does not evaluate its body, we don't
250 // necessarily have a write, so we need to stop to avoid
251 // generating false positives.
253 // This is also the only place we need to stop early (grrr).
254 return StopEarly::Stop;
256 // All other expressions either have only one child or strictly
257 // sequence the evaluation order of their sub-expressions.
261 vis.last_expr = expr;
266 fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt) -> StopEarly {
268 StmtExpr(ref expr, _) |
269 StmtSemi(ref expr, _) => check_expr(vis, expr),
270 StmtDecl(ref decl, _) => {
271 // If the declaration is of a local variable, check its initializer
272 // expression if it has one. Otherwise, keep going.
273 let local = match decl.node {
274 DeclLocal(ref local) => Some(local),
277 local.and_then(|local| local.init.as_ref()).map_or(
278 StopEarly::KeepGoing,
279 |expr| check_expr(vis, expr),
285 /// A visitor that looks for reads from a variable.
286 struct ReadVisitor<'a, 'tcx: 'a> {
287 cx: &'a LateContext<'a, 'tcx>,
288 /// The id of the variable we're looking for.
290 /// The expressions where the write to the variable occurred (for reporting
292 write_expr: &'tcx Expr,
293 /// The last (highest in the AST) expression we've checked, so we know not
295 last_expr: &'tcx Expr,
298 impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> {
299 fn visit_expr(&mut self, expr: &'tcx Expr) {
300 if expr.id == self.last_expr.id {
305 ExprPath(ref qpath) => {
306 if let QPath::Resolved(None, ref path) = *qpath {
307 if path.segments.len() == 1 && self.cx.tables.qpath_def(qpath, expr.hir_id).def_id() == self.var {
308 if is_in_assignment_position(self.cx, expr) {
309 // This is a write, not a read.
313 EVAL_ORDER_DEPENDENCE,
315 "unsequenced read of a variable",
316 self.write_expr.span,
317 "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 ExprClosure(_, _, _, _) |
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 ExprAddrOf(_, _) => {
344 walk_expr(self, expr);
346 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
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 ExprAssign(ref lhs, _) = parent.node {
355 return lhs.id == expr.id;