mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-06-18 15:31:25 +00:00
Merge pull request #787 from bspeice/patch-1
[WIP] Remove --wasm2asm flag, use binaryen directly
This commit is contained in:
@ -11,14 +11,12 @@ use parity_wasm::elements::*;
|
||||
|
||||
pub struct Config {
|
||||
base64: bool,
|
||||
wasm2asm: bool,
|
||||
fetch_path: Option<String>,
|
||||
}
|
||||
|
||||
pub struct Output {
|
||||
module: Module,
|
||||
base64: bool,
|
||||
wasm2asm: bool,
|
||||
fetch_path: Option<String>,
|
||||
}
|
||||
|
||||
@ -26,7 +24,6 @@ impl Config {
|
||||
pub fn new() -> Config {
|
||||
Config {
|
||||
base64: false,
|
||||
wasm2asm: false,
|
||||
fetch_path: None,
|
||||
}
|
||||
}
|
||||
@ -36,25 +33,19 @@ impl Config {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn wasm2asm(&mut self, wasm2asm: bool) -> &mut Self {
|
||||
self.wasm2asm = wasm2asm;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn fetch(&mut self, path: Option<String>) -> &mut Self {
|
||||
self.fetch_path = path;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn generate(&mut self, wasm: &[u8]) -> Result<Output, Error> {
|
||||
if !self.base64 && !self.fetch_path.is_some() && !self.wasm2asm {
|
||||
bail!("one of --base64, --fetch, or --wasm2asm is required");
|
||||
if !self.base64 && !self.fetch_path.is_some() {
|
||||
bail!("one of --base64 or --fetch is required");
|
||||
}
|
||||
let module = deserialize_buffer(wasm)?;
|
||||
Ok(Output {
|
||||
module,
|
||||
base64: self.base64,
|
||||
wasm2asm: self.wasm2asm,
|
||||
fetch_path: self.fetch_path.clone(),
|
||||
})
|
||||
}
|
||||
@ -139,9 +130,6 @@ impl Output {
|
||||
}
|
||||
|
||||
pub fn js(self) -> Result<String, Error> {
|
||||
if self.wasm2asm {
|
||||
return self.js_wasm2asm();
|
||||
}
|
||||
let mut js_imports = String::new();
|
||||
let mut exports = String::new();
|
||||
let mut set_exports = String::new();
|
||||
@ -232,170 +220,6 @@ impl Output {
|
||||
exports = exports,
|
||||
))
|
||||
}
|
||||
|
||||
fn js_wasm2asm(self) -> Result<String, Error> {
|
||||
let mut js_imports = String::new();
|
||||
let mut imported_items = Vec::new();
|
||||
if let Some(i) = self.module.import_section() {
|
||||
let mut name_map = HashMap::new();
|
||||
for (i, entry) in i.entries().iter().enumerate() {
|
||||
match *entry.external() {
|
||||
External::Function(_) => {}
|
||||
External::Table(_) => {
|
||||
bail!("wasm imports a table which isn't supported yet");
|
||||
}
|
||||
External::Memory(_) => {
|
||||
bail!("wasm imports memory which isn't supported yet");
|
||||
}
|
||||
External::Global(_) => {
|
||||
bail!("wasm imports globals which aren't supported yet");
|
||||
}
|
||||
}
|
||||
|
||||
let m = name_map.entry(entry.field()).or_insert(entry.module());
|
||||
if *m != entry.module() {
|
||||
bail!(
|
||||
"the name `{}` is imported from two differnet \
|
||||
modules which currently isn't supported in `wasm2asm` \
|
||||
mode"
|
||||
);
|
||||
}
|
||||
|
||||
let name = format!("import{}", i);
|
||||
js_imports.push_str(&format!(
|
||||
"import {{ {} as {} }} from '{}';\n",
|
||||
entry.field(),
|
||||
name,
|
||||
entry.module()
|
||||
));
|
||||
imported_items.push((entry.field().to_string(), name));
|
||||
}
|
||||
}
|
||||
|
||||
let mut js_exports = String::new();
|
||||
if let Some(i) = self.module.export_section() {
|
||||
let mut export_mem = false;
|
||||
for entry in i.entries() {
|
||||
match *entry.internal() {
|
||||
Internal::Function(_) => {}
|
||||
Internal::Memory(_) => export_mem = true,
|
||||
Internal::Table(_) => continue,
|
||||
Internal::Global(_) => continue,
|
||||
};
|
||||
|
||||
js_exports.push_str(&format!("export const {0} = ret.{0};\n", entry.field()));
|
||||
}
|
||||
if !export_mem {
|
||||
bail!(
|
||||
"the `wasm2asm` mode is currently only compatible with \
|
||||
modules that export memory"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
let memory_size = self.module.memory_section().unwrap().entries()[0]
|
||||
.limits()
|
||||
.initial();
|
||||
|
||||
let mut js_init_mem = String::new();
|
||||
if let Some(s) = self.module.data_section() {
|
||||
for entry in s.entries() {
|
||||
let offset = entry.offset().code();
|
||||
if offset.len() != 2 {
|
||||
bail!("don't recognize data offset {:?}", offset)
|
||||
}
|
||||
if offset[1] != Instruction::End {
|
||||
bail!("don't recognize data offset {:?}", offset)
|
||||
}
|
||||
let offset = match offset[0] {
|
||||
Instruction::I32Const(x) => x,
|
||||
_ => bail!("don't recognize data offset {:?}", offset),
|
||||
};
|
||||
|
||||
let base64 = base64::encode(entry.value());
|
||||
js_init_mem.push_str(&format!("_assign({}, \"{}\");\n", offset, base64));
|
||||
}
|
||||
}
|
||||
|
||||
let td = tempfile::tempdir()?;
|
||||
let wasm = serialize(self.module)?;
|
||||
let wasm_file = td.as_ref().join("foo.wasm");
|
||||
fs::write(&wasm_file, wasm)
|
||||
.with_context(|_| format!("failed to write wasm to `{}`", wasm_file.display()))?;
|
||||
|
||||
let wast_file = td.as_ref().join("foo.wast");
|
||||
run(
|
||||
Command::new("wasm-dis")
|
||||
.arg(&wasm_file)
|
||||
.arg("-o")
|
||||
.arg(&wast_file),
|
||||
"wasm-dis",
|
||||
)?;
|
||||
let js_file = td.as_ref().join("foo.js");
|
||||
run(
|
||||
Command::new("wasm2asm")
|
||||
.arg(&wast_file)
|
||||
.arg("-o")
|
||||
.arg(&js_file),
|
||||
"wasm2asm",
|
||||
)?;
|
||||
|
||||
let asm_func = fs::read_to_string(&js_file)
|
||||
.with_context(|_| format!("failed to read `{}`", js_file.display()))?;
|
||||
|
||||
let mut make_imports = String::from(
|
||||
"
|
||||
var imports = {};
|
||||
",
|
||||
);
|
||||
for (name, import) in imported_items {
|
||||
make_imports.push_str(&format!("imports['{}'] = {};\n", name, import));
|
||||
}
|
||||
|
||||
Ok(format!(
|
||||
"\
|
||||
{js_imports}
|
||||
|
||||
{asm_func}
|
||||
|
||||
const mem = new ArrayBuffer({mem_size});
|
||||
const _mem = new Uint8Array(mem);
|
||||
function _assign(offset, s) {{
|
||||
if (typeof Buffer === 'undefined') {{
|
||||
const bytes = atob(s);
|
||||
for (let i = 0; i < bytes.length; i++)
|
||||
_mem[offset + i] = bytes.charCodeAt(i);
|
||||
}} else {{
|
||||
const bytes = Buffer.from(s, 'base64');
|
||||
for (let i = 0; i < bytes.length; i++)
|
||||
_mem[offset + i] = bytes[i];
|
||||
}}
|
||||
}}
|
||||
{js_init_mem}
|
||||
{make_imports}
|
||||
const ret = asmFunc({{
|
||||
Math,
|
||||
Int8Array,
|
||||
Uint8Array,
|
||||
Int16Array,
|
||||
Uint16Array,
|
||||
Int32Array,
|
||||
Uint32Array,
|
||||
Float32Array,
|
||||
Float64Array,
|
||||
NaN,
|
||||
Infinity,
|
||||
}}, imports, mem);
|
||||
{js_exports}
|
||||
",
|
||||
js_imports = js_imports,
|
||||
js_init_mem = js_init_mem,
|
||||
asm_func = asm_func,
|
||||
js_exports = js_exports,
|
||||
make_imports = make_imports,
|
||||
mem_size = memory_size * (1 << 16),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn run(cmd: &mut Command, program: &str) -> Result<(), Error> {
|
||||
|
@ -24,7 +24,6 @@ Options:
|
||||
--typescript Output a `*.d.ts` file next to the JS output
|
||||
--base64 Inline the wasm module using base64 encoding
|
||||
--fetch PATH Load module by passing the PATH argument to `fetch()`
|
||||
--wasm2asm Convert wasm to asm.js and don't use `WebAssembly`
|
||||
|
||||
Note that this is not intended to produce a production-ready output module
|
||||
but rather is intended purely as a temporary \"hack\" until it's standard in
|
||||
@ -36,7 +35,6 @@ struct Args {
|
||||
flag_output: Option<PathBuf>,
|
||||
flag_typescript: bool,
|
||||
flag_base64: bool,
|
||||
flag_wasm2asm: bool,
|
||||
flag_fetch: Option<String>,
|
||||
arg_input: PathBuf,
|
||||
}
|
||||
@ -62,7 +60,6 @@ fn rmain(args: &Args) -> Result<(), Error> {
|
||||
|
||||
let object = wasm_bindgen_cli_support::wasm2es6js::Config::new()
|
||||
.base64(args.flag_base64)
|
||||
.wasm2asm(args.flag_wasm2asm)
|
||||
.fetch(args.flag_fetch.clone())
|
||||
.generate(&wasm)?;
|
||||
|
||||
|
@ -12,7 +12,7 @@ The examples here are:
|
||||
|
||||
* `add` - an example of generating a tiny wasm binary, one that only adds two
|
||||
numbers.
|
||||
* `asm.js` - an example of using the `wasm2asm` tool from [binaryen] to convert
|
||||
* `asm.js` - an example of using the `wasm2js` tool from [binaryen] to convert
|
||||
the generated WebAssembly to normal JS
|
||||
* `char` - an example of passing the rust `char` type to and from the js `string` type
|
||||
* `closures` - an example of how to invoke functions like `setInterval` or use
|
||||
|
@ -1,6 +1,6 @@
|
||||
# WebAssembly to asm.js
|
||||
|
||||
This directory is an example of using [binaryen]'s `wasm2asm` tool to convert
|
||||
This directory is an example of using [binaryen]'s `wasm2js` tool to convert
|
||||
the wasm output of `wasm-bindgen` to a normal JS file that can be executed like
|
||||
asm.js.
|
||||
|
||||
@ -12,11 +12,7 @@ $ ./build.sh
|
||||
|
||||
When opened in a web browser this should print "Hello, World!" to the console.
|
||||
|
||||
This example uses the `wasm2es6js` tool to convert the wasm file to an ES module
|
||||
that's implemented with asm.js instead of WebAssembly. The conversion to asm.js
|
||||
is done by [binaryen]'s `wasm2asm` tool internally.
|
||||
|
||||
Note that the `wasm2asm` tool is still pretty early days so there's likely to be
|
||||
Note that the `wasm2js` tool is still pretty early days so there's likely to be
|
||||
a number of bugs to run into or work around. If any are encountered though
|
||||
please feel free to report them upstream!
|
||||
|
||||
|
@ -6,17 +6,14 @@ set -ex
|
||||
cargo +nightly build --target wasm32-unknown-unknown --release
|
||||
|
||||
# Run wasm-bindgen, and note that the `--no-demangle` argument is here is
|
||||
# important for compatibility with wasm2asm!
|
||||
# important for compatibility with wasm2js!
|
||||
cargo +nightly run --manifest-path ../../crates/cli/Cargo.toml \
|
||||
--bin wasm-bindgen -- \
|
||||
--no-demangle \
|
||||
../../target/wasm32-unknown-unknown/release/asmjs.wasm --out-dir .
|
||||
|
||||
# Run the `wasm2es6js` primarily with the `--wasm2asm` flag, which will
|
||||
# internally execute `wasm2asm` as necessary
|
||||
cargo +nightly run --manifest-path ../../crates/cli/Cargo.toml \
|
||||
--bin wasm2es6js -- \
|
||||
asmjs_bg.wasm --wasm2asm -o asmjs_bg.js
|
||||
# Run the `wasm2js` tool from `binaryen`
|
||||
wasm2js asmjs_bg.wasm -o asmjs_bg.js
|
||||
|
||||
# Move our original wasm out of the way to avoid cofusing Webpack.
|
||||
mv asmjs_bg.wasm asmjs_bg.bak.wasm
|
||||
|
Reference in New Issue
Block a user