charon_driver/translate/
translate_types.rs

1use super::translate_ctx::*;
2use charon_lib::ast::*;
3use charon_lib::common::hash_by_addr::HashByAddr;
4use charon_lib::ids::Vector;
5use core::convert::*;
6use hax::{HasParamEnv, Visibility};
7use itertools::Itertools;
8
9impl<'tcx, 'ctx> ItemTransCtx<'tcx, 'ctx> {
10    // Translate a region
11    pub(crate) fn translate_region(
12        &mut self,
13        span: Span,
14        region: &hax::Region,
15    ) -> Result<Region, Error> {
16        use hax::RegionKind::*;
17        match &region.kind {
18            ReErased => Ok(Region::Erased),
19            ReStatic => Ok(Region::Static),
20            ReBound(id, br) => {
21                let var = self.lookup_bound_region(span, *id, br.var)?;
22                Ok(Region::Var(var))
23            }
24            ReEarlyParam(region) => {
25                let var = self.lookup_early_region(span, region)?;
26                Ok(Region::Var(var))
27            }
28            ReVar(..) | RePlaceholder(..) => {
29                // Shouldn't exist outside of type inference.
30                raise_error!(
31                    self,
32                    span,
33                    "Should not exist outside of type inference: {region:?}"
34                )
35            }
36            ReLateParam(..) | ReError(..) => {
37                raise_error!(self, span, "Unexpected region kind: {region:?}")
38            }
39        }
40    }
41
42    pub(crate) fn translate_hax_int_ty(int_ty: &hax::IntTy) -> IntTy {
43        match int_ty {
44            hax::IntTy::Isize => IntTy::Isize,
45            hax::IntTy::I8 => IntTy::I8,
46            hax::IntTy::I16 => IntTy::I16,
47            hax::IntTy::I32 => IntTy::I32,
48            hax::IntTy::I64 => IntTy::I64,
49            hax::IntTy::I128 => IntTy::I128,
50        }
51    }
52
53    pub(crate) fn translate_hax_uint_ty(uint_ty: &hax::UintTy) -> UIntTy {
54        use hax::UintTy;
55        match uint_ty {
56            UintTy::Usize => UIntTy::Usize,
57            UintTy::U8 => UIntTy::U8,
58            UintTy::U16 => UIntTy::U16,
59            UintTy::U32 => UIntTy::U32,
60            UintTy::U64 => UIntTy::U64,
61            UintTy::U128 => UIntTy::U128,
62        }
63    }
64
65    /// Translate a Ty.
66    ///
67    /// Typically used in this module to translate the fields of a structure/
68    /// enumeration definition, or later to translate the type of a variable.
69    ///
70    /// Note that we take as parameter a function to translate regions, because
71    /// regions can be translated in several manners (non-erased region or erased
72    /// regions), in which case the return type is different.
73    #[tracing::instrument(skip(self, span))]
74    pub(crate) fn translate_ty(&mut self, span: Span, ty: &hax::Ty) -> Result<Ty, Error> {
75        let cache_key = HashByAddr(ty.inner().clone());
76        if let Some(ty) = self
77            .innermost_binder()
78            .type_trans_cache
79            .get(&cache_key)
80            .cloned()
81        {
82            return Ok(ty.clone());
83        }
84        // Catch the error to avoid a single error stopping the translation of a whole item.
85        let ty = self
86            .translate_ty_inner(span, ty)
87            .unwrap_or_else(|e| TyKind::Error(e.msg).into_ty());
88        self.innermost_binder_mut()
89            .type_trans_cache
90            .insert(cache_key, ty.clone());
91        Ok(ty)
92    }
93
94    fn translate_ty_inner(&mut self, span: Span, ty: &hax::Ty) -> Result<Ty, Error> {
95        trace!("{:?}", ty);
96        let kind = match ty.kind() {
97            hax::TyKind::Bool => TyKind::Literal(LiteralTy::Bool),
98            hax::TyKind::Char => TyKind::Literal(LiteralTy::Char),
99            hax::TyKind::Int(int_ty) => {
100                TyKind::Literal(LiteralTy::Int(Self::translate_hax_int_ty(int_ty)))
101            }
102            hax::TyKind::Uint(uint_ty) => {
103                TyKind::Literal(LiteralTy::UInt(Self::translate_hax_uint_ty(uint_ty)))
104            }
105            hax::TyKind::Float(float_ty) => {
106                use hax::FloatTy;
107                TyKind::Literal(LiteralTy::Float(match float_ty {
108                    FloatTy::F16 => types::FloatTy::F16,
109                    FloatTy::F32 => types::FloatTy::F32,
110                    FloatTy::F64 => types::FloatTy::F64,
111                    FloatTy::F128 => types::FloatTy::F128,
112                }))
113            }
114            hax::TyKind::Never => TyKind::Never,
115
116            hax::TyKind::Alias(alias) => match &alias.kind {
117                hax::AliasKind::Projection {
118                    impl_expr,
119                    assoc_item,
120                } => {
121                    let trait_ref = self.translate_trait_impl_expr(span, impl_expr)?;
122                    let name = self.t_ctx.translate_trait_item_name(&assoc_item.def_id)?;
123                    TyKind::TraitType(trait_ref, name)
124                }
125                hax::AliasKind::Opaque { hidden_ty, .. } => {
126                    return self.translate_ty(span, hidden_ty);
127                }
128                _ => {
129                    raise_error!(self, span, "Unsupported alias type: {:?}", alias.kind)
130                }
131            },
132
133            hax::TyKind::Adt(item) => {
134                let tref = self.translate_type_decl_ref(span, item)?;
135                TyKind::Adt(tref)
136            }
137            hax::TyKind::Str => {
138                let tref = TypeDeclRef::new(TypeId::Builtin(BuiltinTy::Str), GenericArgs::empty());
139                TyKind::Adt(tref)
140            }
141            hax::TyKind::Array(ty, const_param) => {
142                let c = self.translate_constant_expr_to_const_generic(span, const_param)?;
143                let ty = self.translate_ty(span, ty)?;
144                let tref = TypeDeclRef::new(
145                    TypeId::Builtin(BuiltinTy::Array),
146                    GenericArgs::new(Vector::new(), [ty].into(), [c].into(), Vector::new()),
147                );
148                TyKind::Adt(tref)
149            }
150            hax::TyKind::Slice(ty) => {
151                let ty = self.translate_ty(span, ty)?;
152                let tref = TypeDeclRef::new(
153                    TypeId::Builtin(BuiltinTy::Slice),
154                    GenericArgs::new_for_builtin([ty].into()),
155                );
156                TyKind::Adt(tref)
157            }
158            hax::TyKind::Ref(region, ty, mutability) => {
159                trace!("Ref");
160
161                let region = self.translate_region(span, region)?;
162                let ty = self.translate_ty(span, ty)?;
163                let kind = if *mutability {
164                    RefKind::Mut
165                } else {
166                    RefKind::Shared
167                };
168                TyKind::Ref(region, ty, kind)
169            }
170            hax::TyKind::RawPtr(ty, mutbl) => {
171                trace!("RawPtr: {:?}", (ty, mutbl));
172                let ty = self.translate_ty(span, ty)?;
173                let kind = if *mutbl {
174                    RefKind::Mut
175                } else {
176                    RefKind::Shared
177                };
178                TyKind::RawPtr(ty, kind)
179            }
180            hax::TyKind::Tuple(substs) => {
181                let mut params = Vector::new();
182                for param in substs.iter() {
183                    let param_ty = self.translate_ty(span, param)?;
184                    params.push(param_ty);
185                }
186                let tref = TypeDeclRef::new(TypeId::Tuple, GenericArgs::new_for_builtin(params));
187                TyKind::Adt(tref)
188            }
189
190            hax::TyKind::Param(param) => {
191                // A type parameter, for example `T` in `fn f<T>(x : T) {}`.
192                // Note that this type parameter may actually have been
193                // instantiated (in our environment, we may map it to another
194                // type): we just have to look it up.
195                // Note that if we are using this function to translate a field
196                // type in a type definition, it should actually map to a type
197                // parameter.
198                trace!("Param");
199
200                // Retrieve the translation of the substituted type:
201                let var = self.lookup_type_var(span, param)?;
202                TyKind::TypeVar(var)
203            }
204
205            hax::TyKind::Foreign(item) => {
206                let tref = self.translate_type_decl_ref(span, item)?;
207                TyKind::Adt(tref)
208            }
209
210            hax::TyKind::Arrow(sig) => {
211                trace!("Arrow");
212                trace!("bound vars: {:?}", sig.bound_vars);
213                let sig = self.translate_fun_sig(span, sig)?;
214                TyKind::FnPtr(sig)
215            }
216            hax::TyKind::FnDef { item, .. } => {
217                let fnref = self.translate_fn_ptr(span, item)?;
218                TyKind::FnDef(fnref)
219            }
220            hax::TyKind::Closure(args) => {
221                let tref = self.translate_closure_type_ref(span, args)?;
222                TyKind::Adt(tref)
223            }
224
225            hax::TyKind::Dynamic(self_ty, preds, region) => {
226                if self.monomorphize() {
227                    raise_error!(
228                        self,
229                        span,
230                        "`dyn Trait` is not yet supported with `--monomorphize`; \
231                        use `--monomorphize-conservative` instead"
232                    )
233                }
234                let pred = self.translate_existential_predicates(span, self_ty, preds, region)?;
235                if let hax::ClauseKind::Trait(trait_predicate) =
236                    preds.predicates[0].0.kind.hax_skip_binder_ref()
237                {
238                    // TODO(dyn): for now, we consider traits with associated types to not be dyn
239                    // compatible because we don't know how to handle them; for these we skip
240                    // translating the vtable.
241                    if self.trait_is_dyn_compatible(&trait_predicate.trait_ref.def_id)? {
242                        // Ensure the vtable type is translated. The first predicate is the one that
243                        // can have methods, i.e. a vtable.
244                        let _: TypeDeclId = self.register_item(
245                            span,
246                            &trait_predicate.trait_ref,
247                            TransItemSourceKind::VTable,
248                        );
249                    }
250                }
251                TyKind::DynTrait(pred)
252            }
253
254            hax::TyKind::Infer(_) => {
255                raise_error!(self, span, "Unsupported type: infer type")
256            }
257            hax::TyKind::Coroutine(..) => {
258                raise_error!(self, span, "Coroutine types are not supported yet")
259            }
260            hax::TyKind::Bound(_, _) => {
261                raise_error!(self, span, "Unexpected type kind: bound")
262            }
263            hax::TyKind::Placeholder(_) => {
264                raise_error!(self, span, "Unsupported type: placeholder")
265            }
266
267            hax::TyKind::Error => {
268                raise_error!(self, span, "Type checking error")
269            }
270            hax::TyKind::Todo(s) => {
271                raise_error!(self, span, "Unsupported type: {:?}", s)
272            }
273        };
274        Ok(kind.into_ty())
275    }
276
277    pub fn translate_fun_sig(
278        &mut self,
279        span: Span,
280        sig: &hax::Binder<hax::TyFnSig>,
281    ) -> Result<RegionBinder<(Vec<Ty>, Ty)>, Error> {
282        self.translate_region_binder(span, sig, |ctx, sig| {
283            let inputs = sig
284                .inputs
285                .iter()
286                .map(|x| ctx.translate_ty(span, x))
287                .try_collect()?;
288            let output = ctx.translate_ty(span, &sig.output)?;
289            Ok((inputs, output))
290        })
291    }
292
293    /// Translate generic args. Don't call directly; use `translate_xxx_ref` as much as possible.
294    pub fn translate_generic_args(
295        &mut self,
296        span: Span,
297        substs: &[hax::GenericArg],
298        trait_refs: &[hax::ImplExpr],
299    ) -> Result<GenericArgs, Error> {
300        use hax::GenericArg::*;
301        trace!("{:?}", substs);
302
303        let mut regions = Vector::new();
304        let mut types = Vector::new();
305        let mut const_generics = Vector::new();
306        for param in substs {
307            match param {
308                Type(param_ty) => {
309                    types.push(self.translate_ty(span, param_ty)?);
310                }
311                Lifetime(region) => {
312                    regions.push(self.translate_region(span, region)?);
313                }
314                Const(c) => {
315                    const_generics.push(self.translate_constant_expr_to_const_generic(span, c)?);
316                }
317            }
318        }
319        let trait_refs = self.translate_trait_impl_exprs(span, trait_refs)?;
320
321        Ok(GenericArgs {
322            regions,
323            types,
324            const_generics,
325            trait_refs,
326        })
327    }
328
329    /// Append the given late bound variables to the provided generics.
330    pub fn append_late_bound_to_generics(
331        &mut self,
332        span: Span,
333        generics: GenericArgs,
334        late_bound: Option<hax::Binder<()>>,
335    ) -> Result<RegionBinder<GenericArgs>, Error> {
336        let late_bound = late_bound.unwrap_or(hax::Binder {
337            value: (),
338            bound_vars: vec![],
339        });
340        self.translate_region_binder(span, &late_bound, |ctx, _| {
341            Ok(generics
342                .move_under_binder()
343                .concat(&ctx.innermost_binder().params.identity_args()))
344        })
345    }
346
347    /// Checks whether the given id corresponds to a built-in type.
348    pub(crate) fn recognize_builtin_type(
349        &mut self,
350        item: &hax::ItemRef,
351    ) -> Result<Option<BuiltinTy>, Error> {
352        let def = self.hax_def(item)?;
353        let ty = if def.lang_item.as_deref() == Some("owned_box") && !self.t_ctx.options.raw_boxes {
354            Some(BuiltinTy::Box)
355        } else {
356            None
357        };
358        Ok(ty)
359    }
360
361    /// Translate a Dynamically Sized Type metadata kind.
362    ///
363    /// Returns `None` if the type is generic, or if it is not a DST.
364    pub fn translate_ptr_metadata(&self, item: &hax::ItemRef) -> Option<PtrMetadata> {
365        // prepare the call to the method
366        use rustc_middle::ty;
367        let tcx = self.t_ctx.tcx;
368        let rdefid = item.def_id.as_rust_def_id().unwrap();
369        let hax_state = &self.hax_state_with_id();
370        let ty_env = hax_state.typing_env();
371        let ty = tcx
372            .type_of(rdefid)
373            .instantiate(tcx, item.rustc_args(hax_state));
374
375        // call the key method
376        match tcx
377            .struct_tail_raw(
378                ty,
379                |ty| tcx.try_normalize_erasing_regions(ty_env, ty).unwrap_or(ty),
380                || {},
381            )
382            .kind()
383        {
384            ty::Foreign(..) => Some(PtrMetadata::None),
385            ty::Str | ty::Slice(..) => Some(PtrMetadata::Length),
386            ty::Dynamic(..) => Some(PtrMetadata::VTable(VTable)),
387            // This is NOT accurate -- if there is no generic clause that states `?Sized`
388            // Then it will be safe to return `Some(PtrMetadata::None)`.
389            // TODO: inquire the generic clause to get the accurate info.
390            ty::Placeholder(..) | ty::Infer(..) | ty::Param(..) | ty::Bound(..) => None,
391            _ => Some(PtrMetadata::None),
392        }
393    }
394
395    /// Translate a type layout.
396    ///
397    /// Translates the layout as queried from rustc into
398    /// the more restricted [`Layout`].
399    #[tracing::instrument(skip(self))]
400    pub fn translate_layout(&self, item: &hax::ItemRef) -> Option<Layout> {
401        use rustc_abi as r_abi;
402        // Panics if the fields layout is not `Arbitrary`.
403        fn translate_variant_layout(
404            variant_layout: &r_abi::LayoutData<r_abi::FieldIdx, r_abi::VariantIdx>,
405            tag: Option<ScalarValue>,
406        ) -> VariantLayout {
407            match &variant_layout.fields {
408                r_abi::FieldsShape::Arbitrary { offsets, .. } => {
409                    let mut v = Vector::with_capacity(offsets.len());
410                    for o in offsets.iter() {
411                        v.push(o.bytes());
412                    }
413                    VariantLayout {
414                        field_offsets: v,
415                        uninhabited: variant_layout.is_uninhabited(),
416                        tag,
417                    }
418                }
419                r_abi::FieldsShape::Primitive
420                | r_abi::FieldsShape::Union(_)
421                | r_abi::FieldsShape::Array { .. } => panic!("Unexpected layout shape"),
422            }
423        }
424
425        fn translate_primitive_int(int_ty: r_abi::Integer, signed: bool) -> IntegerTy {
426            if signed {
427                IntegerTy::Signed(match int_ty {
428                    r_abi::Integer::I8 => IntTy::I8,
429                    r_abi::Integer::I16 => IntTy::I16,
430                    r_abi::Integer::I32 => IntTy::I32,
431                    r_abi::Integer::I64 => IntTy::I64,
432                    r_abi::Integer::I128 => IntTy::I128,
433                })
434            } else {
435                IntegerTy::Unsigned(match int_ty {
436                    r_abi::Integer::I8 => UIntTy::U8,
437                    r_abi::Integer::I16 => UIntTy::U16,
438                    r_abi::Integer::I32 => UIntTy::U32,
439                    r_abi::Integer::I64 => UIntTy::U64,
440                    r_abi::Integer::I128 => UIntTy::U128,
441                })
442            }
443        }
444
445        let tcx = self.t_ctx.tcx;
446        let rdefid = item.def_id.as_rust_def_id().unwrap();
447        let hax_state = &self.hax_state_with_id();
448        let ty_env = hax_state.typing_env();
449        let ty = tcx
450            .type_of(rdefid)
451            .instantiate(tcx, item.rustc_args(hax_state));
452        let pseudo_input = ty_env.as_query_input(ty);
453
454        // If layout computation returns an error, we return `None`.
455        let layout = tcx.layout_of(pseudo_input).ok()?.layout;
456        let (size, align) = if layout.is_sized() {
457            (
458                Some(layout.size().bytes()),
459                Some(layout.align().abi.bytes()),
460            )
461        } else {
462            (None, None)
463        };
464
465        // Get the layout of the discriminant when there is one (even if it is encoded in a niche).
466        let discriminant_layout = match layout.variants() {
467            r_abi::Variants::Multiple {
468                tag,
469                tag_encoding,
470                tag_field,
471                ..
472            } => {
473                // The tag_field is the index into the `offsets` vector.
474                let r_abi::FieldsShape::Arbitrary { offsets, .. } = layout.fields() else {
475                    unreachable!()
476                };
477
478                let tag_ty = match tag.primitive() {
479                    r_abi::Primitive::Int(int_ty, signed) => {
480                        translate_primitive_int(int_ty, signed)
481                    }
482                    // Try to handle pointer as integers of the same size.
483                    r_abi::Primitive::Pointer(_) => IntegerTy::Signed(IntTy::Isize),
484                    r_abi::Primitive::Float(_) => {
485                        unreachable!()
486                    }
487                };
488
489                let encoding = match tag_encoding {
490                    r_abi::TagEncoding::Direct => TagEncoding::Direct,
491                    r_abi::TagEncoding::Niche {
492                        untagged_variant, ..
493                    } => TagEncoding::Niche {
494                        untagged_variant: VariantId::from_usize(r_abi::VariantIdx::as_usize(
495                            *untagged_variant,
496                        )),
497                    },
498                };
499                offsets.get(*tag_field).map(|s| DiscriminantLayout {
500                    offset: r_abi::Size::bytes(*s),
501                    tag_ty,
502                    encoding,
503                })
504            }
505            r_abi::Variants::Single { .. } | r_abi::Variants::Empty => None,
506        };
507
508        let mut variant_layouts = Vector::new();
509        match layout.variants() {
510            r_abi::Variants::Multiple { variants, .. } => {
511                let tag_ty = discriminant_layout
512                    .as_ref()
513                    .expect("No discriminant layout for enum?")
514                    .tag_ty;
515                let ptr_size = self.t_ctx.translated.target_information.target_pointer_size;
516                let tag_size = r_abi::Size::from_bytes(tag_ty.target_size(ptr_size));
517
518                for (id, variant_layout) in variants.iter_enumerated() {
519                    let tag = if variant_layout.is_uninhabited() {
520                        None
521                    } else {
522                        tcx.tag_for_variant(ty_env.as_query_input((ty, id)))
523                            .map(|s| match tag_ty {
524                                IntegerTy::Signed(int_ty) => {
525                                    ScalarValue::from_int(ptr_size, int_ty, s.to_int(tag_size))
526                                        .unwrap()
527                                }
528                                IntegerTy::Unsigned(uint_ty) => {
529                                    ScalarValue::from_uint(ptr_size, uint_ty, s.to_uint(tag_size))
530                                        .unwrap()
531                                }
532                            })
533                    };
534                    variant_layouts.push(translate_variant_layout(variant_layout, tag));
535                }
536            }
537            r_abi::Variants::Single { index } => {
538                assert!(*index == r_abi::VariantIdx::ZERO);
539                // For structs we add a single variant that has the field offsets. Unions don't
540                // have field offsets.
541                if let r_abi::FieldsShape::Arbitrary { .. } = layout.fields() {
542                    variant_layouts.push(translate_variant_layout(&layout, None));
543                }
544            }
545            r_abi::Variants::Empty => {}
546        }
547
548        Some(Layout {
549            size,
550            align,
551            discriminant_layout,
552            uninhabited: layout.is_uninhabited(),
553            variant_layouts,
554        })
555    }
556
557    /// Generate a naive layout for this type.
558    pub fn generate_naive_layout(&self, span: Span, ty: &TypeDeclKind) -> Result<Layout, Error> {
559        match ty {
560            TypeDeclKind::Struct(fields) => {
561                let mut size = 0;
562                let mut align = 0;
563                let ptr_size = self.t_ctx.translated.target_information.target_pointer_size;
564                let field_offsets = fields.map_ref(|field| {
565                    let offset = size;
566                    let size_of_ty = match field.ty.kind() {
567                        TyKind::Literal(literal_ty) => literal_ty.target_size(ptr_size) as u64,
568                        // This is a lie, the pointers could be fat...
569                        TyKind::Ref(..) | TyKind::RawPtr(..) | TyKind::FnPtr(..) => ptr_size,
570                        _ => panic!("Unsupported type for `generate_naive_layout`: {ty:?}"),
571                    };
572                    size += size_of_ty;
573                    // For these types, align == size is good enough.
574                    align = std::cmp::max(align, size);
575                    offset
576                });
577
578                Ok(Layout {
579                    size: Some(size),
580                    align: Some(align),
581                    discriminant_layout: None,
582                    uninhabited: false,
583                    variant_layouts: [VariantLayout {
584                        field_offsets,
585                        tag: None,
586                        uninhabited: false,
587                    }]
588                    .into(),
589                })
590            }
591            _ => raise_error!(
592                self,
593                span,
594                "`generate_naive_layout` only supports structs at the moment"
595            ),
596        }
597    }
598
599    /// Translate the body of a type declaration.
600    ///
601    /// Note that the type may be external, in which case we translate the body
602    /// only if it is public (i.e., it is a public enumeration, or it is a
603    /// struct with only public fields).
604    pub(crate) fn translate_adt_def(
605        &mut self,
606        trans_id: TypeDeclId,
607        def_span: Span,
608        item_meta: &ItemMeta,
609        def: &hax::FullDef,
610    ) -> Result<TypeDeclKind, Error> {
611        use hax::AdtKind;
612        let hax::FullDefKind::Adt {
613            adt_kind, variants, ..
614        } = def.kind()
615        else {
616            unreachable!()
617        };
618
619        if item_meta.opacity.is_opaque() {
620            return Ok(TypeDeclKind::Opaque);
621        }
622
623        trace!("{}", trans_id);
624
625        // In case the type is external, check if we should consider the type as
626        // transparent (i.e., extract its body). If it is an enumeration, then yes
627        // (because the variants of public enumerations are public, together with their
628        // fields). If it is a structure, we check if all the fields are public.
629        let contents_are_public = match adt_kind {
630            AdtKind::Enum => true,
631            AdtKind::Struct | AdtKind::Union => {
632                // Check the unique variant
633                error_assert!(self, def_span, variants.len() == 1);
634                variants[0]
635                    .fields
636                    .iter()
637                    .all(|f| matches!(f.vis, Visibility::Public))
638            }
639        };
640
641        if item_meta
642            .opacity
643            .with_content_visibility(contents_are_public)
644            .is_opaque()
645        {
646            return Ok(TypeDeclKind::Opaque);
647        }
648
649        // The type is transparent: explore the variants
650        let mut translated_variants: Vector<VariantId, Variant> = Default::default();
651        for (i, var_def) in variants.iter().enumerate() {
652            trace!("variant {i}: {var_def:?}");
653
654            let mut fields: Vector<FieldId, Field> = Default::default();
655            /* This is for sanity: check that either all the fields have names, or
656             * none of them has */
657            let mut have_names: Option<bool> = None;
658            for (j, field_def) in var_def.fields.iter().enumerate() {
659                trace!("variant {i}: field {j}: {field_def:?}");
660                let field_span = self.t_ctx.translate_span_from_hax(&field_def.span);
661                // Translate the field type
662                let ty = self.translate_ty(field_span, &field_def.ty)?;
663                let field_full_def =
664                    self.hax_def(&def.this().with_def_id(self.hax_state(), &field_def.did))?;
665                let field_attrs = self.t_ctx.translate_attr_info(&field_full_def);
666
667                // Retrieve the field name.
668                let field_name = field_def.name.clone();
669                // Sanity check
670                match &have_names {
671                    None => {
672                        have_names = match &field_name {
673                            None => Some(false),
674                            Some(_) => Some(true),
675                        }
676                    }
677                    Some(b) => {
678                        error_assert!(self, field_span, *b == field_name.is_some());
679                    }
680                };
681
682                // Store the field
683                let field = Field {
684                    span: field_span,
685                    attr_info: field_attrs,
686                    name: field_name.clone(),
687                    ty,
688                };
689                fields.push(field);
690            }
691
692            let discriminant = self.translate_discriminant(def_span, &var_def.discr_val)?;
693            let variant_span = self.t_ctx.translate_span_from_hax(&var_def.span);
694            let variant_name = var_def.name.clone();
695            let variant_full_def =
696                self.hax_def(&def.this().with_def_id(self.hax_state(), &var_def.def_id))?;
697            let variant_attrs = self.t_ctx.translate_attr_info(&variant_full_def);
698
699            let mut variant = Variant {
700                span: variant_span,
701                attr_info: variant_attrs,
702                name: variant_name,
703                fields,
704                discriminant,
705            };
706            // Propagate a `#[charon::variants_prefix(..)]` or `#[charon::variants_suffix(..)]` attribute to the variants.
707            if variant.attr_info.rename.is_none() {
708                let prefix = item_meta
709                    .attr_info
710                    .attributes
711                    .iter()
712                    .filter_map(|a| a.as_variants_prefix())
713                    .next()
714                    .map(|attr| attr.as_str());
715                let suffix = item_meta
716                    .attr_info
717                    .attributes
718                    .iter()
719                    .filter_map(|a| a.as_variants_suffix())
720                    .next()
721                    .map(|attr| attr.as_str());
722                if prefix.is_some() || suffix.is_some() {
723                    let prefix = prefix.unwrap_or_default();
724                    let suffix = suffix.unwrap_or_default();
725                    let name = &variant.name;
726                    variant.attr_info.rename = Some(format!("{prefix}{name}{suffix}"));
727                }
728            }
729            translated_variants.push(variant);
730        }
731
732        // Register the type
733        let type_def_kind: TypeDeclKind = match adt_kind {
734            AdtKind::Struct => TypeDeclKind::Struct(translated_variants[0].fields.clone()),
735            AdtKind::Enum => TypeDeclKind::Enum(translated_variants),
736            AdtKind::Union => TypeDeclKind::Union(translated_variants[0].fields.clone()),
737        };
738
739        Ok(type_def_kind)
740    }
741
742    fn translate_discriminant(
743        &mut self,
744        def_span: Span,
745        discr: &hax::DiscriminantValue,
746    ) -> Result<ScalarValue, Error> {
747        let ty = self.translate_ty(def_span, &discr.ty)?;
748        let int_ty = ty.kind().as_literal().unwrap().to_integer_ty().unwrap();
749        Ok(ScalarValue::from_bits(int_ty, discr.val))
750    }
751}