wasmtime_environ/component/
types_builder.rs

1use crate::component::*;
2use crate::prelude::*;
3use crate::{
4    EngineOrModuleTypeIndex, EntityType, ModuleInternedTypeIndex, ModuleTypes, ModuleTypesBuilder,
5    PrimaryMap, TypeConvert, WasmHeapType, WasmValType,
6};
7use anyhow::{bail, Result};
8use cranelift_entity::EntityRef;
9use std::collections::HashMap;
10use std::hash::Hash;
11use std::ops::Index;
12use wasmparser::component_types::{
13    ComponentAnyTypeId, ComponentCoreModuleTypeId, ComponentDefinedType, ComponentDefinedTypeId,
14    ComponentEntityType, ComponentFuncTypeId, ComponentInstanceTypeId, ComponentTypeId,
15    ComponentValType, RecordType, ResourceId, TupleType, VariantType,
16};
17use wasmparser::names::KebabString;
18use wasmparser::types::TypesRef;
19use wasmparser::{PrimitiveValType, Validator};
20use wasmtime_component_util::FlagsSize;
21
22mod resources;
23pub use resources::ResourcesBuilder;
24
25/// Maximum nesting depth of a type allowed in Wasmtime.
26///
27/// This constant isn't chosen via any scientific means and its main purpose is
28/// to enable most of Wasmtime to handle types via recursion without worrying
29/// about stack overflow.
30///
31/// Some more information about this can be found in #4814
32const MAX_TYPE_DEPTH: u32 = 100;
33
34/// Structure used to build a [`ComponentTypes`] during translation.
35///
36/// This contains tables to intern any component types found as well as
37/// managing building up core wasm [`ModuleTypes`] as well.
38pub struct ComponentTypesBuilder {
39    functions: HashMap<TypeFunc, TypeFuncIndex>,
40    lists: HashMap<TypeList, TypeListIndex>,
41    records: HashMap<TypeRecord, TypeRecordIndex>,
42    variants: HashMap<TypeVariant, TypeVariantIndex>,
43    tuples: HashMap<TypeTuple, TypeTupleIndex>,
44    enums: HashMap<TypeEnum, TypeEnumIndex>,
45    flags: HashMap<TypeFlags, TypeFlagsIndex>,
46    options: HashMap<TypeOption, TypeOptionIndex>,
47    results: HashMap<TypeResult, TypeResultIndex>,
48    futures: HashMap<TypeFuture, TypeFutureIndex>,
49    streams: HashMap<TypeStream, TypeStreamIndex>,
50    future_tables: HashMap<TypeFutureTable, TypeFutureTableIndex>,
51    stream_tables: HashMap<TypeStreamTable, TypeStreamTableIndex>,
52    error_context_tables: HashMap<TypeErrorContextTable, TypeComponentLocalErrorContextTableIndex>,
53
54    component_types: ComponentTypes,
55    module_types: ModuleTypesBuilder,
56
57    // Cache of what the "flat" representation of all types are which is only
58    // used at compile-time and not used at runtime, hence the location here
59    // as opposed to `ComponentTypes`.
60    type_info: TypeInformationCache,
61
62    resources: ResourcesBuilder,
63}
64
65impl<T> Index<T> for ComponentTypesBuilder
66where
67    ModuleTypes: Index<T>,
68{
69    type Output = <ModuleTypes as Index<T>>::Output;
70    fn index(&self, idx: T) -> &Self::Output {
71        self.module_types.index(idx)
72    }
73}
74
75macro_rules! intern_and_fill_flat_types {
76    ($me:ident, $name:ident, $val:ident) => {{
77        if let Some(idx) = $me.$name.get(&$val) {
78            *idx
79        } else {
80            let idx = $me.component_types.$name.push($val.clone());
81            let mut info = TypeInformation::new();
82            info.$name($me, &$val);
83            let idx2 = $me.type_info.$name.push(info);
84            assert_eq!(idx, idx2);
85            $me.$name.insert($val, idx);
86            idx
87        }
88    }};
89}
90
91impl ComponentTypesBuilder {
92    /// Construct a new `ComponentTypesBuilder` for use with the given validator.
93    pub fn new(validator: &Validator) -> Self {
94        Self {
95            module_types: ModuleTypesBuilder::new(validator),
96
97            functions: HashMap::default(),
98            lists: HashMap::default(),
99            records: HashMap::default(),
100            variants: HashMap::default(),
101            tuples: HashMap::default(),
102            enums: HashMap::default(),
103            flags: HashMap::default(),
104            options: HashMap::default(),
105            results: HashMap::default(),
106            futures: HashMap::default(),
107            streams: HashMap::default(),
108            future_tables: HashMap::default(),
109            stream_tables: HashMap::default(),
110            error_context_tables: HashMap::default(),
111            component_types: ComponentTypes::default(),
112            type_info: TypeInformationCache::default(),
113            resources: ResourcesBuilder::default(),
114        }
115    }
116
117    fn export_type_def(
118        &mut self,
119        export_items: &PrimaryMap<ExportIndex, Export>,
120        idx: ExportIndex,
121    ) -> TypeDef {
122        match &export_items[idx] {
123            Export::LiftedFunction { ty, .. } => TypeDef::ComponentFunc(*ty),
124            Export::ModuleStatic { ty, .. } | Export::ModuleImport { ty, .. } => {
125                TypeDef::Module(*ty)
126            }
127            Export::Instance { ty, .. } => TypeDef::ComponentInstance(*ty),
128            Export::Type(ty) => *ty,
129        }
130    }
131
132    /// Finishes this list of component types and returns the finished
133    /// structure and the [`TypeComponentIndex`] corresponding to top-level component
134    /// with `imports` and `exports` specified.
135    pub fn finish(mut self, component: &Component) -> (ComponentTypes, TypeComponentIndex) {
136        let mut component_ty = TypeComponent::default();
137        for (_, (name, ty)) in component.import_types.iter() {
138            component_ty.imports.insert(name.clone(), *ty);
139        }
140        for (name, ty) in component.exports.raw_iter() {
141            component_ty.exports.insert(
142                name.clone(),
143                self.export_type_def(&component.export_items, *ty),
144            );
145        }
146        let ty = self.component_types.components.push(component_ty);
147
148        self.component_types.module_types = Some(self.module_types.finish());
149        (self.component_types, ty)
150    }
151
152    /// Smaller helper method to find a `ModuleInternedTypeIndex` which
153    /// corresponds to the `resource.drop` intrinsic in components, namely a
154    /// core wasm function type which takes one `i32` argument and has no
155    /// results.
156    ///
157    /// This is a bit of a hack right now as ideally this find operation
158    /// wouldn't be needed and instead the `ModuleInternedTypeIndex` itself
159    /// would be threaded through appropriately, but that's left for a future
160    /// refactoring. Try not to lean too hard on this method though.
161    pub fn find_resource_drop_signature(&self) -> Option<ModuleInternedTypeIndex> {
162        self.module_types
163            .wasm_types()
164            .find(|(_, ty)| {
165                ty.as_func().map_or(false, |sig| {
166                    sig.params().len() == 1
167                        && sig.returns().len() == 0
168                        && sig.params()[0] == WasmValType::I32
169                })
170            })
171            .map(|(i, _)| i)
172    }
173
174    /// Returns the underlying builder used to build up core wasm module types.
175    ///
176    /// Note that this is shared across all modules found within a component to
177    /// improve the wins from deduplicating function signatures.
178    pub fn module_types_builder(&self) -> &ModuleTypesBuilder {
179        &self.module_types
180    }
181
182    /// Same as `module_types_builder`, but `mut`.
183    pub fn module_types_builder_mut(&mut self) -> &mut ModuleTypesBuilder {
184        &mut self.module_types
185    }
186
187    /// Returns the internal reference to the in-progress `&ComponentTypes`.
188    pub(super) fn component_types(&self) -> &ComponentTypes {
189        &self.component_types
190    }
191
192    /// Returns the number of resource tables allocated so far, or the maximum
193    /// `TypeResourceTableIndex`.
194    pub fn num_resource_tables(&self) -> usize {
195        self.component_types.resource_tables.len()
196    }
197
198    /// Returns the number of future tables allocated so far, or the maximum
199    /// `TypeFutureTableIndex`.
200    pub fn num_future_tables(&self) -> usize {
201        self.component_types.future_tables.len()
202    }
203
204    /// Returns the number of stream tables allocated so far, or the maximum
205    /// `TypeStreamTableIndex`.
206    pub fn num_stream_tables(&self) -> usize {
207        self.component_types.stream_tables.len()
208    }
209
210    /// Returns the number of error-context tables allocated so far, or the maximum
211    /// `TypeComponentLocalErrorContextTableIndex`.
212    pub fn num_error_context_tables(&self) -> usize {
213        self.component_types.error_context_tables.len()
214    }
215
216    /// Returns a mutable reference to the underlying `ResourcesBuilder`.
217    pub fn resources_mut(&mut self) -> &mut ResourcesBuilder {
218        &mut self.resources
219    }
220
221    /// Work around the borrow checker to borrow two sub-fields simultaneously
222    /// externally.
223    pub fn resources_mut_and_types(&mut self) -> (&mut ResourcesBuilder, &ComponentTypes) {
224        (&mut self.resources, &self.component_types)
225    }
226
227    /// Converts a wasmparser `ComponentFuncType` into Wasmtime's type
228    /// representation.
229    pub fn convert_component_func_type(
230        &mut self,
231        types: TypesRef<'_>,
232        id: ComponentFuncTypeId,
233    ) -> Result<TypeFuncIndex> {
234        assert_eq!(types.id(), self.module_types.validator_id());
235        let ty = &types[id];
236        let param_names = ty.params.iter().map(|(name, _)| name.to_string()).collect();
237        let params = ty
238            .params
239            .iter()
240            .map(|(_name, ty)| self.valtype(types, ty))
241            .collect::<Result<_>>()?;
242        let results = ty
243            .result
244            .iter()
245            .map(|ty| self.valtype(types, ty))
246            .collect::<Result<_>>()?;
247        let params = self.new_tuple_type(params);
248        let results = self.new_tuple_type(results);
249        let ty = TypeFunc {
250            param_names,
251            params,
252            results,
253        };
254        Ok(self.add_func_type(ty))
255    }
256
257    /// Converts a wasmparser `ComponentEntityType` into Wasmtime's type
258    /// representation.
259    pub fn convert_component_entity_type(
260        &mut self,
261        types: TypesRef<'_>,
262        ty: ComponentEntityType,
263    ) -> Result<TypeDef> {
264        assert_eq!(types.id(), self.module_types.validator_id());
265        Ok(match ty {
266            ComponentEntityType::Module(id) => TypeDef::Module(self.convert_module(types, id)?),
267            ComponentEntityType::Component(id) => {
268                TypeDef::Component(self.convert_component(types, id)?)
269            }
270            ComponentEntityType::Instance(id) => {
271                TypeDef::ComponentInstance(self.convert_instance(types, id)?)
272            }
273            ComponentEntityType::Func(id) => {
274                TypeDef::ComponentFunc(self.convert_component_func_type(types, id)?)
275            }
276            ComponentEntityType::Type { created, .. } => match created {
277                ComponentAnyTypeId::Defined(id) => {
278                    TypeDef::Interface(self.defined_type(types, id)?)
279                }
280                ComponentAnyTypeId::Resource(id) => {
281                    TypeDef::Resource(self.resource_id(id.resource()))
282                }
283                _ => bail!("unsupported type export"),
284            },
285            ComponentEntityType::Value(_) => bail!("values not supported"),
286        })
287    }
288
289    /// Converts a wasmparser `Type` into Wasmtime's type representation.
290    pub fn convert_type(&mut self, types: TypesRef<'_>, id: ComponentAnyTypeId) -> Result<TypeDef> {
291        assert_eq!(types.id(), self.module_types.validator_id());
292        Ok(match id {
293            ComponentAnyTypeId::Defined(id) => TypeDef::Interface(self.defined_type(types, id)?),
294            ComponentAnyTypeId::Component(id) => {
295                TypeDef::Component(self.convert_component(types, id)?)
296            }
297            ComponentAnyTypeId::Instance(id) => {
298                TypeDef::ComponentInstance(self.convert_instance(types, id)?)
299            }
300            ComponentAnyTypeId::Func(id) => {
301                TypeDef::ComponentFunc(self.convert_component_func_type(types, id)?)
302            }
303            ComponentAnyTypeId::Resource(id) => TypeDef::Resource(self.resource_id(id.resource())),
304        })
305    }
306
307    fn convert_component(
308        &mut self,
309        types: TypesRef<'_>,
310        id: ComponentTypeId,
311    ) -> Result<TypeComponentIndex> {
312        assert_eq!(types.id(), self.module_types.validator_id());
313        let ty = &types[id];
314        let mut result = TypeComponent::default();
315        for (name, ty) in ty.imports.iter() {
316            result.imports.insert(
317                name.clone(),
318                self.convert_component_entity_type(types, *ty)?,
319            );
320        }
321        for (name, ty) in ty.exports.iter() {
322            result.exports.insert(
323                name.clone(),
324                self.convert_component_entity_type(types, *ty)?,
325            );
326        }
327        Ok(self.component_types.components.push(result))
328    }
329
330    pub(crate) fn convert_instance(
331        &mut self,
332        types: TypesRef<'_>,
333        id: ComponentInstanceTypeId,
334    ) -> Result<TypeComponentInstanceIndex> {
335        assert_eq!(types.id(), self.module_types.validator_id());
336        let ty = &types[id];
337        let mut result = TypeComponentInstance::default();
338        for (name, ty) in ty.exports.iter() {
339            result.exports.insert(
340                name.clone(),
341                self.convert_component_entity_type(types, *ty)?,
342            );
343        }
344        Ok(self.component_types.component_instances.push(result))
345    }
346
347    pub(crate) fn convert_module(
348        &mut self,
349        types: TypesRef<'_>,
350        id: ComponentCoreModuleTypeId,
351    ) -> Result<TypeModuleIndex> {
352        assert_eq!(types.id(), self.module_types.validator_id());
353        let ty = &types[id];
354        let mut result = TypeModule::default();
355        for ((module, field), ty) in ty.imports.iter() {
356            result.imports.insert(
357                (module.clone(), field.clone()),
358                self.entity_type(types, ty)?,
359            );
360        }
361        for (name, ty) in ty.exports.iter() {
362            result
363                .exports
364                .insert(name.clone(), self.entity_type(types, ty)?);
365        }
366        Ok(self.component_types.modules.push(result))
367    }
368
369    fn entity_type(
370        &mut self,
371        types: TypesRef<'_>,
372        ty: &wasmparser::types::EntityType,
373    ) -> Result<EntityType> {
374        use wasmparser::types::EntityType::*;
375
376        assert_eq!(types.id(), self.module_types.validator_id());
377        Ok(match ty {
378            Func(id) => EntityType::Function({
379                self.module_types_builder_mut()
380                    .intern_type(types, *id)?
381                    .into()
382            }),
383            Table(ty) => EntityType::Table(self.convert_table_type(ty)?),
384            Memory(ty) => EntityType::Memory((*ty).into()),
385            Global(ty) => EntityType::Global(self.convert_global_type(ty)),
386            Tag(_) => bail!("exceptions proposal not implemented"),
387        })
388    }
389
390    /// Convert a wasmparser `ComponentDefinedTypeId` into Wasmtime's type representation.
391    pub fn defined_type(
392        &mut self,
393        types: TypesRef<'_>,
394        id: ComponentDefinedTypeId,
395    ) -> Result<InterfaceType> {
396        assert_eq!(types.id(), self.module_types.validator_id());
397        let ret = match &types[id] {
398            ComponentDefinedType::Primitive(ty) => self.primitive_type(ty)?,
399            ComponentDefinedType::Record(e) => InterfaceType::Record(self.record_type(types, e)?),
400            ComponentDefinedType::Variant(e) => {
401                InterfaceType::Variant(self.variant_type(types, e)?)
402            }
403            ComponentDefinedType::List(e) => InterfaceType::List(self.list_type(types, e)?),
404            ComponentDefinedType::Tuple(e) => InterfaceType::Tuple(self.tuple_type(types, e)?),
405            ComponentDefinedType::Flags(e) => InterfaceType::Flags(self.flags_type(e)),
406            ComponentDefinedType::Enum(e) => InterfaceType::Enum(self.enum_type(e)),
407            ComponentDefinedType::Option(e) => InterfaceType::Option(self.option_type(types, e)?),
408            ComponentDefinedType::Result { ok, err } => {
409                InterfaceType::Result(self.result_type(types, ok, err)?)
410            }
411            ComponentDefinedType::Own(r) => InterfaceType::Own(self.resource_id(r.resource())),
412            ComponentDefinedType::Borrow(r) => {
413                InterfaceType::Borrow(self.resource_id(r.resource()))
414            }
415            ComponentDefinedType::Future(ty) => {
416                InterfaceType::Future(self.future_table_type(types, ty)?)
417            }
418            ComponentDefinedType::Stream(ty) => {
419                InterfaceType::Stream(self.stream_table_type(types, ty)?)
420            }
421        };
422        let info = self.type_information(&ret);
423        if info.depth > MAX_TYPE_DEPTH {
424            bail!("type nesting is too deep");
425        }
426        Ok(ret)
427    }
428
429    /// Retrieve Wasmtime's type representation of the `error-context` type.
430    pub fn error_context_type(&mut self) -> Result<TypeComponentLocalErrorContextTableIndex> {
431        self.error_context_table_type()
432    }
433
434    pub(crate) fn valtype(
435        &mut self,
436        types: TypesRef<'_>,
437        ty: &ComponentValType,
438    ) -> Result<InterfaceType> {
439        assert_eq!(types.id(), self.module_types.validator_id());
440        match ty {
441            ComponentValType::Primitive(p) => self.primitive_type(p),
442            ComponentValType::Type(id) => self.defined_type(types, *id),
443        }
444    }
445
446    fn primitive_type(&mut self, ty: &PrimitiveValType) -> Result<InterfaceType> {
447        match ty {
448            wasmparser::PrimitiveValType::Bool => Ok(InterfaceType::Bool),
449            wasmparser::PrimitiveValType::S8 => Ok(InterfaceType::S8),
450            wasmparser::PrimitiveValType::U8 => Ok(InterfaceType::U8),
451            wasmparser::PrimitiveValType::S16 => Ok(InterfaceType::S16),
452            wasmparser::PrimitiveValType::U16 => Ok(InterfaceType::U16),
453            wasmparser::PrimitiveValType::S32 => Ok(InterfaceType::S32),
454            wasmparser::PrimitiveValType::U32 => Ok(InterfaceType::U32),
455            wasmparser::PrimitiveValType::S64 => Ok(InterfaceType::S64),
456            wasmparser::PrimitiveValType::U64 => Ok(InterfaceType::U64),
457            wasmparser::PrimitiveValType::F32 => Ok(InterfaceType::Float32),
458            wasmparser::PrimitiveValType::F64 => Ok(InterfaceType::Float64),
459            wasmparser::PrimitiveValType::Char => Ok(InterfaceType::Char),
460            wasmparser::PrimitiveValType::String => Ok(InterfaceType::String),
461            wasmparser::PrimitiveValType::ErrorContext => Ok(InterfaceType::ErrorContext(
462                self.error_context_table_type()?,
463            )),
464        }
465    }
466
467    fn record_type(&mut self, types: TypesRef<'_>, ty: &RecordType) -> Result<TypeRecordIndex> {
468        assert_eq!(types.id(), self.module_types.validator_id());
469        let fields = ty
470            .fields
471            .iter()
472            .map(|(name, ty)| {
473                Ok(RecordField {
474                    name: name.to_string(),
475                    ty: self.valtype(types, ty)?,
476                })
477            })
478            .collect::<Result<Box<[_]>>>()?;
479        let abi = CanonicalAbiInfo::record(
480            fields
481                .iter()
482                .map(|field| self.component_types.canonical_abi(&field.ty)),
483        );
484        Ok(self.add_record_type(TypeRecord { fields, abi }))
485    }
486
487    fn variant_type(&mut self, types: TypesRef<'_>, ty: &VariantType) -> Result<TypeVariantIndex> {
488        assert_eq!(types.id(), self.module_types.validator_id());
489        let cases = ty
490            .cases
491            .iter()
492            .map(|(name, case)| {
493                // FIXME: need to implement `refines`, not sure what that
494                // is at this time.
495                if case.refines.is_some() {
496                    bail!("refines is not supported at this time");
497                }
498                Ok((
499                    name.to_string(),
500                    match &case.ty.as_ref() {
501                        Some(ty) => Some(self.valtype(types, ty)?),
502                        None => None,
503                    },
504                ))
505            })
506            .collect::<Result<IndexMap<_, _>>>()?;
507        let (info, abi) = VariantInfo::new(
508            cases
509                .iter()
510                .map(|(_, c)| c.as_ref().map(|ty| self.component_types.canonical_abi(ty))),
511        );
512        Ok(self.add_variant_type(TypeVariant { cases, abi, info }))
513    }
514
515    fn tuple_type(&mut self, types: TypesRef<'_>, ty: &TupleType) -> Result<TypeTupleIndex> {
516        assert_eq!(types.id(), self.module_types.validator_id());
517        let types = ty
518            .types
519            .iter()
520            .map(|ty| self.valtype(types, ty))
521            .collect::<Result<Box<[_]>>>()?;
522        Ok(self.new_tuple_type(types))
523    }
524
525    pub(crate) fn new_tuple_type(&mut self, types: Box<[InterfaceType]>) -> TypeTupleIndex {
526        let abi = CanonicalAbiInfo::record(
527            types
528                .iter()
529                .map(|ty| self.component_types.canonical_abi(ty)),
530        );
531        self.add_tuple_type(TypeTuple { types, abi })
532    }
533
534    fn flags_type(&mut self, flags: &IndexSet<KebabString>) -> TypeFlagsIndex {
535        let flags = TypeFlags {
536            names: flags.iter().map(|s| s.to_string()).collect(),
537            abi: CanonicalAbiInfo::flags(flags.len()),
538        };
539        self.add_flags_type(flags)
540    }
541
542    fn enum_type(&mut self, variants: &IndexSet<KebabString>) -> TypeEnumIndex {
543        let names = variants
544            .iter()
545            .map(|s| s.to_string())
546            .collect::<IndexSet<_>>();
547        let (info, abi) = VariantInfo::new(names.iter().map(|_| None));
548        self.add_enum_type(TypeEnum { names, abi, info })
549    }
550
551    fn option_type(
552        &mut self,
553        types: TypesRef<'_>,
554        ty: &ComponentValType,
555    ) -> Result<TypeOptionIndex> {
556        assert_eq!(types.id(), self.module_types.validator_id());
557        let ty = self.valtype(types, ty)?;
558        let (info, abi) = VariantInfo::new([None, Some(self.component_types.canonical_abi(&ty))]);
559        Ok(self.add_option_type(TypeOption { ty, abi, info }))
560    }
561
562    fn result_type(
563        &mut self,
564        types: TypesRef<'_>,
565        ok: &Option<ComponentValType>,
566        err: &Option<ComponentValType>,
567    ) -> Result<TypeResultIndex> {
568        assert_eq!(types.id(), self.module_types.validator_id());
569        let ok = match ok {
570            Some(ty) => Some(self.valtype(types, ty)?),
571            None => None,
572        };
573        let err = match err {
574            Some(ty) => Some(self.valtype(types, ty)?),
575            None => None,
576        };
577        let (info, abi) = VariantInfo::new([
578            ok.as_ref().map(|t| self.component_types.canonical_abi(t)),
579            err.as_ref().map(|t| self.component_types.canonical_abi(t)),
580        ]);
581        Ok(self.add_result_type(TypeResult { ok, err, abi, info }))
582    }
583
584    fn future_table_type(
585        &mut self,
586        types: TypesRef<'_>,
587        ty: &Option<ComponentValType>,
588    ) -> Result<TypeFutureTableIndex> {
589        let payload = ty.as_ref().map(|ty| self.valtype(types, ty)).transpose()?;
590        let ty = self.add_future_type(TypeFuture { payload });
591        Ok(self.add_future_table_type(TypeFutureTable {
592            ty,
593            instance: self.resources.get_current_instance().unwrap(),
594        }))
595    }
596
597    fn stream_table_type(
598        &mut self,
599        types: TypesRef<'_>,
600        ty: &Option<ComponentValType>,
601    ) -> Result<TypeStreamTableIndex> {
602        let payload = ty.as_ref().map(|ty| self.valtype(types, ty)).transpose()?;
603        let ty = self.add_stream_type(TypeStream { payload });
604        Ok(self.add_stream_table_type(TypeStreamTable {
605            ty,
606            instance: self.resources.get_current_instance().unwrap(),
607        }))
608    }
609
610    /// Retrieve Wasmtime's type representation of the `error-context` type from
611    /// the point of view of the current component instance.
612    pub fn error_context_table_type(&mut self) -> Result<TypeComponentLocalErrorContextTableIndex> {
613        Ok(self.add_error_context_table_type(TypeErrorContextTable {
614            instance: self.resources.get_current_instance().unwrap(),
615        }))
616    }
617
618    fn list_type(&mut self, types: TypesRef<'_>, ty: &ComponentValType) -> Result<TypeListIndex> {
619        assert_eq!(types.id(), self.module_types.validator_id());
620        let element = self.valtype(types, ty)?;
621        Ok(self.add_list_type(TypeList { element }))
622    }
623
624    /// Converts a wasmparser `id`, which must point to a resource, to its
625    /// corresponding `TypeResourceTableIndex`.
626    pub fn resource_id(&mut self, id: ResourceId) -> TypeResourceTableIndex {
627        self.resources.convert(id, &mut self.component_types)
628    }
629
630    /// Interns a new function type within this type information.
631    pub fn add_func_type(&mut self, ty: TypeFunc) -> TypeFuncIndex {
632        intern(&mut self.functions, &mut self.component_types.functions, ty)
633    }
634
635    /// Interns a new record type within this type information.
636    pub fn add_record_type(&mut self, ty: TypeRecord) -> TypeRecordIndex {
637        intern_and_fill_flat_types!(self, records, ty)
638    }
639
640    /// Interns a new flags type within this type information.
641    pub fn add_flags_type(&mut self, ty: TypeFlags) -> TypeFlagsIndex {
642        intern_and_fill_flat_types!(self, flags, ty)
643    }
644
645    /// Interns a new tuple type within this type information.
646    pub fn add_tuple_type(&mut self, ty: TypeTuple) -> TypeTupleIndex {
647        intern_and_fill_flat_types!(self, tuples, ty)
648    }
649
650    /// Interns a new variant type within this type information.
651    pub fn add_variant_type(&mut self, ty: TypeVariant) -> TypeVariantIndex {
652        intern_and_fill_flat_types!(self, variants, ty)
653    }
654
655    /// Interns a new enum type within this type information.
656    pub fn add_enum_type(&mut self, ty: TypeEnum) -> TypeEnumIndex {
657        intern_and_fill_flat_types!(self, enums, ty)
658    }
659
660    /// Interns a new option type within this type information.
661    pub fn add_option_type(&mut self, ty: TypeOption) -> TypeOptionIndex {
662        intern_and_fill_flat_types!(self, options, ty)
663    }
664
665    /// Interns a new result type within this type information.
666    pub fn add_result_type(&mut self, ty: TypeResult) -> TypeResultIndex {
667        intern_and_fill_flat_types!(self, results, ty)
668    }
669
670    /// Interns a new list type within this type information.
671    pub fn add_list_type(&mut self, ty: TypeList) -> TypeListIndex {
672        intern_and_fill_flat_types!(self, lists, ty)
673    }
674
675    /// Interns a new future type within this type information.
676    pub fn add_future_type(&mut self, ty: TypeFuture) -> TypeFutureIndex {
677        intern(&mut self.futures, &mut self.component_types.futures, ty)
678    }
679
680    /// Interns a new future table type within this type information.
681    pub fn add_future_table_type(&mut self, ty: TypeFutureTable) -> TypeFutureTableIndex {
682        intern(
683            &mut self.future_tables,
684            &mut self.component_types.future_tables,
685            ty,
686        )
687    }
688
689    /// Interns a new stream type within this type information.
690    pub fn add_stream_type(&mut self, ty: TypeStream) -> TypeStreamIndex {
691        intern(&mut self.streams, &mut self.component_types.streams, ty)
692    }
693
694    /// Interns a new stream table type within this type information.
695    pub fn add_stream_table_type(&mut self, ty: TypeStreamTable) -> TypeStreamTableIndex {
696        intern(
697            &mut self.stream_tables,
698            &mut self.component_types.stream_tables,
699            ty,
700        )
701    }
702
703    /// Interns a new error context table type within this type information.
704    pub fn add_error_context_table_type(
705        &mut self,
706        ty: TypeErrorContextTable,
707    ) -> TypeComponentLocalErrorContextTableIndex {
708        intern(
709            &mut self.error_context_tables,
710            &mut self.component_types.error_context_tables,
711            ty,
712        )
713    }
714
715    /// Returns the canonical ABI information about the specified type.
716    pub fn canonical_abi(&self, ty: &InterfaceType) -> &CanonicalAbiInfo {
717        self.component_types.canonical_abi(ty)
718    }
719
720    /// Returns the "flat types" for the given interface type used in the
721    /// canonical ABI.
722    ///
723    /// Returns `None` if the type is too large to be represented via flat types
724    /// in the canonical abi.
725    pub fn flat_types(&self, ty: &InterfaceType) -> Option<FlatTypes<'_>> {
726        self.type_information(ty).flat.as_flat_types()
727    }
728
729    /// Returns whether the type specified contains any borrowed resources
730    /// within it.
731    pub fn ty_contains_borrow_resource(&self, ty: &InterfaceType) -> bool {
732        self.type_information(ty).has_borrow
733    }
734
735    fn type_information(&self, ty: &InterfaceType) -> &TypeInformation {
736        match ty {
737            InterfaceType::U8
738            | InterfaceType::S8
739            | InterfaceType::Bool
740            | InterfaceType::U16
741            | InterfaceType::S16
742            | InterfaceType::U32
743            | InterfaceType::S32
744            | InterfaceType::Char
745            | InterfaceType::Own(_)
746            | InterfaceType::Future(_)
747            | InterfaceType::Stream(_)
748            | InterfaceType::ErrorContext(_) => {
749                static INFO: TypeInformation = TypeInformation::primitive(FlatType::I32);
750                &INFO
751            }
752            InterfaceType::Borrow(_) => {
753                static INFO: TypeInformation = {
754                    let mut info = TypeInformation::primitive(FlatType::I32);
755                    info.has_borrow = true;
756                    info
757                };
758                &INFO
759            }
760            InterfaceType::U64 | InterfaceType::S64 => {
761                static INFO: TypeInformation = TypeInformation::primitive(FlatType::I64);
762                &INFO
763            }
764            InterfaceType::Float32 => {
765                static INFO: TypeInformation = TypeInformation::primitive(FlatType::F32);
766                &INFO
767            }
768            InterfaceType::Float64 => {
769                static INFO: TypeInformation = TypeInformation::primitive(FlatType::F64);
770                &INFO
771            }
772            InterfaceType::String => {
773                static INFO: TypeInformation = TypeInformation::string();
774                &INFO
775            }
776
777            InterfaceType::List(i) => &self.type_info.lists[*i],
778            InterfaceType::Record(i) => &self.type_info.records[*i],
779            InterfaceType::Variant(i) => &self.type_info.variants[*i],
780            InterfaceType::Tuple(i) => &self.type_info.tuples[*i],
781            InterfaceType::Flags(i) => &self.type_info.flags[*i],
782            InterfaceType::Enum(i) => &self.type_info.enums[*i],
783            InterfaceType::Option(i) => &self.type_info.options[*i],
784            InterfaceType::Result(i) => &self.type_info.results[*i],
785        }
786    }
787}
788
789impl TypeConvert for ComponentTypesBuilder {
790    fn lookup_heap_type(&self, _index: wasmparser::UnpackedIndex) -> WasmHeapType {
791        panic!("heap types are not supported yet")
792    }
793
794    fn lookup_type_index(&self, _index: wasmparser::UnpackedIndex) -> EngineOrModuleTypeIndex {
795        panic!("typed references are not supported yet")
796    }
797}
798
799fn intern<T, U>(map: &mut HashMap<T, U>, list: &mut PrimaryMap<U, T>, item: T) -> U
800where
801    T: Hash + Clone + Eq,
802    U: Copy + EntityRef,
803{
804    if let Some(idx) = map.get(&item) {
805        return *idx;
806    }
807    let idx = list.push(item.clone());
808    map.insert(item, idx);
809    return idx;
810}
811
812struct FlatTypesStorage {
813    // This could be represented as `Vec<FlatType>` but on 64-bit architectures
814    // that's 24 bytes. Otherwise `FlatType` is 1 byte large and
815    // `MAX_FLAT_TYPES` is 16, so it should ideally be more space-efficient to
816    // use a flat array instead of a heap-based vector.
817    memory32: [FlatType; MAX_FLAT_TYPES],
818    memory64: [FlatType; MAX_FLAT_TYPES],
819
820    // Tracks the number of flat types pushed into this storage. If this is
821    // `MAX_FLAT_TYPES + 1` then this storage represents an un-reprsentable
822    // type in flat types.
823    len: u8,
824}
825
826impl FlatTypesStorage {
827    const fn new() -> FlatTypesStorage {
828        FlatTypesStorage {
829            memory32: [FlatType::I32; MAX_FLAT_TYPES],
830            memory64: [FlatType::I32; MAX_FLAT_TYPES],
831            len: 0,
832        }
833    }
834
835    fn as_flat_types(&self) -> Option<FlatTypes<'_>> {
836        let len = usize::from(self.len);
837        if len > MAX_FLAT_TYPES {
838            assert_eq!(len, MAX_FLAT_TYPES + 1);
839            None
840        } else {
841            Some(FlatTypes {
842                memory32: &self.memory32[..len],
843                memory64: &self.memory64[..len],
844            })
845        }
846    }
847
848    /// Pushes a new flat type into this list using `t32` for 32-bit memories
849    /// and `t64` for 64-bit memories.
850    ///
851    /// Returns whether the type was actually pushed or whether this list of
852    /// flat types just exceeded the maximum meaning that it is now
853    /// unrepresentable with a flat list of types.
854    fn push(&mut self, t32: FlatType, t64: FlatType) -> bool {
855        let len = usize::from(self.len);
856        if len < MAX_FLAT_TYPES {
857            self.memory32[len] = t32;
858            self.memory64[len] = t64;
859            self.len += 1;
860            true
861        } else {
862            // If this was the first one to go over then flag the length as
863            // being incompatible with a flat representation.
864            if len == MAX_FLAT_TYPES {
865                self.len += 1;
866            }
867            false
868        }
869    }
870}
871
872impl FlatType {
873    fn join(&mut self, other: FlatType) {
874        if *self == other {
875            return;
876        }
877        *self = match (*self, other) {
878            (FlatType::I32, FlatType::F32) | (FlatType::F32, FlatType::I32) => FlatType::I32,
879            _ => FlatType::I64,
880        };
881    }
882}
883
884#[derive(Default)]
885struct TypeInformationCache {
886    records: PrimaryMap<TypeRecordIndex, TypeInformation>,
887    variants: PrimaryMap<TypeVariantIndex, TypeInformation>,
888    tuples: PrimaryMap<TypeTupleIndex, TypeInformation>,
889    enums: PrimaryMap<TypeEnumIndex, TypeInformation>,
890    flags: PrimaryMap<TypeFlagsIndex, TypeInformation>,
891    options: PrimaryMap<TypeOptionIndex, TypeInformation>,
892    results: PrimaryMap<TypeResultIndex, TypeInformation>,
893    lists: PrimaryMap<TypeListIndex, TypeInformation>,
894}
895
896struct TypeInformation {
897    depth: u32,
898    flat: FlatTypesStorage,
899    has_borrow: bool,
900}
901
902impl TypeInformation {
903    const fn new() -> TypeInformation {
904        TypeInformation {
905            depth: 0,
906            flat: FlatTypesStorage::new(),
907            has_borrow: false,
908        }
909    }
910
911    const fn primitive(flat: FlatType) -> TypeInformation {
912        let mut info = TypeInformation::new();
913        info.depth = 1;
914        info.flat.memory32[0] = flat;
915        info.flat.memory64[0] = flat;
916        info.flat.len = 1;
917        info
918    }
919
920    const fn string() -> TypeInformation {
921        let mut info = TypeInformation::new();
922        info.depth = 1;
923        info.flat.memory32[0] = FlatType::I32;
924        info.flat.memory32[1] = FlatType::I32;
925        info.flat.memory64[0] = FlatType::I64;
926        info.flat.memory64[1] = FlatType::I64;
927        info.flat.len = 2;
928        info
929    }
930
931    /// Builds up all flat types internally using the specified representation
932    /// for all of the component fields of the record.
933    fn build_record<'a>(&mut self, types: impl Iterator<Item = &'a TypeInformation>) {
934        self.depth = 1;
935        for info in types {
936            self.depth = self.depth.max(1 + info.depth);
937            self.has_borrow = self.has_borrow || info.has_borrow;
938            match info.flat.as_flat_types() {
939                Some(types) => {
940                    for (t32, t64) in types.memory32.iter().zip(types.memory64) {
941                        if !self.flat.push(*t32, *t64) {
942                            break;
943                        }
944                    }
945                }
946                None => {
947                    self.flat.len = u8::try_from(MAX_FLAT_TYPES + 1).unwrap();
948                }
949            }
950        }
951    }
952
953    /// Builds up the flat types used to represent a `variant` which notably
954    /// handles "join"ing types together so each case is representable as a
955    /// single flat list of types.
956    ///
957    /// The iterator item is:
958    ///
959    /// * `None` - no payload for this case
960    /// * `Some(None)` - this case has a payload but can't be represented with
961    ///   flat types
962    /// * `Some(Some(types))` - this case has a payload and is represented with
963    ///   the types specified in the flat representation.
964    fn build_variant<'a, I>(&mut self, cases: I)
965    where
966        I: IntoIterator<Item = Option<&'a TypeInformation>>,
967    {
968        let cases = cases.into_iter();
969        self.flat.push(FlatType::I32, FlatType::I32);
970        self.depth = 1;
971
972        for info in cases {
973            let info = match info {
974                Some(info) => info,
975                // If this case doesn't have a payload then it doesn't change
976                // the depth/flat representation
977                None => continue,
978            };
979            self.depth = self.depth.max(1 + info.depth);
980            self.has_borrow = self.has_borrow || info.has_borrow;
981
982            // If this variant is already unrepresentable in a flat
983            // representation then this can be skipped.
984            if usize::from(self.flat.len) > MAX_FLAT_TYPES {
985                continue;
986            }
987
988            let types = match info.flat.as_flat_types() {
989                Some(types) => types,
990                // If this case isn't representable with a flat list of types
991                // then this variant also isn't representable.
992                None => {
993                    self.flat.len = u8::try_from(MAX_FLAT_TYPES + 1).unwrap();
994                    continue;
995                }
996            };
997            // If the case used all of the flat types then the discriminant
998            // added for this variant means that this variant is no longer
999            // representable.
1000            if types.memory32.len() >= MAX_FLAT_TYPES {
1001                self.flat.len = u8::try_from(MAX_FLAT_TYPES + 1).unwrap();
1002                continue;
1003            }
1004            let dst = self
1005                .flat
1006                .memory32
1007                .iter_mut()
1008                .zip(&mut self.flat.memory64)
1009                .skip(1);
1010            for (i, ((t32, t64), (dst32, dst64))) in types
1011                .memory32
1012                .iter()
1013                .zip(types.memory64)
1014                .zip(dst)
1015                .enumerate()
1016            {
1017                if i + 1 < usize::from(self.flat.len) {
1018                    // If this index hs already been set by some previous case
1019                    // then the types are joined together.
1020                    dst32.join(*t32);
1021                    dst64.join(*t64);
1022                } else {
1023                    // Otherwise if this is the first time that the
1024                    // representation has gotten this large then the destination
1025                    // is simply whatever the type is. The length is also
1026                    // increased here to indicate this.
1027                    self.flat.len += 1;
1028                    *dst32 = *t32;
1029                    *dst64 = *t64;
1030                }
1031            }
1032        }
1033    }
1034
1035    fn records(&mut self, types: &ComponentTypesBuilder, ty: &TypeRecord) {
1036        self.build_record(ty.fields.iter().map(|f| types.type_information(&f.ty)));
1037    }
1038
1039    fn tuples(&mut self, types: &ComponentTypesBuilder, ty: &TypeTuple) {
1040        self.build_record(ty.types.iter().map(|t| types.type_information(t)));
1041    }
1042
1043    fn enums(&mut self, _types: &ComponentTypesBuilder, _ty: &TypeEnum) {
1044        self.depth = 1;
1045        self.flat.push(FlatType::I32, FlatType::I32);
1046    }
1047
1048    fn flags(&mut self, _types: &ComponentTypesBuilder, ty: &TypeFlags) {
1049        self.depth = 1;
1050        match FlagsSize::from_count(ty.names.len()) {
1051            FlagsSize::Size0 => {}
1052            FlagsSize::Size1 | FlagsSize::Size2 => {
1053                self.flat.push(FlatType::I32, FlatType::I32);
1054            }
1055            FlagsSize::Size4Plus(n) => {
1056                for _ in 0..n {
1057                    self.flat.push(FlatType::I32, FlatType::I32);
1058                }
1059            }
1060        }
1061    }
1062
1063    fn variants(&mut self, types: &ComponentTypesBuilder, ty: &TypeVariant) {
1064        self.build_variant(
1065            ty.cases
1066                .iter()
1067                .map(|(_, c)| c.as_ref().map(|ty| types.type_information(ty))),
1068        )
1069    }
1070
1071    fn results(&mut self, types: &ComponentTypesBuilder, ty: &TypeResult) {
1072        self.build_variant([
1073            ty.ok.as_ref().map(|ty| types.type_information(ty)),
1074            ty.err.as_ref().map(|ty| types.type_information(ty)),
1075        ])
1076    }
1077
1078    fn options(&mut self, types: &ComponentTypesBuilder, ty: &TypeOption) {
1079        self.build_variant([None, Some(types.type_information(&ty.ty))]);
1080    }
1081
1082    fn lists(&mut self, types: &ComponentTypesBuilder, ty: &TypeList) {
1083        *self = TypeInformation::string();
1084        let info = types.type_information(&ty.element);
1085        self.depth += info.depth;
1086        self.has_borrow = info.has_borrow;
1087    }
1088}