]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_constant.rs
merge rustc history
[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::interpret::{
6     Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
7 };
8 use rustc_middle::mir::*;
9 use rustc_middle::thir::*;
10 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, TyCtxt};
11 use rustc_target::abi::Size;
12
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> {
17         let this = self;
18         let tcx = this.tcx;
19         let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
20         match *kind {
21             ExprKind::Scope { region_scope: _, lint_level: _, value } => {
22                 this.as_constant(&this.thir[value])
23             }
24             ExprKind::Literal { lit, neg } => {
25                 let literal =
26                     match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
27                         Ok(c) => c,
28                         Err(LitToConstError::Reported) => ConstantKind::Ty(tcx.const_error(ty)),
29                         Err(LitToConstError::TypeError) => {
30                             bug!("encountered type error in `lit_to_mir_constant")
31                         }
32                     };
33
34                 Constant { span, user_ty: None, literal }
35             }
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 {
39                         span,
40                         user_ty: user_ty.clone(),
41                         inferred_ty: ty,
42                     })
43                 });
44                 let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
45
46                 Constant { span, user_ty: user_ty, literal }
47             }
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 {
51                         span,
52                         user_ty: user_ty.clone(),
53                         inferred_ty: ty,
54                     })
55                 });
56                 let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
57
58                 Constant { span, user_ty: user_ty, literal }
59             }
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 {
63                         span,
64                         user_ty: user_ty.clone(),
65                         inferred_ty: ty,
66                     })
67                 });
68
69                 let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
70                 let literal = ConstantKind::Unevaluated(uneval, ty);
71
72                 Constant { user_ty, span, literal }
73             }
74             ExprKind::ConstParam { param, def_id: _ } => {
75                 let const_param =
76                     tcx.mk_const(ty::ConstS { kind: ty::ConstKind::Param(param), ty: expr.ty });
77                 let literal = ConstantKind::Ty(const_param);
78
79                 Constant { user_ty: None, span, literal }
80             }
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);
84
85                 Constant { user_ty: None, span, literal }
86             }
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);
90
91                 Constant { span, user_ty: None, literal }
92             }
93             _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
94         }
95     }
96 }
97
98 #[instrument(skip(tcx, lit_input))]
99 pub(crate) fn lit_to_mir_constant<'tcx>(
100     tcx: TyCtxt<'tcx>,
101     lit_input: LitToConstInput<'tcx>,
102 ) -> Result<ConstantKind<'tcx>, LitToConstError> {
103     let LitToConstInput { lit, ty, neg } = lit_input;
104     let trunc = |n| {
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)))
111     };
112
113     let value = match (lit, &ty.kind()) {
114         (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
115             let s = s.as_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() }
119         }
120         (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
121             if matches!(inner_ty.kind(), ty::Slice(_)) =>
122         {
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() }
126         }
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))
130         }
131         (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
132             ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
133         }
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 })?
136         }
137         (ast::LitKind::Float(n, _), ty::Float(fty)) => {
138             parse_float_into_constval(*n, *fty, neg).ok_or(LitToConstError::Reported)?
139         }
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),
144     };
145
146     Ok(ConstantKind::Val(value, ty))
147 }