rustc_mir_build/builder/expr/
as_constant.rs1use rustc_abi::Size;
4use rustc_ast::{self as ast};
5use rustc_hir::LangItem;
6use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, LitToConstInput, Scalar};
7use rustc_middle::mir::*;
8use rustc_middle::thir::*;
9use rustc_middle::ty::{
10 self, CanonicalUserType, CanonicalUserTypeAnnotation, Ty, TyCtxt, TypeVisitableExt as _,
11 UserTypeAnnotationIndex,
12};
13use rustc_middle::{bug, mir, span_bug};
14use tracing::{instrument, trace};
15
16use crate::builder::{Builder, parse_float_into_constval};
17
18impl<'a, 'tcx> Builder<'a, 'tcx> {
19 pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> ConstOperand<'tcx> {
22 let this = self; let tcx = this.tcx;
24 let Expr { ty, temp_scope_id: _, span, ref kind } = *expr;
25 match kind {
26 ExprKind::Scope { region_scope: _, lint_level: _, value } => {
27 this.as_constant(&this.thir[*value])
28 }
29 _ => as_constant_inner(
30 expr,
31 |user_ty| {
32 Some(this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
33 span,
34 user_ty: user_ty.clone(),
35 inferred_ty: ty,
36 }))
37 },
38 tcx,
39 ),
40 }
41 }
42}
43
44pub(crate) fn as_constant_inner<'tcx>(
45 expr: &Expr<'tcx>,
46 push_cuta: impl FnMut(&Box<CanonicalUserType<'tcx>>) -> Option<UserTypeAnnotationIndex>,
47 tcx: TyCtxt<'tcx>,
48) -> ConstOperand<'tcx> {
49 let Expr { ty, temp_scope_id: _, span, ref kind } = *expr;
50
51 match *kind {
52 ExprKind::Literal { lit, neg } => {
53 let const_ = lit_to_mir_constant(tcx, LitToConstInput { lit: lit.node, ty, neg });
54
55 ConstOperand { span, user_ty: None, const_ }
56 }
57 ExprKind::NonHirLiteral { lit, ref user_ty } => {
58 let user_ty = user_ty.as_ref().and_then(push_cuta);
59
60 let const_ = Const::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
61
62 ConstOperand { span, user_ty, const_ }
63 }
64 ExprKind::ZstLiteral { ref user_ty } => {
65 let user_ty = user_ty.as_ref().and_then(push_cuta);
66
67 let const_ = Const::Val(ConstValue::ZeroSized, ty);
68
69 ConstOperand { span, user_ty, const_ }
70 }
71 ExprKind::NamedConst { def_id, args, ref user_ty } => {
72 let user_ty = user_ty.as_ref().and_then(push_cuta);
73 if tcx.is_type_const(def_id) {
74 let uneval = ty::UnevaluatedConst::new(def_id, args);
75 let ct = ty::Const::new_unevaluated(tcx, uneval);
76
77 let const_ = Const::Ty(ty, ct);
78 return ConstOperand { span, user_ty, const_ };
79 }
80
81 let uneval = mir::UnevaluatedConst::new(def_id, args);
82 let const_ = Const::Unevaluated(uneval, ty);
83
84 ConstOperand { user_ty, span, const_ }
85 }
86 ExprKind::ConstParam { param, def_id: _ } => {
87 let const_param = ty::Const::new_param(tcx, param);
88 let const_ = Const::Ty(expr.ty, const_param);
89
90 ConstOperand { user_ty: None, span, const_ }
91 }
92 ExprKind::ConstBlock { did: def_id, args } => {
93 let uneval = mir::UnevaluatedConst::new(def_id, args);
94 let const_ = Const::Unevaluated(uneval, ty);
95
96 ConstOperand { user_ty: None, span, const_ }
97 }
98 ExprKind::StaticRef { alloc_id, ty, .. } => {
99 let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
100 let const_ = Const::Val(const_val, ty);
101
102 ConstOperand { span, user_ty: None, const_ }
103 }
104 _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
105 }
106}
107
108#[instrument(skip(tcx, lit_input))]
109fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx>) -> Const<'tcx> {
110 let LitToConstInput { lit, ty, neg } = lit_input;
111
112 if let Err(guar) = ty.error_reported() {
113 return Const::Ty(Ty::new_error(tcx, guar), ty::Const::new_error(tcx, guar));
114 }
115
116 let lit_ty = match *ty.kind() {
117 ty::Pat(base, _) => base,
118 _ => ty,
119 };
120
121 let trunc = |n| {
122 let width = lit_ty.primitive_size(tcx);
123 trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
124 let result = width.truncate(n);
125 trace!("trunc result: {}", result);
126 ConstValue::Scalar(Scalar::from_uint(result, width))
127 };
128
129 let value = match (lit, lit_ty.kind()) {
130 (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
131 let s = s.as_str().as_bytes();
132 let len = s.len();
133 let allocation = tcx.allocate_bytes_dedup(s, CTFE_ALLOC_SALT);
134 ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
135 }
136 (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _))
137 if matches!(inner_ty.kind(), ty::Slice(_)) =>
138 {
139 let data = byte_sym.as_byte_str();
140 let len = data.len();
141 let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
142 ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
143 }
144 (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
145 let id = tcx.allocate_bytes_dedup(byte_sym.as_byte_str(), CTFE_ALLOC_SALT);
146 ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
147 }
148 (ast::LitKind::CStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::CStr)) =>
149 {
150 let data = byte_sym.as_byte_str();
151 let len = data.len();
152 let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
153 ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
154 }
155 (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
156 ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1)))
157 }
158 (ast::LitKind::Int(n, _), ty::Uint(_)) if !neg => trunc(n.get()),
159 (ast::LitKind::Int(n, _), ty::Int(_)) => {
160 trunc(if neg { (n.get() as i128).overflowing_neg().0 as u128 } else { n.get() })
161 }
162 (ast::LitKind::Float(n, _), ty::Float(fty)) => {
163 parse_float_into_constval(n, *fty, neg).unwrap()
164 }
165 (ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(b)),
166 (ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(c)),
167 (ast::LitKind::Err(guar), _) => {
168 return Const::Ty(Ty::new_error(tcx, guar), ty::Const::new_error(tcx, guar));
169 }
170 _ => bug!("invalid lit/ty combination in `lit_to_mir_constant`: {lit:?}: {ty:?}"),
171 };
172
173 Const::Val(value, ty)
174}