1use crate::consts::ConstEvalCtxt;
13use crate::sym;
14use crate::ty::all_clauses_of;
15use crate::visitors::{Visitable as _, is_const_evaluatable};
16use core::ops::ControlFlow::{self, Break, Continue};
17use rustc_hir::def::{DefKind, Res};
18use rustc_hir::def_id::DefId;
19use rustc_hir::intravisit::{Visitor, walk_expr};
20use rustc_hir::{BinOpKind, Block, Expr, ExprKind, QPath, UnOp};
21use rustc_lint::LateContext;
22use rustc_middle::ty::adjustment::{Adjust, DerefAdjustKind};
23use rustc_middle::ty::{self, TyCtxt};
24use rustc_span::Symbol;
25use std::{cmp, ops};
26
27#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
28enum EagernessSuggestion {
29 Eager,
31 NoChange,
34 Lazy,
36 ForceNoChange,
38}
39impl ops::BitOr for EagernessSuggestion {
40 type Output = Self;
41 fn bitor(self, rhs: Self) -> Self {
42 cmp::max(self, rhs)
43 }
44}
45impl ops::BitOrAssign for EagernessSuggestion {
46 fn bitor_assign(&mut self, rhs: Self) {
47 *self = *self | rhs;
48 }
49}
50
51fn fn_eagerness(tcx: TyCtxt<'_>, fn_id: DefId, name: Symbol, have_one_arg: bool) -> EagernessSuggestion {
53 use EagernessSuggestion::{Eager, Lazy, NoChange};
54
55 let ty = match tcx.impl_of_assoc(fn_id) {
56 Some(id) => tcx.type_of(id).instantiate_identity().skip_norm_wip(),
57 None => return Lazy,
58 };
59
60 if (matches!(name, sym::is_empty | sym::len) || name.as_str().starts_with("as_")) && have_one_arg {
61 if matches!(
62 tcx.crate_name(fn_id.krate),
63 sym::std | sym::core | sym::alloc | sym::proc_macro
64 ) {
65 Eager
66 } else {
67 NoChange
68 }
69 } else if let ty::Adt(def, subs) = ty.kind() {
70 if def.variants().iter().flat_map(|v| v.fields.iter()).any(|x| {
74 matches!(
75 tcx.type_of(x.did)
76 .instantiate_identity()
77 .skip_norm_wip()
78 .peel_refs()
79 .kind(),
80 ty::Param(_)
81 )
82 }) && all_clauses_of(tcx, fn_id).all(|(clause, _)| match clause.kind().skip_binder() {
83 ty::ClauseKind::Trait(pred) => tcx.trait_def(pred.trait_ref.def_id).is_marker,
84 _ => true,
85 }) && subs.types().all(|x| matches!(x.peel_refs().kind(), ty::Param(_)))
86 {
87 match &**tcx
89 .fn_sig(fn_id)
90 .instantiate_identity()
91 .skip_norm_wip()
92 .skip_binder()
93 .inputs_and_output
94 {
95 [arg, res] if !arg.is_mutable_ptr() && arg.peel_refs() == ty && res.is_bool() => NoChange,
96 _ => Lazy,
97 }
98 } else {
99 Lazy
100 }
101 } else {
102 Lazy
103 }
104}
105
106fn res_has_significant_drop(res: Res, ecx: &ConstEvalCtxt<'_>, e: &Expr<'_>) -> bool {
107 if let Res::Def(DefKind::Ctor(..) | DefKind::Variant | DefKind::Enum | DefKind::Struct, _)
108 | Res::SelfCtor(_)
109 | Res::SelfTyAlias { .. } = res
110 {
111 ecx.typeck.expr_ty(e).has_significant_drop(ecx.tcx, ecx.typing_env)
112 } else {
113 false
114 }
115}
116
117struct ExprEagernessVisitor<'tcx> {
118 ecx: ConstEvalCtxt<'tcx>,
119 eagerness: EagernessSuggestion,
120}
121impl<'tcx> ExprEagernessVisitor<'tcx> {
122 fn visit_unary(&mut self, op: UnOp, e: &'tcx Expr<'tcx>) -> ControlFlow<()> {
123 use EagernessSuggestion::{Lazy, NoChange};
124
125 let ty = self.ecx.typeck.expr_ty(e).kind();
126 let (deref_ty, deref) = match ty {
127 &ty::Ref(_, ty, _) => {
128 if op != UnOp::Deref {
130 self.eagerness |= NoChange;
131 }
132 (ty.kind(), true)
133 },
134 ty => (ty, false),
135 };
136 match op {
137 UnOp::Neg => match *deref_ty {
138 ty::Int(_) => {
139 if self.ecx.eval_deref(e, deref).is_some() {
140 return Continue(());
142 }
143 self.eagerness |= NoChange;
145 },
146 ty::Float(_) => {},
147 _ => self.eagerness = Lazy,
148 },
149 UnOp::Deref => match *ty {
150 ty::Adt(def, _) if def.is_box() => {},
151 ty::Ref(..) => {},
152 _ => self.eagerness |= NoChange,
156 },
157 UnOp::Not => match *deref_ty {
158 ty::Int(_) | ty::Uint(_) | ty::Bool => {},
159 _ => self.eagerness |= NoChange,
160 },
161 }
162 self.visit_expr(e)
163 }
164
165 fn visit_binary(&mut self, op: BinOpKind, lhs: &'tcx Expr<'tcx>, rhs: &'tcx Expr<'tcx>) -> ControlFlow<()> {
166 use EagernessSuggestion::{Lazy, NoChange};
167
168 let lhs_ty = self.ecx.typeck.expr_ty(lhs);
169 let (lhs_ty, lhs_deref) = match *lhs_ty.kind() {
170 ty::Ref(_, lhs_ty, _) => {
171 self.eagerness |= NoChange;
173 (lhs_ty, true)
174 },
175 _ => (lhs_ty, false),
176 };
177 let rhs_ty = self.ecx.typeck.expr_ty(rhs);
178 let (rhs_ty, rhs_deref) = match *rhs_ty.kind() {
179 ty::Ref(_, rhs_ty, _) => {
180 self.eagerness |= NoChange;
182 (rhs_ty, true)
183 },
184 _ => (rhs_ty, false),
185 };
186
187 if let BinOpKind::Eq | BinOpKind::Ne | BinOpKind::Lt | BinOpKind::Le | BinOpKind::Gt | BinOpKind::Ge = op {
188 if lhs_deref == rhs_deref {
189 let mut lhs_ty = lhs_ty;
190 let mut rhs_ty = rhs_ty;
191 while let ty::Ref(_, lhs, _) = *lhs_ty.kind()
192 && let ty::Ref(_, rhs, _) = *rhs_ty.kind()
193 {
194 lhs_ty = lhs;
195 rhs_ty = rhs;
196 }
197 match *lhs_ty.kind() {
198 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) if lhs_ty == rhs_ty => {},
199 ty::RawPtr(..) if rhs_ty.is_raw_ptr() => {},
200 _ => self.eagerness = Lazy,
201 }
202 } else {
203 self.eagerness = Lazy;
204 }
205 } else if let Some((is_signed, ty)) = match (lhs_ty.kind(), rhs_ty.kind()) {
206 (&ty::Int(ty), ty::Int(_) | ty::Uint(_)) => Some((true, ty)),
210 (&ty::Uint(ty), ty::Int(_) | ty::Uint(_)) => Some((false, ty.to_signed())),
211 (ty::Float(_), ty::Float(_)) | (ty::Bool, ty::Bool) => None,
212 _ => {
213 self.eagerness = Lazy;
214 None
215 },
216 } {
217 match (op, is_signed) {
221 (BinOpKind::Div | BinOpKind::Rem, true) if let Some(rhs_val) = self.ecx.eval_deref(rhs, rhs_deref) => {
222 if rhs_val.to_int(self.ecx.tcx, ty) == Some(-1) {
223 if self.ecx.eval_deref(lhs, lhs_deref).is_some() {
224 return Continue(());
225 }
226 self.eagerness |= NoChange;
228 }
229 return self.visit_expr(rhs);
230 },
231 (BinOpKind::Add | BinOpKind::Sub | BinOpKind::Mul, _)
232 if self.ecx.eval_deref(rhs, rhs_deref).is_some() =>
233 {
234 return if self.ecx.eval_deref(lhs, lhs_deref).is_some() {
235 Continue(())
236 } else {
237 self.eagerness |= NoChange;
239 self.visit_expr(lhs)
240 };
241 },
242 (BinOpKind::Div | BinOpKind::Rem, false) | (BinOpKind::Shl | BinOpKind::Shr, _)
243 if self.ecx.eval_deref(rhs, rhs_deref).is_some() =>
244 {
245 return self.visit_expr(lhs);
246 },
247 (BinOpKind::Or | BinOpKind::And | BinOpKind::BitAnd | BinOpKind::BitOr | BinOpKind::BitXor, _) => {},
248 _ => {
249 self.eagerness |= NoChange;
251 },
252 }
253 }
254 (lhs, rhs).visit(self)
255 }
256}
257impl<'tcx> Visitor<'tcx> for ExprEagernessVisitor<'tcx> {
258 type Result = ControlFlow<()>;
259
260 #[expect(clippy::too_many_lines)]
261 fn visit_expr(&mut self, e: &'tcx Expr<'_>) -> Self::Result {
262 use EagernessSuggestion::{ForceNoChange, Lazy, NoChange};
263
264 if self
267 .ecx
268 .typeck
269 .expr_adjustments(e)
270 .iter()
271 .any(|adj| matches!(adj.kind, Adjust::Deref(DerefAdjustKind::Overloaded(_))))
272 {
273 self.eagerness |= NoChange;
274 }
275
276 match e.kind {
277 ExprKind::Call(
278 &Expr {
279 kind: ExprKind::Path(ref path),
280 hir_id,
281 ..
282 },
283 args,
284 ) => match self.ecx.typeck.qpath_res(path, hir_id) {
285 res @ (Res::Def(DefKind::Ctor(..) | DefKind::Variant, _) | Res::SelfCtor(_)) => {
286 if res_has_significant_drop(res, &self.ecx, e) {
287 self.eagerness = ForceNoChange;
288 return Break(());
289 }
290 },
291 Res::Def(_, id) if self.ecx.tcx.is_promotable_const_fn(id) => (),
292 Res::Def(..) if is_const_evaluatable(self.ecx.tcx, self.ecx.typeck, e) => {
294 self.eagerness |= NoChange;
295 return Break(());
296 },
297 Res::Def(_, id) => match path {
298 QPath::Resolved(_, p) => {
299 self.eagerness |= fn_eagerness(
300 self.ecx.tcx,
301 id,
302 p.segments.last().unwrap().ident.name,
303 !args.is_empty(),
304 );
305 },
306 QPath::TypeRelative(_, name) => {
307 self.eagerness |= fn_eagerness(self.ecx.tcx, id, name.ident.name, !args.is_empty());
308 },
309 },
310 _ => self.eagerness = Lazy,
311 },
312 ExprKind::MethodCall(..) if is_const_evaluatable(self.ecx.tcx, self.ecx.typeck, e) => {
314 self.eagerness |= NoChange;
315 return Break(());
316 },
317 #[expect(clippy::match_same_arms)] ExprKind::Struct(path, ..) => {
319 if res_has_significant_drop(self.ecx.typeck.qpath_res(path, e.hir_id), &self.ecx, e) {
320 self.eagerness = ForceNoChange;
321 return Break(());
322 }
323 },
324 ExprKind::Path(ref path) => {
325 if res_has_significant_drop(self.ecx.typeck.qpath_res(path, e.hir_id), &self.ecx, e) {
326 self.eagerness = ForceNoChange;
327 return Break(());
328 }
329 },
330 ExprKind::MethodCall(name, ..) => {
331 self.eagerness |= self
332 .ecx
333 .typeck
334 .type_dependent_def_id(e.hir_id)
335 .map_or(Lazy, |id| fn_eagerness(self.ecx.tcx, id, name.ident.name, true));
336 },
337 ExprKind::Index(_, e, _) => {
338 let ty = self.ecx.typeck.expr_ty_adjusted(e);
339 if self.ecx.tcx.type_is_copy_modulo_regions(self.ecx.typing_env, ty) && !ty.is_ref() {
340 self.eagerness |= NoChange;
341 } else {
342 self.eagerness = Lazy;
343 }
344 },
345
346 ExprKind::Unary(op, e) => return self.visit_unary(op, e),
347 ExprKind::Binary(op, lhs, rhs) => return self.visit_binary(op.node, lhs, rhs),
348
349 ExprKind::Break(..)
351 | ExprKind::Continue(_)
352 | ExprKind::Ret(_)
353 | ExprKind::Become(_)
354 | ExprKind::InlineAsm(_)
355 | ExprKind::Yield(..)
356 | ExprKind::Err(_) => {
357 self.eagerness = ForceNoChange;
358 return Break(());
359 },
360
361 ExprKind::Loop(..) | ExprKind::Call(..) => {
362 self.eagerness = Lazy;
363 },
364
365 ExprKind::ConstBlock(_)
366 | ExprKind::Array(_)
367 | ExprKind::Tup(_)
368 | ExprKind::Use(..)
369 | ExprKind::Lit(_)
370 | ExprKind::Cast(..)
371 | ExprKind::Type(..)
372 | ExprKind::DropTemps(_)
373 | ExprKind::Let(..)
374 | ExprKind::If(..)
375 | ExprKind::Match(..)
376 | ExprKind::Closure { .. }
377 | ExprKind::Field(..)
378 | ExprKind::AddrOf(..)
379 | ExprKind::Repeat(..)
380 | ExprKind::Block(Block { stmts: [], .. }, _)
381 | ExprKind::OffsetOf(..)
382 | ExprKind::UnsafeBinderCast(..) => (),
383
384 ExprKind::Assign(..) | ExprKind::AssignOp(..) | ExprKind::Block(..) => self.eagerness |= NoChange,
388 }
389 walk_expr(self, e)
390 }
391}
392
393fn expr_eagerness<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> EagernessSuggestion {
394 let mut v = ExprEagernessVisitor {
395 ecx: ConstEvalCtxt::new(cx),
396 eagerness: EagernessSuggestion::Eager,
397 };
398 let _ = v.visit_expr(e);
399 v.eagerness
400}
401
402pub fn switch_to_eager_eval<'tcx>(cx: &'_ LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
404 expr_eagerness(cx, expr) == EagernessSuggestion::Eager
405}
406
407pub fn switch_to_lazy_eval<'tcx>(cx: &'_ LateContext<'tcx>, expr: &'tcx Expr<'_>) -> bool {
409 expr_eagerness(cx, expr) == EagernessSuggestion::Lazy
410}