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_span::DUMMY_SP;
13 use rustc_target::abi::Size;
15 impl<'a, 'tcx> Builder<'a, 'tcx> {
16 /// Compile `expr`, yielding a compile-time constant. Assumes that
17 /// `expr` is a valid compile-time constant!
18 pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> Constant<'tcx> {
21 let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
23 ExprKind::Scope { region_scope: _, lint_level: _, value } => {
24 this.as_constant(&this.thir[value])
26 ExprKind::Literal { lit, neg } => {
28 match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
30 Err(LitToConstError::Reported(guar)) => {
31 ConstantKind::Ty(tcx.const_error_with_guaranteed(ty, guar))
33 Err(LitToConstError::TypeError) => {
34 bug!("encountered type error in `lit_to_mir_constant")
38 Constant { span, user_ty: None, literal }
40 ExprKind::NonHirLiteral { lit, ref user_ty } => {
41 let user_ty = user_ty.as_ref().map(|user_ty| {
42 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
44 user_ty: user_ty.clone(),
48 let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
50 Constant { span, user_ty: user_ty, literal }
52 ExprKind::ZstLiteral { ref user_ty } => {
53 let user_ty = user_ty.as_ref().map(|user_ty| {
54 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
56 user_ty: user_ty.clone(),
60 let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
62 Constant { span, user_ty: user_ty, literal }
64 ExprKind::NamedConst { def_id, substs, ref user_ty } => {
65 let user_ty = user_ty.as_ref().map(|user_ty| {
66 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
68 user_ty: user_ty.clone(),
74 mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
75 let literal = ConstantKind::Unevaluated(uneval, ty);
77 Constant { user_ty, span, literal }
79 ExprKind::ConstParam { param, def_id: _ } => {
80 let const_param = tcx.mk_const(ty::ConstKind::Param(param), expr.ty);
81 let literal = ConstantKind::Ty(const_param);
83 Constant { user_ty: None, span, literal }
85 ExprKind::ConstBlock { did: def_id, substs } => {
87 mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
88 let literal = ConstantKind::Unevaluated(uneval, ty);
90 Constant { user_ty: None, span, literal }
92 ExprKind::StaticRef { alloc_id, ty, .. } => {
93 let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
94 let literal = ConstantKind::Val(const_val, ty);
96 Constant { span, user_ty: None, literal }
98 _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
103 #[instrument(skip(tcx, lit_input))]
104 pub(crate) fn lit_to_mir_constant<'tcx>(
106 lit_input: LitToConstInput<'tcx>,
107 ) -> Result<ConstantKind<'tcx>, LitToConstError> {
108 let LitToConstInput { lit, ty, neg } = lit_input;
110 let param_ty = ty::ParamEnv::reveal_all().and(ty);
114 LitToConstError::Reported(tcx.sess.delay_span_bug(
116 format!("couldn't compute width of literal: {:?}", lit_input.lit),
120 trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
121 let result = width.truncate(n);
122 trace!("trunc result: {}", result);
123 Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
126 let value = match (lit, &ty.kind()) {
127 (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
129 let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
130 let allocation = tcx.intern_const_alloc(allocation);
131 ConstValue::Slice { data: allocation, start: 0, end: s.len() }
133 (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
134 if matches!(inner_ty.kind(), ty::Slice(_)) =>
136 let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
137 let allocation = tcx.intern_const_alloc(allocation);
138 ConstValue::Slice { data: allocation, start: 0, end: data.len() }
140 (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
141 let id = tcx.allocate_bytes(data);
142 ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
144 (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
145 ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
147 (ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
148 trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
150 (ast::LitKind::Float(n, _), ty::Float(fty)) => parse_float_into_constval(*n, *fty, neg)
152 LitToConstError::Reported(tcx.sess.delay_span_bug(
154 format!("couldn't parse float literal: {:?}", lit_input.lit),
157 (ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
158 (ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
159 (ast::LitKind::Err, _) => {
160 return Err(LitToConstError::Reported(
161 tcx.sess.delay_span_bug(DUMMY_SP, "encountered LitKind::Err during mir build"),
164 _ => return Err(LitToConstError::TypeError),
167 Ok(ConstantKind::Val(value, ty))