1use super::*;
3use rustc_const_eval::interpret::{interp_ok, InterpResult};
4use rustc_middle::mir::interpret;
5use rustc_middle::{mir, ty};
6
7impl ConstantLiteral {
8 fn byte_str(bytes: Vec<u8>) -> Self {
12 match String::from_utf8(bytes.clone()) {
13 Ok(s) => Self::Str(s),
14 Err(_) => Self::ByteStr(bytes),
15 }
16 }
17}
18
19#[tracing::instrument(level = "trace", skip(s))]
20pub(crate) fn scalar_int_to_constant_literal<'tcx, S: UnderOwnerState<'tcx>>(
21 s: &S,
22 x: rustc_middle::ty::ScalarInt,
23 ty: rustc_middle::ty::Ty<'tcx>,
24) -> ConstantLiteral {
25 match ty.kind() {
26 ty::Char => ConstantLiteral::Char(
27 char::try_from(x).s_expect(s, "scalar_int_to_constant_literal: expected a char"),
28 ),
29 ty::Bool => ConstantLiteral::Bool(
30 x.try_to_bool()
31 .s_expect(s, "scalar_int_to_constant_literal: expected a bool"),
32 ),
33 ty::Int(kind) => {
34 let v = x.to_int(x.size());
35 ConstantLiteral::Int(ConstantInt::Int(v, kind.sinto(s)))
36 }
37 ty::Uint(kind) => {
38 let v = x.to_uint(x.size());
39 ConstantLiteral::Int(ConstantInt::Uint(v, kind.sinto(s)))
40 }
41 ty::Float(kind) => {
42 let v = x.to_bits_unchecked();
43 bits_and_type_to_float_constant_literal(v, kind.sinto(s))
44 }
45 _ => {
46 let ty_sinto: Ty = ty.sinto(s);
47 supposely_unreachable_fatal!(
48 s,
49 "scalar_int_to_constant_literal_ExpectedLiteralType";
50 { ty, ty_sinto, x }
51 )
52 }
53 }
54}
55
56fn bits_and_type_to_float_constant_literal(bits: u128, ty: FloatTy) -> ConstantLiteral {
58 use rustc_apfloat::{ieee, Float};
59 let string = match &ty {
60 FloatTy::F16 => ieee::Half::from_bits(bits).to_string(),
61 FloatTy::F32 => ieee::Single::from_bits(bits).to_string(),
62 FloatTy::F64 => ieee::Double::from_bits(bits).to_string(),
63 FloatTy::F128 => ieee::Quad::from_bits(bits).to_string(),
64 };
65 ConstantLiteral::Float(string, ty)
66}
67
68impl ConstantExprKind {
69 pub fn decorate(self, ty: Ty, span: Span) -> Decorated<Self> {
70 Decorated {
71 contents: Box::new(self),
72 hir_id: None,
73 attributes: vec![],
74 ty,
75 span,
76 }
77 }
78}
79
80pub(crate) fn is_anon_const(
87 did: rustc_span::def_id::DefId,
88 tcx: rustc_middle::ty::TyCtxt<'_>,
89) -> bool {
90 matches!(
91 tcx.def_kind(did),
92 rustc_hir::def::DefKind::AnonConst | rustc_hir::def::DefKind::InlineConst
93 )
94}
95
96pub fn translate_constant_reference<'tcx>(
100 s: &impl UnderOwnerState<'tcx>,
101 span: rustc_span::Span,
102 ucv: rustc_middle::ty::UnevaluatedConst<'tcx>,
103) -> Option<ConstantExpr> {
104 let tcx = s.base().tcx;
105 if s.base().options.inline_anon_consts && is_anon_const(ucv.def, tcx) {
106 return None;
107 }
108 let typing_env = s.typing_env();
109 let ty = s.base().tcx.type_of(ucv.def).instantiate(tcx, ucv.args);
110 let ty = tcx
111 .try_normalize_erasing_regions(typing_env, ty)
112 .unwrap_or(ty);
113 let kind = if let Some(assoc) = s.base().tcx.opt_associated_item(ucv.def) {
114 if assoc.trait_item_def_id.is_some() {
115 let name = assoc.name.to_string();
117 let impl_expr = self_clause_for_item(s, ucv.def, ucv.args).unwrap();
118 ConstantExprKind::TraitConst { impl_expr, name }
119 } else {
120 let trait_refs = solve_item_required_traits(s, ucv.def, ucv.args);
122 ConstantExprKind::GlobalName {
123 id: ucv.def.sinto(s),
124 generics: ucv.args.sinto(s),
125 trait_refs,
126 }
127 }
128 } else {
129 ConstantExprKind::GlobalName {
131 id: ucv.def.sinto(s),
132 generics: ucv.args.sinto(s),
133 trait_refs: vec![],
134 }
135 };
136 let cv = kind.decorate(ty.sinto(s), span.sinto(s));
137 Some(cv)
138}
139
140pub fn eval_ty_constant<'tcx, S: UnderOwnerState<'tcx>>(
142 s: &S,
143 c: ty::Const<'tcx>,
144) -> Option<ty::Const<'tcx>> {
145 let tcx = s.base().tcx;
146 let evaluated = tcx.try_normalize_erasing_regions(s.typing_env(), c).ok()?;
147 (evaluated != c).then_some(evaluated)
148}
149
150pub fn eval_mir_constant<'tcx, S: UnderOwnerState<'tcx>>(
152 s: &S,
153 c: mir::Const<'tcx>,
154) -> Option<mir::Const<'tcx>> {
155 let evaluated = c
156 .eval(s.base().tcx, s.typing_env(), rustc_span::DUMMY_SP)
157 .ok()?;
158 let evaluated = mir::Const::Val(evaluated, c.ty());
159 (evaluated != c).then_some(evaluated)
160}
161
162impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, ConstantExpr> for ty::Const<'tcx> {
163 #[tracing::instrument(level = "trace", skip(s))]
164 fn sinto(&self, s: &S) -> ConstantExpr {
165 use rustc_middle::query::Key;
166 let span = self.default_span(s.base().tcx);
167 match self.kind() {
168 ty::ConstKind::Param(p) => {
169 let ty = p.find_ty_from_env(s.param_env());
170 let kind = ConstantExprKind::ConstRef { id: p.sinto(s) };
171 kind.decorate(ty.sinto(s), span.sinto(s))
172 }
173 ty::ConstKind::Infer(..) => {
174 fatal!(s[span], "ty::ConstKind::Infer node? {:#?}", self)
175 }
176
177 ty::ConstKind::Unevaluated(ucv) => match translate_constant_reference(s, span, ucv) {
178 Some(val) => val,
179 None => match eval_ty_constant(s, *self) {
180 Some(val) => val.sinto(s),
181 None => supposely_unreachable_fatal!(s, "TranslateUneval"; {self, ucv}),
183 },
184 },
185
186 ty::ConstKind::Value(val) => valtree_to_constant_expr(s, val.valtree, val.ty, span),
187 ty::ConstKind::Error(_) => fatal!(s[span], "ty::ConstKind::Error"),
188 ty::ConstKind::Expr(e) => fatal!(s[span], "ty::ConstKind::Expr {:#?}", e),
189
190 ty::ConstKind::Bound(i, bound) => {
191 supposely_unreachable_fatal!(s[span], "ty::ConstKind::Bound"; {i, bound});
192 }
193 _ => fatal!(s[span], "unexpected case"),
194 }
195 }
196}
197
198#[tracing::instrument(level = "trace", skip(s))]
199pub(crate) fn valtree_to_constant_expr<'tcx, S: UnderOwnerState<'tcx>>(
200 s: &S,
201 valtree: rustc_middle::ty::ValTree<'tcx>,
202 ty: rustc_middle::ty::Ty<'tcx>,
203 span: rustc_span::Span,
204) -> ConstantExpr {
205 let kind = match (&*valtree, ty.kind()) {
206 (_, ty::Ref(_, inner_ty, _)) => {
207 ConstantExprKind::Borrow(valtree_to_constant_expr(s, valtree, *inner_ty, span))
208 }
209 (ty::ValTreeKind::Branch(valtrees), ty::Str) => {
210 let bytes = valtrees
211 .iter()
212 .map(|x| match &***x {
213 ty::ValTreeKind::Leaf(leaf) => leaf.to_u8(),
214 _ => fatal!(
215 s[span],
216 "Expected a flat list of leaves while translating \
217 a str literal, got a arbitrary valtree."
218 ),
219 })
220 .collect();
221 ConstantExprKind::Literal(ConstantLiteral::byte_str(bytes))
222 }
223 (ty::ValTreeKind::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
224 let contents: rustc_middle::ty::DestructuredConst = s
225 .base()
226 .tcx
227 .destructure_const(ty::Const::new_value(s.base().tcx, valtree, ty));
228 let fields = contents.fields.iter().copied();
229 match ty.kind() {
230 ty::Array(_, _) => ConstantExprKind::Array {
231 fields: fields.map(|field| field.sinto(s)).collect(),
232 },
233 ty::Tuple(_) => ConstantExprKind::Tuple {
234 fields: fields.map(|field| field.sinto(s)).collect(),
235 },
236 ty::Adt(def, _) => {
237 let variant_idx = contents
238 .variant
239 .s_expect(s, "destructed const of adt without variant idx");
240 let variant_def = &def.variant(variant_idx);
241
242 ConstantExprKind::Adt {
243 info: get_variant_information(def, variant_idx, s),
244 fields: fields
245 .into_iter()
246 .zip(&variant_def.fields)
247 .map(|(value, field)| ConstantFieldExpr {
248 field: field.did.sinto(s),
249 value: value.sinto(s),
250 })
251 .collect(),
252 }
253 }
254 _ => unreachable!(),
255 }
256 }
257 (ty::ValTreeKind::Leaf(x), ty::RawPtr(_, _)) => {
258 use crate::rustc_type_ir::inherent::Ty;
259 let raw_address = x.to_bits_unchecked();
260 let uint_ty = UintTy::Usize;
261 let usize_ty = rustc_middle::ty::Ty::new_usize(s.base().tcx).sinto(s);
262 let lit = ConstantLiteral::Int(ConstantInt::Uint(raw_address, uint_ty));
263 ConstantExprKind::Cast {
264 source: ConstantExprKind::Literal(lit).decorate(usize_ty, span.sinto(s)),
265 }
266 }
267 (ty::ValTreeKind::Leaf(x), _) => {
268 ConstantExprKind::Literal(scalar_int_to_constant_literal(s, *x, ty))
269 }
270 _ => supposely_unreachable_fatal!(
271 s[span], "valtree_to_expr";
272 {valtree, ty}
273 ),
274 };
275 kind.decorate(ty.sinto(s), span.sinto(s))
276}
277
278fn op_to_const<'tcx, S: UnderOwnerState<'tcx>>(
281 s: &S,
282 span: rustc_span::Span,
283 ecx: &rustc_const_eval::const_eval::CompileTimeInterpCx<'tcx>,
284 op: rustc_const_eval::interpret::OpTy<'tcx>,
285) -> InterpResult<'tcx, ConstantExpr> {
286 use crate::rustc_const_eval::interpret::Projectable;
287 let tcx = s.base().tcx;
290 let ty = op.layout.ty;
291 let read_fields = |of: rustc_const_eval::interpret::OpTy<'tcx>, field_count| {
293 (0..field_count).map(move |i| {
294 let field_op = ecx.project_field(&of, i)?;
295 op_to_const(s, span, &ecx, field_op)
296 })
297 };
298 let kind = match ty.kind() {
299 _ if let Some(place) = op.as_mplace_or_imm().left()
301 && let ptr = place.ptr()
302 && let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr, 0)?
303 && let interpret::GlobalAlloc::Static(did) = tcx.global_alloc(alloc_id) =>
304 {
305 ConstantExprKind::GlobalName {
306 id: did.sinto(s),
307 generics: Vec::new(),
308 trait_refs: Vec::new(),
309 }
310 }
311 ty::Char | ty::Bool | ty::Uint(_) | ty::Int(_) | ty::Float(_) => {
312 let scalar = ecx.read_scalar(&op)?;
313 let scalar_int = scalar.try_to_scalar_int().unwrap();
314 let lit = scalar_int_to_constant_literal(s, scalar_int, ty);
315 ConstantExprKind::Literal(lit)
316 }
317 ty::Adt(adt_def, ..) if adt_def.is_union() => {
318 ConstantExprKind::Todo("Cannot translate constant of union type".into())
319 }
320 ty::Adt(adt_def, ..) => {
321 let variant = ecx.read_discriminant(&op)?;
322 let down = ecx.project_downcast(&op, variant)?;
323 let field_count = adt_def.variants()[variant].fields.len();
324 let fields = read_fields(down, field_count)
325 .zip(&adt_def.variant(variant).fields)
326 .map(|(value, field)| {
327 interp_ok(ConstantFieldExpr {
328 field: field.did.sinto(s),
329 value: value?,
330 })
331 })
332 .collect::<InterpResult<Vec<_>>>()?;
333 let variants_info = get_variant_information(adt_def, variant, s);
334 ConstantExprKind::Adt {
335 info: variants_info,
336 fields,
337 }
338 }
339 ty::Closure(def_id, args) => {
340 let def_id: DefId = def_id.sinto(s);
342 let field_count = args.as_closure().upvar_tys().len();
343 let fields = read_fields(op, field_count)
344 .map(|value| {
345 interp_ok(ConstantFieldExpr {
346 field: def_id.clone(),
349 value: value?,
350 })
351 })
352 .collect::<InterpResult<Vec<_>>>()?;
353 let variants_info = VariantInformations {
354 type_namespace: def_id.parent.clone().unwrap(),
355 typ: def_id.clone(),
356 variant: def_id,
357 kind: VariantKind::Struct { named: false },
358 };
359 ConstantExprKind::Adt {
360 info: variants_info,
361 fields,
362 }
363 }
364 ty::Tuple(args) => {
365 let fields = read_fields(op, args.len()).collect::<InterpResult<Vec<_>>>()?;
366 ConstantExprKind::Tuple { fields }
367 }
368 ty::Array(..) | ty::Slice(..) => {
369 let len = op.len(ecx)?;
370 let fields = (0..len)
371 .map(|i| {
372 let op = ecx.project_index(&op, i)?;
373 op_to_const(s, span, ecx, op)
374 })
375 .collect::<InterpResult<Vec<_>>>()?;
376 ConstantExprKind::Array { fields }
377 }
378 ty::Str => {
379 let str = ecx.read_str(&op.assert_mem_place())?;
380 ConstantExprKind::Literal(ConstantLiteral::Str(str.to_owned()))
381 }
382 ty::FnDef(def_id, args) => {
383 let (def_id, generics, generics_impls, method_impl) =
384 get_function_from_def_id_and_generics(s, *def_id, args);
385 ConstantExprKind::FnPtr {
386 def_id,
387 generics,
388 generics_impls,
389 method_impl,
390 }
391 }
392 ty::RawPtr(..) | ty::Ref(..) => {
393 let op = ecx.deref_pointer(&op)?;
394 let val = op_to_const(s, span, ecx, op.into())?;
395 match ty.kind() {
396 ty::Ref(..) => ConstantExprKind::Borrow(val),
397 ty::RawPtr(.., mutability) => ConstantExprKind::RawBorrow {
398 arg: val,
399 mutability: mutability.sinto(s),
400 },
401 _ => unreachable!(),
402 }
403 }
404 ty::FnPtr(..)
405 | ty::Dynamic(..)
406 | ty::Foreign(..)
407 | ty::Pat(..)
408 | ty::UnsafeBinder(..)
409 | ty::CoroutineClosure(..)
410 | ty::Coroutine(..)
411 | ty::CoroutineWitness(..) => ConstantExprKind::Todo("Unhandled constant type".into()),
412 ty::Alias(..) | ty::Param(..) | ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => {
413 fatal!(s[span], "Encountered evaluated constant of non-monomorphic type"; {op})
414 }
415 ty::Never | ty::Error(..) => {
416 fatal!(s[span], "Encountered evaluated constant of invalid type"; {ty})
417 }
418 };
419 let val = kind.decorate(ty.sinto(s), span.sinto(s));
420 interp_ok(val)
421}
422
423pub fn const_value_to_constant_expr<'tcx, S: UnderOwnerState<'tcx>>(
424 s: &S,
425 ty: rustc_middle::ty::Ty<'tcx>,
426 val: mir::ConstValue<'tcx>,
427 span: rustc_span::Span,
428) -> InterpResult<'tcx, ConstantExpr> {
429 let tcx = s.base().tcx;
430 let typing_env = s.typing_env();
431 let (ecx, op) =
432 rustc_const_eval::const_eval::mk_eval_cx_for_const_val(tcx.at(span), typing_env, val, ty)
433 .unwrap();
434 op_to_const(s, span, &ecx, op)
435}