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