1 //! See docs in build/expr/mod.rs
3 use crate::build::{parse_float_into_constval, Builder};
5 use rustc_middle::mir::interpret::{
6 Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
8 use rustc_middle::mir::*;
9 use rustc_middle::thir::*;
10 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, TyCtxt};
11 use rustc_target::abi::Size;
13 impl<'a, 'tcx> Builder<'a, 'tcx> {
14 /// Compile `expr`, yielding a compile-time constant. Assumes that
15 /// `expr` is a valid compile-time constant!
16 pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> Constant<'tcx> {
19 let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
21 ExprKind::Scope { region_scope: _, lint_level: _, value } => {
22 this.as_constant(&this.thir[value])
24 ExprKind::Literal { lit, neg } => {
26 match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
28 Err(LitToConstError::Reported) => ConstantKind::Ty(tcx.const_error(ty)),
29 Err(LitToConstError::TypeError) => {
30 bug!("encountered type error in `lit_to_mir_constant")
34 Constant { span, user_ty: None, literal }
36 ExprKind::NonHirLiteral { lit, ref user_ty } => {
37 let user_ty = user_ty.as_ref().map(|user_ty| {
38 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
40 user_ty: user_ty.clone(),
44 let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
46 Constant { span, user_ty: user_ty, literal }
48 ExprKind::ZstLiteral { ref user_ty } => {
49 let user_ty = user_ty.as_ref().map(|user_ty| {
50 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
52 user_ty: user_ty.clone(),
56 let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
58 Constant { span, user_ty: user_ty, literal }
60 ExprKind::NamedConst { def_id, substs, ref user_ty } => {
61 let user_ty = user_ty.as_ref().map(|user_ty| {
62 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
64 user_ty: user_ty.clone(),
69 let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
70 let literal = ConstantKind::Unevaluated(uneval, ty);
72 Constant { user_ty, span, literal }
74 ExprKind::ConstParam { param, def_id: _ } => {
76 tcx.mk_const(ty::ConstS { kind: ty::ConstKind::Param(param), ty: expr.ty });
77 let literal = ConstantKind::Ty(const_param);
79 Constant { user_ty: None, span, literal }
81 ExprKind::ConstBlock { did: def_id, substs } => {
82 let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
83 let literal = ConstantKind::Unevaluated(uneval, ty);
85 Constant { user_ty: None, span, literal }
87 ExprKind::StaticRef { alloc_id, ty, .. } => {
88 let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
89 let literal = ConstantKind::Val(const_val, ty);
91 Constant { span, user_ty: None, literal }
93 _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
98 #[instrument(skip(tcx, lit_input))]
99 pub(crate) fn lit_to_mir_constant<'tcx>(
101 lit_input: LitToConstInput<'tcx>,
102 ) -> Result<ConstantKind<'tcx>, LitToConstError> {
103 let LitToConstInput { lit, ty, neg } = lit_input;
105 let param_ty = ty::ParamEnv::reveal_all().and(ty);
106 let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
107 trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
108 let result = width.truncate(n);
109 trace!("trunc result: {}", result);
110 Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
113 let value = match (lit, &ty.kind()) {
114 (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
116 let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
117 let allocation = tcx.intern_const_alloc(allocation);
118 ConstValue::Slice { data: allocation, start: 0, end: s.len() }
120 (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
121 if matches!(inner_ty.kind(), ty::Slice(_)) =>
123 let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
124 let allocation = tcx.intern_const_alloc(allocation);
125 ConstValue::Slice { data: allocation, start: 0, end: data.len() }
127 (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
128 let id = tcx.allocate_bytes(data);
129 ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
131 (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
132 ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
134 (ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
135 trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
137 (ast::LitKind::Float(n, _), ty::Float(fty)) => {
138 parse_float_into_constval(*n, *fty, neg).ok_or(LitToConstError::Reported)?
140 (ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
141 (ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
142 (ast::LitKind::Err, _) => return Err(LitToConstError::Reported),
143 _ => return Err(LitToConstError::TypeError),
146 Ok(ConstantKind::Val(value, ty))