rustc_mir_build/thir/
constant.rs

1use rustc_abi::Size;
2use rustc_ast::{self as ast};
3use rustc_hir::LangItem;
4use rustc_middle::bug;
5use rustc_middle::mir::interpret::LitToConstInput;
6use rustc_middle::ty::{self, ScalarInt, TyCtxt, TypeVisitableExt as _};
7use tracing::trace;
8
9use crate::builder::parse_float_into_scalar;
10
11pub(crate) fn lit_to_const<'tcx>(
12    tcx: TyCtxt<'tcx>,
13    lit_input: LitToConstInput<'tcx>,
14) -> ty::Const<'tcx> {
15    let LitToConstInput { lit, ty, neg } = lit_input;
16
17    if let Err(guar) = ty.error_reported() {
18        return ty::Const::new_error(tcx, guar);
19    }
20
21    let trunc = |n, width: ty::UintTy| {
22        let width = width
23            .normalize(tcx.data_layout.pointer_size.bits().try_into().unwrap())
24            .bit_width()
25            .unwrap();
26        let width = Size::from_bits(width);
27        trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
28        let result = width.truncate(n);
29        trace!("trunc result: {}", result);
30
31        ScalarInt::try_from_uint(result, width)
32            .unwrap_or_else(|| bug!("expected to create ScalarInt from uint {:?}", result))
33    };
34
35    let valtree = match (lit, ty.kind()) {
36        (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
37            let str_bytes = s.as_str().as_bytes();
38            ty::ValTree::from_raw_bytes(tcx, str_bytes)
39        }
40        (ast::LitKind::Str(s, _), ty::Str) if tcx.features().deref_patterns() => {
41            // String literal patterns may have type `str` if `deref_patterns` is enabled, in order
42            // to allow `deref!("..."): String`.
43            let str_bytes = s.as_str().as_bytes();
44            ty::ValTree::from_raw_bytes(tcx, str_bytes)
45        }
46        (ast::LitKind::ByteStr(data, _), ty::Ref(_, inner_ty, _))
47            if matches!(inner_ty.kind(), ty::Slice(_) | ty::Array(..)) =>
48        {
49            let bytes = data as &[u8];
50            ty::ValTree::from_raw_bytes(tcx, bytes)
51        }
52        (ast::LitKind::ByteStr(data, _), ty::Slice(_) | ty::Array(..))
53            if tcx.features().deref_patterns() =>
54        {
55            // Byte string literal patterns may have type `[u8]` or `[u8; N]` if `deref_patterns` is
56            // enabled, in order to allow, e.g., `deref!(b"..."): Vec<u8>`.
57            let bytes = data as &[u8];
58            ty::ValTree::from_raw_bytes(tcx, bytes)
59        }
60        (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
61            ty::ValTree::from_scalar_int(tcx, (*n).into())
62        }
63        (ast::LitKind::CStr(data, _), ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::CStr)) =>
64        {
65            let bytes = data as &[u8];
66            ty::ValTree::from_raw_bytes(tcx, bytes)
67        }
68        (ast::LitKind::Int(n, _), ty::Uint(ui)) if !neg => {
69            let scalar_int = trunc(n.get(), *ui);
70            ty::ValTree::from_scalar_int(tcx, scalar_int)
71        }
72        (ast::LitKind::Int(n, _), ty::Int(i)) => {
73            let scalar_int = trunc(
74                if neg { (n.get() as i128).overflowing_neg().0 as u128 } else { n.get() },
75                i.to_unsigned(),
76            );
77            ty::ValTree::from_scalar_int(tcx, scalar_int)
78        }
79        (ast::LitKind::Bool(b), ty::Bool) => ty::ValTree::from_scalar_int(tcx, (*b).into()),
80        (ast::LitKind::Float(n, _), ty::Float(fty)) => {
81            let bits = parse_float_into_scalar(*n, *fty, neg).unwrap_or_else(|| {
82                tcx.dcx().bug(format!("couldn't parse float literal: {:?}", lit_input.lit))
83            });
84            ty::ValTree::from_scalar_int(tcx, bits)
85        }
86        (ast::LitKind::Char(c), ty::Char) => ty::ValTree::from_scalar_int(tcx, (*c).into()),
87        (ast::LitKind::Err(guar), _) => return ty::Const::new_error(tcx, *guar),
88        _ => return ty::Const::new_misc_error(tcx),
89    };
90
91    ty::Const::new_value(tcx, valtree, ty)
92}