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