]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_constant.rs
Auto merge of #102565 - jyn514:refactor-build-manifest, r=Mark-Simulacrum
[rust.git] / compiler / rustc_mir_build / src / build / expr / as_constant.rs
1 //! See docs in build/expr/mod.rs
2
3 use crate::build::{parse_float_into_constval, Builder};
4 use rustc_ast as ast;
5 use rustc_middle::mir;
6 use rustc_middle::mir::interpret::{
7     Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
8 };
9 use rustc_middle::mir::*;
10 use rustc_middle::thir::*;
11 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, TyCtxt};
12 use rustc_target::abi::Size;
13
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> {
18         let this = self;
19         let tcx = this.tcx;
20         let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
21         match *kind {
22             ExprKind::Scope { region_scope: _, lint_level: _, value } => {
23                 this.as_constant(&this.thir[value])
24             }
25             ExprKind::Literal { lit, neg } => {
26                 let literal =
27                     match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
28                         Ok(c) => c,
29                         Err(LitToConstError::Reported) => ConstantKind::Ty(tcx.const_error(ty)),
30                         Err(LitToConstError::TypeError) => {
31                             bug!("encountered type error in `lit_to_mir_constant")
32                         }
33                     };
34
35                 Constant { span, user_ty: None, literal }
36             }
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 {
40                         span,
41                         user_ty: user_ty.clone(),
42                         inferred_ty: ty,
43                     })
44                 });
45                 let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
46
47                 Constant { span, user_ty: user_ty, literal }
48             }
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 {
52                         span,
53                         user_ty: user_ty.clone(),
54                         inferred_ty: ty,
55                     })
56                 });
57                 let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
58
59                 Constant { span, user_ty: user_ty, literal }
60             }
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 {
64                         span,
65                         user_ty: user_ty.clone(),
66                         inferred_ty: ty,
67                     })
68                 });
69
70                 let uneval =
71                     mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
72                 let literal = ConstantKind::Unevaluated(uneval, ty);
73
74                 Constant { user_ty, span, literal }
75             }
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);
79
80                 Constant { user_ty: None, span, literal }
81             }
82             ExprKind::ConstBlock { did: def_id, substs } => {
83                 let uneval =
84                     mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
85                 let literal = ConstantKind::Unevaluated(uneval, ty);
86
87                 Constant { user_ty: None, span, literal }
88             }
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);
92
93                 Constant { span, user_ty: None, literal }
94             }
95             _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
96         }
97     }
98 }
99
100 #[instrument(skip(tcx, lit_input))]
101 pub(crate) fn lit_to_mir_constant<'tcx>(
102     tcx: TyCtxt<'tcx>,
103     lit_input: LitToConstInput<'tcx>,
104 ) -> Result<ConstantKind<'tcx>, LitToConstError> {
105     let LitToConstInput { lit, ty, neg } = lit_input;
106     let trunc = |n| {
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)))
113     };
114
115     let value = match (lit, &ty.kind()) {
116         (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
117             let s = s.as_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() }
121         }
122         (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
123             if matches!(inner_ty.kind(), ty::Slice(_)) =>
124         {
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() }
128         }
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))
132         }
133         (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
134             ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
135         }
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 })?
138         }
139         (ast::LitKind::Float(n, _), ty::Float(fty)) => {
140             parse_float_into_constval(*n, *fty, neg).ok_or(LitToConstError::Reported)?
141         }
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),
146     };
147
148     Ok(ConstantKind::Val(value, ty))
149 }