Skip to content

Commit

Permalink
Switch from failure to anyhow
Browse files Browse the repository at this point in the history
This moves us back to `std::error::Error` compatibility and helps build
times since it doesn't rely on an older version of `syn`
  • Loading branch information
alexcrichton committed Oct 10, 2019
1 parent 102c133 commit 25fce42
Show file tree
Hide file tree
Showing 24 changed files with 70 additions and 82 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Expand Up @@ -23,7 +23,7 @@ path = "benches/benches.rs"
harness = false

[dependencies]
failure = { version = "0.1.5", default-features = false, features = ['std'] }
anyhow = "1.0"
id-arena = "2.2.1"
leb128 = "0.2.4"
log = "0.4.8"
Expand Down
2 changes: 1 addition & 1 deletion crates/fuzz-utils/Cargo.toml
Expand Up @@ -8,7 +8,7 @@ publish = false
[dependencies]
rand = { version = "0.7.0", features = ['small_rng'] }
tempfile = "3.1.0"
failure = "0.1.5"
anyhow = "1.0"
env_logger = "0.7.0"

[dependencies.walrus]
Expand Down
17 changes: 7 additions & 10 deletions crates/fuzz-utils/src/lib.rs
Expand Up @@ -2,7 +2,7 @@

#![deny(missing_docs)]

use failure::ResultExt;
use anyhow::Context;
use rand::{rngs::SmallRng, Rng, SeedableRng};
use std::cmp;
use std::fmt;
Expand All @@ -12,8 +12,8 @@ use std::path::Path;
use std::time;
use walrus_tests_utils::{wasm_interp, wat2wasm};

/// `Ok(T)` or a `Err(failure::Error)`
pub type Result<T> = std::result::Result<T, failure::Error>;
/// `Ok(T)` or a `Err(anyhow::Error)`
pub type Result<T> = std::result::Result<T, anyhow::Error>;

#[derive(Copy, Clone, Debug)]
enum ValType {
Expand Down Expand Up @@ -139,7 +139,7 @@ where
pub fn run_one(&mut self) -> Result<()> {
let wat = self.gen_wat();
self.test_wat(&wat)
.with_context(|_| format!("wat = {}", wat))?;
.with_context(|| format!("wat = {}", wat))?;
Ok(())
}

Expand Down Expand Up @@ -436,12 +436,9 @@ impl TestCaseGenerator for WasmOptTtf {
}
}

/// Print a `failure::Error` with its chain.
pub fn print_err(e: &failure::Error) {
eprintln!("Error:");
for c in e.iter_chain() {
eprintln!(" - {}", c);
}
/// Print a `anyhow::Error` with its chain.
pub fn print_err(e: &anyhow::Error) {
eprintln!("Error: {:?}", e);
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion crates/tests-utils/Cargo.toml
Expand Up @@ -7,4 +7,4 @@ publish = false

[dependencies]
tempfile = "3.1.0"
failure = "0.1.5"
anyhow = "1.0"
26 changes: 10 additions & 16 deletions crates/tests-utils/src/lib.rs
@@ -1,11 +1,11 @@
use failure::ResultExt;
use anyhow::{bail, Context};
use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Once;

pub type Result<T> = std::result::Result<T, failure::Error>;
pub type Result<T> = std::result::Result<T, anyhow::Error>;

pub const FEATURES: &[&str] = &[
"--enable-threads",
Expand Down Expand Up @@ -56,7 +56,7 @@ pub fn wat2wasm(path: &Path, extra_args: &[&str]) -> Result<Vec<u8>> {
let output = cmd.output().context("could not spawn wat2wasm")?;

if !output.status.success() {
failure::bail!(
bail!(
"wat2wasm exited with status {:?}\n\nstderr = '''\n{}\n'''",
output.status,
String::from_utf8_lossy(&output.stderr)
Expand All @@ -82,7 +82,7 @@ pub fn wasm2wat(path: &Path) -> Result<String> {
println!("running: {:?}", cmd);
let output = cmd.output().context("could not run wasm2wat")?;
if !output.status.success() {
failure::bail!(
bail!(
"wasm2wat exited with status {:?}\n\nstderr = '''\n{}\n'''",
output.status,
String::from_utf8_lossy(&output.stderr)
Expand Down Expand Up @@ -111,7 +111,7 @@ pub fn wasm_interp(path: &Path) -> Result<String> {
println!("running: {:?}", cmd);
let output = cmd.output().context("could notrun wasm-interp")?;
if !output.status.success() {
failure::bail!(
bail!(
"wasm-interp exited with status {:?}\n\nstderr = '''\n{}\n'''",
output.status,
String::from_utf8_lossy(&output.stderr)
Expand Down Expand Up @@ -151,7 +151,7 @@ where
println!("running: {:?}", cmd);
let output = cmd.output().context("could not run wasm-opt")?;
if !output.status.success() {
failure::bail!(
bail!(
"wasm-opt exited with status {:?}\n\nstderr = '''\n{}\n'''",
output.status,
String::from_utf8_lossy(&output.stderr)
Expand All @@ -174,17 +174,11 @@ impl TestResult for () {
fn handle(self) {}
}

impl TestResult for std::result::Result<(), failure::Error> {
impl TestResult for Result<()> {
fn handle(self) {
let err = match self {
Ok(()) => return,
Err(e) => e,
};
eprintln!("got an error:");
for c in err.iter_chain() {
eprintln!(" {}", c);
match self {
Ok(()) => {}
Err(e) => panic!("got an error: {:?}", e),
}
eprintln!("{}", err.backtrace());
panic!("test failed");
}
}
2 changes: 1 addition & 1 deletion crates/tests/Cargo.toml
Expand Up @@ -9,7 +9,7 @@ publish = false
walkdir = "2.2.9"

[dev-dependencies]
failure = "0.1.5"
anyhow = "1.0"
walrus = { path = "../.." }
walrus-tests-utils = { path = "../tests-utils" }
tempfile = "3.1.0"
Expand Down
2 changes: 1 addition & 1 deletion crates/tests/tests/function_imports.rs
@@ -1,7 +1,7 @@
use std::path::Path;
use walrus_tests_utils::wat2wasm;

fn run(wat_path: &Path) -> Result<(), failure::Error> {
fn run(wat_path: &Path) -> Result<(), anyhow::Error> {
static INIT_LOGS: std::sync::Once = std::sync::Once::new();
INIT_LOGS.call_once(|| {
env_logger::init();
Expand Down
9 changes: 3 additions & 6 deletions crates/tests/tests/invalid.rs
@@ -1,7 +1,7 @@
use std::path::Path;
use std::sync::Once;

fn run(wat: &Path) -> Result<(), failure::Error> {
fn run(wat: &Path) -> Result<(), anyhow::Error> {
static INIT_LOGS: Once = Once::new();
INIT_LOGS.call_once(|| {
env_logger::init();
Expand All @@ -12,12 +12,9 @@ fn run(wat: &Path) -> Result<(), failure::Error> {
// NB: reading the module will do the validation.
match walrus::Module::from_buffer(&wasm) {
Err(e) => {
eprintln!("Got error, as expected:");
for c in e.iter_chain() {
eprintln!(" - {}", c);
}
eprintln!("Got error, as expected: {:?}", e);
}
Ok(_) => failure::bail!("expected {} to be invalid, but it was valid", wat.display()),
Ok(_) => anyhow::bail!("expected {} to be invalid, but it was valid", wat.display()),
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion crates/tests/tests/round_trip.rs
Expand Up @@ -2,7 +2,7 @@ use std::env;
use std::path::Path;
use walrus_tests_utils::{wasm2wat, wat2wasm};

fn run(wat_path: &Path) -> Result<(), failure::Error> {
fn run(wat_path: &Path) -> Result<(), anyhow::Error> {
static INIT_LOGS: std::sync::Once = std::sync::Once::new();
INIT_LOGS.call_once(|| {
env_logger::init();
Expand Down
6 changes: 3 additions & 3 deletions crates/tests/tests/spec-tests.rs
@@ -1,4 +1,4 @@
use failure::ResultExt;
use anyhow::Context;
use std::fs;
use std::path::Path;
use std::process::Command;
Expand All @@ -10,7 +10,7 @@ struct Test {
commands: Vec<serde_json::Value>,
}

fn run(wast: &Path) -> Result<(), failure::Error> {
fn run(wast: &Path) -> Result<(), anyhow::Error> {
static INIT_LOGS: std::sync::Once = std::sync::Once::new();
INIT_LOGS.call_once(|| {
env_logger::init();
Expand Down Expand Up @@ -145,7 +145,7 @@ fn run(wast: &Path) -> Result<(), failure::Error> {
Ok(())
}

fn run_spectest_interp(cwd: &Path, extra_args: &[&str]) -> Result<(), failure::Error> {
fn run_spectest_interp(cwd: &Path, extra_args: &[&str]) -> Result<(), anyhow::Error> {
let output = Command::new("spectest-interp")
.current_dir(cwd)
.arg("foo.json")
Expand Down
2 changes: 1 addition & 1 deletion crates/tests/tests/valid.rs
Expand Up @@ -2,7 +2,7 @@ use std::env;
use std::path::Path;
use std::sync::Once;

fn run(wat: &Path) -> Result<(), failure::Error> {
fn run(wat: &Path) -> Result<(), anyhow::Error> {
static INIT_LOGS: Once = Once::new();
INIT_LOGS.call_once(|| {
env_logger::init();
Expand Down
4 changes: 2 additions & 2 deletions src/error.rs
@@ -1,10 +1,10 @@
//! Error types and utilities.

pub use failure::Error;
pub use anyhow::Error;
use std::fmt;

/// Either `Ok(T)` or `Err(failure::Error)`.
pub type Result<T> = ::std::result::Result<T, failure::Error>;
pub type Result<T> = ::std::result::Result<T, anyhow::Error>;

/// A leaf wasm error type.
///
Expand Down
2 changes: 1 addition & 1 deletion src/init_expr.rs
Expand Up @@ -4,7 +4,7 @@ use crate::emit::{Emit, EmitContext};
use crate::ir::Value;
use crate::parse::IndicesToIds;
use crate::{GlobalId, Result};
use failure::bail;
use anyhow::bail;

/// A constant which is produced in WebAssembly, typically used in global
/// initializers or element/data offsets.
Expand Down
4 changes: 2 additions & 2 deletions src/module/data.rs
Expand Up @@ -5,7 +5,7 @@ use crate::ir::Value;
use crate::parse::IndicesToIds;
use crate::tombstone_arena::{Id, Tombstone, TombstoneArena};
use crate::{GlobalId, InitExpr, MemoryId, Module, Result, ValType};
use failure::{bail, ResultExt};
use anyhow::{bail, Context};

/// A passive element segment identifier
pub type DataId = Id<Data>;
Expand Down Expand Up @@ -217,7 +217,7 @@ impl Module {
memory.data_segments.insert(data.id);

let offset = InitExpr::eval(&init_expr, ids)
.with_context(|_e| format!("in segment {}", i))?;
.with_context(|| format!("in segment {}", i))?;
data.kind = DataKind::Active(ActiveData {
memory: memory_id,
location: match offset {
Expand Down
4 changes: 2 additions & 2 deletions src/module/elements.rs
Expand Up @@ -5,7 +5,7 @@ use crate::ir::Value;
use crate::parse::IndicesToIds;
use crate::tombstone_arena::{Id, Tombstone, TombstoneArena};
use crate::{FunctionId, InitExpr, Module, Result, TableKind, ValType};
use failure::{bail, ResultExt};
use anyhow::{bail, Context};

/// A passive element segment identifier
pub type ElementId = Id<Element>;
Expand Down Expand Up @@ -92,7 +92,7 @@ impl Module {
};

let offset = InitExpr::eval(&init_expr, ids)
.with_context(|_e| format!("in segment {}", i))?;
.with_context(|| format!("in segment {}", i))?;
let functions = segment.items.get_items_reader()?.into_iter().map(|func| {
let func = func?;
ids.get_func(func)
Expand Down
35 changes: 16 additions & 19 deletions src/module/functions/local_function/context.rs
Expand Up @@ -7,7 +7,7 @@ use crate::module::Module;
use crate::parse::IndicesToIds;
use crate::ty::ValType;
use crate::{ModuleTypes, TypeId};
use failure::Fail;
use anyhow::Context;

#[derive(Debug)]
pub(crate) struct ControlFrame {
Expand Down Expand Up @@ -173,7 +173,7 @@ impl<'a> ValidationContext<'a> {

pub fn control(&self, n: usize) -> Result<&ControlFrame> {
if n >= self.controls.len() {
failure::bail!("jump to nonexistent control block");
anyhow::bail!("jump to nonexistent control block");
}
let idx = self.controls.len() - n - 1;
Ok(&self.controls[idx])
Expand Down Expand Up @@ -217,9 +217,8 @@ fn impl_pop_operand(
log::trace!("pop operand: None");
return Ok(None);
}
return Err(ErrorKind::InvalidWasm
.context("popped operand past control frame height in non-unreachable code")
.into());
return Err(ErrorKind::InvalidWasm)
.context("popped operand past control frame height in non-unreachable code");
}
}
let op = operands.pop().unwrap();
Expand All @@ -237,10 +236,9 @@ fn impl_pop_operand_expected(
(actual, None) => Ok(actual),
(Some(actual), Some(expected)) => {
if actual != expected {
Err(ErrorKind::InvalidWasm
Err(ErrorKind::InvalidWasm)
.context(format!("expected type {}", expected))
.context(format!("found type {}", actual))
.into())
} else {
Ok(Some(actual))
}
Expand Down Expand Up @@ -275,7 +273,7 @@ fn impl_push_control(
end_types: Box<[ValType]>,
) -> Result<InstrSeqId> {
let ty = InstrSeqType::existing(types, &start_types, &end_types).ok_or_else(|| {
failure::format_err!(
anyhow::anyhow!(
"attempted to push a control frame for an instruction \
sequence with a type that does not exist"
)
Expand Down Expand Up @@ -330,19 +328,18 @@ fn impl_pop_control(
controls: &mut ControlStack,
operands: &mut OperandStack,
) -> Result<ControlFrame> {
let frame = controls.last().ok_or_else(|| {
ErrorKind::InvalidWasm.context("attempted to pop a frame from an empty control stack")
})?;
let frame = controls
.last()
.ok_or_else(|| ErrorKind::InvalidWasm)
.context("attempted to pop a frame from an empty control stack")?;
impl_pop_operands(operands, controls, &frame.end_types)?;
if operands.len() != frame.height {
return Err(ErrorKind::InvalidWasm
.context(format!(
"incorrect number of operands on the stack at the end of a control frame; \
found {}, expected {}",
operands.len(),
frame.height
))
.into());
return Err(ErrorKind::InvalidWasm).context(format!(
"incorrect number of operands on the stack at the end of a control frame; \
found {}, expected {}",
operands.len(),
frame.height
));
}
let frame = controls.pop().unwrap();
Ok(frame)
Expand Down
4 changes: 2 additions & 2 deletions src/module/functions/local_function/mod.rs
Expand Up @@ -12,7 +12,7 @@ use crate::parse::IndicesToIds;
use crate::{
Data, DataId, FunctionBuilder, FunctionId, Module, Result, TableKind, TypeId, ValType,
};
use failure::{bail, ResultExt};
use anyhow::{bail, Context};
use std::collections::BTreeMap;
use wasmparser::Operator;

Expand Down Expand Up @@ -308,7 +308,7 @@ fn validate_instruction(ctx: &mut ValidationContext, inst: Operator) -> Result<(

let mem_arg = |arg: &wasmparser::MemoryImmediate| -> Result<MemArg> {
if arg.flags >= 32 {
failure::bail!("invalid alignment");
bail!("invalid alignment");
}
Ok(MemArg {
align: 1 << (arg.flags as i32),
Expand Down
2 changes: 1 addition & 1 deletion src/module/functions/mod.rs
Expand Up @@ -11,7 +11,7 @@ use crate::parse::IndicesToIds;
use crate::tombstone_arena::{Id, Tombstone, TombstoneArena};
use crate::ty::TypeId;
use crate::ty::ValType;
use failure::bail;
use anyhow::bail;
use std::cmp;

#[cfg(feature = "parallel")]
Expand Down

0 comments on commit 25fce42

Please sign in to comment.