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;
8use crate::source::{SpanRangeExt, walk_span_to_context};
9use crate::{clip, is_direct_expn_of, sext, sym, unsext};
10
11use rustc_abi::Size;
12use rustc_apfloat::Float;
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::ConstValue;
23use rustc_middle::mir::interpret::{Scalar, alloc_range};
24use rustc_middle::ty::{self, FloatTy, IntTy, ScalarInt, Ty, TyCtxt, TypeckResults, UintTy};
25use rustc_middle::{bug, mir, span_bug};
26use rustc_span::{Symbol, SyntaxContext};
27use std::cell::Cell;
28use std::cmp::Ordering;
29use std::hash::{Hash, Hasher};
30use std::iter;
31
32/// A `LitKind`-like enum to fold constant `Expr`s into.
33#[derive(Debug, Clone)]
34pub enum Constant {
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    pub fn partial_cmp(tcx: TyCtxt<'_>, cmp_type: Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
210        match (left, right) {
211            (Self::Str(ls), Self::Str(rs)) => Some(ls.cmp(rs)),
212            (Self::Char(l), Self::Char(r)) => Some(l.cmp(r)),
213            (&Self::Int(l), &Self::Int(r)) => match *cmp_type.kind() {
214                ty::Int(int_ty) => Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty))),
215                ty::Uint(_) => Some(l.cmp(&r)),
216                _ => bug!("Not an int type"),
217            },
218            (&Self::F64(l), &Self::F64(r)) => l.partial_cmp(&r),
219            (&Self::F32(l), &Self::F32(r)) => l.partial_cmp(&r),
220            (Self::Bool(l), Self::Bool(r)) => Some(l.cmp(r)),
221            (Self::Tuple(l), Self::Tuple(r)) if l.len() == r.len() => match *cmp_type.kind() {
222                ty::Tuple(tys) if tys.len() == l.len() => l
223                    .iter()
224                    .zip(r)
225                    .zip(tys)
226                    .map(|((li, ri), cmp_type)| Self::partial_cmp(tcx, cmp_type, li, ri))
227                    .find(|r| r.is_none_or(|o| o != Ordering::Equal))
228                    .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
229                _ => None,
230            },
231            (Self::Vec(l), Self::Vec(r)) => {
232                let cmp_type = cmp_type.builtin_index()?;
233                iter::zip(l, r)
234                    .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
235                    .find(|r| r.is_none_or(|o| o != Ordering::Equal))
236                    .unwrap_or_else(|| Some(l.len().cmp(&r.len())))
237            },
238            (Self::Repeat(lv, ls), Self::Repeat(rv, rs)) => {
239                match Self::partial_cmp(
240                    tcx,
241                    match *cmp_type.kind() {
242                        ty::Array(ty, _) => ty,
243                        _ => return None,
244                    },
245                    lv,
246                    rv,
247                ) {
248                    Some(Ordering::Equal) => Some(ls.cmp(rs)),
249                    x => x,
250                }
251            },
252            (Self::Ref(lb), Self::Ref(rb)) => Self::partial_cmp(
253                tcx,
254                match *cmp_type.kind() {
255                    ty::Ref(_, ty, _) => ty,
256                    _ => return None,
257                },
258                lb,
259                rb,
260            ),
261            // TODO: are there any useful inter-type orderings?
262            _ => None,
263        }
264    }
265
266    /// Returns the integer value or `None` if `self` or `val_type` is not integer type.
267    pub fn int_value(&self, tcx: TyCtxt<'_>, val_type: Ty<'_>) -> Option<FullInt> {
268        if let Constant::Int(const_int) = *self {
269            match *val_type.kind() {
270                ty::Int(ity) => Some(FullInt::S(sext(tcx, const_int, ity))),
271                ty::Uint(_) => Some(FullInt::U(const_int)),
272                _ => None,
273            }
274        } else {
275            None
276        }
277    }
278
279    #[must_use]
280    pub fn peel_refs(mut self) -> Self {
281        while let Constant::Ref(r) = self {
282            self = *r;
283        }
284        self
285    }
286
287    fn parse_f16(s: &str) -> Self {
288        let f: Half = s.parse().unwrap();
289        Self::F16(f.to_bits().try_into().unwrap())
290    }
291
292    fn parse_f128(s: &str) -> Self {
293        let f: Quad = s.parse().unwrap();
294        Self::F128(f.to_bits())
295    }
296
297    pub fn new_numeric_min<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Self> {
298        match *ty.kind() {
299            ty::Uint(_) => Some(Self::Int(0)),
300            ty::Int(ty) => {
301                let val = match ty.normalize(tcx.sess.target.pointer_width) {
302                    IntTy::I8 => i128::from(i8::MIN),
303                    IntTy::I16 => i128::from(i16::MIN),
304                    IntTy::I32 => i128::from(i32::MIN),
305                    IntTy::I64 => i128::from(i64::MIN),
306                    IntTy::I128 => i128::MIN,
307                    IntTy::Isize => return None,
308                };
309                Some(Self::Int(val.cast_unsigned()))
310            },
311            ty::Char => Some(Self::Char(char::MIN)),
312            ty::Float(FloatTy::F32) => Some(Self::F32(f32::NEG_INFINITY)),
313            ty::Float(FloatTy::F64) => Some(Self::F64(f64::NEG_INFINITY)),
314            _ => None,
315        }
316    }
317
318    pub fn new_numeric_max<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Self> {
319        match *ty.kind() {
320            ty::Uint(ty) => Some(Self::Int(match ty.normalize(tcx.sess.target.pointer_width) {
321                UintTy::U8 => u128::from(u8::MAX),
322                UintTy::U16 => u128::from(u16::MAX),
323                UintTy::U32 => u128::from(u32::MAX),
324                UintTy::U64 => u128::from(u64::MAX),
325                UintTy::U128 => u128::MAX,
326                UintTy::Usize => return None,
327            })),
328            ty::Int(ty) => {
329                let val = match ty.normalize(tcx.sess.target.pointer_width) {
330                    IntTy::I8 => i128::from(i8::MAX),
331                    IntTy::I16 => i128::from(i16::MAX),
332                    IntTy::I32 => i128::from(i32::MAX),
333                    IntTy::I64 => i128::from(i64::MAX),
334                    IntTy::I128 => i128::MAX,
335                    IntTy::Isize => return None,
336                };
337                Some(Self::Int(val.cast_unsigned()))
338            },
339            ty::Char => Some(Self::Char(char::MAX)),
340            ty::Float(FloatTy::F32) => Some(Self::F32(f32::INFINITY)),
341            ty::Float(FloatTy::F64) => Some(Self::F64(f64::INFINITY)),
342            _ => None,
343        }
344    }
345
346    pub fn is_numeric_min<'tcx>(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
347        match (self, ty.kind()) {
348            (&Self::Int(x), &ty::Uint(_)) => x == 0,
349            (&Self::Int(x), &ty::Int(ty)) => {
350                let limit = match ty.normalize(tcx.sess.target.pointer_width) {
351                    IntTy::I8 => i128::from(i8::MIN),
352                    IntTy::I16 => i128::from(i16::MIN),
353                    IntTy::I32 => i128::from(i32::MIN),
354                    IntTy::I64 => i128::from(i64::MIN),
355                    IntTy::I128 => i128::MIN,
356                    IntTy::Isize => return false,
357                };
358                x.cast_signed() == limit
359            },
360            (&Self::Char(x), &ty::Char) => x == char::MIN,
361            (&Self::F32(x), &ty::Float(FloatTy::F32)) => x == f32::NEG_INFINITY,
362            (&Self::F64(x), &ty::Float(FloatTy::F64)) => x == f64::NEG_INFINITY,
363            _ => false,
364        }
365    }
366
367    pub fn is_numeric_max<'tcx>(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
368        match (self, ty.kind()) {
369            (&Self::Int(x), &ty::Uint(ty)) => {
370                let limit = match ty.normalize(tcx.sess.target.pointer_width) {
371                    UintTy::U8 => u128::from(u8::MAX),
372                    UintTy::U16 => u128::from(u16::MAX),
373                    UintTy::U32 => u128::from(u32::MAX),
374                    UintTy::U64 => u128::from(u64::MAX),
375                    UintTy::U128 => u128::MAX,
376                    UintTy::Usize => return false,
377                };
378                x == limit
379            },
380            (&Self::Int(x), &ty::Int(ty)) => {
381                let limit = match ty.normalize(tcx.sess.target.pointer_width) {
382                    IntTy::I8 => i128::from(i8::MAX),
383                    IntTy::I16 => i128::from(i16::MAX),
384                    IntTy::I32 => i128::from(i32::MAX),
385                    IntTy::I64 => i128::from(i64::MAX),
386                    IntTy::I128 => i128::MAX,
387                    IntTy::Isize => return false,
388                };
389                x.cast_signed() == limit
390            },
391            (&Self::Char(x), &ty::Char) => x == char::MAX,
392            (&Self::F32(x), &ty::Float(FloatTy::F32)) => x == f32::INFINITY,
393            (&Self::F64(x), &ty::Float(FloatTy::F64)) => x == f64::INFINITY,
394            _ => false,
395        }
396    }
397
398    pub fn is_pos_infinity(&self) -> bool {
399        match *self {
400            // FIXME(f16_f128): add f16 and f128 when constants are available
401            Constant::F32(x) => x == f32::INFINITY,
402            Constant::F64(x) => x == f64::INFINITY,
403            _ => false,
404        }
405    }
406
407    pub fn is_neg_infinity(&self) -> bool {
408        match *self {
409            // FIXME(f16_f128): add f16 and f128 when constants are available
410            Constant::F32(x) => x == f32::NEG_INFINITY,
411            Constant::F64(x) => x == f64::NEG_INFINITY,
412            _ => false,
413        }
414    }
415}
416
417/// Parses a `LitKind` to a `Constant`.
418pub fn lit_to_mir_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
419    match *lit {
420        LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
421        LitKind::Byte(b) => Constant::Int(u128::from(b)),
422        LitKind::ByteStr(ref s, _) | LitKind::CStr(ref s, _) => Constant::Binary(s.as_byte_str().to_vec()),
423        LitKind::Char(c) => Constant::Char(c),
424        LitKind::Int(n, _) => Constant::Int(n.get()),
425        LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {
426            // FIXME(f16_f128): just use `parse()` directly when available for `f16`/`f128`
427            FloatTy::F16 => Constant::parse_f16(is.as_str()),
428            FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()),
429            FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()),
430            FloatTy::F128 => Constant::parse_f128(is.as_str()),
431        },
432        LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind() {
433            ty::Float(FloatTy::F16) => Constant::parse_f16(is.as_str()),
434            ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
435            ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
436            ty::Float(FloatTy::F128) => Constant::parse_f128(is.as_str()),
437            _ => bug!(),
438        },
439        LitKind::Bool(b) => Constant::Bool(b),
440        LitKind::Err(_) => Constant::Err,
441    }
442}
443
444/// The source of a constant value.
445#[derive(Clone, Copy)]
446pub enum ConstantSource {
447    /// The value is determined solely from the expression.
448    Local,
449    /// The value is dependent on another definition that may change independently from the local
450    /// expression.
451    NonLocal,
452}
453impl ConstantSource {
454    pub fn is_local(self) -> bool {
455        matches!(self, Self::Local)
456    }
457}
458
459#[derive(Copy, Clone, Debug, Eq)]
460pub enum FullInt {
461    S(i128),
462    U(u128),
463}
464
465impl PartialEq for FullInt {
466    fn eq(&self, other: &Self) -> bool {
467        self.cmp(other) == Ordering::Equal
468    }
469}
470
471impl PartialOrd for FullInt {
472    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
473        Some(self.cmp(other))
474    }
475}
476
477impl Ord for FullInt {
478    fn cmp(&self, other: &Self) -> Ordering {
479        use FullInt::{S, U};
480
481        fn cmp_s_u(s: i128, u: u128) -> Ordering {
482            u128::try_from(s).map_or(Ordering::Less, |x| x.cmp(&u))
483        }
484
485        match (*self, *other) {
486            (S(s), S(o)) => s.cmp(&o),
487            (U(s), U(o)) => s.cmp(&o),
488            (S(s), U(o)) => cmp_s_u(s, o),
489            (U(s), S(o)) => cmp_s_u(o, s).reverse(),
490        }
491    }
492}
493
494/// The context required to evaluate a constant expression.
495///
496/// This is currently limited to constant folding and reading the value of named constants.
497///
498/// See the module level documentation for some context.
499pub struct ConstEvalCtxt<'tcx> {
500    tcx: TyCtxt<'tcx>,
501    typing_env: ty::TypingEnv<'tcx>,
502    typeck: &'tcx TypeckResults<'tcx>,
503    source: Cell<ConstantSource>,
504    ctxt: Cell<SyntaxContext>,
505}
506
507impl<'tcx> ConstEvalCtxt<'tcx> {
508    /// Creates the evaluation context from the lint context. This requires the lint context to be
509    /// in a body (i.e. `cx.enclosing_body.is_some()`).
510    pub fn new(cx: &LateContext<'tcx>) -> Self {
511        Self {
512            tcx: cx.tcx,
513            typing_env: cx.typing_env(),
514            typeck: cx.typeck_results(),
515            source: Cell::new(ConstantSource::Local),
516            ctxt: Cell::new(SyntaxContext::root()),
517        }
518    }
519
520    /// Creates an evaluation context.
521    pub fn with_env(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, typeck: &'tcx TypeckResults<'tcx>) -> Self {
522        Self {
523            tcx,
524            typing_env,
525            typeck,
526            source: Cell::new(ConstantSource::Local),
527            ctxt: Cell::new(SyntaxContext::root()),
528        }
529    }
530
531    /// Attempts to evaluate the expression and returns both the value and whether it's dependant on
532    /// other items.
533    pub fn eval_with_source(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<(Constant, ConstantSource)> {
534        self.source.set(ConstantSource::Local);
535        self.ctxt.set(ctxt);
536        self.expr(e).map(|c| (c, self.source.get()))
537    }
538
539    /// Attempts to evaluate the expression.
540    pub fn eval(&self, e: &Expr<'_>) -> Option<Constant> {
541        self.expr(e)
542    }
543
544    /// Attempts to evaluate the expression without accessing other items.
545    ///
546    /// The context argument is the context used to view the evaluated expression. e.g. when
547    /// evaluating the argument in `f(m!(1))` the context of the call expression should be used.
548    /// This is need so the const evaluator can see the `m` macro and marke the evaluation as
549    /// non-local independant of what the macro expands to.
550    pub fn eval_local(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<Constant> {
551        match self.eval_with_source(e, ctxt) {
552            Some((x, ConstantSource::Local)) => Some(x),
553            _ => None,
554        }
555    }
556
557    /// Attempts to evaluate the expression as an integer without accessing other items.
558    ///
559    /// The context argument is the context used to view the evaluated expression. e.g. when
560    /// evaluating the argument in `f(m!(1))` the context of the call expression should be used.
561    /// This is need so the const evaluator can see the `m` macro and marke the evaluation as
562    /// non-local independant of what the macro expands to.
563    pub fn eval_full_int(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<FullInt> {
564        match self.eval_with_source(e, ctxt) {
565            Some((x, ConstantSource::Local)) => x.int_value(self.tcx, self.typeck.expr_ty(e)),
566            _ => None,
567        }
568    }
569
570    pub fn eval_pat_expr(&self, pat_expr: &PatExpr<'_>) -> Option<Constant> {
571        match &pat_expr.kind {
572            PatExprKind::Lit { lit, negated } => {
573                let ty = self.typeck.node_type_opt(pat_expr.hir_id);
574                let val = lit_to_mir_constant(&lit.node, ty);
575                if *negated {
576                    self.constant_negate(&val, ty?)
577                } else {
578                    Some(val)
579                }
580            },
581            PatExprKind::Path(qpath) => self.qpath(qpath, pat_expr.hir_id),
582        }
583    }
584
585    fn check_ctxt(&self, ctxt: SyntaxContext) {
586        if self.ctxt.get() != ctxt {
587            self.source.set(ConstantSource::NonLocal);
588        }
589    }
590
591    fn qpath(&self, qpath: &QPath<'_>, hir_id: HirId) -> Option<Constant> {
592        self.fetch_path(qpath, hir_id)
593            .and_then(|c| mir_to_const(self.tcx, c, self.typeck.node_type(hir_id)))
594    }
595
596    /// Simple constant folding: Insert an expression, get a constant or none.
597    fn expr(&self, e: &Expr<'_>) -> Option<Constant> {
598        self.check_ctxt(e.span.ctxt());
599        match e.kind {
600            ExprKind::ConstBlock(ConstBlock { body, .. }) => self.expr(self.tcx.hir_body(body).value),
601            ExprKind::DropTemps(e) => self.expr(e),
602            ExprKind::Path(ref qpath) => self.qpath(qpath, e.hir_id),
603            ExprKind::Block(block, _) => {
604                self.check_ctxt(block.span.ctxt());
605                self.block(block)
606            },
607            ExprKind::Lit(lit) => {
608                self.check_ctxt(lit.span.ctxt());
609                Some(lit_to_mir_constant(&lit.node, self.typeck.expr_ty_opt(e)))
610            },
611            ExprKind::Array(vec) => self.multi(vec).map(Constant::Vec),
612            ExprKind::Tup(tup) => self.multi(tup).map(Constant::Tuple),
613            ExprKind::Repeat(value, _) => {
614                let n = match self.typeck.expr_ty(e).kind() {
615                    ty::Array(_, n) => n.try_to_target_usize(self.tcx)?,
616                    _ => span_bug!(e.span, "typeck error"),
617                };
618                self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
619            },
620            ExprKind::Unary(op, operand) => self.expr(operand).and_then(|o| match op {
621                UnOp::Not => self.constant_not(&o, self.typeck.expr_ty(e)),
622                UnOp::Neg => self.constant_negate(&o, self.typeck.expr_ty(e)),
623                UnOp::Deref => Some(if let Constant::Ref(r) = o { *r } else { o }),
624            }),
625            ExprKind::If(cond, then, ref otherwise) => self.ifthenelse(cond, then, *otherwise),
626            ExprKind::Binary(op, left, right) => {
627                self.check_ctxt(e.span.ctxt());
628                self.binop(op.node, left, right)
629            },
630            ExprKind::Call(callee, []) => {
631                // We only handle a few const functions for now.
632                if let ExprKind::Path(qpath) = &callee.kind
633                    && let Some(did) = self.typeck.qpath_res(qpath, callee.hir_id).opt_def_id()
634                {
635                    match self.tcx.get_diagnostic_name(did) {
636                        Some(sym::i8_legacy_fn_max_value) => Some(Constant::Int(i8::MAX as u128)),
637                        Some(sym::i16_legacy_fn_max_value) => Some(Constant::Int(i16::MAX as u128)),
638                        Some(sym::i32_legacy_fn_max_value) => Some(Constant::Int(i32::MAX as u128)),
639                        Some(sym::i64_legacy_fn_max_value) => Some(Constant::Int(i64::MAX as u128)),
640                        Some(sym::i128_legacy_fn_max_value) => Some(Constant::Int(i128::MAX as u128)),
641                        _ => None,
642                    }
643                } else {
644                    None
645                }
646            },
647            ExprKind::Index(arr, index, _) => self.index(arr, index),
648            ExprKind::AddrOf(_, _, inner) => self.expr(inner).map(|r| Constant::Ref(Box::new(r))),
649            ExprKind::Field(base, ref field)
650                if let base_ty = self.typeck.expr_ty(base)
651                    && match self.typeck.expr_adjustments(base) {
652                        [] => true,
653                        [.., a] => a.target == base_ty,
654                    }
655                    && let Some(Constant::Adt(constant)) = self.expr(base)
656                    && let ty::Adt(adt_def, _) = *base_ty.kind()
657                    && adt_def.is_struct()
658                    && let Some((desired_field, ty)) =
659                        field_of_struct(adt_def, self.tcx, constant, base_ty, field.name) =>
660            {
661                self.check_ctxt(field.span.ctxt());
662                mir_to_const(self.tcx, desired_field, ty)
663            },
664            _ => None,
665        }
666    }
667
668    /// Simple constant folding to determine if an expression is an empty slice, str, array, …
669    /// `None` will be returned if the constness cannot be determined, or if the resolution
670    /// leaves the local crate.
671    pub fn eval_is_empty(&self, e: &Expr<'_>) -> Option<bool> {
672        match e.kind {
673            ExprKind::ConstBlock(ConstBlock { body, .. }) => self.eval_is_empty(self.tcx.hir_body(body).value),
674            ExprKind::DropTemps(e) => self.eval_is_empty(e),
675            ExprKind::Lit(lit) => {
676                if is_direct_expn_of(e.span, sym::cfg).is_some() {
677                    None
678                } else {
679                    match &lit.node {
680                        LitKind::Str(is, _) => Some(is.is_empty()),
681                        LitKind::ByteStr(s, _) | LitKind::CStr(s, _) => Some(s.as_byte_str().is_empty()),
682                        _ => None,
683                    }
684                }
685            },
686            ExprKind::Array(vec) => self.multi(vec).map(|v| v.is_empty()),
687            ExprKind::Repeat(..) => {
688                if let ty::Array(_, n) = self.typeck.expr_ty(e).kind() {
689                    Some(n.try_to_target_usize(self.tcx)? == 0)
690                } else {
691                    span_bug!(e.span, "typeck error");
692                }
693            },
694            _ => None,
695        }
696    }
697
698    #[expect(clippy::cast_possible_wrap)]
699    fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
700        use self::Constant::{Bool, Int};
701        match *o {
702            Bool(b) => Some(Bool(!b)),
703            Int(value) => {
704                let value = !value;
705                match *ty.kind() {
706                    ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
707                    ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
708                    _ => None,
709                }
710            },
711            _ => None,
712        }
713    }
714
715    fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
716        use self::Constant::{F32, F64, Int};
717        match *o {
718            Int(value) => {
719                let ty::Int(ity) = *ty.kind() else { return None };
720                let (min, _) = ity.min_max()?;
721                // sign extend
722                let value = sext(self.tcx, value, ity);
723
724                // Applying unary - to the most negative value of any signed integer type panics.
725                if value == min {
726                    return None;
727                }
728
729                let value = value.checked_neg()?;
730                // clear unused bits
731                Some(Int(unsext(self.tcx, value, ity)))
732            },
733            F32(f) => Some(F32(-f)),
734            F64(f) => Some(F64(-f)),
735            _ => None,
736        }
737    }
738
739    /// Create `Some(Vec![..])` of all constants, unless there is any
740    /// non-constant part.
741    fn multi(&self, vec: &[Expr<'_>]) -> Option<Vec<Constant>> {
742        vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
743    }
744
745    /// Lookup a possibly constant expression from an `ExprKind::Path` and apply a function on it.
746    #[expect(clippy::too_many_lines)]
747    fn fetch_path(&self, qpath: &QPath<'_>, id: HirId) -> Option<ConstValue> {
748        // Resolve the path to a constant and check if that constant is known to
749        // not change based on the target.
750        //
751        // This should be replaced with an attribute at some point.
752        let did = match *qpath {
753            QPath::Resolved(None, path)
754                if path.span.ctxt() == self.ctxt.get()
755                    && path.segments.iter().all(|s| self.ctxt.get() == s.ident.span.ctxt())
756                    && let Res::Def(DefKind::Const, did) = path.res
757                    && (matches!(
758                        self.tcx.get_diagnostic_name(did),
759                        Some(
760                            sym::f32_legacy_const_digits
761                                | sym::f32_legacy_const_epsilon
762                                | sym::f32_legacy_const_infinity
763                                | sym::f32_legacy_const_mantissa_dig
764                                | sym::f32_legacy_const_max
765                                | sym::f32_legacy_const_max_10_exp
766                                | sym::f32_legacy_const_max_exp
767                                | sym::f32_legacy_const_min
768                                | sym::f32_legacy_const_min_10_exp
769                                | sym::f32_legacy_const_min_exp
770                                | sym::f32_legacy_const_min_positive
771                                | sym::f32_legacy_const_nan
772                                | sym::f32_legacy_const_neg_infinity
773                                | sym::f32_legacy_const_radix
774                                | sym::f64_legacy_const_digits
775                                | sym::f64_legacy_const_epsilon
776                                | sym::f64_legacy_const_infinity
777                                | sym::f64_legacy_const_mantissa_dig
778                                | sym::f64_legacy_const_max
779                                | sym::f64_legacy_const_max_10_exp
780                                | sym::f64_legacy_const_max_exp
781                                | sym::f64_legacy_const_min
782                                | sym::f64_legacy_const_min_10_exp
783                                | sym::f64_legacy_const_min_exp
784                                | sym::f64_legacy_const_min_positive
785                                | sym::f64_legacy_const_nan
786                                | sym::f64_legacy_const_neg_infinity
787                                | sym::f64_legacy_const_radix
788                                | sym::u8_legacy_const_min
789                                | sym::u16_legacy_const_min
790                                | sym::u32_legacy_const_min
791                                | sym::u64_legacy_const_min
792                                | sym::u128_legacy_const_min
793                                | sym::usize_legacy_const_min
794                                | sym::u8_legacy_const_max
795                                | sym::u16_legacy_const_max
796                                | sym::u32_legacy_const_max
797                                | sym::u64_legacy_const_max
798                                | sym::u128_legacy_const_max
799                                | sym::i8_legacy_const_min
800                                | sym::i16_legacy_const_min
801                                | sym::i32_legacy_const_min
802                                | sym::i64_legacy_const_min
803                                | sym::i128_legacy_const_min
804                                | sym::i8_legacy_const_max
805                                | sym::i16_legacy_const_max
806                                | sym::i32_legacy_const_max
807                                | sym::i64_legacy_const_max
808                                | sym::i128_legacy_const_max
809                        )
810                    ) || self.tcx.opt_parent(did).is_some_and(|parent| {
811                        matches!(
812                            parent.opt_diag_name(&self.tcx),
813                            Some(
814                                sym::f16_consts_mod | sym::f32_consts_mod | sym::f64_consts_mod | sym::f128_consts_mod
815                            )
816                        )
817                    })) =>
818            {
819                did
820            },
821            QPath::TypeRelative(ty, const_name)
822                if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind
823                    && let [.., ty_name] = ty_path.segments
824                    && (matches!(
825                        ty_name.ident.name,
826                        sym::i8
827                            | sym::i16
828                            | sym::i32
829                            | sym::i64
830                            | sym::i128
831                            | sym::u8
832                            | sym::u16
833                            | sym::u32
834                            | sym::u64
835                            | sym::u128
836                            | sym::f32
837                            | sym::f64
838                            | sym::char
839                    ) || (ty_name.ident.name == sym::usize && const_name.ident.name == sym::MIN))
840                    && const_name.ident.span.ctxt() == self.ctxt.get()
841                    && ty.span.ctxt() == self.ctxt.get()
842                    && ty_name.ident.span.ctxt() == self.ctxt.get()
843                    && matches!(ty_path.res, Res::PrimTy(_))
844                    && let Some((DefKind::AssocConst, did)) = self.typeck.type_dependent_def(id) =>
845            {
846                did
847            },
848            _ if let Res::Def(DefKind::Const | DefKind::AssocConst, did) = self.typeck.qpath_res(qpath, id) => {
849                self.source.set(ConstantSource::NonLocal);
850                did
851            },
852            _ => return None,
853        };
854
855        self.tcx
856            .const_eval_resolve(
857                self.typing_env,
858                mir::UnevaluatedConst::new(did, self.typeck.node_args(id)),
859                qpath.span(),
860            )
861            .ok()
862    }
863
864    fn index(&self, lhs: &'_ Expr<'_>, index: &'_ Expr<'_>) -> Option<Constant> {
865        let lhs = self.expr(lhs);
866        let index = self.expr(index);
867
868        match (lhs, index) {
869            (Some(Constant::Vec(vec)), Some(Constant::Int(index))) => match vec.get(index as usize) {
870                Some(Constant::F16(x)) => Some(Constant::F16(*x)),
871                Some(Constant::F32(x)) => Some(Constant::F32(*x)),
872                Some(Constant::F64(x)) => Some(Constant::F64(*x)),
873                Some(Constant::F128(x)) => Some(Constant::F128(*x)),
874                _ => None,
875            },
876            (Some(Constant::Vec(vec)), _) => {
877                if !vec.is_empty() && vec.iter().all(|x| *x == vec[0]) {
878                    match vec.first() {
879                        Some(Constant::F16(x)) => Some(Constant::F16(*x)),
880                        Some(Constant::F32(x)) => Some(Constant::F32(*x)),
881                        Some(Constant::F64(x)) => Some(Constant::F64(*x)),
882                        Some(Constant::F128(x)) => Some(Constant::F128(*x)),
883                        _ => None,
884                    }
885                } else {
886                    None
887                }
888            },
889            _ => None,
890        }
891    }
892
893    /// A block can only yield a constant if it has exactly one constant expression.
894    fn block(&self, block: &Block<'_>) -> Option<Constant> {
895        if block.stmts.is_empty()
896            && let Some(expr) = block.expr
897        {
898            // Try to detect any `cfg`ed statements or empty macro expansions.
899            let span = block.span.data();
900            if span.ctxt == SyntaxContext::root() {
901                if let Some(expr_span) = walk_span_to_context(expr.span, span.ctxt)
902                    && let expr_lo = expr_span.lo()
903                    && expr_lo >= span.lo
904                    && let Some(src) = (span.lo..expr_lo).get_source_range(&self.tcx)
905                    && let Some(src) = src.as_str()
906                {
907                    use rustc_lexer::TokenKind::{BlockComment, LineComment, OpenBrace, Semi, Whitespace};
908                    if !tokenize(src, FrontmatterAllowed::No)
909                        .map(|t| t.kind)
910                        .filter(|t| !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. } | Semi))
911                        .eq([OpenBrace])
912                    {
913                        self.source.set(ConstantSource::NonLocal);
914                    }
915                } else {
916                    // Unable to access the source. Assume a non-local dependency.
917                    self.source.set(ConstantSource::NonLocal);
918                }
919            }
920
921            self.expr(expr)
922        } else {
923            None
924        }
925    }
926
927    fn ifthenelse(&self, cond: &Expr<'_>, then: &Expr<'_>, otherwise: Option<&Expr<'_>>) -> Option<Constant> {
928        if let Some(Constant::Bool(b)) = self.expr(cond) {
929            if b {
930                self.expr(then)
931            } else {
932                otherwise.as_ref().and_then(|expr| self.expr(expr))
933            }
934        } else {
935            None
936        }
937    }
938
939    fn binop(&self, op: BinOpKind, left: &Expr<'_>, right: &Expr<'_>) -> Option<Constant> {
940        let l = self.expr(left)?;
941        let r = self.expr(right);
942        match (l, r) {
943            (Constant::Int(l), Some(Constant::Int(r))) => match *self.typeck.expr_ty_opt(left)?.kind() {
944                ty::Int(ity) => {
945                    let (ty_min_value, _) = ity.min_max()?;
946                    let bits = ity.bits();
947                    let l = sext(self.tcx, l, ity);
948                    let r = sext(self.tcx, r, ity);
949
950                    // Using / or %, where the left-hand argument is the smallest integer of a signed integer type and
951                    // the right-hand argument is -1 always panics, even with overflow-checks disabled
952                    if let BinOpKind::Div | BinOpKind::Rem = op
953                        && l == ty_min_value
954                        && r == -1
955                    {
956                        return None;
957                    }
958
959                    let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
960                    match op {
961                        // When +, * or binary - create a value greater than the maximum value, or less than
962                        // the minimum value that can be stored, it panics.
963                        BinOpKind::Add => l.checked_add(r).and_then(|n| ity.ensure_fits(n)).map(zext),
964                        BinOpKind::Sub => l.checked_sub(r).and_then(|n| ity.ensure_fits(n)).map(zext),
965                        BinOpKind::Mul => l.checked_mul(r).and_then(|n| ity.ensure_fits(n)).map(zext),
966                        BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
967                        BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
968                        // Using << or >> where the right-hand argument is greater than or equal to the number of bits
969                        // in the type of the left-hand argument, or is negative panics.
970                        BinOpKind::Shr if r < bits && !r.is_negative() => l.checked_shr(r.try_into().ok()?).map(zext),
971                        BinOpKind::Shl if r < bits && !r.is_negative() => l.checked_shl(r.try_into().ok()?).map(zext),
972                        BinOpKind::BitXor => Some(zext(l ^ r)),
973                        BinOpKind::BitOr => Some(zext(l | r)),
974                        BinOpKind::BitAnd => Some(zext(l & r)),
975                        // FIXME: f32/f64 currently consider `0.0` and `-0.0` as different.
976                        BinOpKind::Eq => Some(Constant::Bool(l == r)),
977                        BinOpKind::Ne => Some(Constant::Bool(l != r)),
978                        BinOpKind::Lt => Some(Constant::Bool(l < r)),
979                        BinOpKind::Le => Some(Constant::Bool(l <= r)),
980                        BinOpKind::Ge => Some(Constant::Bool(l >= r)),
981                        BinOpKind::Gt => Some(Constant::Bool(l > r)),
982                        _ => None,
983                    }
984                },
985                ty::Uint(ity) => {
986                    let bits = ity.bits();
987
988                    match op {
989                        BinOpKind::Add => l.checked_add(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
990                        BinOpKind::Sub => l.checked_sub(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
991                        BinOpKind::Mul => l.checked_mul(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
992                        BinOpKind::Div => l.checked_div(r).map(Constant::Int),
993                        BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
994                        BinOpKind::Shr if r < bits => l.checked_shr(r.try_into().ok()?).map(Constant::Int),
995                        BinOpKind::Shl if r < bits => l.checked_shl(r.try_into().ok()?).map(Constant::Int),
996                        BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
997                        BinOpKind::BitOr => Some(Constant::Int(l | r)),
998                        BinOpKind::BitAnd => Some(Constant::Int(l & r)),
999                        BinOpKind::Eq => Some(Constant::Bool(l == r)),
1000                        BinOpKind::Ne => Some(Constant::Bool(l != r)),
1001                        BinOpKind::Lt => Some(Constant::Bool(l < r)),
1002                        BinOpKind::Le => Some(Constant::Bool(l <= r)),
1003                        BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1004                        BinOpKind::Gt => Some(Constant::Bool(l > r)),
1005                        _ => None,
1006                    }
1007                },
1008                _ => None,
1009            },
1010            // FIXME(f16_f128): add these types when binary operations are available on all platforms
1011            (Constant::F32(l), Some(Constant::F32(r))) => match op {
1012                BinOpKind::Add => Some(Constant::F32(l + r)),
1013                BinOpKind::Sub => Some(Constant::F32(l - r)),
1014                BinOpKind::Mul => Some(Constant::F32(l * r)),
1015                BinOpKind::Div => Some(Constant::F32(l / r)),
1016                BinOpKind::Rem => Some(Constant::F32(l % r)),
1017                BinOpKind::Eq => Some(Constant::Bool(l == r)),
1018                BinOpKind::Ne => Some(Constant::Bool(l != r)),
1019                BinOpKind::Lt => Some(Constant::Bool(l < r)),
1020                BinOpKind::Le => Some(Constant::Bool(l <= r)),
1021                BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1022                BinOpKind::Gt => Some(Constant::Bool(l > r)),
1023                _ => None,
1024            },
1025            (Constant::F64(l), Some(Constant::F64(r))) => match op {
1026                BinOpKind::Add => Some(Constant::F64(l + r)),
1027                BinOpKind::Sub => Some(Constant::F64(l - r)),
1028                BinOpKind::Mul => Some(Constant::F64(l * r)),
1029                BinOpKind::Div => Some(Constant::F64(l / r)),
1030                BinOpKind::Rem => Some(Constant::F64(l % r)),
1031                BinOpKind::Eq => Some(Constant::Bool(l == r)),
1032                BinOpKind::Ne => Some(Constant::Bool(l != r)),
1033                BinOpKind::Lt => Some(Constant::Bool(l < r)),
1034                BinOpKind::Le => Some(Constant::Bool(l <= r)),
1035                BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1036                BinOpKind::Gt => Some(Constant::Bool(l > r)),
1037                _ => None,
1038            },
1039            (l, r) => match (op, l, r) {
1040                (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
1041                (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
1042                (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
1043                    Some(r)
1044                },
1045                (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
1046                (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
1047                (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
1048                _ => None,
1049            },
1050        }
1051    }
1052}
1053
1054pub fn mir_to_const<'tcx>(tcx: TyCtxt<'tcx>, val: ConstValue, ty: Ty<'tcx>) -> Option<Constant> {
1055    match (val, ty.kind()) {
1056        (_, &ty::Adt(adt_def, _)) if adt_def.is_struct() => Some(Constant::Adt(val)),
1057        (ConstValue::Scalar(Scalar::Int(int)), _) => match ty.kind() {
1058            ty::Bool => Some(Constant::Bool(int == ScalarInt::TRUE)),
1059            ty::Uint(_) | ty::Int(_) => Some(Constant::Int(int.to_bits(int.size()))),
1060            ty::Float(FloatTy::F16) => Some(Constant::F16(int.into())),
1061            ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(int.into()))),
1062            ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(int.into()))),
1063            ty::Float(FloatTy::F128) => Some(Constant::F128(int.into())),
1064            ty::RawPtr(_, _) => Some(Constant::RawPtr(int.to_bits(int.size()))),
1065            _ => None,
1066        },
1067        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1068            let data = val.try_get_slice_bytes_for_diagnostics(tcx)?;
1069            String::from_utf8(data.to_owned()).ok().map(Constant::Str)
1070        },
1071        (ConstValue::Indirect { alloc_id, offset }, ty::Array(sub_type, len)) => {
1072            let alloc = tcx.global_alloc(alloc_id).unwrap_memory().inner();
1073            let len = len.try_to_target_usize(tcx)?;
1074            let ty::Float(flt) = sub_type.kind() else {
1075                return None;
1076            };
1077            let size = Size::from_bits(flt.bit_width());
1078            let mut res = Vec::new();
1079            for idx in 0..len {
1080                let range = alloc_range(offset + size * idx, size);
1081                let val = alloc.read_scalar(&tcx, range, /* read_provenance */ false).ok()?;
1082                res.push(match flt {
1083                    FloatTy::F16 => Constant::F16(val.to_u16().discard_err()?),
1084                    FloatTy::F32 => Constant::F32(f32::from_bits(val.to_u32().discard_err()?)),
1085                    FloatTy::F64 => Constant::F64(f64::from_bits(val.to_u64().discard_err()?)),
1086                    FloatTy::F128 => Constant::F128(val.to_u128().discard_err()?),
1087                });
1088            }
1089            Some(Constant::Vec(res))
1090        },
1091        _ => None,
1092    }
1093}
1094
1095fn field_of_struct<'tcx>(
1096    adt_def: ty::AdtDef<'tcx>,
1097    tcx: TyCtxt<'tcx>,
1098    value: ConstValue,
1099    ty: Ty<'tcx>,
1100    field: Symbol,
1101) -> Option<(ConstValue, Ty<'tcx>)> {
1102    if let Some(dc) = tcx.try_destructure_mir_constant_for_user_output(value, ty)
1103        && let Some(dc_variant) = dc.variant
1104        && let Some(variant) = adt_def.variants().get(dc_variant)
1105        && let Some(field_idx) = variant.fields.iter().position(|el| el.name == field)
1106    {
1107        dc.fields.get(field_idx).copied()
1108    } else {
1109        None
1110    }
1111}
1112
1113/// If `expr` evaluates to an integer constant, return its value.
1114///
1115/// The context argument is the context used to view the evaluated expression. e.g. when evaluating
1116/// the argument in `f(m!(1))` the context of the call expression should be used. This is need so
1117/// the const evaluator can see the `m` macro and marke the evaluation as non-local independant of
1118/// what the macro expands to.
1119pub fn integer_const(cx: &LateContext<'_>, expr: &Expr<'_>, ctxt: SyntaxContext) -> Option<u128> {
1120    if let Some(Constant::Int(value)) = ConstEvalCtxt::new(cx).eval_local(expr, ctxt) {
1121        Some(value)
1122    } else {
1123        None
1124    }
1125}
1126
1127/// Check if `expr` evaluates to an integer constant of 0.
1128///
1129/// The context argument is the context used to view the evaluated expression. e.g. when evaluating
1130/// the argument in `f(m!(1))` the context of the call expression should be used. This is need so
1131/// the const evaluator can see the `m` macro and marke the evaluation as non-local independant of
1132/// what the macro expands to.
1133#[inline]
1134pub fn is_zero_integer_const(cx: &LateContext<'_>, expr: &Expr<'_>, ctxt: SyntaxContext) -> bool {
1135    integer_const(cx, expr, ctxt) == Some(0)
1136}
1137
1138pub fn const_item_rhs_to_expr<'tcx>(tcx: TyCtxt<'tcx>, ct_rhs: ConstItemRhs<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1139    match ct_rhs {
1140        ConstItemRhs::Body(body_id) => Some(tcx.hir_body(body_id).value),
1141        ConstItemRhs::TypeConst(const_arg) => match const_arg.kind {
1142            ConstArgKind::Anon(anon) => Some(tcx.hir_body(anon.body).value),
1143            ConstArgKind::Struct(..) | ConstArgKind::Path(_) | ConstArgKind::Error(..) | ConstArgKind::Infer(..) => {
1144                None
1145            },
1146        },
1147    }
1148}