From 56ce6e9c9f480fd30b3cd66ec5ed2817eacfa6e9 Mon Sep 17 00:00:00 2001 From: Josh Triplett Date: Mon, 4 Nov 2019 20:43:25 -0800 Subject: [PATCH] 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 in place of std::result::Result 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. --- Cargo.toml | 12 ++--- fuzz/Cargo.toml | 6 +-- lightbeam/Cargo.toml | 5 +- lightbeam/src/error.rs | 9 ++-- lightbeam/src/lib.rs | 3 -- misc/wasmtime-py/Cargo.toml | 12 ++--- misc/wasmtime-py/src/lib.rs | 10 +--- misc/wasmtime-rust/Cargo.toml | 6 +-- misc/wasmtime-rust/README.md | 2 +- misc/wasmtime-rust/examples/markdown.rs | 2 +- misc/wasmtime-rust/macro/src/lib.rs | 4 +- misc/wasmtime-rust/src/lib.rs | 12 ++--- src/bin/wasm2obj.rs | 7 +-- src/bin/wasmtime.rs | 28 +++-------- wasmtime-api/Cargo.toml | 14 +++--- wasmtime-api/examples/gcd.rs | 4 +- wasmtime-api/examples/hello.rs | 27 +++++----- wasmtime-api/examples/memory.rs | 19 +++---- wasmtime-api/examples/multi.rs | 29 +++++------ wasmtime-api/src/instance.rs | 8 +-- wasmtime-api/src/lib.rs | 2 - wasmtime-api/src/module.rs | 8 ++- wasmtime-api/src/trampoline/create_handle.rs | 4 +- wasmtime-api/src/trampoline/func.rs | 4 +- wasmtime-api/src/trampoline/global.rs | 7 +-- wasmtime-api/src/trampoline/memory.rs | 4 +- wasmtime-api/src/trampoline/mod.rs | 10 ++-- wasmtime-api/src/trampoline/table.rs | 4 +- wasmtime-api/src/trap.rs | 5 +- wasmtime-api/src/wasm.rs | 2 +- wasmtime-debug/Cargo.toml | 8 +-- wasmtime-debug/src/lib.rs | 2 - wasmtime-debug/src/transform/mod.rs | 5 +- wasmtime-environ/Cargo.toml | 11 ++--- wasmtime-environ/src/compilation.rs | 13 ++--- wasmtime-environ/src/cranelift.rs | 38 ++++++-------- wasmtime-environ/src/lib.rs | 3 -- wasmtime-interface-types/Cargo.toml | 8 +-- wasmtime-interface-types/src/lib.rs | 30 +++++------ wasmtime-interface-types/src/value.rs | 4 +- wasmtime-jit/Cargo.toml | 10 ++-- wasmtime-jit/src/action.rs | 13 ++--- wasmtime-jit/src/context.rs | 28 +++-------- wasmtime-jit/src/instantiate.rs | 15 +++--- wasmtime-jit/src/lib.rs | 3 -- wasmtime-obj/Cargo.toml | 6 +-- wasmtime-runtime/Cargo.toml | 9 ++-- wasmtime-runtime/src/instance.rs | 15 +++--- wasmtime-runtime/src/lib.rs | 2 - wasmtime-wasi-c/Cargo.toml | 6 +-- wasmtime-wasi/Cargo.toml | 6 +-- wasmtime-wast/Cargo.toml | 8 +-- wasmtime-wast/src/wast.rs | 52 +++++++++----------- 53 files changed, 238 insertions(+), 326 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4cb3301621..98a98cf265 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,10 +11,10 @@ edition = "2018" default-run = "wasmtime" [dependencies] -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-entity = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } -cranelift-native = "0.46.1" +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-entity = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } +cranelift-native = { version = "0.47" } wasmtime-api = { path = "wasmtime-api" } wasmtime-debug = { path = "wasmtime-debug" } wasmtime-environ = { path = "wasmtime-environ" } @@ -29,14 +29,14 @@ wasi-common = { git = "https://github.com/CraneStation/wasi-common", rev = "37ce docopt = "1.0.1" serde = { "version" = "1.0.94", features = ["derive"] } faerie = "0.11.0" -failure = "0.1" +anyhow = "1.0.19" target-lexicon = { version = "0.8.1", default-features = false } pretty_env_logger = "0.3.0" file-per-thread-logger = "0.1.1" wat = "1.0.2" libc = "0.2.60" rayon = "1.1" -wasm-webidl-bindings = "0.5" +wasm-webidl-bindings = "0.6" # build.rs tests whether to enable a workaround for the libc strtof function. [target.'cfg(target_os = "linux")'.build-dependencies] diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 598d8d7b1c..8aa197050c 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -11,9 +11,9 @@ cargo-fuzz = true [dependencies] wasmtime-environ = { path = "../wasmtime-environ" } wasmtime-jit = { path = "../wasmtime-jit" } -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } -cranelift-native = "0.46.1" +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } +cranelift-native = { version = "0.47" } libfuzzer-sys = { git = "https://github.com/rust-fuzz/libfuzzer-sys.git" } wasmparser = { version = "0.39.2", default-features = false } binaryen = "0.5.0" diff --git a/lightbeam/Cargo.toml b/lightbeam/Cargo.toml index 625c36d912..3389816ea8 100644 --- a/lightbeam/Cargo.toml +++ b/lightbeam/Cargo.toml @@ -17,9 +17,8 @@ wasmparser = "0.39.1" memoffset = "0.5.1" itertools = "0.8" capstone = "0.6.0" -failure = "0.1.3" -failure_derive = "0.1.3" -cranelift-codegen = "0.46.1" +thiserror = "1.0.4" +cranelift-codegen = { version = "0.47" } multi_mut = "0.1" either = "1.5" typemap = "0.3" diff --git a/lightbeam/src/error.rs b/lightbeam/src/error.rs index 5f2ac6492e..172a8bc8db 100644 --- a/lightbeam/src/error.rs +++ b/lightbeam/src/error.rs @@ -1,15 +1,16 @@ use capstone; +use thiserror::Error; use wasmparser::BinaryReaderError; -#[derive(Fail, PartialEq, Eq, Clone, Debug)] +#[derive(Error, PartialEq, Eq, Clone, Debug)] pub enum Error { - #[fail(display = "Disassembler error: {}", _0)] + #[error("Disassembler error: {0}")] Disassembler(String), - #[fail(display = "Assembler error: {}", _0)] + #[error("Assembler error: {0}")] Assembler(String), - #[fail(display = "Input error: {}", _0)] + #[error("Input error: {0}")] Input(String), } diff --git a/lightbeam/src/lib.rs b/lightbeam/src/lib.rs index 2e8f00168e..e4ccd6d633 100644 --- a/lightbeam/src/lib.rs +++ b/lightbeam/src/lib.rs @@ -5,11 +5,8 @@ extern crate smallvec; extern crate capstone; extern crate either; -extern crate failure; pub extern crate wasmparser; #[macro_use] -extern crate failure_derive; -#[macro_use] extern crate memoffset; extern crate dynasm; extern crate dynasmrt; diff --git a/misc/wasmtime-py/Cargo.toml b/misc/wasmtime-py/Cargo.toml index 82f571e3c4..f5aa0911f3 100644 --- a/misc/wasmtime-py/Cargo.toml +++ b/misc/wasmtime-py/Cargo.toml @@ -12,17 +12,17 @@ name = "_wasmtime" crate-type = ["cdylib"] [dependencies] -cranelift-codegen = "0.46.1" -cranelift-native = "0.46.1" -cranelift-entity = "0.46.1" -cranelift-wasm = "0.46.1" -cranelift-frontend = "0.46.1" +cranelift-codegen = { version = "0.47" } +cranelift-native = { version = "0.47" } +cranelift-entity = { version = "0.47" } +cranelift-wasm = { version = "0.47" } +cranelift-frontend = { version = "0.47" } wasmtime-environ = { path = "../../wasmtime-environ" } wasmtime-interface-types = { path = "../../wasmtime-interface-types" } wasmtime-jit = { path = "../../wasmtime-jit" } wasmtime-runtime = { path = "../../wasmtime-runtime" } target-lexicon = { version = "0.8.1", default-features = false } -failure = "0.1" +anyhow = "1.0.19" region = "2.0.0" wasmparser = "0.39.2" diff --git a/misc/wasmtime-py/src/lib.rs b/misc/wasmtime-py/src/lib.rs index cbc69b81b9..ddba0c1e60 100644 --- a/misc/wasmtime-py/src/lib.rs +++ b/misc/wasmtime-py/src/lib.rs @@ -18,14 +18,8 @@ mod memory; mod module; mod value; -fn err2py(err: failure::Error) -> PyErr { - let mut desc = err.to_string(); - for cause in err.iter_causes() { - desc.push_str("\n"); - desc.push_str(" caused by: "); - desc.push_str(&cause.to_string()); - } - PyErr::new::(desc) +fn err2py(err: anyhow::Error) -> PyErr { + PyErr::new::(format!("{:?}", err)) } #[pyclass] diff --git a/misc/wasmtime-rust/Cargo.toml b/misc/wasmtime-rust/Cargo.toml index e0a12a468e..2ca7ae84de 100644 --- a/misc/wasmtime-rust/Cargo.toml +++ b/misc/wasmtime-rust/Cargo.toml @@ -12,9 +12,9 @@ test = false doctest = false [dependencies] -cranelift-codegen = "0.46.1" -cranelift-native = "0.46.1" -failure = "0.1.5" +cranelift-codegen = { version = "0.47" } +cranelift-native = { version = "0.47" } wasmtime-interface-types = { path = "../../wasmtime-interface-types" } wasmtime-jit = { path = "../../wasmtime-jit" } wasmtime-rust-macro = { path = "./macro" } +anyhow = "1.0.19" diff --git a/misc/wasmtime-rust/README.md b/misc/wasmtime-rust/README.md index c524b9482f..498e29160b 100644 --- a/misc/wasmtime-rust/README.md +++ b/misc/wasmtime-rust/README.md @@ -10,7 +10,7 @@ trait WasmMarkdown { fn render(&mut self, input: &str) -> String; } -fn main() -> Result<(), failure::Error> { +fn main() -> anyhow::Result<()> { let mut markdown = WasmMarkdown::load_file("markdown.wasm")?; println!("{}", markdown.render("# Hello, Rust!")); diff --git a/misc/wasmtime-rust/examples/markdown.rs b/misc/wasmtime-rust/examples/markdown.rs index 7147bf9835..dde903c574 100644 --- a/misc/wasmtime-rust/examples/markdown.rs +++ b/misc/wasmtime-rust/examples/markdown.rs @@ -5,7 +5,7 @@ trait WasmMarkdown { fn render(&mut self, input: &str) -> String; } -fn main() -> Result<(), failure::Error> { +fn main() -> anyhow::Result<()> { let mut markdown = WasmMarkdown::load_file("markdown.wasm")?; println!("{}", markdown.render("# Hello, Rust!")); diff --git a/misc/wasmtime-rust/macro/src/lib.rs b/misc/wasmtime-rust/macro/src/lib.rs index 1838665d9a..cc8861658b 100644 --- a/misc/wasmtime-rust/macro/src/lib.rs +++ b/misc/wasmtime-rust/macro/src/lib.rs @@ -46,12 +46,12 @@ fn generate_load(item: &syn::ItemTrait) -> syn::Result { let name = &item.ident; let root = root(); Ok(quote! { - #vis fn load_file(path: impl AsRef) -> Result<#name, #root::failure::Error> { + #vis fn load_file(path: impl AsRef) -> #root::anyhow::Result<#name> { let bytes = std::fs::read(path)?; let isa = { let isa_builder = #root::cranelift_native::builder() - .map_err(|s| #root::failure::format_err!("{}", s))?; + .map_err(|s| #root::anyhow::format_err!("{}", s))?; let flag_builder = #root::cranelift_codegen::settings::builder(); isa_builder.finish(#root::cranelift_codegen::settings::Flags::new(flag_builder)) }; diff --git a/misc/wasmtime-rust/src/lib.rs b/misc/wasmtime-rust/src/lib.rs index da9ca53ddd..9fde663b10 100644 --- a/misc/wasmtime-rust/src/lib.rs +++ b/misc/wasmtime-rust/src/lib.rs @@ -3,9 +3,9 @@ pub use wasmtime_rust_macro::wasmtime; // modules used by the macro #[doc(hidden)] pub mod __rt { + pub use anyhow; pub use cranelift_codegen; pub use cranelift_native; - pub use failure; pub use wasmtime_interface_types; pub use wasmtime_jit; @@ -13,24 +13,24 @@ pub mod __rt { use wasmtime_interface_types::Value; pub trait FromVecValue: Sized { - fn from(list: Vec) -> Result; + fn from(list: Vec) -> anyhow::Result; } macro_rules! tuple { ($(($($a:ident),*),)*) => ($( impl<$($a: TryFrom),*> FromVecValue for ($($a,)*) - where $(failure::Error: From<$a::Error>,)* + where $(anyhow::Error: From<$a::Error>,)* { #[allow(non_snake_case)] - fn from(list: Vec) -> Result { + fn from(list: Vec) -> anyhow::Result { let mut iter = list.into_iter(); $( let $a = iter.next() - .ok_or_else(|| failure::format_err!("not enough values"))? + .ok_or_else(|| anyhow::format_err!("not enough values"))? .try_into()?; )* if iter.next().is_some() { - failure::format_err!("too many return values"); + anyhow::bail!("too many return values"); } Ok(($($a,)*)) } diff --git a/src/bin/wasm2obj.rs b/src/bin/wasm2obj.rs index 29baa84485..30747ee9d6 100644 --- a/src/bin/wasm2obj.rs +++ b/src/bin/wasm2obj.rs @@ -203,12 +203,7 @@ fn handle_module( let isa_builder = match *target { Some(ref target) => { let target = Triple::from_str(&target).map_err(|_| "could not parse --target")?; - isa::lookup(target).map_err(|err| match err { - isa::LookupError::SupportDisabled => { - "support for architecture disabled at compile time" - } - isa::LookupError::Unsupported => "unsupported architecture", - })? + isa::lookup(target).map_err(|err| format!("{:?}", err))? } None => cranelift_native::builder().unwrap_or_else(|_| { panic!("host machine is not a supported target"); diff --git a/src/bin/wasmtime.rs b/src/bin/wasmtime.rs index f17a919da7..0b26977712 100644 --- a/src/bin/wasmtime.rs +++ b/src/bin/wasmtime.rs @@ -30,10 +30,10 @@ ) )] +use anyhow::{bail, Context as _, Result}; use cranelift_codegen::settings; use cranelift_codegen::settings::Configurable; use docopt::Docopt; -use failure::{bail, Error, ResultExt}; use pretty_env_logger; use serde::Deserialize; use std::collections::HashMap; @@ -185,19 +185,7 @@ fn compute_environ(flag_env: &[String]) -> Vec<(String, String)> { result } -fn main() { - let err = match rmain() { - Ok(()) => return, - Err(e) => e, - }; - eprintln!("error: {}", err); - for cause in err.iter_causes() { - eprintln!(" caused by: {}", cause); - } - exit(1); -} - -fn rmain() -> Result<(), Error> { +fn main() -> Result<()> { let version = env!("CARGO_PKG_VERSION"); let args: Args = Docopt::new(USAGE) .and_then(|d| { @@ -324,13 +312,13 @@ fn rmain() -> Result<(), Error> { for filename in &args.flag_preload { let path = Path::new(&filename); instantiate_module(store.clone(), &module_registry, path) - .with_context(|_| format!("failed to process preload at `{}`", path.display()))?; + .with_context(|| format!("failed to process preload at `{}`", path.display()))?; } // Load the main wasm module. let path = Path::new(&args.arg_file); handle_module(store, &module_registry, &args, path) - .with_context(|_| format!("failed to process main module `{}`", path.display()))?; + .with_context(|| format!("failed to process main module `{}`", path.display()))?; Ok(()) } @@ -338,7 +326,7 @@ fn instantiate_module( store: HostRef, module_registry: &HashMap)>, path: &Path, -) -> Result<(HostRef, HostRef, Vec), Error> { +) -> Result<(HostRef, HostRef, Vec)> { // Read the wasm module binary either as `*.wat` or a raw binary let data = wat::parse_file(path.to_path_buf())?; @@ -378,7 +366,7 @@ fn handle_module( module_registry: &HashMap)>, args: &Args, path: &Path, -) -> Result<(), Error> { +) -> Result<()> { let (instance, _module, data) = instantiate_module(store.clone(), module_registry, path)?; // If a function to invoke was given, invoke it. @@ -396,7 +384,7 @@ fn invoke_export( data: &ModuleData, name: &str, args: &Args, -) -> Result<(), Error> { +) -> Result<()> { use wasm_webidl_bindings::ast; use wasmtime_interface_types::Value; @@ -445,7 +433,7 @@ fn invoke_export( let mut context = store.borrow().engine().borrow().create_wasmtime_context(); let results = data .invoke(&mut context, &mut handle, name, &values) - .with_context(|_| format!("failed to invoke `{}`", name))?; + .with_context(|| format!("failed to invoke `{}`", name))?; if results.len() > 0 { eprintln!( "warning: using `--render` with a function that returns values \ diff --git a/wasmtime-api/Cargo.toml b/wasmtime-api/Cargo.toml index d02574145c..b48e27ae5c 100644 --- a/wasmtime-api/Cargo.toml +++ b/wasmtime-api/Cargo.toml @@ -12,18 +12,18 @@ name = "wasmtime_api" crate-type = ["lib", "staticlib", "cdylib"] [dependencies] -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-native = "0.46.1" -cranelift-entity = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } -cranelift-frontend = "0.46.1" +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-native = { version = "0.47" } +cranelift-entity = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } +cranelift-frontend = { version = "0.47" } wasmtime-runtime = { path="../wasmtime-runtime" } wasmtime-environ = { path="../wasmtime-environ" } wasmtime-jit = { path="../wasmtime-jit" } wasmparser = { version = "0.39.2", default-features = false } -failure = { version = "0.1.3", default-features = false } -failure_derive = { version = "0.1.3", default-features = false } target-lexicon = { version = "0.8.1", default-features = false } +anyhow = "1.0.19" +thiserror = "1.0.4" region = "2.0.0" hashbrown = { version = "0.6.0", optional = true } diff --git a/wasmtime-api/examples/gcd.rs b/wasmtime-api/examples/gcd.rs index 07176f527a..0e71279496 100644 --- a/wasmtime-api/examples/gcd.rs +++ b/wasmtime-api/examples/gcd.rs @@ -1,11 +1,11 @@ //! Example of instantiating of the WebAssembly module and //! invoking its exported function. -use failure::{format_err, Error}; +use anyhow::{format_err, Result}; use std::fs::read; use wasmtime_api::*; -fn main() -> Result<(), Error> { +fn main() -> Result<()> { let wasm = read("examples/gcd.wasm")?; // Instantiate engine and store. diff --git a/wasmtime-api/examples/hello.rs b/wasmtime-api/examples/hello.rs index 819c3f27e7..1c1bc8ba8a 100644 --- a/wasmtime-api/examples/hello.rs +++ b/wasmtime-api/examples/hello.rs @@ -3,8 +3,8 @@ extern crate alloc; use alloc::rc::Rc; +use anyhow::{ensure, format_err, Context as _, Result}; use core::cell::Ref; -use failure::{bail, format_err, Error}; use std::fs::read; use wasmtime_api::*; @@ -18,7 +18,7 @@ impl Callable for HelloCallback { } } -fn main() -> Result<(), Error> { +fn main() -> Result<()> { // Initialize. println!("Initializing..."); let engine = HostRef::new(Engine::new(Config::default())); @@ -30,10 +30,8 @@ fn main() -> Result<(), Error> { // Compile. println!("Compiling module..."); - let module = HostRef::new( - Module::new(store.clone(), &binary) - .map_err(|_| format_err!("> Error compiling module!"))?, - ); + let module = + HostRef::new(Module::new(store.clone(), &binary).context("> Error compiling module!")?); // Create external print functions. println!("Creating callback..."); @@ -45,24 +43,21 @@ fn main() -> Result<(), Error> { let imports = vec![hello_func.into()]; let instance = HostRef::new( Instance::new(store.clone(), module, imports.as_slice()) - .map_err(|_| format_err!("> Error instantiating module!"))?, + .context("> Error instantiating module!")?, ); // Extract export. println!("Extracting export..."); let exports = Ref::map(instance.borrow(), |instance| instance.exports()); - if exports.len() == 0 { - bail!("> Error accessing exports!"); - } - let run_func = exports[0] - .func() - .ok_or_else(|| format_err!("> Error accessing exports!"))?; + ensure!(!exports.is_empty(), "> Error accessing exports!"); + let run_func = exports[0].func().context("> Error accessing exports!")?; // Call. println!("Calling export..."); - if let Err(_) = run_func.borrow().call(&[]) { - bail!("> Error calling function!"); - } + run_func + .borrow() + .call(&[]) + .map_err(|e| format_err!("> Error calling function: {:?}", e))?; // Shut down. println!("Shutting down..."); diff --git a/wasmtime-api/examples/memory.rs b/wasmtime-api/examples/memory.rs index ad184d8ec1..7d9be3099c 100644 --- a/wasmtime-api/examples/memory.rs +++ b/wasmtime-api/examples/memory.rs @@ -1,7 +1,7 @@ //! Translation of the memory example +use anyhow::{bail, ensure, Context as _, Error}; use core::cell::Ref; -use failure::{bail, format_err, Error}; use std::fs::read; use wasmtime_api::*; @@ -11,7 +11,7 @@ fn get_export_memory(exports: &[Extern], i: usize) -> Result, Er } Ok(exports[i] .memory() - .ok_or_else(|| format_err!("> Error accessing memory export {}!", i))? + .with_context(|| format!("> Error accessing memory export {}!", i))? .clone()) } @@ -21,7 +21,7 @@ fn get_export_func(exports: &[Extern], i: usize) -> Result, Error> } Ok(exports[i] .func() - .ok_or_else(|| format_err!("> Error accessing function export {}!", i))? + .with_context(|| format!("> Error accessing function export {}!", i))? .clone()) } @@ -73,24 +73,19 @@ fn main() -> Result<(), Error> { // Compile. println!("Compiling module..."); - let module = HostRef::new( - Module::new(store.clone(), &binary) - .map_err(|_| format_err!("> Error compiling module!"))?, - ); + let module = + HostRef::new(Module::new(store.clone(), &binary).context("> Error compiling module!")?); // Instantiate. println!("Instantiating module..."); let instance = HostRef::new( - Instance::new(store.clone(), module, &[]) - .map_err(|_| format_err!("> Error instantiating module!"))?, + Instance::new(store.clone(), module, &[]).context("> Error instantiating module!")?, ); // Extract export. println!("Extracting export..."); let exports = Ref::map(instance.borrow(), |instance| instance.exports()); - if exports.len() == 0 { - bail!("> Error accessing exports!"); - } + ensure!(!exports.is_empty(), "> Error accessing exports!"); let memory = get_export_memory(&exports, 0)?; let size_func = get_export_func(&exports, 1)?; let load_func = get_export_func(&exports, 2)?; diff --git a/wasmtime-api/examples/multi.rs b/wasmtime-api/examples/multi.rs index aac95deca6..4bda0b48c3 100644 --- a/wasmtime-api/examples/multi.rs +++ b/wasmtime-api/examples/multi.rs @@ -3,8 +3,8 @@ extern crate alloc; use alloc::rc::Rc; +use anyhow::{ensure, format_err, Context as _, Result}; use core::cell::Ref; -use failure::{bail, format_err, Error}; use std::fs::read; use wasmtime_api::*; @@ -21,7 +21,7 @@ impl Callable for Callback { } } -fn main() -> Result<(), Error> { +fn main() -> Result<()> { // Initialize. println!("Initializing..."); let engine = HostRef::new(Engine::new(Config::default())); @@ -33,10 +33,8 @@ fn main() -> Result<(), Error> { // Compile. println!("Compiling module..."); - let module = HostRef::new( - Module::new(store.clone(), &binary) - .map_err(|_| format_err!("> Error compiling module!"))?, - ); + let module = + HostRef::new(Module::new(store.clone(), &binary).context("Error compiling module!")?); // Create external print functions. println!("Creating callback..."); @@ -51,28 +49,23 @@ fn main() -> Result<(), Error> { let imports = vec![callback_func.into()]; let instance = HostRef::new( Instance::new(store.clone(), module, imports.as_slice()) - .map_err(|_| format_err!("> Error instantiating module!"))?, + .context("Error instantiating module!")?, ); // Extract export. println!("Extracting export..."); let exports = Ref::map(instance.borrow(), |instance| instance.exports()); - if exports.len() == 0 { - bail!("> Error accessing exports!"); - } - let run_func = exports[0] - .func() - .ok_or_else(|| format_err!("> Error accessing 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); - if let Err(_) = results { - bail!("> Error calling function!"); - } + let results = run_func + .borrow() + .call(&args) + .map_err(|e| format_err!("> Error calling function: {:?}", e))?; - let results = results.unwrap(); println!("Printing result..."); println!("> {} {}", results[0].i64(), results[1].i32()); diff --git a/wasmtime-api/src/instance.rs b/wasmtime-api/src/instance.rs index 5bd8cb3e69..d8df3f8b89 100644 --- a/wasmtime-api/src/instance.rs +++ b/wasmtime-api/src/instance.rs @@ -9,8 +9,8 @@ use alloc::boxed::Box; use alloc::rc::Rc; use alloc::string::{String, ToString}; use alloc::vec::Vec; +use anyhow::Result; use core::cell::RefCell; -use failure::Error; use wasmtime_jit::{instantiate, Resolver}; use wasmtime_runtime::{Export, InstanceHandle}; @@ -34,7 +34,7 @@ pub fn instantiate_in_context( imports: Vec<(String, String, Extern)>, mut context: Context, exports: Rc>>>, -) -> Result<(InstanceHandle, HashSet), Error> { +) -> Result<(InstanceHandle, HashSet)> { let mut contexts = HashSet::new(); let debug_info = context.debug_info(); let mut resolver = SimpleResolver { imports }; @@ -64,7 +64,7 @@ impl Instance { store: HostRef, module: HostRef, externs: &[Extern], - ) -> Result { + ) -> Result { let context = store.borrow_mut().context().clone(); let exports = store.borrow_mut().global_exports().clone(); let imports = module @@ -105,7 +105,7 @@ impl Instance { pub fn from_handle( store: HostRef, instance_handle: InstanceHandle, - ) -> Result<(Instance, HashMap), Error> { + ) -> Result<(Instance, HashMap)> { let contexts = HashSet::new(); let mut exports = Vec::new(); diff --git a/wasmtime-api/src/lib.rs b/wasmtime-api/src/lib.rs index 71a3c82077..46866ea65d 100644 --- a/wasmtime-api/src/lib.rs +++ b/wasmtime-api/src/lib.rs @@ -17,8 +17,6 @@ mod values; #[cfg(feature = "wasm-c-api")] pub mod wasm; -#[macro_use] -extern crate failure_derive; #[macro_use] extern crate alloc; diff --git a/wasmtime-api/src/module.rs b/wasmtime-api/src/module.rs index 9d20d1dc8f..b70183c00b 100644 --- a/wasmtime-api/src/module.rs +++ b/wasmtime-api/src/module.rs @@ -7,7 +7,7 @@ use crate::types::{ use alloc::boxed::Box; use alloc::string::String; use alloc::vec::Vec; -use failure::Error; +use anyhow::Result; use wasmparser::{validate, ExternalKind, ImportSectionEntryType, ModuleReader, SectionCode}; @@ -61,9 +61,7 @@ fn into_table_type(tt: wasmparser::TableType) -> TableType { TableType::new(ty, limits) } -fn read_imports_and_exports( - binary: &[u8], -) -> Result<(Box<[ImportType]>, Box<[ExportType]>), Error> { +fn read_imports_and_exports(binary: &[u8]) -> Result<(Box<[ImportType]>, Box<[ExportType]>)> { let mut reader = ModuleReader::new(binary)?; let mut imports = Vec::new(); let mut exports = Vec::new(); @@ -184,7 +182,7 @@ pub struct Module { } impl Module { - pub fn new(store: HostRef, binary: &[u8]) -> Result { + pub fn new(store: HostRef, binary: &[u8]) -> Result { let (imports, exports) = read_imports_and_exports(binary)?; Ok(Module { store, diff --git a/wasmtime-api/src/trampoline/create_handle.rs b/wasmtime-api/src/trampoline/create_handle.rs index 20649c10d0..6ea68c6078 100644 --- a/wasmtime-api/src/trampoline/create_handle.rs +++ b/wasmtime-api/src/trampoline/create_handle.rs @@ -1,9 +1,9 @@ //! Support for a calling of an imported function. +use anyhow::Result; use cranelift_entity::PrimaryMap; use cranelift_wasm::DefinedFuncIndex; //use target_lexicon::HOST; -use failure::Error; use wasmtime_environ::Module; use wasmtime_runtime::{Imports, InstanceHandle, VMFunctionBody}; @@ -22,7 +22,7 @@ pub(crate) fn create_handle( signature_registry: Option>, finished_functions: PrimaryMap, state: Box, -) -> Result { +) -> Result { let global_exports: Rc>>> = Rc::new(RefCell::new(HashMap::new())); diff --git a/wasmtime-api/src/trampoline/func.rs b/wasmtime-api/src/trampoline/func.rs index cc6668409f..1ed333f936 100644 --- a/wasmtime-api/src/trampoline/func.rs +++ b/wasmtime-api/src/trampoline/func.rs @@ -1,6 +1,7 @@ //! Support for a calling of an imported function. use crate::r#ref::HostRef; +use anyhow::Result; use cranelift_codegen::ir::types; use cranelift_codegen::ir::{InstBuilder, StackSlotData, StackSlotKind, TrapCode}; use cranelift_codegen::Context; @@ -9,7 +10,6 @@ use cranelift_entity::{EntityRef, PrimaryMap}; use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use cranelift_wasm::{DefinedFuncIndex, FuncIndex}; //use target_lexicon::HOST; -use failure::Error; use wasmtime_environ::{Export, Module}; use wasmtime_jit::CodeMemory; use wasmtime_runtime::{InstanceHandle, VMContext, VMFunctionBody}; @@ -195,7 +195,7 @@ pub fn create_handle_with_function( ft: &FuncType, func: &Rc, store: &HostRef, -) -> Result { +) -> Result { let sig = ft.get_cranelift_signature().clone(); let isa = { diff --git a/wasmtime-api/src/trampoline/global.rs b/wasmtime-api/src/trampoline/global.rs index 1e38c2fa3c..cb480da969 100644 --- a/wasmtime-api/src/trampoline/global.rs +++ b/wasmtime-api/src/trampoline/global.rs @@ -1,6 +1,6 @@ use alloc::boxed::Box; +use anyhow::Result; use cranelift_entity::PrimaryMap; -use failure::Error; use wasmtime_environ::Module; use wasmtime_runtime::{InstanceHandle, VMGlobalDefinition}; @@ -13,10 +13,7 @@ pub struct GlobalState { handle: InstanceHandle, } -pub fn create_global( - gt: &GlobalType, - val: Val, -) -> Result<(wasmtime_runtime::Export, GlobalState), Error> { +pub fn create_global(gt: &GlobalType, val: Val) -> Result<(wasmtime_runtime::Export, GlobalState)> { let mut definition = Box::new(VMGlobalDefinition::new()); unsafe { match val { diff --git a/wasmtime-api/src/trampoline/memory.rs b/wasmtime-api/src/trampoline/memory.rs index 21c5c3e9dc..612e57bd0b 100644 --- a/wasmtime-api/src/trampoline/memory.rs +++ b/wasmtime-api/src/trampoline/memory.rs @@ -1,7 +1,7 @@ use alloc::boxed::Box; use alloc::string::ToString; +use anyhow::Result; use cranelift_entity::PrimaryMap; -use failure::Error; use wasmtime_environ::Module; use wasmtime_runtime::InstanceHandle; @@ -10,7 +10,7 @@ use crate::MemoryType; #[allow(dead_code)] -pub fn create_handle_with_memory(memory: &MemoryType) -> Result { +pub fn create_handle_with_memory(memory: &MemoryType) -> Result { let mut module = Module::new(); let memory = cranelift_wasm::Memory { diff --git a/wasmtime-api/src/trampoline/mod.rs b/wasmtime-api/src/trampoline/mod.rs index 7d34d4d823..bac15cdc9f 100644 --- a/wasmtime-api/src/trampoline/mod.rs +++ b/wasmtime-api/src/trampoline/mod.rs @@ -8,7 +8,7 @@ mod table; use crate::r#ref::HostRef; use alloc::rc::Rc; -use failure::Error; +use anyhow::Result; use self::func::create_handle_with_function; use self::global::create_global; @@ -22,7 +22,7 @@ pub fn generate_func_export( ft: &FuncType, func: &Rc, store: &HostRef, -) -> Result<(wasmtime_runtime::InstanceHandle, wasmtime_runtime::Export), Error> { +) -> Result<(wasmtime_runtime::InstanceHandle, wasmtime_runtime::Export)> { let mut instance = create_handle_with_function(ft, func, store)?; let export = instance.lookup("trampoline").expect("trampoline export"); Ok((instance, export)) @@ -31,13 +31,13 @@ pub fn generate_func_export( pub fn generate_global_export( gt: &GlobalType, val: Val, -) -> Result<(wasmtime_runtime::Export, GlobalState), Error> { +) -> Result<(wasmtime_runtime::Export, GlobalState)> { create_global(gt, val) } pub fn generate_memory_export( m: &MemoryType, -) -> Result<(wasmtime_runtime::InstanceHandle, wasmtime_runtime::Export), Error> { +) -> Result<(wasmtime_runtime::InstanceHandle, wasmtime_runtime::Export)> { let mut instance = create_handle_with_memory(m)?; let export = instance.lookup("memory").expect("memory export"); Ok((instance, export)) @@ -45,7 +45,7 @@ pub fn generate_memory_export( pub fn generate_table_export( t: &TableType, -) -> Result<(wasmtime_runtime::InstanceHandle, wasmtime_runtime::Export), Error> { +) -> Result<(wasmtime_runtime::InstanceHandle, wasmtime_runtime::Export)> { let mut instance = create_handle_with_table(t)?; let export = instance.lookup("table").expect("table export"); Ok((instance, export)) diff --git a/wasmtime-api/src/trampoline/table.rs b/wasmtime-api/src/trampoline/table.rs index 46ea6a21bd..6ff9000ee0 100644 --- a/wasmtime-api/src/trampoline/table.rs +++ b/wasmtime-api/src/trampoline/table.rs @@ -1,15 +1,15 @@ use alloc::boxed::Box; use alloc::string::ToString; +use anyhow::Result; use cranelift_entity::PrimaryMap; use cranelift_wasm::TableElementType; -use failure::Error; use wasmtime_environ::Module; use wasmtime_runtime::InstanceHandle; use super::create_handle::create_handle; use crate::{TableType, ValType}; -pub fn create_handle_with_table(table: &TableType) -> Result { +pub fn create_handle_with_table(table: &TableType) -> Result { let mut module = Module::new(); let table = cranelift_wasm::Table { diff --git a/wasmtime-api/src/trap.rs b/wasmtime-api/src/trap.rs index 1d0b81b2d3..4010a1eef9 100644 --- a/wasmtime-api/src/trap.rs +++ b/wasmtime-api/src/trap.rs @@ -1,7 +1,8 @@ use alloc::string::{String, ToString}; +use thiserror::Error; -#[derive(Fail, Debug)] -#[fail(display = "Wasm trap")] +#[derive(Error, Debug)] +#[error("Wasm trap: {message}")] pub struct Trap { message: String, } diff --git a/wasmtime-api/src/wasm.rs b/wasmtime-api/src/wasm.rs index e18125169f..e9205b121f 100644 --- a/wasmtime-api/src/wasm.rs +++ b/wasmtime-api/src/wasm.rs @@ -682,7 +682,7 @@ pub unsafe extern "C" fn wasm_instance_new( } Err(_) => { if !result.is_null() { - // TODO Unwrap trap from failure::Error + // TODO Unwrap trap from error let trap = Box::new(wasm_trap_t { trap: HostRef::new(Trap::new("trap during instantiation".to_string())), }); diff --git a/wasmtime-debug/Cargo.toml b/wasmtime-debug/Cargo.toml index 33f0e93050..a87a984ce2 100644 --- a/wasmtime-debug/Cargo.toml +++ b/wasmtime-debug/Cargo.toml @@ -14,15 +14,15 @@ edition = "2018" [dependencies] gimli = "0.19.0" wasmparser = "0.39.2" -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-entity = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-entity = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } faerie = "0.11.0" wasmtime-environ = { path = "../wasmtime-environ", default-features = false } target-lexicon = { version = "0.8.1", default-features = false } failure = { version = "0.1.3", default-features = false } -failure_derive = { version = "0.1.3", default-features = false } hashbrown = { version = "0.6.0", optional = true } +thiserror = "1.0.4" [features] default = ["std"] diff --git a/wasmtime-debug/src/lib.rs b/wasmtime-debug/src/lib.rs index 9519543743..9f0d43e8a9 100644 --- a/wasmtime-debug/src/lib.rs +++ b/wasmtime-debug/src/lib.rs @@ -24,8 +24,6 @@ mod read_debuginfo; mod transform; mod write_debuginfo; -#[macro_use] -extern crate failure_derive; extern crate alloc; struct FunctionRelocResolver {} diff --git a/wasmtime-debug/src/transform/mod.rs b/wasmtime-debug/src/transform/mod.rs index 4633b61ac9..b27ff59939 100644 --- a/wasmtime-debug/src/transform/mod.rs +++ b/wasmtime-debug/src/transform/mod.rs @@ -4,6 +4,7 @@ use crate::HashSet; use cranelift_codegen::isa::TargetFrontendConfig; use failure::Error; use simulate::generate_simulated_dwarf; +use thiserror::Error; use wasmtime_environ::{ModuleAddressMap, ModuleVmctxInfo, ValueLabelsRanges}; use gimli; @@ -31,8 +32,8 @@ pub(crate) trait Reader: gimli::Reader {} impl<'input, Endian> Reader for gimli::EndianSlice<'input, Endian> where Endian: gimli::Endianity {} -#[derive(Fail, Debug)] -#[fail(display = "Debug info transform error: {}", _0)] +#[derive(Error, Debug)] +#[error("Debug info transform error: {0}")] pub struct TransformError(&'static str); pub(crate) struct DebugInputContext<'a, R> diff --git a/wasmtime-environ/Cargo.toml b/wasmtime-environ/Cargo.toml index 36029de652..1389bd6242 100644 --- a/wasmtime-environ/Cargo.toml +++ b/wasmtime-environ/Cargo.toml @@ -12,14 +12,13 @@ readme = "README.md" edition = "2018" [dependencies] -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-entity = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-entity = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } lightbeam = { path = "../lightbeam", optional = true } -failure = { version = "0.1.3", default-features = false } -failure_derive = { version = "0.1.3", default-features = false } indexmap = "1.0.2" rayon = "1.1" +thiserror = "1.0.4" directories = "2.0.1" sha2 = "0.8.0" base64 = "0.10.1" @@ -44,7 +43,7 @@ tempfile = "3" target-lexicon = { version = "0.8.1", default-features = false } pretty_env_logger = "0.3.0" rand = { version = "0.7.0", features = ["small_rng"] } -cranelift-codegen = { version = "0.46.1", features = ["enable-serde", "all-arch"] } +cranelift-codegen = { version = "0.47", features = ["enable-serde", "all-arch"] } filetime = "0.2.7" [features] diff --git a/wasmtime-environ/src/compilation.rs b/wasmtime-environ/src/compilation.rs index 226d42d5c7..8be354ba79 100644 --- a/wasmtime-environ/src/compilation.rs +++ b/wasmtime-environ/src/compilation.rs @@ -10,6 +10,7 @@ use cranelift_entity::PrimaryMap; use cranelift_wasm::{DefinedFuncIndex, FuncIndex, ModuleTranslationState, WasmError}; use serde::{Deserialize, Serialize}; use std::ops::Range; +use thiserror::Error; /// Compiled machine code: body and jump table offsets. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] @@ -144,18 +145,18 @@ pub struct TrapInformation { pub type Traps = PrimaryMap>; /// An error while compiling WebAssembly to machine code. -#[derive(Fail, Debug)] +#[derive(Error, Debug)] pub enum CompileError { /// A wasm translation error occured. - #[fail(display = "WebAssembly translation error: {}", _0)] - Wasm(WasmError), + #[error("WebAssembly translation error: {0}")] + Wasm(#[from] WasmError), /// A compilation error occured. - #[fail(display = "Compilation error: {}", _0)] - Codegen(CodegenError), + #[error("Compilation error: {0}")] + Codegen(#[from] CodegenError), /// A compilation error occured. - #[fail(display = "Debug info is not supported with this configuration")] + #[error("Debug info is not supported with this configuration")] DebugInfoNotSupported, } diff --git a/wasmtime-environ/src/cranelift.rs b/wasmtime-environ/src/cranelift.rs index 26be4d8565..02002b0853 100644 --- a/wasmtime-environ/src/cranelift.rs +++ b/wasmtime-environ/src/cranelift.rs @@ -226,29 +226,25 @@ impl crate::compilation::Compiler for Cranelift { context.func.collect_debug_info(); } - func_translator - .translate( - module_translation, - input.data, - input.module_offset, - &mut context.func, - &mut FuncEnvironment::new(isa.frontend_config(), module), - ) - .map_err(CompileError::Wasm)?; + func_translator.translate( + module_translation, + input.data, + input.module_offset, + &mut context.func, + &mut FuncEnvironment::new(isa.frontend_config(), module), + )?; let mut code_buf: Vec = Vec::new(); let mut reloc_sink = RelocSink::new(func_index); let mut trap_sink = TrapSink::new(); let mut stackmap_sink = binemit::NullStackmapSink {}; - context - .compile_and_emit( - isa, - &mut code_buf, - &mut reloc_sink, - &mut trap_sink, - &mut stackmap_sink, - ) - .map_err(CompileError::Codegen)?; + context.compile_and_emit( + isa, + &mut code_buf, + &mut reloc_sink, + &mut trap_sink, + &mut stackmap_sink, + )?; let jt_offsets = context.func.jt_offsets.clone(); @@ -260,11 +256,7 @@ impl crate::compilation::Compiler for Cranelift { }; let ranges = if generate_debug_info { - Some( - context - .build_value_labels_ranges(isa) - .map_err(CompileError::Codegen)?, - ) + Some(context.build_value_labels_ranges(isa)?) } else { None }; diff --git a/wasmtime-environ/src/lib.rs b/wasmtime-environ/src/lib.rs index 861d5404d5..c23e97b357 100644 --- a/wasmtime-environ/src/lib.rs +++ b/wasmtime-environ/src/lib.rs @@ -27,9 +27,6 @@ extern crate alloc; -#[macro_use] -extern crate failure_derive; - mod address_map; mod compilation; mod func_environ; diff --git a/wasmtime-interface-types/Cargo.toml b/wasmtime-interface-types/Cargo.toml index 29f432e5dc..c977eb7670 100644 --- a/wasmtime-interface-types/Cargo.toml +++ b/wasmtime-interface-types/Cargo.toml @@ -11,10 +11,10 @@ readme = "README.md" edition = "2018" [dependencies] -cranelift-codegen = { version = "0.46.1", default-features = false } -failure = { version = "0.1", default-features = false } -walrus = "0.12.0" +anyhow = "1.0.19" +cranelift-codegen = { version = "0.47", default-features = false } +walrus = "0.13" wasmparser = { version = "0.39.2", default-features = false } -wasm-webidl-bindings = "0.5.0" +wasm-webidl-bindings = "0.6" wasmtime-jit = { path = '../wasmtime-jit', default-features = false } wasmtime-runtime = { path = '../wasmtime-runtime', default-features = false } diff --git a/wasmtime-interface-types/src/lib.rs b/wasmtime-interface-types/src/lib.rs index e09748c7e0..7db0b3fb21 100644 --- a/wasmtime-interface-types/src/lib.rs +++ b/wasmtime-interface-types/src/lib.rs @@ -13,11 +13,11 @@ extern crate alloc; use alloc::boxed::Box; use alloc::string::ToString; use alloc::vec::Vec; +use anyhow::{bail, format_err, Result}; use core::convert::TryFrom; use core::slice; use core::str; use cranelift_codegen::ir; -use failure::{bail, format_err, Error}; use wasm_webidl_bindings::ast; use wasmtime_jit::{ActionOutcome, Context, RuntimeValue}; use wasmtime_runtime::{Export, InstanceHandle}; @@ -59,7 +59,7 @@ impl ModuleData { /// interface types. /// /// Returns an error if the wasm file is malformed. - pub fn new(wasm: &[u8]) -> Result { + pub fn new(wasm: &[u8]) -> Result { // Perform a fast search through the module for the right custom // section. Actually parsing out the interface types data is currently a // pretty expensive operation so we want to only do that if we actually @@ -109,7 +109,7 @@ impl ModuleData { handle: &mut InstanceHandle, export: &str, args: &[Value], - ) -> Result, Error> { + ) -> Result> { let binding = self.binding_for_export(handle, export)?; let incoming = binding.param_bindings()?; let outgoing = binding.result_bindings()?; @@ -130,7 +130,7 @@ impl ModuleData { &self, instance: &mut InstanceHandle, name: &str, - ) -> Result, Error> { + ) -> Result> { if let Some(binding) = self.interface_binding_for_export(name) { return Ok(binding); } @@ -170,7 +170,7 @@ impl ModuleData { impl ExportBinding<'_> { /// Returns the list of binding expressions used to create the parameters /// for this binding. - pub fn param_bindings(&self) -> Result, Error> { + pub fn param_bindings(&self) -> Result> { match &self.kind { ExportBindingKind::Rich { binding, .. } => Ok(binding.params.bindings.clone()), ExportBindingKind::Raw(sig) => sig @@ -184,7 +184,7 @@ impl ExportBinding<'_> { } /// Returns the list of scalar types used for this binding - pub fn param_types(&self) -> Result, Error> { + pub fn param_types(&self) -> Result> { match &self.kind { ExportBindingKind::Rich { binding, section, .. @@ -217,7 +217,7 @@ impl ExportBinding<'_> { /// Returns the list of binding expressions used to extract the return /// values of this binding. - pub fn result_bindings(&self) -> Result, Error> { + pub fn result_bindings(&self) -> Result> { match &self.kind { ExportBindingKind::Rich { binding, .. } => Ok(binding.result.bindings.clone()), ExportBindingKind::Raw(sig) => sig @@ -230,10 +230,7 @@ impl ExportBinding<'_> { } } -fn default_incoming( - idx: usize, - param: &ir::AbiParam, -) -> Result { +fn default_incoming(idx: usize, param: &ir::AbiParam) -> Result { let get = ast::IncomingBindingExpressionGet { idx: idx as u32 }; let ty = if param.value_type == ir::types::I32 { walrus::ValType::I32 @@ -253,10 +250,7 @@ fn default_incoming( .into()) } -fn default_outgoing( - idx: usize, - param: &ir::AbiParam, -) -> Result { +fn default_outgoing(idx: usize, param: &ir::AbiParam) -> Result { let ty = abi2ast(param)?; Ok(ast::OutgoingBindingExpressionAs { ty: ty.into(), @@ -265,7 +259,7 @@ fn default_outgoing( .into()) } -fn abi2ast(param: &ir::AbiParam) -> Result { +fn abi2ast(param: &ir::AbiParam) -> Result { Ok(if param.value_type == ir::types::I32 { ast::WebidlScalarType::Long } else if param.value_type == ir::types::I64 { @@ -284,7 +278,7 @@ fn translate_incoming( handle: &mut InstanceHandle, bindings: &[ast::IncomingBindingExpression], args: &[Value], -) -> Result, Error> { +) -> Result> { let get = |expr: &ast::IncomingBindingExpression| match expr { ast::IncomingBindingExpression::Get(g) => args .get(g.idx as usize) @@ -375,7 +369,7 @@ fn translate_outgoing( handle: &mut InstanceHandle, bindings: &[ast::OutgoingBindingExpression], args: &[RuntimeValue], -) -> Result, Error> { +) -> Result> { let mut values = Vec::new(); let raw_memory = || unsafe { diff --git a/wasmtime-interface-types/src/value.rs b/wasmtime-interface-types/src/value.rs index 67fb206182..50778cf1c6 100644 --- a/wasmtime-interface-types/src/value.rs +++ b/wasmtime-interface-types/src/value.rs @@ -24,12 +24,12 @@ macro_rules! from { } impl TryFrom for $a { - type Error = failure::Error; + type Error = anyhow::Error; fn try_from(val: Value) -> Result<$a, Self::Error> { match val { Value::$b(v) => Ok(v), - v => failure::bail!("cannot convert {:?} to {}", v, stringify!($a)), + v => anyhow::bail!("cannot convert {:?} to {}", v, stringify!($a)), } } } diff --git a/wasmtime-jit/Cargo.toml b/wasmtime-jit/Cargo.toml index 259bb93682..8474a0b3b3 100644 --- a/wasmtime-jit/Cargo.toml +++ b/wasmtime-jit/Cargo.toml @@ -11,16 +11,16 @@ readme = "README.md" edition = "2018" [dependencies] -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-entity = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } -cranelift-frontend = "0.46.1" +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-entity = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } +cranelift-frontend = { version = "0.47" } wasmtime-environ = { path = "../wasmtime-environ", default-features = false } wasmtime-runtime = { path = "../wasmtime-runtime", default-features = false } wasmtime-debug = { path = "../wasmtime-debug", default-features = false } region = "2.0.0" failure = { version = "0.1.3", default-features = false } -failure_derive = { version = "0.1.3", default-features = false } +thiserror = "1.0.4" target-lexicon = { version = "0.8.1", default-features = false } hashbrown = { version = "0.6.0", optional = true } wasmparser = { version = "0.39.2", default-features = false } diff --git a/wasmtime-jit/src/action.rs b/wasmtime-jit/src/action.rs index 6b7da3ba8c..d9ca5f3063 100644 --- a/wasmtime-jit/src/action.rs +++ b/wasmtime-jit/src/action.rs @@ -7,6 +7,7 @@ use alloc::vec::Vec; use core::cmp::max; use core::{fmt, mem, ptr, slice}; use cranelift_codegen::ir; +use thiserror::Error; use wasmtime_runtime::{wasmtime_call_trampoline, Export, InstanceHandle, VMInvokeArgument}; /// A runtime value. @@ -110,22 +111,22 @@ pub enum ActionOutcome { /// An error detected while invoking a wasm function or reading a wasm global. /// Note that at this level, traps are not reported errors, but are rather /// returned through `ActionOutcome`. -#[derive(Fail, Debug)] +#[derive(Error, Debug)] pub enum ActionError { /// An internal implementation error occurred. - #[fail(display = "{}", _0)] - Setup(SetupError), + #[error("{0}")] + Setup(#[from] SetupError), /// No field with the specified name was present. - #[fail(display = "Unknown field: {}", _0)] + #[error("Unknown field: {0}")] Field(String), /// The field was present but was the wrong kind (eg. function, table, global, or memory). - #[fail(display = "Kind error: {}", _0)] + #[error("Kind error: {0}")] Kind(String), /// The field was present but was the wrong type (eg. i32, i64, f32, or f64). - #[fail(display = "Type error: {}", _0)] + #[error("Type error: {0}")] Type(String), } diff --git a/wasmtime-jit/src/context.rs b/wasmtime-jit/src/context.rs index 7c633ea857..267844f523 100644 --- a/wasmtime-jit/src/context.rs +++ b/wasmtime-jit/src/context.rs @@ -8,38 +8,26 @@ use alloc::boxed::Box; use alloc::rc::Rc; use alloc::string::{String, ToString}; use core::cell::RefCell; -use core::{fmt, str}; use cranelift_codegen::isa::TargetIsa; +use thiserror::Error; use wasmparser::{validate, OperatorValidatorConfig, ValidatingParserConfig}; /// Indicates an unknown instance was specified. -#[derive(Fail, Debug)] +#[derive(Error, Debug)] +#[error("no instance {instance_name} present")] pub struct UnknownInstance { instance_name: String, } -impl fmt::Display for UnknownInstance { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "no instance {} present", self.instance_name) - } -} - /// Error message used by `WastContext`. -#[derive(Fail, Debug)] +#[derive(Error, Debug)] pub enum ContextError { /// An unknown instance name was used. - Instance(UnknownInstance), + #[error("{0}")] + Instance(#[from] UnknownInstance), /// An error occured while performing an action. - Action(ActionError), -} - -impl fmt::Display for ContextError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - ContextError::Instance(ref error) => error.fmt(f), - ContextError::Action(ref error) => error.fmt(f), - } - } + #[error("{0}")] + Action(#[from] ActionError), } /// The collection of features configurable during compilation diff --git a/wasmtime-jit/src/instantiate.rs b/wasmtime-jit/src/instantiate.rs index b91931750e..1e41ea9ba8 100644 --- a/wasmtime-jit/src/instantiate.rs +++ b/wasmtime-jit/src/instantiate.rs @@ -16,6 +16,7 @@ use cranelift_entity::{BoxedSlice, PrimaryMap}; use cranelift_wasm::{DefinedFuncIndex, SignatureIndex}; #[cfg(feature = "std")] use std::io::Write; +use thiserror::Error; use wasmtime_debug::read_debuginfo; use wasmtime_environ::{ CompileError, DataInitializer, DataInitializerLocation, Module, ModuleEnvironment, @@ -27,23 +28,23 @@ use wasmtime_runtime::{ /// An error condition while setting up a wasm instance, be it validation, /// compilation, or instantiation. -#[derive(Fail, Debug)] +#[derive(Error, Debug)] pub enum SetupError { /// The module did not pass validation. - #[fail(display = "Validation error: {}", _0)] + #[error("Validation error: {0}")] Validate(String), /// A wasm translation error occured. - #[fail(display = "WebAssembly compilation error: {}", _0)] - Compile(CompileError), + #[error("WebAssembly compilation error: {0}")] + Compile(#[from] CompileError), /// Some runtime resource was unavailable or insufficient, or the start function /// trapped. - #[fail(display = "Instantiation error: {}", _0)] - Instantiate(InstantiationError), + #[error("Instantiation error: {0}")] + Instantiate(#[from] InstantiationError), /// Debug information generation error occured. - #[fail(display = "Debug information error: {}", _0)] + #[error("Debug information error: {0}")] DebugInfo(failure::Error), } diff --git a/wasmtime-jit/src/lib.rs b/wasmtime-jit/src/lib.rs index b55b2916f2..79aafb456f 100644 --- a/wasmtime-jit/src/lib.rs +++ b/wasmtime-jit/src/lib.rs @@ -30,9 +30,6 @@ use hashbrown::{hash_map, HashMap, HashSet}; #[cfg(feature = "std")] use std::collections::{hash_map, HashMap, HashSet}; -#[macro_use] -extern crate failure_derive; - mod action; mod code_memory; mod compiler; diff --git a/wasmtime-obj/Cargo.toml b/wasmtime-obj/Cargo.toml index 77f249c992..6648da1d87 100644 --- a/wasmtime-obj/Cargo.toml +++ b/wasmtime-obj/Cargo.toml @@ -11,8 +11,8 @@ readme = "README.md" edition = "2018" [dependencies] -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-entity = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-entity = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } wasmtime-environ = { path = "../wasmtime-environ" } faerie = "0.11.0" diff --git a/wasmtime-runtime/Cargo.toml b/wasmtime-runtime/Cargo.toml index 975ff77723..5ab893bbab 100644 --- a/wasmtime-runtime/Cargo.toml +++ b/wasmtime-runtime/Cargo.toml @@ -11,19 +11,18 @@ readme = "README.md" edition = "2018" [dependencies] -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-entity = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-entity = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } wasmtime-environ = { path = "../wasmtime-environ", default-features = false } region = "2.0.0" lazy_static = "1.2.0" libc = { version = "0.2.60", default-features = false } memoffset = "0.5.1" -failure = { version = "0.1.3", default-features = false } -failure_derive = { version = "0.1.3", default-features = false } indexmap = "1.0.2" hashbrown = { version = "0.6.0", optional = true } spin = { version = "0.5.2", optional = true } +thiserror = "1.0.4" [target.'cfg(target_os = "windows")'.dependencies] winapi = { version = "0.3.7", features = ["winbase", "memoryapi"] } diff --git a/wasmtime-runtime/src/instance.rs b/wasmtime-runtime/src/instance.rs index 99af6441a0..c205e8a63b 100644 --- a/wasmtime-runtime/src/instance.rs +++ b/wasmtime-runtime/src/instance.rs @@ -33,6 +33,7 @@ use cranelift_wasm::{ GlobalIndex, GlobalInit, MemoryIndex, SignatureIndex, TableIndex, }; use indexmap; +use thiserror::Error; use wasmtime_environ::{DataInitializer, Module, TableElements, VMOffsets}; fn signature_id( @@ -1275,22 +1276,22 @@ fn initialize_globals(instance: &mut Instance) { } /// An link error while instantiating a module. -#[derive(Fail, Debug)] -#[fail(display = "Link error: {}", _0)] +#[derive(Error, Debug)] +#[error("Link error: {0}")] pub struct LinkError(pub String); /// An error while instantiating a module. -#[derive(Fail, Debug)] +#[derive(Error, Debug)] pub enum InstantiationError { /// Insufficient resources available for execution. - #[fail(display = "Insufficient resources: {}", _0)] + #[error("Insufficient resources: {0}")] Resource(String), /// A wasm link error occured. - #[fail(display = "{}", _0)] - Link(LinkError), + #[error("{0}")] + Link(#[from] LinkError), /// A compilation error occured. - #[fail(display = "Trap occurred while invoking start function: {}", _0)] + #[error("Trap occurred while invoking start function: {0}")] StartTrap(String), } diff --git a/wasmtime-runtime/src/lib.rs b/wasmtime-runtime/src/lib.rs index f0e9dc4d56..197ffd8e64 100644 --- a/wasmtime-runtime/src/lib.rs +++ b/wasmtime-runtime/src/lib.rs @@ -27,8 +27,6 @@ extern crate lazy_static; #[macro_use] extern crate memoffset; -#[macro_use] -extern crate failure_derive; extern crate alloc; mod export; diff --git a/wasmtime-wasi-c/Cargo.toml b/wasmtime-wasi-c/Cargo.toml index c68ea132f2..32c199c3f7 100644 --- a/wasmtime-wasi-c/Cargo.toml +++ b/wasmtime-wasi-c/Cargo.toml @@ -13,9 +13,9 @@ edition = "2018" wasmtime-runtime = { path = "../wasmtime-runtime" } wasmtime-environ = { path = "../wasmtime-environ" } wasmtime-jit = { path = "../wasmtime-jit" } -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-entity = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-entity = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } target-lexicon = "0.8.1" log = { version = "0.4.8", default-features = false } libc = "0.2.60" diff --git a/wasmtime-wasi/Cargo.toml b/wasmtime-wasi/Cargo.toml index ab8db29640..08b9792130 100644 --- a/wasmtime-wasi/Cargo.toml +++ b/wasmtime-wasi/Cargo.toml @@ -14,9 +14,9 @@ wasmtime-runtime = { path = "../wasmtime-runtime" } wasmtime-environ = { path = "../wasmtime-environ" } wasmtime-jit = { path = "../wasmtime-jit" } wasi-common = { git = "https://github.com/CraneStation/wasi-common", rev = "37ce4ba"} -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-entity = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-entity = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } target-lexicon = "0.8.1" log = { version = "0.4.8", default-features = false } diff --git a/wasmtime-wast/Cargo.toml b/wasmtime-wast/Cargo.toml index dc4bbaa692..abd423b030 100644 --- a/wasmtime-wast/Cargo.toml +++ b/wasmtime-wast/Cargo.toml @@ -11,15 +11,15 @@ readme = "README.md" edition = "2018" [dependencies] -cranelift-codegen = { version = "0.46.1", features = ["enable-serde"] } -cranelift-entity = { version = "0.46.1", features = ["enable-serde"] } -cranelift-wasm = { version = "0.46.1", features = ["enable-serde"] } +cranelift-codegen = { version = "0.47", features = ["enable-serde"] } +cranelift-entity = { version = "0.47", features = ["enable-serde"] } +cranelift-wasm = { version = "0.47", features = ["enable-serde"] } wasmtime-jit = { path = "../wasmtime-jit" } wasmtime-runtime = { path = "../wasmtime-runtime" } wasmtime-environ = { path = "../wasmtime-environ" } wast = "3.0.0" +anyhow = "1.0.19" target-lexicon = "0.8.1" -failure = { version = "0.1.3", default-features = false } [badges] maintenance = { status = "experimental" } diff --git a/wasmtime-wast/src/wast.rs b/wasmtime-wast/src/wast.rs index fa25d5249d..2025101285 100644 --- a/wasmtime-wast/src/wast.rs +++ b/wasmtime-wast/src/wast.rs @@ -1,5 +1,5 @@ use crate::spectest::instantiate_spectest; -use failure::{bail, Error, ResultExt}; +use anyhow::{bail, Context as _, Result}; use std::path::Path; use std::str; use wasmtime_jit::{ @@ -51,7 +51,7 @@ impl WastContext { } } - fn get_instance(&mut self, instance_name: Option<&str>) -> Result<&mut InstanceHandle, Error> { + fn get_instance(&mut self, instance_name: Option<&str>) -> Result<&mut InstanceHandle> { let instance = if let Some(instance_name) = instance_name { self.context .get_instance(instance_name) @@ -59,21 +59,21 @@ impl WastContext { } else { self.current .as_mut() - .ok_or_else(|| failure::format_err!("no current instance"))? + .ok_or_else(|| anyhow::format_err!("no current instance"))? }; Ok(instance) } /// Register "spectest" which is used by the spec testsuite. - pub fn register_spectest(&mut self) -> Result<(), Error> { + pub fn register_spectest(&mut self) -> Result<()> { let instance = instantiate_spectest()?; self.context.name_instance("spectest".to_owned(), instance); Ok(()) } /// Perform the action portion of a command. - fn perform_execute(&mut self, exec: wast::WastExecute<'_>) -> Result { + fn perform_execute(&mut self, exec: wast::WastExecute<'_>) -> Result { match exec { wast::WastExecute::Invoke(invoke) => self.perform_invoke(invoke), wast::WastExecute::Module(mut module) => { @@ -91,12 +91,12 @@ impl WastContext { } } - fn perform_invoke(&mut self, exec: wast::WastInvoke<'_>) -> Result { + fn perform_invoke(&mut self, exec: wast::WastInvoke<'_>) -> Result { self.invoke(exec.module.map(|i| i.name()), exec.name, &exec.args) } /// Define a module and register it. - fn module(&mut self, instance_name: Option<&str>, module: &[u8]) -> Result<(), Error> { + fn module(&mut self, instance_name: Option<&str>, module: &[u8]) -> Result<()> { let index = self .context .instantiate_module(instance_name.map(|s| s.to_string()), module)?; @@ -105,7 +105,7 @@ impl WastContext { } /// Register an instance to make it available for performing actions. - fn register(&mut self, name: Option<&str>, as_name: &str) -> Result<(), Error> { + fn register(&mut self, name: Option<&str>, as_name: &str) -> Result<()> { let instance = self.get_instance(name)?.clone(); self.context.name_instance(as_name.to_string(), instance); Ok(()) @@ -117,30 +117,30 @@ impl WastContext { instance_name: Option<&str>, field: &str, args: &[wast::Expression], - ) -> Result { + ) -> Result { let value_args = args.iter().map(runtime_value).collect::>(); let mut instance = self.get_instance(instance_name)?.clone(); let result = self .context .invoke(&mut instance, field, &value_args) - .with_context(|_| format!("failed to invoke `{}`", field))?; + .with_context(|| format!("failed to invoke `{}`", field))?; Ok(result) } /// Get the value of an exported global from an instance. - fn get(&mut self, instance_name: Option<&str>, field: &str) -> Result { + fn get(&mut self, instance_name: Option<&str>, field: &str) -> Result { let instance = self .get_instance(instance_name.as_ref().map(|x| &**x))? .clone(); let result = self .context .get(&instance, field) - .with_context(|_| format!("failed to get field `{}`", field))?; + .with_context(|| format!("failed to get field `{}`", field))?; Ok(result) } /// Run a wast script from a byte buffer. - pub fn run_buffer(&mut self, filename: &str, wast: &[u8]) -> Result<(), Error> { + pub fn run_buffer(&mut self, filename: &str, wast: &[u8]) -> Result<()> { use wast::WastDirective::*; let wast = str::from_utf8(wast)?; @@ -163,21 +163,21 @@ impl WastContext { Module(mut module) => { let binary = module.encode().map_err(adjust_wast)?; self.module(module.name.map(|s| s.name()), &binary) - .with_context(|_| context(module.span))?; + .with_context(|| context(module.span))?; } Register { span, name, module } => { self.register(module.map(|s| s.name()), name) - .with_context(|_| context(span))?; + .with_context(|| context(span))?; } Invoke(i) => { let span = i.span; - self.perform_invoke(i).with_context(|_| context(span))?; + self.perform_invoke(i).with_context(|| context(span))?; } AssertReturn { span, exec, results, - } => match self.perform_execute(exec).with_context(|_| context(span))? { + } => match self.perform_execute(exec).with_context(|| context(span))? { ActionOutcome::Returned { values } => { for (v, e) in values.iter().zip(results.iter().map(runtime_value)) { if *v == e { @@ -194,7 +194,7 @@ impl WastContext { span, exec, message, - } => match self.perform_execute(exec).with_context(|_| context(span))? { + } => match self.perform_execute(exec).with_context(|| context(span))? { ActionOutcome::Returned { values } => { bail!("{}\nexpected trap, got {:?}", context(span), values) } @@ -224,7 +224,7 @@ impl WastContext { span, call, message, - } => match self.perform_invoke(call).with_context(|_| context(span))? { + } => match self.perform_invoke(call).with_context(|| context(span))? { ActionOutcome::Returned { values } => { bail!("{}\nexpected trap, got {:?}", context(span), values) } @@ -243,10 +243,7 @@ impl WastContext { } }, AssertReturnCanonicalNan { span, invoke } => { - match self - .perform_invoke(invoke) - .with_context(|_| context(span))? - { + match self.perform_invoke(invoke).with_context(|| context(span))? { ActionOutcome::Returned { values } => { for v in values.iter() { match v { @@ -275,10 +272,7 @@ impl WastContext { } } AssertReturnArithmeticNan { span, invoke } => { - match self - .perform_invoke(invoke) - .with_context(|_| context(span))? - { + match self.perform_invoke(invoke).with_context(|| context(span))? { ActionOutcome::Returned { values } => { for v in values.iter() { match v { @@ -384,9 +378,9 @@ impl WastContext { } /// Run a wast script from a file. - pub fn run_file(&mut self, path: &Path) -> Result<(), Error> { + pub fn run_file(&mut self, path: &Path) -> Result<()> { let bytes = - std::fs::read(path).with_context(|_| format!("failed to read `{}`", path.display()))?; + std::fs::read(path).with_context(|| format!("failed to read `{}`", path.display()))?; self.run_buffer(path.to_str().unwrap(), &bytes) } }