Struct wasmer_wasix::syscalls::Function

pub(crate) struct Function(pub(crate) BackendFunction);
Expand description

A WebAssembly function instance.

A function instance is the runtime representation of a function. It effectively is a closure of the original function (defined in either the host or the WebAssembly module) over the runtime crate::Instance of its originating crate::Module.

The module instance is used to resolve references to other definitions during execution of the function.

Spec: https://webassembly.github.io/spec/core/exec/runtime.html#function-instances

§Panics

  • Closures (functions with captured environments) are not currently supported with native functions. Attempting to create a native Function with one will result in a panic. Closures as host functions tracking issue

Tuple Fields§

§0: BackendFunction

Implementations§

§

impl Function

pub fn new<FT, F>(store: &mut impl AsStoreMut, ty: FT, func: F) -> Function
where FT: Into<FunctionType>, F: Fn(&[Value]) -> Result<Vec<Value>, RuntimeError> + 'static + Send + Sync,

Creates a new host Function (dynamic) with the provided signature.

If you know the signature of the host function at compile time, consider using Function::new_typed for less runtime overhead.

pub fn new_with_env<FT, F, T>( store: &mut impl AsStoreMut, env: &FunctionEnv<T>, ty: FT, func: F, ) -> Function
where T: Send + 'static, FT: Into<FunctionType>, F: Fn(FunctionEnvMut<'_, T>, &[Value]) -> Result<Vec<Value>, RuntimeError> + 'static + Send + Sync,

Creates a new host Function (dynamic) with the provided signature.

If you know the signature of the host function at compile time, consider using Function::new_typed_with_env for less runtime overhead.

Takes a FunctionEnv that is passed into func. If that is not required, Function::new might be an option as well.

§Examples
let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);

let f = Function::new_with_env(&mut store, &env, &signature, |_env, args| {
    let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
    Ok(vec![Value::I32(sum)])
});

With constant signature:

const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]);

let f = Function::new_with_env(&mut store, &env, I32_I32_TO_I32, |_env, args| {
    let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
    Ok(vec![Value::I32(sum)])
});

pub fn new_typed<F, Args, Rets>( store: &mut impl AsStoreMut, func: F, ) -> Function
where F: HostFunction<(), Args, Rets, WithoutEnv> + 'static + Send + Sync, Args: WasmTypeList, Rets: WasmTypeList,

Creates a new host Function from a native function.

pub fn new_typed_with_env<T, F, Args, Rets>( store: &mut impl AsStoreMut, env: &FunctionEnv<T>, func: F, ) -> Function
where T: Send + 'static, F: HostFunction<T, Args, Rets, WithEnv> + 'static + Send + Sync, Args: WasmTypeList, Rets: WasmTypeList,

Creates a new host Function with an environment from a typed function.

The function signature is automatically retrieved using the Rust typing system.

§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_typed_with_env(&mut store, &env, sum);

pub fn ty(&self, store: &impl AsStoreRef) -> FunctionType

Returns the [FunctionType] of the Function.

§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_typed_with_env(&mut store, &env, sum);

assert_eq!(f.ty(&mut store).params(), vec![Type::I32, Type::I32]);
assert_eq!(f.ty(&mut store).results(), vec![Type::I32]);

pub fn param_arity(&self, store: &impl AsStoreRef) -> usize

Returns the number of parameters that this function takes.

§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_typed_with_env(&mut store, &env, sum);

assert_eq!(f.param_arity(&mut store), 2);

pub fn result_arity(&self, store: &impl AsStoreRef) -> usize

Returns the number of results this function produces.

§Example
fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
    a + b
}

let f = Function::new_typed_with_env(&mut store, &env, sum);

assert_eq!(f.result_arity(&mut store), 1);

pub fn call( &self, store: &mut impl AsStoreMut, params: &[Value], ) -> Result<Box<[Value]>, RuntimeError>

Call the function.

Depending on where the Function is defined, it will call it.

  1. If the function is defined inside a WebAssembly, it will call the trampoline for the function signature.
  2. If the function is defined in the host (in a native way), it will call the trampoline.
§Examples
let sum = instance.exports.get_function("sum").unwrap();

assert_eq!(sum.call(&mut store, &[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]);

pub fn typed<Args, Rets>( &self, store: &impl AsStoreRef, ) -> Result<TypedFunction<Args, Rets>, RuntimeError>
where Args: WasmTypeList, Rets: WasmTypeList,

Transform this WebAssembly function into a typed function. See TypedFunction to learn more.

§Examples
let sum = instance.exports.get_function("sum").unwrap();
let sum_typed: TypedFunction<(i32, i32), i32> = sum.typed(&mut store).unwrap();

assert_eq!(sum_typed.call(&mut store, 1, 2).unwrap(), 3);
§Errors

If the Args generic parameter does not match the exported function an error will be raised:

let sum = instance.exports.get_function("sum").unwrap();

// This results in an error: `RuntimeError`
let sum_typed : TypedFunction<(i64, i64), i32> = sum.typed(&mut store).unwrap();

If the Rets generic parameter does not match the exported function an error will be raised:

let sum = instance.exports.get_function("sum").unwrap();

// This results in an error: `RuntimeError`
let sum_typed: TypedFunction<(i32, i32), i64> = sum.typed(&mut store).unwrap();

pub fn is_from_store(&self, store: &impl AsStoreRef) -> bool

Checks whether this Function can be used with the given store.

§

impl Function

pub fn into_sys(self) -> Function

Consume [self] into [crate::backend::sys::function::Function].

pub fn as_sys(&self) -> &Function

Convert a reference to [self] into a reference to [crate::backend::sys::function::Function].

pub fn as_sys_mut(&mut self) -> &mut Function

Convert a mutable reference to [self] into a mutable reference [crate::backend::sys::function::Function].

Trait Implementations§

§

impl Clone for Function

§

fn clone(&self) -> Function

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for Function

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<'a> Exportable<'a> for Function

§

fn get_self_from_extern( _extern: &'a Extern, ) -> Result<&'a Function, ExportError>

Implementation of how to get the export corresponding to the implementing type from an Instance by name.
§

impl From<Function> for Extern

§

fn from(r: Function) -> Extern

Converts to this type from the input type.
§

impl From<Function> for Value

§

fn from(val: Function) -> Value

Converts to this type from the input type.
§

impl<Args, Rets> From<TypedFunction<Args, Rets>> for Function
where Args: WasmTypeList, Rets: WasmTypeList,

§

fn from(other: TypedFunction<Args, Rets>) -> Function

Converts to this type from the input type.
§

impl NativeWasmType for Function

§

const WASM_TYPE: Type = Type::FuncRef

Type for this NativeWasmType.
§

type Abi = usize

The ABI for this type (i32, i64, f32, f64)
§

impl PartialEq for Function

§

fn eq(&self, other: &Function) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl Eq for Function

§

impl StructuralPartialEq for Function

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> ArchivePointee for T

§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

default unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> DynClone for T
where T: Clone,

§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<'a, T> ExportableWithGenerics<'a, (), ()> for T
where T: Exportable<'a> + Clone + 'static,

§

fn get_self_from_extern_with_generics( _extern: &'a Extern, ) -> Result<T, ExportError>

Get an export with the given generics.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> LayoutRaw for T

§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> Pointee for T

§

type Metadata = ()

The metadata type for pointers and references to this type.
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> Upcastable for T
where T: Any + Debug + 'static,

source§

fn upcast_any_ref(&self) -> &(dyn Any + 'static)

source§

fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)

source§

fn upcast_any_box(self: Box<T>) -> Box<dyn Any>

§

impl<T> Upcastable for T
where T: Any + Send + Sync + 'static,

§

fn upcast_any_ref(&self) -> &(dyn Any + 'static)

upcast ref
§

fn upcast_any_mut(&mut self) -> &mut (dyn Any + 'static)

upcast mut ref
§

fn upcast_any_box(self: Box<T>) -> Box<dyn Any>

upcast boxed dyn
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where T: 'static,

§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

§

impl<T> MaybeSendSync for T