1#![expect(clippy::float_cmp)]
6
7use crate::res::MaybeDef as _;
8use crate::source::{SpanExt as _, walk_span_to_context};
9use crate::{clip, is_direct_expn_of, sext, sym, unsext};
10
11use rustc_abi::Size;
12use rustc_apfloat::Float as _;
13use rustc_apfloat::ieee::{Half, Quad};
14use rustc_ast::ast::{LitFloatType, LitKind};
15use rustc_hir::def::{DefKind, Res};
16use rustc_hir::{
17 BinOpKind, Block, ConstArgKind, ConstBlock, ConstItemRhs, Expr, ExprKind, HirId, PatExpr, PatExprKind, QPath,
18 TyKind, UnOp,
19};
20use rustc_lexer::{FrontmatterAllowed, tokenize};
21use rustc_lint::LateContext;
22use rustc_middle::mir::interpret::{Scalar, alloc_range};
23use rustc_middle::mir::{self, ConstValue};
24use rustc_middle::ty::{self, FloatTy, IntTy, ScalarInt, Ty, TyCtxt, TypeckResults, UintTy};
25use rustc_span::{Symbol, SyntaxContext, bug, span_bug};
26use std::cell::Cell;
27use std::cmp::Ordering;
28use std::hash::{Hash, Hasher};
29use std::iter;
30
31#[derive(Debug, Clone)]
33pub enum Constant {
34 Adt(ConstValue),
35 Str(String),
37 Binary(Vec<u8>),
39 Char(char),
41 Int(u128),
43 F16(u16),
46 F32(f32),
48 F64(f64),
50 F128(u128),
53 Bool(bool),
55 Vec(Vec<Self>),
57 Repeat(Box<Self>, u64),
59 Tuple(Vec<Self>),
61 RawPtr(u128),
63 Ref(Box<Self>),
65 Err,
67}
68
69trait IntTypeBounds: Sized {
70 type Output: PartialOrd;
71
72 fn min_max(self) -> Option<(Self::Output, Self::Output)>;
73 fn bits(self) -> Self::Output;
74 fn ensure_fits(self, val: Self::Output) -> Option<Self::Output> {
75 let (min, max) = self.min_max()?;
76 (min <= val && val <= max).then_some(val)
77 }
78}
79impl IntTypeBounds for UintTy {
80 type Output = u128;
81 fn min_max(self) -> Option<(Self::Output, Self::Output)> {
82 Some(match self {
83 UintTy::U8 => (u8::MIN.into(), u8::MAX.into()),
84 UintTy::U16 => (u16::MIN.into(), u16::MAX.into()),
85 UintTy::U32 => (u32::MIN.into(), u32::MAX.into()),
86 UintTy::U64 => (u64::MIN.into(), u64::MAX.into()),
87 UintTy::U128 => (u128::MIN, u128::MAX),
88 UintTy::Usize => (usize::MIN.try_into().ok()?, usize::MAX.try_into().ok()?),
89 })
90 }
91 fn bits(self) -> Self::Output {
92 match self {
93 UintTy::U8 => 8,
94 UintTy::U16 => 16,
95 UintTy::U32 => 32,
96 UintTy::U64 => 64,
97 UintTy::U128 => 128,
98 UintTy::Usize => usize::BITS.into(),
99 }
100 }
101}
102impl IntTypeBounds for IntTy {
103 type Output = i128;
104 fn min_max(self) -> Option<(Self::Output, Self::Output)> {
105 Some(match self {
106 IntTy::I8 => (i8::MIN.into(), i8::MAX.into()),
107 IntTy::I16 => (i16::MIN.into(), i16::MAX.into()),
108 IntTy::I32 => (i32::MIN.into(), i32::MAX.into()),
109 IntTy::I64 => (i64::MIN.into(), i64::MAX.into()),
110 IntTy::I128 => (i128::MIN, i128::MAX),
111 IntTy::Isize => (isize::MIN.try_into().ok()?, isize::MAX.try_into().ok()?),
112 })
113 }
114 fn bits(self) -> Self::Output {
115 match self {
116 IntTy::I8 => 8,
117 IntTy::I16 => 16,
118 IntTy::I32 => 32,
119 IntTy::I64 => 64,
120 IntTy::I128 => 128,
121 IntTy::Isize => isize::BITS.into(),
122 }
123 }
124}
125
126impl PartialEq for Constant {
127 fn eq(&self, other: &Self) -> bool {
128 match (self, other) {
129 (Self::Str(ls), Self::Str(rs)) => ls == rs,
130 (Self::Binary(l), Self::Binary(r)) => l == r,
131 (&Self::Char(l), &Self::Char(r)) => l == r,
132 (&Self::Int(l), &Self::Int(r)) => l == r,
133 (&Self::F64(l), &Self::F64(r)) => {
134 l.to_bits() == r.to_bits() && !l.is_nan()
136 },
137 (&Self::F32(l), &Self::F32(r)) => {
138 l.to_bits() == r.to_bits() && !l.is_nan()
140 },
141 (&Self::Bool(l), &Self::Bool(r)) => l == r,
142 (&Self::Vec(ref l), &Self::Vec(ref r)) | (&Self::Tuple(ref l), &Self::Tuple(ref r)) => l == r,
143 (Self::Repeat(lv, ls), Self::Repeat(rv, rs)) => ls == rs && lv == rv,
144 (Self::Ref(lb), Self::Ref(rb)) => *lb == *rb,
145 _ => false,
147 }
148 }
149}
150
151impl Hash for Constant {
152 fn hash<H>(&self, state: &mut H)
153 where
154 H: Hasher,
155 {
156 std::mem::discriminant(self).hash(state);
157 match *self {
158 Self::Adt(ref elem) => {
159 elem.hash(state);
160 },
161 Self::Str(ref s) => {
162 s.hash(state);
163 },
164 Self::Binary(ref b) => {
165 b.hash(state);
166 },
167 Self::Char(c) => {
168 c.hash(state);
169 },
170 Self::Int(i) => {
171 i.hash(state);
172 },
173 Self::F16(f) => {
174 f.hash(state);
176 },
177 Self::F32(f) => {
178 f64::from(f).to_bits().hash(state);
179 },
180 Self::F64(f) => {
181 f.to_bits().hash(state);
182 },
183 Self::F128(f) => {
184 f.hash(state);
185 },
186 Self::Bool(b) => {
187 b.hash(state);
188 },
189 Self::Vec(ref v) | Self::Tuple(ref v) => {
190 v.hash(state);
191 },
192 Self::Repeat(ref c, l) => {
193 c.hash(state);
194 l.hash(state);
195 },
196 Self::RawPtr(u) => {
197 u.hash(state);
198 },
199 Self::Ref(ref r) => {
200 r.hash(state);
201 },
202 Self::Err => {},
203 }
204 }
205}
206
207impl Constant {
208 pub fn partial_cmp(tcx: TyCtxt<'_>, cmp_type: Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
209 match (left, right) {
210 (Self::Str(ls), Self::Str(rs)) => Some(ls.cmp(rs)),
211 (Self::Char(l), Self::Char(r)) => Some(l.cmp(r)),
212 (&Self::Int(l), &Self::Int(r)) => match *cmp_type.kind() {
213 ty::Int(int_ty) => Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty))),
214 ty::Uint(_) => Some(l.cmp(&r)),
215 _ => bug!("Not an int type"),
216 },
217 (&Self::F64(l), &Self::F64(r)) => l.partial_cmp(&r),
218 (&Self::F32(l), &Self::F32(r)) => l.partial_cmp(&r),
219 (Self::Bool(l), Self::Bool(r)) => Some(l.cmp(r)),
220 (Self::Tuple(l), Self::Tuple(r)) if l.len() == r.len() => match *cmp_type.kind() {
221 ty::Tuple(tys) if tys.len() == l.len() => l
222 .iter()
223 .zip(r)
224 .zip(tys)
225 .map(|((li, ri), cmp_type)| Self::partial_cmp(tcx, cmp_type, li, ri))
226 .find(|r| r.is_none_or(|o| o != Ordering::Equal))
227 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
228 _ => None,
229 },
230 (Self::Vec(l), Self::Vec(r)) => {
231 let cmp_type = cmp_type.builtin_index()?;
232 iter::zip(l, r)
233 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
234 .find(|r| r.is_none_or(|o| o != Ordering::Equal))
235 .unwrap_or_else(|| Some(l.len().cmp(&r.len())))
236 },
237 (Self::Repeat(lv, ls), Self::Repeat(rv, rs)) => {
238 match Self::partial_cmp(
239 tcx,
240 match *cmp_type.kind() {
241 ty::Array(ty, _) => ty,
242 _ => return None,
243 },
244 lv,
245 rv,
246 ) {
247 Some(Ordering::Equal) => Some(ls.cmp(rs)),
248 x => x,
249 }
250 },
251 (Self::Ref(lb), Self::Ref(rb)) => Self::partial_cmp(
252 tcx,
253 match *cmp_type.kind() {
254 ty::Ref(_, ty, _) => ty,
255 _ => return None,
256 },
257 lb,
258 rb,
259 ),
260 _ => None,
262 }
263 }
264
265 pub fn int_value(&self, tcx: TyCtxt<'_>, val_type: Ty<'_>) -> Option<FullInt> {
267 if let Constant::Int(const_int) = *self {
268 match *val_type.kind() {
269 ty::Int(ity) => Some(FullInt::S(sext(tcx, const_int, ity))),
270 ty::Uint(_) => Some(FullInt::U(const_int)),
271 _ => None,
272 }
273 } else {
274 None
275 }
276 }
277
278 #[must_use]
279 pub fn peel_refs(mut self) -> Self {
280 while let Constant::Ref(r) = self {
281 self = *r;
282 }
283 self
284 }
285
286 fn parse_f16(s: &str) -> Self {
287 let f: Half = s.parse().unwrap();
288 Self::F16(f.to_bits().try_into().unwrap())
289 }
290
291 fn parse_f128(s: &str) -> Self {
292 let f: Quad = s.parse().unwrap();
293 Self::F128(f.to_bits())
294 }
295
296 pub fn new_numeric_min<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Self> {
297 match *ty.kind() {
298 ty::Uint(_) => Some(Self::Int(0)),
299 ty::Int(ty) => {
300 let val = match ty.normalize(tcx.sess.target.pointer_width) {
301 IntTy::I8 => i128::from(i8::MIN),
302 IntTy::I16 => i128::from(i16::MIN),
303 IntTy::I32 => i128::from(i32::MIN),
304 IntTy::I64 => i128::from(i64::MIN),
305 IntTy::I128 => i128::MIN,
306 IntTy::Isize => return None,
307 };
308 Some(Self::Int(val.cast_unsigned()))
309 },
310 ty::Char => Some(Self::Char(char::MIN)),
311 ty::Float(FloatTy::F32) => Some(Self::F32(f32::NEG_INFINITY)),
312 ty::Float(FloatTy::F64) => Some(Self::F64(f64::NEG_INFINITY)),
313 _ => None,
314 }
315 }
316
317 pub fn new_numeric_max<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Self> {
318 match *ty.kind() {
319 ty::Uint(ty) => Some(Self::Int(match ty.normalize(tcx.sess.target.pointer_width) {
320 UintTy::U8 => u128::from(u8::MAX),
321 UintTy::U16 => u128::from(u16::MAX),
322 UintTy::U32 => u128::from(u32::MAX),
323 UintTy::U64 => u128::from(u64::MAX),
324 UintTy::U128 => u128::MAX,
325 UintTy::Usize => return None,
326 })),
327 ty::Int(ty) => {
328 let val = match ty.normalize(tcx.sess.target.pointer_width) {
329 IntTy::I8 => i128::from(i8::MAX),
330 IntTy::I16 => i128::from(i16::MAX),
331 IntTy::I32 => i128::from(i32::MAX),
332 IntTy::I64 => i128::from(i64::MAX),
333 IntTy::I128 => i128::MAX,
334 IntTy::Isize => return None,
335 };
336 Some(Self::Int(val.cast_unsigned()))
337 },
338 ty::Char => Some(Self::Char(char::MAX)),
339 ty::Float(FloatTy::F32) => Some(Self::F32(f32::INFINITY)),
340 ty::Float(FloatTy::F64) => Some(Self::F64(f64::INFINITY)),
341 _ => None,
342 }
343 }
344
345 pub fn is_numeric_min<'tcx>(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
346 match (self, ty.kind()) {
347 (&Self::Int(x), &ty::Uint(_)) => x == 0,
348 (&Self::Int(x), &ty::Int(ty)) => {
349 let limit = match ty.normalize(tcx.sess.target.pointer_width) {
350 IntTy::I8 => i128::from(i8::MIN),
351 IntTy::I16 => i128::from(i16::MIN),
352 IntTy::I32 => i128::from(i32::MIN),
353 IntTy::I64 => i128::from(i64::MIN),
354 IntTy::I128 => i128::MIN,
355 IntTy::Isize => return false,
356 };
357 x.cast_signed() == limit
358 },
359 (&Self::Char(x), &ty::Char) => x == char::MIN,
360 (&Self::F32(x), &ty::Float(FloatTy::F32)) => x == f32::NEG_INFINITY,
361 (&Self::F64(x), &ty::Float(FloatTy::F64)) => x == f64::NEG_INFINITY,
362 _ => false,
363 }
364 }
365
366 pub fn is_numeric_max<'tcx>(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
367 match (self, ty.kind()) {
368 (&Self::Int(x), &ty::Uint(ty)) => {
369 let limit = match ty.normalize(tcx.sess.target.pointer_width) {
370 UintTy::U8 => u128::from(u8::MAX),
371 UintTy::U16 => u128::from(u16::MAX),
372 UintTy::U32 => u128::from(u32::MAX),
373 UintTy::U64 => u128::from(u64::MAX),
374 UintTy::U128 => u128::MAX,
375 UintTy::Usize => return false,
376 };
377 x == limit
378 },
379 (&Self::Int(x), &ty::Int(ty)) => {
380 let limit = match ty.normalize(tcx.sess.target.pointer_width) {
381 IntTy::I8 => i128::from(i8::MAX),
382 IntTy::I16 => i128::from(i16::MAX),
383 IntTy::I32 => i128::from(i32::MAX),
384 IntTy::I64 => i128::from(i64::MAX),
385 IntTy::I128 => i128::MAX,
386 IntTy::Isize => return false,
387 };
388 x.cast_signed() == limit
389 },
390 (&Self::Char(x), &ty::Char) => x == char::MAX,
391 (&Self::F32(x), &ty::Float(FloatTy::F32)) => x == f32::INFINITY,
392 (&Self::F64(x), &ty::Float(FloatTy::F64)) => x == f64::INFINITY,
393 _ => false,
394 }
395 }
396
397 pub fn is_pos_infinity(&self) -> bool {
398 match *self {
399 Constant::F32(x) => x == f32::INFINITY,
401 Constant::F64(x) => x == f64::INFINITY,
402 _ => false,
403 }
404 }
405
406 pub fn is_neg_infinity(&self) -> bool {
407 match *self {
408 Constant::F32(x) => x == f32::NEG_INFINITY,
410 Constant::F64(x) => x == f64::NEG_INFINITY,
411 _ => false,
412 }
413 }
414}
415
416pub fn lit_to_mir_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
418 match *lit {
419 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
420 LitKind::Byte(b) => Constant::Int(u128::from(b)),
421 LitKind::ByteStr(ref s, _) | LitKind::CStr(ref s, _) => Constant::Binary(s.as_byte_str().to_vec()),
422 LitKind::Char(c) => Constant::Char(c),
423 LitKind::Int(n, _) => Constant::Int(n.get()),
424 LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {
425 FloatTy::F16 => Constant::parse_f16(is.as_str()),
427 FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()),
428 FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()),
429 FloatTy::F128 => Constant::parse_f128(is.as_str()),
430 },
431 LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind() {
432 ty::Float(FloatTy::F16) => Constant::parse_f16(is.as_str()),
433 ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
434 ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
435 ty::Float(FloatTy::F128) => Constant::parse_f128(is.as_str()),
436 _ => bug!(),
437 },
438 LitKind::Bool(b) => Constant::Bool(b),
439 LitKind::Err(_) => Constant::Err,
440 }
441}
442
443#[derive(Clone, Copy)]
445pub enum ConstantSource {
446 Local,
448 NonLocal,
451}
452impl ConstantSource {
453 pub fn is_local(self) -> bool {
454 matches!(self, Self::Local)
455 }
456}
457
458#[derive(Copy, Clone, Debug, Eq)]
459pub enum FullInt {
460 S(i128),
461 U(u128),
462}
463
464impl FullInt {
465 pub fn is_zero(self) -> bool {
466 matches!(self, Self::S(0) | Self::U(0))
467 }
468}
469
470impl PartialEq for FullInt {
471 fn eq(&self, other: &Self) -> bool {
472 self.cmp(other) == Ordering::Equal
473 }
474}
475
476impl PartialOrd for FullInt {
477 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
478 Some(self.cmp(other))
479 }
480}
481
482impl Ord for FullInt {
483 fn cmp(&self, other: &Self) -> Ordering {
484 use FullInt::{S, U};
485
486 fn cmp_s_u(s: i128, u: u128) -> Ordering {
487 u128::try_from(s).map_or(Ordering::Less, |x| x.cmp(&u))
488 }
489
490 match (*self, *other) {
491 (S(s), S(o)) => s.cmp(&o),
492 (U(s), U(o)) => s.cmp(&o),
493 (S(s), U(o)) => cmp_s_u(s, o),
494 (U(s), S(o)) => cmp_s_u(o, s).reverse(),
495 }
496 }
497}
498
499pub fn eval_int(cx: &LateContext<'_>, e: &Expr<'_>) -> Option<FullInt> {
501 match e.kind {
502 ExprKind::Lit(lit) if let LitKind::Int(val, _) = lit.node => Some(FullInt::U(val.0)),
503 ExprKind::Unary(UnOp::Neg, e)
504 if let ExprKind::Lit(lit) = e.kind
505 && let LitKind::Int(val, _) = lit.node =>
506 {
507 Some(FullInt::S(val.0.cast_signed().wrapping_neg()))
508 },
509 _ if let ty = cx.typeck_results().expr_ty(e)
510 && let ty::Int(_) | ty::Uint(_) = *ty.kind() =>
511 {
512 ConstEvalCtxt::new(cx).eval(e).and_then(|x| x.int_value(cx.tcx, ty))
513 },
514 _ => None,
515 }
516}
517
518pub struct ConstEvalCtxt<'tcx> {
524 pub tcx: TyCtxt<'tcx>,
525 pub typing_env: ty::TypingEnv<'tcx>,
526 pub typeck: &'tcx TypeckResults<'tcx>,
527 source: Cell<ConstantSource>,
528 ctxt: Cell<SyntaxContext>,
529}
530
531impl<'tcx> ConstEvalCtxt<'tcx> {
532 pub fn new(cx: &LateContext<'tcx>) -> Self {
535 Self {
536 tcx: cx.tcx,
537 typing_env: cx.typing_env(),
538 typeck: cx.typeck_results(),
539 source: Cell::new(ConstantSource::Local),
540 ctxt: Cell::new(SyntaxContext::root()),
541 }
542 }
543
544 pub fn with_env(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, typeck: &'tcx TypeckResults<'tcx>) -> Self {
546 Self {
547 tcx,
548 typing_env,
549 typeck,
550 source: Cell::new(ConstantSource::Local),
551 ctxt: Cell::new(SyntaxContext::root()),
552 }
553 }
554
555 pub fn eval_with_source(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<(Constant, ConstantSource)> {
558 self.source.set(ConstantSource::Local);
559 self.ctxt.set(ctxt);
560 self.expr(e).map(|c| (c, self.source.get()))
561 }
562
563 pub fn eval(&self, e: &Expr<'_>) -> Option<Constant> {
565 self.expr(e)
566 }
567
568 pub fn eval_local(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<Constant> {
575 match self.eval_with_source(e, ctxt) {
576 Some((x, ConstantSource::Local)) => Some(x),
577 _ => None,
578 }
579 }
580
581 pub fn eval_full_int(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<FullInt> {
588 match self.eval_with_source(e, ctxt) {
589 Some((x, ConstantSource::Local)) => x.int_value(self.tcx, self.typeck.expr_ty(e)),
590 _ => None,
591 }
592 }
593
594 pub fn eval_pat_expr(&self, pat_expr: &PatExpr<'_>) -> Option<Constant> {
595 match &pat_expr.kind {
596 PatExprKind::Lit { lit, negated } => {
597 let ty = self.typeck.node_type_opt(pat_expr.hir_id);
598 let val = lit_to_mir_constant(&lit.node, ty);
599 if *negated {
600 self.constant_negate(&val, ty?)
601 } else {
602 Some(val)
603 }
604 },
605 PatExprKind::Path(qpath) => self.qpath(qpath, pat_expr.hir_id),
606 }
607 }
608
609 fn check_ctxt(&self, ctxt: SyntaxContext) {
610 if self.ctxt.get() != ctxt {
611 self.source.set(ConstantSource::NonLocal);
612 }
613 }
614
615 fn qpath(&self, qpath: &QPath<'_>, hir_id: HirId) -> Option<Constant> {
616 self.fetch_path(qpath, hir_id)
617 .and_then(|c| mir_to_const(self.tcx, c, self.typeck.node_type(hir_id)))
618 }
619
620 fn expr(&self, e: &Expr<'_>) -> Option<Constant> {
622 self.check_ctxt(e.span.ctxt());
623 match e.kind {
624 ExprKind::ConstBlock(ConstBlock { body, .. }) => self.expr(self.tcx.hir_body(body).value),
625 ExprKind::DropTemps(e) => self.expr(e),
626 ExprKind::Path(ref qpath) => self.qpath(qpath, e.hir_id),
627 ExprKind::Block(block, _) => {
628 self.check_ctxt(block.span.ctxt());
629 self.block(block)
630 },
631 ExprKind::Lit(lit) => {
632 self.check_ctxt(lit.span.ctxt());
633 Some(lit_to_mir_constant(&lit.node, self.typeck.expr_ty_opt(e)))
634 },
635 ExprKind::Array(vec) => self.multi(vec).map(Constant::Vec),
636 ExprKind::Tup(tup) => self.multi(tup).map(Constant::Tuple),
637 ExprKind::Repeat(value, _) => {
638 let n = match self.typeck.expr_ty(e).kind() {
639 ty::Array(_, n) => n.try_to_target_usize(self.tcx)?,
640 _ => span_bug!(e.span, "typeck error"),
641 };
642 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
643 },
644 ExprKind::Unary(op, operand) => self.expr(operand).and_then(|o| match op {
645 UnOp::Not => self.constant_not(&o, self.typeck.expr_ty(e)),
646 UnOp::Neg => self.constant_negate(&o, self.typeck.expr_ty(e)),
647 UnOp::Deref => Some(if let Constant::Ref(r) = o { *r } else { o }),
648 }),
649 ExprKind::If(cond, then, ref otherwise) => self.ifthenelse(cond, then, *otherwise),
650 ExprKind::Binary(op, left, right) => {
651 self.check_ctxt(e.span.ctxt());
652 self.binop(op.node, left, right)
653 },
654 ExprKind::Call(callee, []) => {
655 if let ExprKind::Path(qpath) = &callee.kind
657 && let Some(did) = self.typeck.qpath_res(qpath, callee.hir_id).opt_def_id()
658 {
659 match self.tcx.get_diagnostic_name(did) {
660 Some(sym::i8_legacy_fn_max_value) => Some(Constant::Int(i8::MAX as u128)),
661 Some(sym::i16_legacy_fn_max_value) => Some(Constant::Int(i16::MAX as u128)),
662 Some(sym::i32_legacy_fn_max_value) => Some(Constant::Int(i32::MAX as u128)),
663 Some(sym::i64_legacy_fn_max_value) => Some(Constant::Int(i64::MAX as u128)),
664 Some(sym::i128_legacy_fn_max_value) => Some(Constant::Int(i128::MAX as u128)),
665 _ => None,
666 }
667 } else {
668 None
669 }
670 },
671 ExprKind::Index(arr, index, _) => self.index(arr, index),
672 ExprKind::AddrOf(_, _, inner) => self.expr(inner).map(|r| Constant::Ref(Box::new(r))),
673 ExprKind::Field(base, ref field)
674 if let base_ty = self.typeck.expr_ty(base)
675 && match self.typeck.expr_adjustments(base) {
676 [] => true,
677 [.., a] => a.target == base_ty,
678 }
679 && let Some(Constant::Adt(constant)) = self.expr(base)
680 && let ty::Adt(adt_def, _) = *base_ty.kind()
681 && adt_def.is_struct()
682 && let Some((desired_field, ty)) =
683 field_of_struct(adt_def, self.tcx, constant, base_ty, field.name) =>
684 {
685 self.check_ctxt(field.span.ctxt());
686 mir_to_const(self.tcx, desired_field, ty)
687 },
688 _ => None,
689 }
690 }
691
692 pub fn eval_is_empty(&self, e: &Expr<'_>) -> Option<bool> {
696 match e.kind {
697 ExprKind::ConstBlock(ConstBlock { body, .. }) => self.eval_is_empty(self.tcx.hir_body(body).value),
698 ExprKind::DropTemps(e) => self.eval_is_empty(e),
699 ExprKind::Lit(lit) => {
700 if is_direct_expn_of(e.span, sym::cfg).is_some() {
701 None
702 } else {
703 match &lit.node {
704 LitKind::Str(is, _) => Some(is.is_empty()),
705 LitKind::ByteStr(s, _) | LitKind::CStr(s, _) => Some(s.as_byte_str().is_empty()),
706 _ => None,
707 }
708 }
709 },
710 ExprKind::Array(vec) => self.multi(vec).map(|v| v.is_empty()),
711 ExprKind::Repeat(..) => {
712 if let ty::Array(_, n) = self.typeck.expr_ty(e).kind() {
713 Some(n.try_to_target_usize(self.tcx)? == 0)
714 } else {
715 span_bug!(e.span, "typeck error");
716 }
717 },
718 _ => None,
719 }
720 }
721
722 #[expect(clippy::cast_possible_wrap)]
723 fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
724 use self::Constant::{Bool, Int};
725 match *o {
726 Bool(b) => Some(Bool(!b)),
727 Int(value) => {
728 let value = !value;
729 match *ty.kind() {
730 ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
731 ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
732 _ => None,
733 }
734 },
735 _ => None,
736 }
737 }
738
739 fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
740 use self::Constant::{F32, F64, Int};
741 match *o {
742 Int(value) => {
743 let ty::Int(ity) = *ty.kind() else { return None };
744 let (min, _) = ity.min_max()?;
745 let value = sext(self.tcx, value, ity);
747
748 if value == min {
750 return None;
751 }
752
753 let value = value.checked_neg()?;
754 Some(Int(unsext(self.tcx, value, ity)))
756 },
757 F32(f) => Some(F32(-f)),
758 F64(f) => Some(F64(-f)),
759 _ => None,
760 }
761 }
762
763 fn multi(&self, vec: &[Expr<'_>]) -> Option<Vec<Constant>> {
766 vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
767 }
768
769 #[expect(clippy::too_many_lines)]
771 fn fetch_path(&self, qpath: &QPath<'_>, id: HirId) -> Option<ConstValue> {
772 let did = match *qpath {
777 QPath::Resolved(None, path)
778 if path.span.ctxt() == self.ctxt.get()
779 && path.segments.iter().all(|s| self.ctxt.get() == s.ident.span.ctxt())
780 && let Res::Def(DefKind::Const, did) = path.res
781 && (matches!(
782 self.tcx.get_diagnostic_name(did),
783 Some(
784 sym::f32_legacy_const_digits
785 | sym::f32_legacy_const_epsilon
786 | sym::f32_legacy_const_infinity
787 | sym::f32_legacy_const_mantissa_dig
788 | sym::f32_legacy_const_max
789 | sym::f32_legacy_const_max_10_exp
790 | sym::f32_legacy_const_max_exp
791 | sym::f32_legacy_const_min
792 | sym::f32_legacy_const_min_10_exp
793 | sym::f32_legacy_const_min_exp
794 | sym::f32_legacy_const_min_positive
795 | sym::f32_legacy_const_nan
796 | sym::f32_legacy_const_neg_infinity
797 | sym::f32_legacy_const_radix
798 | sym::f64_legacy_const_digits
799 | sym::f64_legacy_const_epsilon
800 | sym::f64_legacy_const_infinity
801 | sym::f64_legacy_const_mantissa_dig
802 | sym::f64_legacy_const_max
803 | sym::f64_legacy_const_max_10_exp
804 | sym::f64_legacy_const_max_exp
805 | sym::f64_legacy_const_min
806 | sym::f64_legacy_const_min_10_exp
807 | sym::f64_legacy_const_min_exp
808 | sym::f64_legacy_const_min_positive
809 | sym::f64_legacy_const_nan
810 | sym::f64_legacy_const_neg_infinity
811 | sym::f64_legacy_const_radix
812 | sym::u8_legacy_const_min
813 | sym::u16_legacy_const_min
814 | sym::u32_legacy_const_min
815 | sym::u64_legacy_const_min
816 | sym::u128_legacy_const_min
817 | sym::usize_legacy_const_min
818 | sym::u8_legacy_const_max
819 | sym::u16_legacy_const_max
820 | sym::u32_legacy_const_max
821 | sym::u64_legacy_const_max
822 | sym::u128_legacy_const_max
823 | sym::i8_legacy_const_min
824 | sym::i16_legacy_const_min
825 | sym::i32_legacy_const_min
826 | sym::i64_legacy_const_min
827 | sym::i128_legacy_const_min
828 | sym::i8_legacy_const_max
829 | sym::i16_legacy_const_max
830 | sym::i32_legacy_const_max
831 | sym::i64_legacy_const_max
832 | sym::i128_legacy_const_max
833 )
834 ) || self.tcx.opt_parent(did).is_some_and(|parent| {
835 matches!(
836 parent.opt_diag_name(&self.tcx),
837 Some(
838 sym::f16_consts_mod | sym::f32_consts_mod | sym::f64_consts_mod | sym::f128_consts_mod
839 )
840 )
841 })) =>
842 {
843 did
844 },
845 QPath::TypeRelative(ty, const_name)
846 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind
847 && let [.., ty_name] = ty_path.segments
848 && (matches!(
849 ty_name.ident.name,
850 sym::i8
851 | sym::i16
852 | sym::i32
853 | sym::i64
854 | sym::i128
855 | sym::u8
856 | sym::u16
857 | sym::u32
858 | sym::u64
859 | sym::u128
860 | sym::f32
861 | sym::f64
862 | sym::char
863 ) || (ty_name.ident.name == sym::usize && const_name.ident.name == sym::MIN))
864 && const_name.ident.span.ctxt() == self.ctxt.get()
865 && ty.span.ctxt() == self.ctxt.get()
866 && ty_name.ident.span.ctxt() == self.ctxt.get()
867 && matches!(ty_path.res, Res::PrimTy(_))
868 && let Some((DefKind::AssocConst, did)) = self.typeck.type_dependent_def(id)
869 && self.tcx.inherent_impl_of_assoc(did).is_some() =>
870 {
871 did
872 },
873 _ if let Res::Def(DefKind::Const | DefKind::AssocConst, did) = self.typeck.qpath_res(qpath, id)
877 && !self.tcx.is_direct_const(did) =>
878 {
879 self.source.set(ConstantSource::NonLocal);
880 did
881 },
882 _ => return None,
883 };
884
885 let args = self.typeck.node_args(id);
886
887 if !args.is_empty() {
888 let owner_def_id = self.typeck.hir_owner.def_id.to_def_id();
889 let identity_args = ty::GenericArgs::identity_for_item(self.tcx, owner_def_id);
890 if self
892 .tcx
893 .instantiate_and_check_impossible_clauses((owner_def_id, identity_args))
894 {
895 return None;
896 }
897 }
898
899 self.tcx
900 .const_eval_resolve(self.typing_env, mir::UnevaluatedConst::new(did, args), qpath.span())
901 .ok()
902 }
903
904 fn index(&self, lhs: &'_ Expr<'_>, index: &'_ Expr<'_>) -> Option<Constant> {
905 let lhs = self.expr(lhs);
906 let index = self.expr(index);
907
908 match (lhs, index) {
909 (Some(Constant::Vec(vec)), Some(Constant::Int(index))) => match vec.get(index as usize) {
910 Some(Constant::F16(x)) => Some(Constant::F16(*x)),
911 Some(Constant::F32(x)) => Some(Constant::F32(*x)),
912 Some(Constant::F64(x)) => Some(Constant::F64(*x)),
913 Some(Constant::F128(x)) => Some(Constant::F128(*x)),
914 _ => None,
915 },
916 (Some(Constant::Vec(vec)), _) => {
917 if !vec.is_empty() && vec.iter().all(|x| *x == vec[0]) {
918 match vec.first() {
919 Some(Constant::F16(x)) => Some(Constant::F16(*x)),
920 Some(Constant::F32(x)) => Some(Constant::F32(*x)),
921 Some(Constant::F64(x)) => Some(Constant::F64(*x)),
922 Some(Constant::F128(x)) => Some(Constant::F128(*x)),
923 _ => None,
924 }
925 } else {
926 None
927 }
928 },
929 _ => None,
930 }
931 }
932
933 fn block(&self, block: &Block<'_>) -> Option<Constant> {
935 if block.stmts.is_empty()
936 && let Some(expr) = block.expr
937 {
938 let span = block.span.data();
940 if span.ctxt == SyntaxContext::root() {
941 if let Some(expr_span) = walk_span_to_context(expr.span, span.ctxt)
942 && let expr_lo = expr_span.lo()
943 && expr_lo >= span.lo
944 && let Some(src) = (span.lo..expr_lo).get_source_range(self.tcx)
945 && let Some(src) = src.as_str()
946 {
947 use rustc_lexer::TokenKind::{BlockComment, LineComment, OpenBrace, Semi, Whitespace};
948 if !tokenize(src, FrontmatterAllowed::No)
949 .map(|t| t.kind)
950 .filter(|t| !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. } | Semi))
951 .eq([OpenBrace])
952 {
953 self.source.set(ConstantSource::NonLocal);
954 }
955 } else {
956 self.source.set(ConstantSource::NonLocal);
958 }
959 }
960
961 self.expr(expr)
962 } else {
963 None
964 }
965 }
966
967 fn ifthenelse(&self, cond: &Expr<'_>, then: &Expr<'_>, otherwise: Option<&Expr<'_>>) -> Option<Constant> {
968 if let Some(Constant::Bool(b)) = self.expr(cond) {
969 if b {
970 self.expr(then)
971 } else {
972 otherwise.as_ref().and_then(|expr| self.expr(expr))
973 }
974 } else {
975 None
976 }
977 }
978
979 #[expect(clippy::too_many_lines)]
980 fn binop(&self, op: BinOpKind, left: &Expr<'_>, right: &Expr<'_>) -> Option<Constant> {
981 let l = self.expr(left)?;
982 let r = self.expr(right);
983 match (l, r) {
984 (Constant::Int(l), Some(Constant::Int(r))) => match *self.typeck.expr_ty_opt(left)?.kind() {
985 ty::Int(ity) => {
986 let (ty_min_value, _) = ity.min_max()?;
987 let bits = ity.bits();
988 let l = sext(self.tcx, l, ity);
989 let r = sext(self.tcx, r, ity);
990
991 if let BinOpKind::Div | BinOpKind::Rem = op
994 && l == ty_min_value
995 && r == -1
996 {
997 return None;
998 }
999
1000 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
1001 match op {
1002 BinOpKind::Add => l.checked_add(r).and_then(|n| ity.ensure_fits(n)).map(zext),
1005 BinOpKind::Sub => l.checked_sub(r).and_then(|n| ity.ensure_fits(n)).map(zext),
1006 BinOpKind::Mul => l.checked_mul(r).and_then(|n| ity.ensure_fits(n)).map(zext),
1007 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
1008 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
1009 BinOpKind::Shr if r < bits && !r.is_negative() => l.checked_shr(r.try_into().ok()?).map(zext),
1012 BinOpKind::Shl if r < bits && !r.is_negative() => l.checked_shl(r.try_into().ok()?).map(zext),
1013 BinOpKind::BitXor => Some(zext(l ^ r)),
1014 BinOpKind::BitOr => Some(zext(l | r)),
1015 BinOpKind::BitAnd => Some(zext(l & r)),
1016 BinOpKind::Eq => Some(Constant::Bool(l == r)),
1018 BinOpKind::Ne => Some(Constant::Bool(l != r)),
1019 BinOpKind::Lt => Some(Constant::Bool(l < r)),
1020 BinOpKind::Le => Some(Constant::Bool(l <= r)),
1021 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1022 BinOpKind::Gt => Some(Constant::Bool(l > r)),
1023 _ => None,
1024 }
1025 },
1026 ty::Uint(ity) => {
1027 let bits = ity.bits();
1028 let mask = !0u128 >> (128 - bits);
1029
1030 match op {
1031 BinOpKind::Add => l.checked_add(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
1032 BinOpKind::Sub => l.checked_sub(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
1033 BinOpKind::Mul => l.checked_mul(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
1034 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
1035 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
1036 BinOpKind::Shr if r < bits => {
1037 l.checked_shr(r.try_into().ok()?).map(|x| Constant::Int(x & mask))
1038 },
1039 BinOpKind::Shl if r < bits => {
1040 l.checked_shl(r.try_into().ok()?).map(|x| Constant::Int(x & mask))
1041 },
1042 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
1043 BinOpKind::BitOr => Some(Constant::Int(l | r)),
1044 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
1045 BinOpKind::Eq => Some(Constant::Bool(l == r)),
1046 BinOpKind::Ne => Some(Constant::Bool(l != r)),
1047 BinOpKind::Lt => Some(Constant::Bool(l < r)),
1048 BinOpKind::Le => Some(Constant::Bool(l <= r)),
1049 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1050 BinOpKind::Gt => Some(Constant::Bool(l > r)),
1051 _ => None,
1052 }
1053 },
1054 _ => None,
1055 },
1056 (Constant::F32(l), Some(Constant::F32(r))) => match op {
1058 BinOpKind::Add => Some(Constant::F32(l + r)),
1059 BinOpKind::Sub => Some(Constant::F32(l - r)),
1060 BinOpKind::Mul => Some(Constant::F32(l * r)),
1061 BinOpKind::Div => Some(Constant::F32(l / r)),
1062 BinOpKind::Rem => Some(Constant::F32(l % r)),
1063 BinOpKind::Eq => Some(Constant::Bool(l == r)),
1064 BinOpKind::Ne => Some(Constant::Bool(l != r)),
1065 BinOpKind::Lt => Some(Constant::Bool(l < r)),
1066 BinOpKind::Le => Some(Constant::Bool(l <= r)),
1067 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1068 BinOpKind::Gt => Some(Constant::Bool(l > r)),
1069 _ => None,
1070 },
1071 (Constant::F64(l), Some(Constant::F64(r))) => match op {
1072 BinOpKind::Add => Some(Constant::F64(l + r)),
1073 BinOpKind::Sub => Some(Constant::F64(l - r)),
1074 BinOpKind::Mul => Some(Constant::F64(l * r)),
1075 BinOpKind::Div => Some(Constant::F64(l / r)),
1076 BinOpKind::Rem => Some(Constant::F64(l % r)),
1077 BinOpKind::Eq => Some(Constant::Bool(l == r)),
1078 BinOpKind::Ne => Some(Constant::Bool(l != r)),
1079 BinOpKind::Lt => Some(Constant::Bool(l < r)),
1080 BinOpKind::Le => Some(Constant::Bool(l <= r)),
1081 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1082 BinOpKind::Gt => Some(Constant::Bool(l > r)),
1083 _ => None,
1084 },
1085 (l, r) => match (op, l, r) {
1086 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
1087 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
1088 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
1089 Some(r)
1090 },
1091 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
1092 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
1093 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
1094 _ => None,
1095 },
1096 }
1097 }
1098}
1099
1100pub fn mir_to_const<'tcx>(tcx: TyCtxt<'tcx>, val: ConstValue, ty: Ty<'tcx>) -> Option<Constant> {
1101 match (val, ty.kind()) {
1102 (_, &ty::Adt(adt_def, _)) if adt_def.is_struct() => Some(Constant::Adt(val)),
1103 (ConstValue::Scalar(Scalar::Int(int)), _) => match ty.kind() {
1104 ty::Bool => Some(Constant::Bool(int == ScalarInt::TRUE)),
1105 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(int.to_bits(int.size()))),
1106 ty::Float(FloatTy::F16) => Some(Constant::F16(int.into())),
1107 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(int.into()))),
1108 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(int.into()))),
1109 ty::Float(FloatTy::F128) => Some(Constant::F128(int.into())),
1110 ty::RawPtr(_, _) => Some(Constant::RawPtr(int.to_bits(int.size()))),
1111 _ => None,
1112 },
1113 (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1114 let data = val.try_get_slice_bytes_for_diagnostics(tcx)?;
1115 String::from_utf8(data.to_owned()).ok().map(Constant::Str)
1116 },
1117 (ConstValue::Indirect { alloc_id, offset }, ty::Array(sub_type, len)) => {
1118 let alloc = tcx.global_alloc(alloc_id).unwrap_memory().inner();
1119 let len = len.try_to_target_usize(tcx)?;
1120 let ty::Float(flt) = sub_type.kind() else {
1121 return None;
1122 };
1123 let size = Size::from_bits(flt.bit_width());
1124 let mut res = Vec::new();
1125 for idx in 0..len {
1126 let range = alloc_range(offset + size * idx, size);
1127 let val = alloc.read_scalar(&tcx, range, false).ok()?;
1128 res.push(match flt {
1129 FloatTy::F16 => Constant::F16(val.to_u16().discard_err()?),
1130 FloatTy::F32 => Constant::F32(f32::from_bits(val.to_u32().discard_err()?)),
1131 FloatTy::F64 => Constant::F64(f64::from_bits(val.to_u64().discard_err()?)),
1132 FloatTy::F128 => Constant::F128(val.to_u128().discard_err()?),
1133 });
1134 }
1135 Some(Constant::Vec(res))
1136 },
1137 _ => None,
1138 }
1139}
1140
1141fn field_of_struct<'tcx>(
1142 adt_def: ty::AdtDef<'tcx>,
1143 tcx: TyCtxt<'tcx>,
1144 value: ConstValue,
1145 ty: Ty<'tcx>,
1146 field: Symbol,
1147) -> Option<(ConstValue, Ty<'tcx>)> {
1148 if let Some(dc) = tcx.try_destructure_mir_constant_for_user_output(value, ty)
1149 && let Some(dc_variant) = dc.variant
1150 && let Some(variant) = adt_def.variants().get(dc_variant)
1151 && let Some(field_idx) = variant.fields.iter().position(|el| el.name == field)
1152 {
1153 dc.fields.get(field_idx).copied()
1154 } else {
1155 None
1156 }
1157}
1158
1159pub fn integer_const(cx: &LateContext<'_>, expr: &Expr<'_>, ctxt: SyntaxContext) -> Option<u128> {
1166 if let Some(Constant::Int(value)) = ConstEvalCtxt::new(cx).eval_local(expr, ctxt) {
1167 Some(value)
1168 } else {
1169 None
1170 }
1171}
1172
1173#[inline]
1180pub fn is_zero_integer_const(cx: &LateContext<'_>, expr: &Expr<'_>, ctxt: SyntaxContext) -> bool {
1181 integer_const(cx, expr, ctxt) == Some(0)
1182}
1183
1184pub fn const_item_rhs_to_expr<'tcx>(tcx: TyCtxt<'tcx>, ct_rhs: ConstItemRhs<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1185 match ct_rhs {
1186 ConstItemRhs::Body(body_id) => Some(tcx.hir_body(body_id).value),
1187 ConstItemRhs::Direct(const_arg) => match const_arg.kind {
1188 ConstArgKind::Anon(anon) => Some(tcx.hir_body(anon.body).value),
1189 ConstArgKind::Struct(..)
1190 | ConstArgKind::Tup(..)
1191 | ConstArgKind::Literal { .. }
1192 | ConstArgKind::TupleCall(..)
1193 | ConstArgKind::Array(..)
1194 | ConstArgKind::Path(_)
1195 | ConstArgKind::Error(..)
1196 | ConstArgKind::Infer(..) => None,
1197 },
1198 }
1199}