Files
wasmtime/crates/api/tests/import-indexes.rs
Alex Crichton 16804673a2 Support parsing the text format in wasmtime crate (#813)
* Support parsing the text format in `wasmtime` crate

This commit adds support to the `wasmtime::Module` type to parse the
text format. This is often quite convenient to support in testing or
tinkering with the runtime. Additionally the `wat` parser is pretty
lightweight and easy to add to builds, so it's relatively easy for us to
support as well!

The exact manner that this is now supported comes with a few updates to
the existing API:

* A new optional feature of the `wasmtime` crate, `wat`, has been added.
  This is enabled by default.
* The `Module::new` API now takes `impl AsRef<[u8]>` instead of just
  `&[u8]`, and when the `wat` feature is enabled it will attempt to
  interpret it either as a wasm binary or as the text format. Note that
  this check is quite cheap since you just check the first byte.
* A `Module::from_file` API was added as a convenience to parse a file
  from disk, allowing error messages for `*.wat` files on disk to be a
  bit nicer.
* APIs like `Module::new_unchecked` and `Module::validate` remain
  unchanged, they require the binary format to be called.

The intention here is to make this as convenient as possible for new
developers of the `wasmtime` crate. By changing the default behavior
though this has ramifications such as, for example, supporting the text
format implicitly through the C API now.

* Handle review comments

* Update more tests to avoid usage of `wat` crate

* Go back to unchecked for now in wasm_module_new

Looks like C# tests rely on this?
2020-01-24 14:20:51 -06:00

68 lines
1.6 KiB
Rust

use std::rc::Rc;
use wasmtime::*;
#[test]
fn same_import_names_still_distinct() -> anyhow::Result<()> {
const WAT: &str = r#"
(module
(import "" "" (func $a (result i32)))
(import "" "" (func $b (result f32)))
(func (export "foo") (result i32)
call $a
call $b
i32.trunc_f32_u
i32.add)
)
"#;
struct Ret1;
impl Callable for Ret1 {
fn call(&self, params: &[Val], results: &mut [Val]) -> Result<(), Trap> {
assert!(params.is_empty());
assert_eq!(results.len(), 1);
results[0] = 1i32.into();
Ok(())
}
}
struct Ret2;
impl Callable for Ret2 {
fn call(&self, params: &[Val], results: &mut [Val]) -> Result<(), Trap> {
assert!(params.is_empty());
assert_eq!(results.len(), 1);
results[0] = 2.0f32.into();
Ok(())
}
}
let store = Store::default();
let module = Module::new(&store, WAT)?;
let imports = [
Func::new(
&store,
FuncType::new(Box::new([]), Box::new([ValType::I32])),
Rc::new(Ret1),
)
.into(),
Func::new(
&store,
FuncType::new(Box::new([]), Box::new([ValType::F32])),
Rc::new(Ret2),
)
.into(),
];
let instance = Instance::new(&module, &imports)?;
let func = instance.get_export("foo").unwrap().func().unwrap();
let results = func.call(&[])?;
assert_eq!(results.len(), 1);
match results[0] {
Val::I32(n) => assert_eq!(n, 3),
_ => panic!("unexpected type of return"),
}
Ok(())
}