charon_driver/translate/
translate_types.rs

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