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::{
12 self, CanonicalUserType, CanonicalUserTypeAnnotation, TyCtxt, UserTypeAnnotationIndex,
14 use rustc_span::DUMMY_SP;
15 use rustc_target::abi::Size;
17 impl<'a, 'tcx> Builder<'a, 'tcx> {
18 /// Compile `expr`, yielding a compile-time constant. Assumes that
19 /// `expr` is a valid compile-time constant!
20 pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> Constant<'tcx> {
23 let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
25 ExprKind::Scope { region_scope: _, lint_level: _, value } => {
26 this.as_constant(&this.thir[*value])
28 _ => as_constant_inner(
31 Some(this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
33 user_ty: user_ty.clone(),
43 pub fn as_constant_inner<'tcx>(
45 push_cuta: impl FnMut(&Box<CanonicalUserType<'tcx>>) -> Option<UserTypeAnnotationIndex>,
48 let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
50 ExprKind::Literal { lit, neg } => {
52 match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
54 Err(LitToConstError::Reported(guar)) => {
55 ConstantKind::Ty(tcx.const_error_with_guaranteed(ty, guar))
57 Err(LitToConstError::TypeError) => {
58 bug!("encountered type error in `lit_to_mir_constant")
62 Constant { span, user_ty: None, literal }
64 ExprKind::NonHirLiteral { lit, ref user_ty } => {
65 let user_ty = user_ty.as_ref().map(push_cuta).flatten();
67 let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
69 Constant { span, user_ty: user_ty, literal }
71 ExprKind::ZstLiteral { ref user_ty } => {
72 let user_ty = user_ty.as_ref().map(push_cuta).flatten();
74 let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
76 Constant { span, user_ty: user_ty, literal }
78 ExprKind::NamedConst { def_id, substs, ref user_ty } => {
79 let user_ty = user_ty.as_ref().map(push_cuta).flatten();
81 let uneval = mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
82 let literal = ConstantKind::Unevaluated(uneval, ty);
84 Constant { user_ty, span, literal }
86 ExprKind::ConstParam { param, def_id: _ } => {
87 let const_param = tcx.mk_const(ty::ConstKind::Param(param), expr.ty);
88 let literal = ConstantKind::Ty(const_param);
90 Constant { user_ty: None, span, literal }
92 ExprKind::ConstBlock { did: def_id, substs } => {
93 let uneval = mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
94 let literal = ConstantKind::Unevaluated(uneval, ty);
96 Constant { user_ty: None, span, literal }
98 ExprKind::StaticRef { alloc_id, ty, .. } => {
99 let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
100 let literal = ConstantKind::Val(const_val, ty);
102 Constant { span, user_ty: None, literal }
104 _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
108 #[instrument(skip(tcx, lit_input))]
109 pub(crate) fn lit_to_mir_constant<'tcx>(
111 lit_input: LitToConstInput<'tcx>,
112 ) -> Result<ConstantKind<'tcx>, LitToConstError> {
113 let LitToConstInput { lit, ty, neg } = lit_input;
115 let param_ty = ty::ParamEnv::reveal_all().and(ty);
119 LitToConstError::Reported(tcx.sess.delay_span_bug(
121 format!("couldn't compute width of literal: {:?}", lit_input.lit),
125 trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
126 let result = width.truncate(n);
127 trace!("trunc result: {}", result);
128 Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
131 let value = match (lit, &ty.kind()) {
132 (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
134 let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
135 let allocation = tcx.intern_const_alloc(allocation);
136 ConstValue::Slice { data: allocation, start: 0, end: s.len() }
138 (ast::LitKind::ByteStr(data, _), ty::Ref(_, inner_ty, _))
139 if matches!(inner_ty.kind(), ty::Slice(_)) =>
141 let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
142 let allocation = tcx.intern_const_alloc(allocation);
143 ConstValue::Slice { data: allocation, start: 0, end: data.len() }
145 (ast::LitKind::ByteStr(data, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
146 let id = tcx.allocate_bytes(data);
147 ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
149 (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
150 ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
152 (ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
153 trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
155 (ast::LitKind::Float(n, _), ty::Float(fty)) => parse_float_into_constval(*n, *fty, neg)
157 LitToConstError::Reported(tcx.sess.delay_span_bug(
159 format!("couldn't parse float literal: {:?}", lit_input.lit),
162 (ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
163 (ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
164 (ast::LitKind::Err, _) => {
165 return Err(LitToConstError::Reported(
166 tcx.sess.delay_span_bug(DUMMY_SP, "encountered LitKind::Err during mir build"),
169 _ => return Err(LitToConstError::TypeError),
172 Ok(ConstantKind::Val(value, ty))