Redo the statically typed Func API (#2719)
* Redo the statically typed `Func` API
This commit reimplements the `Func` API with respect to statically typed
dispatch. Previously `Func` had a `getN` and `getN_async` family of
methods which were implemented for 0 to 16 parameters. The return value
of these functions was an `impl Fn(..)` closure with the appropriate
parameters and return values.
There are a number of downsides with this approach that have become
apparent over time:
* The addition of `*_async` doubled the API surface area (which is quite
large here due to one-method-per-number-of-parameters).
* The [documentation of `Func`][old-docs] are quite verbose and feel
"polluted" with all these getters, making it harder to understand the
other methods that can be used to interact with a `Func`.
* These methods unconditionally pay the cost of returning an owned `impl
Fn` with a `'static` lifetime. While cheap, this is still paying the
cost for cloning the `Store` effectively and moving data into the
closed-over environment.
* Storage of the return value into a struct, for example, always
requires `Box`-ing the returned closure since it otherwise cannot be
named.
* Recently I had the desire to implement an "unchecked" path for
invoking wasm where you unsafely assert the type signature of a wasm
function. Doing this with today's scheme would require doubling
(again) the API surface area for both async and synchronous calls,
further polluting the documentation.
The main benefit of the previous scheme is that by returning a `impl Fn`
it was quite easy and ergonomic to actually invoke the function. In
practice, though, examples would often have something akin to
`.get0::<()>()?()?` which is a lot of things to interpret all at once.
Note that `get0` means "0 parameters" yet a type parameter is passed.
There's also a double function invocation which looks like a lot of
characters all lined up in a row.
Overall, I think that the previous design is starting to show too many
cracks and deserves a rewrite. This commit is that rewrite.
The new design in this commit is to delete the `getN{,_async}` family of
functions and instead have a new API:
impl Func {
fn typed<P, R>(&self) -> Result<&Typed<P, R>>;
}
impl Typed<P, R> {
fn call(&self, params: P) -> Result<R, Trap>;
async fn call_async(&self, params: P) -> Result<R, Trap>;
}
This should entirely replace the current scheme, albeit by slightly
losing ergonomics use cases. The idea behind the API is that the
existence of `Typed<P, R>` is a "proof" that the underlying function
takes `P` and returns `R`. The `Func::typed` method peforms a runtime
type-check to ensure that types all match up, and if successful you get
a `Typed` value. Otherwise an error is returned.
Once you have a `Typed` then, like `Func`, you can either `call` or
`call_async`. The difference with a `Typed`, however, is that the
params/results are statically known and hence these calls can be much
more efficient.
This is a much smaller API surface area from before and should greatly
simplify the `Func` documentation. There's still a problem where
`Func::wrapN_async` produces a lot of functions to document, but that's
now the sole offender. It's a nice benefit that the
statically-typed-async verisons are now expressed with an `async`
function rather than a function-returning-a-future which makes it both
more efficient and easier to understand.
The type `P` and `R` are intended to either be bare types (e.g. `i32`)
or tuples of any length (including 0). At this time `R` is only allowed
to be `()` or a bare `i32`-style type because multi-value is not
supported with a native ABI (yet). The `P`, however, can be any size of
tuples of parameters. This is also where some ergonomics are lost
because instead of `f(1, 2)` you now have to write `f.call((1, 2))`
(note the double-parens). Similarly `f()` becomes `f.call(())`.
Overall I feel that this is a better tradeoff than before. While not
universally better due to the loss in ergonomics I feel that this design
is much more flexible in terms of what you can do with the return value
and also understanding the API surface area (just less to take in).
[old-docs]: https://docs.rs/wasmtime/0.24.0/wasmtime/struct.Func.html#method.get0
* Rename Typed to TypedFunc
* Implement multi-value returns through `Func::typed`
* Fix examples in docs
* Fix some more errors
* More test fixes
* Rebasing and adding `get_typed_func`
* Updating tests
* Fix typo
* More doc tweaks
* Tweak visibility on `Func::invoke`
* Fix tests again
This commit is contained in:
@@ -301,9 +301,8 @@ impl BenchState {
|
||||
.as_ref()
|
||||
.expect("instantiate the module before executing it");
|
||||
|
||||
let start_func = instance.get_func("_start").expect("a _start function");
|
||||
let runnable_func = start_func.get0::<()>()?;
|
||||
match runnable_func() {
|
||||
let start_func = instance.get_typed_func::<(), ()>("_start")?;
|
||||
match start_func.call(()) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(trap) => {
|
||||
// Since _start will likely return by using the system `exit` call, we must
|
||||
|
||||
@@ -57,9 +57,8 @@ pub fn instantiate(data: &[u8], bin_name: &str, workspace: Option<&Path>) -> any
|
||||
|
||||
let module = Module::new(store.engine(), &data).context("failed to create wasm module")?;
|
||||
let instance = linker.instantiate(&module)?;
|
||||
let start = instance.get_func("_start").unwrap();
|
||||
let with_type = start.get0::<()>()?;
|
||||
with_type().map_err(anyhow::Error::from)
|
||||
let start = instance.get_typed_func::<(), ()>("_start")?;
|
||||
start.call(()).map_err(anyhow::Error::from)
|
||||
};
|
||||
|
||||
match r {
|
||||
@@ -112,9 +111,8 @@ pub fn instantiate_inherit_stdio(
|
||||
|
||||
let module = Module::new(store.engine(), &data).context("failed to create wasm module")?;
|
||||
let instance = linker.instantiate(&module)?;
|
||||
let start = instance.get_func("_start").unwrap();
|
||||
let with_type = start.get0::<()>()?;
|
||||
with_type().map_err(anyhow::Error::from)
|
||||
let start = instance.get_typed_func::<(), ()>("_start")?;
|
||||
start.call(()).map_err(anyhow::Error::from)
|
||||
};
|
||||
|
||||
match r {
|
||||
|
||||
@@ -350,8 +350,8 @@ macro_rules! generate_wrap_async_host_func {
|
||||
debug_assert!(store.async_support());
|
||||
let mut future = Pin::from(func(caller, $($args),*));
|
||||
match store.block_on(future.as_mut()) {
|
||||
Ok(ret) => ret.into_result(),
|
||||
Err(e) => Err(e),
|
||||
Ok(ret) => ret.into_fallible(),
|
||||
Err(e) => R::fallible_from_trap(e),
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
488
crates/wasmtime/src/func/typed.rs
Normal file
488
crates/wasmtime/src/func/typed.rs
Normal file
@@ -0,0 +1,488 @@
|
||||
use super::invoke_wasm_and_catch_traps;
|
||||
use crate::{ExternRef, Func, Store, Trap, ValType};
|
||||
use anyhow::{bail, Result};
|
||||
use std::marker;
|
||||
use std::mem::{self, MaybeUninit};
|
||||
use std::ptr;
|
||||
use wasmtime_runtime::{VMContext, VMFunctionBody, VMTrampoline};
|
||||
|
||||
/// A statically typed WebAssembly function.
|
||||
///
|
||||
/// Values of this type represent statically type-checked WebAssembly functions.
|
||||
/// The function within a [`TypedFunc`] is statically known to have `Params` as its
|
||||
/// parameters and `Results` as its results.
|
||||
///
|
||||
/// This structure is created via [`Func::typed`] or [`Func::typed_unchecked`].
|
||||
/// For more documentation about this see those methods.
|
||||
#[repr(transparent)]
|
||||
pub struct TypedFunc<Params, Results> {
|
||||
_a: marker::PhantomData<fn(Params) -> Results>,
|
||||
func: Func,
|
||||
}
|
||||
|
||||
impl<Params, Results> Clone for TypedFunc<Params, Results> {
|
||||
fn clone(&self) -> TypedFunc<Params, Results> {
|
||||
TypedFunc {
|
||||
_a: marker::PhantomData,
|
||||
func: self.func.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Params, Results> TypedFunc<Params, Results>
|
||||
where
|
||||
Params: WasmParams,
|
||||
Results: WasmResults,
|
||||
{
|
||||
/// Returns the underlying [`Func`] that this is wrapping, losing the static
|
||||
/// type information in the process.
|
||||
pub fn func(&self) -> &Func {
|
||||
&self.func
|
||||
}
|
||||
|
||||
/// Invokes this WebAssembly function with the specified parameters.
|
||||
///
|
||||
/// Returns either the results of the call, or a [`Trap`] if one happened.
|
||||
///
|
||||
/// For more information, see the [`Func::typed`] and [`Func::call`]
|
||||
/// documentation.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if it is called when the underlying [`Func`] is
|
||||
/// connected to an asynchronous store.
|
||||
pub fn call(&self, params: Params) -> Result<Results, Trap> {
|
||||
assert!(
|
||||
!self.func.store().async_support(),
|
||||
"must use `call_async` with async stores"
|
||||
);
|
||||
unsafe { self._call(params) }
|
||||
}
|
||||
|
||||
/// Invokes this WebAssembly function with the specified parameters.
|
||||
///
|
||||
/// Returns either the results of the call, or a [`Trap`] if one happened.
|
||||
///
|
||||
/// For more information, see the [`Func::typed`] and [`Func::call_async`]
|
||||
/// documentation.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if it is called when the underlying [`Func`] is
|
||||
/// connected to a synchronous store.
|
||||
#[cfg(feature = "async")]
|
||||
#[cfg_attr(nightlydoc, doc(cfg(feature = "async")))]
|
||||
pub async fn call_async(&self, params: Params) -> Result<Results, Trap> {
|
||||
assert!(
|
||||
self.func.store().async_support(),
|
||||
"must use `call` with non-async stores"
|
||||
);
|
||||
self.func
|
||||
.store()
|
||||
.on_fiber(|| unsafe { self._call(params) })
|
||||
.await?
|
||||
}
|
||||
|
||||
unsafe fn _call(&self, params: Params) -> Result<Results, Trap> {
|
||||
// Validate that all runtime values flowing into this store indeed
|
||||
// belong within this store, otherwise it would be unsafe for store
|
||||
// values to cross each other.
|
||||
if !params.compatible_with_store(&self.func.instance.store) {
|
||||
return Err(Trap::new(
|
||||
"attempt to pass cross-`Store` value to Wasm as function argument",
|
||||
));
|
||||
}
|
||||
|
||||
let anyfunc = self.func.export.anyfunc.as_ref();
|
||||
let trampoline = self.func.trampoline;
|
||||
let params = MaybeUninit::new(params);
|
||||
let mut ret = MaybeUninit::uninit();
|
||||
let mut called = false;
|
||||
let mut returned = false;
|
||||
let result = invoke_wasm_and_catch_traps(&self.func.instance.store, || {
|
||||
called = true;
|
||||
let params = ptr::read(params.as_ptr());
|
||||
let result = params.invoke::<Results>(
|
||||
&self.func.instance.store,
|
||||
trampoline,
|
||||
anyfunc.func_ptr.as_ptr(),
|
||||
anyfunc.vmctx,
|
||||
ptr::null_mut(),
|
||||
);
|
||||
ptr::write(ret.as_mut_ptr(), result);
|
||||
returned = true
|
||||
});
|
||||
|
||||
// This can happen if we early-trap due to interrupts or other
|
||||
// pre-flight checks, so we need to be sure the parameters are at least
|
||||
// dropped at some point.
|
||||
if !called {
|
||||
drop(params.assume_init());
|
||||
}
|
||||
debug_assert_eq!(result.is_ok(), returned);
|
||||
result?;
|
||||
|
||||
Ok(ret.assume_init())
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait implemented for types which can be arguments and results for
|
||||
/// closures passed to [`Func::wrap`] as well as parameters to [`Func::typed`].
|
||||
///
|
||||
/// This trait should not be implemented by user types. This trait may change at
|
||||
/// any time internally. The types which implement this trait, however, are
|
||||
/// stable over time.
|
||||
///
|
||||
/// For more information see [`Func::wrap`] and [`Func::typed`]
|
||||
pub unsafe trait WasmTy {
|
||||
#[doc(hidden)]
|
||||
type Abi: Copy;
|
||||
#[doc(hidden)]
|
||||
#[inline]
|
||||
fn typecheck(ty: crate::ValType) -> Result<()> {
|
||||
if ty == Self::valtype() {
|
||||
Ok(())
|
||||
} else {
|
||||
bail!("expected {} found {}", Self::valtype(), ty)
|
||||
}
|
||||
}
|
||||
#[doc(hidden)]
|
||||
fn valtype() -> ValType;
|
||||
#[doc(hidden)]
|
||||
fn compatible_with_store(&self, store: &Store) -> bool;
|
||||
#[doc(hidden)]
|
||||
fn into_abi(self, store: &Store) -> Self::Abi;
|
||||
#[doc(hidden)]
|
||||
unsafe fn from_abi(abi: Self::Abi, store: &Store) -> Self;
|
||||
}
|
||||
|
||||
macro_rules! primitives {
|
||||
($($primitive:ident => $ty:ident)*) => ($(
|
||||
unsafe impl WasmTy for $primitive {
|
||||
type Abi = $primitive;
|
||||
#[inline]
|
||||
fn valtype() -> ValType {
|
||||
ValType::$ty
|
||||
}
|
||||
#[inline]
|
||||
fn compatible_with_store(&self, _: &Store) -> bool {
|
||||
true
|
||||
}
|
||||
#[inline]
|
||||
fn into_abi(self, _store: &Store) -> Self::Abi {
|
||||
self
|
||||
}
|
||||
#[inline]
|
||||
unsafe fn from_abi(abi: Self::Abi, _store: &Store) -> Self {
|
||||
abi
|
||||
}
|
||||
}
|
||||
)*)
|
||||
}
|
||||
|
||||
primitives! {
|
||||
i32 => I32
|
||||
u32 => I32
|
||||
i64 => I64
|
||||
u64 => I64
|
||||
f32 => F32
|
||||
f64 => F64
|
||||
}
|
||||
|
||||
unsafe impl WasmTy for Option<ExternRef> {
|
||||
type Abi = *mut u8;
|
||||
|
||||
#[inline]
|
||||
fn valtype() -> ValType {
|
||||
ValType::ExternRef
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn compatible_with_store(&self, _store: &Store) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn into_abi(self, store: &Store) -> Self::Abi {
|
||||
if let Some(x) = self {
|
||||
let abi = x.inner.as_raw();
|
||||
unsafe {
|
||||
store
|
||||
.externref_activations_table()
|
||||
.insert_with_gc(x.inner, store.stack_map_registry());
|
||||
}
|
||||
abi
|
||||
} else {
|
||||
ptr::null_mut()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn from_abi(abi: Self::Abi, _store: &Store) -> Self {
|
||||
if abi.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(ExternRef {
|
||||
inner: wasmtime_runtime::VMExternRef::clone_from_raw(abi),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl WasmTy for Option<Func> {
|
||||
type Abi = *mut wasmtime_runtime::VMCallerCheckedAnyfunc;
|
||||
|
||||
#[inline]
|
||||
fn valtype() -> ValType {
|
||||
ValType::FuncRef
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn compatible_with_store<'a>(&self, store: &Store) -> bool {
|
||||
if let Some(f) = self {
|
||||
Store::same(&store, f.store())
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn into_abi(self, _store: &Store) -> Self::Abi {
|
||||
if let Some(f) = self {
|
||||
f.caller_checked_anyfunc().as_ptr()
|
||||
} else {
|
||||
ptr::null_mut()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
unsafe fn from_abi(abi: Self::Abi, store: &Store) -> Self {
|
||||
Func::from_caller_checked_anyfunc(&store, abi)
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait used for [`Func::typed`] and with [`TypedFunc`] to represent the set of
|
||||
/// parameters for wasm functions.
|
||||
///
|
||||
/// This is implemented for bare types that can be passed to wasm as well as
|
||||
/// tuples of those types.
|
||||
pub unsafe trait WasmParams {
|
||||
#[doc(hidden)]
|
||||
fn typecheck(params: impl ExactSizeIterator<Item = crate::ValType>) -> Result<()>;
|
||||
#[doc(hidden)]
|
||||
fn compatible_with_store(&self, store: &Store) -> bool;
|
||||
#[doc(hidden)]
|
||||
unsafe fn invoke<R: WasmResults>(
|
||||
self,
|
||||
store: &Store,
|
||||
trampoline: VMTrampoline,
|
||||
func: *const VMFunctionBody,
|
||||
vmctx1: *mut VMContext,
|
||||
vmctx2: *mut VMContext,
|
||||
) -> R;
|
||||
}
|
||||
|
||||
// Forward an impl from `T` to `(T,)` for convenience if there's only one
|
||||
// parameter.
|
||||
unsafe impl<T> WasmParams for T
|
||||
where
|
||||
T: WasmTy,
|
||||
{
|
||||
fn typecheck(params: impl ExactSizeIterator<Item = crate::ValType>) -> Result<()> {
|
||||
<(T,)>::typecheck(params)
|
||||
}
|
||||
fn compatible_with_store(&self, store: &Store) -> bool {
|
||||
<T as WasmTy>::compatible_with_store(self, store)
|
||||
}
|
||||
unsafe fn invoke<R: WasmResults>(
|
||||
self,
|
||||
store: &Store,
|
||||
trampoline: VMTrampoline,
|
||||
func: *const VMFunctionBody,
|
||||
vmctx1: *mut VMContext,
|
||||
vmctx2: *mut VMContext,
|
||||
) -> R {
|
||||
<(T,)>::invoke((self,), store, trampoline, func, vmctx1, vmctx2)
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_wasm_params {
|
||||
($n:tt $($t:ident)*) => {
|
||||
#[allow(non_snake_case)]
|
||||
unsafe impl<$($t: WasmTy,)*> WasmParams for ($($t,)*) {
|
||||
fn typecheck(mut params: impl ExactSizeIterator<Item = crate::ValType>) -> Result<()> {
|
||||
let mut _n = 0;
|
||||
$(
|
||||
match params.next() {
|
||||
Some(t) => $t::typecheck(t)?,
|
||||
None => bail!("expected {} types, found {}", $n, _n),
|
||||
}
|
||||
_n += 1;
|
||||
)*
|
||||
|
||||
match params.next() {
|
||||
None => Ok(()),
|
||||
Some(_) => bail!("expected {} types, found {}", $n, params.len() + _n),
|
||||
}
|
||||
}
|
||||
|
||||
fn compatible_with_store(&self, _store: &Store) -> bool {
|
||||
let ($($t,)*) = self;
|
||||
$($t.compatible_with_store(_store)&&)* true
|
||||
}
|
||||
|
||||
unsafe fn invoke<R: WasmResults>(
|
||||
self,
|
||||
store: &Store,
|
||||
trampoline: VMTrampoline,
|
||||
func: *const VMFunctionBody,
|
||||
vmctx1: *mut VMContext,
|
||||
vmctx2: *mut VMContext,
|
||||
) -> R {
|
||||
// Some signatures can go directly into JIT code which uses the
|
||||
// default platform ABI, but basically only those without
|
||||
// multiple return values. With multiple return values we can't
|
||||
// natively in Rust call such a function because there's no way
|
||||
// to model it (yet).
|
||||
//
|
||||
// To work around that we use the trampoline which passes
|
||||
// arguments/values via the stack which allows us to match the
|
||||
// expected ABI. Note that this branch, using the trampoline,
|
||||
// is slower as a result and has an extra indirect function
|
||||
// call as well. In the future if this is a problem we should
|
||||
// consider updating JIT code to use an ABI we can call from
|
||||
// Rust itself.
|
||||
if R::uses_trampoline() {
|
||||
R::with_space(|space1| {
|
||||
// Figure out whether the parameters or the results
|
||||
// require more space, and use the bigger one as where
|
||||
// to store arguments and load return values from.
|
||||
let mut space2 = [0; $n];
|
||||
let space = if space1.len() < space2.len() {
|
||||
space2.as_mut_ptr()
|
||||
} else {
|
||||
space1.as_mut_ptr()
|
||||
};
|
||||
|
||||
// ... store the ABI for all values into our storage
|
||||
// area...
|
||||
let ($($t,)*) = self;
|
||||
let mut _n = 0;
|
||||
$(
|
||||
*space.add(_n).cast::<$t::Abi>() = $t.into_abi(store);
|
||||
_n += 1;
|
||||
)*
|
||||
|
||||
// ... make the indirect call through the trampoline
|
||||
// which will read from `space` and also write all the
|
||||
// results to `space`...
|
||||
trampoline(vmctx1, vmctx2, func, space);
|
||||
|
||||
// ... and then we can decode all the return values
|
||||
// from `space`.
|
||||
R::from_storage(space, store)
|
||||
})
|
||||
} else {
|
||||
let fnptr = mem::transmute::<
|
||||
*const VMFunctionBody,
|
||||
unsafe extern "C" fn(
|
||||
*mut VMContext,
|
||||
*mut VMContext,
|
||||
$($t::Abi,)*
|
||||
) -> R::Abi,
|
||||
>(func);
|
||||
let ($($t,)*) = self;
|
||||
R::from_abi(fnptr(vmctx1, vmctx2, $($t.into_abi(store),)*), store)
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
for_each_function_signature!(impl_wasm_params);
|
||||
|
||||
/// A trait used for [`Func::typed`] and with [`TypedFunc`] to represent the set of
|
||||
/// results for wasm functions.
|
||||
///
|
||||
/// This is currently only implemented for `()` and for bare types that can be
|
||||
/// returned. This is not yet implemented for tuples because a multi-value
|
||||
/// `TypedFunc` is not currently supported.
|
||||
pub unsafe trait WasmResults: WasmParams {
|
||||
#[doc(hidden)]
|
||||
type Abi;
|
||||
#[doc(hidden)]
|
||||
unsafe fn from_abi(abi: Self::Abi, store: &Store) -> Self;
|
||||
#[doc(hidden)]
|
||||
fn uses_trampoline() -> bool;
|
||||
// Provides a stack-allocated array with enough space to store all these
|
||||
// result values.
|
||||
//
|
||||
// It'd be nice if we didn't have to have this API and could do something
|
||||
// with const-generics (or something like that), but I couldn't figure it
|
||||
// out. If a future Rust explorer is able to get something like `const LEN:
|
||||
// usize` working that'd be great!
|
||||
#[doc(hidden)]
|
||||
fn with_space<R>(_: impl FnOnce(&mut [u128]) -> R) -> R;
|
||||
#[doc(hidden)]
|
||||
unsafe fn from_storage(ptr: *const u128, store: &Store) -> Self;
|
||||
}
|
||||
|
||||
unsafe impl<T: WasmTy> WasmResults for T {
|
||||
type Abi = <(T,) as WasmResults>::Abi;
|
||||
unsafe fn from_abi(abi: Self::Abi, store: &Store) -> Self {
|
||||
<(T,) as WasmResults>::from_abi(abi, store).0
|
||||
}
|
||||
fn uses_trampoline() -> bool {
|
||||
<(T,) as WasmResults>::uses_trampoline()
|
||||
}
|
||||
fn with_space<R>(f: impl FnOnce(&mut [u128]) -> R) -> R {
|
||||
<(T,) as WasmResults>::with_space(f)
|
||||
}
|
||||
unsafe fn from_storage(ptr: *const u128, store: &Store) -> Self {
|
||||
<(T,) as WasmResults>::from_storage(ptr, store).0
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub enum Void {}
|
||||
|
||||
macro_rules! impl_wasm_results {
|
||||
($n:tt $($t:ident)*) => {
|
||||
#[allow(non_snake_case, unused_variables)]
|
||||
unsafe impl<$($t: WasmTy,)*> WasmResults for ($($t,)*) {
|
||||
type Abi = impl_wasm_results!(@abi $n $($t)*);
|
||||
unsafe fn from_abi(abi: Self::Abi, store: &Store) -> Self {
|
||||
impl_wasm_results!(@from_abi abi store $n $($t)*)
|
||||
}
|
||||
fn uses_trampoline() -> bool {
|
||||
$n > 1
|
||||
}
|
||||
fn with_space<R>(f: impl FnOnce(&mut [u128]) -> R) -> R {
|
||||
f(&mut [0; $n])
|
||||
}
|
||||
unsafe fn from_storage(ptr: *const u128, store: &Store) -> Self {
|
||||
let mut _n = 0;
|
||||
$(
|
||||
let $t = $t::from_abi(*ptr.add(_n).cast::<$t::Abi>(), store);
|
||||
_n += 1;
|
||||
)*
|
||||
($($t,)*)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 0/1 return values we can use natively, everything else isn't expressible
|
||||
// and won't be used so define the abi type to Void.
|
||||
(@abi 0) => (());
|
||||
(@abi 1 $t:ident) => ($t::Abi);
|
||||
(@abi $($t:tt)*) => (Void);
|
||||
|
||||
(@from_abi $abi:ident $store:ident 0) => (());
|
||||
(@from_abi $abi:ident $store:ident 1 $t:ident) => (($t::from_abi($abi, $store),));
|
||||
(@from_abi $abi:ident $store:ident $($t:tt)*) => ({
|
||||
debug_assert!(false);
|
||||
match $abi {}
|
||||
});
|
||||
}
|
||||
|
||||
for_each_function_signature!(impl_wasm_results);
|
||||
@@ -2,8 +2,9 @@ use crate::trampoline::StoreInstanceHandle;
|
||||
use crate::types::matching;
|
||||
use crate::{
|
||||
Engine, Export, Extern, Func, Global, InstanceType, Memory, Module, Store, Table, Trap,
|
||||
TypedFunc,
|
||||
};
|
||||
use anyhow::{bail, Context, Error, Result};
|
||||
use anyhow::{anyhow, bail, Context, Error, Result};
|
||||
use std::mem;
|
||||
use std::rc::Rc;
|
||||
use wasmtime_environ::entity::PrimaryMap;
|
||||
@@ -216,6 +217,25 @@ impl Instance {
|
||||
self.get_export(name)?.into_func()
|
||||
}
|
||||
|
||||
/// Looks up an exported [`Func`] value by name and with its type.
|
||||
///
|
||||
/// This function is a convenience wrapper over [`Instance::get_func`] and
|
||||
/// [`Func::typed`]. For more information see the linked documentation.
|
||||
///
|
||||
/// Returns an error if `name` isn't a function export or if the export's
|
||||
/// type did not match `Params` or `Results`
|
||||
pub fn get_typed_func<Params, Results>(&self, name: &str) -> Result<TypedFunc<Params, Results>>
|
||||
where
|
||||
Params: crate::WasmParams,
|
||||
Results: crate::WasmResults,
|
||||
{
|
||||
let f = self
|
||||
.get_export(name)
|
||||
.and_then(|f| f.into_func())
|
||||
.ok_or_else(|| anyhow!("failed to find function export `{}`", name))?;
|
||||
Ok(f.typed::<Params, Results>()?.clone())
|
||||
}
|
||||
|
||||
/// Looks up an exported [`Table`] value by name.
|
||||
///
|
||||
/// Returns `None` if there was no export named `name`, or if there was but
|
||||
|
||||
@@ -47,15 +47,12 @@
|
||||
//!
|
||||
//! // Instantiation of a module requires specifying its imports and then
|
||||
//! // afterwards we can fetch exports by name, as well as asserting the
|
||||
//! // type signature of the function with `get0`.
|
||||
//! // type signature of the function with `get_typed_func`.
|
||||
//! let instance = Instance::new(&store, &module, &[host_hello.into()])?;
|
||||
//! let hello = instance
|
||||
//! .get_func("hello")
|
||||
//! .ok_or(anyhow::format_err!("failed to find `hello` function export"))?
|
||||
//! .get0::<()>()?;
|
||||
//! let hello = instance.get_typed_func::<(), ()>("hello")?;
|
||||
//!
|
||||
//! // And finally we can call the wasm as if it were a Rust function!
|
||||
//! hello()?;
|
||||
//! hello.call(())?;
|
||||
//!
|
||||
//! Ok(())
|
||||
//! }
|
||||
@@ -262,8 +259,8 @@
|
||||
//! "#,
|
||||
//! )?;
|
||||
//! let instance = Instance::new(&store, &module, &[log_str.into()])?;
|
||||
//! let foo = instance.get_func("foo").unwrap().get0::<()>()?;
|
||||
//! foo()?;
|
||||
//! let foo = instance.get_typed_func::<(), ()>("foo")?;
|
||||
//! foo.call(())?;
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
@@ -355,10 +355,10 @@ impl Linker {
|
||||
/// "#;
|
||||
/// let module = Module::new(store.engine(), wat)?;
|
||||
/// linker.module("commander", &module)?;
|
||||
/// let run = linker.get_default("")?.get0::<()>()?;
|
||||
/// run()?;
|
||||
/// run()?;
|
||||
/// run()?;
|
||||
/// let run = linker.get_default("")?.typed::<(), ()>()?.clone();
|
||||
/// run.call(())?;
|
||||
/// run.call(())?;
|
||||
/// run.call(())?;
|
||||
///
|
||||
/// let wat = r#"
|
||||
/// (module
|
||||
@@ -374,7 +374,8 @@ impl Linker {
|
||||
/// "#;
|
||||
/// let module = Module::new(store.engine(), wat)?;
|
||||
/// linker.module("", &module)?;
|
||||
/// let count = linker.get_one_by_name("", Some("run"))?.into_func().unwrap().get0::<i32>()?()?;
|
||||
/// let run = linker.get_one_by_name("", Some("run"))?.into_func().unwrap();
|
||||
/// let count = run.typed::<(), i32>()?.call(())?;
|
||||
/// assert_eq!(count, 0, "a Command should get a fresh instance on each invocation");
|
||||
///
|
||||
/// # Ok(())
|
||||
@@ -388,8 +389,8 @@ impl Linker {
|
||||
|
||||
if let Some(export) = instance.get_export("_initialize") {
|
||||
if let Extern::Func(func) = export {
|
||||
func.get0::<()>()
|
||||
.and_then(|f| f().map_err(Into::into))
|
||||
func.typed::<(), ()>()
|
||||
.and_then(|f| f.call(()).map_err(Into::into))
|
||||
.context("calling the Reactor initialization function")?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,10 +479,7 @@ impl Store {
|
||||
/// (func (export "run") (loop br 0))
|
||||
/// "#)?;
|
||||
/// let instance = Instance::new(&store, &module, &[])?;
|
||||
/// let run = instance
|
||||
/// .get_func("run")
|
||||
/// .ok_or(anyhow::format_err!("failed to find `run` function export"))?
|
||||
/// .get0::<()>()?;
|
||||
/// let run = instance.get_typed_func::<(), ()>("run")?;
|
||||
///
|
||||
/// // Spin up a thread to send us an interrupt in a second
|
||||
/// std::thread::spawn(move || {
|
||||
@@ -490,7 +487,7 @@ impl Store {
|
||||
/// interrupt_handle.interrupt();
|
||||
/// });
|
||||
///
|
||||
/// let trap = run().unwrap_err();
|
||||
/// let trap = run.call(()).unwrap_err();
|
||||
/// assert!(trap.to_string().contains("wasm trap: interrupt"));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
|
||||
Reference in New Issue
Block a user