Refine the runtime api and document the exposed items (#115)

* private module, remove unused method, docs on compile_with

* refine runtime api and document exposed items

* Fix integration test build

* Fix lint
This commit is contained in:
Lachlan Sneff
2019-01-23 12:34:15 -08:00
committed by GitHub
parent 7632beced8
commit ab65477d1f
10 changed files with 205 additions and 53 deletions

View File

@ -5,17 +5,53 @@ pub trait LikeNamespace {
fn get_export(&mut self, name: &str) -> Option<Export>;
}
/// All of the import data used when instantiating.
///
/// It's suggested that you use the [`imports!`] macro
/// instead of creating an `ImportObject` by hand.
///
/// [`imports!`]: macro.imports.html
///
/// # Usage:
/// ```
/// # use wasmer_runtime_core::imports;
/// # use wasmer_runtime_core::vm::Ctx;
/// let import_object = imports! {
/// "env" => {
/// "foo" => foo<[i32] -> [i32]>,
/// },
/// };
///
/// extern fn foo(n: i32, _: &mut Ctx) -> i32 {
/// n
/// }
/// ```
pub struct ImportObject {
map: HashMap<String, Box<dyn LikeNamespace>>,
}
impl ImportObject {
/// Create a new `ImportObject`.
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}
/// Register anything that implements `LikeNamespace` as a namespace.
///
/// # Usage:
/// ```
/// # use wasmer_runtime_core::Instance;
/// # use wasmer_runtime_core::import::{ImportObject, Namespace};
/// fn register(instance: Instance, namespace: Namespace) {
/// let mut import_object = ImportObject::new();
///
/// import_object.register("namespace0", instance);
/// import_object.register("namespace1", namespace);
/// // ...
/// }
/// ```
pub fn register<S, N>(&mut self, name: S, namespace: N) -> Option<Box<dyn LikeNamespace>>
where
S: Into<String>,

View File

@ -23,9 +23,15 @@ pub(crate) struct InstanceInner {
vmctx: Box<vm::Ctx>,
}
/// A WebAssembly instance
/// An instantiated WebAssembly module.
///
/// An `Instance` represents a WebAssembly module that
/// has been instantiated with an [`ImportObject`] and is
/// ready to be called.
///
/// [`ImportObject`]: struct.ImportObject.html
pub struct Instance {
pub module: Rc<ModuleInner>,
module: Rc<ModuleInner>,
inner: Box<InstanceInner>,
#[allow(dead_code)]
imports: Box<ImportObject>,
@ -67,11 +73,27 @@ impl Instance {
}
/// Call an exported webassembly function given the export name.
/// Pass arguments by wrapping each one in the `Value` enum.
/// The returned values are also each wrapped in a `Value`.
/// Pass arguments by wrapping each one in the [`Value`] enum.
/// The returned values are also each wrapped in a [`Value`].
///
/// [`Value`]: enum.Value.html
///
/// # Note:
/// This returns `CallResult<Vec<Value>>` in order to support
/// the future multi-value returns webassembly feature.
///
/// # Usage:
/// ```
/// # use wasmer_runtime_core::types::Value;
/// # use wasmer_runtime_core::error::Result;
/// # use wasmer_runtime_core::Instance;
/// # fn call_foo(instance: &mut Instance) -> Result<()> {
/// // ...
/// let results = instance.call("foo", &[Value::I32(42)])?;
/// // ...
/// # Ok(())
/// # }
/// ```
pub fn call(&mut self, name: &str, args: &[Value]) -> CallResult<Vec<Value>> {
let export_index =
self.module
@ -329,9 +351,9 @@ impl LikeNamespace for Instance {
}
}
// TODO Remove this later, only needed for compilation till emscripten is updated
#[doc(hidden)]
impl Instance {
pub fn memory_offset_addr(&self, _index: usize, _offset: usize) -> *const u8 {
pub fn memory_offset_addr(&self, _: u32, _: usize) -> *const u8 {
unimplemented!()
}
}

View File

@ -42,7 +42,12 @@ pub mod prelude {
pub use crate::{export_func, imports};
}
/// Compile a webassembly module using the provided compiler.
/// Compile a [`Module`] using the provided compiler from
/// WebAssembly binary code. This function is useful if it
/// is necessary to a compile a module before it can be instantiated
/// and must be used if you wish to use a different backend from the default.
///
/// [`Module`]: struct.Module.html
pub fn compile_with(
wasm: &[u8],
compiler: &dyn backend::Compiler,
@ -53,9 +58,9 @@ pub fn compile_with(
.map(|inner| module::Module::new(Rc::new(inner)))
}
/// This function performs validation as defined by the
/// WebAssembly specification and returns true if validation
/// succeeded, false if validation failed.
/// Perform validation as defined by the
/// WebAssembly specification. Returns `true` if validation
/// succeeded, `false` if validation failed.
pub fn validate(wasm: &[u8]) -> bool {
use wasmparser::WasmDecoder;
let mut parser = wasmparser::ValidatingParser::new(wasm, None);

View File

@ -51,6 +51,29 @@ macro_rules! __export_func_convert_type {
};
}
/// Generate an [`ImportObject`] safely.
///
/// [`ImportObject`]: struct.ImportObject.html
///
/// # Note:
/// The `import` macro currently only supports
/// importing functions.
///
///
/// # Usage:
/// ```
/// # use wasmer_runtime_core::imports;
/// # use wasmer_runtime_core::vm::Ctx;
/// let import_object = imports! {
/// "env" => {
/// "foo" => foo<[i32] -> [i32]>,
/// },
/// };
///
/// extern fn foo(n: i32, _: &mut Ctx) -> i32 {
/// n
/// }
/// ```
#[macro_export]
macro_rules! imports {
( $( $ns_name:expr => $ns:tt, )* ) => {{

View File

@ -42,16 +42,44 @@ pub struct ModuleInner {
pub sig_registry: SigRegistry,
}
pub struct Module(pub Rc<ModuleInner>);
/// A compiled WebAssembly module.
///
/// `Module` is returned by the [`compile`] and
/// [`compile_with`] functions.
///
/// [`compile`]: fn.compile.html
/// [`compile_with`]: fn.compile_with.html
pub struct Module(#[doc(hidden)] pub Rc<ModuleInner>);
impl Module {
pub(crate) fn new(inner: Rc<ModuleInner>) -> Self {
Module(inner)
}
/// Instantiate a WebAssembly module with the provided imports.
pub fn instantiate(&self, imports: ImportObject) -> Result<Instance> {
Instance::new(Rc::clone(&self.0), Box::new(imports))
/// Instantiate a WebAssembly module with the provided [`ImportObject`].
///
/// [`ImportObject`]: struct.ImportObject.html
///
/// # Note:
/// Instantiating a `Module` will also call the function designated as `start`
/// in the WebAssembly module, if there is one.
///
/// # Usage:
/// ```
/// # use wasmer_runtime_core::error::Result;
/// # use wasmer_runtime_core::Module;
/// # use wasmer_runtime_core::imports;
/// # fn instantiate(module: &Module) -> Result<()> {
/// let import_object = imports! {
/// // ...
/// };
/// let instance = module.instantiate(import_object)?;
/// // ...
/// # Ok(())
/// # }
/// ```
pub fn instantiate(&self, import_object: ImportObject) -> Result<Instance> {
Instance::new(Rc::clone(&self.0), Box::new(import_object))
}
}

View File

@ -1,5 +1,6 @@
use crate::{module::ModuleInner, structures::TypedIndex};
/// Represents a WebAssembly type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Type {
/// The `i32` type.
@ -12,6 +13,10 @@ pub enum Type {
F64,
}
/// Represents a WebAssembly value.
///
/// As the number of types in WebAssembly expand,
/// this structure will expand as well.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
/// The `i32` type.

View File

@ -6,6 +6,9 @@ use crate::{
};
use std::{ffi::c_void, mem, ptr, slice};
/// The context of the currently running WebAssembly instance.
///
///
#[derive(Debug)]
#[repr(C)]
pub struct Ctx {
@ -39,6 +42,7 @@ pub struct Ctx {
}
impl Ctx {
#[doc(hidden)]
pub unsafe fn new(
local_backing: &mut LocalBacking,
import_backing: &mut ImportBacking,
@ -63,6 +67,7 @@ impl Ctx {
}
}
#[doc(hidden)]
pub unsafe fn new_with_data(
local_backing: &mut LocalBacking,
import_backing: &mut ImportBacking,
@ -89,6 +94,25 @@ impl Ctx {
}
}
/// This exposes the specified memory of the WebAssembly instance
/// as a mutable slice.
///
/// WebAssembly will soon support multiple linear memories, so this
/// forces the user to specify.
///
/// # Usage:
///
/// ```
/// # use wasmer_runtime_core::{
/// # vm::Ctx,
/// # error::Result,
/// # };
/// extern fn host_func(ctx: &mut Ctx) {
/// let first_memory = ctx.memory(0);
/// // Set the first byte of that linear memory.
/// first_memory[0] = 42;
/// }
/// ```
pub fn memory<'a>(&'a mut self, mem_index: u32) -> &'a mut [u8] {
let module = unsafe { &*self.module };
let mem_index = MemoryIndex::new(mem_index as usize);
@ -110,6 +134,7 @@ impl Ctx {
}
}
#[doc(hidden)]
impl Ctx {
#[allow(clippy::erasing_op)] // TODO
pub fn offset_memories() -> u8 {