]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_constant.rs
Rollup merge of #101648 - Timmmm:home_dir_docs, r=joshtriplett
[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::{
12     self, CanonicalUserType, CanonicalUserTypeAnnotation, TyCtxt, UserTypeAnnotationIndex,
13 };
14 use rustc_span::DUMMY_SP;
15 use rustc_target::abi::Size;
16
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> {
21         let this = self;
22         let tcx = this.tcx;
23         let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
24         match kind {
25             ExprKind::Scope { region_scope: _, lint_level: _, value } => {
26                 this.as_constant(&this.thir[*value])
27             }
28             _ => as_constant_inner(
29                 expr,
30                 |user_ty| {
31                     Some(this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
32                         span,
33                         user_ty: user_ty.clone(),
34                         inferred_ty: ty,
35                     }))
36                 },
37                 tcx,
38             ),
39         }
40     }
41 }
42
43 pub fn as_constant_inner<'tcx>(
44     expr: &Expr<'tcx>,
45     push_cuta: impl FnMut(&Box<CanonicalUserType<'tcx>>) -> Option<UserTypeAnnotationIndex>,
46     tcx: TyCtxt<'tcx>,
47 ) -> Constant<'tcx> {
48     let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
49     match *kind {
50         ExprKind::Literal { lit, neg } => {
51             let literal =
52                 match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
53                     Ok(c) => c,
54                     Err(LitToConstError::Reported(guar)) => {
55                         ConstantKind::Ty(tcx.const_error_with_guaranteed(ty, guar))
56                     }
57                     Err(LitToConstError::TypeError) => {
58                         bug!("encountered type error in `lit_to_mir_constant")
59                     }
60                 };
61
62             Constant { span, user_ty: None, literal }
63         }
64         ExprKind::NonHirLiteral { lit, ref user_ty } => {
65             let user_ty = user_ty.as_ref().map(push_cuta).flatten();
66
67             let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
68
69             Constant { span, user_ty: user_ty, literal }
70         }
71         ExprKind::ZstLiteral { ref user_ty } => {
72             let user_ty = user_ty.as_ref().map(push_cuta).flatten();
73
74             let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
75
76             Constant { span, user_ty: user_ty, literal }
77         }
78         ExprKind::NamedConst { def_id, substs, ref user_ty } => {
79             let user_ty = user_ty.as_ref().map(push_cuta).flatten();
80
81             let uneval = mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
82             let literal = ConstantKind::Unevaluated(uneval, ty);
83
84             Constant { user_ty, span, literal }
85         }
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);
89
90             Constant { user_ty: None, span, literal }
91         }
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);
95
96             Constant { user_ty: None, span, literal }
97         }
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);
101
102             Constant { span, user_ty: None, literal }
103         }
104         _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
105     }
106 }
107
108 #[instrument(skip(tcx, lit_input))]
109 pub(crate) fn lit_to_mir_constant<'tcx>(
110     tcx: TyCtxt<'tcx>,
111     lit_input: LitToConstInput<'tcx>,
112 ) -> Result<ConstantKind<'tcx>, LitToConstError> {
113     let LitToConstInput { lit, ty, neg } = lit_input;
114     let trunc = |n| {
115         let param_ty = ty::ParamEnv::reveal_all().and(ty);
116         let width = tcx
117             .layout_of(param_ty)
118             .map_err(|_| {
119                 LitToConstError::Reported(tcx.sess.delay_span_bug(
120                     DUMMY_SP,
121                     format!("couldn't compute width of literal: {:?}", lit_input.lit),
122                 ))
123             })?
124             .size;
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)))
129     };
130
131     let value = match (lit, &ty.kind()) {
132         (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
133             let s = s.as_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() }
137         }
138         (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
139             if matches!(inner_ty.kind(), ty::Slice(_)) =>
140         {
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() }
144         }
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))
148         }
149         (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
150             ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
151         }
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 })?
154         }
155         (ast::LitKind::Float(n, _), ty::Float(fty)) => parse_float_into_constval(*n, *fty, neg)
156             .ok_or_else(|| {
157                 LitToConstError::Reported(tcx.sess.delay_span_bug(
158                     DUMMY_SP,
159                     format!("couldn't parse float literal: {:?}", lit_input.lit),
160                 ))
161             })?,
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"),
167             ));
168         }
169         _ => return Err(LitToConstError::TypeError),
170     };
171
172     Ok(ConstantKind::Val(value, ty))
173 }