Skip to main content

charon_driver/translate/
translate_types.rs

1use itertools::Itertools;
2use rustc_middle::ty;
3use rustc_trait_elaboration::{ItemId, erase_free_regions};
4
5use super::translate_ctx::*;
6use crate::frontend::{self as front, UnderOwnerState, Visibility};
7use charon_lib::ast::*;
8use charon_lib::ids::IndexVec;
9
10impl<'tcx, 'ctx> ItemTransCtx<'tcx, 'ctx> {
11    pub(crate) fn translate_sized_proof(
12        &mut self,
13        span: Span,
14        ty: ty::Ty<'tcx>,
15    ) -> Result<Option<TraitRef>, Error> {
16        if self.options.hide_marker_traits {
17            return Ok(None);
18        }
19        let proof = front::solve_sized(&self.frontend_state, ty);
20        self.translate_trait_proof(span, &proof)
21            .map(PolyTraitRef::no_bound_vars)
22            .map(Some)
23    }
24
25    /// Translate an erased region. If we're inside a body, this will return a fresh body region
26    /// instead.
27    pub(crate) fn translate_erased_region(&mut self) -> Region {
28        if let Some(v) = &mut self.lifetime_freshener {
29            Region::Body(v.push(()))
30        } else {
31            Region::Erased
32        }
33    }
34
35    /// Generate a list of erased arguments, or fresh body lifetimes if we're inside a body.
36    pub(crate) fn translate_erased_region_args(&mut self, len: usize) -> RegionArgs {
37        RegionArgs::new((0..len).map(|_| self.translate_erased_region()).collect())
38    }
39
40    /// Erase a region binder by supplying erased lifetimes (or fresh body lifetimes) for all its
41    /// arguments.
42    pub(crate) fn erase_region_binder<T: TyVisitable>(&mut self, b: RegionBinder<T>) -> T {
43        let args = self.translate_erased_region_args(b.regions.len());
44        b.apply(args)
45    }
46
47    // Translate a region
48    pub(crate) fn translate_region(
49        &mut self,
50        span: Span,
51        region: &ty::Region<'tcx>,
52    ) -> Result<Region, Error> {
53        match region.kind() {
54            ty::ReErased => Ok(self.translate_erased_region()),
55            ty::ReStatic => Ok(Region::Static),
56            ty::ReBound(ty::BoundVarIndexKind::Bound(id), br) => {
57                Ok(match self.lookup_bound_region(span, id, br.var) {
58                    Ok(var) => Region::Var(var),
59                    Err(_) => Region::Erased,
60                })
61            }
62            ty::ReEarlyParam(region) => Ok(match self.lookup_early_region(span, &region) {
63                Ok(var) => Region::Var(var),
64                Err(_) => Region::Erased,
65            }),
66            ty::ReLateParam(region) => {
67                Ok(Region::Var(self.lookup_late_param_region(span, &region)?))
68            }
69            ty::RePlaceholder(placeholder) => {
70                // We use placeholders to track some closure regions that rustc erases.
71                for (dbid, level) in self.binding_levels.iter_enumerated() {
72                    if let Some(&rid) = level.extra_early_region_vars.get(&placeholder) {
73                        return Ok(Region::Var(DeBruijnVar::bound(dbid, rid)));
74                    }
75                }
76                if let ty::BoundRegionKind::NamedForPrinting(name) = placeholder.bound.kind
77                    && name.to_string().starts_with("__charon_closure_region_")
78                {
79                    return Ok(self.translate_erased_region());
80                }
81                raise_error!(self, span, "Unexpected placeholder region: {region:?}")
82            }
83            ty::ReVar(..) => {
84                // Shouldn't exist outside of type inference.
85                raise_error!(
86                    self,
87                    span,
88                    "Should not exist outside of type inference: {region:?}"
89                )
90            }
91            ty::ReBound(..) | ty::ReError(..) => {
92                raise_error!(self, span, "Unexpected region kind: {region:?}")
93            }
94        }
95    }
96
97    pub(crate) fn translate_frontend_int_ty(int_ty: &front::IntTy) -> IntTy {
98        match int_ty {
99            front::IntTy::Isize => IntTy::Isize,
100            front::IntTy::I8 => IntTy::I8,
101            front::IntTy::I16 => IntTy::I16,
102            front::IntTy::I32 => IntTy::I32,
103            front::IntTy::I64 => IntTy::I64,
104            front::IntTy::I128 => IntTy::I128,
105        }
106    }
107
108    pub(crate) fn translate_frontend_uint_ty(uint_ty: &front::UintTy) -> UIntTy {
109        use crate::frontend::UintTy;
110        match uint_ty {
111            UintTy::Usize => UIntTy::Usize,
112            UintTy::U8 => UIntTy::U8,
113            UintTy::U16 => UIntTy::U16,
114            UintTy::U32 => UIntTy::U32,
115            UintTy::U64 => UIntTy::U64,
116            UintTy::U128 => UIntTy::U128,
117        }
118    }
119
120    /// Translate a Ty.
121    ///
122    /// Typically used in this module to translate the fields of a structure/
123    /// enumeration definition, or later to translate the type of a variable.
124    ///
125    /// Note that we take as parameter a function to translate regions, because
126    /// regions can be translated in several manners (non-erased region or erased
127    /// regions), in which case the return type is different.
128    #[tracing::instrument(skip(self, span))]
129    pub(crate) fn translate_ty(
130        &mut self,
131        span: Span,
132        frontend_ty: &front::Ty<'tcx>,
133    ) -> Result<Ty, Error> {
134        let mut ty = if let Some(ty) = self
135            .innermost_binder()
136            .type_trans_cache
137            .get(frontend_ty)
138            .cloned()
139        {
140            ty
141        } else {
142            let ty = self
143                .translate_ty_inner(span, frontend_ty)
144                .unwrap_or_else(|e| TyKind::Error(e.msg).into_ty());
145            self.innermost_binder_mut().type_trans_cache.insert(
146                frontend_ty.clone(),
147                ty.clone().replace_erased_regions(|| Region::Erased),
148            );
149            ty
150        };
151        if let Some(v) = &mut self.lifetime_freshener {
152            // We might be reusing a value from cache: we must refresh the erased & body regions.
153            ty = ty.replace_erased_regions(|| Region::Body(v.push(())));
154        }
155        if self.options.collect_instantiated_layouts && !self.recording_mono_layouts {
156            // Avoid cycles from recursing into all mentioned types
157            self.recording_mono_layouts = true;
158            // Drop the lifetime freshener, so regions are erased and can be used as keys.
159            let lifetime_freshener = self.lifetime_freshener.take();
160            self.record_monomorphic_layout(span, frontend_ty, &ty);
161            self.lifetime_freshener = lifetime_freshener;
162            self.recording_mono_layouts = false;
163        }
164        Ok(ty)
165    }
166
167    fn translate_ty_inner(&mut self, span: Span, ty: &front::Ty<'tcx>) -> Result<Ty, Error> {
168        trace!("{:?}", ty);
169        let kind = match ty.kind() {
170            front::TyKind::Bool => TyKind::Scalar(ScalarTy::Bool),
171            front::TyKind::Char => TyKind::Scalar(ScalarTy::Char),
172            front::TyKind::Int(int_ty) => TyKind::Scalar(ScalarTy::Integer(IntegerTy::Signed(
173                Self::translate_frontend_int_ty(int_ty),
174            ))),
175            front::TyKind::Uint(uint_ty) => TyKind::Scalar(ScalarTy::Integer(IntegerTy::Unsigned(
176                Self::translate_frontend_uint_ty(uint_ty),
177            ))),
178            front::TyKind::Float(float_ty) => TyKind::Scalar(ScalarTy::Float(match float_ty {
179                front::FloatTy::F16 => FloatTy::F16,
180                front::FloatTy::F32 => FloatTy::F32,
181                front::FloatTy::F64 => FloatTy::F64,
182                front::FloatTy::F128 => FloatTy::F128,
183            })),
184            front::TyKind::Never => TyKind::Never,
185
186            front::TyKind::Alias(alias) => match &alias.kind {
187                front::AliasKind::Projection(item) => {
188                    let trait_ref = self
189                        .translate_trait_proof(
190                            span,
191                            item.in_trait
192                                .as_ref()
193                                .expect("projection without a trait_ref?"),
194                        )?
195                        .erase();
196                    let assoc_type_id =
197                        self.translate_assoc_type_id(trait_ref.trait_id(), &item.def_id)?;
198                    let generics = self.translate_generic_args(span, item)?;
199                    TyKind::TraitType(trait_ref, assoc_type_id, generics)
200                }
201                front::AliasKind::Opaque { hidden_ty, .. } => {
202                    return self.translate_ty(span, hidden_ty);
203                }
204                _ => {
205                    raise_error!(self, span, "Unsupported alias type: {:?}", alias.kind)
206                }
207            },
208
209            front::TyKind::Adt(adt) => {
210                let tref = self.translate_type_decl_ref(span, &adt.item)?;
211                TyKind::Adt(tref)
212            }
213            front::TyKind::Str(str_ty) => {
214                let tref = self.translate_type_decl_ref(span, &str_ty.item)?;
215                TyKind::Adt(tref)
216            }
217            front::TyKind::Array(array) => {
218                let item_ref = &array.item;
219                let item_ty_is_sized = if let Some(proof) = array.element_sized_proof() {
220                    Some(self.translate_trait_proof(span, proof)?.no_bound_vars())
221                } else {
222                    None
223                };
224                let mut args = self.translate_generic_args_without_trait_refs(span, item_ref)?;
225                assert!(args.types.len() == 1 && args.const_generics.len() == 1);
226                TyKind::Array(
227                    args.types.pop().unwrap(),
228                    args.const_generics.pop().unwrap(),
229                    item_ty_is_sized,
230                )
231            }
232            front::TyKind::Pat(pattern) => {
233                let ty = self.translate_ty(span, &pattern.ty)?;
234                let pat = self.translate_pattern(span, &pattern.pat)?;
235                TyKind::Pattern(ty, pat)
236            }
237            front::TyKind::Slice(slice) => {
238                let item_ref = &slice.item;
239                let item_ty_is_sized = if let Some(proof) = slice.element_sized_proof() {
240                    Some(self.translate_trait_proof(span, proof)?.no_bound_vars())
241                } else {
242                    None
243                };
244                let mut args = self.translate_generic_args_without_trait_refs(span, item_ref)?;
245                assert!(args.types.len() == 1);
246                TyKind::Slice(args.types.pop().unwrap(), item_ty_is_sized)
247            }
248            front::TyKind::Tuple(tuple) => {
249                let tref = self.translate_type_decl_ref(span, &tuple.item)?;
250                TyKind::Adt(tref)
251            }
252            front::TyKind::Ref(reference) => {
253                trace!("Ref");
254
255                let region = self.translate_region(span, &reference.region)?;
256                let ty = self.translate_ty(span, &reference.ty)?;
257                let kind = if reference.mutbl.is_mut() {
258                    RefKind::Mut
259                } else {
260                    RefKind::Shared
261                };
262                TyKind::Ref(region, ty, kind)
263            }
264            front::TyKind::RawPtr(ptr) => {
265                trace!("RawPtr: {:?}", (&ptr.ty, &ptr.mutbl));
266                let ty = self.translate_ty(span, &ptr.ty)?;
267                let kind = if ptr.mutbl.is_mut() {
268                    RefKind::Mut
269                } else {
270                    RefKind::Shared
271                };
272                TyKind::RawPtr(ty, kind)
273            }
274
275            front::TyKind::Param(param) => {
276                // A type parameter, for example `T` in `fn f<T>(x : T) {}`.
277                match self.lookup_type_var(span, param) {
278                    Ok(var) => TyKind::TypeVar(var),
279                    Err(err) => TyKind::Error(err.msg),
280                }
281            }
282
283            front::TyKind::Foreign(foreign) => {
284                let tref = self.translate_type_decl_ref(span, &foreign.item)?;
285                TyKind::Adt(tref)
286            }
287
288            front::TyKind::FnPtr(fn_ptr) => {
289                trace!("FnPtr");
290                trace!("bound vars: {:?}", fn_ptr.sig.bound_vars);
291                let sig = self.translate_poly_fun_sig(span, &fn_ptr.sig)?;
292                TyKind::FnPtr(sig)
293            }
294            front::TyKind::FnDef(fn_def) => {
295                let fnref = self.translate_bound_fn_ptr(span, &fn_def.item)?;
296                TyKind::FnDef(fnref)
297            }
298            front::TyKind::Closure(args) => {
299                let tref = self.translate_closure_type_ref(span, &args.item)?;
300                TyKind::Adt(tref)
301            }
302
303            front::TyKind::DynTrait(dyn_trait) => {
304                // self.check_no_monomorphize(span)?;
305                // Translate the region outside the binder.
306                let region = self.translate_region(span, &dyn_trait.region)?;
307
308                let binder =
309                    self.translate_dyn_binder(span, &dyn_trait.binder, |ctx, ty, ()| {
310                        let region = region.move_under_binder();
311                        ctx.innermost_binder_mut()
312                            .params
313                            .outlives
314                            .push(RegionBinder::empty(OutlivesPred(
315                                Region::Lub(ty.clone()),
316                                region,
317                            )));
318                        Ok(ty)
319                    })?;
320
321                if let Some(clause) = dyn_trait.principal_trait_clause()
322                    && let front::ClauseKind::Trait(trait_predicate) =
323                        clause.frontend_skip_binder_ref()
324                {
325                    // TODO(dyn): for now, we consider traits with associated types to not be dyn
326                    // compatible because we don't know how to handle them; for these we skip
327                    // translating the vtable.
328                    if self.trait_is_dyn_compatible(&trait_predicate.trait_ref.def_id) {
329                        // Ensure the vtable type is translated. The first predicate is the one that
330                        // can have methods, i.e. a vtable.
331                        let s = self.frontend_state_with_id();
332                        let vtable_ref = trait_predicate
333                            .trait_ref
334                            .make_derived(s, front::DerivedItemKind::VTableDef);
335                        let _: TypeDeclId = self.register_item(span, &vtable_ref);
336                    }
337                }
338                TyKind::DynTrait(DynPredicate { binder })
339            }
340
341            front::TyKind::Infer(_) => {
342                raise_error!(self, span, "Unsupported type: infer type")
343            }
344            front::TyKind::Coroutine(..) => {
345                raise_error!(self, span, "Coroutine types are not supported yet")
346            }
347            front::TyKind::Bound(_) => {
348                raise_error!(self, span, "Unexpected type kind: bound")
349            }
350            front::TyKind::Placeholder(_) => {
351                raise_error!(self, span, "Unsupported type: placeholder")
352            }
353
354            front::TyKind::Error => {
355                raise_error!(self, span, "Type checking error")
356            }
357            front::TyKind::Todo(s) => {
358                raise_error!(self, span, "Unsupported type: {:?}", s)
359            }
360        };
361        Ok(kind.into_ty())
362    }
363
364    /// If `ty` is monomorphic, record its computed layout for `TypeDecl::monomorphic_layouts`.
365    fn record_monomorphic_layout(&mut self, span: Span, frontend_ty: &front::Ty<'tcx>, ty: &Ty) {
366        if
367        // Select types that have a `TypeDecl`...
368        let TyKind::Adt(tref) = ty.kind()
369            // ...where the decl does take generics
370            && tref.generics.has_non_lt_explicits()
371            && let front::TyKind::Adt(front::AdtTy { item })
372            | front::TyKind::Tuple(front::TupleTy { item })
373            | front::TyKind::Closure(front::ClosureTy { item }) = frontend_ty.kind()
374            // ...instantiated with monomorphic arguments
375            && !item.mentions_non_lt_param
376            && let tref = tref.clone().replace_regions(|| Region::Erased)
377            // ...where the type doesn't mention any in-scope clauses
378            && tref.type_info().is_closed()
379            // ...and hasn't been seen yet
380            && !self.monomorphic_layouts.contains_key(&tref)
381            && let Some(layout) = self.translate_layout(span, item, None)
382        {
383            self.monomorphic_layouts.insert(tref, layout);
384        }
385    }
386
387    pub fn translate_pattern(
388        &mut self,
389        span: Span,
390        pat: &front::Pattern<'tcx>,
391    ) -> Result<TypePattern, Error> {
392        Ok(match pat {
393            front::Pattern::Range { start, end } => TypePattern::Range(
394                self.translate_constant_expr(span, start)?,
395                self.translate_constant_expr(span, end)?,
396            ),
397            front::Pattern::Or(patterns) => TypePattern::OrPattern(
398                patterns
399                    .iter()
400                    .map(|pat| self.translate_pattern(span, pat))
401                    .try_collect()?,
402            ),
403            front::Pattern::NotNull => TypePattern::NotNull,
404        })
405    }
406
407    pub(crate) fn translate_rustc_ty(
408        &mut self,
409        span: Span,
410        ty: &ty::Ty<'tcx>,
411    ) -> Result<Ty, Error> {
412        let ty = self.t_ctx.catch_sinto(&self.frontend_state, span, ty)?;
413        self.translate_ty(span, &ty)
414    }
415
416    pub fn translate_poly_fun_sig(
417        &mut self,
418        span: Span,
419        sig: &front::Binder<front::TyFnSig<'tcx>>,
420    ) -> Result<RegionBinder<FunSig>, Error> {
421        self.translate_region_binder(span, sig, |ctx, sig| ctx.translate_fun_sig(span, sig))
422    }
423    pub fn translate_fun_sig(
424        &mut self,
425        span: Span,
426        sig: &front::TyFnSig<'tcx>,
427    ) -> Result<FunSig, Error> {
428        let inputs = sig
429            .inputs
430            .iter()
431            .map(|x| self.translate_ty(span, x))
432            .try_collect()?;
433        let output = self.translate_ty(span, &sig.output)?;
434        Ok(FunSig {
435            is_unsafe: sig.safety == front::Safety::Unsafe,
436            abi: self
437                .t_ctx
438                .translate_rustc_extern_abi(&sig.abi)
439                .expect("all rustc ExternAbi variants should be translated"),
440            is_variadic: sig.c_variadic,
441            inputs,
442            output,
443        })
444    }
445
446    /// Translate an item's base generic arguments. This does not include extra arguments coming
447    /// from unerasing lifetimes or derived items; don't call directly; use `translate_xxx_ref` as
448    /// much as possible.
449    pub fn translate_generic_args(
450        &mut self,
451        span: Span,
452        item: &front::ItemRef<'tcx>,
453    ) -> Result<GenericArgs, Error> {
454        self.translate_generic_args_inner(span, item, true)
455    }
456
457    /// Translate the same arguments without their trait proofs, e.g. for an instantiated name.
458    /// Don't call directly; use `translate_xxx_ref` as much as possible.
459    pub fn translate_generic_args_without_trait_refs(
460        &mut self,
461        span: Span,
462        item: &front::ItemRef<'tcx>,
463    ) -> Result<GenericArgs, Error> {
464        self.translate_generic_args_inner(span, item, false)
465    }
466
467    fn translate_generic_args_inner(
468        &mut self,
469        span: Span,
470        item: &front::ItemRef<'tcx>,
471        include_trait_refs: bool,
472    ) -> Result<GenericArgs, Error> {
473        // Items that have a typeck parent use their extra arguments for inference variables that
474        // we don't translate directly. Instead, use `translate_closure_region_args` to extract the
475        // arguments we do translate.
476        // FIXME: iterate through parents and find some uniform scheme
477        let substs = if let Some(parent) = item
478            .def_id
479            // TODO: `derived_base` is to compensate for wonky generics.
480            .derived_base()
481            .typeck_parent(self.frontend_state())
482        {
483            &item.generic_args[..parent.generics_of(self.frontend_state()).count()]
484        } else {
485            &item.generic_args
486        };
487        let mut args = self.translate_raw_generic_args(span, substs)?;
488        if include_trait_refs {
489            args.trait_refs = self.translate_trait_proofs(span, &item.trait_proofs)?;
490        }
491        Ok(args)
492    }
493
494    /// Translate a raw list of generic arguments. This does not produce the arguments of a Charon
495    /// item: use `translate_generic_args` for item references.
496    fn translate_raw_generic_args(
497        &mut self,
498        span: Span,
499        substs: &[front::GenericArg<'tcx>],
500    ) -> Result<GenericArgs, Error> {
501        let mut args = GenericArgs::empty();
502        for arg in substs {
503            match arg {
504                front::GenericArg::Type(ty) => {
505                    args.types.push(self.translate_ty(span, ty)?);
506                }
507                front::GenericArg::Lifetime(region) => {
508                    args.regions.push(self.translate_region(span, region)?);
509                }
510                front::GenericArg::Const(c) => {
511                    args.const_generics
512                        .push(self.translate_constant_expr(span, c)?);
513                }
514            }
515        }
516        Ok(args)
517    }
518
519    /// In rustc/frontend, closures and inline consts take a few extra generic types, which get inferred
520    /// and represent closure upvars and signature, or inline const return type. These types are
521    /// known so we don't consider them parameters in charon, however they still need to be given
522    /// lifetimes. These are the "extra early regions". On top of that, inner bodies may mention
523    /// outer bodies late bound lifetimes, which we fill in here as well.
524    pub(crate) fn recover_extra_early_regions(
525        &mut self,
526        span: Span,
527        item: &front::ItemRef<'tcx>,
528    ) -> Result<Vec<Region>, Error> {
529        let has_own_context = match item.def_id.as_derived() {
530            Some(front::DerivedItemKind::BuiltinAssocItemImpl(decl)) => {
531                decl.kind == front::DefKind::AssocFn
532            }
533            Some(front::DerivedItemKind::VTableDropShim) => true,
534            _ => false,
535        };
536        // Other derived items inherit the typing environment of the underlying item.
537        if item.def_id.as_derived().is_some() && !has_own_context {
538            return self
539                .recover_extra_early_regions(span, &item.peel_derived(self.frontend_state()));
540        }
541        // Fast path: only typeck children (closures, coroutine bodies, inline consts),
542        // anon/promoted consts, and items derived from closures can have extra early regions
543        // somewhere in the soft parent chain
544        if !item.def_id.is_typeck_child(self.frontend_state())
545            && !matches!(
546                item.def_id.kind,
547                front::DefKind::AnonConst | front::DefKind::PromotedConst
548            )
549            && !has_own_context
550        {
551            return Ok(vec![]);
552        }
553        let def = self.frontend_def(item)?;
554        let Some(param_env) = def.param_env() else {
555            return Ok(vec![]);
556        };
557        if param_env.extra_early_regions.is_empty() && param_env.soft_parent.is_none() {
558            return Ok(vec![]);
559        }
560        let (parent, actual, template) = item.soft_typing_parent(self.frontend_state_with_id());
561        // Recover parent arguments, in the same order as `push_generics_for_def`.
562        let mut regions = if let Some(parent) = parent {
563            let mut regions = self.recover_extra_early_regions(span, &parent)?;
564            let parent_def = self.frontend_def(&parent)?;
565            if let Some(parent_env) = parent_def.param_env()
566                && let Some(late_bound) = &parent_env.late_bound
567            {
568                // Rustc does not track the relationship between late bound lifetimes across
569                // bodies, so we fill in with erased regions to be inferred later.
570                regions.extend(
571                    late_bound
572                        .binder
573                        .bound_vars
574                        .iter()
575                        .map(|_| self.translate_erased_region()),
576                );
577            }
578            regions
579        } else {
580            Vec::new()
581        };
582        if param_env.extra_early_regions.is_empty() {
583            return Ok(regions);
584        }
585        // See `soft_typing_parent` for details: `template` and `actual` should be the same
586        // arguments, except that `template` has placeholder regions corresponding to the items
587        // `extra_early_regions`, and actual has actual regions in the same locations. We zip the
588        // two to infer a mapping.
589        let mapping = front::match_region_args(self.tcx, template, actual);
590        let mapping = match mapping {
591            Ok(mapping) => mapping,
592            Err(err) => raise_error!(
593                self,
594                span,
595                "Inferred arguments don't match their definition: {template:?} vs {actual:?}: {err:?}"
596            ),
597        };
598        for placeholder in &param_env.extra_early_regions {
599            // Normalization may discard a parameter, for example through an associated type.
600            let region = mapping
601                .get(placeholder)
602                .copied()
603                .unwrap_or(self.tcx.lifetimes.re_erased);
604            regions.push(self.translate_region(span, &region)?);
605        }
606        Ok(regions)
607    }
608
609    /// Whether Rust treats this type specially, i.e. whether it is a tuple, `str` or `Box`.
610    pub(crate) fn recognize_builtin_adt(
611        &mut self,
612        item: &front::ItemRef<'tcx>,
613    ) -> Option<BuiltinAdt> {
614        item.def_id
615            .as_synthetic(self.frontend_state())
616            .and_then(|synthetic| match synthetic {
617                front::SyntheticItem::Tuple(_) => Some(BuiltinAdt::Tuple),
618                front::SyntheticItem::Str => Some(BuiltinAdt::Str),
619                front::SyntheticItem::Array
620                | front::SyntheticItem::Slice
621                | front::SyntheticItem::FnPtr(_) => None,
622            })
623            .or_else(|| {
624                let def_id = item.def_id.as_real_def_id()?;
625                self.tcx
626                    .is_lang_item(def_id, rustc_attr_ir::LangItem::OwnedBox)
627                    .then_some(BuiltinAdt::Box)
628            })
629    }
630
631    /// Translate a Dynamically Sized Type metadata kind.
632    ///
633    /// Returns `None` if the type is generic, or if it is not a DST.
634    pub fn translate_ptr_metadata(
635        &mut self,
636        span: Span,
637        item: &front::ItemRef<'tcx>,
638    ) -> Result<PtrMetadata, Error> {
639        // prepare the call to the method
640        use rustc_middle::ty;
641        let tcx = self.t_ctx.tcx;
642        let frontend_state = &self.frontend_state;
643        let ty_env = frontend_state.typing_env();
644        let ty = item
645            .def_id
646            .type_of(frontend_state)
647            .instantiate(tcx, item.rustc_args(frontend_state));
648        let ty = front::normalize(tcx, ty_env, ty);
649
650        // Get the tail type, which determines the metadata of `ty`.
651        let tail_ty = ty.ptr_metadata_ty_or_tail(tcx, |ty| front::normalize(tcx, ty_env, ty));
652        let ret = match tail_ty {
653            Ok(ty) if ty.is_unit() => PtrMetadata::None,
654            Ok(ty) if ty.is_usize() => PtrMetadata::Length,
655            Ok(ty)
656                if let ty::Adt(def, args) = ty.kind()
657                    && tcx.is_lang_item(def.did(), rustc_attr_ir::LangItem::DynMetadata)
658                    && let rustc_dyn_ty = args.type_at(0)
659                    && let ty::Dynamic(predicates, _) = rustc_dyn_ty.kind() =>
660            {
661                // Use the `dyn Trait` type as self type so that assoc types projections on it can
662                // be normalized.
663                let principal = predicates
664                    .principal()
665                    .expect("expected a principal trait for vtable metadata")
666                    .with_self_ty(tcx, rustc_dyn_ty);
667                let principal = self.catch_sinto(span, &principal)?;
668                let vtable = self.translate_region_binder(span, &principal, |ctx, tref| {
669                    ctx.translate_vtable_struct_ref(span, tref)
670                })?;
671                let vtable = self.erase_region_binder(vtable);
672                PtrMetadata::VTable(vtable)
673            }
674            Ok(_) => unreachable!("unexpected unsized tail type"),
675            // extra check, as `ptr_metadata_ty_or_tail` ignores `Sized` bounds
676            Err(ty) if ty.is_sized(tcx, ty_env) => PtrMetadata::None,
677            Err(ty) => {
678                let frontend_ty = self.t_ctx.catch_sinto(frontend_state, span, &ty)?;
679                PtrMetadata::InheritFrom(self.translate_ty(span, &frontend_ty)?)
680            }
681        };
682
683        Ok(ret)
684    }
685
686    /// Translate a type layout.
687    ///
688    /// Translates the layout as queried from rustc into the more restricted [`Layout`].
689    #[tracing::instrument(skip(self))]
690    pub fn translate_layout(
691        &mut self,
692        span: Span,
693        item: &front::ItemRef<'tcx>,
694        fallback: Option<&TypeDeclKind>,
695    ) -> Option<Layout> {
696        use rustc_abi as r_abi;
697
698        fn translate_variant_layout_data(
699            layout_data: &r_abi::LayoutData<r_abi::FieldIdx, r_abi::VariantIdx>,
700            inhabited: InhabitedPredicate,
701            tagger: Vec<(ByteCount, IntegerValue)>,
702        ) -> Option<VariantLayout> {
703            let field_offsets = match &layout_data.fields {
704                r_abi::FieldsShape::Arbitrary { offsets, .. } => {
705                    offsets.iter().map(|o| OffsetExpr::new(o.bytes())).collect()
706                }
707                r_abi::FieldsShape::Union(n) => (0..n.get()).map(|_| OffsetExpr::new(0)).collect(),
708                r_abi::FieldsShape::Primitive => IndexVec::default(),
709                r_abi::FieldsShape::Array { .. } => panic!("Unexpected layout shape"),
710            };
711            Some(VariantLayout {
712                field_offsets,
713                inhabited,
714                tagger,
715            })
716        }
717
718        fn translate_primitive_int(int_ty: r_abi::Integer, signed: bool) -> IntegerTy {
719            if signed {
720                IntegerTy::Signed(match int_ty {
721                    r_abi::Integer::I8 => IntTy::I8,
722                    r_abi::Integer::I16 => IntTy::I16,
723                    r_abi::Integer::I32 => IntTy::I32,
724                    r_abi::Integer::I64 => IntTy::I64,
725                    r_abi::Integer::I128 => IntTy::I128,
726                })
727            } else {
728                IntegerTy::Unsigned(match int_ty {
729                    r_abi::Integer::I8 => UIntTy::U8,
730                    r_abi::Integer::I16 => UIntTy::U16,
731                    r_abi::Integer::I32 => UIntTy::U32,
732                    r_abi::Integer::I64 => UIntTy::U64,
733                    r_abi::Integer::I128 => UIntTy::U128,
734                })
735            }
736        }
737
738        /// Returns expressions that compute the layout (size, align) chosen by rustc. For sized
739        /// types, that's plain integers; for unsized types, we build expressions that compute the
740        /// right value based on pointer metadata values. This mirrors rustc's
741        /// `size_and_align_of_dst` computation:
742        /// <https://github.com/rust-lang/rust/blob/3fbb92e14159dd8b9bdb81e065883d1132e5abb7/compiler/rustc_codegen_ssa/src/size_of_val.rs#L100-L182>.
743        fn chosen_size_and_align<'tcx>(
744            cx: &ty::layout::LayoutCx<'tcx>,
745            layout: ty::layout::TyAndLayout<'tcx>,
746        ) -> Option<(SizeExpr, SizeExpr)> {
747            let constant = |value: u64| SizeExprKind::from_usize(u128::from(value)).into_expr();
748
749            if layout.is_sized() {
750                return Some((
751                    constant(layout.size.bytes()),
752                    constant(layout.align.bytes()),
753                ));
754            }
755
756            match layout.ty.kind() {
757                ty::Dynamic(..) => Some((
758                    SizeExprKind::FromMetadata(MetadataValue::DynSize).into_expr(),
759                    SizeExprKind::FromMetadata(MetadataValue::DynAlign).into_expr(),
760                )),
761                ty::Slice(..) | ty::Str => {
762                    let unit = layout.field(cx, 0);
763                    Some((
764                        SizeExprKind::Scale(
765                            SizeExprKind::FromMetadata(MetadataValue::SliceLength).into_expr(),
766                            ConstantExpr::mk_usize(u128::from(unit.size.bytes())),
767                        )
768                        .into_expr(),
769                        constant(unit.align.bytes()),
770                    ))
771                }
772                ty::Adt(..) | ty::Tuple(..) => {
773                    let tail_idx = layout.fields.count() - 1;
774                    let tail_offset = constant(layout.fields.offset(tail_idx).bytes());
775                    let sized_align = constant(layout.align.bytes());
776                    let tail_layout = layout.field(cx, tail_idx);
777                    let (tail_size, mut tail_align) = chosen_size_and_align(cx, tail_layout)?;
778
779                    if let ty::Adt(def, _) = layout.ty.kind()
780                        && let Some(pack) = def.repr().pack
781                    {
782                        tail_align =
783                            SizeExprKind::Min(vec![tail_align, constant(pack.bytes())]).into_expr();
784                    }
785
786                    let full_align = SizeExprKind::Max(vec![sized_align, tail_align]).into_expr();
787                    let full_size = SizeExprKind::AlignTo {
788                        base: SizeExprKind::Plus(tail_offset, tail_size).into_expr(),
789                        target_align: full_align.clone(),
790                    }
791                    .into_expr();
792                    Some((full_size, full_align))
793                }
794                ty::Foreign(..) => None,
795                _ => None,
796            }
797        }
798
799        /// Marks the bytes of `layout` that aren't padding, i.e. that are part of a primitive in
800        /// at least one field of one variant. This mirrors MiniRust's `calc_chunks`:
801        /// <https://github.com/minirust/minirust/blob/master/tooling/minimize/src/chunks.rs>.
802        fn mark_data_bytes<'tcx>(
803            cx: &ty::layout::LayoutCx<'tcx>,
804            layout: ty::layout::TyAndLayout<'tcx>,
805            markers: &mut [bool],
806        ) {
807            // The tag of a multi-variant layout is handled as one of its fields below.
808            if let r_abi::Variants::Multiple { variants, .. } = &layout.variants {
809                for id in variants.indices() {
810                    mark_data_bytes(cx, layout.for_variant(cx, id), markers);
811                }
812            }
813            match layout.fields {
814                r_abi::FieldsShape::Primitive => markers[..layout.size.bytes_usize()].fill(true),
815                r_abi::FieldsShape::Array { stride, count } => {
816                    let elem = layout.field(cx, 0);
817                    // Skip ZSTs which may have huge counts ([(); isize::MAX] & co.)
818                    if elem.is_zst() {
819                        return;
820                    }
821                    let mut elem_markers = vec![false; elem.size.bytes_usize()];
822                    mark_data_bytes(cx, elem, &mut elem_markers);
823                    for i in 0..count {
824                        let offset = (stride * i).bytes_usize();
825                        for (m, e) in markers[offset..].iter_mut().zip(&elem_markers) {
826                            *m |= e;
827                        }
828                    }
829                }
830                r_abi::FieldsShape::Union(_) | r_abi::FieldsShape::Arbitrary { .. } => {
831                    for i in 0..layout.fields.count() {
832                        let offset = layout.fields.offset(i).bytes_usize();
833                        mark_data_bytes(cx, layout.field(cx, i), &mut markers[offset..]);
834                    }
835                }
836            }
837        }
838
839        let tcx = self.t_ctx.tcx;
840        let frontend_state = self.frontend_state_with_id();
841        let ty_env = frontend_state.typing_env();
842        let ty = item
843            .def_id
844            .type_of(frontend_state)
845            .instantiate(tcx, item.rustc_args(frontend_state));
846        // Lifetimes don't affect layouts. We must erase them because `layout_of` ICEs on escaping
847        // bound regions, which we get e.g. from late-bound regions in signatures like
848        // `fn f(&self) -> Option<&dyn Trait>`.
849        let ty = erase_free_regions(tcx, ty);
850        let ty = front::normalize(tcx, ty_env, ty);
851        let pseudo_input = ty_env.as_query_input(ty);
852        let ptr_size = self.translated.the_target_information().target_pointer_size;
853
854        let repr = match &self.poly_frontend_def(&item.def_id).ok()?.kind {
855            front::FullDefKind::Adt(adt) => self.translate_repr_options(adt.repr()),
856            _ => ReprOptions::default(),
857        };
858        let ty_layout = match tcx.layout_of(pseudo_input) {
859            Ok(layout) => layout,
860            Err(_) => return Layout::for_type(&self.translated, fallback?, repr),
861        };
862        let rustc_variant_inhabited = |id| match ty.kind() {
863            ty::Adt(adt, args) if adt.is_enum() => adt
864                .variant(id)
865                .inhabited_predicate(tcx)
866                .instantiate(tcx, *args),
867            _ => ty.inhabited_predicate(tcx),
868        };
869        let inhabited = self
870            .translate_inhabited_predicate(span, ty.inhabited_predicate(tcx))
871            .ok()?;
872        let layout_cx = ty::layout::LayoutCx::new(tcx, ty_env);
873        let (size, align) = chosen_size_and_align(&layout_cx, ty_layout)?;
874        let size = Size::from_expr(size.normalize(Some(&self.translated), None, false));
875        let align = Size::from_expr(align.normalize(Some(&self.translated), None, false));
876        let layout = ty_layout.layout;
877
878        // Record the layout of all fields, if using `--collect-instantiated-layouts`
879        let record_field_layouts = |this: &mut Self, variant: ty::layout::TyAndLayout<'tcx>| {
880            if this.recording_mono_layouts {
881                for i in 0..variant.fields.count() {
882                    let field_ty = variant.field(&layout_cx, i).ty;
883                    if let Ok(frontend_ty) = this.catch_sinto(span, &field_ty)
884                        && let Ok(ty) = this.translate_ty(span, &frontend_ty)
885                    {
886                        this.record_monomorphic_layout(span, &frontend_ty, &ty);
887                    }
888                }
889            }
890        };
891
892        let num_variants = match ty.variant_range(self.t_ctx.tcx) {
893            Some(range) => range.end.index(),
894            None => match layout.fields() {
895                r_abi::FieldsShape::Arbitrary { .. } | r_abi::FieldsShape::Union(_) => 1,
896                // We interpret `str` as a struct, hence one variant.
897                r_abi::FieldsShape::Array { .. } if ty.is_str() => 1,
898                r_abi::FieldsShape::Primitive | r_abi::FieldsShape::Array { .. } => 0,
899            },
900        };
901        let mut variant_layouts: IndexVec<VariantId, Option<VariantLayout>> =
902            (0..num_variants).map(|_| None).collect();
903        // Build the discriminator tree and variant layouts.
904        let discriminator = match layout.variants() {
905            r_abi::Variants::Multiple {
906                tag,
907                tag_encoding,
908                tag_field,
909                variants,
910                ..
911            } => {
912                // The tag_field is the index into the `offsets` vector.
913                let r_abi::FieldsShape::Arbitrary { offsets, .. } = layout.fields() else {
914                    unreachable!()
915                };
916                let tag_offset = offsets
917                    .get(*tag_field)
918                    .map(|s| r_abi::Size::bytes(*s))
919                    .expect("No tag field offset for enum?");
920                let tag_offset_expr = OffsetExpr::new(tag_offset);
921
922                let tag_ty = match tag.primitive() {
923                    // A `bool` tag is a `u8` that only takes the values 0 and 1.
924                    r_abi::Primitive::Bool => IntegerTy::Unsigned(UIntTy::U8),
925                    r_abi::Primitive::Int(int_ty, signed) => {
926                        translate_primitive_int(int_ty, signed)
927                    }
928                    r_abi::Primitive::Pointer(_) => IntegerTy::Signed(IntTy::Isize),
929                    r_abi::Primitive::Float(_) => unreachable!(),
930                };
931                let tag_size = r_abi::Size::from_bytes(tag_ty.target_size(ptr_size));
932                // Reinterpret raw tag bits in `tag_ty`, sign-extending if needed.
933                let tag_from_bits =
934                    |bits: u128| IntegerValue::from_bits(tag_ty, tag_size.truncate(bits));
935
936                struct VariantTagInfo {
937                    /// The value of the tag for this variant, even if this is the untagged variant
938                    /// of a niched enum. `None` if we can't compute it.
939                    value: Option<IntegerValue>,
940                    /// Whether the variant is inhabited or not.
941                    uninhabited: bool,
942                    /// Whether this is the niched (untagged) variant of a niched enum.
943                    niched: bool,
944                }
945                let taginfo_for_variant = |id: rustc_abi::VariantIdx| {
946                    let uninhabited = variants[id].is_uninhabited();
947                    match tag_encoding {
948                        r_abi::TagEncoding::Direct => {
949                            let value = if uninhabited {
950                                None
951                            } else {
952                                let tag = tcx
953                                    .tag_for_variant(ty_env.as_query_input((ty, id)))
954                                    .unwrap();
955                                Some(tag_from_bits(tag.to_bits(tag_size)))
956                            };
957                            VariantTagInfo {
958                                value,
959                                uninhabited,
960                                niched: false,
961                            }
962                        }
963                        r_abi::TagEncoding::Niche {
964                            untagged_variant,
965                            niche_variants,
966                            niche_start,
967                        } => {
968                            let value = niche_variants.contains(&id).then(|| {
969                                let relative = (id.index() - niche_variants.start.index()) as u128;
970                                tag_from_bits(niche_start.wrapping_add(relative))
971                            });
972                            VariantTagInfo {
973                                value,
974                                uninhabited,
975                                niched: id == *untagged_variant,
976                            }
977                        }
978                    }
979                };
980
981                // Compute per-variant tag values and build tagger + discriminator children.
982                let mut children = Vec::new();
983
984                for (id, variant_layout) in variants.iter_enumerated() {
985                    record_field_layouts(self, ty_layout.for_variant(&layout_cx, id));
986
987                    let variant_id = self.translate_variant_id(id);
988                    let taginfo = taginfo_for_variant(id);
989                    let variant_inhabited = self
990                        .translate_inhabited_predicate(span, rustc_variant_inhabited(id))
991                        .ok()?;
992                    let tagger = if let Some(val) = taginfo.value {
993                        if taginfo.niched || taginfo.uninhabited {
994                            // If we could compute a tag for this variant, encountering it is UB.
995                            children.push((val..=val, Discriminator::Invalid));
996                            vec![]
997                        } else {
998                            children.push((val..=val, Discriminator::Known(variant_id)));
999                            vec![(tag_offset, val)]
1000                        }
1001                    } else {
1002                        // Niched or uninhabited variant that corresponds to no tag.
1003                        vec![]
1004                    };
1005
1006                    let field_offsets = variant_layout
1007                        .field_offsets
1008                        .iter()
1009                        .map(|o| OffsetExpr::new(o.bytes()))
1010                        .collect();
1011                    variant_layouts[variant_id] = Some(VariantLayout {
1012                        field_offsets,
1013                        inhabited: variant_inhabited,
1014                        tagger,
1015                    });
1016                }
1017
1018                let fallback = match tag_encoding {
1019                    r_abi::TagEncoding::Direct => Discriminator::Invalid,
1020                    // We follow what Minirust does:
1021                    // https://github.com/minirust/minirust/blob/master/tooling/minimize/src/enums.rs
1022                    r_abi::TagEncoding::Niche {
1023                        untagged_variant, ..
1024                    } => {
1025                        // Every value outside the valid range of the tag is invalid. The valid
1026                        // range is given as bits and may wrap around; we compare in `tag_ty`.
1027                        let valid = tag.valid_range(&self.t_ctx.tcx);
1028                        let start = tag_from_bits(valid.start);
1029                        let end = tag_from_bits(valid.end);
1030                        let (min, max) = match tag_ty {
1031                            IntegerTy::Signed(_) => (
1032                                tag_from_bits(tag_size.signed_int_min() as u128),
1033                                tag_from_bits(tag_size.signed_int_max() as u128),
1034                            ),
1035                            IntegerTy::Unsigned(_) => {
1036                                (tag_from_bits(0), tag_from_bits(tag_size.unsigned_int_max()))
1037                            }
1038                        };
1039
1040                        let after_end = tag_from_bits(valid.end.wrapping_add(1));
1041                        let before_start = tag_from_bits(valid.start.wrapping_sub(1));
1042                        if start <= end {
1043                            // The valid range is contiguous: the invalid values are on either side.
1044                            if end < max {
1045                                children.push((after_end..=max, Discriminator::Invalid));
1046                            }
1047                            if min < start {
1048                                children.push((min..=before_start, Discriminator::Invalid));
1049                            }
1050                        } else {
1051                            // The valid range wraps around: the invalid values are in the middle.
1052                            if after_end <= before_start {
1053                                children.push((after_end..=before_start, Discriminator::Invalid));
1054                            }
1055                        }
1056                        if variants[*untagged_variant].is_uninhabited() {
1057                            Discriminator::Invalid
1058                        } else {
1059                            Discriminator::Known(self.translate_variant_id(*untagged_variant))
1060                        }
1061                    }
1062                };
1063
1064                // The ranges are disjoint; sort them for readability.
1065                children.sort_by_key(|(range, _)| *range.start());
1066                let discriminator = Discriminator::Branch {
1067                    offset: tag_offset_expr,
1068                    int_ty: tag_ty,
1069                    fallback: Box::new(fallback),
1070                    children,
1071                };
1072
1073                Some(discriminator)
1074            }
1075            r_abi::Variants::Single { index } => {
1076                let variant_id = self.translate_variant_id(*index);
1077                match layout.fields() {
1078                    r_abi::FieldsShape::Arbitrary { .. } | r_abi::FieldsShape::Union(_) => {
1079                        record_field_layouts(self, ty_layout);
1080
1081                        let variant_inhabited = self
1082                            .translate_inhabited_predicate(span, rustc_variant_inhabited(*index))
1083                            .ok()?;
1084                        variant_layouts[variant_id] =
1085                            translate_variant_layout_data(&layout, variant_inhabited, vec![]);
1086                    }
1087                    r_abi::FieldsShape::Array { .. } if ty.is_str() => {
1088                        // Charon models `str` as a struct containing a single `[u8]` field.
1089                        variant_layouts[variant_id] = Some(VariantLayout {
1090                            field_offsets: [OffsetExpr::new(0)].into(),
1091                            inhabited: InhabitedPredicate::mk_true(),
1092                            tagger: vec![],
1093                        });
1094                    }
1095                    r_abi::FieldsShape::Primitive | r_abi::FieldsShape::Array { .. } => {}
1096                }
1097                Some(Discriminator::trivial(variant_id))
1098            }
1099            r_abi::Variants::Empty => None,
1100        };
1101
1102        let union_chunks = ty.is_union().then(|| {
1103            let mut markers = vec![false; ty_layout.size.bytes_usize()];
1104            mark_data_bytes(&layout_cx, ty_layout, &mut markers);
1105            let mut chunks = vec![];
1106            let mut offset = 0;
1107            for run in markers.chunk_by(|a, b| a == b) {
1108                if run[0] {
1109                    chunks.push((offset, run.len() as ByteCount));
1110                }
1111                offset += run.len() as ByteCount;
1112            }
1113            chunks
1114        });
1115
1116        Some(Layout {
1117            size,
1118            align,
1119            discriminator,
1120            inhabited,
1121            variant_layouts,
1122            union_chunks,
1123            repr,
1124        })
1125    }
1126
1127    /// Generate a naive layout for this type.
1128    pub fn generate_naive_layout(&self, span: Span, ty: &TypeDeclKind) -> Result<Layout, Error> {
1129        match ty {
1130            TypeDeclKind::Struct(fields) => {
1131                let mut size = 0;
1132                let mut align = 0;
1133                let ptr_size = self.translated.the_target_information().target_pointer_size;
1134                let field_offsets = fields.map_ref(|field| {
1135                    let offset = size;
1136                    let size_of_ty = match field.ty.kind() {
1137                        TyKind::Scalar(scalar_ty) => scalar_ty.target_size(ptr_size) as u64,
1138                        // This is a lie, the pointers could be fat...
1139                        TyKind::Ref(..) | TyKind::RawPtr(..) | TyKind::FnPtr(..) => ptr_size,
1140                        _ => panic!("Unsupported type for `generate_naive_layout`: {ty:?}"),
1141                    };
1142                    // For these types, align == size is good enough.
1143                    let align_of_ty = size_of_ty;
1144                    size += size_of_ty;
1145                    align = std::cmp::max(align, align_of_ty);
1146                    OffsetExpr::new(offset)
1147                });
1148
1149                Ok(Layout {
1150                    size: Size::new(size),
1151                    align: Size::new(align),
1152                    discriminator: None,
1153                    inhabited: InhabitedPredicate::mk_true(),
1154                    variant_layouts: IndexVec::from([Some(VariantLayout {
1155                        field_offsets,
1156                        tagger: vec![],
1157                        inhabited: InhabitedPredicate::mk_true(),
1158                    })]),
1159                    union_chunks: None,
1160                    repr: ReprOptions::default(),
1161                })
1162            }
1163            _ => raise_error!(
1164                self,
1165                span,
1166                "`generate_naive_layout` only supports structs at the moment"
1167            ),
1168        }
1169    }
1170
1171    /// Translate the body of a type declaration.
1172    ///
1173    /// Note that the type may be external, in which case we translate the body
1174    /// only if it is public (i.e., it is a public enumeration, or it is a
1175    /// struct with only public fields).
1176    pub(crate) fn translate_adt_def(
1177        &mut self,
1178        trans_id: TypeDeclId,
1179        def_span: Span,
1180        item_meta: &ItemMeta,
1181        def: &front::FullDef<'tcx>,
1182    ) -> Result<TypeDeclKind, Error> {
1183        use crate::frontend::AdtKind;
1184        let adt = def.kind().as_adt().unwrap();
1185
1186        if item_meta.opacity.is_opaque() {
1187            return Ok(TypeDeclKind::Opaque);
1188        }
1189
1190        let adt_kind = adt.adt_kind();
1191        if matches!(adt_kind, AdtKind::Tuple) && self.t_ctx.options.no_gen_tuple_structs {
1192            return Ok(TypeDeclKind::Opaque);
1193        }
1194
1195        // The frontend's synthetic ADTs have no variants; we must construct the fields ourselves
1196        let synthetic_fields = match adt_kind {
1197            AdtKind::Tuple => {
1198                let item = def.this();
1199                let args = self.translate_generic_args_without_trait_refs(def_span, item)?;
1200                Some(args.types.into_iter().collect_vec())
1201            }
1202            AdtKind::Str => {
1203                let u8_is_sized = self.translate_sized_proof(def_span, self.tcx.types.u8)?;
1204                Some(vec![Ty::mk_slice(Ty::mk_u8(), u8_is_sized)])
1205            }
1206            _ => None,
1207        };
1208        if let Some(tys) = synthetic_fields {
1209            let fields = tys
1210                .into_iter()
1211                .enumerate()
1212                .map(|(field_id, ty)| Field {
1213                    span: def_span,
1214                    attr_info: AttrInfo::dummy_public(),
1215                    name: format!("_{field_id}"),
1216                    is_positional: true,
1217                    ty,
1218                })
1219                .collect();
1220            return Ok(TypeDeclKind::Struct(fields));
1221        }
1222
1223        trace!("{}", trans_id);
1224
1225        // In case the type is external, check if we should consider the type as
1226        // transparent (i.e., extract its body). If it is an enumeration, then yes
1227        // (because the variants of public enumerations are public, together with their
1228        // fields). If it is a structure, we check if all the fields are public.
1229        let variants = adt.variants();
1230        let contents_are_public = match adt_kind {
1231            AdtKind::Enum => true,
1232            AdtKind::Struct | AdtKind::Union => {
1233                // Check the unique variant
1234                error_assert!(self, def_span, variants.len() == 1);
1235                variants[front::VariantIdx::from(0usize)]
1236                    .fields
1237                    .iter()
1238                    .all(|f| matches!(f.vis, Visibility::Public))
1239            }
1240            // The rest are fake adt kinds that won't reach here.
1241            _ => unreachable!(),
1242        };
1243
1244        if item_meta
1245            .opacity
1246            .with_content_visibility(contents_are_public)
1247            .is_opaque()
1248        {
1249            return Ok(TypeDeclKind::Opaque);
1250        }
1251
1252        // The type is transparent: explore the variants
1253        let mut translated_variants: IndexVec<VariantId, Variant> = Default::default();
1254        for (i, var_def) in variants.iter().enumerate() {
1255            trace!("variant {i}: {var_def:?}");
1256
1257            let mut fields: IndexVec<FieldId, Field> = Default::default();
1258            for (j, field_def) in var_def.fields.iter().enumerate() {
1259                trace!("variant {i}: field {j}: {field_def:?}");
1260                let field_span = self.t_ctx.translate_span(&field_def.span);
1261                // Translate the field type
1262                let ty = self.translate_ty(field_span, &field_def.ty)?;
1263                let field_full_def = self.poly_frontend_def(&field_def.did)?;
1264                let field_attrs = self.t_ctx.translate_attr_info(&field_full_def);
1265
1266                // Retrieve the field name.
1267                let is_positional = field_def.name.is_none();
1268                let field_name = field_def
1269                    .name
1270                    .map_or_else(|| format!("_{j}"), |name| name.to_string());
1271
1272                // Store the field
1273                let field = Field {
1274                    span: field_span,
1275                    attr_info: field_attrs,
1276                    name: field_name,
1277                    is_positional,
1278                    ty,
1279                };
1280                fields.push(field);
1281            }
1282
1283            let discriminant = self.translate_discriminant(def_span, &var_def.discr_val)?;
1284            let variant_span = self.t_ctx.translate_span(&var_def.span);
1285            let variant_name = var_def.name.to_string();
1286            let variant_full_def = self.poly_frontend_def(&var_def.def_id)?;
1287
1288            let mut variant_attrs = self.t_ctx.translate_attr_info(&variant_full_def);
1289            // Propagate a `#[charon::variants_prefix(..)]` or `#[charon::variants_suffix(..)]` attribute to the variants.
1290            if variant_attrs.rename.is_none() {
1291                let prefix = item_meta
1292                    .attr_info
1293                    .attributes
1294                    .iter()
1295                    .filter_map(|a| a.as_variants_prefix())
1296                    .next()
1297                    .map(|attr| attr.as_str());
1298                let suffix = item_meta
1299                    .attr_info
1300                    .attributes
1301                    .iter()
1302                    .filter_map(|a| a.as_variants_suffix())
1303                    .next()
1304                    .map(|attr| attr.as_str());
1305                if prefix.is_some() || suffix.is_some() {
1306                    let prefix = prefix.unwrap_or_default();
1307                    let suffix = suffix.unwrap_or_default();
1308                    variant_attrs.rename = Some(format!("{prefix}{variant_name}{suffix}"));
1309                }
1310            }
1311
1312            translated_variants.push_with(|id| Variant {
1313                id,
1314                span: variant_span,
1315                attr_info: variant_attrs,
1316                name: variant_name,
1317                fields,
1318                discriminant,
1319            });
1320        }
1321
1322        // Register the type
1323        let type_def_kind: TypeDeclKind = match adt_kind {
1324            AdtKind::Struct => TypeDeclKind::Struct(translated_variants[0].fields.clone()),
1325            AdtKind::Enum => TypeDeclKind::Enum(translated_variants),
1326            AdtKind::Union => TypeDeclKind::Union(translated_variants[0].fields.clone()),
1327            // The rest are fake adt kinds that won't reach here.
1328            _ => unreachable!(),
1329        };
1330
1331        Ok(type_def_kind)
1332    }
1333
1334    fn translate_discriminant(
1335        &mut self,
1336        def_span: Span,
1337        discr: &front::DiscriminantValue<'tcx>,
1338    ) -> Result<IntegerValue, Error> {
1339        let ty = self.translate_ty(def_span, &discr.ty)?;
1340        let scalar_ty = ty.kind().as_scalar().unwrap();
1341        match scalar_ty.as_integer() {
1342            Some(int_ty) => Ok(IntegerValue::from_bits(*int_ty, discr.val)),
1343            None => raise_error!(self, def_span, "unexpected discriminant type: {ty:?}",),
1344        }
1345    }
1346
1347    fn translate_inhabited_predicate(
1348        &mut self,
1349        span: Span,
1350        predicate: ty::inhabitedness::InhabitedPredicate<'tcx>,
1351    ) -> Result<InhabitedPredicate, Error> {
1352        use ty::inhabitedness::InhabitedPredicate as RustcPredicate;
1353        Ok(match predicate {
1354            RustcPredicate::True => InhabitedPredicateKind::True,
1355            RustcPredicate::False => InhabitedPredicateKind::False,
1356            RustcPredicate::ConstIsZero(value) => {
1357                InhabitedPredicateKind::ConstIsZero(self.translate_ty_constant_expr(span, &value)?)
1358            }
1359            // We only retain layout-relevant inhabitedness.
1360            RustcPredicate::NotInModule(_) => InhabitedPredicateKind::False,
1361            RustcPredicate::GenericType(ty) => {
1362                InhabitedPredicateKind::GenericType(self.translate_rustc_ty(span, &ty)?)
1363            }
1364            RustcPredicate::OpaqueType(key) => {
1365                // Reveal the opaque type.
1366                let opaque_ty = self
1367                    .tcx
1368                    .type_of(key.def_id)
1369                    .instantiate(self.tcx, key.args)
1370                    .skip_norm_wip();
1371                return self
1372                    .translate_inhabited_predicate(span, opaque_ty.inhabited_predicate(self.tcx));
1373            }
1374            RustcPredicate::And(&[left, right]) => InhabitedPredicateKind::And(vec![
1375                self.translate_inhabited_predicate(span, left)?,
1376                self.translate_inhabited_predicate(span, right)?,
1377            ]),
1378            RustcPredicate::Or(&[left, right]) => InhabitedPredicateKind::Or(vec![
1379                self.translate_inhabited_predicate(span, left)?,
1380                self.translate_inhabited_predicate(span, right)?,
1381            ]),
1382        }
1383        .into_pred())
1384    }
1385
1386    pub fn translate_repr_options(
1387        &mut self,
1388        frontend_repr_options: &front::ReprOptions,
1389    ) -> ReprOptions {
1390        let repr_algo = if frontend_repr_options.flags.is_simd {
1391            ReprAlgorithm::Simd
1392        } else if frontend_repr_options.flags.is_c {
1393            ReprAlgorithm::C
1394        } else {
1395            ReprAlgorithm::Rust
1396        };
1397
1398        let align_mod = if let Some(align) = &frontend_repr_options.align {
1399            Some(AlignmentModifier::Align(align.bytes()))
1400        } else if let Some(pack) = &frontend_repr_options.pack {
1401            Some(AlignmentModifier::Pack(pack.bytes()))
1402        } else {
1403            None
1404        };
1405
1406        let explicit_discr_type =
1407            frontend_repr_options
1408                .int_specified
1409                .then(|| match frontend_repr_options.typ.kind() {
1410                    front::TyKind::Int(ty) => {
1411                        IntegerTy::Signed(Self::translate_frontend_int_ty(ty))
1412                    }
1413                    front::TyKind::Uint(ty) => {
1414                        IntegerTy::Unsigned(Self::translate_frontend_uint_ty(ty))
1415                    }
1416                    ty => unreachable!("explicit enum discriminant type is not an integer: {ty:?}"),
1417                });
1418
1419        ReprOptions {
1420            transparent: frontend_repr_options.flags.is_transparent,
1421            explicit_discr_type,
1422            repr_algo,
1423            align_modif: align_mod,
1424        }
1425    }
1426}