1 use crate::ty::needs_ordered_drop;
2 use crate::{get_enclosing_block, path_to_local_id};
3 use core::ops::ControlFlow;
5 use rustc_hir::def::{CtorKind, DefKind, Res};
6 use rustc_hir::intravisit::{self, walk_block, walk_expr, Visitor};
8 Arm, Block, BlockCheckMode, Body, BodyId, Expr, ExprKind, HirId, ItemId, ItemKind, Let, Pat, QPath, Stmt, UnOp,
9 UnsafeSource, Unsafety,
11 use rustc_lint::LateContext;
12 use rustc_middle::hir::map::Map;
13 use rustc_middle::hir::nested_filter;
14 use rustc_middle::ty::adjustment::Adjust;
15 use rustc_middle::ty::{self, Ty, TypeckResults};
19 /// Trait for visitor functions to control whether or not to descend to child nodes. Implemented
20 /// for only two types. `()` always descends. `Descend` allows controlled descent.
22 fn descend(&self) -> bool;
25 use internal::Continue;
27 impl Continue for () {
28 fn descend(&self) -> bool {
33 /// Allows for controlled descent when using visitor functions. Use `()` instead when always
34 /// descending into child nodes.
35 #[derive(Clone, Copy)]
40 impl From<bool> for Descend {
41 fn from(from: bool) -> Self {
42 if from { Self::Yes } else { Self::No }
45 impl Continue for Descend {
46 fn descend(&self) -> bool {
47 matches!(self, Self::Yes)
51 /// Calls the given function once for each expression contained. This does not enter any bodies or
53 pub fn for_each_expr<'tcx, B, C: Continue>(
54 node: impl Visitable<'tcx>,
55 f: impl FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B, C>,
61 impl<'tcx, B, C: Continue, F: FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B, C>> Visitor<'tcx> for V<B, F> {
62 fn visit_expr(&mut self, e: &'tcx Expr<'tcx>) {
63 if self.res.is_some() {
67 ControlFlow::Continue(c) if c.descend() => walk_expr(self, e),
68 ControlFlow::Break(b) => self.res = Some(b),
69 ControlFlow::Continue(_) => (),
73 // Avoid unnecessary `walk_*` calls.
74 fn visit_ty(&mut self, _: &'tcx hir::Ty<'tcx>) {}
75 fn visit_pat(&mut self, _: &'tcx Pat<'tcx>) {}
76 fn visit_qpath(&mut self, _: &'tcx QPath<'tcx>, _: HirId, _: Span) {}
77 // Avoid monomorphising all `visit_*` functions.
78 fn visit_nested_item(&mut self, _: ItemId) {}
80 let mut v = V { f, res: None };
85 /// Convenience method for creating a `Visitor` with just `visit_expr` overridden and nested
86 /// bodies (i.e. closures) are visited.
87 /// If the callback returns `true`, the expr just provided to the callback is walked.
89 pub fn expr_visitor<'tcx>(cx: &LateContext<'tcx>, f: impl FnMut(&'tcx Expr<'tcx>) -> bool) -> impl Visitor<'tcx> {
94 impl<'tcx, F: FnMut(&'tcx Expr<'tcx>) -> bool> Visitor<'tcx> for V<'tcx, F> {
95 type NestedFilter = nested_filter::OnlyBodies;
96 fn nested_visit_map(&mut self) -> Self::Map {
100 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
102 walk_expr(self, expr);
106 V { hir: cx.tcx.hir(), f }
109 /// Convenience method for creating a `Visitor` with just `visit_expr` overridden and nested
110 /// bodies (i.e. closures) are not visited.
111 /// If the callback returns `true`, the expr just provided to the callback is walked.
113 pub fn expr_visitor_no_bodies<'tcx>(f: impl FnMut(&'tcx Expr<'tcx>) -> bool) -> impl Visitor<'tcx> {
115 impl<'tcx, F: FnMut(&'tcx Expr<'tcx>) -> bool> Visitor<'tcx> for V<F> {
116 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
125 /// returns `true` if expr contains match expr desugared from try
126 fn contains_try(expr: &hir::Expr<'_>) -> bool {
127 let mut found = false;
128 expr_visitor_no_bodies(|e| {
130 found = matches!(e.kind, hir::ExprKind::Match(_, _, hir::MatchSource::TryDesugar));
138 pub fn find_all_ret_expressions<'hir, F>(_cx: &LateContext<'_>, expr: &'hir hir::Expr<'hir>, callback: F) -> bool
140 F: FnMut(&'hir hir::Expr<'hir>) -> bool,
142 struct RetFinder<F> {
148 struct WithStmtGuarg<'a, F> {
149 val: &'a mut RetFinder<F>,
153 impl<F> RetFinder<F> {
154 fn inside_stmt(&mut self, in_stmt: bool) -> WithStmtGuarg<'_, F> {
155 let prev_in_stmt = std::mem::replace(&mut self.in_stmt, in_stmt);
163 impl<F> std::ops::Deref for WithStmtGuarg<'_, F> {
164 type Target = RetFinder<F>;
166 fn deref(&self) -> &Self::Target {
171 impl<F> std::ops::DerefMut for WithStmtGuarg<'_, F> {
172 fn deref_mut(&mut self) -> &mut Self::Target {
177 impl<F> Drop for WithStmtGuarg<'_, F> {
179 self.val.in_stmt = self.prev_in_stmt;
183 impl<'hir, F: FnMut(&'hir hir::Expr<'hir>) -> bool> intravisit::Visitor<'hir> for RetFinder<F> {
184 fn visit_stmt(&mut self, stmt: &'hir hir::Stmt<'_>) {
185 intravisit::walk_stmt(&mut *self.inside_stmt(true), stmt);
188 fn visit_expr(&mut self, expr: &'hir hir::Expr<'_>) {
194 hir::ExprKind::Ret(Some(expr)) => self.inside_stmt(false).visit_expr(expr),
195 _ => intravisit::walk_expr(self, expr),
199 hir::ExprKind::If(cond, then, else_opt) => {
200 self.inside_stmt(true).visit_expr(cond);
201 self.visit_expr(then);
202 if let Some(el) = else_opt {
206 hir::ExprKind::Match(cond, arms, _) => {
207 self.inside_stmt(true).visit_expr(cond);
209 self.visit_expr(arm.body);
212 hir::ExprKind::Block(..) => intravisit::walk_expr(self, expr),
213 hir::ExprKind::Ret(Some(expr)) => self.visit_expr(expr),
214 _ => self.failed |= !(self.cb)(expr),
220 !contains_try(expr) && {
221 let mut ret_finder = RetFinder {
226 ret_finder.visit_expr(expr);
231 /// A type which can be visited.
232 pub trait Visitable<'tcx> {
233 /// Calls the corresponding `visit_*` function on the visitor.
234 fn visit<V: Visitor<'tcx>>(self, visitor: &mut V);
236 macro_rules! visitable_ref {
237 ($t:ident, $f:ident) => {
238 impl<'tcx> Visitable<'tcx> for &'tcx $t<'tcx> {
239 fn visit<V: Visitor<'tcx>>(self, visitor: &mut V) {
245 visitable_ref!(Arm, visit_arm);
246 visitable_ref!(Block, visit_block);
247 visitable_ref!(Body, visit_body);
248 visitable_ref!(Expr, visit_expr);
249 visitable_ref!(Stmt, visit_stmt);
251 // impl<'tcx, I: IntoIterator> Visitable<'tcx> for I
253 // I::Item: Visitable<'tcx>,
255 // fn visit<V: Visitor<'tcx>>(self, visitor: &mut V) {
262 /// Checks if the given resolved path is used in the given body.
263 pub fn is_res_used(cx: &LateContext<'_>, res: Res, body: BodyId) -> bool {
264 let mut found = false;
265 expr_visitor(cx, |e| {
270 if let ExprKind::Path(p) = &e.kind {
271 if cx.qpath_res(p, e.hir_id) == res {
277 .visit_expr(cx.tcx.hir().body(body).value);
281 /// Checks if the given local is used.
282 pub fn is_local_used<'tcx>(cx: &LateContext<'tcx>, visitable: impl Visitable<'tcx>, id: HirId) -> bool {
283 let mut is_used = false;
284 let mut visitor = expr_visitor(cx, |expr| {
286 is_used = path_to_local_id(expr, id);
290 visitable.visit(&mut visitor);
295 /// Checks if the given expression is a constant.
296 pub fn is_const_evaluatable<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool {
298 cx: &'a LateContext<'tcx>,
301 impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> {
302 type NestedFilter = nested_filter::OnlyBodies;
303 fn nested_visit_map(&mut self) -> Self::Map {
307 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
312 ExprKind::ConstBlock(_) => return,
315 kind: ExprKind::Path(ref p),
322 .qpath_res(p, hir_id)
324 .map_or(false, |id| self.cx.tcx.is_const_fn_raw(id)) => {},
325 ExprKind::MethodCall(..)
329 .type_dependent_def_id(e.hir_id)
330 .map_or(false, |id| self.cx.tcx.is_const_fn_raw(id)) => {},
331 ExprKind::Binary(_, lhs, rhs)
332 if self.cx.typeck_results().expr_ty(lhs).peel_refs().is_primitive_ty()
333 && self.cx.typeck_results().expr_ty(rhs).peel_refs().is_primitive_ty() => {},
334 ExprKind::Unary(UnOp::Deref, e) if self.cx.typeck_results().expr_ty(e).is_ref() => (),
335 ExprKind::Unary(_, e) if self.cx.typeck_results().expr_ty(e).peel_refs().is_primitive_ty() => (),
336 ExprKind::Index(base, _)
338 self.cx.typeck_results().expr_ty(base).peel_refs().kind(),
339 ty::Slice(_) | ty::Array(..)
341 ExprKind::Path(ref p)
343 self.cx.qpath_res(p, e.hir_id),
346 | DefKind::AssocConst
348 | DefKind::ConstParam
358 | ExprKind::Block(..)
360 | ExprKind::DropTemps(_)
361 | ExprKind::Field(..)
365 | ExprKind::Match(..)
366 | ExprKind::Repeat(..)
367 | ExprKind::Struct(..)
369 | ExprKind::Type(..) => (),
372 self.is_const = false;
380 let mut v = V { cx, is_const: true };
385 /// Checks if the given expression performs an unsafe operation outside of an unsafe block.
386 pub fn is_expr_unsafe<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool {
388 cx: &'a LateContext<'tcx>,
391 impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> {
392 type NestedFilter = nested_filter::OnlyBodies;
393 fn nested_visit_map(&mut self) -> Self::Map {
396 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
401 ExprKind::Unary(UnOp::Deref, e) if self.cx.typeck_results().expr_ty(e).is_unsafe_ptr() => {
402 self.is_unsafe = true;
404 ExprKind::MethodCall(..)
408 .type_dependent_def_id(e.hir_id)
409 .map_or(false, |id| self.cx.tcx.fn_sig(id).unsafety() == Unsafety::Unsafe) =>
411 self.is_unsafe = true;
413 ExprKind::Call(func, _) => match *self.cx.typeck_results().expr_ty(func).peel_refs().kind() {
414 ty::FnDef(id, _) if self.cx.tcx.fn_sig(id).unsafety() == Unsafety::Unsafe => self.is_unsafe = true,
415 ty::FnPtr(sig) if sig.unsafety() == Unsafety::Unsafe => self.is_unsafe = true,
416 _ => walk_expr(self, e),
418 ExprKind::Path(ref p)
421 .qpath_res(p, e.hir_id)
423 .map_or(false, |id| self.cx.tcx.is_mutable_static(id)) =>
425 self.is_unsafe = true;
427 _ => walk_expr(self, e),
430 fn visit_block(&mut self, b: &'tcx Block<'_>) {
431 if !matches!(b.rules, BlockCheckMode::UnsafeBlock(_)) {
435 fn visit_nested_item(&mut self, id: ItemId) {
436 if let ItemKind::Impl(i) = &self.cx.tcx.hir().item(id).kind {
437 self.is_unsafe = i.unsafety == Unsafety::Unsafe;
441 let mut v = V { cx, is_unsafe: false };
446 /// Checks if the given expression contains an unsafe block
447 pub fn contains_unsafe_block<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) -> bool {
448 struct V<'cx, 'tcx> {
449 cx: &'cx LateContext<'tcx>,
452 impl<'tcx> Visitor<'tcx> for V<'_, 'tcx> {
453 type NestedFilter = nested_filter::OnlyBodies;
454 fn nested_visit_map(&mut self) -> Self::Map {
458 fn visit_block(&mut self, b: &'tcx Block<'_>) {
459 if self.found_unsafe {
462 if b.rules == BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided) {
463 self.found_unsafe = true;
477 /// Runs the given function for each sub-expression producing the final value consumed by the parent
478 /// of the give expression.
480 /// e.g. for the following expression
488 /// this will pass both `f(0)` and `1+1` to the given function.
489 pub fn for_each_value_source<'tcx, B>(
491 f: &mut impl FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>,
492 ) -> ControlFlow<B> {
494 ExprKind::Block(Block { expr: Some(e), .. }, _) => for_each_value_source(e, f),
495 ExprKind::Match(_, arms, _) => {
497 for_each_value_source(arm.body, f)?;
499 ControlFlow::Continue(())
501 ExprKind::If(_, if_expr, Some(else_expr)) => {
502 for_each_value_source(if_expr, f)?;
503 for_each_value_source(else_expr, f)
505 ExprKind::DropTemps(e) => for_each_value_source(e, f),
510 /// Runs the given function for each path expression referencing the given local which occur after
511 /// the given expression.
512 pub fn for_each_local_use_after_expr<'tcx, B>(
513 cx: &LateContext<'tcx>,
516 f: impl FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>,
517 ) -> ControlFlow<B> {
518 struct V<'cx, 'tcx, F, B> {
519 cx: &'cx LateContext<'tcx>,
526 impl<'cx, 'tcx, F: FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>, B> Visitor<'tcx> for V<'cx, 'tcx, F, B> {
527 type NestedFilter = nested_filter::OnlyBodies;
528 fn nested_visit_map(&mut self) -> Self::Map {
532 fn visit_expr(&mut self, e: &'tcx Expr<'tcx>) {
534 if e.hir_id == self.expr_id {
541 if self.res.is_break() {
544 if path_to_local_id(e, self.local_id) {
545 self.res = (self.f)(e);
552 if let Some(b) = get_enclosing_block(cx, local_id) {
558 res: ControlFlow::Continue(()),
564 ControlFlow::Continue(())
568 // Calls the given function for every unconsumed temporary created by the expression. Note the
569 // function is only guaranteed to be called for types which need to be dropped, but it may be called
571 #[allow(clippy::too_many_lines)]
572 pub fn for_each_unconsumed_temporary<'tcx, B>(
573 cx: &LateContext<'tcx>,
575 mut f: impl FnMut(Ty<'tcx>) -> ControlFlow<B>,
576 ) -> ControlFlow<B> {
577 // Todo: Handle partially consumed values.
579 typeck: &'tcx TypeckResults<'tcx>,
582 f: &mut impl FnMut(Ty<'tcx>) -> ControlFlow<B>,
583 ) -> ControlFlow<B> {
586 typeck.expr_adjustments(e),
587 [adjust, ..] if matches!(adjust.kind, Adjust::Borrow(_) | Adjust::Deref(_))
591 ExprKind::Path(QPath::Resolved(None, p))
592 if matches!(p.res, Res::Def(DefKind::Ctor(_, CtorKind::Const), _)) =>
594 f(typeck.expr_ty(e))?;
597 | ExprKind::Unary(UnOp::Deref, _)
598 | ExprKind::Index(..)
599 | ExprKind::Field(..)
600 | ExprKind::AddrOf(..) => (),
601 _ => f(typeck.expr_ty(e))?,
605 ExprKind::AddrOf(_, _, e)
606 | ExprKind::Field(e, _)
607 | ExprKind::Unary(UnOp::Deref, e)
608 | ExprKind::Match(e, ..)
609 | ExprKind::Let(&Let { init: e, .. }) => {
610 helper(typeck, false, e, f)?;
612 ExprKind::Block(&Block { expr: Some(e), .. }, _)
614 | ExprKind::Cast(e, _)
615 | ExprKind::Unary(_, e) => {
616 helper(typeck, true, e, f)?;
618 ExprKind::Call(callee, args) => {
619 helper(typeck, true, callee, f)?;
621 helper(typeck, true, arg, f)?;
624 ExprKind::MethodCall(_, receiver, args, _) => {
625 helper(typeck, true, receiver, f)?;
627 helper(typeck, true, arg, f)?;
630 ExprKind::Tup(args) | ExprKind::Array(args) => {
632 helper(typeck, true, arg, f)?;
635 ExprKind::Index(borrowed, consumed)
636 | ExprKind::Assign(borrowed, consumed, _)
637 | ExprKind::AssignOp(_, borrowed, consumed) => {
638 helper(typeck, false, borrowed, f)?;
639 helper(typeck, true, consumed, f)?;
641 ExprKind::Binary(_, lhs, rhs) => {
642 helper(typeck, true, lhs, f)?;
643 helper(typeck, true, rhs, f)?;
645 ExprKind::Struct(_, fields, default) => {
646 for field in fields {
647 helper(typeck, true, field.expr, f)?;
649 if let Some(default) = default {
650 helper(typeck, false, default, f)?;
653 ExprKind::If(cond, then, else_expr) => {
654 helper(typeck, true, cond, f)?;
655 helper(typeck, true, then, f)?;
656 if let Some(else_expr) = else_expr {
657 helper(typeck, true, else_expr, f)?;
660 ExprKind::Type(e, _) => {
661 helper(typeck, consume, e, f)?;
664 // Either drops temporaries, jumps out of the current expression, or has no sub expression.
665 ExprKind::DropTemps(_)
667 | ExprKind::Break(..)
668 | ExprKind::Yield(..)
669 | ExprKind::Block(..)
671 | ExprKind::Repeat(..)
673 | ExprKind::ConstBlock(_)
674 | ExprKind::Closure { .. }
676 | ExprKind::Continue(_)
677 | ExprKind::InlineAsm(_)
678 | ExprKind::Err => (),
680 ControlFlow::Continue(())
682 helper(cx.typeck_results(), true, e, &mut f)
685 pub fn any_temporaries_need_ordered_drop<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) -> bool {
686 for_each_unconsumed_temporary(cx, e, |ty| {
687 if needs_ordered_drop(cx, ty) {
688 ControlFlow::Break(())
690 ControlFlow::Continue(())
696 /// Runs the given function for each path expression referencing the given local which occur after
697 /// the given expression.
698 pub fn for_each_local_assignment<'tcx, B>(
699 cx: &LateContext<'tcx>,
701 f: impl FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>,
702 ) -> ControlFlow<B> {
703 struct V<'cx, 'tcx, F, B> {
704 cx: &'cx LateContext<'tcx>,
709 impl<'cx, 'tcx, F: FnMut(&'tcx Expr<'tcx>) -> ControlFlow<B>, B> Visitor<'tcx> for V<'cx, 'tcx, F, B> {
710 type NestedFilter = nested_filter::OnlyBodies;
711 fn nested_visit_map(&mut self) -> Self::Map {
715 fn visit_expr(&mut self, e: &'tcx Expr<'tcx>) {
716 if let ExprKind::Assign(lhs, rhs, _) = e.kind
717 && self.res.is_continue()
718 && path_to_local_id(lhs, self.local_id)
720 self.res = (self.f)(rhs);
721 self.visit_expr(rhs);
728 if let Some(b) = get_enclosing_block(cx, local_id) {
732 res: ControlFlow::Continue(()),
738 ControlFlow::Continue(())