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::{self, 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::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, _) => {
308            Constant::Binary(s.as_byte_str().to_vec())
309        }
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, sym::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.node, 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, sym::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, _) => {
572                            Some(s.as_byte_str().is_empty())
573                        }
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, sym::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}
963
964/// If `expr` evaluates to an integer constant, return its value.
965pub fn integer_const(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<u128> {
966    if let Some(Constant::Int(value)) = ConstEvalCtxt::new(cx).eval_simple(expr) {
967        Some(value)
968    } else {
969        None
970    }
971}
972
973/// Check if `expr` evaluates to an integer constant of 0.
974#[inline]
975pub fn is_zero_integer_const(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
976    integer_const(cx, expr) == Some(0)
977}