Add a wasmtime::Linker type (#1384)

* Add a `wasmtime::Linker` type

This commit adds a new type to the `wasmtime` crate, a `Linker`. This
linker is intended to vastly simplify calling `Instance::new` by easily
performing name resolution and incrementally defining state over time.
The goal here is to start down a path of making linking wasm modules in
`wasmtime` a first-class and ergonomic operation. This is highly likely
to evolve over time and get tweaked through releases as we iterate
towards a design well-suited for `wasmtime`, but this is intended to at
least be the initial foundation for such functionality.

This commit additionally also adds a C API for the linker and switches
the existing linking examples to using this linker in both Rust and C.

One piece of future work I'd like to tackle next is to integrate WASI
into the `wasmtime` crate in a more first-class manner. This [`Linker`]
type provides a great location to hook into the instantiation process to
easily instantiate modules with WASI imports. That's a relatively large
refactoring for now though and I figured it'd be best left for a
different time.

Closes #727
This commit is contained in:
Alex Crichton
2020-03-23 21:02:31 -05:00
committed by GitHub
parent 021ebb3748
commit 0d4bde4ab3
13 changed files with 630 additions and 110 deletions

View File

@@ -266,8 +266,10 @@ pub fn define_struct_for_wiggle(args: TokenStream) -> TokenStream {
let mut get_exports = Vec::new();
let mut ctor_externs = Vec::new();
let mut ctor_fields = Vec::new();
let mut linker_add = Vec::new();
for module in doc.modules() {
let module_name = module.name.as_str();
let module_id = Ident::new(module.name.as_str(), Span::call_site());
for func in module.funcs() {
let name = func.name.as_str();
@@ -275,6 +277,9 @@ pub fn define_struct_for_wiggle(args: TokenStream) -> TokenStream {
fields.push(quote! { pub #name_ident: wasmtime::Func });
get_exports.push(quote! { #name => Some(&self.#name_ident) });
ctor_fields.push(name_ident.clone());
linker_add.push(quote! {
linker.define(#module_name, #name, self.#name_ident.clone())?;
});
let mut shim_arg_decls = Vec::new();
let mut params = Vec::new();
@@ -501,6 +506,12 @@ pub fn define_struct_for_wiggle(args: TokenStream) -> TokenStream {
_ => None,
}
}
/// Adds all wasi items to the specified `Linker`.
pub fn add_to_linker(&self, linker: &mut wasmtime::Linker) -> anyhow::Result<()> {
#(#linker_add)*
Ok(())
}
}
}
}