Skip to content

Commit

Permalink
Migrated internal samples to new Context API
Browse files Browse the repository at this point in the history
  • Loading branch information
ptitSeb committed Jun 30, 2022
1 parent 5fbe6b4 commit 6e94cae
Show file tree
Hide file tree
Showing 12 changed files with 156 additions and 96 deletions.
21 changes: 12 additions & 9 deletions lib/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
//!
//! ```rust
//! use wasmer::{Store, Module, Instance, Value, imports};
//! use wasmer::Context as WasmerContext;
//!
//! fn main() -> anyhow::Result<()> {
//! let module_wat = r#"
Expand All @@ -53,13 +54,14 @@
//! "#;
//!
//! let store = Store::default();
//! let mut ctx = WasmerContext::new(&store, ());
//! let module = Module::new(&store, &module_wat)?;
//! // The module doesn't import anything, so we create an empty import object.
//! let import_object = imports! {};
//! let instance = Instance::new(&module, &import_object)?;
//! let instance = Instance::new(&mut ctx, &module, &import_object)?;
//!
//! let add_one = instance.exports.get_function("add_one")?;
//! let result = add_one.call(&[Value::I32(42)])?;
//! let result = add_one.call(&mut ctx, &[Value::I32(42)])?;
//! assert_eq!(result[0], Value::I32(43));
//!
//! Ok(())
Expand Down Expand Up @@ -150,11 +152,12 @@
//!
//! ```
//! # use wasmer::{imports, Function, Memory, MemoryType, Store, Imports};
//! # fn imports_example(store: &Store) -> Imports {
//! let memory = Memory::new(&store, MemoryType::new(1, None, false)).unwrap();
//! # use wasmer::ContextMut;
//! # fn imports_example(mut ctx: ContextMut<()>, store: &Store) -> Imports {
//! let memory = Memory::new(&mut ctx, MemoryType::new(1, None, false)).unwrap();
//! imports! {
//! "env" => {
//! "my_function" => Function::new_native(store, || println!("Hello")),
//! "my_function" => Function::new_native(&mut ctx, |_ctx: ContextMut<()>| println!("Hello")),
//! "memory" => memory,
//! }
//! }
Expand All @@ -165,12 +168,12 @@
//! from any instance via `instance.exports`:
//!
//! ```
//! # use wasmer::{imports, Instance, Function, Memory, TypedFunction};
//! # fn exports_example(instance: &Instance) -> anyhow::Result<()> {
//! # use wasmer::{imports, Instance, Function, Memory, TypedFunction, ContextMut};
//! # fn exports_example(mut ctx: ContextMut<()>, instance: &Instance) -> anyhow::Result<()> {
//! let memory = instance.exports.get_memory("memory")?;
//! let memory: &Memory = instance.exports.get("some_other_memory")?;
//! let add: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function("add")?;
//! let result = add.call(5, 37)?;
//! let add: TypedFunction<(i32, i32), i32> = instance.exports.get_typed_function(&mut ctx, "add")?;
//! let result = add.call(&mut ctx, 5, 37)?;
//! assert_eq!(result, 42);
//! # Ok(())
//! # }
Expand Down
8 changes: 6 additions & 2 deletions lib/api/src/sys/exports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ use thiserror::Error;
///
/// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (global $one (export "glob") f32 (f32.const 1)))
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// #
/// // This results with an error: `ExportError::IncompatibleType`.
/// let export = instance.exports.get_function("glob").unwrap();
Expand All @@ -35,11 +37,13 @@ use thiserror::Error;
///
/// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value, ExportError};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm("(module)".as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// #
/// // This results with an error: `ExportError::Missing`.
/// let export = instance.exports.get_function("unknown").unwrap();
Expand Down
80 changes: 50 additions & 30 deletions lib/api/src/sys/externals/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,13 @@ impl Function {
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// #
/// let signature = FunctionType::new(vec![Type::I32, Type::I32], vec![Type::I32]);
///
/// let f = Function::new(&store, &signature, |args| {
/// let f = Function::new(&mut ctx, &signature, |_ctx, args| {
/// let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
/// Ok(vec![Value::I32(sum)])
/// });
Expand All @@ -65,11 +67,13 @@ impl Function {
///
/// ```
/// # use wasmer::{Function, FunctionType, Type, Store, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// #
/// const I32_I32_TO_I32: ([Type; 2], [Type; 1]) = ([Type::I32, Type::I32], [Type::I32]);
///
/// let f = Function::new(&store, I32_I32_TO_I32, |args| {
/// let f = Function::new(&mut ctx, I32_I32_TO_I32, |_ctx, args| {
/// let sum = args[0].unwrap_i32() + args[1].unwrap_i32();
/// Ok(vec![Value::I32(sum)])
/// });
Expand Down Expand Up @@ -152,14 +156,16 @@ impl Function {
/// # Example
///
/// ```
/// # use wasmer::{Store, Function};
/// # use wasmer::{ContextMut, Store, Function};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
/// let f = Function::new_native(&mut ctx, sum);
/// ```
pub fn new_native<T, F, Args, Rets>(ctx: &mut impl AsContextMut<Data = T>, func: F) -> Self
where
Expand Down Expand Up @@ -203,17 +209,19 @@ impl Function {
/// # Example
///
/// ```
/// # use wasmer::{Function, Store, Type};
/// # use wasmer::{ContextMut, Function, Store, Type};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
/// let f = Function::new_native(&mut ctx, sum);
///
/// assert_eq!(f.ty().params(), vec![Type::I32, Type::I32]);
/// assert_eq!(f.ty().results(), vec![Type::I32]);
/// assert_eq!(f.ty(&mut ctx).params(), vec![Type::I32, Type::I32]);
/// assert_eq!(f.ty(&mut ctx).results(), vec![Type::I32]);
/// ```
pub fn ty(&self, ctx: &impl AsContextRef) -> FunctionType {
self.handle
Expand Down Expand Up @@ -302,16 +310,18 @@ impl Function {
/// # Example
///
/// ```
/// # use wasmer::{Function, Store, Type};
/// # use wasmer::{ContextMut, Function, Store, Type};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
/// let f = Function::new_native(&mut ctx, sum);
///
/// assert_eq!(f.param_arity(), 2);
/// assert_eq!(f.param_arity(&mut ctx), 2);
/// ```
pub fn param_arity(&self, ctx: &impl AsContextRef) -> usize {
self.ty(ctx).params().len()
Expand All @@ -322,16 +332,18 @@ impl Function {
/// # Example
///
/// ```
/// # use wasmer::{Function, Store, Type};
/// # use wasmer::{ContextMut, Function, Store, Type};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// #
/// fn sum(a: i32, b: i32) -> i32 {
/// fn sum(_ctx: ContextMut<()>, a: i32, b: i32) -> i32 {
/// a + b
/// }
///
/// let f = Function::new_native(&store, sum);
/// let f = Function::new_native(&mut ctx, sum);
///
/// assert_eq!(f.result_arity(), 1);
/// assert_eq!(f.result_arity(&mut ctx), 1);
/// ```
pub fn result_arity(&self, ctx: &impl AsContextRef) -> usize {
self.ty(ctx).results().len()
Expand All @@ -349,7 +361,9 @@ impl Function {
///
/// ```
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
Expand All @@ -360,11 +374,11 @@ impl Function {
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
///
/// assert_eq!(sum.call(&[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]);
/// assert_eq!(sum.call(&mut ctx, &[Value::I32(1), Value::I32(2)]).unwrap().to_vec(), vec![Value::I32(3)]);
/// ```
pub fn call(
&self,
Expand Down Expand Up @@ -418,8 +432,10 @@ impl Function {
/// # Examples
///
/// ```
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, TypedFunction, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
Expand All @@ -430,12 +446,12 @@ impl Function {
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
/// let sum_native = sum.native::<(i32, i32), i32>().unwrap();
/// let sum_native: TypedFunction<(i32, i32), i32> = sum.native(&mut ctx).unwrap();
///
/// assert_eq!(sum_native.call(1, 2).unwrap(), 3);
/// assert_eq!(sum_native.call(&mut ctx, 1, 2).unwrap(), 3);
/// ```
///
/// # Errors
Expand All @@ -444,8 +460,10 @@ impl Function {
/// an error will be raised:
///
/// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, TypedFunction, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
Expand All @@ -456,20 +474,22 @@ impl Function {
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
///
/// // This results in an error: `RuntimeError`
/// let sum_native = sum.native::<(i64, i64), i32>().unwrap();
/// let sum_native : TypedFunction<(i64, i64), i32> = sum.native(&mut ctx).unwrap();
/// ```
///
/// If the `Rets` generic parameter does not match the exported function
/// an error will be raised:
///
/// ```should_panic
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, Value};
/// # use wasmer::{imports, wat2wasm, Function, Instance, Module, Store, Type, TypedFunction, Value};
/// # use wasmer::Context as WasmerContext;
/// # let store = Store::default();
/// # let mut ctx = WasmerContext::new(&store, ());
/// # let wasm_bytes = wat2wasm(r#"
/// # (module
/// # (func (export "sum") (param $x i32) (param $y i32) (result i32)
Expand All @@ -480,12 +500,12 @@ impl Function {
/// # "#.as_bytes()).unwrap();
/// # let module = Module::new(&store, wasm_bytes).unwrap();
/// # let import_object = imports! {};
/// # let instance = Instance::new(&module, &import_object).unwrap();
/// # let instance = Instance::new(&mut ctx, &module, &import_object).unwrap();
/// #
/// let sum = instance.exports.get_function("sum").unwrap();
///
/// // This results in an error: `RuntimeError`
/// let sum_native = sum.native::<(i32, i32), i64>().unwrap();
/// let sum_native: TypedFunction<(i32, i32), i64> = sum.native(&mut ctx).unwrap();
/// ```
pub fn native<Args, Rets>(
&self,
Expand Down
Loading

0 comments on commit 6e94cae

Please sign in to comment.