Repository: bytecodealliance/wasmtime
Pull request #5853 (2023-02-22 17:24:11)

Result alias for convienient use of anyhow::Error without depending on anyhow
<!--

Please ensure that the following steps are all taken care of before submitting
the PR.

- [ ] This has been discussed in issue #..., or if not, please tell us why
  here.
- [ ] A short description of what this does, why it is needed; if the
  description becomes long, the matter should probably be discussed in an issue
  first.
- [ ] This PR contains test cases, if meaningful.
- [ ] A reviewer from the core maintainer team has been assigned for this PR.
  If you don't know who could review this, please indicate so. The list of
  suggested reviewers on the right can help you.

Please ensure all communication adheres to the [code of
conduct](https://github.com/bytecodealliance/wasmtime/blob/master/CODE_OF_CONDUCT.md).
-->
As discussed on [Zulip](https://bytecodealliance.zulipchat.com/#narrow/stream/217126-wasmtime/topic/Assumption.20of.20anyhow), the `bindgen!` macro assumes the usage of `anyhow`. This adds a type alias to `wasmtime` for `std::result::Result<T, anyhow::Error>` that allows users to use `wasmtime::Result` where a `std::result::Result<T, anyhow::Error>` is expected. 

In particular, this means that users of `bindgen!` can use `wasmtime::Result` when they are implementing an import function. 

One caveat: after making this change, I realized that the `bindgen!` macro has the `trappable_error_type` option which could be used to change the error type assume. While some changes need to be made no matter what (as many of the methods generated by the macro still assume `anyhow` and don't respect that option), we might want to consider not adding this type alias and just making it clearer that users should use the `trappable_error_type` option if they are not using `anyhow`.

r? @alexcrichton 

github-actions[bot]: #### Subscribe to Label Action

cc @fitzgen

<details>
This issue or pull request has been labeled: "fuzzing"

Thus the following users have been cc'd because of the following labels:

* fitzgen: fuzzing

To subscribe or unsubscribe from this label, edit the <code>.github/subscribe-to-label.json</code> configuration file.

[Learn more.](https://github.com/bytecodealliance/subscribe-to-label-action)
</details>
rylev: @alexcrichton I applied your suggestion!

Patch:
diff --git a/crates/fuzzing/src/oracles.rs b/crates/fuzzing/src/oracles.rs
index 2ed29e6a3..b656dc2ea 100644
--- a/crates/fuzzing/src/oracles.rs
+++ b/crates/fuzzing/src/oracles.rs
@@ -785,7 +785,6 @@ pub fn set_fuel<T>(store: &mut Store<T>, fuel: u64) {
 /// arbitrary types and values.
 pub fn dynamic_component_api_target(input: &mut arbitrary::Unstructured) -> arbitrary::Result<()> {
     use crate::generators::component_types;
-    use anyhow::Result;
     use component_fuzz_util::{TestCase, EXPORT_FUNCTION, IMPORT_FUNCTION};
     use component_test_util::FuncExt;
     use wasmtime::component::{Component, Linker, Val};
diff --git a/crates/wasmtime/src/component/mod.rs b/crates/wasmtime/src/component/mod.rs
index f1f88c2d7..15212fb92 100644
--- a/crates/wasmtime/src/component/mod.rs
+++ b/crates/wasmtime/src/component/mod.rs
@@ -82,7 +82,6 @@ pub(crate) use self::store::ComponentStoreData;
 /// Then you can interact with the generated bindings like so:
 ///
 /// ```rust,ignore
-/// use anyhow::Result;
 /// use wasmtime::component::*;
 /// use wasmtime::{Config, Engine, Store};
 ///
@@ -97,12 +96,12 @@ pub(crate) use self::store::ComponentStoreData;
 /// impl HelloWorldImports for MyState {
 ///     // Note the `Result` return value here where `Ok` is returned back to
 ///     // the component and `Err` will raise a trap.
-///     fn name(&mut self) -> Result<String> {
+///     fn name(&mut self) -> wasmtime::Result<String> {
 ///         Ok(self.name.clone())
 ///     }
 /// }
 ///
-/// fn main() -> Result<()> {
+/// fn main() -> wasmtime::Result<()> {
 ///     // Configure an `Engine` and compile the `Component` that is being run for
 ///     // the application.
 ///     let mut config = Config::new();
@@ -168,7 +167,6 @@ pub(crate) use self::store::ComponentStoreData;
 /// Then you can interact with the generated bindings like so:
 ///
 /// ```rust,ignore
-/// use anyhow::Result;
 /// use wasmtime::component::*;
 /// use wasmtime::{Config, Engine, Store};
 ///
@@ -180,16 +178,16 @@ pub(crate) use self::store::ComponentStoreData;
 ///
 /// // Note that the trait here is per-interface and within a submodule now.
 /// impl host::Host for MyState {
-///     fn gen_random_integer(&mut self) -> Result<u32> {
+///     fn gen_random_integer(&mut self) -> wasmtime::Result<u32> {
 ///         Ok(rand::thread_rng().gen())
 ///     }
 ///
-///     fn sha256(&mut self, bytes: Vec<u8>) -> Result<String> {
+///     fn sha256(&mut self, bytes: Vec<u8>) -> wasmtime::Result<String> {
 ///         // ...
 ///     }
 /// }
 ///
-/// fn main() -> Result<()> {
+/// fn main() -> wasmtime::Result<()> {
 ///     let mut config = Config::new();
 ///     config.wasm_component_model(true);
 ///     let engine = Engine::new(&config)?;
diff --git a/crates/wasmtime/src/lib.rs b/crates/wasmtime/src/lib.rs
index a11bdd940..dd54cdc77 100644
--- a/crates/wasmtime/src/lib.rs
+++ b/crates/wasmtime/src/lib.rs
@@ -27,10 +27,9 @@
 //! An example of using Wasmtime looks like:
 //!
 //! ```
-//! use anyhow::Result;
 //! use wasmtime::*;
 //!
-//! fn main() -> Result<()> {
+//! fn main() -> wasmtime::Result<()> {
 //!     // Modules can be compiled through either the text or binary format
 //!     let engine = Engine::default();
 //!     let wat = r#"
@@ -141,10 +140,9 @@
 //! For example we can reimplement the above example with a `Linker`:
 //!
 //! ```
-//! use anyhow::Result;
 //! use wasmtime::*;
 //!
-//! fn main() -> Result<()> {
+//! fn main() -> wasmtime::Result<()> {
 //!     let engine = Engine::default();
 //!     let wat = r#"
 //!         (module
@@ -301,11 +299,10 @@
 //! An example of using WASI looks like:
 //!
 //! ```no_run
-//! # use anyhow::Result;
 //! # use wasmtime::*;
 //! use wasmtime_wasi::sync::WasiCtxBuilder;
 //!
-//! # fn main() -> Result<()> {
+//! # fn main() -> wasmtime::Result<()> {
 //! // Compile our module and create a `Linker` which has WASI functions defined
 //! // within it.
 //! let engine = Engine::default();
@@ -333,7 +330,7 @@
 //! use std::str;
 //!
 //! # use wasmtime::*;
-//! # fn main() -> anyhow::Result<()> {
+//! # fn main() -> wasmtime::Result<()> {
 //! let mut store = Store::default();
 //! let log_str = Func::wrap(&mut store, |mut caller: Caller<'_, ()>, ptr: i32, len: i32| {
 //!     // Use our `caller` context to learn about the memory export of the
@@ -427,6 +424,13 @@ pub use crate::trap::*;
 pub use crate::types::*;
 pub use crate::values::*;
 
+/// A convenience wrapper for `Result<T, anyhow::Error>`.
+///
+/// This type can be used to interact with `wasmtimes`'s extensive use
+/// of `anyhow::Error` while still not directly depending on `anyhow`.
+/// This type alias is identical to `anyhow::Result`.
+pub use anyhow::{Error, Result};
+
 #[cfg(feature = "component-model")]
 pub mod component;
 
diff --git a/crates/wit-bindgen/src/lib.rs b/crates/wit-bindgen/src/lib.rs
index 9fdde5317..21f029613 100644
--- a/crates/wit-bindgen/src/lib.rs
+++ b/crates/wit-bindgen/src/lib.rs
@@ -179,7 +179,7 @@ impl Wasmtime {
                     "
                         pub fn new(
                             __exports: &mut wasmtime::component::ExportInstance<'_, '_>,
-                        ) -> anyhow::Result<{camel}> {{
+                        ) -> wasmtime::Result<{camel}> {{
                     "
                 );
                 let mut fields = Vec::new();
@@ -267,7 +267,7 @@ impl Wasmtime {
                     mut store: impl wasmtime::AsContextMut<Data = T>,
                     component: &wasmtime::component::Component,
                     linker: &wasmtime::component::Linker<T>,
-                ) -> anyhow::Result<(Self, wasmtime::component::Instance)> {{
+                ) -> wasmtime::Result<(Self, wasmtime::component::Instance)> {{
                     let instance = linker.instantiate{async__}(&mut store, component){await_}?;
                     Ok((Self::new(store, &instance)?, instance))
                 }}
@@ -278,7 +278,7 @@ impl Wasmtime {
                 pub {async_} fn instantiate_pre<T {send}>(
                     mut store: impl wasmtime::AsContextMut<Data = T>,
                     instance_pre: &wasmtime::component::InstancePre<T>,
-                ) -> anyhow::Result<(Self, wasmtime::component::Instance)> {{
+                ) -> wasmtime::Result<(Self, wasmtime::component::Instance)> {{
                     let instance = instance_pre.instantiate{async__}(&mut store){await_}?;
                     Ok((Self::new(store, &instance)?, instance))
                 }}
@@ -294,7 +294,7 @@ impl Wasmtime {
                 pub fn new(
                     mut store: impl wasmtime::AsContextMut,
                     instance: &wasmtime::component::Instance,
-                ) -> anyhow::Result<Self> {{
+                ) -> wasmtime::Result<Self> {{
                     let mut store = store.as_context_mut();
                     let mut exports = instance.exports(&mut store);
                     let mut __exports = exports.root();
@@ -397,7 +397,7 @@ impl Wasmtime {
                 pub fn add_to_linker<T, U>(
                     linker: &mut wasmtime::component::Linker<T>,
                     get: impl Fn(&mut T) -> &mut U + Send + Sync + Copy + 'static,
-                ) -> anyhow::Result<()>
+                ) -> wasmtime::Result<()>
                     where U: \
             "
         );
@@ -442,7 +442,7 @@ impl Wasmtime {
                 pub fn add_root_to_linker<T, U>(
                     linker: &mut wasmtime::component::Linker<T>,
                     get: impl Fn(&mut T) -> &mut U + Send + Sync + Copy + 'static,
-                ) -> anyhow::Result<()>
+                ) -> wasmtime::Result<()>
                     where U: {world_trait}{maybe_send}
                 {{
                     let mut linker = linker.root();
@@ -978,7 +978,7 @@ impl<'a> InterfaceGenerator<'a> {
                 pub fn add_to_linker<T, U>(
                     linker: &mut wasmtime::component::Linker<T>,
                     get: impl Fn(&mut T) -> &mut U + Send + Sync + Copy + 'static,
-                ) -> anyhow::Result<()>
+                ) -> wasmtime::Result<()>
                     where {where_clause},
                 {{
             "
@@ -1124,9 +1124,9 @@ impl<'a> InterfaceGenerator<'a> {
             self.push_str(&error_typename);
             self.push_str(">");
         } else {
-            // All other functions get their return values wrapped in an anyhow::Result.
+            // All other functions get their return values wrapped in an wasmtime::Result.
             // Returning the anyhow::Error case can be used to trap.
-            self.push_str("anyhow::Result<");
+            self.push_str("wasmtime::Result<");
             self.print_result_ty(&func.results, TypeMode::Owned);
             self.push_str(">");
         }
@@ -1174,7 +1174,7 @@ impl<'a> InterfaceGenerator<'a> {
             self.print_ty(&param.1, TypeMode::AllBorrowed("'_"));
             self.push_str(",");
         }
-        self.src.push_str(") -> anyhow::Result<");
+        self.src.push_str(") -> wasmtime::Result<");
         self.print_result_ty(&func.results, TypeMode::Owned);
 
         if self.gen.opts.async_ {


Test patch:
diff --git a/tests/all/memory_creator.rs b/tests/all/memory_creator.rs
index cdf4c5c9e..01cc0fabf 100644
--- a/tests/all/memory_creator.rs
+++ b/tests/all/memory_creator.rs
@@ -57,7 +57,7 @@ mod not_for_windows {
             Some(self.size - self.guard_size)
         }
 
-        fn grow_to(&mut self, new_size: usize) -> Result<(), anyhow::Error> {
+        fn grow_to(&mut self, new_size: usize) -> wasmtime::Result<()> {
             println!("grow to {:x}", new_size);
             let delta = new_size - self.used_wasm_bytes;
             unsafe {