clippy_utils/
consts.rs

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