1 use crate::utils::{get_parent_expr, span_lint, span_note_and_lint};
2 use if_chain::if_chain;
3 use rustc::declare_lint_pass;
4 use rustc::hir::map::Map;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
9 use rustc_session::declare_tool_lint;
11 declare_clippy_lint! {
12 /// **What it does:** 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?** It is often confusing to read. In addition, the
17 /// sub-expression evaluation order for Rust is not well documented.
19 /// **Known problems:** Code which intentionally depends on the evaluation
20 /// order, or which is correct for any evaluation order.
29 /// // Unclear whether a is 1 or 2.
31 pub EVAL_ORDER_DEPENDENCE,
33 "whether a variable read occurs before a write depends on sub-expression evaluation order"
36 declare_clippy_lint! {
37 /// **What it does:** Checks for diverging calls that are not match arms or
40 /// **Why is this bad?** It is often confusing to read. In addition, the
41 /// sub-expression evaluation order for Rust is not well documented.
43 /// **Known problems:** Someone might want to use `some_bool || panic!()` as a
48 /// # fn b() -> bool { true }
49 /// # fn c() -> bool { true }
50 /// let a = b() || panic!() || c();
51 /// // `c()` is dead, `panic!()` is only called if `b()` returns `false`
52 /// let x = (a, b, c, panic!());
53 /// // can simply be replaced by `panic!()`
55 pub DIVERGING_SUB_EXPRESSION,
57 "whether an expression contains a diverging sub expression"
60 declare_lint_pass!(EvalOrderDependence => [EVAL_ORDER_DEPENDENCE, DIVERGING_SUB_EXPRESSION]);
62 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EvalOrderDependence {
63 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
64 // Find a write to a local variable.
66 ExprKind::Assign(ref lhs, ..) | ExprKind::AssignOp(_, ref lhs, _) => {
67 if let ExprKind::Path(ref qpath) = lhs.kind {
68 if let QPath::Resolved(_, ref path) = *qpath {
69 if path.segments.len() == 1 {
70 if let def::Res::Local(var) = cx.tables.qpath_res(qpath, lhs.hir_id) {
71 let mut visitor = ReadVisitor {
77 check_for_unsequenced_reads(&mut visitor);
86 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt<'_>) {
88 StmtKind::Local(ref local) => {
89 if let Local { init: Some(ref e), .. } = **local {
90 DivergenceVisitor { cx }.visit_expr(e);
93 StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => DivergenceVisitor { cx }.maybe_walk_expr(e),
94 StmtKind::Item(..) => {},
99 struct DivergenceVisitor<'a, 'tcx> {
100 cx: &'a LateContext<'a, 'tcx>,
103 impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> {
104 fn maybe_walk_expr(&mut self, e: &'tcx Expr<'_>) {
106 ExprKind::Closure(..) => {},
107 ExprKind::Match(ref e, arms, _) => {
110 if let Some(ref guard) = arm.guard {
112 Guard::If(if_expr) => self.visit_expr(if_expr),
115 // make sure top level arm expressions aren't linted
116 self.maybe_walk_expr(&*arm.body);
119 _ => walk_expr(self, e),
122 fn report_diverging_sub_expr(&mut self, e: &Expr<'_>) {
123 span_lint(self.cx, DIVERGING_SUB_EXPRESSION, e.span, "sub-expression diverges");
127 impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> {
128 type Map = Map<'tcx>;
130 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
132 ExprKind::Continue(_) | ExprKind::Break(_, _) | ExprKind::Ret(_) => self.report_diverging_sub_expr(e),
133 ExprKind::Call(ref func, _) => {
134 let typ = self.cx.tables.expr_ty(func);
136 ty::FnDef(..) | ty::FnPtr(_) => {
137 let sig = typ.fn_sig(self.cx.tcx);
138 if let ty::Never = self.cx.tcx.erase_late_bound_regions(&sig).output().kind {
139 self.report_diverging_sub_expr(e);
145 ExprKind::MethodCall(..) => {
146 let borrowed_table = self.cx.tables;
147 if borrowed_table.expr_ty(e).is_never() {
148 self.report_diverging_sub_expr(e);
152 // do not lint expressions referencing objects of type `!`, as that required a
153 // diverging expression
157 self.maybe_walk_expr(e);
159 fn visit_block(&mut self, _: &'tcx Block<'_>) {
160 // don't continue over blocks, LateLintPass already does that
162 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
163 NestedVisitorMap::None
167 /// Walks up the AST from the given write expression (`vis.write_expr`) looking
168 /// for reads to the same variable that are unsequenced relative to the write.
170 /// This means reads for which there is a common ancestor between the read and
171 /// the write such that
173 /// * evaluating the ancestor necessarily evaluates both the read and the write (for example, `&x`
174 /// and `|| x = 1` don't necessarily evaluate `x`), and
176 /// * which one is evaluated first depends on the order of sub-expression evaluation. Blocks, `if`s,
177 /// loops, `match`es, and the short-circuiting logical operators are considered to have a defined
178 /// evaluation order.
180 /// When such a read is found, the lint is triggered.
181 fn check_for_unsequenced_reads(vis: &mut ReadVisitor<'_, '_>) {
182 let map = &vis.cx.tcx.hir();
183 let mut cur_id = vis.write_expr.hir_id;
185 let parent_id = map.get_parent_node(cur_id);
186 if parent_id == cur_id {
189 let parent_node = match map.find(parent_id) {
190 Some(parent) => parent,
194 let stop_early = match parent_node {
195 Node::Expr(expr) => check_expr(vis, expr),
196 Node::Stmt(stmt) => check_stmt(vis, stmt),
198 // We reached the top of the function, stop.
201 _ => StopEarly::KeepGoing,
204 StopEarly::Stop => break,
205 StopEarly::KeepGoing => {},
212 /// Whether to stop early for the loop in `check_for_unsequenced_reads`. (If
213 /// `check_expr` weren't an independent function, this would be unnecessary and
214 /// we could just use `break`).
220 fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr<'_>) -> StopEarly {
221 if expr.hir_id == vis.last_expr.hir_id {
222 return StopEarly::KeepGoing;
228 | ExprKind::MethodCall(..)
229 | ExprKind::Call(_, _)
230 | ExprKind::Assign(..)
231 | ExprKind::Index(_, _)
232 | ExprKind::Repeat(_, _)
233 | ExprKind::Struct(_, _, _) => {
234 walk_expr(vis, expr);
236 ExprKind::Binary(op, _, _) | ExprKind::AssignOp(op, _, _) => {
237 if op.node == BinOpKind::And || op.node == BinOpKind::Or {
238 // x && y and x || y always evaluate x first, so these are
239 // strictly sequenced.
241 walk_expr(vis, expr);
244 ExprKind::Closure(_, _, _, _, _) => {
247 // * `var` is defined in the closure body, in which case we've reached the top of the enclosing
248 // function and can stop, or
250 // * `var` is captured by the closure, in which case, because evaluating a closure does not evaluate
251 // its body, we don't necessarily have a write, so we need to stop to avoid generating false
254 // This is also the only place we need to stop early (grrr).
255 return StopEarly::Stop;
257 // All other expressions either have only one child or strictly
258 // sequence the evaluation order of their sub-expressions.
262 vis.last_expr = expr;
267 fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt<'_>) -> StopEarly {
269 StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => check_expr(vis, expr),
270 // If the declaration is of a local variable, check its initializer
271 // expression if it has one. Otherwise, keep going.
272 StmtKind::Local(ref local) => local
275 .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr)),
276 _ => StopEarly::KeepGoing,
280 /// A visitor that looks for reads from a variable.
281 struct ReadVisitor<'a, 'tcx> {
282 cx: &'a LateContext<'a, 'tcx>,
283 /// The ID of the variable we're looking for.
285 /// The expressions where the write to the variable occurred (for reporting
287 write_expr: &'tcx Expr<'tcx>,
288 /// The last (highest in the AST) expression we've checked, so we know not
290 last_expr: &'tcx Expr<'tcx>,
293 impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> {
294 type Map = Map<'tcx>;
296 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
297 if expr.hir_id == self.last_expr.hir_id {
302 ExprKind::Path(ref qpath) => {
304 if let QPath::Resolved(None, ref path) = *qpath;
305 if path.segments.len() == 1;
306 if let def::Res::Local(local_id) = self.cx.tables.qpath_res(qpath, expr.hir_id);
307 if local_id == self.var;
308 // Check that this is a read, not a write.
309 if !is_in_assignment_position(self.cx, expr);
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"
322 // We're about to descend a closure. Since we don't know when (or
323 // if) the closure will be evaluated, any reads in it might not
324 // occur here (or ever). Like above, bail to avoid false positives.
325 ExprKind::Closure(_, _, _, _, _) |
327 // We want to avoid a false positive when a variable name occurs
328 // only to have its address taken, so we stop here. Technically,
329 // this misses some weird cases, eg.
333 // let a = foo(&{x = 1; x}, x);
337 ExprKind::AddrOf(_, _, _) => {
343 walk_expr(self, expr);
345 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
346 NestedVisitorMap::None
350 /// Returns `true` if `expr` is the LHS of an assignment, like `expr = ...`.
351 fn is_in_assignment_position(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
352 if let Some(parent) = get_parent_expr(cx, expr) {
353 if let ExprKind::Assign(ref lhs, ..) = parent.kind {
354 return lhs.hir_id == expr.hir_id;