]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_constant.rs
Rollup merge of #104117 - crlf0710:update_feature_gate, r=jackh726
[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_span::DUMMY_SP;
13 use rustc_target::abi::Size;
14
15 impl<'a, 'tcx> Builder<'a, 'tcx> {
16     /// Compile `expr`, yielding a compile-time constant. Assumes that
17     /// `expr` is a valid compile-time constant!
18     pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> Constant<'tcx> {
19         let this = self;
20         let tcx = this.tcx;
21         let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
22         match *kind {
23             ExprKind::Scope { region_scope: _, lint_level: _, value } => {
24                 this.as_constant(&this.thir[value])
25             }
26             ExprKind::Literal { lit, neg } => {
27                 let literal =
28                     match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
29                         Ok(c) => c,
30                         Err(LitToConstError::Reported(guar)) => {
31                             ConstantKind::Ty(tcx.const_error_with_guaranteed(ty, guar))
32                         }
33                         Err(LitToConstError::TypeError) => {
34                             bug!("encountered type error in `lit_to_mir_constant")
35                         }
36                     };
37
38                 Constant { span, user_ty: None, literal }
39             }
40             ExprKind::NonHirLiteral { lit, ref user_ty } => {
41                 let user_ty = user_ty.as_ref().map(|user_ty| {
42                     this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
43                         span,
44                         user_ty: user_ty.clone(),
45                         inferred_ty: ty,
46                     })
47                 });
48                 let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
49
50                 Constant { span, user_ty: user_ty, literal }
51             }
52             ExprKind::ZstLiteral { ref user_ty } => {
53                 let user_ty = user_ty.as_ref().map(|user_ty| {
54                     this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
55                         span,
56                         user_ty: user_ty.clone(),
57                         inferred_ty: ty,
58                     })
59                 });
60                 let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
61
62                 Constant { span, user_ty: user_ty, literal }
63             }
64             ExprKind::NamedConst { def_id, substs, ref user_ty } => {
65                 let user_ty = user_ty.as_ref().map(|user_ty| {
66                     this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
67                         span,
68                         user_ty: user_ty.clone(),
69                         inferred_ty: ty,
70                     })
71                 });
72
73                 let uneval =
74                     mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
75                 let literal = ConstantKind::Unevaluated(uneval, ty);
76
77                 Constant { user_ty, span, literal }
78             }
79             ExprKind::ConstParam { param, def_id: _ } => {
80                 let const_param = tcx.mk_const(ty::ConstKind::Param(param), expr.ty);
81                 let literal = ConstantKind::Ty(const_param);
82
83                 Constant { user_ty: None, span, literal }
84             }
85             ExprKind::ConstBlock { did: def_id, substs } => {
86                 let uneval =
87                     mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
88                 let literal = ConstantKind::Unevaluated(uneval, ty);
89
90                 Constant { user_ty: None, span, literal }
91             }
92             ExprKind::StaticRef { alloc_id, ty, .. } => {
93                 let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
94                 let literal = ConstantKind::Val(const_val, ty);
95
96                 Constant { span, user_ty: None, literal }
97             }
98             _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
99         }
100     }
101 }
102
103 #[instrument(skip(tcx, lit_input))]
104 pub(crate) fn lit_to_mir_constant<'tcx>(
105     tcx: TyCtxt<'tcx>,
106     lit_input: LitToConstInput<'tcx>,
107 ) -> Result<ConstantKind<'tcx>, LitToConstError> {
108     let LitToConstInput { lit, ty, neg } = lit_input;
109     let trunc = |n| {
110         let param_ty = ty::ParamEnv::reveal_all().and(ty);
111         let width = tcx
112             .layout_of(param_ty)
113             .map_err(|_| {
114                 LitToConstError::Reported(tcx.sess.delay_span_bug(
115                     DUMMY_SP,
116                     format!("couldn't compute width of literal: {:?}", lit_input.lit),
117                 ))
118             })?
119             .size;
120         trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
121         let result = width.truncate(n);
122         trace!("trunc result: {}", result);
123         Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
124     };
125
126     let value = match (lit, &ty.kind()) {
127         (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
128             let s = s.as_str();
129             let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
130             let allocation = tcx.intern_const_alloc(allocation);
131             ConstValue::Slice { data: allocation, start: 0, end: s.len() }
132         }
133         (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
134             if matches!(inner_ty.kind(), ty::Slice(_)) =>
135         {
136             let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
137             let allocation = tcx.intern_const_alloc(allocation);
138             ConstValue::Slice { data: allocation, start: 0, end: data.len() }
139         }
140         (ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
141             let id = tcx.allocate_bytes(data);
142             ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
143         }
144         (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
145             ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
146         }
147         (ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
148             trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
149         }
150         (ast::LitKind::Float(n, _), ty::Float(fty)) => parse_float_into_constval(*n, *fty, neg)
151             .ok_or_else(|| {
152                 LitToConstError::Reported(tcx.sess.delay_span_bug(
153                     DUMMY_SP,
154                     format!("couldn't parse float literal: {:?}", lit_input.lit),
155                 ))
156             })?,
157         (ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
158         (ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
159         (ast::LitKind::Err, _) => {
160             return Err(LitToConstError::Reported(
161                 tcx.sess.delay_span_bug(DUMMY_SP, "encountered LitKind::Err during mir build"),
162             ));
163         }
164         _ => return Err(LitToConstError::TypeError),
165     };
166
167     Ok(ConstantKind::Val(value, ty))
168 }