use super::utils::FromWasmparser as _;
use crate::{GlobalType, MemoryType, TableType};
use alloc::boxed::Box;
use core::fmt::{self, Display};
use wasmparser::TypeRef;
#[derive(Debug)]
pub struct Import {
name: ImportName,
kind: ExternTypeIdx,
}
#[derive(Debug, Clone)]
pub struct ImportName {
module: Box<str>,
field: Box<str>,
}
impl Display for ImportName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let module_name = &*self.module;
let field_name = &*self.field;
write!(f, "{module_name}::{field_name}")
}
}
impl ImportName {
pub fn new(module: &str, field: &str) -> Self {
Self {
module: module.into(),
field: field.into(),
}
}
pub fn module(&self) -> &str {
&self.module
}
pub fn name(&self) -> &str {
&self.field
}
}
impl From<wasmparser::Import<'_>> for Import {
fn from(import: wasmparser::Import) -> Self {
let kind = match import.ty {
TypeRef::Func(ty) => ExternTypeIdx::Func(ty.into()),
TypeRef::Table(ty) => ExternTypeIdx::Table(TableType::from_wasmparser(ty)),
TypeRef::Memory(ty) => ExternTypeIdx::Memory(MemoryType::from_wasmparser(ty)),
TypeRef::Global(ty) => ExternTypeIdx::Global(GlobalType::from_wasmparser(ty)),
TypeRef::Tag(tag) => panic!(
"wasmi does not support the `exception-handling` Wasm proposal but found: {tag:?}"
),
};
Self::new(import.module, import.name, kind)
}
}
impl Import {
pub fn new(module: &str, field: &str, kind: ExternTypeIdx) -> Self {
Self {
name: ImportName::new(module, field),
kind,
}
}
pub fn into_name_and_type(self) -> (ImportName, ExternTypeIdx) {
(self.name, self.kind)
}
}
#[derive(Debug)]
pub enum ExternTypeIdx {
Func(FuncTypeIdx),
Table(TableType),
Memory(MemoryType),
Global(GlobalType),
}
#[derive(Debug, Copy, Clone)]
pub struct FuncTypeIdx(u32);
impl From<u32> for FuncTypeIdx {
fn from(index: u32) -> Self {
Self(index)
}
}
impl FuncTypeIdx {
pub fn into_u32(self) -> u32 {
self.0
}
}