Files
wasmtime/wasmtime-api/examples/multi.rs
Josh Triplett 56ce6e9c9f Migrate from failure to thiserror and anyhow (#436)
* Migrate from failure to thiserror and anyhow

The failure crate invents its own traits that don't use
std::error::Error (because failure predates certain features added to
Error); this prevents using ? on an error from failure in a function
using Error. The thiserror and anyhow crates integrate with the standard
Error trait instead.

This change does not attempt to semantically change or refactor the
approach to error-handling in any portion of the code, to ensure that
the change remains straightforward to review. Modules using specific
differentiated error types move from failure_derive and derive(Fail) to
thiserror and derive(Error). Modules boxing all errors opaquely move
from failure::Error to anyhow. Modules using String as an error type
continue to do so. Code using unwrap or expect continues to do so.

Drop Display implementations when thiserror can easily derive an
identical instance.

Drop manual traversal of iter_causes; anyhow's Debug instance prints the
chain of causes by default.

Use anyhow's type alias anyhow::Result<T> in place of
std::result::Result<T, anyhow::Error> whenever possible.

* wasm2obj: Simplify error handling using existing messages

handle_module in wasm2obj manually maps
cranelift_codegen::isa::LookupError values to strings, but LookupError
values already have strings that say almost exactly the same thing.
Rely on the strings from cranelift.

* wasmtime: Rely on question-mark-in-main

The main() wrapper around rmain() completely matches the behavior of
question-mark-in-main (print error to stderr and return 1), so switch to
question-mark-in-main.

* Update to walrus 0.13 and wasm-webidl-bindings 0.6

Both crates switched from failure to anyhow; updating lets us avoid a
translation from failure to anyhow within wasmtime-interface-types.
2019-11-04 20:43:25 -08:00

83 lines
2.4 KiB
Rust

//! Translation of multi example
extern crate alloc;
use alloc::rc::Rc;
use anyhow::{ensure, format_err, Context as _, Result};
use core::cell::Ref;
use std::fs::read;
use wasmtime_api::*;
struct Callback;
impl Callable for Callback {
fn call(&self, args: &[Val], results: &mut [Val]) -> Result<(), HostRef<Trap>> {
println!("Calling back...");
println!("> {} {}", args[0].i32(), args[1].i64());
results[0] = Val::I64(args[1].i64() + 1);
results[1] = Val::I32(args[0].i32() + 1);
Ok(())
}
}
fn main() -> Result<()> {
// Initialize.
println!("Initializing...");
let engine = HostRef::new(Engine::new(Config::default()));
let store = HostRef::new(Store::new(engine));
// Load binary.
println!("Loading binary...");
let binary = read("examples/multi.wasm")?;
// Compile.
println!("Compiling module...");
let module =
HostRef::new(Module::new(store.clone(), &binary).context("Error compiling module!")?);
// Create external print functions.
println!("Creating callback...");
let callback_type = FuncType::new(
Box::new([ValType::I32, ValType::I64]),
Box::new([ValType::I64, ValType::I32]),
);
let callback_func = HostRef::new(Func::new(store.clone(), callback_type, Rc::new(Callback)));
// Instantiate.
println!("Instantiating module...");
let imports = vec![callback_func.into()];
let instance = HostRef::new(
Instance::new(store.clone(), module, imports.as_slice())
.context("Error instantiating module!")?,
);
// Extract export.
println!("Extracting export...");
let exports = Ref::map(instance.borrow(), |instance| instance.exports());
ensure!(!exports.is_empty(), "Error accessing exports!");
let run_func = exports[0].func().context("Error accessing exports!")?;
// Call.
println!("Calling export...");
let args = vec![Val::I32(1), Val::I64(3)];
let results = run_func
.borrow()
.call(&args)
.map_err(|e| format_err!("> Error calling function: {:?}", e))?;
println!("Printing result...");
println!("> {} {}", results[0].i64(), results[1].i32());
debug_assert!(results[0].i64() == 4);
debug_assert!(results[1].i32() == 2);
// Shut down.
println!("Shutting down...");
drop(store);
// All done.
println!("Done.");
Ok(())
}