hax_frontend_exporter/constant_utils/
uneval.rs

1//! Reconstruct structured expressions from rustc's various constant representations.
2use super::*;
3use rustc_const_eval::interpret::{InterpResult, interp_ok};
4use rustc_middle::mir::interpret;
5use rustc_middle::{mir, ty};
6
7impl ConstantLiteral {
8    /// Rustc always represents string constants as `&[u8]`, but this
9    /// is not nice to consume. This associated function interpret
10    /// bytes as an unicode string, and as a byte string otherwise.
11    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
56/// Converts a bit-representation of a float of type `ty` to a constant literal
57fn bits_and_type_to_float_constant_literal(bits: u128, ty: FloatTy) -> ConstantLiteral {
58    use rustc_apfloat::{Float, ieee};
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
80/// Whether a `DefId` is a `AnonConst`. An anonymous constant is
81/// generated by Rustc, hoisting every constat bits from items as
82/// separate top-level items. This AnonConst mechanism is internal to
83/// Rustc; we don't want to reflect that, instead we prefer inlining
84/// those. `is_anon_const` is used to detect such AnonConst so that we
85/// can evaluate and inline them.
86pub(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
96/// Attempts to translate a `ty::UnevaluatedConst` into a constant expression. This handles cases
97/// of references to top-level or associated constants. Returns `None` if the input was not a named
98/// constant.
99pub 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        && (assoc.trait_item_def_id.is_some() || assoc.container == ty::AssocItemContainer::Trait)
115    {
116        // This is an associated constant in a trait.
117        let name = assoc.name().to_string();
118        let impl_expr = self_clause_for_item(s, ucv.def, ucv.args).unwrap();
119        ConstantExprKind::TraitConst { impl_expr, name }
120    } else {
121        let item = translate_item_ref(s, ucv.def, ucv.args);
122        ConstantExprKind::GlobalName(item)
123    };
124    let cv = kind.decorate(ty.sinto(s), span.sinto(s));
125    Some(cv)
126}
127
128/// Evaluate a `ty::Const`.
129pub fn eval_ty_constant<'tcx, S: UnderOwnerState<'tcx>>(
130    s: &S,
131    c: ty::Const<'tcx>,
132) -> Option<ty::Const<'tcx>> {
133    let tcx = s.base().tcx;
134    let evaluated = tcx.try_normalize_erasing_regions(s.typing_env(), c).ok()?;
135    (evaluated != c).then_some(evaluated)
136}
137
138/// Evaluate a `mir::Const`.
139pub fn eval_mir_constant<'tcx, S: UnderOwnerState<'tcx>>(
140    s: &S,
141    c: mir::Const<'tcx>,
142) -> Option<mir::Const<'tcx>> {
143    let evaluated = c
144        .eval(s.base().tcx, s.typing_env(), rustc_span::DUMMY_SP)
145        .ok()?;
146    let evaluated = mir::Const::Val(evaluated, c.ty());
147    (evaluated != c).then_some(evaluated)
148}
149
150impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, ConstantExpr> for ty::Const<'tcx> {
151    #[tracing::instrument(level = "trace", skip(s))]
152    fn sinto(&self, s: &S) -> ConstantExpr {
153        use rustc_middle::query::Key;
154        let span = self.default_span(s.base().tcx);
155        match self.kind() {
156            ty::ConstKind::Param(p) => {
157                let ty = p.find_const_ty_from_env(s.param_env());
158                let kind = ConstantExprKind::ConstRef { id: p.sinto(s) };
159                kind.decorate(ty.sinto(s), span.sinto(s))
160            }
161            ty::ConstKind::Infer(..) => {
162                fatal!(s[span], "ty::ConstKind::Infer node? {:#?}", self)
163            }
164
165            ty::ConstKind::Unevaluated(ucv) => match translate_constant_reference(s, span, ucv) {
166                Some(val) => val,
167                None => match eval_ty_constant(s, *self) {
168                    Some(val) => val.sinto(s),
169                    // TODO: This is triggered when compiling using `generic_const_exprs`
170                    None => supposely_unreachable_fatal!(s, "TranslateUneval"; {self, ucv}),
171                },
172            },
173
174            ty::ConstKind::Value(val) => valtree_to_constant_expr(s, val.valtree, val.ty, span),
175            ty::ConstKind::Error(_) => fatal!(s[span], "ty::ConstKind::Error"),
176            ty::ConstKind::Expr(e) => fatal!(s[span], "ty::ConstKind::Expr {:#?}", e),
177
178            ty::ConstKind::Bound(i, bound) => {
179                supposely_unreachable_fatal!(s[span], "ty::ConstKind::Bound"; {i, bound})
180            }
181            _ => fatal!(s[span], "unexpected case"),
182        }
183    }
184}
185
186#[tracing::instrument(level = "trace", skip(s))]
187pub(crate) fn valtree_to_constant_expr<'tcx, S: UnderOwnerState<'tcx>>(
188    s: &S,
189    valtree: rustc_middle::ty::ValTree<'tcx>,
190    ty: rustc_middle::ty::Ty<'tcx>,
191    span: rustc_span::Span,
192) -> ConstantExpr {
193    let kind = match (&*valtree, ty.kind()) {
194        (_, ty::Ref(_, inner_ty, _)) => {
195            ConstantExprKind::Borrow(valtree_to_constant_expr(s, valtree, *inner_ty, span))
196        }
197        (ty::ValTreeKind::Branch(valtrees), ty::Str) => {
198            let bytes = valtrees
199                .iter()
200                .map(|x| match &***x {
201                    ty::ValTreeKind::Leaf(leaf) => leaf.to_u8(),
202                    _ => fatal!(
203                        s[span],
204                        "Expected a flat list of leaves while translating \
205                            a str literal, got a arbitrary valtree."
206                    ),
207                })
208                .collect();
209            ConstantExprKind::Literal(ConstantLiteral::byte_str(bytes))
210        }
211        (ty::ValTreeKind::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => {
212            let contents: rustc_middle::ty::DestructuredConst = s
213                .base()
214                .tcx
215                .destructure_const(ty::Const::new_value(s.base().tcx, valtree, ty));
216            let fields = contents.fields.iter().copied();
217            match ty.kind() {
218                ty::Array(_, _) => ConstantExprKind::Array {
219                    fields: fields.map(|field| field.sinto(s)).collect(),
220                },
221                ty::Tuple(_) => ConstantExprKind::Tuple {
222                    fields: fields.map(|field| field.sinto(s)).collect(),
223                },
224                ty::Adt(def, _) => {
225                    let variant_idx = contents
226                        .variant
227                        .s_expect(s, "destructed const of adt without variant idx");
228                    let variant_def = &def.variant(variant_idx);
229
230                    ConstantExprKind::Adt {
231                        info: get_variant_information(def, variant_idx, s),
232                        fields: fields
233                            .into_iter()
234                            .zip(&variant_def.fields)
235                            .map(|(value, field)| ConstantFieldExpr {
236                                field: field.did.sinto(s),
237                                value: value.sinto(s),
238                            })
239                            .collect(),
240                    }
241                }
242                _ => unreachable!(),
243            }
244        }
245        (ty::ValTreeKind::Leaf(x), ty::RawPtr(_, _)) => {
246            use crate::rustc_type_ir::inherent::Ty;
247            let raw_address = x.to_bits_unchecked();
248            let uint_ty = UintTy::Usize;
249            let usize_ty = rustc_middle::ty::Ty::new_usize(s.base().tcx).sinto(s);
250            let lit = ConstantLiteral::Int(ConstantInt::Uint(raw_address, uint_ty));
251            ConstantExprKind::Cast {
252                source: ConstantExprKind::Literal(lit).decorate(usize_ty, span.sinto(s)),
253            }
254        }
255        (ty::ValTreeKind::Leaf(x), _) => {
256            ConstantExprKind::Literal(scalar_int_to_constant_literal(s, *x, ty))
257        }
258        _ => supposely_unreachable_fatal!(
259            s[span], "valtree_to_expr";
260            {valtree, ty}
261        ),
262    };
263    kind.decorate(ty.sinto(s), span.sinto(s))
264}
265
266/// Use the const-eval interpreter to convert an evaluated operand back to a structured
267/// constant expression.
268fn op_to_const<'tcx, S: UnderOwnerState<'tcx>>(
269    s: &S,
270    span: rustc_span::Span,
271    ecx: &rustc_const_eval::const_eval::CompileTimeInterpCx<'tcx>,
272    op: rustc_const_eval::interpret::OpTy<'tcx>,
273) -> InterpResult<'tcx, ConstantExpr> {
274    use crate::rustc_const_eval::interpret::Projectable;
275    // Code inspired from `try_destructure_mir_constant_for_user_output` and
276    // `const_eval::eval_queries::op_to_const`.
277    let tcx = s.base().tcx;
278    let ty = op.layout.ty;
279    // Helper for struct-likes.
280    let read_fields = |of: rustc_const_eval::interpret::OpTy<'tcx>, field_count| {
281        (0..field_count).map(move |i| {
282            let field_op = ecx.project_field(&of, rustc_abi::FieldIdx::from_usize(i))?;
283            op_to_const(s, span, &ecx, field_op)
284        })
285    };
286    let kind = match ty.kind() {
287        // Detect statics
288        _ if let Some(place) = op.as_mplace_or_imm().left()
289            && let ptr = place.ptr()
290            && let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr, 0)?
291            && let interpret::GlobalAlloc::Static(did) = tcx.global_alloc(alloc_id) =>
292        {
293            let item = translate_item_ref(s, did, ty::GenericArgsRef::default());
294            ConstantExprKind::GlobalName(item)
295        }
296        ty::Char | ty::Bool | ty::Uint(_) | ty::Int(_) | ty::Float(_) => {
297            let scalar = ecx.read_scalar(&op)?;
298            let scalar_int = scalar.try_to_scalar_int().unwrap();
299            let lit = scalar_int_to_constant_literal(s, scalar_int, ty);
300            ConstantExprKind::Literal(lit)
301        }
302        ty::Adt(adt_def, ..) if adt_def.is_union() => {
303            ConstantExprKind::Todo("Cannot translate constant of union type".into())
304        }
305        ty::Adt(adt_def, ..) => {
306            let variant = ecx.read_discriminant(&op)?;
307            let down = ecx.project_downcast(&op, variant)?;
308            let field_count = adt_def.variants()[variant].fields.len();
309            let fields = read_fields(down, field_count)
310                .zip(&adt_def.variant(variant).fields)
311                .map(|(value, field)| {
312                    interp_ok(ConstantFieldExpr {
313                        field: field.did.sinto(s),
314                        value: value?,
315                    })
316                })
317                .collect::<InterpResult<Vec<_>>>()?;
318            let variants_info = get_variant_information(adt_def, variant, s);
319            ConstantExprKind::Adt {
320                info: variants_info,
321                fields,
322            }
323        }
324        ty::Closure(def_id, args) => {
325            // A closure is essentially an adt with funky generics and some builtin impls.
326            let def_id: DefId = def_id.sinto(s);
327            let field_count = args.as_closure().upvar_tys().len();
328            let fields = read_fields(op, field_count)
329                .map(|value| {
330                    interp_ok(ConstantFieldExpr {
331                        // HACK: Closure fields don't have their own def_id, but Charon doesn't use
332                        // field DefIds so we put a dummy one.
333                        field: def_id.clone(),
334                        value: value?,
335                    })
336                })
337                .collect::<InterpResult<Vec<_>>>()?;
338            let variants_info = VariantInformations {
339                type_namespace: def_id.parent.clone().unwrap(),
340                typ: def_id.clone(),
341                variant: def_id,
342                kind: VariantKind::Struct { named: false },
343            };
344            ConstantExprKind::Adt {
345                info: variants_info,
346                fields,
347            }
348        }
349        ty::Tuple(args) => {
350            let fields = read_fields(op, args.len()).collect::<InterpResult<Vec<_>>>()?;
351            ConstantExprKind::Tuple { fields }
352        }
353        ty::Array(..) | ty::Slice(..) => {
354            let len = op.len(ecx)?;
355            let fields = (0..len)
356                .map(|i| {
357                    let op = ecx.project_index(&op, i)?;
358                    op_to_const(s, span, ecx, op)
359                })
360                .collect::<InterpResult<Vec<_>>>()?;
361            ConstantExprKind::Array { fields }
362        }
363        ty::Str => {
364            let str = ecx.read_str(&op.assert_mem_place())?;
365            ConstantExprKind::Literal(ConstantLiteral::Str(str.to_owned()))
366        }
367        ty::FnDef(def_id, args) => {
368            let item = translate_item_ref(s, *def_id, args);
369            ConstantExprKind::FnPtr(item)
370        }
371        ty::RawPtr(..) | ty::Ref(..) => {
372            let op = ecx.deref_pointer(&op)?;
373            let val = op_to_const(s, span, ecx, op.into())?;
374            match ty.kind() {
375                ty::Ref(..) => ConstantExprKind::Borrow(val),
376                ty::RawPtr(.., mutability) => ConstantExprKind::RawBorrow {
377                    arg: val,
378                    mutability: mutability.sinto(s),
379                },
380                _ => unreachable!(),
381            }
382        }
383        ty::FnPtr(..)
384        | ty::Dynamic(..)
385        | ty::Foreign(..)
386        | ty::Pat(..)
387        | ty::UnsafeBinder(..)
388        | ty::CoroutineClosure(..)
389        | ty::Coroutine(..)
390        | ty::CoroutineWitness(..) => ConstantExprKind::Todo("Unhandled constant type".into()),
391        ty::Alias(..) | ty::Param(..) | ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => {
392            fatal!(s[span], "Encountered evaluated constant of non-monomorphic type"; {op})
393        }
394        ty::Never | ty::Error(..) => {
395            fatal!(s[span], "Encountered evaluated constant of invalid type"; {ty})
396        }
397    };
398    let val = kind.decorate(ty.sinto(s), span.sinto(s));
399    interp_ok(val)
400}
401
402pub fn const_value_to_constant_expr<'tcx, S: UnderOwnerState<'tcx>>(
403    s: &S,
404    ty: rustc_middle::ty::Ty<'tcx>,
405    val: mir::ConstValue<'tcx>,
406    span: rustc_span::Span,
407) -> InterpResult<'tcx, ConstantExpr> {
408    let tcx = s.base().tcx;
409    let typing_env = s.typing_env();
410    let (ecx, op) =
411        rustc_const_eval::const_eval::mk_eval_cx_for_const_val(tcx.at(span), typing_env, val, ty)
412            .unwrap();
413    op_to_const(s, span, &ecx, op)
414}