use crate::StringEncoding;
use crate::metadata::{self, Bindgen, ModuleMetadata};
use crate::validation::{
Export, ExportMap, Import, ImportInstance, ImportMap, PayloadInfo, PayloadType,
};
use anyhow::{Context, Result, anyhow, bail};
use indexmap::{IndexMap, IndexSet};
use std::borrow::Cow;
use std::collections::HashMap;
use std::hash::Hash;
use std::mem;
use wasm_encoder::*;
use wasmparser::{Validator, WasmFeatures};
use wit_parser::{
Function, FunctionKind, InterfaceId, LiveTypes, Param, Resolve, Stability, Type, TypeDefKind,
TypeId, TypeOwner, WorldItem, WorldKey,
abi::{AbiVariant, WasmSignature, WasmType},
};
const INDIRECT_TABLE_NAME: &str = "$imports";
mod wit;
pub use wit::{encode, encode_world};
mod types;
use types::{InstanceTypeEncoder, RootTypeEncoder, TypeEncodingMaps, ValtypeEncoder};
mod world;
use world::{ComponentWorld, ImportedInterface, Lowering};
mod dedupe;
pub(crate) use dedupe::ModuleImportMap;
use wasm_metadata::AddMetadataField;
fn to_val_type(ty: &WasmType) -> ValType {
match ty {
WasmType::I32 => ValType::I32,
WasmType::I64 => ValType::I64,
WasmType::F32 => ValType::F32,
WasmType::F64 => ValType::F64,
WasmType::Pointer => ValType::I32,
WasmType::PointerOrI64 => ValType::I64,
WasmType::Length => ValType::I32,
}
}
fn import_func_name(f: &Function) -> String {
match f.kind {
FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
format!("import-func-{}", f.item_name())
}
FunctionKind::Method(_)
| FunctionKind::AsyncMethod(_)
| FunctionKind::Static(_)
| FunctionKind::AsyncStatic(_)
| FunctionKind::Constructor(_) => {
format!(
"import-{}",
f.name.replace('[', "").replace([']', '.', ' '], "-")
)
}
}
}
bitflags::bitflags! {
#[derive(Copy, Clone, Debug)]
pub struct RequiredOptions: u8 {
const MEMORY = 1 << 0;
const REALLOC = 1 << 1;
const STRING_ENCODING = 1 << 2;
const ASYNC = 1 << 3;
}
}
impl RequiredOptions {
fn for_import(resolve: &Resolve, func: &Function, abi: AbiVariant) -> RequiredOptions {
let sig = resolve.wasm_signature(abi, func);
let mut ret = RequiredOptions::empty();
ret.add_lift(TypeContents::for_types(
resolve,
func.params.iter().map(|p| &p.ty),
));
ret.add_lower(TypeContents::for_types(resolve, &func.result));
if sig.retptr || sig.indirect_params {
ret |= RequiredOptions::MEMORY;
}
if abi == AbiVariant::GuestImportAsync {
ret |= RequiredOptions::ASYNC;
}
ret
}
fn for_export(resolve: &Resolve, func: &Function, abi: AbiVariant) -> RequiredOptions {
let sig = resolve.wasm_signature(abi, func);
let mut ret = RequiredOptions::empty();
ret.add_lower(TypeContents::for_types(
resolve,
func.params.iter().map(|p| &p.ty),
));
ret.add_lift(TypeContents::for_types(resolve, &func.result));
if sig.retptr || sig.indirect_params {
ret |= RequiredOptions::MEMORY;
if sig.indirect_params {
ret |= RequiredOptions::REALLOC;
}
}
if let AbiVariant::GuestExportAsync | AbiVariant::GuestExportAsyncStackful = abi {
ret |= RequiredOptions::ASYNC;
ret |= task_return_options_and_type(resolve, func).0;
}
ret
}
fn add_lower(&mut self, types: TypeContents) {
if types.contains(TypeContents::NEEDS_MEMORY) {
*self |= RequiredOptions::MEMORY | RequiredOptions::REALLOC;
}
if types.contains(TypeContents::STRING) {
*self |= RequiredOptions::MEMORY
| RequiredOptions::STRING_ENCODING
| RequiredOptions::REALLOC;
}
}
fn add_lift(&mut self, types: TypeContents) {
if types.contains(TypeContents::NEEDS_MEMORY) {
*self |= RequiredOptions::MEMORY;
}
if types.contains(TypeContents::STRING) {
*self |= RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING;
}
}
fn into_iter(
self,
encoding: StringEncoding,
memory_index: Option<u32>,
realloc_index: Option<u32>,
) -> Result<impl ExactSizeIterator<Item = CanonicalOption>> {
#[derive(Default)]
struct Iter {
options: [Option<CanonicalOption>; 5],
current: usize,
count: usize,
}
impl Iter {
fn push(&mut self, option: CanonicalOption) {
assert!(self.count < self.options.len());
self.options[self.count] = Some(option);
self.count += 1;
}
}
impl Iterator for Iter {
type Item = CanonicalOption;
fn next(&mut self) -> Option<Self::Item> {
if self.current == self.count {
return None;
}
let option = self.options[self.current];
self.current += 1;
option
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.count - self.current, Some(self.count - self.current))
}
}
impl ExactSizeIterator for Iter {}
let mut iter = Iter::default();
if self.contains(RequiredOptions::MEMORY) {
iter.push(CanonicalOption::Memory(memory_index.ok_or_else(|| {
anyhow!("module does not export a memory named `memory`")
})?));
}
if self.contains(RequiredOptions::REALLOC) {
iter.push(CanonicalOption::Realloc(realloc_index.ok_or_else(
|| anyhow!("module does not export a function named `cabi_realloc`"),
)?));
}
if self.contains(RequiredOptions::STRING_ENCODING) {
iter.push(encoding.into());
}
if self.contains(RequiredOptions::ASYNC) {
iter.push(CanonicalOption::Async);
}
Ok(iter)
}
}
bitflags::bitflags! {
struct TypeContents: u8 {
const STRING = 1 << 0;
const NEEDS_MEMORY = 1 << 1;
}
}
impl TypeContents {
fn for_types<'a>(resolve: &Resolve, types: impl IntoIterator<Item = &'a Type>) -> Self {
let mut cur = TypeContents::empty();
for ty in types {
cur |= Self::for_type(resolve, ty);
}
cur
}
fn for_optional_types<'a>(
resolve: &Resolve,
types: impl Iterator<Item = Option<&'a Type>>,
) -> Self {
Self::for_types(resolve, types.flatten())
}
fn for_optional_type(resolve: &Resolve, ty: Option<&Type>) -> Self {
match ty {
Some(ty) => Self::for_type(resolve, ty),
None => Self::empty(),
}
}
fn for_type(resolve: &Resolve, ty: &Type) -> Self {
match ty {
Type::Id(id) => match &resolve.types[*id].kind {
TypeDefKind::Handle(h) => match h {
wit_parser::Handle::Own(_) => Self::empty(),
wit_parser::Handle::Borrow(_) => Self::empty(),
},
TypeDefKind::Resource => Self::empty(),
TypeDefKind::Record(r) => Self::for_types(resolve, r.fields.iter().map(|f| &f.ty)),
TypeDefKind::Tuple(t) => Self::for_types(resolve, t.types.iter()),
TypeDefKind::Flags(_) => Self::empty(),
TypeDefKind::Option(t) => Self::for_type(resolve, t),
TypeDefKind::Result(r) => {
Self::for_optional_type(resolve, r.ok.as_ref())
| Self::for_optional_type(resolve, r.err.as_ref())
}
TypeDefKind::Variant(v) => {
Self::for_optional_types(resolve, v.cases.iter().map(|c| c.ty.as_ref()))
}
TypeDefKind::Enum(_) => Self::empty(),
TypeDefKind::List(t) => Self::for_type(resolve, t) | Self::NEEDS_MEMORY,
TypeDefKind::Map(k, v) => {
Self::for_type(resolve, k) | Self::for_type(resolve, v) | Self::NEEDS_MEMORY
}
TypeDefKind::FixedLengthList(t, _elements) => Self::for_type(resolve, t),
TypeDefKind::Type(t) => Self::for_type(resolve, t),
TypeDefKind::Future(_) => Self::empty(),
TypeDefKind::Stream(_) => Self::empty(),
TypeDefKind::Unknown => unreachable!(),
},
Type::String => Self::STRING,
_ => Self::empty(),
}
}
}
pub struct EncodingState<'a> {
component: ComponentBuilder,
module_index: Option<u32>,
instance_index: Option<u32>,
memory_index: Option<u32>,
shim_instance_index: Option<u32>,
fixups_module_index: Option<u32>,
adapter_modules: IndexMap<&'a str, u32>,
adapter_instances: IndexMap<&'a str, u32>,
imported_instances: IndexMap<InterfaceId, u32>,
imported_funcs: IndexMap<String, u32>,
exported_instances: IndexMap<InterfaceId, u32>,
import_type_encoding_maps: TypeEncodingMaps<'a>,
export_type_encoding_maps: TypeEncodingMaps<'a>,
aliased_core_items: HashMap<(u32, String), u32>,
info: &'a ComponentWorld<'a>,
export_task_initialization_wrappers: HashMap<String, u32>,
}
impl<'a> EncodingState<'a> {
fn encode_core_modules(&mut self) {
assert!(self.module_index.is_none());
let idx = self
.component
.core_module_raw(Some("main"), &self.info.encoder.module);
self.module_index = Some(idx);
for (name, adapter) in self.info.adapters.iter() {
let debug_name = if adapter.library_info.is_some() {
name.to_string()
} else {
format!("wit-component:adapter:{name}")
};
let idx = if self.info.encoder.debug_names {
let mut add_meta = wasm_metadata::AddMetadata::default();
add_meta.name = AddMetadataField::Set(debug_name.clone());
let wasm = add_meta
.to_wasm(&adapter.wasm)
.expect("core wasm can get name added");
self.component.core_module_raw(Some(&debug_name), &wasm)
} else {
self.component
.core_module_raw(Some(&debug_name), &adapter.wasm)
};
let prev = self.adapter_modules.insert(name, idx);
assert!(prev.is_none());
}
}
fn root_import_type_encoder(
&mut self,
interface: Option<InterfaceId>,
) -> RootTypeEncoder<'_, 'a> {
RootTypeEncoder {
state: self,
interface,
import_types: true,
}
}
fn root_export_type_encoder(
&mut self,
interface: Option<InterfaceId>,
) -> RootTypeEncoder<'_, 'a> {
RootTypeEncoder {
state: self,
interface,
import_types: false,
}
}
fn instance_type_encoder(&mut self, interface: InterfaceId) -> InstanceTypeEncoder<'_, 'a> {
InstanceTypeEncoder {
state: self,
interface,
type_encoding_maps: Default::default(),
ty: Default::default(),
}
}
fn encode_imports(&mut self, name_map: &HashMap<String, String>) -> Result<()> {
let mut has_funcs = false;
for (name, info) in self.info.import_map.iter() {
match name {
Some(name) => {
self.encode_interface_import(name_map.get(name).unwrap_or(name), info)?
}
None => has_funcs = true,
}
}
let resolve = &self.info.encoder.metadata.resolve;
let world = &resolve.worlds[self.info.encoder.metadata.world];
for (_name, item) in world.imports.iter() {
if let WorldItem::Type { id, .. } = item {
self.root_import_type_encoder(None)
.encode_valtype(resolve, &Type::Id(*id))?;
}
}
if has_funcs {
let info = &self.info.import_map[&None];
self.encode_root_import_funcs(info)?;
}
Ok(())
}
fn encode_interface_import(&mut self, name: &str, info: &ImportedInterface) -> Result<()> {
let resolve = &self.info.encoder.metadata.resolve;
let interface_id = info.interface.as_ref().unwrap();
let interface_id = *interface_id;
let interface = &resolve.interfaces[interface_id];
log::trace!("encoding imports for `{name}` as {interface_id:?}");
let mut encoder = self.instance_type_encoder(interface_id);
if let Some(live) = encoder.state.info.live_type_imports.get(&interface_id) {
for ty in live {
log::trace!(
"encoding extra type {ty:?} name={:?}",
resolve.types[*ty].name
);
encoder.encode_valtype(resolve, &Type::Id(*ty))?;
}
}
for (_, func) in interface.functions.iter() {
if !(info
.lowerings
.contains_key(&(func.name.clone(), AbiVariant::GuestImport))
|| info
.lowerings
.contains_key(&(func.name.clone(), AbiVariant::GuestImportAsync)))
{
continue;
}
log::trace!("encoding function type for `{}`", func.name);
let idx = encoder.encode_func_type(resolve, func)?;
encoder.ty.export(&func.name, ComponentTypeRef::Func(idx));
}
let ty = encoder.ty;
if ty.is_empty() {
return Ok(());
}
let instance_type_idx = self
.component
.type_instance(Some(&format!("ty-{name}")), &ty);
let instance_idx = self
.component
.import(name, ComponentTypeRef::Instance(instance_type_idx));
let prev = self.imported_instances.insert(interface_id, instance_idx);
assert!(prev.is_none());
Ok(())
}
fn encode_root_import_funcs(&mut self, info: &ImportedInterface) -> Result<()> {
let resolve = &self.info.encoder.metadata.resolve;
let world = self.info.encoder.metadata.world;
for (name, item) in resolve.worlds[world].imports.iter() {
let func = match item {
WorldItem::Function(f) => f,
WorldItem::Interface { .. } | WorldItem::Type { .. } => continue,
};
let name = resolve.name_world_key(name);
if !(info
.lowerings
.contains_key(&(name.clone(), AbiVariant::GuestImport))
|| info
.lowerings
.contains_key(&(name.clone(), AbiVariant::GuestImportAsync)))
{
continue;
}
log::trace!("encoding function type for `{}`", func.name);
let idx = self
.root_import_type_encoder(None)
.encode_func_type(resolve, func)?;
let func_idx = self.component.import(&name, ComponentTypeRef::Func(idx));
let prev = self.imported_funcs.insert(name, func_idx);
assert!(prev.is_none());
}
Ok(())
}
fn alias_imported_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 {
let ty = &self.info.encoder.metadata.resolve.types[id];
let name = ty.name.as_ref().expect("type must have a name");
let instance = self.imported_instances[&interface];
self.component
.alias_export(instance, name, ComponentExportKind::Type)
}
fn alias_exported_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 {
let ty = &self.info.encoder.metadata.resolve.types[id];
let name = ty.name.as_ref().expect("type must have a name");
let instance = self.exported_instances[&interface];
self.component
.alias_export(instance, name, ComponentExportKind::Type)
}
fn encode_core_instantiation(&mut self) -> Result<()> {
let shims = self.encode_shim_instantiation()?;
self.declare_types_for_imported_intrinsics(&shims)?;
self.instantiate_main_module(&shims)?;
self.create_export_task_initialization_wrappers()?;
let (before, after) = self
.info
.adapters
.iter()
.partition::<Vec<_>, _>(|(_, adapter)| {
!matches!(
adapter.library_info,
Some(LibraryInfo {
instantiate_after_shims: true,
..
})
)
});
for (name, _adapter) in before {
self.instantiate_adapter_module(&shims, name)?;
}
self.encode_indirect_lowerings(&shims)?;
for (name, _adapter) in after {
self.instantiate_adapter_module(&shims, name)?;
}
self.encode_initialize_with_start()?;
Ok(())
}
fn lookup_resource_index(&mut self, id: TypeId) -> u32 {
let resolve = &self.info.encoder.metadata.resolve;
let ty = &resolve.types[id];
match ty.owner {
TypeOwner::World(_) => self.import_type_encoding_maps.id_to_index[&id],
TypeOwner::Interface(i) => {
let instance = self.imported_instances[&i];
let name = ty.name.as_ref().expect("resources must be named");
self.component
.alias_export(instance, name, ComponentExportKind::Type)
}
TypeOwner::None => panic!("resources must have an owner"),
}
}
fn encode_exports(&mut self, module: CustomModule) -> Result<()> {
let resolve = &self.info.encoder.metadata.resolve;
let exports = match module {
CustomModule::Main => &self.info.encoder.main_module_exports,
CustomModule::Adapter(name) => &self.info.encoder.adapters[name].required_exports,
};
if exports.is_empty() {
return Ok(());
}
let mut interface_func_core_names = IndexMap::new();
let mut world_func_core_names = IndexMap::new();
for (core_name, export) in self.info.exports_for(module).iter() {
match export {
Export::WorldFunc(_, name, _) => {
let prev = world_func_core_names.insert(name, core_name);
assert!(prev.is_none());
}
Export::InterfaceFunc(_, id, name, _) => {
let prev = interface_func_core_names
.entry(id)
.or_insert(IndexMap::new())
.insert(name.as_str(), core_name);
assert!(prev.is_none());
}
Export::WorldFuncCallback(..)
| Export::InterfaceFuncCallback(..)
| Export::WorldFuncPostReturn(..)
| Export::InterfaceFuncPostReturn(..)
| Export::ResourceDtor(..)
| Export::Memory
| Export::GeneralPurposeRealloc
| Export::GeneralPurposeExportRealloc
| Export::GeneralPurposeImportRealloc
| Export::Initialize
| Export::ReallocForAdapter
| Export::IndirectFunctionTable
| Export::WasmInitTask
| Export::WasmInitAsyncTask => continue,
}
}
let world = &resolve.worlds[self.info.encoder.metadata.world];
for export_name in exports {
let export_string = resolve.name_world_key(export_name);
match &world.exports[export_name] {
WorldItem::Function(func) => {
let ty = self
.root_import_type_encoder(None)
.encode_func_type(resolve, func)?;
let core_name = world_func_core_names[&func.name];
let idx = self.encode_lift(module, &core_name, export_name, func, ty)?;
self.component
.export(&export_string, ComponentExportKind::Func, idx, None);
}
WorldItem::Interface { id, .. } => {
let core_names = interface_func_core_names.get(id);
self.encode_interface_export(
&export_string,
module,
export_name,
*id,
core_names,
)?;
}
WorldItem::Type { .. } => unreachable!(),
}
}
Ok(())
}
fn encode_interface_export(
&mut self,
export_name: &str,
module: CustomModule<'_>,
key: &WorldKey,
export: InterfaceId,
interface_func_core_names: Option<&IndexMap<&str, &str>>,
) -> Result<()> {
log::trace!("encode interface export `{export_name}`");
let resolve = &self.info.encoder.metadata.resolve;
let mut imports = Vec::new();
let mut root = self.root_export_type_encoder(Some(export));
for (_, func) in &resolve.interfaces[export].functions {
let core_name = interface_func_core_names.unwrap()[func.name.as_str()];
let ty = root.encode_func_type(resolve, func)?;
let func_index = root.state.encode_lift(module, &core_name, key, func, ty)?;
imports.push((
import_func_name(func),
ComponentExportKind::Func,
func_index,
));
}
let mut nested = NestedComponentTypeEncoder {
component: ComponentBuilder::default(),
type_encoding_maps: Default::default(),
export_types: false,
interface: export,
state: self,
imports: IndexMap::new(),
};
let mut types_to_import = LiveTypes::default();
types_to_import.add_interface(resolve, export);
let exports_used = &nested.state.info.exports_used[&export];
for ty in types_to_import.iter() {
if let TypeOwner::Interface(owner) = resolve.types[ty].owner {
if owner == export {
continue;
}
let mut encoder = if exports_used.contains(&owner) {
nested.state.root_export_type_encoder(Some(export))
} else {
nested.state.root_import_type_encoder(Some(export))
};
encoder.encode_valtype(resolve, &Type::Id(ty))?;
nested.interface = owner;
nested.encode_valtype(resolve, &Type::Id(ty))?;
}
}
nested.interface = export;
let imported_type_maps = nested.type_encoding_maps.clone();
let mut resources = HashMap::new();
for (_name, ty) in resolve.interfaces[export].types.iter() {
if !matches!(resolve.types[*ty].kind, TypeDefKind::Resource) {
continue;
}
let idx = match nested.encode_valtype(resolve, &Type::Id(*ty))? {
ComponentValType::Type(idx) => idx,
_ => unreachable!(),
};
resources.insert(*ty, idx);
}
for (_, func) in resolve.interfaces[export].functions.iter() {
let ty = nested.encode_func_type(resolve, func)?;
nested
.component
.import(&import_func_name(func), ComponentTypeRef::Func(ty));
}
let reverse_map = nested
.type_encoding_maps
.id_to_index
.drain()
.map(|p| (p.1, p.0))
.collect::<HashMap<_, _>>();
nested.type_encoding_maps.def_to_index.clear();
for (name, idx) in nested.imports.drain(..) {
let id = reverse_map[&idx];
let owner = match resolve.types[id].owner {
TypeOwner::Interface(id) => id,
_ => unreachable!(),
};
let idx = if owner == export || exports_used.contains(&owner) {
log::trace!("consulting exports for {id:?}");
nested.state.export_type_encoding_maps.id_to_index[&id]
} else {
log::trace!("consulting imports for {id:?}");
nested.state.import_type_encoding_maps.id_to_index[&id]
};
imports.push((name, ComponentExportKind::Type, idx))
}
nested.type_encoding_maps = imported_type_maps;
nested.export_types = true;
nested.type_encoding_maps.func_type_map.clear();
for (_, id) in resolve.interfaces[export].types.iter() {
let ty = &resolve.types[*id];
match ty.kind {
TypeDefKind::Resource => {
let idx = nested.component.export(
ty.name.as_ref().expect("resources must be named"),
ComponentExportKind::Type,
resources[id],
None,
);
nested.type_encoding_maps.id_to_index.insert(*id, idx);
}
_ => {
nested.encode_valtype(resolve, &Type::Id(*id))?;
}
}
}
for (i, (_, func)) in resolve.interfaces[export].functions.iter().enumerate() {
let ty = nested.encode_func_type(resolve, func)?;
nested.component.export(
&func.name,
ComponentExportKind::Func,
i as u32,
Some(ComponentTypeRef::Func(ty)),
);
}
let component = nested.component;
let component_index = self
.component
.component(Some(&format!("{export_name}-shim-component")), component);
let instance_index = self.component.instantiate(
Some(&format!("{export_name}-shim-instance")),
component_index,
imports,
);
let idx = self.component.export(
export_name,
ComponentExportKind::Instance,
instance_index,
None,
);
let prev = self.exported_instances.insert(export, idx);
assert!(prev.is_none());
for (_name, id) in resolve.interfaces[export].types.iter() {
self.export_type_encoding_maps.id_to_index.remove(id);
self.export_type_encoding_maps
.def_to_index
.remove(&resolve.types[*id].kind);
}
return Ok(());
struct NestedComponentTypeEncoder<'state, 'a> {
component: ComponentBuilder,
type_encoding_maps: TypeEncodingMaps<'a>,
export_types: bool,
interface: InterfaceId,
state: &'state mut EncodingState<'a>,
imports: IndexMap<String, u32>,
}
impl<'a> ValtypeEncoder<'a> for NestedComponentTypeEncoder<'_, 'a> {
fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) {
self.component.type_defined(None)
}
fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) {
self.component.type_function(None)
}
fn export_type(&mut self, idx: u32, name: &'a str) -> Option<u32> {
if self.export_types {
Some(
self.component
.export(name, ComponentExportKind::Type, idx, None),
)
} else {
let name = self.unique_import_name(name);
let ret = self
.component
.import(&name, ComponentTypeRef::Type(TypeBounds::Eq(idx)));
self.imports.insert(name, ret);
Some(ret)
}
}
fn export_resource(&mut self, name: &'a str) -> u32 {
if self.export_types {
panic!("resources should already be exported")
} else {
let name = self.unique_import_name(name);
let ret = self
.component
.import(&name, ComponentTypeRef::Type(TypeBounds::SubResource));
self.imports.insert(name, ret);
ret
}
}
fn import_type(&mut self, _: InterfaceId, _id: TypeId) -> u32 {
unreachable!()
}
fn type_encoding_maps(&mut self) -> &mut TypeEncodingMaps<'a> {
&mut self.type_encoding_maps
}
fn interface(&self) -> Option<InterfaceId> {
Some(self.interface)
}
}
impl NestedComponentTypeEncoder<'_, '_> {
fn unique_import_name(&mut self, name: &str) -> String {
let mut name = format!("import-type-{name}");
let mut n = 0;
while self.imports.contains_key(&name) {
name = format!("{name}{n}");
n += 1;
}
name
}
}
}
fn encode_lift(
&mut self,
module: CustomModule<'_>,
core_name: &str,
key: &WorldKey,
func: &Function,
ty: u32,
) -> Result<u32> {
let resolve = &self.info.encoder.metadata.resolve;
let metadata = self.info.module_metadata_for(module);
let instance_index = self.instance_for(module);
let core_func_index =
if let Some(&wrapper_idx) = self.export_task_initialization_wrappers.get(core_name) {
wrapper_idx
} else {
self.core_alias_export(Some(core_name), instance_index, core_name, ExportKind::Func)
};
let exports = self.info.exports_for(module);
let options = RequiredOptions::for_export(
resolve,
func,
exports
.abi(key, func)
.ok_or_else(|| anyhow!("no ABI found for {}", func.name))?,
);
let encoding = metadata
.export_encodings
.get(resolve, key, &func.name)
.unwrap();
let exports = self.info.exports_for(module);
let realloc_index = exports
.export_realloc_for(key, &func.name)
.map(|name| self.core_alias_export(Some(name), instance_index, name, ExportKind::Func));
let mut options = options
.into_iter(encoding, self.memory_index, realloc_index)?
.collect::<Vec<_>>();
if let Some(post_return) = exports.post_return(key, func) {
let post_return = self.core_alias_export(
Some(post_return),
instance_index,
post_return,
ExportKind::Func,
);
options.push(CanonicalOption::PostReturn(post_return));
}
if let Some(callback) = exports.callback(key, func) {
let callback =
self.core_alias_export(Some(callback), instance_index, callback, ExportKind::Func);
options.push(CanonicalOption::Callback(callback));
}
let func_index = self
.component
.lift_func(Some(&func.name), core_func_index, ty, options);
Ok(func_index)
}
fn encode_shim_instantiation(&mut self) -> Result<Shims<'a>> {
let mut ret = Shims::default();
ret.append_indirect(self.info, CustomModule::Main)
.context("failed to register indirect shims for main module")?;
for (adapter_name, _adapter) in self.info.adapters.iter() {
ret.append_indirect(self.info, CustomModule::Adapter(adapter_name))
.with_context(|| {
format!("failed to register indirect shims for adapter {adapter_name}")
})?;
}
if ret.shims.is_empty() {
return Ok(ret);
}
assert!(self.shim_instance_index.is_none());
assert!(self.fixups_module_index.is_none());
let mut types = TypeSection::new();
let mut tables = TableSection::new();
let mut functions = FunctionSection::new();
let mut exports = ExportSection::new();
let mut code = CodeSection::new();
let mut sigs = IndexMap::new();
let mut imports_section = ImportSection::new();
let mut elements = ElementSection::new();
let mut func_indexes = Vec::new();
let mut func_names = NameMap::new();
for (i, shim) in ret.shims.values().enumerate() {
let i = i as u32;
let type_index = *sigs.entry(&shim.sig).or_insert_with(|| {
let index = types.len();
types.ty().function(
shim.sig.params.iter().map(to_val_type),
shim.sig.results.iter().map(to_val_type),
);
index
});
functions.function(type_index);
Self::encode_shim_function(type_index, i, &mut code, shim.sig.params.len() as u32);
exports.export(&shim.name, ExportKind::Func, i);
imports_section.import("", &shim.name, EntityType::Function(type_index));
func_indexes.push(i);
func_names.append(i, &shim.debug_name);
}
let mut names = NameSection::new();
names.module("wit-component:shim");
names.functions(&func_names);
let table_type = TableType {
element_type: RefType::FUNCREF,
minimum: ret.shims.len() as u64,
maximum: Some(ret.shims.len() as u64),
table64: false,
shared: false,
};
tables.table(table_type);
exports.export(INDIRECT_TABLE_NAME, ExportKind::Table, 0);
imports_section.import("", INDIRECT_TABLE_NAME, table_type);
elements.active(
None,
&ConstExpr::i32_const(0),
Elements::Functions(func_indexes.into()),
);
let mut shim = Module::new();
shim.section(&types);
shim.section(&functions);
shim.section(&tables);
shim.section(&exports);
shim.section(&code);
shim.section(&RawCustomSection(
&crate::base_producers().raw_custom_section(),
));
if self.info.encoder.debug_names {
shim.section(&names);
}
let mut fixups = Module::default();
fixups.section(&types);
fixups.section(&imports_section);
fixups.section(&elements);
fixups.section(&RawCustomSection(
&crate::base_producers().raw_custom_section(),
));
if self.info.encoder.debug_names {
let mut names = NameSection::new();
names.module("wit-component:fixups");
fixups.section(&names);
}
let shim_module_index = self
.component
.core_module(Some("wit-component-shim-module"), &shim);
let fixup_index = self
.component
.core_module(Some("wit-component-fixup"), &fixups);
self.fixups_module_index = Some(fixup_index);
let shim_instance = self.component.core_instantiate(
Some("wit-component-shim-instance"),
shim_module_index,
[],
);
self.shim_instance_index = Some(shim_instance);
return Ok(ret);
}
fn encode_shim_function(
type_index: u32,
func_index: u32,
code: &mut CodeSection,
param_count: u32,
) {
let mut func = wasm_encoder::Function::new(std::iter::empty());
for i in 0..param_count {
func.instructions().local_get(i);
}
func.instructions().i32_const(func_index as i32);
func.instructions().call_indirect(0, type_index);
func.instructions().end();
code.function(&func);
}
fn encode_indirect_lowerings(&mut self, shims: &Shims<'_>) -> Result<()> {
if shims.shims.is_empty() {
return Ok(());
}
let shim_instance_index = self
.shim_instance_index
.expect("must have an instantiated shim");
let table_index = self.core_alias_export(
Some("shim table"),
shim_instance_index,
INDIRECT_TABLE_NAME,
ExportKind::Table,
);
let resolve = &self.info.encoder.metadata.resolve;
let mut exports = Vec::new();
exports.push((INDIRECT_TABLE_NAME, ExportKind::Table, table_index));
for shim in shims.shims.values() {
let core_func_index = match &shim.kind {
ShimKind::IndirectLowering {
interface,
index,
realloc,
encoding,
} => {
let interface = &self.info.import_map[interface];
let ((name, _), _) = interface.lowerings.get_index(*index).unwrap();
let func_index = match &interface.interface {
Some(interface_id) => {
let instance_index = self.imported_instances[interface_id];
self.component.alias_export(
instance_index,
name,
ComponentExportKind::Func,
)
}
None => self.imported_funcs[name],
};
let realloc = self
.info
.exports_for(*realloc)
.import_realloc_for(interface.interface, name)
.map(|name| {
let instance = self.instance_for(*realloc);
self.core_alias_export(
Some("realloc"),
instance,
name,
ExportKind::Func,
)
});
self.component.lower_func(
Some(&shim.debug_name),
func_index,
shim.options
.into_iter(*encoding, self.memory_index, realloc)?,
)
}
ShimKind::Adapter { adapter, func } => self.core_alias_export(
Some(func),
self.adapter_instances[adapter],
func,
ExportKind::Func,
),
ShimKind::ResourceDtor { module, export } => self.core_alias_export(
Some(export),
self.instance_for(*module),
export,
ExportKind::Func,
),
ShimKind::PayloadFunc {
for_module,
info,
kind,
} => {
let metadata = self.info.module_metadata_for(*for_module);
let exports = self.info.exports_for(*for_module);
let instance_index = self.instance_for(*for_module);
let (encoding, realloc) = match &info.ty {
PayloadType::Type { function, .. } => {
if info.imported {
(
metadata.import_encodings.get(resolve, &info.key, function),
exports.import_realloc_for(info.interface, function),
)
} else {
(
metadata.export_encodings.get(resolve, &info.key, function),
exports.export_realloc_for(&info.key, function),
)
}
}
PayloadType::UnitFuture | PayloadType::UnitStream => (None, None),
};
let encoding = encoding.unwrap_or(StringEncoding::UTF8);
let realloc_index = realloc.map(|name| {
self.core_alias_export(
Some("realloc"),
instance_index,
name,
ExportKind::Func,
)
});
let type_index = self.payload_type_index(info)?;
let options =
shim.options
.into_iter(encoding, self.memory_index, realloc_index)?;
match kind {
PayloadFuncKind::FutureWrite => {
self.component.future_write(type_index, options)
}
PayloadFuncKind::FutureRead => {
self.component.future_read(type_index, options)
}
PayloadFuncKind::StreamWrite => {
self.component.stream_write(type_index, options)
}
PayloadFuncKind::StreamRead => {
self.component.stream_read(type_index, options)
}
}
}
ShimKind::WaitableSetWait { cancellable } => self
.component
.waitable_set_wait(*cancellable, self.memory_index.unwrap()),
ShimKind::WaitableSetPoll { cancellable } => self
.component
.waitable_set_poll(*cancellable, self.memory_index.unwrap()),
ShimKind::ErrorContextNew { encoding } => self.component.error_context_new(
shim.options.into_iter(*encoding, self.memory_index, None)?,
),
ShimKind::ErrorContextDebugMessage {
for_module,
encoding,
} => {
let instance_index = self.instance_for(*for_module);
let realloc = self.info.exports_for(*for_module).import_realloc_fallback();
let realloc_index = realloc.map(|r| {
self.core_alias_export(Some("realloc"), instance_index, r, ExportKind::Func)
});
self.component
.error_context_debug_message(shim.options.into_iter(
*encoding,
self.memory_index,
realloc_index,
)?)
}
ShimKind::TaskReturn {
interface,
func,
result,
encoding,
for_module,
} => {
let mut encoder = if interface.is_none() {
self.root_import_type_encoder(*interface)
} else {
self.root_export_type_encoder(*interface)
};
let result = match result {
Some(ty) => Some(encoder.encode_valtype(resolve, ty)?),
None => None,
};
let exports = self.info.exports_for(*for_module);
let realloc = exports.import_realloc_for(*interface, func);
let instance_index = self.instance_for(*for_module);
let realloc_index = realloc.map(|r| {
self.core_alias_export(Some("realloc"), instance_index, r, ExportKind::Func)
});
let options =
shim.options
.into_iter(*encoding, self.memory_index, realloc_index)?;
self.component.task_return(result, options)
}
ShimKind::ThreadNewIndirect {
for_module,
func_ty,
} => {
let (func_ty_idx, f) = self.component.core_type(Some("thread-start"));
f.core().func_type(func_ty);
let exports = self.info.exports_for(*for_module);
let instance_index = self.instance_for(*for_module);
let table_idx = exports.indirect_function_table().map(|table| {
self.core_alias_export(
Some("indirect-function-table"),
instance_index,
table,
ExportKind::Table,
)
}).ok_or_else(|| {
anyhow!(
"table __indirect_function_table must be an exported funcref table for thread.new-indirect"
)
})?;
self.component.thread_new_indirect(func_ty_idx, table_idx)
}
};
exports.push((shim.name.as_str(), ExportKind::Func, core_func_index));
}
let instance_index = self
.component
.core_instantiate_exports(Some("fixup-args"), exports);
self.component.core_instantiate(
Some("fixup"),
self.fixups_module_index.expect("must have fixup module"),
[("", ModuleArg::Instance(instance_index))],
);
Ok(())
}
fn payload_type_index(&mut self, info: &PayloadInfo) -> Result<u32> {
let resolve = &self.info.encoder.metadata.resolve;
let mut encoder = if info.imported || info.interface.is_none() {
self.root_import_type_encoder(None)
} else {
self.root_export_type_encoder(info.interface)
};
match info.ty {
PayloadType::Type { id, .. } => match encoder.encode_valtype(resolve, &Type::Id(id))? {
ComponentValType::Type(index) => Ok(index),
ComponentValType::Primitive(_) => unreachable!(),
},
PayloadType::UnitFuture => Ok(encoder.encode_unit_future()),
PayloadType::UnitStream => Ok(encoder.encode_unit_stream()),
}
}
fn declare_types_for_imported_intrinsics(&mut self, shims: &Shims<'_>) -> Result<()> {
let resolve = &self.info.encoder.metadata.resolve;
let world = &resolve.worlds[self.info.encoder.metadata.world];
let main_module_keys = self.info.encoder.main_module_exports.iter();
let main_module_keys = main_module_keys.map(|key| (CustomModule::Main, key));
let adapter_keys = self.info.encoder.adapters.iter().flat_map(|(name, info)| {
info.required_exports
.iter()
.map(move |key| (CustomModule::Adapter(name), key))
});
for (for_module, key) in main_module_keys.chain(adapter_keys) {
let id = match &world.exports[key] {
WorldItem::Interface { id, .. } => *id,
WorldItem::Type { .. } => unreachable!(),
WorldItem::Function(_) => continue,
};
for ty in resolve.interfaces[id].types.values() {
let def = &resolve.types[*ty];
match &def.kind {
TypeDefKind::Resource => {
let exports = self.info.exports_for(for_module);
let dtor = exports.resource_dtor(*ty).map(|name| {
let shim = &shims.shims[&ShimKind::ResourceDtor {
module: for_module,
export: name,
}];
let index = self.shim_instance_index.unwrap();
self.core_alias_export(
Some(&shim.debug_name),
index,
&shim.name,
ExportKind::Func,
)
});
let resource_idx = self.component.type_resource(
Some(def.name.as_ref().unwrap()),
ValType::I32,
dtor,
);
let prev = self
.export_type_encoding_maps
.id_to_index
.insert(*ty, resource_idx);
assert!(prev.is_none());
}
_other => {
self.root_export_type_encoder(Some(id))
.encode_valtype(resolve, &Type::Id(*ty))?;
}
}
}
}
Ok(())
}
fn instantiate_main_module(&mut self, shims: &Shims<'_>) -> Result<()> {
assert!(self.instance_index.is_none());
let instance_index = self.instantiate_core_module(shims, CustomModule::Main)?;
if let Some(memory) = self.info.info.exports.memory() {
self.memory_index = Some(self.core_alias_export(
Some("memory"),
instance_index,
memory,
ExportKind::Memory,
));
}
self.instance_index = Some(instance_index);
Ok(())
}
fn instantiate_adapter_module(&mut self, shims: &Shims<'_>, name: &'a str) -> Result<()> {
let instance = self.instantiate_core_module(shims, CustomModule::Adapter(name))?;
self.adapter_instances.insert(name, instance);
Ok(())
}
fn instantiate_core_module(
&mut self,
shims: &Shims,
for_module: CustomModule<'_>,
) -> Result<u32> {
let module = self.module_for(for_module);
let mut args = Vec::new();
for (core_wasm_name, instance) in self.info.imports_for(for_module).modules() {
match instance {
ImportInstance::Names(names) => {
let mut exports = Vec::new();
for (name, import) in names {
log::trace!(
"attempting to materialize import of `{core_wasm_name}::{name}` for {for_module:?}"
);
let (kind, index) = self
.materialize_import(&shims, for_module, import)
.with_context(|| {
format!("failed to satisfy import `{core_wasm_name}::{name}`")
})?;
exports.push((name.as_str(), kind, index));
}
let index = self
.component
.core_instantiate_exports(Some(core_wasm_name), exports);
args.push((core_wasm_name.as_str(), ModuleArg::Instance(index)));
}
ImportInstance::Whole(which) => {
let instance = self.instance_for(which.to_custom_module());
args.push((core_wasm_name.as_str(), ModuleArg::Instance(instance)));
}
}
}
Ok(self
.component
.core_instantiate(Some(for_module.debug_name()), module, args))
}
fn materialize_import(
&mut self,
shims: &Shims<'_>,
for_module: CustomModule<'_>,
import: &'a Import,
) -> Result<(ExportKind, u32)> {
let resolve = &self.info.encoder.metadata.resolve;
match import {
Import::AdapterExport {
adapter,
func,
ty: _,
} => {
assert!(self.info.encoder.adapters.contains_key(adapter));
Ok(self.materialize_shim_import(shims, &ShimKind::Adapter { adapter, func }))
}
Import::MainModuleMemory => {
let index = self
.memory_index
.ok_or_else(|| anyhow!("main module cannot import memory"))?;
Ok((ExportKind::Memory, index))
}
Import::MainModuleExport { name, kind } => {
let instance = self.instance_index.unwrap();
let index = self.core_alias_export(Some(name), instance, name, *kind);
Ok((*kind, index))
}
Import::Item(item) => {
let instance = self.instance_for(item.which.to_custom_module());
let index =
self.core_alias_export(Some(&item.name), instance, &item.name, item.kind);
Ok((item.kind, index))
}
Import::ExportedResourceDrop(_key, id) => {
let index = self
.component
.resource_drop(self.export_type_encoding_maps.id_to_index[id]);
Ok((ExportKind::Func, index))
}
Import::ExportedResourceRep(_key, id) => {
let index = self
.component
.resource_rep(self.export_type_encoding_maps.id_to_index[id]);
Ok((ExportKind::Func, index))
}
Import::ExportedResourceNew(_key, id) => {
let index = self
.component
.resource_new(self.export_type_encoding_maps.id_to_index[id]);
Ok((ExportKind::Func, index))
}
Import::ImportedResourceDrop(key, iface, id) => {
let ty = &resolve.types[*id];
let name = ty.name.as_ref().unwrap();
self.materialize_wit_import(
shims,
for_module,
iface.map(|_| resolve.name_world_key(key)),
&format!("{name}_drop"),
key,
AbiVariant::GuestImport,
)
}
Import::ExportedTaskReturn(key, interface, func) => {
let (options, _sig) = task_return_options_and_type(resolve, func);
let result_ty = func.result;
if options.is_empty() {
let mut encoder = if interface.is_none() {
self.root_import_type_encoder(*interface)
} else {
self.root_export_type_encoder(*interface)
};
let result = match result_ty.as_ref() {
Some(ty) => Some(encoder.encode_valtype(resolve, ty)?),
None => None,
};
let index = self.component.task_return(result, []);
Ok((ExportKind::Func, index))
} else {
let metadata = &self.info.module_metadata_for(for_module);
let encoding = metadata
.export_encodings
.get(resolve, key, &func.name)
.unwrap();
Ok(self.materialize_shim_import(
shims,
&ShimKind::TaskReturn {
for_module,
interface: *interface,
func: &func.name,
result: result_ty,
encoding,
},
))
}
}
Import::BackpressureInc => {
let index = self.component.backpressure_inc();
Ok((ExportKind::Func, index))
}
Import::BackpressureDec => {
let index = self.component.backpressure_dec();
Ok((ExportKind::Func, index))
}
Import::WaitableSetWait { cancellable } => Ok(self.materialize_shim_import(
shims,
&ShimKind::WaitableSetWait {
cancellable: *cancellable,
},
)),
Import::WaitableSetPoll { cancellable } => Ok(self.materialize_shim_import(
shims,
&ShimKind::WaitableSetPoll {
cancellable: *cancellable,
},
)),
Import::ThreadYield { cancellable } => {
let index = self.component.thread_yield(*cancellable);
Ok((ExportKind::Func, index))
}
Import::SubtaskDrop => {
let index = self.component.subtask_drop();
Ok((ExportKind::Func, index))
}
Import::SubtaskCancel { async_ } => {
let index = self.component.subtask_cancel(*async_);
Ok((ExportKind::Func, index))
}
Import::StreamNew(info) => {
let ty = self.payload_type_index(info)?;
let index = self.component.stream_new(ty);
Ok((ExportKind::Func, index))
}
Import::StreamRead { info, .. } => Ok(self.materialize_payload_import(
shims,
for_module,
info,
PayloadFuncKind::StreamRead,
)),
Import::StreamWrite { info, .. } => Ok(self.materialize_payload_import(
shims,
for_module,
info,
PayloadFuncKind::StreamWrite,
)),
Import::StreamCancelRead { info, async_ } => {
let ty = self.payload_type_index(info)?;
let index = self.component.stream_cancel_read(ty, *async_);
Ok((ExportKind::Func, index))
}
Import::StreamCancelWrite { info, async_ } => {
let ty = self.payload_type_index(info)?;
let index = self.component.stream_cancel_write(ty, *async_);
Ok((ExportKind::Func, index))
}
Import::StreamDropReadable(info) => {
let type_index = self.payload_type_index(info)?;
let index = self.component.stream_drop_readable(type_index);
Ok((ExportKind::Func, index))
}
Import::StreamDropWritable(info) => {
let type_index = self.payload_type_index(info)?;
let index = self.component.stream_drop_writable(type_index);
Ok((ExportKind::Func, index))
}
Import::FutureNew(info) => {
let ty = self.payload_type_index(info)?;
let index = self.component.future_new(ty);
Ok((ExportKind::Func, index))
}
Import::FutureRead { info, .. } => Ok(self.materialize_payload_import(
shims,
for_module,
info,
PayloadFuncKind::FutureRead,
)),
Import::FutureWrite { info, .. } => Ok(self.materialize_payload_import(
shims,
for_module,
info,
PayloadFuncKind::FutureWrite,
)),
Import::FutureCancelRead { info, async_ } => {
let ty = self.payload_type_index(info)?;
let index = self.component.future_cancel_read(ty, *async_);
Ok((ExportKind::Func, index))
}
Import::FutureCancelWrite { info, async_ } => {
let ty = self.payload_type_index(info)?;
let index = self.component.future_cancel_write(ty, *async_);
Ok((ExportKind::Func, index))
}
Import::FutureDropReadable(info) => {
let type_index = self.payload_type_index(info)?;
let index = self.component.future_drop_readable(type_index);
Ok((ExportKind::Func, index))
}
Import::FutureDropWritable(info) => {
let type_index = self.payload_type_index(info)?;
let index = self.component.future_drop_writable(type_index);
Ok((ExportKind::Func, index))
}
Import::ErrorContextNew { encoding } => Ok(self.materialize_shim_import(
shims,
&ShimKind::ErrorContextNew {
encoding: *encoding,
},
)),
Import::ErrorContextDebugMessage { encoding } => Ok(self.materialize_shim_import(
shims,
&ShimKind::ErrorContextDebugMessage {
for_module,
encoding: *encoding,
},
)),
Import::ErrorContextDrop => {
let index = self.component.error_context_drop();
Ok((ExportKind::Func, index))
}
Import::WorldFunc(key, name, abi) => {
self.materialize_wit_import(shims, for_module, None, name, key, *abi)
}
Import::InterfaceFunc(key, _, name, abi) => self.materialize_wit_import(
shims,
for_module,
Some(resolve.name_world_key(key)),
name,
key,
*abi,
),
Import::WaitableSetNew => {
let index = self.component.waitable_set_new();
Ok((ExportKind::Func, index))
}
Import::WaitableSetDrop => {
let index = self.component.waitable_set_drop();
Ok((ExportKind::Func, index))
}
Import::WaitableJoin => {
let index = self.component.waitable_join();
Ok((ExportKind::Func, index))
}
Import::ContextGet(n) => {
let index = self.component.context_get(*n);
Ok((ExportKind::Func, index))
}
Import::ContextSet(n) => {
let index = self.component.context_set(*n);
Ok((ExportKind::Func, index))
}
Import::ExportedTaskCancel => {
let index = self.component.task_cancel();
Ok((ExportKind::Func, index))
}
Import::ThreadIndex => {
let index = self.component.thread_index();
Ok((ExportKind::Func, index))
}
Import::ThreadNewIndirect => Ok(self.materialize_shim_import(
shims,
&ShimKind::ThreadNewIndirect {
for_module,
func_ty: FuncType::new([ValType::I32], []),
},
)),
Import::ThreadSuspendToSuspended { cancellable } => {
let index = self.component.thread_suspend_to_suspended(*cancellable);
Ok((ExportKind::Func, index))
}
Import::ThreadSuspend { cancellable } => {
let index = self.component.thread_suspend(*cancellable);
Ok((ExportKind::Func, index))
}
Import::ThreadSuspendTo { cancellable } => {
let index = self.component.thread_suspend_to(*cancellable);
Ok((ExportKind::Func, index))
}
Import::ThreadUnsuspend => {
let index = self.component.thread_unsuspend();
Ok((ExportKind::Func, index))
}
Import::ThreadYieldToSuspended { cancellable } => {
let index = self.component.thread_yield_to_suspended(*cancellable);
Ok((ExportKind::Func, index))
}
}
}
fn materialize_shim_import(&mut self, shims: &Shims<'_>, kind: &ShimKind) -> (ExportKind, u32) {
let index = self.core_alias_export(
Some(&shims.shims[kind].debug_name),
self.shim_instance_index
.expect("shim should be instantiated"),
&shims.shims[kind].name,
ExportKind::Func,
);
(ExportKind::Func, index)
}
fn materialize_payload_import(
&mut self,
shims: &Shims<'_>,
for_module: CustomModule<'_>,
info: &PayloadInfo,
kind: PayloadFuncKind,
) -> (ExportKind, u32) {
self.materialize_shim_import(
shims,
&ShimKind::PayloadFunc {
for_module,
info,
kind,
},
)
}
fn materialize_wit_import(
&mut self,
shims: &Shims<'_>,
for_module: CustomModule<'_>,
interface_key: Option<String>,
name: &String,
key: &WorldKey,
abi: AbiVariant,
) -> Result<(ExportKind, u32)> {
let resolve = &self.info.encoder.metadata.resolve;
let import = &self.info.import_map[&interface_key];
let (index, _, lowering) = import.lowerings.get_full(&(name.clone(), abi)).unwrap();
let metadata = self.info.module_metadata_for(for_module);
let index = match lowering {
Lowering::Direct => {
let func_index = match &import.interface {
Some(interface) => {
let instance_index = self.imported_instances[interface];
self.component
.alias_export(instance_index, name, ComponentExportKind::Func)
}
None => self.imported_funcs[name],
};
self.component.lower_func(
Some(name),
func_index,
if let AbiVariant::GuestImportAsync = abi {
vec![CanonicalOption::Async]
} else {
Vec::new()
},
)
}
Lowering::Indirect { .. } => {
let encoding = metadata.import_encodings.get(resolve, key, name).unwrap();
return Ok(self.materialize_shim_import(
shims,
&ShimKind::IndirectLowering {
interface: interface_key,
index,
realloc: for_module,
encoding,
},
));
}
Lowering::ResourceDrop(id) => {
let resource_idx = self.lookup_resource_index(*id);
self.component.resource_drop(resource_idx)
}
};
Ok((ExportKind::Func, index))
}
fn encode_initialize_with_start(&mut self) -> Result<()> {
let initialize = match self.info.info.exports.initialize() {
Some(name) => name,
None => return Ok(()),
};
let initialize_index = self.core_alias_export(
Some("start"),
self.instance_index.unwrap(),
initialize,
ExportKind::Func,
);
let mut shim = Module::default();
let mut section = TypeSection::new();
section.ty().function([], []);
shim.section(§ion);
let mut section = ImportSection::new();
section.import("", "", EntityType::Function(0));
shim.section(§ion);
shim.section(&StartSection { function_index: 0 });
let shim_module_index = self.component.core_module(Some("start-shim-module"), &shim);
let shim_args_instance_index = self.component.core_instantiate_exports(
Some("start-shim-args"),
[("", ExportKind::Func, initialize_index)],
);
self.component.core_instantiate(
Some("start-shim-instance"),
shim_module_index,
[("", ModuleArg::Instance(shim_args_instance_index))],
);
Ok(())
}
fn instance_for(&self, module: CustomModule) -> u32 {
match module {
CustomModule::Main => self.instance_index.expect("instantiated by now"),
CustomModule::Adapter(name) => self.adapter_instances[name],
}
}
fn module_for(&self, module: CustomModule) -> u32 {
match module {
CustomModule::Main => self.module_index.unwrap(),
CustomModule::Adapter(name) => self.adapter_modules[name],
}
}
fn core_alias_export(
&mut self,
debug_name: Option<&str>,
instance: u32,
name: &str,
kind: ExportKind,
) -> u32 {
*self
.aliased_core_items
.entry((instance, name.to_string()))
.or_insert_with(|| {
self.component
.core_alias_export(debug_name, instance, name, kind)
})
}
fn create_export_task_initialization_wrappers(&mut self) -> Result<()> {
let instance_index = self.instance_index.unwrap();
let resolve = &self.info.encoder.metadata.resolve;
let world = &resolve.worlds[self.info.encoder.metadata.world];
let exports = self.info.exports_for(CustomModule::Main);
let wasm_init_task_export = exports.wasm_init_task();
let wasm_init_async_task_export = exports.wasm_init_async_task();
if wasm_init_task_export.is_none() || wasm_init_async_task_export.is_none() {
return Ok(());
}
let wasm_init_task = wasm_init_task_export.unwrap();
let wasm_init_async_task = wasm_init_async_task_export.unwrap();
let funcs_to_wrap: Vec<_> = exports
.iter()
.flat_map(|(core_name, export)| match export {
Export::WorldFunc(key, _, abi) => match &world.exports[key] {
WorldItem::Function(f) => Some((core_name, f, abi)),
_ => None,
},
Export::InterfaceFunc(_, id, func_name, abi) => {
let func = &resolve.interfaces[*id].functions[func_name.as_str()];
Some((core_name, func, abi))
}
_ => None,
})
.collect();
if funcs_to_wrap.is_empty() {
return Ok(());
}
let mut types = TypeSection::new();
let mut imports = ImportSection::new();
let mut functions = FunctionSection::new();
let mut exports_section = ExportSection::new();
let mut code = CodeSection::new();
types.ty().function([], []);
let wasm_init_task_type_idx = 0;
imports.import(
"",
wasm_init_task,
EntityType::Function(wasm_init_task_type_idx),
);
imports.import(
"",
wasm_init_async_task,
EntityType::Function(wasm_init_task_type_idx),
);
let wasm_init_task_func_idx = 0u32;
let wasm_init_async_task_func_idx = 1u32;
let mut type_indices = HashMap::new();
let mut next_type_idx = 1u32;
let mut next_func_idx = 2u32;
struct FuncInfo<'a> {
name: &'a str,
type_idx: u32,
orig_func_idx: u32,
is_async: bool,
n_params: usize,
}
let mut func_info = Vec::new();
for &(name, func, abi) in funcs_to_wrap.iter() {
let sig = resolve.wasm_signature(*abi, func);
let type_idx = *type_indices.entry(sig.clone()).or_insert_with(|| {
let idx = next_type_idx;
types.ty().function(
sig.params.iter().map(to_val_type),
sig.results.iter().map(to_val_type),
);
next_type_idx += 1;
idx
});
imports.import("", &import_func_name(func), EntityType::Function(type_idx));
let orig_func_idx = next_func_idx;
next_func_idx += 1;
func_info.push(FuncInfo {
name,
type_idx,
orig_func_idx,
is_async: abi.is_async(),
n_params: sig.params.len(),
});
}
for info in func_info.iter() {
let wrapper_func_idx = next_func_idx;
functions.function(info.type_idx);
let mut func = wasm_encoder::Function::new([]);
if info.is_async {
func.instruction(&Instruction::Call(wasm_init_async_task_func_idx));
} else {
func.instruction(&Instruction::Call(wasm_init_task_func_idx));
}
for i in 0..info.n_params as u32 {
func.instruction(&Instruction::LocalGet(i));
}
func.instruction(&Instruction::Call(info.orig_func_idx));
func.instruction(&Instruction::End);
code.function(&func);
exports_section.export(info.name, ExportKind::Func, wrapper_func_idx);
next_func_idx += 1;
}
let mut wrapper_module = Module::new();
wrapper_module.section(&types);
wrapper_module.section(&imports);
wrapper_module.section(&functions);
wrapper_module.section(&exports_section);
wrapper_module.section(&code);
let wrapper_module_idx = self
.component
.core_module(Some("init-task-wrappers"), &wrapper_module);
let mut wrapper_imports = Vec::new();
let init_idx = self.core_alias_export(
Some(wasm_init_task),
instance_index,
wasm_init_task,
ExportKind::Func,
);
let init_async_idx = self.core_alias_export(
Some(wasm_init_async_task),
instance_index,
wasm_init_async_task,
ExportKind::Func,
);
wrapper_imports.push((wasm_init_task.into(), ExportKind::Func, init_idx));
wrapper_imports.push((
wasm_init_async_task.into(),
ExportKind::Func,
init_async_idx,
));
for (name, func, _) in &funcs_to_wrap {
let orig_idx =
self.core_alias_export(Some(name), instance_index, name, ExportKind::Func);
wrapper_imports.push((import_func_name(func), ExportKind::Func, orig_idx));
}
let wrapper_args_idx = self.component.core_instantiate_exports(
Some("init-task-wrappers-args"),
wrapper_imports.iter().map(|(n, k, i)| (n.as_str(), *k, *i)),
);
let wrapper_instance = self.component.core_instantiate(
Some("init-task-wrappers-instance"),
wrapper_module_idx,
[("", ModuleArg::Instance(wrapper_args_idx))],
);
for (name, _, _) in funcs_to_wrap {
let wrapper_idx =
self.core_alias_export(Some(&name), wrapper_instance, &name, ExportKind::Func);
self.export_task_initialization_wrappers
.insert(name.into(), wrapper_idx);
}
Ok(())
}
}
#[derive(Default)]
struct Shims<'a> {
shims: IndexMap<ShimKind<'a>, Shim<'a>>,
}
struct Shim<'a> {
options: RequiredOptions,
name: String,
debug_name: String,
kind: ShimKind<'a>,
sig: WasmSignature,
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
enum PayloadFuncKind {
FutureWrite,
FutureRead,
StreamWrite,
StreamRead,
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
enum ShimKind<'a> {
IndirectLowering {
interface: Option<String>,
index: usize,
realloc: CustomModule<'a>,
encoding: StringEncoding,
},
Adapter {
adapter: &'a str,
func: &'a str,
},
ResourceDtor {
module: CustomModule<'a>,
export: &'a str,
},
PayloadFunc {
for_module: CustomModule<'a>,
info: &'a PayloadInfo,
kind: PayloadFuncKind,
},
WaitableSetWait { cancellable: bool },
WaitableSetPoll { cancellable: bool },
TaskReturn {
interface: Option<InterfaceId>,
func: &'a str,
result: Option<Type>,
for_module: CustomModule<'a>,
encoding: StringEncoding,
},
ErrorContextNew {
encoding: StringEncoding,
},
ErrorContextDebugMessage {
for_module: CustomModule<'a>,
encoding: StringEncoding,
},
ThreadNewIndirect {
for_module: CustomModule<'a>,
func_ty: FuncType,
},
}
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
enum CustomModule<'a> {
Main,
Adapter(&'a str),
}
impl<'a> CustomModule<'a> {
fn debug_name(&self) -> &'a str {
match self {
CustomModule::Main => "main",
CustomModule::Adapter(s) => s,
}
}
}
impl<'a> Shims<'a> {
fn append_indirect(
&mut self,
world: &'a ComponentWorld<'a>,
for_module: CustomModule<'a>,
) -> Result<()> {
let module_imports = world.imports_for(for_module);
let module_exports = world.exports_for(for_module);
let resolve = &world.encoder.metadata.resolve;
for (module, field, import) in module_imports.imports() {
match import {
Import::ImportedResourceDrop(..)
| Import::MainModuleMemory
| Import::MainModuleExport { .. }
| Import::Item(_)
| Import::ExportedResourceDrop(..)
| Import::ExportedResourceRep(..)
| Import::ExportedResourceNew(..)
| Import::ExportedTaskCancel
| Import::ErrorContextDrop
| Import::BackpressureInc
| Import::BackpressureDec
| Import::ThreadYield { .. }
| Import::SubtaskDrop
| Import::SubtaskCancel { .. }
| Import::FutureNew(..)
| Import::StreamNew(..)
| Import::FutureCancelRead { .. }
| Import::FutureCancelWrite { .. }
| Import::FutureDropWritable { .. }
| Import::FutureDropReadable { .. }
| Import::StreamCancelRead { .. }
| Import::StreamCancelWrite { .. }
| Import::StreamDropWritable { .. }
| Import::StreamDropReadable { .. }
| Import::WaitableSetNew
| Import::WaitableSetDrop
| Import::WaitableJoin
| Import::ContextGet(_)
| Import::ContextSet(_)
| Import::ThreadIndex
| Import::ThreadSuspendToSuspended { .. }
| Import::ThreadSuspend { .. }
| Import::ThreadSuspendTo { .. }
| Import::ThreadUnsuspend
| Import::ThreadYieldToSuspended { .. } => {}
Import::ExportedTaskReturn(key, interface, func) => {
let (options, sig) = task_return_options_and_type(resolve, func);
if options.is_empty() {
continue;
}
let name = self.shims.len().to_string();
let encoding = world
.module_metadata_for(for_module)
.export_encodings
.get(resolve, key, &func.name)
.ok_or_else(|| {
anyhow::anyhow!(
"missing component metadata for export of \
`{module}::{field}`"
)
})?;
self.push(Shim {
name,
debug_name: format!("task-return-{}", func.name),
options,
kind: ShimKind::TaskReturn {
interface: *interface,
func: &func.name,
result: func.result,
for_module,
encoding,
},
sig,
});
}
Import::FutureWrite { async_, info } => {
self.append_indirect_payload_push(
resolve,
for_module,
module,
*async_,
info,
PayloadFuncKind::FutureWrite,
vec![WasmType::I32; 2],
vec![WasmType::I32],
);
}
Import::FutureRead { async_, info } => {
self.append_indirect_payload_push(
resolve,
for_module,
module,
*async_,
info,
PayloadFuncKind::FutureRead,
vec![WasmType::I32; 2],
vec![WasmType::I32],
);
}
Import::StreamWrite { async_, info } => {
self.append_indirect_payload_push(
resolve,
for_module,
module,
*async_,
info,
PayloadFuncKind::StreamWrite,
vec![WasmType::I32; 3],
vec![WasmType::I32],
);
}
Import::StreamRead { async_, info } => {
self.append_indirect_payload_push(
resolve,
for_module,
module,
*async_,
info,
PayloadFuncKind::StreamRead,
vec![WasmType::I32; 3],
vec![WasmType::I32],
);
}
Import::WaitableSetWait { cancellable } => {
let name = self.shims.len().to_string();
self.push(Shim {
name,
debug_name: "waitable-set.wait".to_string(),
options: RequiredOptions::empty(),
kind: ShimKind::WaitableSetWait {
cancellable: *cancellable,
},
sig: WasmSignature {
params: vec![WasmType::I32; 2],
results: vec![WasmType::I32],
indirect_params: false,
retptr: false,
},
});
}
Import::WaitableSetPoll { cancellable } => {
let name = self.shims.len().to_string();
self.push(Shim {
name,
debug_name: "waitable-set.poll".to_string(),
options: RequiredOptions::empty(),
kind: ShimKind::WaitableSetPoll {
cancellable: *cancellable,
},
sig: WasmSignature {
params: vec![WasmType::I32; 2],
results: vec![WasmType::I32],
indirect_params: false,
retptr: false,
},
});
}
Import::ErrorContextNew { encoding } => {
let name = self.shims.len().to_string();
self.push(Shim {
name,
debug_name: "error-new".to_string(),
options: RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING,
kind: ShimKind::ErrorContextNew {
encoding: *encoding,
},
sig: WasmSignature {
params: vec![WasmType::I32; 2],
results: vec![WasmType::I32],
indirect_params: false,
retptr: false,
},
});
}
Import::ErrorContextDebugMessage { encoding } => {
let name = self.shims.len().to_string();
self.push(Shim {
name,
debug_name: "error-debug-message".to_string(),
options: RequiredOptions::MEMORY
| RequiredOptions::STRING_ENCODING
| RequiredOptions::REALLOC,
kind: ShimKind::ErrorContextDebugMessage {
for_module,
encoding: *encoding,
},
sig: WasmSignature {
params: vec![WasmType::I32; 2],
results: vec![],
indirect_params: false,
retptr: false,
},
});
}
Import::ThreadNewIndirect => {
let name = self.shims.len().to_string();
self.push(Shim {
name,
debug_name: "thread.new-indirect".to_string(),
options: RequiredOptions::empty(),
kind: ShimKind::ThreadNewIndirect {
for_module,
func_ty: FuncType::new([ValType::I32], vec![]),
},
sig: WasmSignature {
params: vec![WasmType::I32; 2],
results: vec![WasmType::I32],
indirect_params: false,
retptr: false,
},
});
}
Import::AdapterExport { adapter, func, ty } => {
let name = self.shims.len().to_string();
log::debug!("shim {name} is adapter `{module}::{field}`");
self.push(Shim {
name,
debug_name: format!("adapt-{module}-{field}"),
options: RequiredOptions::MEMORY,
kind: ShimKind::Adapter { adapter, func },
sig: WasmSignature {
params: ty.params().iter().map(to_wasm_type).collect(),
results: ty.results().iter().map(to_wasm_type).collect(),
indirect_params: false,
retptr: false,
},
});
fn to_wasm_type(ty: &wasmparser::ValType) -> WasmType {
match ty {
wasmparser::ValType::I32 => WasmType::I32,
wasmparser::ValType::I64 => WasmType::I64,
wasmparser::ValType::F32 => WasmType::F32,
wasmparser::ValType::F64 => WasmType::F64,
_ => unreachable!(),
}
}
}
Import::InterfaceFunc(key, _, name, abi) => {
self.append_indirect_wit_func(
world,
for_module,
module,
field,
key,
name,
Some(resolve.name_world_key(key)),
*abi,
)?;
}
Import::WorldFunc(key, name, abi) => {
self.append_indirect_wit_func(
world, for_module, module, field, key, name, None, *abi,
)?;
}
}
}
for (export_name, export) in module_exports.iter() {
let id = match export {
Export::ResourceDtor(id) => id,
_ => continue,
};
let resource = resolve.types[*id].name.as_ref().unwrap();
let name = self.shims.len().to_string();
self.push(Shim {
name,
debug_name: format!("dtor-{resource}"),
options: RequiredOptions::empty(),
kind: ShimKind::ResourceDtor {
module: for_module,
export: export_name,
},
sig: WasmSignature {
params: vec![WasmType::I32],
results: Vec::new(),
indirect_params: false,
retptr: false,
},
});
}
Ok(())
}
fn append_indirect_payload_push(
&mut self,
resolve: &Resolve,
for_module: CustomModule<'a>,
module: &str,
async_: bool,
info: &'a PayloadInfo,
kind: PayloadFuncKind,
params: Vec<WasmType>,
results: Vec<WasmType>,
) {
let debug_name = format!("{module}-{}", info.name);
let name = self.shims.len().to_string();
let payload = info.payload(resolve);
let (wit_param, wit_result) = match kind {
PayloadFuncKind::StreamRead | PayloadFuncKind::FutureRead => (None, payload),
PayloadFuncKind::StreamWrite | PayloadFuncKind::FutureWrite => (payload, None),
};
self.push(Shim {
name,
debug_name,
options: RequiredOptions::MEMORY
| RequiredOptions::for_import(
resolve,
&Function {
name: String::new(),
kind: FunctionKind::Freestanding,
params: match wit_param {
Some(ty) => vec![Param {
name: "a".to_string(),
ty,
span: Default::default(),
}],
None => Vec::new(),
},
result: wit_result,
docs: Default::default(),
stability: Stability::Unknown,
span: Default::default(),
},
if async_ {
AbiVariant::GuestImportAsync
} else {
AbiVariant::GuestImport
},
),
kind: ShimKind::PayloadFunc {
for_module,
info,
kind,
},
sig: WasmSignature {
params,
results,
indirect_params: false,
retptr: false,
},
});
}
fn append_indirect_wit_func(
&mut self,
world: &'a ComponentWorld<'a>,
for_module: CustomModule<'a>,
module: &str,
field: &str,
key: &WorldKey,
name: &String,
interface_key: Option<String>,
abi: AbiVariant,
) -> Result<()> {
let resolve = &world.encoder.metadata.resolve;
let metadata = world.module_metadata_for(for_module);
let interface = &world.import_map[&interface_key];
let (index, _, lowering) = interface.lowerings.get_full(&(name.clone(), abi)).unwrap();
let shim_name = self.shims.len().to_string();
match lowering {
Lowering::Direct | Lowering::ResourceDrop(_) => {}
Lowering::Indirect { sig, options } => {
log::debug!(
"shim {shim_name} is import `{module}::{field}` lowering {index} `{name}`",
);
let encoding = metadata
.import_encodings
.get(resolve, key, name)
.ok_or_else(|| {
anyhow::anyhow!(
"missing component metadata for import of \
`{module}::{field}`"
)
})?;
self.push(Shim {
name: shim_name,
debug_name: format!("indirect-{module}-{field}"),
options: *options,
kind: ShimKind::IndirectLowering {
interface: interface_key,
index,
realloc: for_module,
encoding,
},
sig: sig.clone(),
});
}
}
Ok(())
}
fn push(&mut self, shim: Shim<'a>) {
if !self.shims.contains_key(&shim.kind) {
self.shims.insert(shim.kind.clone(), shim);
}
}
}
fn task_return_options_and_type(
resolve: &Resolve,
func: &Function,
) -> (RequiredOptions, WasmSignature) {
let func_tmp = Function {
name: String::new(),
kind: FunctionKind::Freestanding,
params: match &func.result {
Some(ty) => vec![Param {
name: "a".to_string(),
ty: *ty,
span: Default::default(),
}],
None => Vec::new(),
},
result: None,
docs: Default::default(),
stability: Stability::Unknown,
span: Default::default(),
};
let abi = AbiVariant::GuestImport;
let mut options = RequiredOptions::for_import(resolve, func, abi);
options.remove(RequiredOptions::REALLOC);
let sig = resolve.wasm_signature(abi, &func_tmp);
(options, sig)
}
#[derive(Clone, Debug)]
pub struct Item {
pub alias: String,
pub kind: ExportKind,
pub which: MainOrAdapter,
pub name: String,
}
#[derive(Debug, PartialEq, Clone)]
pub enum MainOrAdapter {
Main,
Adapter(String),
}
impl MainOrAdapter {
fn to_custom_module(&self) -> CustomModule<'_> {
match self {
MainOrAdapter::Main => CustomModule::Main,
MainOrAdapter::Adapter(s) => CustomModule::Adapter(s),
}
}
}
#[derive(Clone)]
pub enum Instance {
MainOrAdapter(MainOrAdapter),
Items(Vec<Item>),
}
#[derive(Clone)]
pub struct LibraryInfo {
pub instantiate_after_shims: bool,
pub arguments: Vec<(String, Instance)>,
}
pub(super) struct Adapter {
wasm: Vec<u8>,
metadata: ModuleMetadata,
required_exports: IndexSet<WorldKey>,
library_info: Option<LibraryInfo>,
}
#[derive(Default)]
pub struct ComponentEncoder {
module: Vec<u8>,
module_import_map: Option<ModuleImportMap>,
pub(super) metadata: Bindgen,
validate: bool,
pub(super) main_module_exports: IndexSet<WorldKey>,
pub(super) adapters: IndexMap<String, Adapter>,
import_name_map: HashMap<String, String>,
realloc_via_memory_grow: bool,
merge_imports_based_on_semver: Option<bool>,
pub(super) reject_legacy_names: bool,
debug_names: bool,
}
impl ComponentEncoder {
pub fn module(mut self, module: &[u8]) -> Result<Self> {
let (wasm, metadata) = self.decode(module.as_ref())?;
let (wasm, module_import_map) = ModuleImportMap::new(wasm)?;
let exports = self
.merge_metadata(metadata)
.context("failed merge WIT metadata for module with previous metadata")?;
self.main_module_exports.extend(exports);
self.module = if let Some(producers) = &self.metadata.producers {
producers.add_to_wasm(&wasm)?
} else {
wasm.to_vec()
};
self.module_import_map = module_import_map;
Ok(self)
}
fn decode<'a>(&self, wasm: &'a [u8]) -> Result<(Cow<'a, [u8]>, Bindgen)> {
let (bytes, metadata) = metadata::decode(wasm)?;
match bytes {
Some(wasm) => Ok((Cow::Owned(wasm), metadata)),
None => Ok((Cow::Borrowed(wasm), metadata)),
}
}
fn merge_metadata(&mut self, metadata: Bindgen) -> Result<IndexSet<WorldKey>> {
self.metadata.merge(metadata)
}
pub fn validate(mut self, validate: bool) -> Self {
self.validate = validate;
self
}
pub fn debug_names(mut self, debug_names: bool) -> Self {
self.debug_names = debug_names;
self
}
pub fn merge_imports_based_on_semver(mut self, merge: bool) -> Self {
self.merge_imports_based_on_semver = Some(merge);
self
}
pub fn reject_legacy_names(mut self, reject: bool) -> Self {
self.reject_legacy_names = reject;
self
}
pub fn adapter(self, name: &str, bytes: &[u8]) -> Result<Self> {
self.library_or_adapter(name, bytes, None)
}
pub fn library(self, name: &str, bytes: &[u8], library_info: LibraryInfo) -> Result<Self> {
self.library_or_adapter(name, bytes, Some(library_info))
}
fn library_or_adapter(
mut self,
name: &str,
bytes: &[u8],
library_info: Option<LibraryInfo>,
) -> Result<Self> {
let (wasm, mut metadata) = self.decode(bytes)?;
let adapter_metadata = mem::take(&mut metadata.metadata);
let exports = self.merge_metadata(metadata).with_context(|| {
format!("failed to merge WIT packages of adapter `{name}` into main packages")
})?;
if let Some(library_info) = &library_info {
for (_, instance) in &library_info.arguments {
let resolve = |which: &_| match which {
MainOrAdapter::Main => Ok(()),
MainOrAdapter::Adapter(name) => {
if self.adapters.contains_key(name.as_str()) {
Ok(())
} else {
Err(anyhow!("instance refers to unknown adapter `{name}`"))
}
}
};
match instance {
Instance::MainOrAdapter(which) => resolve(which)?,
Instance::Items(items) => {
for item in items {
resolve(&item.which)?;
}
}
}
}
}
self.adapters.insert(
name.to_string(),
Adapter {
wasm: wasm.to_vec(),
metadata: adapter_metadata,
required_exports: exports,
library_info,
},
);
Ok(self)
}
pub fn realloc_via_memory_grow(mut self, value: bool) -> Self {
self.realloc_via_memory_grow = value;
self
}
pub fn import_name_map(mut self, map: HashMap<String, String>) -> Self {
self.import_name_map = map;
self
}
pub fn encode(&mut self) -> Result<Vec<u8>> {
if self.module.is_empty() {
bail!("a module is required when encoding a component");
}
if self.merge_imports_based_on_semver.unwrap_or(true) {
self.metadata
.resolve
.merge_world_imports_based_on_semver(self.metadata.world)?;
}
let world = ComponentWorld::new(self).context("failed to decode world from module")?;
let mut state = EncodingState {
component: ComponentBuilder::default(),
module_index: None,
instance_index: None,
memory_index: None,
shim_instance_index: None,
fixups_module_index: None,
adapter_modules: IndexMap::new(),
adapter_instances: IndexMap::new(),
import_type_encoding_maps: Default::default(),
export_type_encoding_maps: Default::default(),
imported_instances: Default::default(),
imported_funcs: Default::default(),
exported_instances: Default::default(),
aliased_core_items: Default::default(),
info: &world,
export_task_initialization_wrappers: HashMap::new(),
};
state.encode_imports(&self.import_name_map)?;
state.encode_core_modules();
state.encode_core_instantiation()?;
state.encode_exports(CustomModule::Main)?;
for name in self.adapters.keys() {
state.encode_exports(CustomModule::Adapter(name))?;
}
state.component.append_names();
state
.component
.raw_custom_section(&crate::base_producers().raw_custom_section());
let bytes = state.component.finish();
if self.validate {
Validator::new_with_features(WasmFeatures::all())
.validate_all(&bytes)
.context("failed to validate component output")?;
}
Ok(bytes)
}
}
impl ComponentWorld<'_> {
fn imports_for(&self, module: CustomModule) -> &ImportMap {
match module {
CustomModule::Main => &self.info.imports,
CustomModule::Adapter(name) => &self.adapters[name].info.imports,
}
}
fn exports_for(&self, module: CustomModule) -> &ExportMap {
match module {
CustomModule::Main => &self.info.exports,
CustomModule::Adapter(name) => &self.adapters[name].info.exports,
}
}
fn module_metadata_for(&self, module: CustomModule) -> &ModuleMetadata {
match module {
CustomModule::Main => &self.encoder.metadata.metadata,
CustomModule::Adapter(name) => &self.encoder.adapters[name].metadata,
}
}
}
#[cfg(all(test, feature = "dummy-module"))]
mod test {
use super::*;
use crate::{dummy_module, embed_component_metadata};
use wit_parser::ManglingAndAbi;
#[test]
fn it_renames_imports() {
let mut resolve = Resolve::new();
let pkg = resolve
.push_str(
"test.wit",
r#"
package test:wit;
interface i {
f: func();
}
world test {
import i;
import foo: interface {
f: func();
}
}
"#,
)
.unwrap();
let world = resolve.select_world(&[pkg], None).unwrap();
let mut module = dummy_module(&resolve, world, ManglingAndAbi::Standard32);
embed_component_metadata(&mut module, &resolve, world, StringEncoding::UTF8).unwrap();
let encoded = ComponentEncoder::default()
.import_name_map(HashMap::from([
(
"foo".to_string(),
"unlocked-dep=<foo:bar/foo@{>=1.0.0 <1.1.0}>".to_string(),
),
(
"test:wit/i".to_string(),
"locked-dep=<foo:bar/i@1.2.3>".to_string(),
),
]))
.module(&module)
.unwrap()
.validate(true)
.encode()
.unwrap();
let wat = wasmprinter::print_bytes(encoded).unwrap();
assert!(wat.contains("unlocked-dep=<foo:bar/foo@{>=1.0.0 <1.1.0}>"));
assert!(wat.contains("locked-dep=<foo:bar/i@1.2.3>"));
}
}