1 //! Utilities for evaluating whether eagerly evaluated expressions can be made lazy and vice versa.
3 //! Things to consider:
4 //! - has the expression side-effects?
5 //! - is the expression computationally expensive?
8 //! - unnecessary-lazy-evaluations
10 //! - option-if-let-else
12 use crate::ty::{all_predicates_of, is_copy};
13 use crate::visitors::is_const_evaluatable;
14 use rustc_hir::def::{DefKind, Res};
15 use rustc_hir::intravisit::{walk_expr, Visitor};
16 use rustc_hir::{def_id::DefId, Block, Expr, ExprKind, QPath, UnOp};
17 use rustc_lint::LateContext;
18 use rustc_middle::ty::{self, PredicateKind};
19 use rustc_span::{sym, Symbol};
23 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
24 enum EagernessSuggestion {
25 // The expression is cheap and should be evaluated eagerly
27 // The expression may be cheap, so don't suggested lazy evaluation; or the expression may not be safe to switch to
30 // The expression is likely expensive and should be evaluated lazily.
32 // The expression cannot be placed into a closure.
35 impl ops::BitOr for EagernessSuggestion {
37 fn bitor(self, rhs: Self) -> Self {
41 impl ops::BitOrAssign for EagernessSuggestion {
42 fn bitor_assign(&mut self, rhs: Self) {
47 /// Determine the eagerness of the given function call.
48 fn fn_eagerness<'tcx>(
49 cx: &LateContext<'tcx>,
52 args: &'tcx [Expr<'_>],
53 ) -> EagernessSuggestion {
54 use EagernessSuggestion::{Eager, Lazy, NoChange};
55 let name = name.as_str();
57 let ty = match cx.tcx.impl_of_method(fn_id) {
58 Some(id) => cx.tcx.type_of(id),
62 if (name.starts_with("as_") || name == "len" || name == "is_empty") && args.len() == 1 {
64 cx.tcx.crate_name(fn_id.krate),
65 sym::std | sym::core | sym::alloc | sym::proc_macro
71 } else if let ty::Adt(def, subs) = ty.kind() {
72 // Types where the only fields are generic types (or references to) with no trait bounds other
73 // than marker traits.
74 // Due to the limited operations on these types functions should be fairly cheap.
78 .flat_map(|v| v.fields.iter())
79 .any(|x| matches!(cx.tcx.type_of(x.did).peel_refs().kind(), ty::Param(_)))
80 && all_predicates_of(cx.tcx, fn_id).all(|(pred, _)| match pred.kind().skip_binder() {
81 PredicateKind::Trait(pred) => cx.tcx.trait_def(pred.trait_ref.def_id).is_marker,
84 && subs.types().all(|x| matches!(x.peel_refs().kind(), ty::Param(_)))
86 // Limit the function to either `(self) -> bool` or `(&self) -> bool`
87 match &**cx.tcx.fn_sig(fn_id).skip_binder().inputs_and_output {
88 [arg, res] if !arg.is_mutable_ptr() && arg.peel_refs() == ty && res.is_bool() => NoChange,
99 #[expect(clippy::too_many_lines)]
100 fn expr_eagerness<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> EagernessSuggestion {
101 struct V<'cx, 'tcx> {
102 cx: &'cx LateContext<'tcx>,
103 eagerness: EagernessSuggestion,
106 impl<'cx, 'tcx> Visitor<'tcx> for V<'cx, 'tcx> {
107 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
108 use EagernessSuggestion::{ForceNoChange, Lazy, NoChange};
109 if self.eagerness == ForceNoChange {
115 kind: ExprKind::Path(ref path),
120 ) => match self.cx.qpath_res(path, hir_id) {
121 Res::Def(DefKind::Ctor(..) | DefKind::Variant, _) | Res::SelfCtor(_) => (),
122 Res::Def(_, id) if self.cx.tcx.is_promotable_const_fn(id) => (),
123 // No need to walk the arguments here, `is_const_evaluatable` already did
124 Res::Def(..) if is_const_evaluatable(self.cx, e) => {
125 self.eagerness |= NoChange;
128 Res::Def(_, id) => match path {
129 QPath::Resolved(_, p) => {
130 self.eagerness |= fn_eagerness(self.cx, id, p.segments.last().unwrap().ident.name, args);
132 QPath::TypeRelative(_, name) => {
133 self.eagerness |= fn_eagerness(self.cx, id, name.ident.name, args);
135 QPath::LangItem(..) => self.eagerness = Lazy,
137 _ => self.eagerness = Lazy,
139 // No need to walk the arguments here, `is_const_evaluatable` already did
140 ExprKind::MethodCall(..) if is_const_evaluatable(self.cx, e) => {
141 self.eagerness |= NoChange;
144 ExprKind::MethodCall(name, args, _) => {
145 self.eagerness |= self
148 .type_dependent_def_id(e.hir_id)
149 .map_or(Lazy, |id| fn_eagerness(self.cx, id, name.ident.name, args));
151 ExprKind::Index(_, e) => {
152 let ty = self.cx.typeck_results().expr_ty_adjusted(e);
153 if is_copy(self.cx, ty) && !ty.is_ref() {
154 self.eagerness |= NoChange;
156 self.eagerness = Lazy;
160 // Dereferences should be cheap, but dereferencing a raw pointer earlier may not be safe.
161 ExprKind::Unary(UnOp::Deref, e) if !self.cx.typeck_results().expr_ty(e).is_unsafe_ptr() => (),
162 ExprKind::Unary(UnOp::Deref, _) => self.eagerness |= NoChange,
164 ExprKind::Unary(_, e)
166 self.cx.typeck_results().expr_ty(e).kind(),
167 ty::Bool | ty::Int(_) | ty::Uint(_),
169 ExprKind::Binary(_, lhs, rhs)
170 if self.cx.typeck_results().expr_ty(lhs).is_primitive()
171 && self.cx.typeck_results().expr_ty(rhs).is_primitive() => {},
173 // Can't be moved into a closure
175 | ExprKind::Continue(_)
177 | ExprKind::InlineAsm(_)
178 | ExprKind::Yield(..)
180 self.eagerness = ForceNoChange;
184 // Memory allocation, custom operator, loop, or call to an unknown function
186 | ExprKind::Unary(..)
187 | ExprKind::Binary(..)
189 | ExprKind::Call(..) => self.eagerness = Lazy,
191 ExprKind::ConstBlock(_)
197 | ExprKind::DropTemps(_)
200 | ExprKind::Match(..)
201 | ExprKind::Closure { .. }
202 | ExprKind::Field(..)
204 | ExprKind::AddrOf(..)
205 | ExprKind::Struct(..)
206 | ExprKind::Repeat(..)
207 | ExprKind::Block(Block { stmts: [], .. }, _) => (),
209 // Assignment might be to a local defined earlier, so don't eagerly evaluate.
210 // Blocks with multiple statements might be expensive, so don't eagerly evaluate.
211 // TODO: Actually check if either of these are true here.
212 ExprKind::Assign(..) | ExprKind::AssignOp(..) | ExprKind::Block(..) => self.eagerness |= NoChange,
220 eagerness: EagernessSuggestion::Eager,
226 /// Whether the given expression should be changed to evaluate eagerly
227 pub fn switch_to_eager_eval<'tcx>(cx: &'_ LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
228 expr_eagerness(cx, expr) == EagernessSuggestion::Eager
231 /// Whether the given expression should be changed to evaluate lazily
232 pub fn switch_to_lazy_eval<'tcx>(cx: &'_ LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
233 expr_eagerness(cx, expr) == EagernessSuggestion::Lazy