1#![expect(clippy::float_cmp)]
6
7use crate::res::MaybeDef;
8use crate::source::{SpanRangeExt, walk_span_to_context};
9use crate::{clip, is_direct_expn_of, sext, sym, unsext};
10
11use rustc_abi::Size;
12use rustc_apfloat::Float;
13use rustc_apfloat::ieee::{Half, Quad};
14use rustc_ast::ast::{LitFloatType, LitKind};
15use rustc_hir::def::{DefKind, Res};
16use rustc_hir::{
17 BinOpKind, Block, ConstArgKind, ConstBlock, ConstItemRhs, Expr, ExprKind, HirId, PatExpr, PatExprKind, QPath,
18 TyKind, UnOp,
19};
20use rustc_lexer::{FrontmatterAllowed, 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::{Symbol, SyntaxContext};
27use std::cell::Cell;
28use std::cmp::Ordering;
29use std::hash::{Hash, Hasher};
30use std::iter;
31
32#[derive(Debug, Clone)]
34pub enum Constant {
35 Adt(ConstValue),
36 Str(String),
38 Binary(Vec<u8>),
40 Char(char),
42 Int(u128),
44 F16(u16),
47 F32(f32),
49 F64(f64),
51 F128(u128),
54 Bool(bool),
56 Vec(Vec<Self>),
58 Repeat(Box<Self>, u64),
60 Tuple(Vec<Self>),
62 RawPtr(u128),
64 Ref(Box<Self>),
66 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 l.to_bits() == r.to_bits() && !l.is_nan()
137 },
138 (&Self::F32(l), &Self::F32(r)) => {
139 l.to_bits() == r.to_bits() && !l.is_nan()
141 },
142 (&Self::Bool(l), &Self::Bool(r)) => l == r,
143 (&Self::Vec(ref l), &Self::Vec(ref r)) | (&Self::Tuple(ref l), &Self::Tuple(ref r)) => l == r,
144 (Self::Repeat(lv, ls), Self::Repeat(rv, rs)) => ls == rs && lv == rv,
145 (Self::Ref(lb), Self::Ref(rb)) => *lb == *rb,
146 _ => false,
148 }
149 }
150}
151
152impl Hash for Constant {
153 fn hash<H>(&self, state: &mut H)
154 where
155 H: Hasher,
156 {
157 std::mem::discriminant(self).hash(state);
158 match *self {
159 Self::Adt(ref elem) => {
160 elem.hash(state);
161 },
162 Self::Str(ref s) => {
163 s.hash(state);
164 },
165 Self::Binary(ref b) => {
166 b.hash(state);
167 },
168 Self::Char(c) => {
169 c.hash(state);
170 },
171 Self::Int(i) => {
172 i.hash(state);
173 },
174 Self::F16(f) => {
175 f.hash(state);
177 },
178 Self::F32(f) => {
179 f64::from(f).to_bits().hash(state);
180 },
181 Self::F64(f) => {
182 f.to_bits().hash(state);
183 },
184 Self::F128(f) => {
185 f.hash(state);
186 },
187 Self::Bool(b) => {
188 b.hash(state);
189 },
190 Self::Vec(ref v) | Self::Tuple(ref v) => {
191 v.hash(state);
192 },
193 Self::Repeat(ref c, l) => {
194 c.hash(state);
195 l.hash(state);
196 },
197 Self::RawPtr(u) => {
198 u.hash(state);
199 },
200 Self::Ref(ref r) => {
201 r.hash(state);
202 },
203 Self::Err => {},
204 }
205 }
206}
207
208impl Constant {
209 pub fn partial_cmp(tcx: TyCtxt<'_>, cmp_type: Ty<'_>, left: &Self, right: &Self) -> Option<Ordering> {
210 match (left, right) {
211 (Self::Str(ls), Self::Str(rs)) => Some(ls.cmp(rs)),
212 (Self::Char(l), Self::Char(r)) => Some(l.cmp(r)),
213 (&Self::Int(l), &Self::Int(r)) => match *cmp_type.kind() {
214 ty::Int(int_ty) => Some(sext(tcx, l, int_ty).cmp(&sext(tcx, r, int_ty))),
215 ty::Uint(_) => Some(l.cmp(&r)),
216 _ => bug!("Not an int type"),
217 },
218 (&Self::F64(l), &Self::F64(r)) => l.partial_cmp(&r),
219 (&Self::F32(l), &Self::F32(r)) => l.partial_cmp(&r),
220 (Self::Bool(l), Self::Bool(r)) => Some(l.cmp(r)),
221 (Self::Tuple(l), Self::Tuple(r)) if l.len() == r.len() => match *cmp_type.kind() {
222 ty::Tuple(tys) if tys.len() == l.len() => l
223 .iter()
224 .zip(r)
225 .zip(tys)
226 .map(|((li, ri), cmp_type)| Self::partial_cmp(tcx, cmp_type, li, ri))
227 .find(|r| r.is_none_or(|o| o != Ordering::Equal))
228 .unwrap_or_else(|| Some(l.len().cmp(&r.len()))),
229 _ => None,
230 },
231 (Self::Vec(l), Self::Vec(r)) => {
232 let cmp_type = cmp_type.builtin_index()?;
233 iter::zip(l, r)
234 .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri))
235 .find(|r| r.is_none_or(|o| o != Ordering::Equal))
236 .unwrap_or_else(|| Some(l.len().cmp(&r.len())))
237 },
238 (Self::Repeat(lv, ls), Self::Repeat(rv, rs)) => {
239 match Self::partial_cmp(
240 tcx,
241 match *cmp_type.kind() {
242 ty::Array(ty, _) => ty,
243 _ => return None,
244 },
245 lv,
246 rv,
247 ) {
248 Some(Ordering::Equal) => Some(ls.cmp(rs)),
249 x => x,
250 }
251 },
252 (Self::Ref(lb), Self::Ref(rb)) => Self::partial_cmp(
253 tcx,
254 match *cmp_type.kind() {
255 ty::Ref(_, ty, _) => ty,
256 _ => return None,
257 },
258 lb,
259 rb,
260 ),
261 _ => None,
263 }
264 }
265
266 pub fn int_value(&self, tcx: TyCtxt<'_>, val_type: Ty<'_>) -> Option<FullInt> {
268 if let Constant::Int(const_int) = *self {
269 match *val_type.kind() {
270 ty::Int(ity) => Some(FullInt::S(sext(tcx, const_int, ity))),
271 ty::Uint(_) => Some(FullInt::U(const_int)),
272 _ => None,
273 }
274 } else {
275 None
276 }
277 }
278
279 #[must_use]
280 pub fn peel_refs(mut self) -> Self {
281 while let Constant::Ref(r) = self {
282 self = *r;
283 }
284 self
285 }
286
287 fn parse_f16(s: &str) -> Self {
288 let f: Half = s.parse().unwrap();
289 Self::F16(f.to_bits().try_into().unwrap())
290 }
291
292 fn parse_f128(s: &str) -> Self {
293 let f: Quad = s.parse().unwrap();
294 Self::F128(f.to_bits())
295 }
296
297 pub fn new_numeric_min<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Self> {
298 match *ty.kind() {
299 ty::Uint(_) => Some(Self::Int(0)),
300 ty::Int(ty) => {
301 let val = match ty.normalize(tcx.sess.target.pointer_width) {
302 IntTy::I8 => i128::from(i8::MIN),
303 IntTy::I16 => i128::from(i16::MIN),
304 IntTy::I32 => i128::from(i32::MIN),
305 IntTy::I64 => i128::from(i64::MIN),
306 IntTy::I128 => i128::MIN,
307 IntTy::Isize => return None,
308 };
309 Some(Self::Int(val.cast_unsigned()))
310 },
311 ty::Char => Some(Self::Char(char::MIN)),
312 ty::Float(FloatTy::F32) => Some(Self::F32(f32::NEG_INFINITY)),
313 ty::Float(FloatTy::F64) => Some(Self::F64(f64::NEG_INFINITY)),
314 _ => None,
315 }
316 }
317
318 pub fn new_numeric_max<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Self> {
319 match *ty.kind() {
320 ty::Uint(ty) => Some(Self::Int(match ty.normalize(tcx.sess.target.pointer_width) {
321 UintTy::U8 => u128::from(u8::MAX),
322 UintTy::U16 => u128::from(u16::MAX),
323 UintTy::U32 => u128::from(u32::MAX),
324 UintTy::U64 => u128::from(u64::MAX),
325 UintTy::U128 => u128::MAX,
326 UintTy::Usize => return None,
327 })),
328 ty::Int(ty) => {
329 let val = match ty.normalize(tcx.sess.target.pointer_width) {
330 IntTy::I8 => i128::from(i8::MAX),
331 IntTy::I16 => i128::from(i16::MAX),
332 IntTy::I32 => i128::from(i32::MAX),
333 IntTy::I64 => i128::from(i64::MAX),
334 IntTy::I128 => i128::MAX,
335 IntTy::Isize => return None,
336 };
337 Some(Self::Int(val.cast_unsigned()))
338 },
339 ty::Char => Some(Self::Char(char::MAX)),
340 ty::Float(FloatTy::F32) => Some(Self::F32(f32::INFINITY)),
341 ty::Float(FloatTy::F64) => Some(Self::F64(f64::INFINITY)),
342 _ => None,
343 }
344 }
345
346 pub fn is_numeric_min<'tcx>(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
347 match (self, ty.kind()) {
348 (&Self::Int(x), &ty::Uint(_)) => x == 0,
349 (&Self::Int(x), &ty::Int(ty)) => {
350 let limit = match ty.normalize(tcx.sess.target.pointer_width) {
351 IntTy::I8 => i128::from(i8::MIN),
352 IntTy::I16 => i128::from(i16::MIN),
353 IntTy::I32 => i128::from(i32::MIN),
354 IntTy::I64 => i128::from(i64::MIN),
355 IntTy::I128 => i128::MIN,
356 IntTy::Isize => return false,
357 };
358 x.cast_signed() == limit
359 },
360 (&Self::Char(x), &ty::Char) => x == char::MIN,
361 (&Self::F32(x), &ty::Float(FloatTy::F32)) => x == f32::NEG_INFINITY,
362 (&Self::F64(x), &ty::Float(FloatTy::F64)) => x == f64::NEG_INFINITY,
363 _ => false,
364 }
365 }
366
367 pub fn is_numeric_max<'tcx>(&self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
368 match (self, ty.kind()) {
369 (&Self::Int(x), &ty::Uint(ty)) => {
370 let limit = match ty.normalize(tcx.sess.target.pointer_width) {
371 UintTy::U8 => u128::from(u8::MAX),
372 UintTy::U16 => u128::from(u16::MAX),
373 UintTy::U32 => u128::from(u32::MAX),
374 UintTy::U64 => u128::from(u64::MAX),
375 UintTy::U128 => u128::MAX,
376 UintTy::Usize => return false,
377 };
378 x == limit
379 },
380 (&Self::Int(x), &ty::Int(ty)) => {
381 let limit = match ty.normalize(tcx.sess.target.pointer_width) {
382 IntTy::I8 => i128::from(i8::MAX),
383 IntTy::I16 => i128::from(i16::MAX),
384 IntTy::I32 => i128::from(i32::MAX),
385 IntTy::I64 => i128::from(i64::MAX),
386 IntTy::I128 => i128::MAX,
387 IntTy::Isize => return false,
388 };
389 x.cast_signed() == limit
390 },
391 (&Self::Char(x), &ty::Char) => x == char::MAX,
392 (&Self::F32(x), &ty::Float(FloatTy::F32)) => x == f32::INFINITY,
393 (&Self::F64(x), &ty::Float(FloatTy::F64)) => x == f64::INFINITY,
394 _ => false,
395 }
396 }
397
398 pub fn is_pos_infinity(&self) -> bool {
399 match *self {
400 Constant::F32(x) => x == f32::INFINITY,
402 Constant::F64(x) => x == f64::INFINITY,
403 _ => false,
404 }
405 }
406
407 pub fn is_neg_infinity(&self) -> bool {
408 match *self {
409 Constant::F32(x) => x == f32::NEG_INFINITY,
411 Constant::F64(x) => x == f64::NEG_INFINITY,
412 _ => false,
413 }
414 }
415}
416
417pub fn lit_to_mir_constant(lit: &LitKind, ty: Option<Ty<'_>>) -> Constant {
419 match *lit {
420 LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
421 LitKind::Byte(b) => Constant::Int(u128::from(b)),
422 LitKind::ByteStr(ref s, _) | LitKind::CStr(ref s, _) => Constant::Binary(s.as_byte_str().to_vec()),
423 LitKind::Char(c) => Constant::Char(c),
424 LitKind::Int(n, _) => Constant::Int(n.get()),
425 LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {
426 FloatTy::F16 => Constant::parse_f16(is.as_str()),
428 FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()),
429 FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()),
430 FloatTy::F128 => Constant::parse_f128(is.as_str()),
431 },
432 LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind() {
433 ty::Float(FloatTy::F16) => Constant::parse_f16(is.as_str()),
434 ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()),
435 ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()),
436 ty::Float(FloatTy::F128) => Constant::parse_f128(is.as_str()),
437 _ => bug!(),
438 },
439 LitKind::Bool(b) => Constant::Bool(b),
440 LitKind::Err(_) => Constant::Err,
441 }
442}
443
444#[derive(Clone, Copy)]
446pub enum ConstantSource {
447 Local,
449 NonLocal,
452}
453impl ConstantSource {
454 pub fn is_local(self) -> bool {
455 matches!(self, Self::Local)
456 }
457}
458
459#[derive(Copy, Clone, Debug, Eq)]
460pub enum FullInt {
461 S(i128),
462 U(u128),
463}
464
465impl PartialEq for FullInt {
466 fn eq(&self, other: &Self) -> bool {
467 self.cmp(other) == Ordering::Equal
468 }
469}
470
471impl PartialOrd for FullInt {
472 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
473 Some(self.cmp(other))
474 }
475}
476
477impl Ord for FullInt {
478 fn cmp(&self, other: &Self) -> Ordering {
479 use FullInt::{S, U};
480
481 fn cmp_s_u(s: i128, u: u128) -> Ordering {
482 u128::try_from(s).map_or(Ordering::Less, |x| x.cmp(&u))
483 }
484
485 match (*self, *other) {
486 (S(s), S(o)) => s.cmp(&o),
487 (U(s), U(o)) => s.cmp(&o),
488 (S(s), U(o)) => cmp_s_u(s, o),
489 (U(s), S(o)) => cmp_s_u(o, s).reverse(),
490 }
491 }
492}
493
494pub struct ConstEvalCtxt<'tcx> {
500 tcx: TyCtxt<'tcx>,
501 typing_env: ty::TypingEnv<'tcx>,
502 typeck: &'tcx TypeckResults<'tcx>,
503 source: Cell<ConstantSource>,
504 ctxt: Cell<SyntaxContext>,
505}
506
507impl<'tcx> ConstEvalCtxt<'tcx> {
508 pub fn new(cx: &LateContext<'tcx>) -> Self {
511 Self {
512 tcx: cx.tcx,
513 typing_env: cx.typing_env(),
514 typeck: cx.typeck_results(),
515 source: Cell::new(ConstantSource::Local),
516 ctxt: Cell::new(SyntaxContext::root()),
517 }
518 }
519
520 pub fn with_env(tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, typeck: &'tcx TypeckResults<'tcx>) -> Self {
522 Self {
523 tcx,
524 typing_env,
525 typeck,
526 source: Cell::new(ConstantSource::Local),
527 ctxt: Cell::new(SyntaxContext::root()),
528 }
529 }
530
531 pub fn eval_with_source(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<(Constant, ConstantSource)> {
534 self.source.set(ConstantSource::Local);
535 self.ctxt.set(ctxt);
536 self.expr(e).map(|c| (c, self.source.get()))
537 }
538
539 pub fn eval(&self, e: &Expr<'_>) -> Option<Constant> {
541 self.expr(e)
542 }
543
544 pub fn eval_local(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<Constant> {
551 match self.eval_with_source(e, ctxt) {
552 Some((x, ConstantSource::Local)) => Some(x),
553 _ => None,
554 }
555 }
556
557 pub fn eval_full_int(&self, e: &Expr<'_>, ctxt: SyntaxContext) -> Option<FullInt> {
564 match self.eval_with_source(e, ctxt) {
565 Some((x, ConstantSource::Local)) => x.int_value(self.tcx, self.typeck.expr_ty(e)),
566 _ => None,
567 }
568 }
569
570 pub fn eval_pat_expr(&self, pat_expr: &PatExpr<'_>) -> Option<Constant> {
571 match &pat_expr.kind {
572 PatExprKind::Lit { lit, negated } => {
573 let ty = self.typeck.node_type_opt(pat_expr.hir_id);
574 let val = lit_to_mir_constant(&lit.node, ty);
575 if *negated {
576 self.constant_negate(&val, ty?)
577 } else {
578 Some(val)
579 }
580 },
581 PatExprKind::ConstBlock(ConstBlock { body, .. }) => self.expr(self.tcx.hir_body(*body).value),
582 PatExprKind::Path(qpath) => self.qpath(qpath, pat_expr.hir_id),
583 }
584 }
585
586 fn check_ctxt(&self, ctxt: SyntaxContext) {
587 if self.ctxt.get() != ctxt {
588 self.source.set(ConstantSource::NonLocal);
589 }
590 }
591
592 fn qpath(&self, qpath: &QPath<'_>, hir_id: HirId) -> Option<Constant> {
593 self.fetch_path(qpath, hir_id)
594 .and_then(|c| mir_to_const(self.tcx, c, self.typeck.node_type(hir_id)))
595 }
596
597 fn expr(&self, e: &Expr<'_>) -> Option<Constant> {
599 self.check_ctxt(e.span.ctxt());
600 match e.kind {
601 ExprKind::ConstBlock(ConstBlock { body, .. }) => self.expr(self.tcx.hir_body(body).value),
602 ExprKind::DropTemps(e) => self.expr(e),
603 ExprKind::Path(ref qpath) => self.qpath(qpath, e.hir_id),
604 ExprKind::Block(block, _) => {
605 self.check_ctxt(block.span.ctxt());
606 self.block(block)
607 },
608 ExprKind::Lit(lit) => {
609 self.check_ctxt(lit.span.ctxt());
610 Some(lit_to_mir_constant(&lit.node, self.typeck.expr_ty_opt(e)))
611 },
612 ExprKind::Array(vec) => self.multi(vec).map(Constant::Vec),
613 ExprKind::Tup(tup) => self.multi(tup).map(Constant::Tuple),
614 ExprKind::Repeat(value, _) => {
615 let n = match self.typeck.expr_ty(e).kind() {
616 ty::Array(_, n) => n.try_to_target_usize(self.tcx)?,
617 _ => span_bug!(e.span, "typeck error"),
618 };
619 self.expr(value).map(|v| Constant::Repeat(Box::new(v), n))
620 },
621 ExprKind::Unary(op, operand) => self.expr(operand).and_then(|o| match op {
622 UnOp::Not => self.constant_not(&o, self.typeck.expr_ty(e)),
623 UnOp::Neg => self.constant_negate(&o, self.typeck.expr_ty(e)),
624 UnOp::Deref => Some(if let Constant::Ref(r) = o { *r } else { o }),
625 }),
626 ExprKind::If(cond, then, ref otherwise) => self.ifthenelse(cond, then, *otherwise),
627 ExprKind::Binary(op, left, right) => {
628 self.check_ctxt(e.span.ctxt());
629 self.binop(op.node, left, right)
630 },
631 ExprKind::Call(callee, []) => {
632 if let ExprKind::Path(qpath) = &callee.kind
634 && let Some(did) = self.typeck.qpath_res(qpath, callee.hir_id).opt_def_id()
635 {
636 match self.tcx.get_diagnostic_name(did) {
637 Some(sym::i8_legacy_fn_max_value) => Some(Constant::Int(i8::MAX as u128)),
638 Some(sym::i16_legacy_fn_max_value) => Some(Constant::Int(i16::MAX as u128)),
639 Some(sym::i32_legacy_fn_max_value) => Some(Constant::Int(i32::MAX as u128)),
640 Some(sym::i64_legacy_fn_max_value) => Some(Constant::Int(i64::MAX as u128)),
641 Some(sym::i128_legacy_fn_max_value) => Some(Constant::Int(i128::MAX as u128)),
642 _ => None,
643 }
644 } else {
645 None
646 }
647 },
648 ExprKind::Index(arr, index, _) => self.index(arr, index),
649 ExprKind::AddrOf(_, _, inner) => self.expr(inner).map(|r| Constant::Ref(Box::new(r))),
650 ExprKind::Field(base, ref field)
651 if let base_ty = self.typeck.expr_ty(base)
652 && match self.typeck.expr_adjustments(base) {
653 [] => true,
654 [.., a] => a.target == base_ty,
655 }
656 && let Some(Constant::Adt(constant)) = self.expr(base)
657 && let ty::Adt(adt_def, _) = *base_ty.kind()
658 && adt_def.is_struct()
659 && let Some((desired_field, ty)) =
660 field_of_struct(adt_def, self.tcx, constant, base_ty, field.name) =>
661 {
662 self.check_ctxt(field.span.ctxt());
663 mir_to_const(self.tcx, desired_field, ty)
664 },
665 _ => None,
666 }
667 }
668
669 pub fn eval_is_empty(&self, e: &Expr<'_>) -> Option<bool> {
673 match e.kind {
674 ExprKind::ConstBlock(ConstBlock { body, .. }) => self.eval_is_empty(self.tcx.hir_body(body).value),
675 ExprKind::DropTemps(e) => self.eval_is_empty(e),
676 ExprKind::Lit(lit) => {
677 if is_direct_expn_of(e.span, sym::cfg).is_some() {
678 None
679 } else {
680 match &lit.node {
681 LitKind::Str(is, _) => Some(is.is_empty()),
682 LitKind::ByteStr(s, _) | LitKind::CStr(s, _) => Some(s.as_byte_str().is_empty()),
683 _ => None,
684 }
685 }
686 },
687 ExprKind::Array(vec) => self.multi(vec).map(|v| v.is_empty()),
688 ExprKind::Repeat(..) => {
689 if let ty::Array(_, n) = self.typeck.expr_ty(e).kind() {
690 Some(n.try_to_target_usize(self.tcx)? == 0)
691 } else {
692 span_bug!(e.span, "typeck error");
693 }
694 },
695 _ => None,
696 }
697 }
698
699 #[expect(clippy::cast_possible_wrap)]
700 fn constant_not(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
701 use self::Constant::{Bool, Int};
702 match *o {
703 Bool(b) => Some(Bool(!b)),
704 Int(value) => {
705 let value = !value;
706 match *ty.kind() {
707 ty::Int(ity) => Some(Int(unsext(self.tcx, value as i128, ity))),
708 ty::Uint(ity) => Some(Int(clip(self.tcx, value, ity))),
709 _ => None,
710 }
711 },
712 _ => None,
713 }
714 }
715
716 fn constant_negate(&self, o: &Constant, ty: Ty<'_>) -> Option<Constant> {
717 use self::Constant::{F32, F64, Int};
718 match *o {
719 Int(value) => {
720 let ty::Int(ity) = *ty.kind() else { return None };
721 let (min, _) = ity.min_max()?;
722 let value = sext(self.tcx, value, ity);
724
725 if value == min {
727 return None;
728 }
729
730 let value = value.checked_neg()?;
731 Some(Int(unsext(self.tcx, value, ity)))
733 },
734 F32(f) => Some(F32(-f)),
735 F64(f) => Some(F64(-f)),
736 _ => None,
737 }
738 }
739
740 fn multi(&self, vec: &[Expr<'_>]) -> Option<Vec<Constant>> {
743 vec.iter().map(|elem| self.expr(elem)).collect::<Option<_>>()
744 }
745
746 #[expect(clippy::too_many_lines)]
748 fn fetch_path(&self, qpath: &QPath<'_>, id: HirId) -> Option<ConstValue> {
749 let did = match *qpath {
754 QPath::Resolved(None, path)
755 if path.span.ctxt() == self.ctxt.get()
756 && path.segments.iter().all(|s| self.ctxt.get() == s.ident.span.ctxt())
757 && let Res::Def(DefKind::Const, did) = path.res
758 && (matches!(
759 self.tcx.get_diagnostic_name(did),
760 Some(
761 sym::f32_legacy_const_digits
762 | sym::f32_legacy_const_epsilon
763 | sym::f32_legacy_const_infinity
764 | sym::f32_legacy_const_mantissa_dig
765 | sym::f32_legacy_const_max
766 | sym::f32_legacy_const_max_10_exp
767 | sym::f32_legacy_const_max_exp
768 | sym::f32_legacy_const_min
769 | sym::f32_legacy_const_min_10_exp
770 | sym::f32_legacy_const_min_exp
771 | sym::f32_legacy_const_min_positive
772 | sym::f32_legacy_const_nan
773 | sym::f32_legacy_const_neg_infinity
774 | sym::f32_legacy_const_radix
775 | sym::f64_legacy_const_digits
776 | sym::f64_legacy_const_epsilon
777 | sym::f64_legacy_const_infinity
778 | sym::f64_legacy_const_mantissa_dig
779 | sym::f64_legacy_const_max
780 | sym::f64_legacy_const_max_10_exp
781 | sym::f64_legacy_const_max_exp
782 | sym::f64_legacy_const_min
783 | sym::f64_legacy_const_min_10_exp
784 | sym::f64_legacy_const_min_exp
785 | sym::f64_legacy_const_min_positive
786 | sym::f64_legacy_const_nan
787 | sym::f64_legacy_const_neg_infinity
788 | sym::f64_legacy_const_radix
789 | sym::u8_legacy_const_min
790 | sym::u16_legacy_const_min
791 | sym::u32_legacy_const_min
792 | sym::u64_legacy_const_min
793 | sym::u128_legacy_const_min
794 | sym::usize_legacy_const_min
795 | sym::u8_legacy_const_max
796 | sym::u16_legacy_const_max
797 | sym::u32_legacy_const_max
798 | sym::u64_legacy_const_max
799 | sym::u128_legacy_const_max
800 | sym::i8_legacy_const_min
801 | sym::i16_legacy_const_min
802 | sym::i32_legacy_const_min
803 | sym::i64_legacy_const_min
804 | sym::i128_legacy_const_min
805 | sym::i8_legacy_const_max
806 | sym::i16_legacy_const_max
807 | sym::i32_legacy_const_max
808 | sym::i64_legacy_const_max
809 | sym::i128_legacy_const_max
810 )
811 ) || self.tcx.opt_parent(did).is_some_and(|parent| {
812 parent.is_diag_item(&self.tcx, sym::f16_consts_mod)
813 || parent.is_diag_item(&self.tcx, sym::f32_consts_mod)
814 || parent.is_diag_item(&self.tcx, sym::f64_consts_mod)
815 || parent.is_diag_item(&self.tcx, sym::f128_consts_mod)
816 })) =>
817 {
818 did
819 },
820 QPath::TypeRelative(ty, const_name)
821 if let TyKind::Path(QPath::Resolved(None, ty_path)) = ty.kind
822 && let [.., ty_name] = ty_path.segments
823 && (matches!(
824 ty_name.ident.name,
825 sym::i8
826 | sym::i16
827 | sym::i32
828 | sym::i64
829 | sym::i128
830 | sym::u8
831 | sym::u16
832 | sym::u32
833 | sym::u64
834 | sym::u128
835 | sym::f32
836 | sym::f64
837 | sym::char
838 ) || (ty_name.ident.name == sym::usize && const_name.ident.name == sym::MIN))
839 && const_name.ident.span.ctxt() == self.ctxt.get()
840 && ty.span.ctxt() == self.ctxt.get()
841 && ty_name.ident.span.ctxt() == self.ctxt.get()
842 && matches!(ty_path.res, Res::PrimTy(_))
843 && let Some((DefKind::AssocConst, did)) = self.typeck.type_dependent_def(id) =>
844 {
845 did
846 },
847 _ if let Res::Def(DefKind::Const | DefKind::AssocConst, did) = self.typeck.qpath_res(qpath, id) => {
848 self.source.set(ConstantSource::NonLocal);
849 did
850 },
851 _ => return None,
852 };
853
854 self.tcx
855 .const_eval_resolve(
856 self.typing_env,
857 mir::UnevaluatedConst::new(did, self.typeck.node_args(id)),
858 qpath.span(),
859 )
860 .ok()
861 }
862
863 fn index(&self, lhs: &'_ Expr<'_>, index: &'_ Expr<'_>) -> Option<Constant> {
864 let lhs = self.expr(lhs);
865 let index = self.expr(index);
866
867 match (lhs, index) {
868 (Some(Constant::Vec(vec)), Some(Constant::Int(index))) => match vec.get(index as usize) {
869 Some(Constant::F16(x)) => Some(Constant::F16(*x)),
870 Some(Constant::F32(x)) => Some(Constant::F32(*x)),
871 Some(Constant::F64(x)) => Some(Constant::F64(*x)),
872 Some(Constant::F128(x)) => Some(Constant::F128(*x)),
873 _ => None,
874 },
875 (Some(Constant::Vec(vec)), _) => {
876 if !vec.is_empty() && vec.iter().all(|x| *x == vec[0]) {
877 match vec.first() {
878 Some(Constant::F16(x)) => Some(Constant::F16(*x)),
879 Some(Constant::F32(x)) => Some(Constant::F32(*x)),
880 Some(Constant::F64(x)) => Some(Constant::F64(*x)),
881 Some(Constant::F128(x)) => Some(Constant::F128(*x)),
882 _ => None,
883 }
884 } else {
885 None
886 }
887 },
888 _ => None,
889 }
890 }
891
892 fn block(&self, block: &Block<'_>) -> Option<Constant> {
894 if block.stmts.is_empty()
895 && let Some(expr) = block.expr
896 {
897 let span = block.span.data();
899 if span.ctxt == SyntaxContext::root() {
900 if let Some(expr_span) = walk_span_to_context(expr.span, span.ctxt)
901 && let expr_lo = expr_span.lo()
902 && expr_lo >= span.lo
903 && let Some(src) = (span.lo..expr_lo).get_source_range(&self.tcx)
904 && let Some(src) = src.as_str()
905 {
906 use rustc_lexer::TokenKind::{BlockComment, LineComment, OpenBrace, Semi, Whitespace};
907 if !tokenize(src, FrontmatterAllowed::No)
908 .map(|t| t.kind)
909 .filter(|t| !matches!(t, Whitespace | LineComment { .. } | BlockComment { .. } | Semi))
910 .eq([OpenBrace])
911 {
912 self.source.set(ConstantSource::NonLocal);
913 }
914 } else {
915 self.source.set(ConstantSource::NonLocal);
917 }
918 }
919
920 self.expr(expr)
921 } else {
922 None
923 }
924 }
925
926 fn ifthenelse(&self, cond: &Expr<'_>, then: &Expr<'_>, otherwise: Option<&Expr<'_>>) -> Option<Constant> {
927 if let Some(Constant::Bool(b)) = self.expr(cond) {
928 if b {
929 self.expr(then)
930 } else {
931 otherwise.as_ref().and_then(|expr| self.expr(expr))
932 }
933 } else {
934 None
935 }
936 }
937
938 fn binop(&self, op: BinOpKind, left: &Expr<'_>, right: &Expr<'_>) -> Option<Constant> {
939 let l = self.expr(left)?;
940 let r = self.expr(right);
941 match (l, r) {
942 (Constant::Int(l), Some(Constant::Int(r))) => match *self.typeck.expr_ty_opt(left)?.kind() {
943 ty::Int(ity) => {
944 let (ty_min_value, _) = ity.min_max()?;
945 let bits = ity.bits();
946 let l = sext(self.tcx, l, ity);
947 let r = sext(self.tcx, r, ity);
948
949 if let BinOpKind::Div | BinOpKind::Rem = op
952 && l == ty_min_value
953 && r == -1
954 {
955 return None;
956 }
957
958 let zext = |n: i128| Constant::Int(unsext(self.tcx, n, ity));
959 match op {
960 BinOpKind::Add => l.checked_add(r).and_then(|n| ity.ensure_fits(n)).map(zext),
963 BinOpKind::Sub => l.checked_sub(r).and_then(|n| ity.ensure_fits(n)).map(zext),
964 BinOpKind::Mul => l.checked_mul(r).and_then(|n| ity.ensure_fits(n)).map(zext),
965 BinOpKind::Div if r != 0 => l.checked_div(r).map(zext),
966 BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext),
967 BinOpKind::Shr if r < bits && !r.is_negative() => l.checked_shr(r.try_into().ok()?).map(zext),
970 BinOpKind::Shl if r < bits && !r.is_negative() => l.checked_shl(r.try_into().ok()?).map(zext),
971 BinOpKind::BitXor => Some(zext(l ^ r)),
972 BinOpKind::BitOr => Some(zext(l | r)),
973 BinOpKind::BitAnd => Some(zext(l & r)),
974 BinOpKind::Eq => Some(Constant::Bool(l == r)),
976 BinOpKind::Ne => Some(Constant::Bool(l != r)),
977 BinOpKind::Lt => Some(Constant::Bool(l < r)),
978 BinOpKind::Le => Some(Constant::Bool(l <= r)),
979 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
980 BinOpKind::Gt => Some(Constant::Bool(l > r)),
981 _ => None,
982 }
983 },
984 ty::Uint(ity) => {
985 let bits = ity.bits();
986
987 match op {
988 BinOpKind::Add => l.checked_add(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
989 BinOpKind::Sub => l.checked_sub(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
990 BinOpKind::Mul => l.checked_mul(r).and_then(|n| ity.ensure_fits(n)).map(Constant::Int),
991 BinOpKind::Div => l.checked_div(r).map(Constant::Int),
992 BinOpKind::Rem => l.checked_rem(r).map(Constant::Int),
993 BinOpKind::Shr if r < bits => l.checked_shr(r.try_into().ok()?).map(Constant::Int),
994 BinOpKind::Shl if r < bits => l.checked_shl(r.try_into().ok()?).map(Constant::Int),
995 BinOpKind::BitXor => Some(Constant::Int(l ^ r)),
996 BinOpKind::BitOr => Some(Constant::Int(l | r)),
997 BinOpKind::BitAnd => Some(Constant::Int(l & r)),
998 BinOpKind::Eq => Some(Constant::Bool(l == r)),
999 BinOpKind::Ne => Some(Constant::Bool(l != r)),
1000 BinOpKind::Lt => Some(Constant::Bool(l < r)),
1001 BinOpKind::Le => Some(Constant::Bool(l <= r)),
1002 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1003 BinOpKind::Gt => Some(Constant::Bool(l > r)),
1004 _ => None,
1005 }
1006 },
1007 _ => None,
1008 },
1009 (Constant::F32(l), Some(Constant::F32(r))) => match op {
1011 BinOpKind::Add => Some(Constant::F32(l + r)),
1012 BinOpKind::Sub => Some(Constant::F32(l - r)),
1013 BinOpKind::Mul => Some(Constant::F32(l * r)),
1014 BinOpKind::Div => Some(Constant::F32(l / r)),
1015 BinOpKind::Rem => Some(Constant::F32(l % r)),
1016 BinOpKind::Eq => Some(Constant::Bool(l == r)),
1017 BinOpKind::Ne => Some(Constant::Bool(l != r)),
1018 BinOpKind::Lt => Some(Constant::Bool(l < r)),
1019 BinOpKind::Le => Some(Constant::Bool(l <= r)),
1020 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1021 BinOpKind::Gt => Some(Constant::Bool(l > r)),
1022 _ => None,
1023 },
1024 (Constant::F64(l), Some(Constant::F64(r))) => match op {
1025 BinOpKind::Add => Some(Constant::F64(l + r)),
1026 BinOpKind::Sub => Some(Constant::F64(l - r)),
1027 BinOpKind::Mul => Some(Constant::F64(l * r)),
1028 BinOpKind::Div => Some(Constant::F64(l / r)),
1029 BinOpKind::Rem => Some(Constant::F64(l % r)),
1030 BinOpKind::Eq => Some(Constant::Bool(l == r)),
1031 BinOpKind::Ne => Some(Constant::Bool(l != r)),
1032 BinOpKind::Lt => Some(Constant::Bool(l < r)),
1033 BinOpKind::Le => Some(Constant::Bool(l <= r)),
1034 BinOpKind::Ge => Some(Constant::Bool(l >= r)),
1035 BinOpKind::Gt => Some(Constant::Bool(l > r)),
1036 _ => None,
1037 },
1038 (l, r) => match (op, l, r) {
1039 (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)),
1040 (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)),
1041 (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => {
1042 Some(r)
1043 },
1044 (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)),
1045 (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)),
1046 (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)),
1047 _ => None,
1048 },
1049 }
1050 }
1051}
1052
1053pub fn mir_to_const<'tcx>(tcx: TyCtxt<'tcx>, val: ConstValue, ty: Ty<'tcx>) -> Option<Constant> {
1054 match (val, ty.kind()) {
1055 (_, &ty::Adt(adt_def, _)) if adt_def.is_struct() => Some(Constant::Adt(val)),
1056 (ConstValue::Scalar(Scalar::Int(int)), _) => match ty.kind() {
1057 ty::Bool => Some(Constant::Bool(int == ScalarInt::TRUE)),
1058 ty::Uint(_) | ty::Int(_) => Some(Constant::Int(int.to_bits(int.size()))),
1059 ty::Float(FloatTy::F16) => Some(Constant::F16(int.into())),
1060 ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits(int.into()))),
1061 ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits(int.into()))),
1062 ty::Float(FloatTy::F128) => Some(Constant::F128(int.into())),
1063 ty::RawPtr(_, _) => Some(Constant::RawPtr(int.to_bits(int.size()))),
1064 _ => None,
1065 },
1066 (_, ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Str) => {
1067 let data = val.try_get_slice_bytes_for_diagnostics(tcx)?;
1068 String::from_utf8(data.to_owned()).ok().map(Constant::Str)
1069 },
1070 (ConstValue::Indirect { alloc_id, offset }, ty::Array(sub_type, len)) => {
1071 let alloc = tcx.global_alloc(alloc_id).unwrap_memory().inner();
1072 let len = len.try_to_target_usize(tcx)?;
1073 let ty::Float(flt) = sub_type.kind() else {
1074 return None;
1075 };
1076 let size = Size::from_bits(flt.bit_width());
1077 let mut res = Vec::new();
1078 for idx in 0..len {
1079 let range = alloc_range(offset + size * idx, size);
1080 let val = alloc.read_scalar(&tcx, range, false).ok()?;
1081 res.push(match flt {
1082 FloatTy::F16 => Constant::F16(val.to_u16().discard_err()?),
1083 FloatTy::F32 => Constant::F32(f32::from_bits(val.to_u32().discard_err()?)),
1084 FloatTy::F64 => Constant::F64(f64::from_bits(val.to_u64().discard_err()?)),
1085 FloatTy::F128 => Constant::F128(val.to_u128().discard_err()?),
1086 });
1087 }
1088 Some(Constant::Vec(res))
1089 },
1090 _ => None,
1091 }
1092}
1093
1094fn field_of_struct<'tcx>(
1095 adt_def: ty::AdtDef<'tcx>,
1096 tcx: TyCtxt<'tcx>,
1097 value: ConstValue,
1098 ty: Ty<'tcx>,
1099 field: Symbol,
1100) -> Option<(ConstValue, Ty<'tcx>)> {
1101 if let Some(dc) = tcx.try_destructure_mir_constant_for_user_output(value, ty)
1102 && let Some(dc_variant) = dc.variant
1103 && let Some(variant) = adt_def.variants().get(dc_variant)
1104 && let Some(field_idx) = variant.fields.iter().position(|el| el.name == field)
1105 {
1106 dc.fields.get(field_idx).copied()
1107 } else {
1108 None
1109 }
1110}
1111
1112pub fn integer_const(cx: &LateContext<'_>, expr: &Expr<'_>, ctxt: SyntaxContext) -> Option<u128> {
1119 if let Some(Constant::Int(value)) = ConstEvalCtxt::new(cx).eval_local(expr, ctxt) {
1120 Some(value)
1121 } else {
1122 None
1123 }
1124}
1125
1126#[inline]
1133pub fn is_zero_integer_const(cx: &LateContext<'_>, expr: &Expr<'_>, ctxt: SyntaxContext) -> bool {
1134 integer_const(cx, expr, ctxt) == Some(0)
1135}
1136
1137pub fn const_item_rhs_to_expr<'tcx>(tcx: TyCtxt<'tcx>, ct_rhs: ConstItemRhs<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1138 match ct_rhs {
1139 ConstItemRhs::Body(body_id) => Some(tcx.hir_body(body_id).value),
1140 ConstItemRhs::TypeConst(const_arg) => match const_arg.kind {
1141 ConstArgKind::Anon(anon) => Some(tcx.hir_body(anon.body).value),
1142 ConstArgKind::Path(_) | ConstArgKind::Error(..) | ConstArgKind::Infer(..) => None,
1143 },
1144 }
1145}