Refactor the types.rs types and structures (#681)

* Refactor the `types.rs` types and structures

A few changes applied along the way:

* Documentation added to most methods and types.
* Limits are now stored with the maximum as optional rather than a
  sentinel u32 value for `None`.
* The `Name` type was removed in favor of just using a bare `String`.
* The `Extern` prefix in the varaints of `ExternType` has been removed
  since it was redundant.
* Accessors of `ExternType` variants no longer panic, and unwrapping
  versions were added with "unwrap" in the name.
* Fields and methods named `r#type` were renamed to `ty` to avoid
  requiring a raw identifier to use them.

* Remove `fail-fast: false`

This was left around since the development of GitHub Actions for
wasmtime, but they're no longer needed!

* Fix compilation of the test-programs code

* Fix compilation of wasmtime-py package

* Run rustfmt
This commit is contained in:
Alex Crichton
2019-12-06 16:19:55 -06:00
committed by GitHub
parent 3d69e04659
commit e134505b90
16 changed files with 226 additions and 174 deletions

View File

@@ -92,7 +92,6 @@ jobs:
name: Test name: Test
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false
matrix: matrix:
build: [stable, beta, nightly, windows, macos] build: [stable, beta, nightly, windows, macos]
include: include:
@@ -165,7 +164,6 @@ jobs:
name: Python Wheel name: Python Wheel
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] os: [ubuntu-latest, macos-latest, windows-latest]
steps: steps:
@@ -262,7 +260,6 @@ jobs:
name: Build wasmtime name: Build wasmtime
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] os: [ubuntu-latest, macos-latest, windows-latest]
steps: steps:

View File

@@ -151,7 +151,7 @@ fn main() -> Result<(), Error> {
// Create stand-alone memory. // Create stand-alone memory.
// TODO(wasm+): Once Wasm allows multiple memories, turn this into import. // TODO(wasm+): Once Wasm allows multiple memories, turn this into import.
println!("Creating stand-alone memory..."); println!("Creating stand-alone memory...");
let memorytype = MemoryType::new(Limits::new(5, 5)); let memorytype = MemoryType::new(Limits::new(5, Some(5)));
let mut memory2 = Memory::new(&store, memorytype); let mut memory2 = Memory::new(&store, memorytype);
check!(memory2.size(), 5u32); check!(memory2.size(), 5u32);
check!(memory2.grow(1), false); check!(memory2.grow(1), false);

View File

@@ -49,10 +49,10 @@ impl Extern {
pub fn r#type(&self) -> ExternType { pub fn r#type(&self) -> ExternType {
match self { match self {
Extern::Func(ft) => ExternType::ExternFunc(ft.borrow().r#type().clone()), Extern::Func(ft) => ExternType::Func(ft.borrow().r#type().clone()),
Extern::Memory(ft) => ExternType::ExternMemory(ft.borrow().r#type().clone()), Extern::Memory(ft) => ExternType::Memory(ft.borrow().r#type().clone()),
Extern::Table(tt) => ExternType::ExternTable(tt.borrow().r#type().clone()), Extern::Table(tt) => ExternType::Table(tt.borrow().r#type().clone()),
Extern::Global(gt) => ExternType::ExternGlobal(gt.borrow().r#type().clone()), Extern::Global(gt) => ExternType::Global(gt.borrow().r#type().clone()),
} }
} }

View File

@@ -4,7 +4,7 @@ use crate::module::Module;
use crate::r#ref::HostRef; use crate::r#ref::HostRef;
use crate::runtime::Store; use crate::runtime::Store;
use crate::trampoline::take_api_trap; use crate::trampoline::take_api_trap;
use crate::types::{ExportType, ExternType, Name}; use crate::types::{ExportType, ExternType};
use anyhow::Result; use anyhow::Result;
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
@@ -122,7 +122,7 @@ impl Instance {
.exports() .exports()
.iter() .iter()
.enumerate() .enumerate()
.find(|(_, e)| e.name().as_str() == name)?; .find(|(_, e)| e.name() == name)?;
Some(&self.exports()[i]) Some(&self.exports()[i])
} }
@@ -141,7 +141,7 @@ impl Instance {
let _ = store.borrow_mut().register_wasmtime_signature(signature); let _ = store.borrow_mut().register_wasmtime_signature(signature);
} }
let extern_type = ExternType::from_wasmtime_export(&export); let extern_type = ExternType::from_wasmtime_export(&export);
exports_types.push(ExportType::new(Name::new(name), extern_type)); exports_types.push(ExportType::new(name, extern_type));
exports.push(Extern::from_wasmtime_export( exports.push(Extern::from_wasmtime_export(
store, store,
instance_handle.clone(), instance_handle.clone(),

View File

@@ -1,4 +1,10 @@
//! Wasmtime embed API. Based on wasm-c-api. //! Wasmtime's embedding API
//!
//! This crate contains a high-level API used to interact with WebAssembly
//! modules. The API here is intended to mirror the proposed [WebAssembly C
//! API](https://github.com/WebAssembly/wasm-c-api), with small extensions here
//! and there to implement Rust idioms. This crate also defines the actual C API
//! itself for consumption from other languages.
#![allow(improper_ctypes)] #![allow(improper_ctypes)]

View File

@@ -12,10 +12,7 @@ use wasmparser::{
fn into_memory_type(mt: wasmparser::MemoryType) -> MemoryType { fn into_memory_type(mt: wasmparser::MemoryType) -> MemoryType {
assert!(!mt.shared); assert!(!mt.shared);
MemoryType::new(Limits::new( MemoryType::new(Limits::new(mt.limits.initial, mt.limits.maximum))
mt.limits.initial,
mt.limits.maximum.unwrap_or(std::u32::MAX),
))
} }
fn into_global_type(gt: &wasmparser::GlobalType) -> GlobalType { fn into_global_type(gt: &wasmparser::GlobalType) -> GlobalType {
@@ -53,10 +50,7 @@ fn into_table_type(tt: wasmparser::TableType) -> TableType {
tt.element_type == wasmparser::Type::AnyFunc || tt.element_type == wasmparser::Type::AnyRef tt.element_type == wasmparser::Type::AnyFunc || tt.element_type == wasmparser::Type::AnyRef
); );
let ty = into_valtype(&tt.element_type); let ty = into_valtype(&tt.element_type);
let limits = Limits::new( let limits = Limits::new(tt.limits.initial, tt.limits.maximum);
tt.limits.initial,
tt.limits.maximum.unwrap_or(std::u32::MAX),
);
TableType::new(ty, limits) TableType::new(ty, limits)
} }
@@ -112,31 +106,29 @@ fn read_imports_and_exports(binary: &[u8]) -> Result<(Box<[ImportType]>, Box<[Ex
imports.reserve_exact(section.get_count() as usize); imports.reserve_exact(section.get_count() as usize);
for entry in section { for entry in section {
let entry = entry?; let entry = entry?;
let module = String::from(entry.module).into();
let name = String::from(entry.field).into();
let r#type = match entry.ty { let r#type = match entry.ty {
ImportSectionEntryType::Function(index) => { ImportSectionEntryType::Function(index) => {
func_sig.push(index); func_sig.push(index);
let sig = &sigs[index as usize]; let sig = &sigs[index as usize];
ExternType::ExternFunc(sig.clone()) ExternType::Func(sig.clone())
} }
ImportSectionEntryType::Table(tt) => { ImportSectionEntryType::Table(tt) => {
let table = into_table_type(tt); let table = into_table_type(tt);
tables.push(table.clone()); tables.push(table.clone());
ExternType::ExternTable(table) ExternType::Table(table)
} }
ImportSectionEntryType::Memory(mt) => { ImportSectionEntryType::Memory(mt) => {
let memory = into_memory_type(mt); let memory = into_memory_type(mt);
memories.push(memory.clone()); memories.push(memory.clone());
ExternType::ExternMemory(memory) ExternType::Memory(memory)
} }
ImportSectionEntryType::Global(gt) => { ImportSectionEntryType::Global(gt) => {
let global = into_global_type(&gt); let global = into_global_type(&gt);
globals.push(global.clone()); globals.push(global.clone());
ExternType::ExternGlobal(global) ExternType::Global(global)
} }
}; };
imports.push(ImportType::new(module, name, r#type)); imports.push(ImportType::new(entry.module, entry.field, r#type));
} }
} }
SectionCode::Export => { SectionCode::Export => {
@@ -144,24 +136,23 @@ fn read_imports_and_exports(binary: &[u8]) -> Result<(Box<[ImportType]>, Box<[Ex
exports.reserve_exact(section.get_count() as usize); exports.reserve_exact(section.get_count() as usize);
for entry in section { for entry in section {
let entry = entry?; let entry = entry?;
let name = String::from(entry.field).into();
let r#type = match entry.kind { let r#type = match entry.kind {
ExternalKind::Function => { ExternalKind::Function => {
let sig_index = func_sig[entry.index as usize] as usize; let sig_index = func_sig[entry.index as usize] as usize;
let sig = &sigs[sig_index]; let sig = &sigs[sig_index];
ExternType::ExternFunc(sig.clone()) ExternType::Func(sig.clone())
} }
ExternalKind::Table => { ExternalKind::Table => {
ExternType::ExternTable(tables[entry.index as usize].clone()) ExternType::Table(tables[entry.index as usize].clone())
} }
ExternalKind::Memory => { ExternalKind::Memory => {
ExternType::ExternMemory(memories[entry.index as usize].clone()) ExternType::Memory(memories[entry.index as usize].clone())
} }
ExternalKind::Global => { ExternalKind::Global => {
ExternType::ExternGlobal(globals[entry.index as usize].clone()) ExternType::Global(globals[entry.index as usize].clone())
} }
}; };
exports.push(ExportType::new(name, r#type)); exports.push(ExportType::new(entry.field, r#type));
} }
} }
_ => { _ => {

View File

@@ -12,11 +12,7 @@ pub fn create_handle_with_memory(memory: &MemoryType) -> Result<InstanceHandle>
let memory = wasm::Memory { let memory = wasm::Memory {
minimum: memory.limits().min(), minimum: memory.limits().min(),
maximum: if memory.limits().max() == std::u32::MAX { maximum: memory.limits().max(),
None
} else {
Some(memory.limits().max())
},
shared: false, // TODO shared: false, // TODO
}; };
let tunable = Default::default(); let tunable = Default::default();

View File

@@ -10,11 +10,7 @@ pub fn create_handle_with_table(table: &TableType) -> Result<InstanceHandle> {
let table = wasm::Table { let table = wasm::Table {
minimum: table.limits().min(), minimum: table.limits().min(),
maximum: if table.limits().max() == std::u32::MAX { maximum: table.limits().max(),
None
} else {
Some(table.limits().max())
},
ty: match table.element() { ty: match table.element() {
ValType::FuncRef => wasm::TableElementType::Func, ValType::FuncRef => wasm::TableElementType::Func,
_ => wasm::TableElementType::Val(table.element().get_wasmtime_type()), _ => wasm::TableElementType::Val(table.element().get_wasmtime_type()),

View File

@@ -4,35 +4,43 @@ use wasmtime_environ::{ir, wasm};
// Type attributes // Type attributes
/// Indicator of whether a global is mutable or not
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum Mutability { pub enum Mutability {
/// The global is constant and its value does not change
Const, Const,
/// The value of the global can change over time
Var, Var,
} }
/// Limits of tables/memories where the units of the limits are defined by the
/// table/memory types.
///
/// A minimum is always available but the maximum may not be present.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Limits { pub struct Limits {
min: u32, min: u32,
max: u32, max: Option<u32>,
} }
impl Limits { impl Limits {
pub fn new(min: u32, max: u32) -> Limits { /// Creates a new set of limits with the minimum and maximum both specified.
pub fn new(min: u32, max: Option<u32>) -> Limits {
Limits { min, max } Limits { min, max }
} }
/// Creates a new `Limits` with the `min` specified and no maximum specified.
pub fn at_least(min: u32) -> Limits { pub fn at_least(min: u32) -> Limits {
Limits { Limits::new(min, None)
min,
max: ::std::u32::MAX,
}
} }
/// Returns the minimum amount for these limits.
pub fn min(&self) -> u32 { pub fn min(&self) -> u32 {
self.min self.min
} }
pub fn max(&self) -> u32 { /// Returs the maximum amount for these limits, if specified.
pub fn max(&self) -> Option<u32> {
self.max self.max
} }
} }
@@ -90,52 +98,63 @@ impl ValType {
// External Types // External Types
/// A list of all possible types which can be externally referenced from a
/// WebAssembly module.
///
/// This list can be found in [`ImportType`] or [`ExportType`], so these types
/// can either be imported or exported.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum ExternType { pub enum ExternType {
ExternFunc(FuncType), Func(FuncType),
ExternGlobal(GlobalType), Global(GlobalType),
ExternTable(TableType), Table(TableType),
ExternMemory(MemoryType), Memory(MemoryType),
}
macro_rules! accessors {
($(($variant:ident($ty:ty) $get:ident $unwrap:ident))*) => ($(
/// Attempt to return the underlying type of this external type,
/// returning `None` if it is a different type.
pub fn $get(&self) -> Option<&$ty> {
if let ExternType::$variant(e) = self {
Some(e)
} else {
None
}
}
/// Returns the underlying descriptor of this [`ExternType`], panicking
/// if it is a different type.
///
/// # Panics
///
/// Panics if `self` is not of the right type.
pub fn $unwrap(&self) -> &$ty {
self.$get().expect(concat!("expected ", stringify!($ty)))
}
)*)
} }
impl ExternType { impl ExternType {
pub fn func(&self) -> &FuncType { accessors! {
match self { (Func(FuncType) func unwrap_func)
ExternType::ExternFunc(func) => func, (Global(GlobalType) global unwrap_global)
_ => panic!("ExternType::ExternFunc expected"), (Table(TableType) table unwrap_table)
} (Memory(MemoryType) memory unwrap_memory)
}
pub fn global(&self) -> &GlobalType {
match self {
ExternType::ExternGlobal(func) => func,
_ => panic!("ExternType::ExternGlobal expected"),
}
}
pub fn table(&self) -> &TableType {
match self {
ExternType::ExternTable(table) => table,
_ => panic!("ExternType::ExternTable expected"),
}
}
pub fn memory(&self) -> &MemoryType {
match self {
ExternType::ExternMemory(memory) => memory,
_ => panic!("ExternType::ExternMemory expected"),
}
} }
pub(crate) fn from_wasmtime_export(export: &wasmtime_runtime::Export) -> Self { pub(crate) fn from_wasmtime_export(export: &wasmtime_runtime::Export) -> Self {
match export { match export {
wasmtime_runtime::Export::Function { signature, .. } => { wasmtime_runtime::Export::Function { signature, .. } => {
ExternType::ExternFunc(FuncType::from_wasmtime_signature(signature.clone())) ExternType::Func(FuncType::from_wasmtime_signature(signature.clone()))
} }
wasmtime_runtime::Export::Memory { memory, .. } => { wasmtime_runtime::Export::Memory { memory, .. } => {
ExternType::ExternMemory(MemoryType::from_wasmtime_memory(&memory.memory)) ExternType::Memory(MemoryType::from_wasmtime_memory(&memory.memory))
} }
wasmtime_runtime::Export::Global { global, .. } => { wasmtime_runtime::Export::Global { global, .. } => {
ExternType::ExternGlobal(GlobalType::from_wasmtime_global(&global)) ExternType::Global(GlobalType::from_wasmtime_global(&global))
} }
wasmtime_runtime::Export::Table { table, .. } => { wasmtime_runtime::Export::Table { table, .. } => {
ExternType::ExternTable(TableType::from_wasmtime_table(&table.table)) ExternType::Table(TableType::from_wasmtime_table(&table.table))
} }
} }
} }
@@ -147,6 +166,9 @@ fn from_wasmtime_abiparam(param: &ir::AbiParam) -> ValType {
ValType::from_wasmtime_type(param.value_type) ValType::from_wasmtime_type(param.value_type)
} }
/// A descriptor for a function in a WebAssembly module.
///
/// WebAssembly functions can have 0 or more parameters and results.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct FuncType { pub struct FuncType {
params: Box<[ValType]>, params: Box<[ValType]>,
@@ -155,6 +177,10 @@ pub struct FuncType {
} }
impl FuncType { impl FuncType {
/// Creates a new function descriptor from the given parameters and results.
///
/// The function descriptor returned will represent a function which takes
/// `params` as arguments and returns `results` when it is finished.
pub fn new(params: Box<[ValType]>, results: Box<[ValType]>) -> FuncType { pub fn new(params: Box<[ValType]>, results: Box<[ValType]>) -> FuncType {
use wasmtime_environ::ir::{types, AbiParam, ArgumentPurpose, Signature}; use wasmtime_environ::ir::{types, AbiParam, ArgumentPurpose, Signature};
use wasmtime_jit::native; use wasmtime_jit::native;
@@ -182,9 +208,13 @@ impl FuncType {
signature, signature,
} }
} }
/// Returns the list of parameter types for this function.
pub fn params(&self) -> &[ValType] { pub fn params(&self) -> &[ValType] {
&self.params &self.params
} }
/// Returns the list of result types for this function.
pub fn results(&self) -> &[ValType] { pub fn results(&self) -> &[ValType] {
&self.results &self.results
} }
@@ -215,6 +245,11 @@ impl FuncType {
// Global Types // Global Types
/// A WebAssembly global descriptor.
///
/// This type describes an instance of a global in a WebAssembly module. Globals
/// are local to an [`Instance`](crate::Instance) and are either immutable or
/// mutable.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct GlobalType { pub struct GlobalType {
content: ValType, content: ValType,
@@ -222,15 +257,21 @@ pub struct GlobalType {
} }
impl GlobalType { impl GlobalType {
/// Creates a new global descriptor of the specified `content` type and
/// whether or not it's mutable.
pub fn new(content: ValType, mutability: Mutability) -> GlobalType { pub fn new(content: ValType, mutability: Mutability) -> GlobalType {
GlobalType { GlobalType {
content, content,
mutability, mutability,
} }
} }
/// Returns the value type of this global descriptor.
pub fn content(&self) -> &ValType { pub fn content(&self) -> &ValType {
&self.content &self.content
} }
/// Returns whether or not this global is mutable.
pub fn mutability(&self) -> Mutability { pub fn mutability(&self) -> Mutability {
self.mutability self.mutability
} }
@@ -248,6 +289,11 @@ impl GlobalType {
// Table Types // Table Types
/// A descriptor for a table in a WebAssembly module.
///
/// Tables are contiguous chunks of a specific element, typically a `funcref` or
/// an `anyref`. The most common use for tables is a function table through
/// which `call_indirect` can invoke other functions.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct TableType { pub struct TableType {
element: ValType, element: ValType,
@@ -255,12 +301,18 @@ pub struct TableType {
} }
impl TableType { impl TableType {
/// Creates a new table descriptor which will contain the specified
/// `element` and have the `limits` applied to its length.
pub fn new(element: ValType, limits: Limits) -> TableType { pub fn new(element: ValType, limits: Limits) -> TableType {
TableType { element, limits } TableType { element, limits }
} }
/// Returns the element value type of this table.
pub fn element(&self) -> &ValType { pub fn element(&self) -> &ValType {
&self.element &self.element
} }
/// Returns the limits, in units of elements, of this table.
pub fn limits(&self) -> &Limits { pub fn limits(&self) -> &Limits {
&self.limits &self.limits
} }
@@ -272,103 +324,113 @@ impl TableType {
false false
}); });
let ty = ValType::FuncRef; let ty = ValType::FuncRef;
let limits = Limits::new(table.minimum, table.maximum.unwrap_or(::std::u32::MAX)); let limits = Limits::new(table.minimum, table.maximum);
TableType::new(ty, limits) TableType::new(ty, limits)
} }
} }
// Memory Types // Memory Types
/// A descriptor for a WebAssembly memory type.
///
/// Memories are described in units of pages (64KB) and represent contiguous
/// chunks of addressable memory.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct MemoryType { pub struct MemoryType {
limits: Limits, limits: Limits,
} }
impl MemoryType { impl MemoryType {
/// Creates a new descriptor for a WebAssembly memory given the specified
/// limits of the memory.
pub fn new(limits: Limits) -> MemoryType { pub fn new(limits: Limits) -> MemoryType {
MemoryType { limits } MemoryType { limits }
} }
/// Returns the limits (in pages) that are configured for this memory.
pub fn limits(&self) -> &Limits { pub fn limits(&self) -> &Limits {
&self.limits &self.limits
} }
pub(crate) fn from_wasmtime_memory(memory: &wasm::Memory) -> MemoryType { pub(crate) fn from_wasmtime_memory(memory: &wasm::Memory) -> MemoryType {
MemoryType::new(Limits::new( MemoryType::new(Limits::new(memory.minimum, memory.maximum))
memory.minimum,
memory.maximum.unwrap_or(::std::u32::MAX),
))
} }
} }
// Import Types // Import Types
#[derive(Debug, Clone)] /// A descriptor for an imported value into a wasm module.
pub struct Name(String); ///
/// This type is primarily accessed from the
impl Name { /// [`Module::imports`](crate::Module::imports) API. Each [`ImportType`]
pub fn new(value: &str) -> Self { /// describes an import into the wasm module with the module/name that it's
Name(value.to_owned()) /// imported from as well as the type of item that's being imported.
}
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl From<String> for Name {
fn from(s: String) -> Name {
Name(s)
}
}
impl ToString for Name {
fn to_string(&self) -> String {
self.0.to_owned()
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ImportType { pub struct ImportType {
module: Name, module: String,
name: Name, name: String,
r#type: ExternType, ty: ExternType,
} }
impl ImportType { impl ImportType {
pub fn new(module: Name, name: Name, r#type: ExternType) -> ImportType { /// Creates a new import descriptor which comes from `module` and `name` and
/// is of type `ty`.
pub fn new(module: &str, name: &str, ty: ExternType) -> ImportType {
ImportType { ImportType {
module, module: module.to_string(),
name, name: name.to_string(),
r#type, ty,
} }
} }
pub fn module(&self) -> &Name {
/// Returns the module name that this import is expected to come from.
pub fn module(&self) -> &str {
&self.module &self.module
} }
pub fn name(&self) -> &Name {
/// Returns the field name of the module that this import is expected to
/// come from.
pub fn name(&self) -> &str {
&self.name &self.name
} }
pub fn r#type(&self) -> &ExternType {
&self.r#type /// Returns the expected type of this import.
pub fn ty(&self) -> &ExternType {
&self.ty
} }
} }
// Export Types // Export Types
/// A descriptor for an exported WebAssembly value.
///
/// This type is primarily accessed from the
/// [`Module::exports`](crate::Module::exports) accessor and describes what
/// names are exported from a wasm module and the type of the item that is
/// exported.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ExportType { pub struct ExportType {
name: Name, name: String,
r#type: ExternType, ty: ExternType,
} }
impl ExportType { impl ExportType {
pub fn new(name: Name, r#type: ExternType) -> ExportType { /// Creates a new export which is exported with the given `name` and has the
ExportType { name, r#type } /// given `ty`.
pub fn new(name: &str, ty: ExternType) -> ExportType {
ExportType {
name: name.to_string(),
ty,
}
} }
pub fn name(&self) -> &Name {
/// Returns the name by which this export is known by.
pub fn name(&self) -> &str {
&self.name &self.name
} }
pub fn r#type(&self) -> &ExternType {
&self.r#type /// Returns the type of this export.
pub fn ty(&self) -> &ExternType {
&self.ty
} }
} }

View File

@@ -7,8 +7,8 @@
use super::{ use super::{
AnyRef, Callable, Engine, ExportType, Extern, ExternType, Func, FuncType, Global, GlobalType, AnyRef, Callable, Engine, ExportType, Extern, ExternType, Func, FuncType, Global, GlobalType,
HostInfo, HostRef, ImportType, Instance, Limits, Memory, MemoryType, Module, Name, Store, HostInfo, HostRef, ImportType, Instance, Limits, Memory, MemoryType, Module, Store, Table,
Table, TableType, Trap, Val, ValType, TableType, Trap, Val, ValType,
}; };
use std::rc::Rc; use std::rc::Rc;
use std::{mem, ptr, slice}; use std::{mem, ptr, slice};
@@ -714,11 +714,8 @@ pub unsafe extern "C" fn wasm_module_delete(module: *mut wasm_module_t) {
} }
impl wasm_name_t { impl wasm_name_t {
fn from_name(name: &Name) -> wasm_name_t { fn from_name(name: &str) -> wasm_name_t {
let s = name.to_string(); name.to_string().into_bytes().into()
let mut buffer = Vec::new();
buffer.extend_from_slice(s.as_bytes());
buffer.into()
} }
} }
@@ -977,7 +974,7 @@ pub unsafe extern "C" fn wasm_importtype_type(
it: *const wasm_importtype_t, it: *const wasm_importtype_t,
) -> *const wasm_externtype_t { ) -> *const wasm_externtype_t {
let ty = Box::new(wasm_externtype_t { let ty = Box::new(wasm_externtype_t {
ty: (*it).ty.r#type().clone(), ty: (*it).ty.ty().clone(),
cache: wasm_externtype_t_type_cache::Empty, cache: wasm_externtype_t_type_cache::Empty,
}); });
Box::into_raw(ty) Box::into_raw(ty)
@@ -1004,7 +1001,7 @@ pub unsafe extern "C" fn wasm_exporttype_type(
if (*et).type_cache.is_none() { if (*et).type_cache.is_none() {
let et = (et as *mut wasm_exporttype_t).as_mut().unwrap(); let et = (et as *mut wasm_exporttype_t).as_mut().unwrap();
et.type_cache = Some(wasm_externtype_t { et.type_cache = Some(wasm_externtype_t {
ty: (*et).ty.r#type().clone(), ty: (*et).ty.ty().clone(),
cache: wasm_externtype_t_type_cache::Empty, cache: wasm_externtype_t_type_cache::Empty,
}); });
} }
@@ -1018,10 +1015,10 @@ pub unsafe extern "C" fn wasm_exporttype_vec_delete(et: *mut wasm_exporttype_vec
fn from_externtype(ty: &ExternType) -> wasm_externkind_t { fn from_externtype(ty: &ExternType) -> wasm_externkind_t {
match ty { match ty {
ExternType::ExternFunc(_) => 0, ExternType::Func(_) => 0,
ExternType::ExternGlobal(_) => 1, ExternType::Global(_) => 1,
ExternType::ExternTable(_) => 2, ExternType::Table(_) => 2,
ExternType::ExternMemory(_) => 3, ExternType::Memory(_) => 3,
} }
} }
@@ -1044,7 +1041,7 @@ pub unsafe extern "C" fn wasm_externtype_as_functype_const(
et: *const wasm_externtype_t, et: *const wasm_externtype_t,
) -> *const wasm_functype_t { ) -> *const wasm_functype_t {
if let wasm_externtype_t_type_cache::Empty = (*et).cache { if let wasm_externtype_t_type_cache::Empty = (*et).cache {
let functype = (*et).ty.func().clone(); let functype = (*et).ty.unwrap_func().clone();
let f = wasm_functype_t { let f = wasm_functype_t {
functype, functype,
params_cache: None, params_cache: None,
@@ -1064,7 +1061,7 @@ pub unsafe extern "C" fn wasm_externtype_as_globaltype_const(
et: *const wasm_externtype_t, et: *const wasm_externtype_t,
) -> *const wasm_globaltype_t { ) -> *const wasm_globaltype_t {
if let wasm_externtype_t_type_cache::Empty = (*et).cache { if let wasm_externtype_t_type_cache::Empty = (*et).cache {
let globaltype = (*et).ty.global().clone(); let globaltype = (*et).ty.unwrap_global().clone();
let g = wasm_globaltype_t { let g = wasm_globaltype_t {
globaltype, globaltype,
content_cache: None, content_cache: None,
@@ -1083,7 +1080,7 @@ pub unsafe extern "C" fn wasm_externtype_as_tabletype_const(
et: *const wasm_externtype_t, et: *const wasm_externtype_t,
) -> *const wasm_tabletype_t { ) -> *const wasm_tabletype_t {
if let wasm_externtype_t_type_cache::Empty = (*et).cache { if let wasm_externtype_t_type_cache::Empty = (*et).cache {
let tabletype = (*et).ty.table().clone(); let tabletype = (*et).ty.unwrap_table().clone();
let t = wasm_tabletype_t { let t = wasm_tabletype_t {
tabletype, tabletype,
element_cache: None, element_cache: None,
@@ -1103,7 +1100,7 @@ pub unsafe extern "C" fn wasm_externtype_as_memorytype_const(
et: *const wasm_externtype_t, et: *const wasm_externtype_t,
) -> *const wasm_memorytype_t { ) -> *const wasm_memorytype_t {
if let wasm_externtype_t_type_cache::Empty = (*et).cache { if let wasm_externtype_t_type_cache::Empty = (*et).cache {
let memorytype = (*et).ty.memory().clone(); let memorytype = (*et).ty.unwrap_memory().clone();
let m = wasm_memorytype_t { let m = wasm_memorytype_t {
memorytype, memorytype,
limits_cache: None, limits_cache: None,
@@ -1210,7 +1207,7 @@ pub unsafe extern "C" fn wasm_memorytype_limits(
let limits = (*mt).memorytype.limits(); let limits = (*mt).memorytype.limits();
mt.limits_cache = Some(wasm_limits_t { mt.limits_cache = Some(wasm_limits_t {
min: limits.min(), min: limits.min(),
max: limits.max(), max: limits.max().unwrap_or(u32::max_value()),
}); });
} }
(*mt).limits_cache.as_ref().unwrap() (*mt).limits_cache.as_ref().unwrap()
@@ -1270,7 +1267,7 @@ pub unsafe extern "C" fn wasm_tabletype_limits(
let limits = (*tt).tabletype.limits(); let limits = (*tt).tabletype.limits();
tt.limits_cache = Some(wasm_limits_t { tt.limits_cache = Some(wasm_limits_t {
min: limits.min(), min: limits.min(),
max: limits.max(), max: limits.max().unwrap_or(u32::max_value()),
}); });
} }
(*tt).limits_cache.as_ref().unwrap() (*tt).limits_cache.as_ref().unwrap()
@@ -1469,7 +1466,12 @@ pub unsafe extern "C" fn wasm_memorytype_delete(mt: *mut wasm_memorytype_t) {
pub unsafe extern "C" fn wasm_memorytype_new( pub unsafe extern "C" fn wasm_memorytype_new(
limits: *const wasm_limits_t, limits: *const wasm_limits_t,
) -> *mut wasm_memorytype_t { ) -> *mut wasm_memorytype_t {
let limits = Limits::new((*limits).min, (*limits).max); let max = if (*limits).max == u32::max_value() {
None
} else {
Some((*limits).max)
};
let limits = Limits::new((*limits).min, max);
let mt = Box::new(wasm_memorytype_t { let mt = Box::new(wasm_memorytype_t {
memorytype: MemoryType::new(limits), memorytype: MemoryType::new(limits),
limits_cache: None, limits_cache: None,
@@ -1619,7 +1621,12 @@ pub unsafe extern "C" fn wasm_tabletype_new(
limits: *const wasm_limits_t, limits: *const wasm_limits_t,
) -> *mut wasm_tabletype_t { ) -> *mut wasm_tabletype_t {
let ty = Box::from_raw(ty).ty; let ty = Box::from_raw(ty).ty;
let limits = Limits::new((*limits).min, (*limits).max); let max = if (*limits).max == u32::max_value() {
None
} else {
Some((*limits).max)
};
let limits = Limits::new((*limits).min, max);
let tt = Box::new(wasm_tabletype_t { let tt = Box::new(wasm_tabletype_t {
tabletype: TableType::new(ty, limits), tabletype: TableType::new(ty, limits),
element_cache: None, element_cache: None,

View File

@@ -13,17 +13,17 @@ pub fn dummy_imports(
) -> Result<Vec<Extern>, HostRef<Trap>> { ) -> Result<Vec<Extern>, HostRef<Trap>> {
let mut imports = Vec::with_capacity(import_tys.len()); let mut imports = Vec::with_capacity(import_tys.len());
for imp in import_tys { for imp in import_tys {
imports.push(match imp.r#type() { imports.push(match imp.ty() {
ExternType::ExternFunc(func_ty) => { ExternType::Func(func_ty) => {
Extern::Func(HostRef::new(DummyFunc::new(&store, func_ty.clone()))) Extern::Func(HostRef::new(DummyFunc::new(&store, func_ty.clone())))
} }
ExternType::ExternGlobal(global_ty) => { ExternType::Global(global_ty) => {
Extern::Global(HostRef::new(dummy_global(&store, global_ty.clone())?)) Extern::Global(HostRef::new(dummy_global(&store, global_ty.clone())?))
} }
ExternType::ExternTable(table_ty) => { ExternType::Table(table_ty) => {
Extern::Table(HostRef::new(dummy_table(&store, table_ty.clone())?)) Extern::Table(HostRef::new(dummy_table(&store, table_ty.clone())?))
} }
ExternType::ExternMemory(mem_ty) => { ExternType::Memory(mem_ty) => {
Extern::Memory(HostRef::new(dummy_memory(&store, mem_ty.clone()))) Extern::Memory(HostRef::new(dummy_memory(&store, mem_ty.clone())))
} }
}); });

View File

@@ -22,8 +22,8 @@ impl Instance {
let exports = PyDict::new(py); let exports = PyDict::new(py);
let module = self.instance.borrow().module().clone(); let module = self.instance.borrow().module().clone();
for (i, e) in module.borrow().exports().iter().enumerate() { for (i, e) in module.borrow().exports().iter().enumerate() {
match e.r#type() { match e.ty() {
wasmtime::ExternType::ExternFunc(ft) => { wasmtime::ExternType::Func(ft) => {
let mut args_types = Vec::new(); let mut args_types = Vec::new();
for ty in ft.params().iter() { for ty in ft.params().iter() {
args_types.push(ty.clone()); args_types.push(ty.clone());
@@ -39,7 +39,7 @@ impl Instance {
)?; )?;
exports.set_item(e.name().to_string(), f)?; exports.set_item(e.name().to_string(), f)?;
} }
wasmtime::ExternType::ExternMemory(_) => { wasmtime::ExternType::Memory(_) => {
let f = Py::new( let f = Py::new(
py, py,
Memory { Memory {

View File

@@ -111,21 +111,18 @@ pub fn instantiate(
let mut imports: Vec<wasmtime::Extern> = Vec::new(); let mut imports: Vec<wasmtime::Extern> = Vec::new();
for i in module.borrow().imports() { for i in module.borrow().imports() {
let module_name = i.module().as_str(); let module_name = i.module();
if let Some(m) = import_obj.get_item(module_name) { if let Some(m) = import_obj.get_item(module_name) {
let e = find_export_in(m, &store, i.name().as_str())?; let e = find_export_in(m, &store, i.name())?;
imports.push(e); imports.push(e);
} else if wasi.is_some() && module_name == wasi.as_ref().unwrap().0 { } else if wasi.is_some() && module_name == wasi.as_ref().unwrap().0 {
let e = wasi let e = wasi
.as_ref() .as_ref()
.unwrap() .unwrap()
.1 .1
.find_export_by_name(i.name().as_str()) .find_export_by_name(i.name())
.ok_or_else(|| { .ok_or_else(|| {
PyErr::new::<Exception, _>(format!( PyErr::new::<Exception, _>(format!("wasi export {} is not found", i.name(),))
"wasi export {} is not found",
i.name().as_str()
))
})?; })?;
imports.push(e.clone()); imports.push(e.clone());
} else { } else {

View File

@@ -69,13 +69,13 @@ fn generate_load(item: &syn::ItemTrait) -> syn::Result<TokenStream> {
let wasi_instance = #root::wasmtime_wasi::create_wasi_instance(&store, &[], &[], &[]) let wasi_instance = #root::wasmtime_wasi::create_wasi_instance(&store, &[], &[], &[])
.map_err(|e| format_err!("wasm instantiation error: {:?}", e))?; .map_err(|e| format_err!("wasm instantiation error: {:?}", e))?;
for i in module.borrow().imports().iter() { for i in module.borrow().imports().iter() {
if i.module().as_str() != module_name { if i.module() != module_name {
bail!("unknown import module {}", i.module().as_str()); bail!("unknown import module {}", i.module());
} }
if let Some(export) = wasi_instance.find_export_by_name(i.name().as_str()) { if let Some(export) = wasi_instance.find_export_by_name(i.name()) {
imports.push(export.clone()); imports.push(export.clone());
} else { } else {
bail!("unknown import {}:{}", i.module().as_str(), i.name().as_str()) bail!("unknown import {}:{}", i.module(), i.name())
} }
} }
} }

View File

@@ -68,9 +68,9 @@ pub fn instantiate(data: &[u8], bin_name: &str, workspace: Option<&Path>) -> any
.imports() .imports()
.iter() .iter()
.map(|i| { .map(|i| {
let module_name = i.module().as_str(); let module_name = i.module();
if let Some(instance) = module_registry.get(module_name) { if let Some(instance) = module_registry.get(module_name) {
let field_name = i.name().as_str(); let field_name = i.name();
if let Some(export) = instance.find_export_by_name(field_name) { if let Some(export) = instance.find_export_by_name(field_name) {
Ok(export.clone()) Ok(export.clone())
} else { } else {

View File

@@ -341,9 +341,9 @@ fn instantiate_module(
.imports() .imports()
.iter() .iter()
.map(|i| { .map(|i| {
let module_name = i.module().as_str(); let module_name = i.module();
if let Some(instance) = module_registry.get(module_name) { if let Some(instance) = module_registry.get(module_name) {
let field_name = i.name().as_str(); let field_name = i.name();
if let Some(export) = instance.borrow().find_export_by_name(field_name) { if let Some(export) = instance.borrow().find_export_by_name(field_name) {
Ok(export.clone()) Ok(export.clone())
} else { } else {
@@ -380,7 +380,7 @@ fn handle_module(
.borrow() .borrow()
.exports() .exports()
.iter() .iter()
.find(|export| export.name().as_str().is_empty()) .find(|export| export.name().is_empty())
.is_some() .is_some()
{ {
// Launch the default command export. // Launch the default command export.