Skip to content

Commit

Permalink
4th iteration on documentation (bytecodealliance#22)
Browse files Browse the repository at this point in the history
* Rename LoadedModule to Module

* Hide TryInto

* Fix rustdoc tests.

* Rename from_parity_wasm_module and doc it.

* Document `Module::from_buffer`

* Tidy Module docs

* Some rustdoc headers.

* Document FuncInstance::{alloc_host, signature}

* Document descriptors.

* Doc NotStartedModuleRef

* Fix cargo-deadlinks
  • Loading branch information
pepyakin authored Jan 26, 2018
1 parent aa4c8fe commit 551c992
Show file tree
Hide file tree
Showing 15 changed files with 179 additions and 75 deletions.
3 changes: 2 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ addons:
- g++-6
- cmake
install:
- cargo install cargo-deadlinks
# Install `cargo-deadlinks` unless it is currently installed.
- command -v cargo-deadlinks &> /dev/null || cargo install cargo-deadlinks
script:
- export CC=/usr/bin/gcc-6
- export CXX=/usr/bin/g++-6
Expand Down
6 changes: 3 additions & 3 deletions examples/interpret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ extern crate wasmi;

use std::env::args;
use std::fs::File;
use wasmi::{ModuleInstance, NopExternals, RuntimeValue, ImportsBuilder, load_from_buffer, LoadedModule};
use wasmi::{ModuleInstance, NopExternals, RuntimeValue, ImportsBuilder, Module};

fn load_from_file(filename: &str) -> LoadedModule {
fn load_from_file(filename: &str) -> Module {
use std::io::prelude::*;
let mut file = File::open(filename).unwrap();
let mut buf = Vec::new();
file.read_to_end(&mut buf).unwrap();
load_from_buffer(buf).unwrap()
Module::from_buffer(buf).unwrap()
}

fn main() {
Expand Down
4 changes: 2 additions & 2 deletions examples/invoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ extern crate wasmi;
use std::env::args;

use parity_wasm::elements::{Internal, External, Type, FunctionType, ValueType};
use wasmi::{RuntimeValue, ModuleInstance, NopExternals, ImportsBuilder, load_from_module};
use wasmi::{RuntimeValue, ModuleInstance, NopExternals, ImportsBuilder};


fn main() {
Expand Down Expand Up @@ -69,7 +69,7 @@ fn main() {
}).collect::<Vec<RuntimeValue>>()
};

let loaded_module = load_from_module(module).expect("Module to be valid");
let loaded_module = wasmi::Module::from_parity_wasm_module(module).expect("Module to be valid");

// Intialize deserialized module. It adds module into It expects 3 parameters:
// - a name for the module
Expand Down
2 changes: 1 addition & 1 deletion examples/tictactoe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ fn instantiate(path: &str) -> Result<ModuleRef, Error> {
let mut file = File::open(path).unwrap();
let mut wasm_buf = Vec::new();
file.read_to_end(&mut wasm_buf).unwrap();
wasmi::load_from_buffer(&wasm_buf)?
wasmi::Module::from_buffer(&wasm_buf)?
};

let mut imports = ImportsBuilder::new();
Expand Down
6 changes: 3 additions & 3 deletions spec/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use wasmi::{
GlobalInstance, GlobalRef, ImportResolver, ImportsBuilder,
MemoryInstance, MemoryRef, ModuleImportResolver, ModuleInstance,
ModuleRef, RuntimeValue, TableInstance, TableRef, ValueType,
load_from_buffer, LoadedModule, Signature, MemoryDescriptor,
Module, Signature, MemoryDescriptor,
TableDescriptor, GlobalDescriptor, FuncInstance, RuntimeArgs,
};

Expand Down Expand Up @@ -225,15 +225,15 @@ impl ImportResolver for SpecDriver {
}
}

fn try_load_module(base_dir: &Path, module_path: &str) -> Result<LoadedModule, Error> {
fn try_load_module(base_dir: &Path, module_path: &str) -> Result<Module, Error> {
use std::io::prelude::*;

let mut wasm_path = PathBuf::from(base_dir.clone());
wasm_path.push(module_path);
let mut file = File::open(wasm_path).unwrap();
let mut buf = Vec::new();
file.read_to_end(&mut buf).unwrap();
load_from_buffer(buf).map_err(|e| Error::Load(e.to_string()))
Module::from_buffer(buf).map_err(|e| Error::Load(e.to_string()))
}

fn try_load(
Expand Down
30 changes: 22 additions & 8 deletions src/func.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use module::ModuleInstance;
use common::stack::StackWithLimit;
use common::{DEFAULT_FRAME_STACK_LIMIT, DEFAULT_VALUE_STACK_LIMIT};

/// Reference to a [`FuncInstance`].
/// Reference to a function (See [`FuncInstance`] for details).
///
/// This reference has a reference-counting semantics.
///
Expand Down Expand Up @@ -77,6 +77,15 @@ impl fmt::Debug for FuncInstance {
}

impl FuncInstance {

/// Allocate a function instance for a host function.
///
/// When this function instance will be called by the wasm code,
/// the instance of [`Externals`] will be invoked by calling `invoke_index`
/// with specified `host_func_index` here.
/// This call will be made with the `signature` provided here.
///
/// [`Externals`]: trait.Externals.html
pub fn alloc_host(signature: Signature, host_func_index: usize) -> FuncRef {
let func = FuncInstanceInternal::Host {
signature,
Expand All @@ -85,6 +94,18 @@ impl FuncInstance {
FuncRef(Rc::new(FuncInstance(func)))
}

/// Returns [signature] of this function instance.
///
/// This function instance can only be called with matching signatures.
///
/// [signature]: struct.Signature.html
pub fn signature(&self) -> &Signature {
match *self.as_internal() {
FuncInstanceInternal::Internal { ref signature, .. } => signature,
FuncInstanceInternal::Host { ref signature, .. } => signature,
}
}

pub(crate) fn as_internal(&self) -> &FuncInstanceInternal {
&self.0
}
Expand All @@ -102,13 +123,6 @@ impl FuncInstance {
FuncRef(Rc::new(FuncInstance(func)))
}

pub fn signature(&self) -> &Signature {
match *self.as_internal() {
FuncInstanceInternal::Internal { ref signature, .. } => signature,
FuncInstanceInternal::Host { ref signature, .. } => signature,
}
}

pub(crate) fn body(&self) -> Option<Rc<FuncBody>> {
match *self.as_internal() {
FuncInstanceInternal::Internal { ref body, .. } => Some(Rc::clone(body)),
Expand Down
2 changes: 1 addition & 1 deletion src/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use Error;
use types::ValueType;
use parity_wasm::elements::{ValueType as EValueType};

/// Reference to a [`GlobalInstance`].
/// Reference to a global variable (See [`GlobalInstance`] for details).
///
/// This reference has a reference-counting semantics.
///
Expand Down
4 changes: 2 additions & 2 deletions src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,12 @@ pub trait ImportResolver {
/// # Examples
///
/// ```rust
/// use wasmi::{load_from_buffer, ModuleInstance, ImportsBuilder};
/// use wasmi::{ModuleInstance, ImportsBuilder};
/// #
/// # struct EnvModuleResolver;
/// # impl ::wasmi::ModuleImportResolver for EnvModuleResolver { }
/// # fn func() -> Result<(), ::wasmi::Error> {
/// # let module = load_from_buffer(&[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]).unwrap();
/// # let module = wasmi::Module::from_buffer(&[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]).unwrap();
/// # let other_instance = ModuleInstance::new(&module, &ImportsBuilder::default())?.assert_no_start();
///
/// let imports = ImportsBuilder::new()
Expand Down
115 changes: 85 additions & 30 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
//! .expect("failed to parse wat");
//!
//! // Load wasm binary and prepare it for instantiation.
//! let module = wasmi::load_from_buffer(&wasm_binary)
//! let module = wasmi::Module::from_buffer(&wasm_binary)
//! .expect("failed to load wasm");
//!
//! // Instantiate a module with empty imports and
Expand Down Expand Up @@ -105,7 +105,6 @@ extern crate byteorder;
use std::fmt;
use std::error;
use std::collections::HashMap;
use parity_wasm::elements::Module;

/// Internal interpreter error.
#[derive(Debug)]
Expand Down Expand Up @@ -223,48 +222,104 @@ mod tests;

pub use self::memory::{MemoryInstance, MemoryRef};
pub use self::table::{TableInstance, TableRef};
pub use self::value::{RuntimeValue, TryInto};
pub use self::value::RuntimeValue;
pub use self::host::{Externals, NopExternals, HostError, RuntimeArgs};
pub use self::imports::{ModuleImportResolver, ImportResolver, ImportsBuilder};
pub use self::module::{ModuleInstance, ModuleRef, ExternVal, NotStartedModuleRef};
pub use self::global::{GlobalInstance, GlobalRef};
pub use self::func::{FuncInstance, FuncRef};
pub use self::types::{Signature, ValueType, GlobalDescriptor, TableDescriptor, MemoryDescriptor};

pub struct LoadedModule {
/// Deserialized module prepared for instantiation.
pub struct Module {
labels: HashMap<usize, HashMap<usize, usize>>,
module: Module,
module: parity_wasm::elements::Module,
}

impl LoadedModule {
pub(crate) fn module(&self) -> &Module {
&self.module
}
impl Module {

pub(crate) fn labels(&self) -> &HashMap<usize, HashMap<usize, usize>> {
&self.labels
}
/// Create `Module` from `parity_wasm::elements::Module`.
///
/// This function will load, validate and prepare a `parity_wasm`'s `Module`.
///
/// # Errors
///
/// Returns `Err` if provided `Module` is not valid.
///
/// # Examples
///
/// ```rust
/// extern crate parity_wasm;
/// extern crate wasmi;
///
/// use parity_wasm::builder;
/// use parity_wasm::elements;
///
/// fn main() {
/// let parity_module =
/// builder::module()
/// .function()
/// .signature().with_param(elements::ValueType::I32).build()
/// .body().build()
/// .build()
/// .build();
///
/// let module = wasmi::Module::from_parity_wasm_module(parity_module)
/// .expect("parity-wasm builder generated invalid module!");
///
/// // Instantiate `module`, etc...
/// }
/// ```
pub fn from_parity_wasm_module(module: parity_wasm::elements::Module) -> Result<Module, Error> {
use validation::{validate_module, ValidatedModule};
let ValidatedModule {
labels,
module,
} = validate_module(module)?;

pub fn into_module(self) -> Module {
self.module
Ok(Module {
labels,
module,
})
}
}

pub fn load_from_module(module: Module) -> Result<LoadedModule, Error> {
use validation::{validate_module, ValidatedModule};
let ValidatedModule {
labels,
module,
} = validate_module(module)?;
/// Create `Module` from a given buffer.
///
/// This function will deserialize wasm module from a given module,
/// validate and prepare it for instantiation.
///
/// # Errors
///
/// Returns `Err` if wasm binary in provided `buffer` is not valid wasm binary.
///
/// # Examples
///
/// ```rust
/// extern crate wasmi;
///
/// fn main() {
/// let module =
/// wasmi::Module::from_buffer(
/// // Minimal module:
/// // \0asm - magic
/// // 0x01 - version (in little-endian)
/// &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]
/// ).expect("Failed to load minimal module");
///
/// // Instantiate `module`, etc...
/// }
/// ```
pub fn from_buffer<B: AsRef<[u8]>>(buffer: B) -> Result<Module, Error> {
let module = parity_wasm::elements::deserialize_buffer(buffer.as_ref())
.map_err(|e: parity_wasm::elements::Error| Error::Validation(e.to_string()))?;
Module::from_parity_wasm_module(module)
}

Ok(LoadedModule {
labels,
module,
})
}
pub(crate) fn module(&self) -> &parity_wasm::elements::Module {
&self.module
}

pub fn load_from_buffer<B: AsRef<[u8]>>(buffer: B) -> Result<LoadedModule, Error> {
let module = parity_wasm::elements::deserialize_buffer(buffer.as_ref())
.map_err(|e: parity_wasm::elements::Error| Error::Validation(e.to_string()))?;
load_from_module(module)
pub(crate) fn labels(&self) -> &HashMap<usize, HashMap<usize, usize>> {
&self.labels
}
}
2 changes: 1 addition & 1 deletion src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub const LINEAR_MEMORY_PAGE_SIZE: u32 = 65536;
/// Maximal number of pages.
const LINEAR_MEMORY_MAX_PAGES: u32 = 65536;

/// Reference to a [`MemoryInstance`].
/// Reference to a memory (See [`MemoryInstance`] for details).
///
/// This reference has a reference-counting semantics.
///
Expand Down
Loading

0 comments on commit 551c992

Please sign in to comment.