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#![allow(clippy::float_cmp)]
6
7use std::sync::Arc;
8
9use crate::source::{SpanRangeExt, walk_span_to_context};
10use crate::{clip, is_direct_expn_of, sext, unsext};
11
12use rustc_abi::Size;
13use rustc_apfloat::Float;
14use rustc_apfloat::ieee::{Half, Quad};
15use rustc_ast::ast::{self, LitFloatType, LitKind};
16use rustc_hir::def::{DefKind, Res};
17use rustc_hir::{
18    BinOp, BinOpKind, Block, ConstBlock, Expr, ExprKind, HirId, Item, ItemKind, Node, PatExpr, PatExprKind, QPath, UnOp,
19};
20use rustc_lexer::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::def_id::DefId;
27use rustc_span::symbol::Ident;
28use rustc_span::{SyntaxContext, sym};
29use std::cell::Cell;
30use std::cmp::Ordering;
31use std::hash::{Hash, Hasher};
32use std::iter;
33
34/// A `LitKind`-like enum to fold constant `Expr`s into.
35#[derive(Debug, Clone)]
36pub enum Constant<'tcx> {
37    Adt(mir::Const<'tcx>),
38    /// A `String` (e.g., "abc").
39    Str(String),
40    /// A binary string (e.g., `b"abc"`).
41    Binary(Arc<[u8]>),
42    /// A single `char` (e.g., `'a'`).
43    Char(char),
44    /// An integer's bit representation.
45    Int(u128),
46    /// An `f16`.
47    F16(f16),
48    /// An `f32`.
49    F32(f32),
50    /// An `f64`.
51    F64(f64),
52    /// An `f128`.
53    F128(f128),
54    /// `true` or `false`.
55    Bool(bool),
56    /// An array of constants.
57    Vec(Vec<Constant<'tcx>>),
58    /// Also an array, but with only one constant, repeated N times.
59    Repeat(Box<Constant<'tcx>>, u64),
60    /// A tuple of constants.
61    Tuple(Vec<Constant<'tcx>>),
62    /// A raw pointer.
63    RawPtr(u128),
64    /// A reference
65    Ref(Box<Constant<'tcx>>),
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                // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
136                // `Fw32 == Fw64`, so don’t compare them.
137                // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
138                l.to_bits() == r.to_bits()
139            },
140            (&Self::F32(l), &Self::F32(r)) => {
141                // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have
142                // `Fw32 == Fw64`, so don’t compare them.
143                // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs.
144                f64::from(l).to_bits() == f64::from(r).to_bits()
145            },
146            (&Self::Bool(l), &Self::Bool(r)) => l == r,
147            (&Self::Vec(ref l), &Self::Vec(ref r)) | (&Self::Tuple(ref l), &Self::Tuple(ref r)) => l == r,
148            (Self::Repeat(lv, ls), Self::Repeat(rv, rs)) => ls == rs && lv == rv,
149            (Self::Ref(lb), Self::Ref(rb)) => *lb == *rb,
150            // TODO: are there inter-type equalities?
151            _ => false,
152        }
153    }
154}
155
156impl Hash for Constant<'_> {
157    fn hash<H>(&self, state: &mut H)
158    where
159        H: Hasher,
160    {
161        std::mem::discriminant(self).hash(state);
162        match *self {
163            Self::Adt(ref elem) => {
164                elem.hash(state);
165            },
166            Self::Str(ref s) => {
167                s.hash(state);
168            },
169            Self::Binary(ref b) => {
170                b.hash(state);
171            },
172            Self::Char(c) => {
173                c.hash(state);
174            },
175            Self::Int(i) => {
176                i.hash(state);
177            },
178            Self::F16(f) => {
179                // FIXME(f16_f128): once conversions to/from `f128` are available on all platforms,
180                f.to_bits().hash(state);
181            },
182            Self::F32(f) => {
183                f64::from(f).to_bits().hash(state);
184            },
185            Self::F64(f) => {
186                f.to_bits().hash(state);
187            },
188            Self::F128(f) => {
189                f.to_bits().hash(state);
190            },
191            Self::Bool(b) => {
192                b.hash(state);
193            },
194            Self::Vec(ref v) | Self::Tuple(ref v) => {
195                v.hash(state);
196            },
197            Self::Repeat(ref c, l) => {
198                c.hash(state);
199                l.hash(state);
200            },
201            Self::RawPtr(u) => {
202                u.hash(state);
203            },
204            Self::Ref(ref r) => {
205                r.hash(state);
206            },
207            Self::Err => {},
208        }
209    }
210}
211
212impl Constant<'_> {
213    pub fn partial_cmp(tcx: TyCtxt<'_>, cmp_type: Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
214        match (left, right) {
215            (Self::Str(ls), Self::Str(rs)) => Some(ls.cmp(rs)),
216            (Self::Char(l), Self::Char(r)) => Some(l.cmp(r)),
217            (&Self::Int(l), &Self::Int(r)) => match *cmp_type.kind() {
218                ty::Int(int_ty) => Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty))),
219                ty::Uint(_) => Some(l.cmp(&r)),
220                _ => bug!("Not an int type"),
221            },
222            (&Self::F64(l), &Self::F64(r)) => l.partial_cmp(&r),
223            (&Self::F32(l), &Self::F32(r)) => l.partial_cmp(&r),
224            (Self::Bool(l), Self::Bool(r)) => Some(l.cmp(r)),
225            (Self::Tuple(l), Self::Tuple(r)) if l.len() == r.len() => match *cmp_type.kind() {
226                ty::Tuple(tys) if tys.len() == l.len() => l
227                    .iter()
228                    .zip(r)
229                    .zip(tys)
230                    .map(|((li, ri), cmp_type)| Self::partial_cmp(tcx, cmp_type, li, ri))
231                    .find(|r| r.is_none_or(|o| o != Ordering::Equal))
232                    .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
233                _ => None,
234            },
235            (Self::Vec(l), Self::Vec(r)) => {
236                let (ty::Array(cmp_type, _) | ty::Slice(cmp_type)) = *cmp_type.kind() else {
237                    return None;
238                };
239                iter::zip(l, r)
240                    .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
241                    .find(|r| r.is_none_or(|o| o != Ordering::Equal))
242                    .unwrap_or_else(|| Some(l.len().cmp(&r.len())))
243            },
244            (Self::Repeat(lv, ls), Self::Repeat(rv, rs)) => {
245                match Self::partial_cmp(
246                    tcx,
247                    match *cmp_type.kind() {
248                        ty::Array(ty, _) => ty,
249                        _ => return None,
250                    },
251                    lv,
252                    rv,
253                ) {
254                    Some(Ordering::Equal) => Some(ls.cmp(rs)),
255                    x => x,
256                }
257            },
258            (Self::Ref(lb), Self::Ref(rb)) => Self::partial_cmp(
259                tcx,
260                match *cmp_type.kind() {
261                    ty::Ref(_, ty, _) => ty,
262                    _ => return None,
263                },
264                lb,
265                rb,
266            ),
267            // TODO: are there any useful inter-type orderings?
268            _ => None,
269        }
270    }
271
272    /// Returns the integer value or `None` if `self` or `val_type` is not integer type.
273    pub fn int_value(&self, tcx: TyCtxt<'_>, val_type: Ty<'_>) -> Option<FullInt> {
274        if let Constant::Int(const_int) = *self {
275            match *val_type.kind() {
276                ty::Int(ity) => Some(FullInt::S(sext(tcx, const_int, ity))),
277                ty::Uint(_) => Some(FullInt::U(const_int)),
278                _ => None,
279            }
280        } else {
281            None
282        }
283    }
284
285    #[must_use]
286    pub fn peel_refs(mut self) -> Self {
287        while let Constant::Ref(r) = self {
288            self = *r;
289        }
290        self
291    }
292
293    fn parse_f16(s: &str) -> Self {
294        let f: Half = s.parse().unwrap();
295        Self::F16(f16::from_bits(f.to_bits().try_into().unwrap()))
296    }
297
298    fn parse_f128(s: &str) -> Self {
299        let f: Quad = s.parse().unwrap();
300        Self::F128(f128::from_bits(f.to_bits()))
301    }
302}
303
304/// Parses a `LitKind` to a `Constant`.
305pub fn lit_to_mir_constant<'tcx>(lit: &LitKind, ty: Option<Ty<'tcx>>) -> Constant<'tcx> {
306    match *lit {
307        LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
308        LitKind::Byte(b) => Constant::Int(u128::from(b)),
309        LitKind::ByteStr(ref s, _) | LitKind::CStr(ref s, _) => Constant::Binary(Arc::clone(s)),
310        LitKind::Char(c) => Constant::Char(c),
311        LitKind::Int(n, _) => Constant::Int(n.get()),
312        LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {
313            // FIXME(f16_f128): just use `parse()` directly when available for `f16`/`f128`
314            ast::FloatTy::F16 => Constant::parse_f16(is.as_str()),
315            ast::FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()),
316            ast::FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()),
317            ast::FloatTy::F128 => Constant::parse_f128(is.as_str()),
318        },
319        LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind() {
320            ty::Float(FloatTy::F16) => Constant::parse_f16(is.as_str()),
321            ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
322            ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
323            ty::Float(FloatTy::F128) => Constant::parse_f128(is.as_str()),
324            _ => bug!(),
325        },
326        LitKind::Bool(b) => Constant::Bool(b),
327        LitKind::Err(_) => Constant::Err,
328    }
329}
330
331/// The source of a constant value.
332#[derive(Clone, Copy)]
333pub enum ConstantSource {
334    /// The value is determined solely from the expression.
335    Local,
336    /// The value is dependent on a defined constant.
337    Constant,
338    /// The value is dependent on a constant defined in `core` crate.
339    CoreConstant,
340}
341impl ConstantSource {
342    pub fn is_local(self) -> bool {
343        matches!(self, Self::Local)
344    }
345}
346
347#[derive(Copy, Clone, Debug, Eq)]
348pub enum FullInt {
349    S(i128),
350    U(u128),
351}
352
353impl PartialEq for FullInt {
354    fn eq(&self, other: &Self) -> bool {
355        self.cmp(other) == Ordering::Equal
356    }
357}
358
359impl PartialOrd for FullInt {
360    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
361        Some(self.cmp(other))
362    }
363}
364
365impl Ord for FullInt {
366    fn cmp(&self, other: &Self) -> Ordering {
367        use FullInt::{S, U};
368
369        fn cmp_s_u(s: i128, u: u128) -> Ordering {
370            u128::try_from(s).map_or(Ordering::Less, |x| x.cmp(&u))
371        }
372
373        match (*self, *other) {
374            (S(s), S(o)) => s.cmp(&o),
375            (U(s), U(o)) => s.cmp(&o),
376            (S(s), U(o)) => cmp_s_u(s, o),
377            (U(s), S(o)) => cmp_s_u(o, s).reverse(),
378        }
379    }
380}
381
382/// The context required to evaluate a constant expression.
383///
384/// This is currently limited to constant folding and reading the value of named constants.
385///
386/// See the module level documentation for some context.
387pub struct ConstEvalCtxt<'tcx> {
388    tcx: TyCtxt<'tcx>,
389    typing_env: ty::TypingEnv<'tcx>,
390    typeck: &'tcx TypeckResults<'tcx>,
391    source: Cell<ConstantSource>,
392}
393
394impl<'tcx> ConstEvalCtxt<'tcx> {
395    /// Creates the evaluation context from the lint context. This requires the lint context to be
396    /// in a body (i.e. `cx.enclosing_body.is_some()`).
397    pub fn new(cx: &LateContext<'tcx>) -> Self {
398        Self {
399            tcx: cx.tcx,
400            typing_env: cx.typing_env(),
401            typeck: cx.typeck_results(),
402            source: Cell::new(ConstantSource::Local),
403        }
404    }
405
406    /// Creates an evaluation context.
407    pub fn with_env(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, typeck: &'tcx TypeckResults<'tcx>) -> Self {
408        Self {
409            tcx,
410            typing_env,
411            typeck,
412            source: Cell::new(ConstantSource::Local),
413        }
414    }
415
416    /// Attempts to evaluate the expression and returns both the value and whether it's dependant on
417    /// other items.
418    pub fn eval_with_source(&self, e: &Expr<'_>) -> Option<(Constant<'tcx>, ConstantSource)> {
419        self.source.set(ConstantSource::Local);
420        self.expr(e).map(|c| (c, self.source.get()))
421    }
422
423    /// Attempts to evaluate the expression.
424    pub fn eval(&self, e: &Expr<'_>) -> Option<Constant<'tcx>> {
425        self.expr(e)
426    }
427
428    /// Attempts to evaluate the expression without accessing other items.
429    pub fn eval_simple(&self, e: &Expr<'_>) -> Option<Constant<'tcx>> {
430        match self.eval_with_source(e) {
431            Some((x, ConstantSource::Local)) => Some(x),
432            _ => None,
433        }
434    }
435
436    /// Attempts to evaluate the expression as an integer without accessing other items.
437    pub fn eval_full_int(&self, e: &Expr<'_>) -> Option<FullInt> {
438        match self.eval_with_source(e) {
439            Some((x, ConstantSource::Local)) => x.int_value(self.tcx, self.typeck.expr_ty(e)),
440            _ => None,
441        }
442    }
443
444    pub fn eval_pat_expr(&self, pat_expr: &PatExpr<'_>) -> Option<Constant<'tcx>> {
445        match &pat_expr.kind {
446            PatExprKind::Lit { lit, negated } => {
447                let ty = self.typeck.node_type_opt(pat_expr.hir_id);
448                let val = lit_to_mir_constant(&lit.node, ty);
449                if *negated {
450                    self.constant_negate(&val, ty?)
451                } else {
452                    Some(val)
453                }
454            },
455            PatExprKind::ConstBlock(ConstBlock { body, .. }) => self.expr(self.tcx.hir_body(*body).value),
456            PatExprKind::Path(qpath) => self.qpath(qpath, pat_expr.hir_id),
457        }
458    }
459
460    fn qpath(&self, qpath: &QPath<'_>, hir_id: HirId) -> Option<Constant<'tcx>> {
461        let is_core_crate = if let Some(def_id) = self.typeck.qpath_res(qpath, hir_id).opt_def_id() {
462            self.tcx.crate_name(def_id.krate) == sym::core
463        } else {
464            false
465        };
466        self.fetch_path_and_apply(qpath, hir_id, self.typeck.node_type(hir_id), |self_, result| {
467            let result = mir_to_const(self_.tcx, result)?;
468            // If source is already Constant we wouldn't want to override it with CoreConstant
469            self_.source.set(
470                if is_core_crate && !matches!(self_.source.get(), ConstantSource::Constant) {
471                    ConstantSource::CoreConstant
472                } else {
473                    ConstantSource::Constant
474                },
475            );
476            Some(result)
477        })
478    }
479
480    /// Simple constant folding: Insert an expression, get a constant or none.
481    fn expr(&self, e: &Expr<'_>) -> Option<Constant<'tcx>> {
482        match e.kind {
483            ExprKind::ConstBlock(ConstBlock { body, .. }) => self.expr(self.tcx.hir_body(body).value),
484            ExprKind::DropTemps(e) => self.expr(e),
485            ExprKind::Path(ref qpath) => self.qpath(qpath, e.hir_id),
486            ExprKind::Block(block, _) => self.block(block),
487            ExprKind::Lit(lit) => {
488                if is_direct_expn_of(e.span, "cfg").is_some() {
489                    None
490                } else {
491                    Some(lit_to_mir_constant(&lit.node, self.typeck.expr_ty_opt(e)))
492                }
493            },
494            ExprKind::Array(vec) => self.multi(vec).map(Constant::Vec),
495            ExprKind::Tup(tup) => self.multi(tup).map(Constant::Tuple),
496            ExprKind::Repeat(value, _) => {
497                let n = match self.typeck.expr_ty(e).kind() {
498                    ty::Array(_, n) => n.try_to_target_usize(self.tcx)?,
499                    _ => span_bug!(e.span, "typeck error"),
500                };
501                self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
502            },
503            ExprKind::Unary(op, operand) => self.expr(operand).and_then(|o| match op {
504                UnOp::Not => self.constant_not(&o, self.typeck.expr_ty(e)),
505                UnOp::Neg => self.constant_negate(&o, self.typeck.expr_ty(e)),
506                UnOp::Deref => Some(if let Constant::Ref(r) = o { *r } else { o }),
507            }),
508            ExprKind::If(cond, then, ref otherwise) => self.ifthenelse(cond, then, *otherwise),
509            ExprKind::Binary(op, left, right) => self.binop(op, left, right),
510            ExprKind::Call(callee, []) => {
511                // We only handle a few const functions for now.
512                if let ExprKind::Path(qpath) = &callee.kind
513                    && let Some(did) = self.typeck.qpath_res(qpath, callee.hir_id).opt_def_id()
514                {
515                    match self.tcx.get_diagnostic_name(did) {
516                        Some(sym::i8_legacy_fn_max_value) => Some(Constant::Int(i8::MAX as u128)),
517                        Some(sym::i16_legacy_fn_max_value) => Some(Constant::Int(i16::MAX as u128)),
518                        Some(sym::i32_legacy_fn_max_value) => Some(Constant::Int(i32::MAX as u128)),
519                        Some(sym::i64_legacy_fn_max_value) => Some(Constant::Int(i64::MAX as u128)),
520                        Some(sym::i128_legacy_fn_max_value) => Some(Constant::Int(i128::MAX as u128)),
521                        _ => None,
522                    }
523                } else {
524                    None
525                }
526            },
527            ExprKind::Index(arr, index, _) => self.index(arr, index),
528            ExprKind::AddrOf(_, _, inner) => self.expr(inner).map(|r| Constant::Ref(Box::new(r))),
529            ExprKind::Field(local_expr, ref field) => {
530                let result = self.expr(local_expr);
531                if let Some(Constant::Adt(constant)) = &self.expr(local_expr)
532                    && let ty::Adt(adt_def, _) = constant.ty().kind()
533                    && adt_def.is_struct()
534                    && let Some(desired_field) = field_of_struct(*adt_def, self.tcx, *constant, field)
535                {
536                    mir_to_const(self.tcx, desired_field)
537                } else {
538                    result
539                }
540            },
541            _ => None,
542        }
543    }
544
545    /// Simple constant folding to determine if an expression is an empty slice, str, array, …
546    /// `None` will be returned if the constness cannot be determined, or if the resolution
547    /// leaves the local crate.
548    pub fn eval_is_empty(&self, e: &Expr<'_>) -> Option<bool> {
549        match e.kind {
550            ExprKind::ConstBlock(ConstBlock { body, .. }) => self.eval_is_empty(self.tcx.hir_body(body).value),
551            ExprKind::DropTemps(e) => self.eval_is_empty(e),
552            ExprKind::Path(ref qpath) => {
553                if !self
554                    .typeck
555                    .qpath_res(qpath, e.hir_id)
556                    .opt_def_id()
557                    .is_some_and(DefId::is_local)
558                {
559                    return None;
560                }
561                self.fetch_path_and_apply(qpath, e.hir_id, self.typeck.expr_ty(e), |self_, result| {
562                    mir_is_empty(self_.tcx, result)
563                })
564            },
565            ExprKind::Lit(lit) => {
566                if is_direct_expn_of(e.span, "cfg").is_some() {
567                    None
568                } else {
569                    match &lit.node {
570                        LitKind::Str(is, _) => Some(is.is_empty()),
571                        LitKind::ByteStr(s, _) | LitKind::CStr(s, _) => Some(s.is_empty()),
572                        _ => None,
573                    }
574                }
575            },
576            ExprKind::Array(vec) => self.multi(vec).map(|v| v.is_empty()),
577            ExprKind::Repeat(..) => {
578                if let ty::Array(_, n) = self.typeck.expr_ty(e).kind() {
579                    Some(n.try_to_target_usize(self.tcx)? == 0)
580                } else {
581                    span_bug!(e.span, "typeck error");
582                }
583            },
584            _ => None,
585        }
586    }
587
588    #[expect(clippy::cast_possible_wrap)]
589    fn constant_not(&self, o: &Constant<'tcx>, ty: Ty<'_>) -> Option<Constant<'tcx>> {
590        use self::Constant::{Bool, Int};
591        match *o {
592            Bool(b) => Some(Bool(!b)),
593            Int(value) => {
594                let value = !value;
595                match *ty.kind() {
596                    ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
597                    ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
598                    _ => None,
599                }
600            },
601            _ => None,
602        }
603    }
604
605    fn constant_negate(&self, o: &Constant<'tcx>, ty: Ty<'_>) -> Option<Constant<'tcx>> {
606        use self::Constant::{F32, F64, Int};
607        match *o {
608            Int(value) => {
609                let ty::Int(ity) = *ty.kind() else { return None };
610                let (min, _) = ity.min_max()?;
611                // sign extend
612                let value = sext(self.tcx, value, ity);
613
614                // Applying unary - to the most negative value of any signed integer type panics.
615                if value == min {
616                    return None;
617                }
618
619                let value = value.checked_neg()?;
620                // clear unused bits
621                Some(Int(unsext(self.tcx, value, ity)))
622            },
623            F32(f) => Some(F32(-f)),
624            F64(f) => Some(F64(-f)),
625            _ => None,
626        }
627    }
628
629    /// Create `Some(Vec![..])` of all constants, unless there is any
630    /// non-constant part.
631    fn multi(&self, vec: &[Expr<'_>]) -> Option<Vec<Constant<'tcx>>> {
632        vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
633    }
634
635    /// Lookup a possibly constant expression from an `ExprKind::Path` and apply a function on it.
636    fn fetch_path_and_apply<T, F>(&self, qpath: &QPath<'_>, id: HirId, ty: Ty<'tcx>, f: F) -> Option<T>
637    where
638        F: FnOnce(&Self, mir::Const<'tcx>) -> Option<T>,
639    {
640        let res = self.typeck.qpath_res(qpath, id);
641        match res {
642            Res::Def(DefKind::Const | DefKind::AssocConst, def_id) => {
643                // Check if this constant is based on `cfg!(..)`,
644                // which is NOT constant for our purposes.
645                if let Some(node) = self.tcx.hir_get_if_local(def_id)
646                    && let Node::Item(Item {
647                        kind: ItemKind::Const(.., body_id),
648                        ..
649                    }) = node
650                    && let Node::Expr(Expr {
651                        kind: ExprKind::Lit(_),
652                        span,
653                        ..
654                    }) = self.tcx.hir_node(body_id.hir_id)
655                    && is_direct_expn_of(*span, "cfg").is_some()
656                {
657                    return None;
658                }
659
660                let args = self.typeck.node_args(id);
661                let result = self
662                    .tcx
663                    .const_eval_resolve(self.typing_env, mir::UnevaluatedConst::new(def_id, args), qpath.span())
664                    .ok()
665                    .map(|val| mir::Const::from_value(val, ty))?;
666                f(self, result)
667            },
668            _ => None,
669        }
670    }
671
672    fn index(&self, lhs: &'_ Expr<'_>, index: &'_ Expr<'_>) -> Option<Constant<'tcx>> {
673        let lhs = self.expr(lhs);
674        let index = self.expr(index);
675
676        match (lhs, index) {
677            (Some(Constant::Vec(vec)), Some(Constant::Int(index))) => match vec.get(index as usize) {
678                Some(Constant::F16(x)) => Some(Constant::F16(*x)),
679                Some(Constant::F32(x)) => Some(Constant::F32(*x)),
680                Some(Constant::F64(x)) => Some(Constant::F64(*x)),
681                Some(Constant::F128(x)) => Some(Constant::F128(*x)),
682                _ => None,
683            },
684            (Some(Constant::Vec(vec)), _) => {
685                if !vec.is_empty() && vec.iter().all(|x| *x == vec[0]) {
686                    match vec.first() {
687                        Some(Constant::F16(x)) => Some(Constant::F16(*x)),
688                        Some(Constant::F32(x)) => Some(Constant::F32(*x)),
689                        Some(Constant::F64(x)) => Some(Constant::F64(*x)),
690                        Some(Constant::F128(x)) => Some(Constant::F128(*x)),
691                        _ => None,
692                    }
693                } else {
694                    None
695                }
696            },
697            _ => None,
698        }
699    }
700
701    /// A block can only yield a constant if it has exactly one constant expression.
702    fn block(&self, block: &Block<'_>) -> Option<Constant<'tcx>> {
703        if block.stmts.is_empty()
704            && let Some(expr) = block.expr
705        {
706            // Try to detect any `cfg`ed statements or empty macro expansions.
707            let span = block.span.data();
708            if span.ctxt == SyntaxContext::root() {
709                if let Some(expr_span) = walk_span_to_context(expr.span, span.ctxt)
710                    && let expr_lo = expr_span.lo()
711                    && expr_lo >= span.lo
712                    && let Some(src) = (span.lo..expr_lo).get_source_range(&self.tcx)
713                    && let Some(src) = src.as_str()
714                {
715                    use rustc_lexer::TokenKind::{BlockComment, LineComment, OpenBrace, Semi, Whitespace};
716                    if !tokenize(src)
717                        .map(|t| t.kind)
718                        .filter(|t| !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. } | Semi))
719                        .eq([OpenBrace])
720                    {
721                        self.source.set(ConstantSource::Constant);
722                    }
723                } else {
724                    // Unable to access the source. Assume a non-local dependency.
725                    self.source.set(ConstantSource::Constant);
726                }
727            }
728
729            self.expr(expr)
730        } else {
731            None
732        }
733    }
734
735    fn ifthenelse(&self, cond: &Expr<'_>, then: &Expr<'_>, otherwise: Option<&Expr<'_>>) -> Option<Constant<'tcx>> {
736        if let Some(Constant::Bool(b)) = self.expr(cond) {
737            if b {
738                self.expr(then)
739            } else {
740                otherwise.as_ref().and_then(|expr| self.expr(expr))
741            }
742        } else {
743            None
744        }
745    }
746
747    fn binop(&self, op: BinOp, left: &Expr<'_>, right: &Expr<'_>) -> Option<Constant<'tcx>> {
748        let l = self.expr(left)?;
749        let r = self.expr(right);
750        match (l, r) {
751            (Constant::Int(l), Some(Constant::Int(r))) => match *self.typeck.expr_ty_opt(left)?.kind() {
752                ty::Int(ity) => {
753                    let (ty_min_value, _) = ity.min_max()?;
754                    let bits = ity.bits();
755                    let l = sext(self.tcx, l, ity);
756                    let r = sext(self.tcx, r, ity);
757
758                    // Using / or %, where the left-hand argument is the smallest integer of a signed integer type and
759                    // the right-hand argument is -1 always panics, even with overflow-checks disabled
760                    if let BinOpKind::Div | BinOpKind::Rem = op.node
761                        && l == ty_min_value
762                        && r == -1
763                    {
764                        return None;
765                    }
766
767                    let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
768                    match op.node {
769                        // When +, * or binary - create a value greater than the maximum value, or less than
770                        // the minimum value that can be stored, it panics.
771                        BinOpKind::Add => l.checked_add(r).and_then(|n| ity.ensure_fits(n)).map(zext),
772                        BinOpKind::Sub => l.checked_sub(r).and_then(|n| ity.ensure_fits(n)).map(zext),
773                        BinOpKind::Mul => l.checked_mul(r).and_then(|n| ity.ensure_fits(n)).map(zext),
774                        BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
775                        BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
776                        // Using << or >> where the right-hand argument is greater than or equal to the number of bits
777                        // in the type of the left-hand argument, or is negative panics.
778                        BinOpKind::Shr if r < bits && !r.is_negative() => l.checked_shr(r.try_into().ok()?).map(zext),
779                        BinOpKind::Shl if r < bits && !r.is_negative() => l.checked_shl(r.try_into().ok()?).map(zext),
780                        BinOpKind::BitXor => Some(zext(l ^ r)),
781                        BinOpKind::BitOr => Some(zext(l | r)),
782                        BinOpKind::BitAnd => Some(zext(l & r)),
783                        BinOpKind::Eq => Some(Constant::Bool(l == r)),
784                        BinOpKind::Ne => Some(Constant::Bool(l != r)),
785                        BinOpKind::Lt => Some(Constant::Bool(l < r)),
786                        BinOpKind::Le => Some(Constant::Bool(l <= r)),
787                        BinOpKind::Ge => Some(Constant::Bool(l >= r)),
788                        BinOpKind::Gt => Some(Constant::Bool(l > r)),
789                        _ => None,
790                    }
791                },
792                ty::Uint(ity) => {
793                    let bits = ity.bits();
794
795                    match op.node {
796                        BinOpKind::Add => l.checked_add(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
797                        BinOpKind::Sub => l.checked_sub(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
798                        BinOpKind::Mul => l.checked_mul(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
799                        BinOpKind::Div => l.checked_div(r).map(Constant::Int),
800                        BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
801                        BinOpKind::Shr if r < bits => l.checked_shr(r.try_into().ok()?).map(Constant::Int),
802                        BinOpKind::Shl if r < bits => l.checked_shl(r.try_into().ok()?).map(Constant::Int),
803                        BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
804                        BinOpKind::BitOr => Some(Constant::Int(l | r)),
805                        BinOpKind::BitAnd => Some(Constant::Int(l & r)),
806                        BinOpKind::Eq => Some(Constant::Bool(l == r)),
807                        BinOpKind::Ne => Some(Constant::Bool(l != r)),
808                        BinOpKind::Lt => Some(Constant::Bool(l < r)),
809                        BinOpKind::Le => Some(Constant::Bool(l <= r)),
810                        BinOpKind::Ge => Some(Constant::Bool(l >= r)),
811                        BinOpKind::Gt => Some(Constant::Bool(l > r)),
812                        _ => None,
813                    }
814                },
815                _ => None,
816            },
817            // FIXME(f16_f128): add these types when binary operations are available on all platforms
818            (Constant::F32(l), Some(Constant::F32(r))) => match op.node {
819                BinOpKind::Add => Some(Constant::F32(l + r)),
820                BinOpKind::Sub => Some(Constant::F32(l - r)),
821                BinOpKind::Mul => Some(Constant::F32(l * r)),
822                BinOpKind::Div => Some(Constant::F32(l / r)),
823                BinOpKind::Rem => Some(Constant::F32(l % r)),
824                BinOpKind::Eq => Some(Constant::Bool(l == r)),
825                BinOpKind::Ne => Some(Constant::Bool(l != r)),
826                BinOpKind::Lt => Some(Constant::Bool(l < r)),
827                BinOpKind::Le => Some(Constant::Bool(l <= r)),
828                BinOpKind::Ge => Some(Constant::Bool(l >= r)),
829                BinOpKind::Gt => Some(Constant::Bool(l > r)),
830                _ => None,
831            },
832            (Constant::F64(l), Some(Constant::F64(r))) => match op.node {
833                BinOpKind::Add => Some(Constant::F64(l + r)),
834                BinOpKind::Sub => Some(Constant::F64(l - r)),
835                BinOpKind::Mul => Some(Constant::F64(l * r)),
836                BinOpKind::Div => Some(Constant::F64(l / r)),
837                BinOpKind::Rem => Some(Constant::F64(l % r)),
838                BinOpKind::Eq => Some(Constant::Bool(l == r)),
839                BinOpKind::Ne => Some(Constant::Bool(l != r)),
840                BinOpKind::Lt => Some(Constant::Bool(l < r)),
841                BinOpKind::Le => Some(Constant::Bool(l <= r)),
842                BinOpKind::Ge => Some(Constant::Bool(l >= r)),
843                BinOpKind::Gt => Some(Constant::Bool(l > r)),
844                _ => None,
845            },
846            (l, r) => match (op.node, l, r) {
847                (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
848                (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
849                (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
850                    Some(r)
851                },
852                (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
853                (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
854                (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
855                _ => None,
856            },
857        }
858    }
859}
860
861pub fn mir_to_const<'tcx>(tcx: TyCtxt<'tcx>, result: mir::Const<'tcx>) -> Option<Constant<'tcx>> {
862    let mir::Const::Val(val, _) = result else {
863        // We only work on evaluated consts.
864        return None;
865    };
866    match (val, result.ty().kind()) {
867        (ConstValue::Scalar(Scalar::Int(int)), _) => match result.ty().kind() {
868            ty::Adt(adt_def, _) if adt_def.is_struct() => Some(Constant::Adt(result)),
869            ty::Bool => Some(Constant::Bool(int == ScalarInt::TRUE)),
870            ty::Uint(_) | ty::Int(_) => Some(Constant::Int(int.to_bits(int.size()))),
871            ty::Float(FloatTy::F16) => Some(Constant::F16(f16::from_bits(int.into()))),
872            ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(int.into()))),
873            ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(int.into()))),
874            ty::Float(FloatTy::F128) => Some(Constant::F128(f128::from_bits(int.into()))),
875            ty::RawPtr(_, _) => Some(Constant::RawPtr(int.to_bits(int.size()))),
876            _ => None,
877        },
878        (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
879            let data = val.try_get_slice_bytes_for_diagnostics(tcx)?;
880            String::from_utf8(data.to_owned()).ok().map(Constant::Str)
881        },
882        (_, ty::Adt(adt_def, _)) if adt_def.is_struct() => Some(Constant::Adt(result)),
883        (ConstValue::Indirect { alloc_id, offset }, ty::Array(sub_type, len)) => {
884            let alloc = tcx.global_alloc(alloc_id).unwrap_memory().inner();
885            let len = len.try_to_target_usize(tcx)?;
886            let ty::Float(flt) = sub_type.kind() else {
887                return None;
888            };
889            let size = Size::from_bits(flt.bit_width());
890            let mut res = Vec::new();
891            for idx in 0..len {
892                let range = alloc_range(offset + size * idx, size);
893                let val = alloc.read_scalar(&tcx, range, /* read_provenance */ false).ok()?;
894                res.push(match flt {
895                    FloatTy::F16 => Constant::F16(f16::from_bits(val.to_u16().discard_err()?)),
896                    FloatTy::F32 => Constant::F32(f32::from_bits(val.to_u32().discard_err()?)),
897                    FloatTy::F64 => Constant::F64(f64::from_bits(val.to_u64().discard_err()?)),
898                    FloatTy::F128 => Constant::F128(f128::from_bits(val.to_u128().discard_err()?)),
899                });
900            }
901            Some(Constant::Vec(res))
902        },
903        _ => None,
904    }
905}
906
907fn mir_is_empty<'tcx>(tcx: TyCtxt<'tcx>, result: mir::Const<'tcx>) -> Option<bool> {
908    let mir::Const::Val(val, _) = result else {
909        // We only work on evaluated consts.
910        return None;
911    };
912    match (val, result.ty().kind()) {
913        (_, ty::Ref(_, inner_ty, _)) => match inner_ty.kind() {
914            ty::Str | ty::Slice(_) => {
915                if let ConstValue::Indirect { alloc_id, offset } = val {
916                    // Get the length from the slice, using the same formula as
917                    // [`ConstValue::try_get_slice_bytes_for_diagnostics`].
918                    let a = tcx.global_alloc(alloc_id).unwrap_memory().inner();
919                    let ptr_size = tcx.data_layout.pointer_size;
920                    if a.size() < offset + 2 * ptr_size {
921                        // (partially) dangling reference
922                        return None;
923                    }
924                    let len = a
925                        .read_scalar(&tcx, alloc_range(offset + ptr_size, ptr_size), false)
926                        .ok()?
927                        .to_target_usize(&tcx)
928                        .discard_err()?;
929                    Some(len == 0)
930                } else {
931                    None
932                }
933            },
934            ty::Array(_, len) => Some(len.try_to_target_usize(tcx)? == 0),
935            _ => None,
936        },
937        (ConstValue::Indirect { .. }, ty::Array(_, len)) => Some(len.try_to_target_usize(tcx)? == 0),
938        (ConstValue::ZeroSized, _) => Some(true),
939        _ => None,
940    }
941}
942
943fn field_of_struct<'tcx>(
944    adt_def: ty::AdtDef<'tcx>,
945    tcx: TyCtxt<'tcx>,
946    result: mir::Const<'tcx>,
947    field: &Ident,
948) -> Option<mir::Const<'tcx>> {
949    if let mir::Const::Val(result, ty) = result
950        && let Some(dc) = tcx.try_destructure_mir_constant_for_user_output(result, ty)
951        && let Some(dc_variant) = dc.variant
952        && let Some(variant) = adt_def.variants().get(dc_variant)
953        && let Some(field_idx) = variant.fields.iter().position(|el| el.name == field.name)
954        && let Some(&(val, ty)) = dc.fields.get(field_idx)
955    {
956        Some(mir::Const::Val(val, ty))
957    } else {
958        None
959    }
960}