Skip to main content

charon_driver/frontend/constant_utils/
uneval.rs

1//! Translate constants to the frontend: type-system constants, and the values read by `rustc_const_uneval`.
2use super::*;
3use annotate_snippets::Level;
4use rustc_const_uneval::{AllocTarget, Byte, ConstReader, PtrTarget, ReadError};
5use rustc_middle::ty;
6
7#[tracing::instrument(level = "trace", skip(s))]
8fn scalar_int_to_constant_literal<'tcx, S: UnderOwnerState<'tcx>>(
9    s: &S,
10    x: rustc_middle::ty::ScalarInt,
11    ty: rustc_middle::ty::Ty<'tcx>,
12) -> ConstantLiteral {
13    match ty.kind() {
14        ty::Char => ConstantLiteral::Char(
15            char::try_from(x).expect("scalar_int_to_constant_literal: expected a char"),
16        ),
17        ty::Bool => ConstantLiteral::Bool(
18            x.try_to_bool()
19                .expect("scalar_int_to_constant_literal: expected a bool"),
20        ),
21        ty::Int(kind) => {
22            let v = x.to_int(x.size());
23            ConstantLiteral::Int(ConstantInt::Int(v, kind.sinto(s)))
24        }
25        ty::Uint(kind) => {
26            let v = x.to_uint(x.size());
27            ConstantLiteral::Int(ConstantInt::Uint(v, kind.sinto(s)))
28        }
29        ty::Float(kind) => {
30            let v = x.to_bits_unchecked();
31            bits_and_type_to_float_constant_literal(v, kind.sinto(s))
32        }
33        _ => unreachable!("not a literal type: {ty:?}"),
34    }
35}
36
37/// Converts a bit-representation of a float of type `ty` to a constant literal
38fn bits_and_type_to_float_constant_literal(bits: u128, ty: FloatTy) -> ConstantLiteral {
39    use rustc_apfloat::{Float, ieee};
40    let string = match &ty {
41        FloatTy::F16 => ieee::Half::from_bits(bits).to_string(),
42        FloatTy::F32 => ieee::Single::from_bits(bits).to_string(),
43        FloatTy::F64 => ieee::Double::from_bits(bits).to_string(),
44        FloatTy::F128 => ieee::Quad::from_bits(bits).to_string(),
45    };
46    ConstantLiteral::Float(string, bits, ty)
47}
48
49impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, ConstantExpr<'tcx>> for ty::Const<'tcx> {
50    #[tracing::instrument(level = "trace", skip(s))]
51    fn sinto(&self, s: &S) -> ConstantExpr<'tcx> {
52        let tcx = s.base().tcx;
53        let span = rustc_span::DUMMY_SP;
54        match self.kind() {
55            ty::ConstKind::Param(p) => {
56                let ty = p.find_const_ty_from_env(s.param_env());
57                let kind = ConstantExprKind::ConstRef { id: p.sinto(s) };
58                ConstantExpr::new(kind, ty.sinto(s))
59            }
60            ty::ConstKind::Alias(_, ucv) => {
61                let def = match ucv.kind {
62                    ty::AliasConstKind::Projection { def_id: def }
63                    | ty::AliasConstKind::InherentImpl { def_id: def }
64                    | ty::AliasConstKind::Free { def_id: def }
65                    | ty::AliasConstKind::Anon { def_id: def } => def,
66                    ty::AliasConstKind::InherentSelf { .. } => {
67                        // Normalization replaces `InherentSelf` with its value
68                        let msg = format!("unnormalized constant: {self:?}");
69                        s.raise(Level::ERROR, span, msg.clone());
70                        let ty = Ty::new(s, TyKind::Error);
71                        return ConstantExpr::new(ConstantExprKind::Todo(msg), ty);
72                    }
73                };
74                let src = ConstSource::TyConst(ucv);
75                if s.base().options.inline_anon_consts
76                    // Rustc hoists inline `const {}` blocks and constant expressions into
77                    // separate `AnonConst` items. This is internal to rustc, so we prefer inlining
78                    // their value.
79                    && matches!(tcx.def_kind(def), rustc_hir::def::DefKind::AnonConst)
80                    && let Some(val) = read_const(s, tcx.def_span(def), src, ReadMode::Structured)
81                {
82                    val
83                } else {
84                    let item = translate_item_ref(s, def, ucv.args);
85                    let kind = ConstantExprKind::NamedGlobal(item);
86                    let ty = tcx.type_of(def).instantiate(tcx, ucv.args);
87                    let ty = normalize(tcx, s.typing_env(), ty);
88                    ConstantExpr::new(kind, ty.sinto(s))
89                }
90            }
91            ty::ConstKind::Value(val) => val.sinto(s),
92            _ => {
93                let msg = format!("unexpected constant kind: {self:?}");
94                s.raise(Level::ERROR, span, msg.clone());
95                let ty = Ty::new(s, TyKind::Error);
96                ConstantExpr::new(ConstantExprKind::Todo(msg), ty)
97            }
98        }
99    }
100}
101
102impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, ConstantExpr<'tcx>> for ty::Value<'tcx> {
103    #[tracing::instrument(level = "trace", skip(s))]
104    fn sinto(&self, s: &S) -> ConstantExpr<'tcx> {
105        let span = rustc_span::DUMMY_SP;
106        read_const(s, span, ConstSource::ValTree(*self), ReadMode::Structured).unwrap_or_else(
107            || {
108                ConstantExpr::new(
109                    ConstantExprKind::Todo("ConstValTree".into()),
110                    self.ty.sinto(s),
111                )
112            },
113        )
114    }
115}
116
117/// The reader for constants evaluated in the current context.
118fn const_reader<'tcx, S: UnderOwnerState<'tcx>>(s: &S) -> ConstReader<'tcx> {
119    ConstReader {
120        tcx: s.base().tcx,
121        typing_env: s.typing_env(),
122        config: s.base().options.consts,
123        state: s.with_global_cache(|cache| cache.const_reader_state.clone()),
124    }
125}
126
127/// The global standing for `self`.
128impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, ItemRef<'tcx>> for GlobalRef {
129    fn sinto(&self, s: &S) -> ItemRef<'tcx> {
130        match *self {
131            GlobalRef::Static(did) => translate_item_ref(s, did, Default::default()),
132            GlobalRef::Alloc(alloc_id) => {
133                let def_id = DefId::make_anon_alloc(s, alloc_id);
134                ItemRef::dummy_without_generics(s, def_id)
135            }
136        }
137    }
138}
139
140impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, FnPtrTarget<'tcx>>
141    for rustc_const_uneval::FnTarget<'tcx>
142{
143    fn sinto(&self, s: &S) -> FnPtrTarget<'tcx> {
144        use rustc_const_uneval::FnTarget;
145        match *self {
146            FnTarget::Instance(instance) => {
147                FnPtrTarget::Fn(translate_item_ref(s, instance.def_id(), instance.args))
148            }
149            FnTarget::ClosureAsFn(def_id, args) => {
150                FnPtrTarget::ClosureAsFn(ClosureTy::sfrom(s, def_id, args))
151            }
152        }
153    }
154}
155
156/// The metadata of a pointer to a value of type `from` unsized to type `to`.
157fn unsizing_metadata<'tcx, S: UnderOwnerState<'tcx>>(
158    s: &S,
159    from: ty::Ty<'tcx>,
160    to: ty::Ty<'tcx>,
161) -> UnsizingMetadata<'tcx> {
162    let from = ty::Ty::new_imm_ptr(s.base().tcx, from);
163    let to = ty::Ty::new_imm_ptr(s.base().tcx, to);
164    let (path, metadata) = compute_unsizing_metadata(s, from, to);
165    assert!(path.is_empty(), "Non-empty unsize path in const ptr");
166    metadata
167}
168
169/// The provenance to give to the bytes of a pointer into the given allocation.
170impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, ConstantByteProvenance<'tcx>> for AllocTarget<'tcx> {
171    fn sinto(&self, s: &S) -> ConstantByteProvenance<'tcx> {
172        match *self {
173            AllocTarget::Fn(target) => {
174                let fn_ptr_ty = target.fn_ptr_ty(s.base().tcx, s.typing_env());
175                ConstantByteProvenance::Function(target.sinto(s), fn_ptr_ty.sinto(s))
176            }
177            AllocTarget::Global(global) => ConstantByteProvenance::Global(global.sinto(s)),
178            AllocTarget::TypeId(ty) => ConstantByteProvenance::TypeId(ty.sinto(s)),
179            AllocTarget::VTable(ty, preds) => {
180                let tcx = s.base().tcx;
181                let dyn_ty = ty::Ty::new_dynamic(tcx, preds, tcx.lifetimes.re_erased);
182                match unsizing_metadata(s, ty, dyn_ty) {
183                    UnsizingMetadata::DirectVTable(proof) => ConstantByteProvenance::VTable(proof),
184                    metadata => unreachable!("unexpected vtable metadata {metadata:?}"),
185                }
186            }
187        }
188    }
189}
190
191impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, ConstantExpr<'tcx>>
192    for rustc_const_uneval::Const<'tcx>
193{
194    fn sinto(&self, s: &S) -> ConstantExpr<'tcx> {
195        use rustc_const_uneval::ConstKind;
196        // The value of a pattern type is described at its base type.
197        let ty = match self.ty.kind() {
198            ty::Pat(base_ty, _) => *base_ty,
199            _ => self.ty,
200        };
201        let unsizing_metadata = |unsize: &Option<rustc_const_uneval::Unsize<'tcx>>| {
202            unsize.map(|unsize| unsizing_metadata(s, unsize.from, unsize.to))
203        };
204        let kind = match &self.kind {
205            ConstKind::Scalar(scalar_int) => {
206                ConstantExprKind::Literal(scalar_int_to_constant_literal(s, *scalar_int, ty))
207            }
208            ConstKind::PtrNoProvenance(addr) => {
209                ConstantExprKind::Literal(ConstantLiteral::PtrNoProvenance(*addr))
210            }
211            ConstKind::Str(str) => ConstantExprKind::Literal(ConstantLiteral::Str(str.clone())),
212            ConstKind::ByteStr(bytes) => {
213                ConstantExprKind::Literal(ConstantLiteral::ByteStr(bytes.clone()))
214            }
215            ConstKind::Aggregate { variant, fields } => {
216                let fields = fields.iter().map(|field| field.sinto(s));
217                match ty.kind() {
218                    ty::Adt(adt_def, _) => {
219                        let variant = variant.unwrap();
220                        ConstantExprKind::Adt {
221                            kind: get_variant_kind(adt_def, variant, s),
222                            fields: fields
223                                .zip(&adt_def.variant(variant).fields)
224                                .map(|(value, field)| ConstantFieldExpr {
225                                    field: field.did.sinto(s),
226                                    value,
227                                })
228                                .collect(),
229                        }
230                    }
231                    ty::Closure(def_id, _) => {
232                        let def_id: DefId = def_id.sinto(s);
233                        ConstantExprKind::Adt {
234                            kind: VariantKind::Struct,
235                            fields: fields
236                                .map(|value| ConstantFieldExpr {
237                                    // HACK: Closure fields don't have their own def_id, but Charon
238                                    // doesn't use field DefIds so we put a dummy one.
239                                    field: def_id.clone(),
240                                    value,
241                                })
242                                .collect(),
243                        }
244                    }
245                    ty::Tuple(_) => ConstantExprKind::Tuple {
246                        fields: fields.collect(),
247                    },
248                    ty::Array(..) | ty::Slice(..) => ConstantExprKind::Array {
249                        fields: fields.collect(),
250                    },
251                    _ => unreachable!("unexpected aggregate type {ty:?}"),
252                }
253            }
254            ConstKind::Repeat { value, .. } => ConstantExprKind::Repeat {
255                value: value.sinto(s),
256            },
257            ConstKind::FnDef { def, args } => {
258                ConstantExprKind::FnDef(translate_item_ref(s, *def, *args))
259            }
260            ConstKind::FnPtr(target) => ConstantExprKind::FnPtr(target.sinto(s)),
261            ConstKind::Ptr { target, unsize } => {
262                let metadata = unsizing_metadata(unsize);
263                let (base, projections) = match target {
264                    PtrTarget::Global {
265                        target,
266                        ty,
267                        projections,
268                    } => {
269                        let prov = match *target {
270                            // We name the globals we point into, even the ones that we otherwise
271                            // inline.
272                            AllocTarget::Global(global) => {
273                                ConstantByteProvenance::Global(global.sinto(s))
274                            }
275                            _ => target.sinto(s),
276                        };
277                        let projections = projections
278                            .iter()
279                            .map(|(proj, ty)| {
280                                use rustc_const_uneval::Projection;
281                                let proj = match *proj {
282                                    Projection::Field(variant, field) => {
283                                        ConstantProjectionElem::Field(variant, field)
284                                    }
285                                    Projection::Index(i) => ConstantProjectionElem::Index(i),
286                                    Projection::Subslice { from, to } => {
287                                        ConstantProjectionElem::Subslice { from, to }
288                                    }
289                                    Projection::Offset {
290                                        count,
291                                        ty: elem_ty,
292                                        in_bounds,
293                                    } => ConstantProjectionElem::Offset {
294                                        count,
295                                        ty: elem_ty.sinto(s),
296                                        in_bounds,
297                                        pointee_is_sized: solve_sized(s, *ty),
298                                    },
299                                };
300                                (proj, ty.sinto(s))
301                            })
302                            .collect();
303                        (ConstantPtrBase::Global(prov, ty.sinto(s)), projections)
304                    }
305                    PtrTarget::Inline(val) => (ConstantPtrBase::Value(val.sinto(s)), vec![]),
306                };
307                ConstantExprKind::Ptr {
308                    base,
309                    projections,
310                    metadata,
311                }
312            }
313            ConstKind::PtrCast { ptr, unsize } => {
314                ConstantExprKind::PtrCast(ptr.sinto(s), unsizing_metadata(unsize))
315            }
316            ConstKind::Memory(bytes) => {
317                // The bytes of a pointer share their provenance; we convert it only once.
318                let mut last_prov: Option<(AllocTarget, ConstantByteProvenance)> = None;
319                let bytes = bytes.iter().map(|byte| match *byte {
320                    Byte::Uninit => ConstantByte::Uninit,
321                    Byte::Value(v) => ConstantByte::Value(v),
322                    Byte::Ptr(target, offset, i) => {
323                        if last_prov.as_ref().is_none_or(|(last, _)| *last != target) {
324                            last_prov = Some((target, target.sinto(s)));
325                        }
326                        let prov = last_prov.as_ref().unwrap().1.clone();
327                        ConstantByte::Provenance(prov, offset.bytes(), i)
328                    }
329                });
330                ConstantExprKind::Memory(bytes.collect())
331            }
332            ConstKind::TypeId(ty) => ConstantExprKind::TypeId(ty.sinto(s)),
333            ConstKind::Unsupported(msg) => ConstantExprKind::Todo(msg.to_string()),
334        };
335        ConstantExpr::new(kind, self.ty.sinto(s))
336    }
337}
338
339/// Evaluate `src` and read it back as a `ConstantExpr`.
340pub fn read_const<'tcx, S: UnderOwnerState<'tcx>>(
341    s: &S,
342    span: rustc_span::Span,
343    src: ConstSource<'tcx>,
344    mode: ReadMode,
345) -> Option<ConstantExpr<'tcx>> {
346    match const_reader(s).read(span, src, mode) {
347        Ok(val) => Some(val.sinto(s)),
348        Err(ReadError::NotEvaluable) => None,
349        Err(err) => {
350            s.raise(
351                Level::WARNING,
352                span,
353                format!("Couldn't convert constant {src:?} back to an expression: {err:?}"),
354            );
355            None
356        }
357    }
358}