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