1 //! See docs in build/expr/mod.rs
3 use crate::build::{parse_float_into_constval, Builder};
6 use rustc_middle::mir::interpret::{
7 Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
9 use rustc_middle::mir::*;
10 use rustc_middle::thir::*;
11 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, TyCtxt};
12 use rustc_target::abi::Size;
14 impl<'a, 'tcx> Builder<'a, 'tcx> {
15 /// Compile `expr`, yielding a compile-time constant. Assumes that
16 /// `expr` is a valid compile-time constant!
17 pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> Constant<'tcx> {
20 let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
22 ExprKind::Scope { region_scope: _, lint_level: _, value } => {
23 this.as_constant(&this.thir[value])
25 ExprKind::Literal { lit, neg } => {
27 match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
29 Err(LitToConstError::Reported) => ConstantKind::Ty(tcx.const_error(ty)),
30 Err(LitToConstError::TypeError) => {
31 bug!("encountered type error in `lit_to_mir_constant")
35 Constant { span, user_ty: None, literal }
37 ExprKind::NonHirLiteral { lit, ref user_ty } => {
38 let user_ty = user_ty.as_ref().map(|user_ty| {
39 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
41 user_ty: user_ty.clone(),
45 let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
47 Constant { span, user_ty: user_ty, literal }
49 ExprKind::ZstLiteral { ref user_ty } => {
50 let user_ty = user_ty.as_ref().map(|user_ty| {
51 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
53 user_ty: user_ty.clone(),
57 let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
59 Constant { span, user_ty: user_ty, literal }
61 ExprKind::NamedConst { def_id, substs, ref user_ty } => {
62 let user_ty = user_ty.as_ref().map(|user_ty| {
63 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
65 user_ty: user_ty.clone(),
71 mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
72 let literal = ConstantKind::Unevaluated(uneval, ty);
74 Constant { user_ty, span, literal }
76 ExprKind::ConstParam { param, def_id: _ } => {
77 let const_param = tcx.mk_const(ty::ConstKind::Param(param), expr.ty);
78 let literal = ConstantKind::Ty(const_param);
80 Constant { user_ty: None, span, literal }
82 ExprKind::ConstBlock { did: def_id, substs } => {
84 mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
85 let literal = ConstantKind::Unevaluated(uneval, ty);
87 Constant { user_ty: None, span, literal }
89 ExprKind::StaticRef { alloc_id, ty, .. } => {
90 let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
91 let literal = ConstantKind::Val(const_val, ty);
93 Constant { span, user_ty: None, literal }
95 _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
100 #[instrument(skip(tcx, lit_input))]
101 pub(crate) fn lit_to_mir_constant<'tcx>(
103 lit_input: LitToConstInput<'tcx>,
104 ) -> Result<ConstantKind<'tcx>, LitToConstError> {
105 let LitToConstInput { lit, ty, neg } = lit_input;
107 let param_ty = ty::ParamEnv::reveal_all().and(ty);
108 let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
109 trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
110 let result = width.truncate(n);
111 trace!("trunc result: {}", result);
112 Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
115 let value = match (lit, &ty.kind()) {
116 (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
118 let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
119 let allocation = tcx.intern_const_alloc(allocation);
120 ConstValue::Slice { data: allocation, start: 0, end: s.len() }
122 (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
123 if matches!(inner_ty.kind(), ty::Slice(_)) =>
125 let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
126 let allocation = tcx.intern_const_alloc(allocation);
127 ConstValue::Slice { data: allocation, start: 0, end: data.len() }
129 (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
130 let id = tcx.allocate_bytes(data);
131 ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
133 (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
134 ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
136 (ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
137 trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
139 (ast::LitKind::Float(n, _), ty::Float(fty)) => {
140 parse_float_into_constval(*n, *fty, neg).ok_or(LitToConstError::Reported)?
142 (ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
143 (ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
144 (ast::LitKind::Err, _) => return Err(LitToConstError::Reported),
145 _ => return Err(LitToConstError::TypeError),
148 Ok(ConstantKind::Val(value, ty))