Skip to main content

clippy_utils/
consts.rs

1//! A simple const eval API, for use on arbitrary HIR expressions.
2//!
3//! This cannot use rustc's const eval, aka miri, as arbitrary HIR expressions cannot be lowered to
4//! executable MIR bodies, so we have to do this instead.
5#![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/// A `LitKind`-like enum to fold constant `Expr`s into.
32#[derive(Debug, Clone)]
33pub enum Constant {
34    /// A constant representing an [algebraic data type](https://rustc-dev-guide.rust-lang.org/ty-module/generic-arguments.html#adts-and-generic-arguments)
35    Adt(ConstValue),
36    /// A `String` (e.g., "abc").
37    Str(String),
38    /// A binary string (e.g., `b"abc"`).
39    Binary(Vec<u8>),
40    /// A single `char` (e.g., `'a'`).
41    Char(char),
42    /// An integer's bit representation.
43    Int(u128),
44    /// An `f16` bitcast to a `u16`.
45    // FIXME(f16_f128): use `f16` once builtins are available on all host tools platforms.
46    F16(u16),
47    /// An `f32`.
48    F32(f32),
49    /// An `f64`.
50    F64(f64),
51    /// An `f128` bitcast to a `u128`.
52    // FIXME(f16_f128): use `f128` once builtins are available on all host tools platforms.
53    F128(u128),
54    /// `true` or `false`.
55    Bool(bool),
56    /// An array of constants.
57    Vec(Vec<Self>),
58    /// Also an array, but with only one constant, repeated N times.
59    Repeat(Box<Self>, u64),
60    /// A tuple of constants.
61    Tuple(Vec<Self>),
62    /// A raw pointer.
63    RawPtr(u128),
64    /// A reference
65    Ref(Box<Self>),
66    /// A literal with syntax error.
67    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                // `to_bits` is required to catch non-matching `0.0` and `-0.0`.
136                l.to_bits() == r.to_bits() && !l.is_nan()
137            },
138            (&Self::F32(l), &Self::F32(r)) => {
139                // `to_bits` is required to catch non-matching `0.0` and `-0.0`.
140                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            // TODO: are there inter-type equalities?
147            _ => 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                // FIXME(f16_f128): once conversions to/from `f128` are available on all platforms,
176                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    /// Returns an ordering between `left` and `right`, if one exists. `cmp_type` determines
210    /// comparison behavior for constants with ambiguous typing (ex. [`Constant::Int`], which may be
211    /// signed or unsigned).
212    ///
213    /// # Panics
214    ///
215    /// Panics if the compared type is ambiguous and `cmp_type` describes a nonsensical type. For
216    /// example, if `left` and `right` are [`Constant::Int`], `cmp_type.kind()` must be either
217    /// [`Int`](ty::Int) or [`Uint`](ty::Uint).
218    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            // TODO: are there any useful inter-type orderings?
271            _ => None,
272        }
273    }
274
275    /// Returns the integer value or `None` if `self` or `val_type` is not integer type.
276    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    /// Consume [`Constant::Ref`], removing all references to return the contained expression, e.g.
289    /// `&&T` -> `T`.
290    #[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    /// Create a constant representing the minimum value of the type described by `ty`, if one
309    /// is defined.
310    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    /// Create a constant representing the maximum value of the type described by `ty`, if one
332    /// is defined.
333    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    /// Checks whether `self` is a numeric of the type `ty` and whether `self` is the minimum value
362    /// of that type.
363    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    /// Checks whether `self` is a numeric of the type `ty` and whether `self` is the maximum value
385    /// of that type.
386    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    /// Checks whether `self` is a floating-point value representing positive infinity.
418    pub fn is_pos_infinity(&self) -> bool {
419        match *self {
420            // FIXME(f16_f128): add f16 and f128 when constants are available
421            Constant::F32(x) => x == f32::INFINITY,
422            Constant::F64(x) => x == f64::INFINITY,
423            _ => false,
424        }
425    }
426
427    /// Checks whether `self` is a floating-point value representing negative infinity.
428    pub fn is_neg_infinity(&self) -> bool {
429        match *self {
430            // FIXME(f16_f128): add f16 and f128 when constants are available
431            Constant::F32(x) => x == f32::NEG_INFINITY,
432            Constant::F64(x) => x == f64::NEG_INFINITY,
433            _ => false,
434        }
435    }
436
437    pub fn to_int(&self, tcx: TyCtxt<'_>, ty: IntTy) -> Option<i128> {
438        match *self {
439            Self::Int(x) => Some(sext(tcx, x, ty)),
440            _ => None,
441        }
442    }
443}
444
445/// Parses a `LitKind` to a `Constant`.
446pub fn lit_to_mir_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
447    match *lit {
448        LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
449        LitKind::Byte(b) => Constant::Int(u128::from(b)),
450        LitKind::ByteStr(ref s, _) | LitKind::CStr(ref s, _) => Constant::Binary(s.as_byte_str().to_vec()),
451        LitKind::Char(c) => Constant::Char(c),
452        LitKind::Int(n, _) => Constant::Int(n.get()),
453        LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {
454            // FIXME(f16_f128): just use `parse()` directly when available for `f16`/`f128`
455            FloatTy::F16 => Constant::parse_f16(is.as_str()),
456            FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()),
457            FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()),
458            FloatTy::F128 => Constant::parse_f128(is.as_str()),
459        },
460        LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind() {
461            ty::Float(FloatTy::F16) => Constant::parse_f16(is.as_str()),
462            ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
463            ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
464            ty::Float(FloatTy::F128) => Constant::parse_f128(is.as_str()),
465            _ => bug!(),
466        },
467        LitKind::Bool(b) => Constant::Bool(b),
468        LitKind::Err(_) => Constant::Err,
469    }
470}
471
472/// The source of a constant value.
473#[derive(Clone, Copy)]
474pub enum ConstantSource {
475    /// The value is determined solely from the expression.
476    Local,
477    /// The value is dependent on another definition that may change independently from the local
478    /// expression.
479    NonLocal,
480}
481impl ConstantSource {
482    /// Checks whether this constant value is determined solely from its expression, and is not
483    /// dependent on another definition.
484    pub fn is_local(self) -> bool {
485        matches!(self, Self::Local)
486    }
487}
488
489/// An integer type (signed or unsigned) with enough bits to represent any integer that can be
490/// represented in Rust.
491#[derive(Copy, Clone, Debug, Eq)]
492pub enum FullInt {
493    /// Signed full int
494    S(i128),
495    /// Unsigned full int
496    U(u128),
497}
498
499impl FullInt {
500    /// Checks whether the current full int is equal to zero, regardless of whether its signed or unsigned.
501    pub fn is_zero(self) -> bool {
502        matches!(self, Self::S(0) | Self::U(0))
503    }
504}
505
506impl PartialEq for FullInt {
507    fn eq(&self, other: &Self) -> bool {
508        self.cmp(other) == Ordering::Equal
509    }
510}
511
512impl PartialOrd for FullInt {
513    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
514        Some(self.cmp(other))
515    }
516}
517
518impl Ord for FullInt {
519    fn cmp(&self, other: &Self) -> Ordering {
520        use FullInt::{S, U};
521
522        fn cmp_s_u(s: i128, u: u128) -> Ordering {
523            u128::try_from(s).map_or(Ordering::Less, |x| x.cmp(&u))
524        }
525
526        match (*self, *other) {
527            (S(s), S(o)) => s.cmp(&o),
528            (U(s), U(o)) => s.cmp(&o),
529            (S(s), U(o)) => cmp_s_u(s, o),
530            (U(s), S(o)) => cmp_s_u(o, s).reverse(),
531        }
532    }
533}
534
535/// Evaluates an expression if it's a builtin integer type.
536pub fn eval_int(cx: &LateContext<'_>, e: &Expr<'_>) -> Option<FullInt> {
537    match e.kind {
538        ExprKind::Lit(lit) if let LitKind::Int(val, _) = lit.node => Some(FullInt::U(val.0)),
539        ExprKind::Unary(UnOp::Neg, e)
540            if let ExprKind::Lit(lit) = e.kind
541                && let LitKind::Int(val, _) = lit.node =>
542        {
543            Some(FullInt::S(val.0.cast_signed().wrapping_neg()))
544        },
545        _ if let ty = cx.typeck_results().expr_ty(e)
546            && let ty::Int(_) | ty::Uint(_) = *ty.kind() =>
547        {
548            ConstEvalCtxt::new(cx).eval(e).and_then(|x| x.int_value(cx.tcx, ty))
549        },
550        _ => None,
551    }
552}
553
554/// The context required to evaluate a constant expression.
555///
556/// This is currently limited to constant folding and reading the value of named constants.
557///
558/// See the module level documentation for some context.
559pub struct ConstEvalCtxt<'tcx> {
560    pub tcx: TyCtxt<'tcx>,
561    pub typing_env: ty::TypingEnv<'tcx>,
562    pub typeck: &'tcx TypeckResults<'tcx>,
563    source: Cell<ConstantSource>,
564    ctxt: Cell<SyntaxContext>,
565}
566
567impl<'tcx> ConstEvalCtxt<'tcx> {
568    /// Creates the evaluation context from the lint context. This requires the lint context to be
569    /// in a body (i.e. `cx.enclosing_body.is_some()`).
570    pub fn new(cx: &LateContext<'tcx>) -> Self {
571        Self {
572            tcx: cx.tcx,
573            typing_env: cx.typing_env(),
574            typeck: cx.typeck_results(),
575            source: Cell::new(ConstantSource::Local),
576            ctxt: Cell::new(SyntaxContext::root()),
577        }
578    }
579
580    /// Creates an evaluation context.
581    pub fn with_env(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, typeck: &'tcx TypeckResults<'tcx>) -> Self {
582        Self {
583            tcx,
584            typing_env,
585            typeck,
586            source: Cell::new(ConstantSource::Local),
587            ctxt: Cell::new(SyntaxContext::root()),
588        }
589    }
590
591    /// Attempts to evaluate the expression and returns both the value and whether it's dependant on
592    /// other items.
593    pub fn eval_with_source(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<(Constant, ConstantSource)> {
594        self.source.set(ConstantSource::Local);
595        self.ctxt.set(ctxt);
596        self.expr(e).map(|c| (c, self.source.get()))
597    }
598
599    /// Attempts to evaluate the expression.
600    pub fn eval(&self, e: &Expr<'_>) -> Option<Constant> {
601        self.expr(e)
602    }
603
604    /// Attempts to evaluate the expression and optionally dereference the result.
605    pub fn eval_deref(&self, e: &Expr<'_>, deref: bool) -> Option<Constant> {
606        match (self.eval(e), deref) {
607            (Some(c), false) => Some(c),
608            (Some(Constant::Ref(c)), true) => Some(*c),
609            _ => None,
610        }
611    }
612
613    /// Attempts to evaluate the expression without accessing other items.
614    ///
615    /// The context argument is the context used to view the evaluated expression. e.g. when
616    /// evaluating the argument in `f(m!(1))` the context of the call expression should be used.
617    /// This is need so the const evaluator can see the `m` macro and marke the evaluation as
618    /// non-local independant of what the macro expands to.
619    pub fn eval_local(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<Constant> {
620        match self.eval_with_source(e, ctxt) {
621            Some((x, ConstantSource::Local)) => Some(x),
622            _ => None,
623        }
624    }
625
626    /// Attempts to evaluate the expression as an integer without accessing other items.
627    ///
628    /// The context argument is the context used to view the evaluated expression. e.g. when
629    /// evaluating the argument in `f(m!(1))` the context of the call expression should be used.
630    /// This is need so the const evaluator can see the `m` macro and marke the evaluation as
631    /// non-local independant of what the macro expands to.
632    pub fn eval_full_int(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<FullInt> {
633        match self.eval_with_source(e, ctxt) {
634            Some((x, ConstantSource::Local)) => x.int_value(self.tcx, self.typeck.expr_ty(e)),
635            _ => None,
636        }
637    }
638
639    /// Attempts to evaluate the given [pattern expression](PatExpr) as a [`Constant`].
640    pub fn eval_pat_expr(&self, pat_expr: &PatExpr<'_>) -> Option<Constant> {
641        match &pat_expr.kind {
642            PatExprKind::Lit { lit, negated } => {
643                let ty = self.typeck.node_type_opt(pat_expr.hir_id);
644                let val = lit_to_mir_constant(&lit.node, ty);
645                if *negated {
646                    self.constant_negate(&val, ty?)
647                } else {
648                    Some(val)
649                }
650            },
651            PatExprKind::Path(qpath) => self.qpath(qpath, pat_expr.hir_id),
652        }
653    }
654
655    fn check_ctxt(&self, ctxt: SyntaxContext) {
656        if self.ctxt.get() != ctxt {
657            self.source.set(ConstantSource::NonLocal);
658        }
659    }
660
661    fn qpath(&self, qpath: &QPath<'_>, hir_id: HirId) -> Option<Constant> {
662        self.fetch_path(qpath, hir_id)
663            .and_then(|c| mir_to_const(self.tcx, c, self.typeck.node_type(hir_id)))
664    }
665
666    /// Simple constant folding: Insert an expression, get a constant or none.
667    fn expr(&self, e: &Expr<'_>) -> Option<Constant> {
668        self.check_ctxt(e.span.ctxt());
669        match e.kind {
670            ExprKind::ConstBlock(ConstBlock { body, .. }) => self.expr(self.tcx.hir_body(body).value),
671            ExprKind::DropTemps(e) => self.expr(e),
672            ExprKind::Path(ref qpath) => self.qpath(qpath, e.hir_id),
673            ExprKind::Block(block, _) => {
674                self.check_ctxt(block.span.ctxt());
675                self.block(block)
676            },
677            ExprKind::Lit(lit) => {
678                self.check_ctxt(lit.span.ctxt());
679                Some(lit_to_mir_constant(&lit.node, self.typeck.expr_ty_opt(e)))
680            },
681            ExprKind::Array(vec) => self.multi(vec).map(Constant::Vec),
682            ExprKind::Tup(tup) => self.multi(tup).map(Constant::Tuple),
683            ExprKind::Repeat(value, _) => {
684                let n = match self.typeck.expr_ty(e).kind() {
685                    ty::Array(_, n) => n.try_to_target_usize(self.tcx)?,
686                    _ => span_bug!(e.span, "typeck error"),
687                };
688                self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
689            },
690            ExprKind::Unary(op, operand) => self.expr(operand).and_then(|o| match op {
691                UnOp::Not => self.constant_not(&o, self.typeck.expr_ty(e)),
692                UnOp::Neg => self.constant_negate(&o, self.typeck.expr_ty(e)),
693                UnOp::Deref => Some(if let Constant::Ref(r) = o { *r } else { o }),
694            }),
695            ExprKind::If(cond, then, ref otherwise) => self.ifthenelse(cond, then, *otherwise),
696            ExprKind::Binary(op, left, right) => {
697                self.check_ctxt(e.span.ctxt());
698                self.binop(op.node, left, right)
699            },
700            ExprKind::Call(callee, []) => {
701                // We only handle a few const functions for now.
702                if let ExprKind::Path(qpath) = &callee.kind
703                    && let Some(did) = self.typeck.qpath_res(qpath, callee.hir_id).opt_def_id()
704                {
705                    match self.tcx.get_diagnostic_name(did) {
706                        Some(sym::i8_legacy_fn_max_value) => Some(Constant::Int(i8::MAX as u128)),
707                        Some(sym::i16_legacy_fn_max_value) => Some(Constant::Int(i16::MAX as u128)),
708                        Some(sym::i32_legacy_fn_max_value) => Some(Constant::Int(i32::MAX as u128)),
709                        Some(sym::i64_legacy_fn_max_value) => Some(Constant::Int(i64::MAX as u128)),
710                        Some(sym::i128_legacy_fn_max_value) => Some(Constant::Int(i128::MAX as u128)),
711                        _ => None,
712                    }
713                } else {
714                    None
715                }
716            },
717            ExprKind::Index(arr, index, _) => self.index(arr, index),
718            ExprKind::AddrOf(_, _, inner) => self.expr(inner).map(|r| Constant::Ref(Box::new(r))),
719            ExprKind::Field(base, ref field)
720                if let base_ty = self.typeck.expr_ty(base)
721                    && match self.typeck.expr_adjustments(base) {
722                        [] => true,
723                        [.., a] => a.target == base_ty,
724                    }
725                    && let Some(Constant::Adt(constant)) = self.expr(base)
726                    && let ty::Adt(adt_def, _) = *base_ty.kind()
727                    && adt_def.is_struct()
728                    && let Some((desired_field, ty)) =
729                        field_of_struct(adt_def, self.tcx, constant, base_ty, field.name) =>
730            {
731                self.check_ctxt(field.span.ctxt());
732                mir_to_const(self.tcx, desired_field, ty)
733            },
734            _ => None,
735        }
736    }
737
738    /// Simple constant folding to determine if an expression is an empty slice, str, array, …
739    /// `None` will be returned if the constness cannot be determined, or if the resolution
740    /// leaves the local crate.
741    pub fn eval_is_empty(&self, e: &Expr<'_>) -> Option<bool> {
742        match e.kind {
743            ExprKind::ConstBlock(ConstBlock { body, .. }) => self.eval_is_empty(self.tcx.hir_body(body).value),
744            ExprKind::DropTemps(e) => self.eval_is_empty(e),
745            ExprKind::Lit(lit) => {
746                if is_direct_expn_of(e.span, sym::cfg).is_some() {
747                    None
748                } else {
749                    match &lit.node {
750                        LitKind::Str(is, _) => Some(is.is_empty()),
751                        LitKind::ByteStr(s, _) | LitKind::CStr(s, _) => Some(s.as_byte_str().is_empty()),
752                        _ => None,
753                    }
754                }
755            },
756            ExprKind::Array(vec) => self.multi(vec).map(|v| v.is_empty()),
757            ExprKind::Repeat(..) => {
758                if let ty::Array(_, n) = self.typeck.expr_ty(e).kind() {
759                    Some(n.try_to_target_usize(self.tcx)? == 0)
760                } else {
761                    span_bug!(e.span, "typeck error");
762                }
763            },
764            _ => None,
765        }
766    }
767
768    #[expect(clippy::cast_possible_wrap)]
769    fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
770        use self::Constant::{Bool, Int};
771        match *o {
772            Bool(b) => Some(Bool(!b)),
773            Int(value) => {
774                let value = !value;
775                match *ty.kind() {
776                    ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
777                    ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
778                    _ => None,
779                }
780            },
781            _ => None,
782        }
783    }
784
785    fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
786        use self::Constant::{F32, F64, Int};
787        match *o {
788            Int(value) => {
789                let ty::Int(ity) = *ty.kind() else { return None };
790                let (min, _) = ity.min_max()?;
791                // sign extend
792                let value = sext(self.tcx, value, ity);
793
794                // Applying unary - to the most negative value of any signed integer type panics.
795                if value == min {
796                    return None;
797                }
798
799                let value = value.checked_neg()?;
800                // clear unused bits
801                Some(Int(unsext(self.tcx, value, ity)))
802            },
803            F32(f) => Some(F32(-f)),
804            F64(f) => Some(F64(-f)),
805            _ => None,
806        }
807    }
808
809    /// Create `Some(Vec![..])` of all constants, unless there is any
810    /// non-constant part.
811    fn multi(&self, vec: &[Expr<'_>]) -> Option<Vec<Constant>> {
812        vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
813    }
814
815    /// Lookup a possibly constant expression from an `ExprKind::Path` and apply a function on it.
816    #[expect(clippy::too_many_lines)]
817    fn fetch_path(&self, qpath: &QPath<'_>, id: HirId) -> Option<ConstValue> {
818        // Resolve the path to a constant and check if that constant is known to
819        // not change based on the target.
820        //
821        // This should be replaced with an attribute at some point.
822        let did = match *qpath {
823            QPath::Resolved(None, path)
824                if path.span.ctxt() == self.ctxt.get()
825                    && path.segments.iter().all(|s| self.ctxt.get() == s.ident.span.ctxt())
826                    && let Res::Def(DefKind::Const, did) = path.res
827                    && (matches!(
828                        self.tcx.get_diagnostic_name(did),
829                        Some(
830                            sym::f32_legacy_const_digits
831                                | sym::f32_legacy_const_epsilon
832                                | sym::f32_legacy_const_infinity
833                                | sym::f32_legacy_const_mantissa_dig
834                                | sym::f32_legacy_const_max
835                                | sym::f32_legacy_const_max_10_exp
836                                | sym::f32_legacy_const_max_exp
837                                | sym::f32_legacy_const_min
838                                | sym::f32_legacy_const_min_10_exp
839                                | sym::f32_legacy_const_min_exp
840                                | sym::f32_legacy_const_min_positive
841                                | sym::f32_legacy_const_nan
842                                | sym::f32_legacy_const_neg_infinity
843                                | sym::f32_legacy_const_radix
844                                | sym::f64_legacy_const_digits
845                                | sym::f64_legacy_const_epsilon
846                                | sym::f64_legacy_const_infinity
847                                | sym::f64_legacy_const_mantissa_dig
848                                | sym::f64_legacy_const_max
849                                | sym::f64_legacy_const_max_10_exp
850                                | sym::f64_legacy_const_max_exp
851                                | sym::f64_legacy_const_min
852                                | sym::f64_legacy_const_min_10_exp
853                                | sym::f64_legacy_const_min_exp
854                                | sym::f64_legacy_const_min_positive
855                                | sym::f64_legacy_const_nan
856                                | sym::f64_legacy_const_neg_infinity
857                                | sym::f64_legacy_const_radix
858                                | sym::u8_legacy_const_min
859                                | sym::u16_legacy_const_min
860                                | sym::u32_legacy_const_min
861                                | sym::u64_legacy_const_min
862                                | sym::u128_legacy_const_min
863                                | sym::usize_legacy_const_min
864                                | sym::u8_legacy_const_max
865                                | sym::u16_legacy_const_max
866                                | sym::u32_legacy_const_max
867                                | sym::u64_legacy_const_max
868                                | sym::u128_legacy_const_max
869                                | sym::i8_legacy_const_min
870                                | sym::i16_legacy_const_min
871                                | sym::i32_legacy_const_min
872                                | sym::i64_legacy_const_min
873                                | sym::i128_legacy_const_min
874                                | sym::i8_legacy_const_max
875                                | sym::i16_legacy_const_max
876                                | sym::i32_legacy_const_max
877                                | sym::i64_legacy_const_max
878                                | sym::i128_legacy_const_max
879                        )
880                    ) || self.tcx.opt_parent(did).is_some_and(|parent| {
881                        matches!(
882                            parent.opt_diag_name(&self.tcx),
883                            Some(
884                                sym::f16_consts_mod | sym::f32_consts_mod | sym::f64_consts_mod | sym::f128_consts_mod
885                            )
886                        )
887                    })) =>
888            {
889                did
890            },
891            QPath::TypeRelative(ty, const_name)
892                if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind
893                    && let [.., ty_name] = ty_path.segments
894                    && (matches!(
895                        ty_name.ident.name,
896                        sym::i8
897                            | sym::i16
898                            | sym::i32
899                            | sym::i64
900                            | sym::i128
901                            | sym::u8
902                            | sym::u16
903                            | sym::u32
904                            | sym::u64
905                            | sym::u128
906                            | sym::f32
907                            | sym::f64
908                            | sym::char
909                    ) || (ty_name.ident.name == sym::usize && const_name.ident.name == sym::MIN))
910                    && const_name.ident.span.ctxt() == self.ctxt.get()
911                    && ty.span.ctxt() == self.ctxt.get()
912                    && ty_name.ident.span.ctxt() == self.ctxt.get()
913                    && matches!(ty_path.res, Res::PrimTy(_))
914                    && let Some((DefKind::AssocConst, did)) = self.typeck.type_dependent_def(id)
915                    && self.tcx.inherent_impl_of_assoc(did).is_some() =>
916            {
917                did
918            },
919            // TODO: revisit when feature `gca_min_const_items` is stabilized. In the meantime,
920            // `TyCtxt::const_eval_resolve()` will trigger an ICE when evaluating the body of the
921            // `type const` definition.
922            _ if let Res::Def(DefKind::Const | DefKind::AssocConst, did) = self.typeck.qpath_res(qpath, id)
923                && !self.tcx.is_direct_const(did) =>
924            {
925                self.source.set(ConstantSource::NonLocal);
926                did
927            },
928            _ => return None,
929        };
930
931        let args = self.typeck.node_args(id);
932
933        if !args.is_empty() {
934            let owner_def_id = self.typeck.hir_owner.def_id.to_def_id();
935            let identity_args = ty::GenericArgs::identity_for_item(self.tcx, owner_def_id);
936            // Don't try to fully evaluate consts inside code whose bounds can't be satisfied.
937            if self
938                .tcx
939                .instantiate_and_check_impossible_clauses((owner_def_id, identity_args))
940            {
941                return None;
942            }
943        }
944
945        self.tcx
946            .const_eval_resolve(self.typing_env, mir::UnevaluatedConst::new(did, args), qpath.span())
947            .ok()
948    }
949
950    fn index(&self, lhs: &'_ Expr<'_>, index: &'_ Expr<'_>) -> Option<Constant> {
951        let lhs = self.expr(lhs);
952        let index = self.expr(index);
953
954        match (lhs, index) {
955            (Some(Constant::Vec(vec)), Some(Constant::Int(index))) => match vec.get(index as usize) {
956                Some(Constant::F16(x)) => Some(Constant::F16(*x)),
957                Some(Constant::F32(x)) => Some(Constant::F32(*x)),
958                Some(Constant::F64(x)) => Some(Constant::F64(*x)),
959                Some(Constant::F128(x)) => Some(Constant::F128(*x)),
960                _ => None,
961            },
962            (Some(Constant::Vec(vec)), _) => {
963                if !vec.is_empty() && vec.iter().all(|x| *x == vec[0]) {
964                    match vec.first() {
965                        Some(Constant::F16(x)) => Some(Constant::F16(*x)),
966                        Some(Constant::F32(x)) => Some(Constant::F32(*x)),
967                        Some(Constant::F64(x)) => Some(Constant::F64(*x)),
968                        Some(Constant::F128(x)) => Some(Constant::F128(*x)),
969                        _ => None,
970                    }
971                } else {
972                    None
973                }
974            },
975            _ => None,
976        }
977    }
978
979    /// A block can only yield a constant if it has exactly one constant expression.
980    fn block(&self, block: &Block<'_>) -> Option<Constant> {
981        if block.stmts.is_empty()
982            && let Some(expr) = block.expr
983        {
984            // Try to detect any `cfg`ed statements or empty macro expansions.
985            let span = block.span.data();
986            if span.ctxt == SyntaxContext::root() {
987                if let Some(expr_span) = walk_span_to_context(expr.span, span.ctxt)
988                    && let expr_lo = expr_span.lo()
989                    && expr_lo >= span.lo
990                    && let Some(src) = (span.lo..expr_lo).get_source_range(self.tcx)
991                    && let Some(src) = src.as_str()
992                {
993                    use rustc_lexer::TokenKind::{BlockComment, LineComment, OpenBrace, Semi, Whitespace};
994                    if !tokenize(src, FrontmatterAllowed::No)
995                        .map(|t| t.kind)
996                        .filter(|t| !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. } | Semi))
997                        .eq([OpenBrace])
998                    {
999                        self.source.set(ConstantSource::NonLocal);
1000                    }
1001                } else {
1002                    // Unable to access the source. Assume a non-local dependency.
1003                    self.source.set(ConstantSource::NonLocal);
1004                }
1005            }
1006
1007            self.expr(expr)
1008        } else {
1009            None
1010        }
1011    }
1012
1013    fn ifthenelse(&self, cond: &Expr<'_>, then: &Expr<'_>, otherwise: Option<&Expr<'_>>) -> Option<Constant> {
1014        if let Some(Constant::Bool(b)) = self.expr(cond) {
1015            if b {
1016                self.expr(then)
1017            } else {
1018                otherwise.as_ref().and_then(|expr| self.expr(expr))
1019            }
1020        } else {
1021            None
1022        }
1023    }
1024
1025    #[expect(clippy::too_many_lines)]
1026    fn binop(&self, op: BinOpKind, left: &Expr<'_>, right: &Expr<'_>) -> Option<Constant> {
1027        let l = self.expr(left)?;
1028        let r = self.expr(right);
1029        match (l, r) {
1030            (Constant::Int(l), Some(Constant::Int(r))) => match *self.typeck.expr_ty_opt(left)?.kind() {
1031                ty::Int(ity) => {
1032                    let (ty_min_value, _) = ity.min_max()?;
1033                    let bits = ity.bits();
1034                    let l = sext(self.tcx, l, ity);
1035                    let r = sext(self.tcx, r, ity);
1036
1037                    // Using / or %, where the left-hand argument is the smallest integer of a signed integer type and
1038                    // the right-hand argument is -1 always panics, even with overflow-checks disabled
1039                    if let BinOpKind::Div | BinOpKind::Rem = op
1040                        && l == ty_min_value
1041                        && r == -1
1042                    {
1043                        return None;
1044                    }
1045
1046                    let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
1047                    match op {
1048                        // When +, * or binary - create a value greater than the maximum value, or less than
1049                        // the minimum value that can be stored, it panics.
1050                        BinOpKind::Add => l.checked_add(r).and_then(|n| ity.ensure_fits(n)).map(zext),
1051                        BinOpKind::Sub => l.checked_sub(r).and_then(|n| ity.ensure_fits(n)).map(zext),
1052                        BinOpKind::Mul => l.checked_mul(r).and_then(|n| ity.ensure_fits(n)).map(zext),
1053                        BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
1054                        BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
1055                        // Using << or >> where the right-hand argument is greater than or equal to the number of bits
1056                        // in the type of the left-hand argument, or is negative panics.
1057                        BinOpKind::Shr if r < bits && !r.is_negative() => l.checked_shr(r.try_into().ok()?).map(zext),
1058                        BinOpKind::Shl if r < bits && !r.is_negative() => l.checked_shl(r.try_into().ok()?).map(zext),
1059                        BinOpKind::BitXor => Some(zext(l ^ r)),
1060                        BinOpKind::BitOr => Some(zext(l | r)),
1061                        BinOpKind::BitAnd => Some(zext(l & r)),
1062                        // FIXME: f32/f64 currently consider `0.0` and `-0.0` as different.
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                },
1072                ty::Uint(ity) => {
1073                    let bits = ity.bits();
1074                    let mask = !0u128 >> (128 - bits);
1075
1076                    match op {
1077                        BinOpKind::Add => l.checked_add(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
1078                        BinOpKind::Sub => l.checked_sub(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
1079                        BinOpKind::Mul => l.checked_mul(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
1080                        BinOpKind::Div => l.checked_div(r).map(Constant::Int),
1081                        BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
1082                        BinOpKind::Shr if r < bits => {
1083                            l.checked_shr(r.try_into().ok()?).map(|x| Constant::Int(x & mask))
1084                        },
1085                        BinOpKind::Shl if r < bits => {
1086                            l.checked_shl(r.try_into().ok()?).map(|x| Constant::Int(x & mask))
1087                        },
1088                        BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
1089                        BinOpKind::BitOr => Some(Constant::Int(l | r)),
1090                        BinOpKind::BitAnd => Some(Constant::Int(l & r)),
1091                        BinOpKind::Eq => Some(Constant::Bool(l == r)),
1092                        BinOpKind::Ne => Some(Constant::Bool(l != r)),
1093                        BinOpKind::Lt => Some(Constant::Bool(l < r)),
1094                        BinOpKind::Le => Some(Constant::Bool(l <= r)),
1095                        BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1096                        BinOpKind::Gt => Some(Constant::Bool(l > r)),
1097                        _ => None,
1098                    }
1099                },
1100                _ => None,
1101            },
1102            // FIXME(f16_f128): add these types when binary operations are available on all platforms
1103            (Constant::F32(l), Some(Constant::F32(r))) => match op {
1104                BinOpKind::Add => Some(Constant::F32(l + r)),
1105                BinOpKind::Sub => Some(Constant::F32(l - r)),
1106                BinOpKind::Mul => Some(Constant::F32(l * r)),
1107                BinOpKind::Div => Some(Constant::F32(l / r)),
1108                BinOpKind::Rem => Some(Constant::F32(l % r)),
1109                BinOpKind::Eq => Some(Constant::Bool(l == r)),
1110                BinOpKind::Ne => Some(Constant::Bool(l != r)),
1111                BinOpKind::Lt => Some(Constant::Bool(l < r)),
1112                BinOpKind::Le => Some(Constant::Bool(l <= r)),
1113                BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1114                BinOpKind::Gt => Some(Constant::Bool(l > r)),
1115                _ => None,
1116            },
1117            (Constant::F64(l), Some(Constant::F64(r))) => match op {
1118                BinOpKind::Add => Some(Constant::F64(l + r)),
1119                BinOpKind::Sub => Some(Constant::F64(l - r)),
1120                BinOpKind::Mul => Some(Constant::F64(l * r)),
1121                BinOpKind::Div => Some(Constant::F64(l / r)),
1122                BinOpKind::Rem => Some(Constant::F64(l % r)),
1123                BinOpKind::Eq => Some(Constant::Bool(l == r)),
1124                BinOpKind::Ne => Some(Constant::Bool(l != r)),
1125                BinOpKind::Lt => Some(Constant::Bool(l < r)),
1126                BinOpKind::Le => Some(Constant::Bool(l <= r)),
1127                BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1128                BinOpKind::Gt => Some(Constant::Bool(l > r)),
1129                _ => None,
1130            },
1131            (l, r) => match (op, l, r) {
1132                (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
1133                (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
1134                (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
1135                    Some(r)
1136                },
1137                (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
1138                (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
1139                (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
1140                _ => None,
1141            },
1142        }
1143    }
1144}
1145
1146/// Converts a [`ConstValue`] to a [`Constant`], if possible.
1147///
1148/// - If `ty` is an [`Adt`](ty::Adt) describing a struct, returns a [`Constant::Adt`] containing `val`.
1149/// - If `val` is a [`Int`](Scalar::Int), `ty` determines the variant of the returned constant:
1150///   - [`Bool`](ty::Bool) → [`Constant::Bool`]
1151///   - [`Uint`](ty::Uint)/[`Int`](ty::Int) → [`Constant::Int`]
1152///   - [`Float`](ty::Float) → [`Constant::F16`]/[`Constant::F32`]/[`Constant::F64`]/[`Constant::F128`], depending on
1153///     width
1154///   - [`RawPtr`](ty::RawPtr) → [`Constant::RawPtr`]
1155///   - any other `ty` → `None`
1156/// - If `ty` is a [`Ref`](ty::Ref) referring to a [`Str`](ty::Str) (i.e. a `&str`), returns a [`Constant::Str`].
1157/// - If `val` is a [`ConstValue::Indirect`] and `ty` is an [`Array`](ty::Array) of [`Float`](ty::Float), returns a
1158///   [`Constant::Vec`]
1159///
1160/// Otherwise, returns `None`.
1161pub fn mir_to_const<'tcx>(tcx: TyCtxt<'tcx>, val: ConstValue, ty: Ty<'tcx>) -> Option<Constant> {
1162    match (val, ty.kind()) {
1163        (_, &ty::Adt(adt_def, _)) if adt_def.is_struct() => Some(Constant::Adt(val)),
1164        (ConstValue::Scalar(Scalar::Int(int)), _) => match ty.kind() {
1165            ty::Bool => Some(Constant::Bool(int == ScalarInt::TRUE)),
1166            ty::Uint(_) | ty::Int(_) => Some(Constant::Int(int.to_bits(int.size()))),
1167            ty::Float(FloatTy::F16) => Some(Constant::F16(int.into())),
1168            ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(int.into()))),
1169            ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(int.into()))),
1170            ty::Float(FloatTy::F128) => Some(Constant::F128(int.into())),
1171            ty::RawPtr(_, _) => Some(Constant::RawPtr(int.to_bits(int.size()))),
1172            _ => None,
1173        },
1174        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1175            let data = val.try_get_slice_bytes_for_diagnostics(tcx)?;
1176            String::from_utf8(data.to_owned()).ok().map(Constant::Str)
1177        },
1178        (ConstValue::Indirect { alloc_id, offset }, ty::Array(sub_type, len)) => {
1179            let alloc = tcx.global_alloc(alloc_id).unwrap_memory().inner();
1180            let len = len.try_to_target_usize(tcx)?;
1181            let ty::Float(flt) = sub_type.kind() else {
1182                return None;
1183            };
1184            let size = Size::from_bits(flt.bit_width());
1185            let mut res = Vec::new();
1186            for idx in 0..len {
1187                let range = alloc_range(offset + size * idx, size);
1188                let val = alloc.read_scalar(&tcx, range, /* read_provenance */ false).ok()?;
1189                res.push(match flt {
1190                    FloatTy::F16 => Constant::F16(val.to_u16().discard_err()?),
1191                    FloatTy::F32 => Constant::F32(f32::from_bits(val.to_u32().discard_err()?)),
1192                    FloatTy::F64 => Constant::F64(f64::from_bits(val.to_u64().discard_err()?)),
1193                    FloatTy::F128 => Constant::F128(val.to_u128().discard_err()?),
1194                });
1195            }
1196            Some(Constant::Vec(res))
1197        },
1198        _ => None,
1199    }
1200}
1201
1202fn field_of_struct<'tcx>(
1203    adt_def: ty::AdtDef<'tcx>,
1204    tcx: TyCtxt<'tcx>,
1205    value: ConstValue,
1206    ty: Ty<'tcx>,
1207    field: Symbol,
1208) -> Option<(ConstValue, Ty<'tcx>)> {
1209    if let Some(dc) = tcx.try_destructure_mir_constant_for_user_output(value, ty)
1210        && let Some(dc_variant) = dc.variant
1211        && let Some(variant) = adt_def.variants().get(dc_variant)
1212        && let Some(field_idx) = variant.fields.iter().position(|el| el.name == field)
1213    {
1214        dc.fields.get(field_idx).copied()
1215    } else {
1216        None
1217    }
1218}
1219
1220/// If `expr` evaluates to an integer constant, return its value.
1221///
1222/// The context argument is the context used to view the evaluated expression. e.g. when evaluating
1223/// the argument in `f(m!(1))` the context of the call expression should be used. This is need so
1224/// the const evaluator can see the `m` macro and marke the evaluation as non-local independant of
1225/// what the macro expands to.
1226pub fn integer_const(cx: &LateContext<'_>, expr: &Expr<'_>, ctxt: SyntaxContext) -> Option<u128> {
1227    if let Some(Constant::Int(value)) = ConstEvalCtxt::new(cx).eval_local(expr, ctxt) {
1228        Some(value)
1229    } else {
1230        None
1231    }
1232}
1233
1234/// Check if `expr` evaluates to an integer constant of 0.
1235///
1236/// The context argument is the context used to view the evaluated expression. e.g. when evaluating
1237/// the argument in `f(m!(1))` the context of the call expression should be used. This is need so
1238/// the const evaluator can see the `m` macro and marke the evaluation as non-local independant of
1239/// what the macro expands to.
1240#[inline]
1241pub fn is_zero_integer_const(cx: &LateContext<'_>, expr: &Expr<'_>, ctxt: SyntaxContext) -> bool {
1242    integer_const(cx, expr, ctxt) == Some(0)
1243}
1244
1245/// Extracts the [`Expr`] backing a const item's right-hand side, if it has one.
1246pub fn const_item_rhs_to_expr<'tcx>(tcx: TyCtxt<'tcx>, ct_rhs: ConstItemRhs<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1247    match ct_rhs {
1248        ConstItemRhs::Body(body_id) => Some(tcx.hir_body(body_id).value),
1249        ConstItemRhs::Direct(const_arg) => match const_arg.kind {
1250            ConstArgKind::Anon(anon) => Some(tcx.hir_body(anon.body).value),
1251            ConstArgKind::Struct(..)
1252            | ConstArgKind::Tup(..)
1253            | ConstArgKind::Literal { .. }
1254            | ConstArgKind::TupleCall(..)
1255            | ConstArgKind::Array(..)
1256            | ConstArgKind::Path(_)
1257            | ConstArgKind::Error(..)
1258            | ConstArgKind::Infer(..) => None,
1259        },
1260    }
1261}