diff --git a/lib/js-api/src/externals/function.rs b/lib/js-api/src/externals/function.rs index 6f61de87e..ecf0d51f6 100644 --- a/lib/js-api/src/externals/function.rs +++ b/lib/js-api/src/externals/function.rs @@ -57,79 +57,8 @@ pub struct Function { pub(crate) exported: VMFunction, } -impl wasmer_types::WasmValueType for Function { - /// Write the value. - unsafe fn write_value_to(&self, _p: *mut i128) { - // let func_ref = - // Val::into_vm_funcref(&Val::FuncRef(Some(self.clone())), &self.store).unwrap(); - // std::ptr::write(p as *mut VMFuncRef, func_ref); - unimplemented!(); - } - - /// Read the value. - // TODO(reftypes): this entire function should be cleaned up, `dyn Any` should - // ideally be removed - unsafe fn read_value_from(_store: &dyn std::any::Any, _p: *const i128) -> Self { - unimplemented!(); - // let func_ref = std::ptr::read(p as *const VMFuncRef); - // let store = store.downcast_ref::().expect("Store expected in `Function::read_value_from`. If you see this error message it likely means you're using a function ref in a place we don't yet support it -- sorry about the inconvenience."); - // match Val::from_vm_funcref(func_ref, store) { - // Val::FuncRef(Some(fr)) => fr, - // // these bottom two cases indicate bugs in `wasmer-types` or elsewhere. - // // They should never be triggered, so we just panic. - // Val::FuncRef(None) => panic!("Null funcref found in `Function::read_value_from`!"), - // other => panic!("Invalid value in `Function::read_value_from`: {:?}", other), - // } - } -} - -// fn build_export_function_metadata( -// env: Env, -// import_init_function_ptr: for<'a> fn( -// &'a mut Env, -// &'a crate::Instance, -// ) -> Result<(), crate::HostEnvInitError>, -// ) -> (*mut c_void, ExportFunctionMetadata) -// where -// Env: Clone + Sized + 'static + Send + Sync, -// { -// let import_init_function_ptr = Some(unsafe { -// std::mem::transmute::<_, ImportInitializerFuncPtr>(import_init_function_ptr) -// }); -// let host_env_clone_fn = |ptr: *mut c_void| -> *mut c_void { -// let env_ref: &Env = unsafe { -// ptr.cast::() -// .as_ref() -// .expect("`ptr` to the environment is null when cloning it") -// }; -// Box::into_raw(Box::new(env_ref.clone())) as _ -// }; -// let host_env_drop_fn = |ptr: *mut c_void| { -// unsafe { Box::from_raw(ptr.cast::()) }; -// }; -// let env = Box::into_raw(Box::new(env)) as _; - -// // # Safety -// // - All these functions work on all threads -// // - The host env is `Send`. -// let metadata = unsafe { -// ExportFunctionMetadata::new( -// env, -// import_init_function_ptr, -// host_env_clone_fn, -// host_env_drop_fn, -// ) -// }; - -// (env, metadata) -// } - impl WasmerEnv for WithoutEnv {} -pub extern "C" fn call_func_dynamic(arg: u32) -> u32 { - return arg + 1; -} - impl Function { /// Creates a new host `Function` (dynamic) with the provided signature. /// @@ -197,7 +126,7 @@ impl Function { }) as Box Result>) .into_js_value(), - n => Closure::wrap(Box::new(move |args: &Array| { + _n => Closure::wrap(Box::new(move |args: &Array| { let wasm_arguments = new_ty .params() .iter() @@ -288,7 +217,7 @@ impl Function { .collect::>(); let env_ptr = args.get(0).as_f64().unwrap() as usize; let env: &Env = unsafe { &*(env_ptr as *const u8 as *const Env) }; - let results = func(env, &wasm_arguments)?; + let _results = func(env, &wasm_arguments)?; Ok(()) }) as Box Result<(), JsValue>>) @@ -307,7 +236,7 @@ impl Function { }) as Box Result>) .into_js_value(), - n => Closure::wrap(Box::new(move |args: &Array| { + _n => Closure::wrap(Box::new(move |args: &Array| { let wasm_arguments = new_ty .params() .iter() @@ -457,76 +386,6 @@ impl Function { &self.store } - // fn call_wasm( - // &self, - // trampoline: VMTrampoline, - // params: &[Val], - // results: &mut [Val], - // ) -> Result<(), RuntimeError> { - // let format_types_for_error_message = |items: &[Val]| { - // items - // .iter() - // .map(|param| param.ty().to_string()) - // .collect::>() - // .join(", ") - // }; - // let signature = self.ty(); - // if signature.params().len() != params.len() { - // return Err(RuntimeError::new(format!( - // "Parameters of type [{}] did not match signature {}", - // format_types_for_error_message(params), - // &signature - // ))); - // } - // if signature.results().len() != results.len() { - // return Err(RuntimeError::new(format!( - // "Results of type [{}] did not match signature {}", - // format_types_for_error_message(results), - // &signature, - // ))); - // } - - // let mut values_vec = vec![0; max(params.len(), results.len())]; - - // // Store the argument values into `values_vec`. - // let param_tys = signature.params().iter(); - // for ((arg, slot), ty) in params.iter().zip(&mut values_vec).zip(param_tys) { - // if arg.ty() != *ty { - // let param_types = format_types_for_error_message(params); - // return Err(RuntimeError::new(format!( - // "Parameters of type [{}] did not match signature {}", - // param_types, &signature, - // ))); - // } - // unsafe { - // arg.write_value_to(slot); - // } - // } - - // // Call the trampoline. - // if let Err(error) = unsafe { - // wasmer_call_trampoline( - // &self.store, - // self.exported.vm_function.vmctx, - // trampoline, - // self.exported.vm_function.address, - // values_vec.as_mut_ptr() as *mut u8, - // ) - // } { - // return Err(RuntimeError::from_trap(error)); - // } - - // // Load the return values out of `values_vec`. - // for (index, &value_type) in signature.results().iter().enumerate() { - // unsafe { - // let ptr = values_vec.as_ptr().add(index); - // results[index] = Val::read_value_from(&self.store, ptr, value_type); - // } - // } - - // Ok(()) - // } - /// Returns the number of parameters that this function takes. /// /// # Example @@ -632,17 +491,6 @@ impl Function { } } - // pub(crate) fn vm_funcref(&self) -> VMFuncRef { - // unimplemented!(); - // // let engine = self.store.engine(); - // // let vmsignature = engine.register_signature(&self.exported.vm_function.signature); - // // engine.register_function_metadata(VMCallerCheckedAnyfunc { - // // func_ptr: self.exported.vm_function.address, - // // type_index: vmsignature, - // // vmctx: self.exported.vm_function.vmctx, - // // }) - // } - /// Transform this WebAssembly function into a function with the /// native ABI. See [`NativeFunc`] to learn more. /// @@ -782,112 +630,6 @@ impl fmt::Debug for Function { } } -// /// This trait is one that all dynamic functions must fulfill. -// pub(crate) trait VMDynamicFunction: Send + Sync { -// fn call(&self, args: &[Val]) -> Result, RuntimeError>; -// fn function_type(&self) -> &FunctionType; -// fn store(&self) -> &Store; -// } - -// pub(crate) struct DynamicFunction -// where -// Env: Sized + 'static + Send + Sync, -// { -// function_type: FunctionType, -// #[allow(clippy::type_complexity)] -// func: Arc Result, RuntimeError> + 'static + Send + Sync>, -// store: Store, -// env: Box, -// } - -// impl Clone for DynamicFunction { -// fn clone(&self) -> Self { -// Self { -// env: self.env.clone(), -// function_type: self.function_type.clone(), -// store: self.store.clone(), -// func: self.func.clone(), -// } -// } -// } - -// impl VMDynamicFunction for DynamicFunction -// where -// Env: Sized + 'static + Send + Sync, -// { -// fn call(&self, args: &[Val]) -> Result, RuntimeError> { -// (*self.func)(&*self.env, &args) -// } -// fn function_type(&self) -> &FunctionType { -// &self.function_type -// } -// fn store(&self) -> &Store { -// &self.store -// } -// } - -// trait VMDynamicFunctionCall { -// fn from_context(ctx: T) -> Self; -// fn address_ptr() -> *const VMFunctionBody; -// unsafe fn func_wrapper(&self, values_vec: *mut i128); -// } - -// impl VMDynamicFunctionCall for VMDynamicFunctionContext { -// fn from_context(ctx: T) -> Self { -// Self { -// address: Self::address_ptr(), -// ctx, -// } -// } - -// fn address_ptr() -> *const VMFunctionBody { -// Self::func_wrapper as *const () as *const VMFunctionBody -// } - -// // This function wraps our func, to make it compatible with the -// // reverse trampoline signature -// unsafe fn func_wrapper( -// // Note: we use the trick that the first param to this function is the `VMDynamicFunctionContext` -// // itself, so rather than doing `dynamic_ctx: &VMDynamicFunctionContext`, we simplify it a bit -// &self, -// values_vec: *mut i128, -// ) { -// use std::panic::{self, AssertUnwindSafe}; -// let result = panic::catch_unwind(AssertUnwindSafe(|| { -// let func_ty = self.ctx.function_type(); -// let mut args = Vec::with_capacity(func_ty.params().len()); -// let store = self.ctx.store(); -// for (i, ty) in func_ty.params().iter().enumerate() { -// args.push(Val::read_value_from(store, values_vec.add(i), *ty)); -// } -// let returns = self.ctx.call(&args)?; - -// // We need to dynamically check that the returns -// // match the expected types, as well as expected length. -// let return_types = returns.iter().map(|ret| ret.ty()).collect::>(); -// if return_types != func_ty.results() { -// return Err(RuntimeError::new(format!( -// "Dynamic function returned wrong signature. Expected {:?} but got {:?}", -// func_ty.results(), -// return_types -// ))); -// } -// for (i, ret) in returns.iter().enumerate() { -// ret.write_value_to(values_vec.add(i)); -// } -// Ok(()) -// })); // We get extern ref drops at the end of this block that we don't need. -// // By preventing extern ref incs in the code above we can save the work of -// // incrementing and decrementing. However the logic as-is is correct. - -// match result { -// Ok(Ok(())) => {} -// Ok(Err(trap)) => raise_user_trap(Box::new(trap)), -// Err(panic) => resume_panic(panic), -// } -// } -// } - /// This private inner module contains the low-level implementation /// for `Function` and its siblings. mod inner { @@ -901,7 +643,7 @@ mod inner { #[cfg(feature = "experimental-reference-types-extern-ref")] pub use wasmer_types::{ExternRef, VMExternRef}; use wasmer_types::{FunctionType, NativeWasmType, Type}; - // use wasmer_vm::{raise_user_trap, resume_panic, VMFunctionBody}; + // use wasmer::{raise_user_trap, resume_panic}; /// A trait to convert a Rust value to a `WasmNativeType` value, /// or to convert `WasmNativeType` value to a Rust value. @@ -1370,7 +1112,6 @@ mod inner { let result = panic::catch_unwind(AssertUnwindSafe(|| { func( $( FromToNativeWasmType::from_native($x) ),* ).into_result() })); - // unimplemented!(); match result { Ok(Ok(result)) => return result.into_c_struct(), _ => unimplemented!(), diff --git a/lib/js-api/src/externals/table.rs b/lib/js-api/src/externals/table.rs index 287764322..20c8281f0 100644 --- a/lib/js-api/src/externals/table.rs +++ b/lib/js-api/src/externals/table.rs @@ -109,11 +109,6 @@ impl Table { /// Returns an error if the `delta` is out of bounds for the table. pub fn grow(&self, _delta: u32, _init: Val) -> Result { unimplemented!(); - // let item = init.into_table_reference(&self.store)?; - // self.vm_table - // .from - // .grow(delta, item) - // .ok_or_else(|| RuntimeError::new(format!("failed to grow table by `{}`", delta))) } /// Copies the `len` elements of `src_table` starting at `src_index` @@ -131,20 +126,6 @@ impl Table { _len: u32, ) -> Result<(), RuntimeError> { unimplemented!(); - // if !Store::same(&dst_table.store, &src_table.store) { - // return Err(RuntimeError::new( - // "cross-`Store` table copies are not supported", - // )); - // } - // RuntimeTable::copy( - // dst_table.vm_table.from.as_ref(), - // src_table.vm_table.from.as_ref(), - // dst_index, - // src_index, - // len, - // ) - // .map_err(RuntimeError::from_trap)?; - // Ok(()) } pub(crate) fn from_vm_export(store: &Store, vm_table: VMTable) -> Self { @@ -174,8 +155,7 @@ impl Table { impl<'a> Exportable<'a> for Table { fn to_export(&self) -> Export { - // self.vm_table.clone().into() - unimplemented!(); + Export::Table(self.vm_table.clone()) } fn get_self_from_extern(_extern: &'a Extern) -> Result<&'a Self, ExportError> { diff --git a/lib/js-api/src/import_object.rs b/lib/js-api/src/import_object.rs index 6c03dad90..4732cdbce 100644 --- a/lib/js-api/src/import_object.rs +++ b/lib/js-api/src/import_object.rs @@ -55,7 +55,7 @@ impl ImportObject { /// /// # Usage /// ```ignore - /// # use wasmer_vm::{ImportObject, Instance, Namespace}; + /// # use wasmer::{ImportObject, Instance, Namespace}; /// let mut import_object = ImportObject::new(); /// import_object.get_export("module", "name"); /// ``` @@ -78,7 +78,7 @@ impl ImportObject { /// /// # Usage: /// ```ignore - /// # use wasmer_vm::{ImportObject, Instance, Namespace}; + /// # use wasmer::{ImportObject, Instance, Namespace}; /// let mut import_object = ImportObject::new(); /// /// import_object.register("namespace0", instance); @@ -245,167 +245,167 @@ macro_rules! import_namespace { }; } -// #[cfg(test)] -// mod test { -// use super::*; -// use crate::{Global, Store, Val}; -// use wasmer_engine::ChainableNamedResolver; -// use wasmer_types::Type; +#[cfg(test)] +mod test { + use super::*; + use crate::ChainableNamedResolver; + use crate::Type; + use crate::{Global, Store, Val}; -// #[test] -// fn chaining_works() { -// let store = Store::default(); -// let g = Global::new(&store, Val::I32(0)); + #[wasm_bindgen_test] + fn chaining_works() { + let store = Store::default(); + let g = Global::new(&store, Val::I32(0)); -// let imports1 = imports! { -// "dog" => { -// "happy" => g.clone() -// } -// }; + let imports1 = imports! { + "dog" => { + "happy" => g.clone() + } + }; -// let imports2 = imports! { -// "dog" => { -// "small" => g.clone() -// }, -// "cat" => { -// "small" => g.clone() -// } -// }; + let imports2 = imports! { + "dog" => { + "small" => g.clone() + }, + "cat" => { + "small" => g.clone() + } + }; -// let resolver = imports1.chain_front(imports2); + let resolver = imports1.chain_front(imports2); -// let small_cat_export = resolver.resolve_by_name("cat", "small"); -// assert!(small_cat_export.is_some()); + let small_cat_export = resolver.resolve_by_name("cat", "small"); + assert!(small_cat_export.is_some()); -// let happy = resolver.resolve_by_name("dog", "happy"); -// let small = resolver.resolve_by_name("dog", "small"); -// assert!(happy.is_some()); -// assert!(small.is_some()); -// } + let happy = resolver.resolve_by_name("dog", "happy"); + let small = resolver.resolve_by_name("dog", "small"); + assert!(happy.is_some()); + assert!(small.is_some()); + } -// #[test] -// fn extending_conflict_overwrites() { -// let store = Store::default(); -// let g1 = Global::new(&store, Val::I32(0)); -// let g2 = Global::new(&store, Val::I64(0)); + #[wasm_bindgen_test] + fn extending_conflict_overwrites() { + let store = Store::default(); + let g1 = Global::new(&store, Val::I32(0)); + let g2 = Global::new(&store, Val::I64(0)); -// let imports1 = imports! { -// "dog" => { -// "happy" => g1, -// }, -// }; + let imports1 = imports! { + "dog" => { + "happy" => g1, + }, + }; -// let imports2 = imports! { -// "dog" => { -// "happy" => g2, -// }, -// }; + let imports2 = imports! { + "dog" => { + "happy" => g2, + }, + }; -// let resolver = imports1.chain_front(imports2); -// let happy_dog_entry = resolver.resolve_by_name("dog", "happy").unwrap(); + let resolver = imports1.chain_front(imports2); + let happy_dog_entry = resolver.resolve_by_name("dog", "happy").unwrap(); -// assert!(if let Export::Global(happy_dog_global) = happy_dog_entry { -// happy_dog_global.from.ty().ty == Type::I64 -// } else { -// false -// }); + assert!(if let Export::Global(happy_dog_global) = happy_dog_entry { + happy_dog_global.from.ty().ty == Type::I64 + } else { + false + }); -// // now test it in reverse -// let store = Store::default(); -// let g1 = Global::new(&store, Val::I32(0)); -// let g2 = Global::new(&store, Val::I64(0)); + // now test it in reverse + let store = Store::default(); + let g1 = Global::new(&store, Val::I32(0)); + let g2 = Global::new(&store, Val::I64(0)); -// let imports1 = imports! { -// "dog" => { -// "happy" => g1, -// }, -// }; + let imports1 = imports! { + "dog" => { + "happy" => g1, + }, + }; -// let imports2 = imports! { -// "dog" => { -// "happy" => g2, -// }, -// }; + let imports2 = imports! { + "dog" => { + "happy" => g2, + }, + }; -// let resolver = imports1.chain_back(imports2); -// let happy_dog_entry = resolver.resolve_by_name("dog", "happy").unwrap(); + let resolver = imports1.chain_back(imports2); + let happy_dog_entry = resolver.resolve_by_name("dog", "happy").unwrap(); -// assert!(if let Export::Global(happy_dog_global) = happy_dog_entry { -// happy_dog_global.from.ty().ty == Type::I32 -// } else { -// false -// }); -// } + assert!(if let Export::Global(happy_dog_global) = happy_dog_entry { + happy_dog_global.from.ty().ty == Type::I32 + } else { + false + }); + } -// #[test] -// fn namespace() { -// let store = Store::default(); -// let g1 = Global::new(&store, Val::I32(0)); -// let namespace = namespace! { -// "happy" => g1 -// }; -// let imports1 = imports! { -// "dog" => namespace -// }; + #[wasm_bindgen_test] + fn namespace() { + let store = Store::default(); + let g1 = Global::new(&store, Val::I32(0)); + let namespace = namespace! { + "happy" => g1 + }; + let imports1 = imports! { + "dog" => namespace + }; -// let happy_dog_entry = imports1.resolve_by_name("dog", "happy").unwrap(); + let happy_dog_entry = imports1.resolve_by_name("dog", "happy").unwrap(); -// assert!(if let Export::Global(happy_dog_global) = happy_dog_entry { -// happy_dog_global.from.ty().ty == Type::I32 -// } else { -// false -// }); -// } + assert!(if let Export::Global(happy_dog_global) = happy_dog_entry { + happy_dog_global.from.ty().ty == Type::I32 + } else { + false + }); + } -// #[test] -// fn imports_macro_allows_trailing_comma_and_none() { -// use crate::Function; + #[wasm_bindgen_test] + fn imports_macro_allows_trailing_comma_and_none() { + use crate::Function; -// let store = Default::default(); + let store = Default::default(); -// fn func(arg: i32) -> i32 { -// arg + 1 -// } + fn func(arg: i32) -> i32 { + arg + 1 + } -// let _ = imports! { -// "env" => { -// "func" => Function::new_native(&store, func), -// }, -// }; -// let _ = imports! { -// "env" => { -// "func" => Function::new_native(&store, func), -// } -// }; -// let _ = imports! { -// "env" => { -// "func" => Function::new_native(&store, func), -// }, -// "abc" => { -// "def" => Function::new_native(&store, func), -// } -// }; -// let _ = imports! { -// "env" => { -// "func" => Function::new_native(&store, func) -// }, -// }; -// let _ = imports! { -// "env" => { -// "func" => Function::new_native(&store, func) -// } -// }; -// let _ = imports! { -// "env" => { -// "func1" => Function::new_native(&store, func), -// "func2" => Function::new_native(&store, func) -// } -// }; -// let _ = imports! { -// "env" => { -// "func1" => Function::new_native(&store, func), -// "func2" => Function::new_native(&store, func), -// } -// }; -// } -// } + let _ = imports! { + "env" => { + "func" => Function::new_native(&store, func), + }, + }; + let _ = imports! { + "env" => { + "func" => Function::new_native(&store, func), + } + }; + let _ = imports! { + "env" => { + "func" => Function::new_native(&store, func), + }, + "abc" => { + "def" => Function::new_native(&store, func), + } + }; + let _ = imports! { + "env" => { + "func" => Function::new_native(&store, func) + }, + }; + let _ = imports! { + "env" => { + "func" => Function::new_native(&store, func) + } + }; + let _ = imports! { + "env" => { + "func1" => Function::new_native(&store, func), + "func2" => Function::new_native(&store, func) + } + }; + let _ = imports! { + "env" => { + "func1" => Function::new_native(&store, func), + "func2" => Function::new_native(&store, func), + } + }; + } +} diff --git a/lib/js-api/src/instance.rs b/lib/js-api/src/instance.rs index b4579eb2e..4a10ec5f6 100644 --- a/lib/js-api/src/instance.rs +++ b/lib/js-api/src/instance.rs @@ -25,20 +25,6 @@ pub struct Instance { pub exports: Exports, } -// #[cfg(test)] -// mod send_test { -// use super::*; - -// fn is_send() -> bool { -// true -// } - -// #[test] -// fn instance_is_send() { -// assert!(is_send::()); -// } -// } - /// An error while instantiating a module. /// /// This is not a common WebAssembly error, however diff --git a/lib/js-api/src/module.rs b/lib/js-api/src/module.rs index 99428dbc2..e051b8ab8 100644 --- a/lib/js-api/src/module.rs +++ b/lib/js-api/src/module.rs @@ -205,14 +205,6 @@ impl Module { } } - fn compile(_store: &Store, _binary: &[u8]) -> Result { - unimplemented!(); - } - - // fn from_artifact(store: &Store, artifact: Arc) -> Self { - // unimplemented!(); - // } - pub(crate) fn instantiate( &self, resolver: &dyn Resolver, @@ -508,21 +500,19 @@ impl Module { size: exports.length() as usize, } } - // /// Get the custom sections of the module given a `name`. - // /// - // /// # Important - // /// - // /// Following the WebAssembly spec, one name can have multiple - // /// custom sections. That's why an iterator (rather than one element) - // /// is returned. - // pub fn custom_sections<'a>(&'a self, name: &'a str) -> impl Iterator> + 'a { - // unimplemented!(); - // // self.artifact.module_ref().custom_sections(name) - // } + /// Get the custom sections of the module given a `name`. + /// + /// # Important + /// + /// Following the WebAssembly spec, one name can have multiple + /// custom sections. That's why an iterator (rather than one element) + /// is returned. + pub fn custom_sections<'a>(&'a self, name: &'a str) -> impl Iterator> + 'a { + unimplemented!(); + } /// Returns the [`Store`] where the `Instance` belongs. pub fn store(&self) -> &Store { - // unimplemented!(); &self.store } } @@ -534,472 +524,3 @@ impl fmt::Debug for Module { .finish() } } - -// use anyhow::{bail, Result}; -// use std::fmt::Write; -// use wasmparser::*; - -// pub fn wasm_types(bytes: &[u8]) -> Result { -// let mut d = ModuleTypes::new(bytes); -// d.parse()?; -// Ok(d.dst) -// } - -// struct ModuleTypes<'a> { -// bytes: &'a [u8], -// cur: usize, -// } - -// #[derive(Default)] -// struct ModuleTypesIndices { -// funcs: u32, -// globals: u32, -// tables: u32, -// memories: u32, -// } - -// const NBYTES: usize = 4; - -// impl<'a> ModuleTypes<'a> { -// fn new(bytes: &'a [u8]) -> Dump<'a> { -// Dump { -// bytes, -// cur: 0, -// nesting: 0, -// state: String::new(), -// dst: String::new(), -// } -// } - -// fn run(&mut self) -> Result<()> { -// self.print_module()?; -// assert_eq!(self.cur, self.bytes.len()); -// Ok(()) -// } - -// fn print_module(&mut self) -> Result<()> { -// let mut stack = Vec::new(); -// let mut i = ModuleTypesIndices::default(); -// self.nesting += 1; - -// for item in Parser::new(0).parse_all(self.bytes) { -// match item? { -// Payload::Version { num, range } => { -// write!(self.state, "version {}", num)?; -// self.print(range.end)?; -// } -// Payload::TypeSection(s) => self.section(s, "type", |me, end, t| { -// write!(me.state, "[type {}] {:?}", i.types, t)?; -// i.types += 1; -// me.print(end) -// })?, -// Payload::ImportSection(s) => self.section(s, "import", |me, end, imp| { -// write!(me.state, "import ")?; -// match imp.ty { -// ImportSectionEntryType::Function(_) => { -// write!(me.state, "[func {}]", i.funcs)?; -// i.funcs += 1; -// } -// ImportSectionEntryType::Memory(_) => { -// write!(me.state, "[memory {}]", i.memories)?; -// i.memories += 1; -// } -// ImportSectionEntryType::Tag(_) => { -// write!(me.state, "[tag {}]", i.tags)?; -// i.tags += 1; -// } -// ImportSectionEntryType::Table(_) => { -// write!(me.state, "[table {}]", i.tables)?; -// i.tables += 1; -// } -// ImportSectionEntryType::Global(_) => { -// write!(me.state, "[global {}]", i.globals)?; -// i.globals += 1; -// } -// ImportSectionEntryType::Instance(_) => { -// write!(me.state, "[instance {}]", i.instances)?; -// i.instances += 1; -// } -// ImportSectionEntryType::Module(_) => { -// write!(me.state, "[module {}]", i.modules)?; -// i.modules += 1; -// } -// } -// write!(me.state, " {:?}", imp)?; -// me.print(end) -// })?, -// Payload::FunctionSection(s) => { -// let mut cnt = 0; -// self.section(s, "func", |me, end, f| { -// write!(me.state, "[func {}] type {:?}", cnt + i.funcs, f)?; -// cnt += 1; -// me.print(end) -// })? -// } -// Payload::TableSection(s) => self.section(s, "table", |me, end, t| { -// write!(me.state, "[table {}] {:?}", i.tables, t)?; -// i.tables += 1; -// me.print(end) -// })?, -// Payload::MemorySection(s) => self.section(s, "memory", |me, end, m| { -// write!(me.state, "[memory {}] {:?}", i.memories, m)?; -// i.memories += 1; -// me.print(end) -// })?, -// Payload::TagSection(s) => self.section(s, "tag", |me, end, m| { -// write!(me.state, "[tag {}] {:?}", i.tags, m)?; -// i.tags += 1; -// me.print(end) -// })?, -// Payload::ExportSection(s) => self.section(s, "export", |me, end, e| { -// write!(me.state, "export {:?}", e)?; -// me.print(end) -// })?, -// Payload::GlobalSection(s) => self.section(s, "global", |me, _end, g| { -// write!(me.state, "[global {}] {:?}", i.globals, g.ty)?; -// i.globals += 1; -// me.print(g.init_expr.get_binary_reader().original_position())?; -// me.print_ops(g.init_expr.get_operators_reader()) -// })?, -// Payload::AliasSection(s) => self.section(s, "alias", |me, end, a| { -// write!(me.state, "[alias] {:?}", a)?; -// match a { -// Alias::InstanceExport { kind, .. } => match kind { -// ExternalKind::Function => i.funcs += 1, -// ExternalKind::Global => i.globals += 1, -// ExternalKind::Module => i.modules += 1, -// ExternalKind::Table => i.tables += 1, -// ExternalKind::Instance => i.instances += 1, -// ExternalKind::Memory => i.memories += 1, -// ExternalKind::Tag => i.tags += 1, -// ExternalKind::Type => i.types += 1, -// }, -// Alias::OuterType { .. } => i.types += 1, -// Alias::OuterModule { .. } => i.modules += 1, -// } -// me.print(end) -// })?, -// Payload::InstanceSection(s) => { -// self.section(s, "instance", |me, _end, instance| { -// write!( -// me.state, -// "[instance {}] instantiate module:{}", -// i.instances, -// instance.module() -// )?; -// me.print(instance.original_position())?; -// i.instances += 1; -// me.print_iter(instance.args()?, |me, end, arg| { -// write!(me.state, "[instantiate arg] {:?}", arg)?; -// me.print(end) -// }) -// })? -// } -// Payload::StartSection { func, range } => { -// write!(self.state, "start section")?; -// self.print(range.start)?; -// write!(self.state, "start function {}", func)?; -// self.print(range.end)?; -// } -// Payload::DataCountSection { count, range } => { -// write!(self.state, "data count section")?; -// self.print(range.start)?; -// write!(self.state, "data count {}", count)?; -// self.print(range.end)?; -// } -// Payload::ElementSection(s) => self.section(s, "element", |me, _end, i| { -// write!(me.state, "element {:?}", i.ty)?; -// let mut items = i.items.get_items_reader()?; -// match i.kind { -// ElementKind::Passive => { -// write!(me.state, " passive, {} items", items.get_count())?; -// } -// ElementKind::Active { -// table_index, -// init_expr, -// } => { -// write!(me.state, " table[{}]", table_index)?; -// me.print(init_expr.get_binary_reader().original_position())?; -// me.print_ops(init_expr.get_operators_reader())?; -// write!(me.state, "{} items", items.get_count())?; -// } -// ElementKind::Declared => { -// write!(me.state, " declared {} items", items.get_count())?; -// } -// } -// me.print(items.original_position())?; -// for _ in 0..items.get_count() { -// let item = items.read()?; -// write!(me.state, "item {:?}", item)?; -// me.print(items.original_position())?; -// } -// Ok(()) -// })?, - -// Payload::DataSection(s) => self.section(s, "data", |me, end, i| { -// match i.kind { -// DataKind::Passive => { -// write!(me.state, "data passive")?; -// me.print(end - i.data.len())?; -// } -// DataKind::Active { -// memory_index, -// init_expr, -// } => { -// write!(me.state, "data memory[{}]", memory_index)?; -// me.print(init_expr.get_binary_reader().original_position())?; -// me.print_ops(init_expr.get_operators_reader())?; -// } -// } -// write!(me.dst, "0x{:04x} |", me.cur)?; -// for _ in 0..NBYTES { -// write!(me.dst, "---")?; -// } -// write!(me.dst, "-| ... {} bytes of data\n", i.data.len())?; -// me.cur = end; -// Ok(()) -// })?, - -// Payload::CodeSectionStart { count, range, size } => { -// write!(self.state, "code section")?; -// self.print(range.start)?; -// write!(self.state, "{} count", count)?; -// self.print(range.end - size as usize)?; -// } - -// Payload::CodeSectionEntry(body) => { -// write!( -// self.dst, -// "============== func {} ====================\n", -// i.funcs -// )?; -// i.funcs += 1; -// write!(self.state, "size of function")?; -// self.print(body.get_binary_reader().original_position())?; -// let mut locals = body.get_locals_reader()?; -// write!(self.state, "{} local blocks", locals.get_count())?; -// self.print(locals.original_position())?; -// for _ in 0..locals.get_count() { -// let (amt, ty) = locals.read()?; -// write!(self.state, "{} locals of type {:?}", amt, ty)?; -// self.print(locals.original_position())?; -// } -// self.print_ops(body.get_operators_reader()?)?; -// } - -// Payload::ModuleSectionStart { count, range, size } => { -// write!(self.state, "module section")?; -// self.print(range.start)?; -// write!(self.state, "{} count", count)?; -// self.print(range.end - size as usize)?; -// } -// Payload::ModuleSectionEntry { parser: _, range } => { -// write!(self.state, "inline module size")?; -// self.print(range.start)?; -// self.nesting += 1; -// stack.push(i); -// i = Indices::default(); -// } - -// Payload::CustomSection { -// name, -// data_offset, -// data, -// range, -// } => { -// write!(self.state, "custom section")?; -// self.print(range.start)?; -// write!(self.state, "name: {:?}", name)?; -// self.print(data_offset)?; -// if name == "name" { -// let mut iter = NameSectionReader::new(data, data_offset)?; -// while !iter.eof() { -// self.print_custom_name_section(iter.read()?, iter.original_position())?; -// } -// } else { -// write!(self.dst, "0x{:04x} |", self.cur)?; -// for _ in 0..NBYTES { -// write!(self.dst, "---")?; -// } -// write!(self.dst, "-| ... {} bytes of data\n", data.len())?; -// self.cur += data.len(); -// } -// } -// Payload::UnknownSection { -// id, -// range, -// contents, -// } => { -// write!(self.state, "unknown section: {}", id)?; -// self.print(range.start)?; -// write!(self.dst, "0x{:04x} |", self.cur)?; -// for _ in 0..NBYTES { -// write!(self.dst, "---")?; -// } -// write!(self.dst, "-| ... {} bytes of data\n", contents.len())?; -// self.cur += contents.len(); -// } -// Payload::End => { -// self.nesting -= 1; -// if self.nesting > 0 { -// i = stack.pop().unwrap(); -// } -// } -// } -// } - -// Ok(()) -// } - -// fn print_name_map(&mut self, thing: &str, n: NameMap<'_>) -> Result<()> { -// write!(self.state, "{} names", thing)?; -// self.print(n.original_position())?; -// let mut map = n.get_map()?; -// write!(self.state, "{} count", map.get_count())?; -// self.print(map.original_position())?; -// for _ in 0..map.get_count() { -// write!(self.state, "{:?}", map.read()?)?; -// self.print(map.original_position())?; -// } -// Ok(()) -// } - -// fn print_indirect_name_map( -// &mut self, -// thing_a: &str, -// thing_b: &str, -// n: IndirectNameMap<'_>, -// ) -> Result<()> { -// write!(self.state, "{} names", thing_b)?; -// self.print(n.original_position())?; -// let mut outer_map = n.get_indirect_map()?; -// write!(self.state, "{} count", outer_map.get_indirect_count())?; -// self.print(outer_map.original_position())?; -// for _ in 0..outer_map.get_indirect_count() { -// let inner = outer_map.read()?; -// write!( -// self.state, -// "{} {} {}s", -// thing_a, inner.indirect_index, thing_b, -// )?; -// self.print(inner.original_position())?; -// let mut map = inner.get_map()?; -// write!(self.state, "{} count", map.get_count())?; -// self.print(map.original_position())?; -// for _ in 0..map.get_count() { -// write!(self.state, "{:?}", map.read()?)?; -// self.print(map.original_position())?; -// } -// } -// Ok(()) -// } - -// fn print_custom_name_section(&mut self, name: Name<'_>, end: usize) -> Result<()> { -// match name { -// Name::Module(n) => { -// write!(self.state, "module name")?; -// self.print(n.original_position())?; -// write!(self.state, "{:?}", n.get_name()?)?; -// self.print(end)?; -// } -// Name::Function(n) => self.print_name_map("function", n)?, -// Name::Local(n) => self.print_indirect_name_map("function", "local", n)?, -// Name::Label(n) => self.print_indirect_name_map("function", "label", n)?, -// Name::Type(n) => self.print_name_map("type", n)?, -// Name::Table(n) => self.print_name_map("table", n)?, -// Name::Memory(n) => self.print_name_map("memory", n)?, -// Name::Global(n) => self.print_name_map("global", n)?, -// Name::Element(n) => self.print_name_map("element", n)?, -// Name::Data(n) => self.print_name_map("data", n)?, -// Name::Unknown { ty, range, .. } => { -// write!(self.state, "unknown names: {}", ty)?; -// self.print(range.start)?; -// self.print(end)?; -// } -// } -// Ok(()) -// } - -// fn section( -// &mut self, -// iter: T, -// name: &str, -// print: impl FnMut(&mut Self, usize, T::Item) -> Result<()>, -// ) -> Result<()> -// where -// T: SectionReader + SectionWithLimitedItems, -// { -// write!(self.state, "{} section", name)?; -// self.print(iter.range().start)?; -// self.print_iter(iter, print) -// } - -// fn print_iter( -// &mut self, -// mut iter: T, -// mut print: impl FnMut(&mut Self, usize, T::Item) -> Result<()>, -// ) -> Result<()> -// where -// T: SectionReader + SectionWithLimitedItems, -// { -// write!(self.state, "{} count", iter.get_count())?; -// self.print(iter.original_position())?; -// for _ in 0..iter.get_count() { -// let item = iter.read()?; -// print(self, iter.original_position(), item)?; -// } -// if !iter.eof() { -// bail!("too many bytes in section"); -// } -// Ok(()) -// } - -// fn print_ops(&mut self, mut i: OperatorsReader) -> Result<()> { -// while !i.eof() { -// match i.read() { -// Ok(op) => write!(self.state, "{:?}", op)?, -// Err(_) => write!(self.state, "??")?, -// } -// self.print(i.original_position())?; -// } -// Ok(()) -// } - -// fn print(&mut self, end: usize) -> Result<()> { -// assert!( -// self.cur < end, -// "{:#x} >= {:#x}\ntrying to print: {}\n{}", -// self.cur, -// end, -// self.state, -// self.dst -// ); -// let bytes = &self.bytes[self.cur..end]; -// for _ in 0..self.nesting - 1 { -// write!(self.dst, " ")?; -// } -// write!(self.dst, "0x{:04x} |", self.cur)?; -// for (i, chunk) in bytes.chunks(NBYTES).enumerate() { -// if i > 0 { -// for _ in 0..self.nesting - 1 { -// write!(self.dst, " ")?; -// } -// self.dst.push_str(" |"); -// } -// for j in 0..NBYTES { -// match chunk.get(j) { -// Some(b) => write!(self.dst, " {:02x}", b)?, -// None => write!(self.dst, " ")?, -// } -// } -// if i == 0 { -// self.dst.push_str(" | "); -// self.dst.push_str(&self.state); -// self.state.truncate(0); -// } -// self.dst.push_str("\n"); -// } -// self.cur = end; -// Ok(()) -// } -// } diff --git a/lib/js-api/src/types.rs b/lib/js-api/src/types.rs index 1e637a270..fd1d807ae 100644 --- a/lib/js-api/src/types.rs +++ b/lib/js-api/src/types.rs @@ -7,7 +7,6 @@ pub use wasmer_types::{ ExportType, ExternType, FunctionType, GlobalType, ImportType, MemoryType, Mutability, TableType, Type as ValType, }; -// use wasmer_vm::VMFuncRef; /// WebAssembly computations manipulate values of basic value types: /// * Integers (32 or 64 bit width) @@ -41,104 +40,7 @@ impl AsJs for Val { Self::F32(f) => JsValue::from_f64(*f as f64), Self::F64(f) => JsValue::from_f64(*f), Self::FuncRef(func) => func.as_ref().unwrap().exported.function.clone().into(), - _ => unimplemented!(), + _ => unimplemented!("The type is not yet supported in the JS Function API"), } } } - -// impl StoreObject for Val { -// fn comes_from_same_store(&self, store: &Store) -> bool { -// match self { -// Self::FuncRef(None) => true, -// Self::FuncRef(Some(f)) => Store::same(store, f.store()), -// // `ExternRef`s are not tied to specific stores -// Self::ExternRef(_) => true, -// Self::I32(_) | Self::I64(_) | Self::F32(_) | Self::F64(_) | Self::V128(_) => true, -// } -// } -// } - -// impl From for Val { -// fn from(val: Function) -> Self { -// Self::FuncRef(Some(val)) -// } -// } - -// /// It provides useful functions for converting back and forth -// /// from [`Val`] into `FuncRef`. -// pub trait ValFuncRef { -// fn into_vm_funcref(&self, store: &Store) -> Result; - -// fn from_vm_funcref(item: VMFuncRef, store: &Store) -> Self; - -// fn into_table_reference(&self, store: &Store) -> Result; - -// fn from_table_reference(item: wasmer_vm::TableElement, store: &Store) -> Self; -// } - -// impl ValFuncRef for Val { -// fn into_vm_funcref(&self, store: &Store) -> Result { -// if !self.comes_from_same_store(store) { -// return Err(RuntimeError::new("cross-`Store` values are not supported")); -// } -// Ok(match self { -// Self::FuncRef(None) => VMFuncRef::null(), -// Self::FuncRef(Some(f)) => f.vm_funcref(), -// _ => return Err(RuntimeError::new("val is not func ref")), -// }) -// } - -// fn from_vm_funcref(func_ref: VMFuncRef, store: &Store) -> Self { -// if func_ref.is_null() { -// return Self::FuncRef(None); -// } -// let item: &wasmer_vm::VMCallerCheckedAnyfunc = unsafe { -// let anyfunc: *const wasmer_vm::VMCallerCheckedAnyfunc = *func_ref; -// &*anyfunc -// }; -// let signature = store -// .engine() -// .lookup_signature(item.type_index) -// .expect("Signature not found in store"); -// let export = wasmer_engine::ExportFunction { -// // TODO: -// // figure out if we ever need a value here: need testing with complicated import patterns -// metadata: None, -// vm_function: wasmer_vm::VMFunction { -// address: item.func_ptr, -// signature, -// // TODO: review this comment (unclear if it's still correct): -// // All functions in tables are already Static (as dynamic functions -// // are converted to use the trampolines with static signatures). -// kind: wasmer_vm::VMFunctionKind::Static, -// vmctx: item.vmctx, -// call_trampoline: None, -// instance_ref: None, -// }, -// }; -// let f = Function::from_vm_export(store, export); -// Self::FuncRef(Some(f)) -// } - -// fn into_table_reference(&self, store: &Store) -> Result { -// if !self.comes_from_same_store(store) { -// return Err(RuntimeError::new("cross-`Store` values are not supported")); -// } -// Ok(match self { -// // TODO(reftypes): review this clone -// Self::ExternRef(extern_ref) => { -// wasmer_vm::TableElement::ExternRef(extern_ref.clone().into()) -// } -// Self::FuncRef(None) => wasmer_vm::TableElement::FuncRef(VMFuncRef::null()), -// Self::FuncRef(Some(f)) => wasmer_vm::TableElement::FuncRef(f.vm_funcref()), -// _ => return Err(RuntimeError::new("val is not reference")), -// }) -// } - -// fn from_table_reference(item: wasmer_vm::TableElement, store: &Store) -> Self { -// match item { -// wasmer_vm::TableElement::FuncRef(f) => Self::from_vm_funcref(f, store), -// wasmer_vm::TableElement::ExternRef(extern_ref) => Self::ExternRef(extern_ref.into()), -// } -// } -// }