| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
import argparse |
| 4 |
import sys |
| 5 |
from pathlib import Path |
| 6 |
|
| 7 |
JS_TEMPLATE = """ |
| 8 |
#include "emscripten.h" |
| 9 |
|
| 10 |
EM_JS(void, {function_name}, (void), {{ |
| 11 |
return new WebAssembly.Module(hexStringToUTF8Array("{hex_string}")); |
| 12 |
}} |
| 13 |
function hexStringToUTF8Array(hex) {{ |
| 14 |
const bytes = []; |
| 15 |
for (let i = 0; i < hex.length; i += 2) {{ |
| 16 |
bytes.push(parseInt(hex.substr(i, 2), 16)); |
| 17 |
}} |
| 18 |
return new Uint8Array(bytes); |
| 19 |
}}); |
| 20 |
""" |
| 21 |
|
| 22 |
|
| 23 |
def prepare_wasm(input_file, output_file, function_name): |
| 24 |
# Read the compiled WASM as binary and convert to hex |
| 25 |
wasm_bytes = Path(input_file).read_bytes() |
| 26 |
|
| 27 |
hex_string = "".join(f"{byte:02x}" for byte in wasm_bytes) |
| 28 |
|
| 29 |
# Generate JavaScript module |
| 30 |
js_content = JS_TEMPLATE.format( |
| 31 |
function_name=function_name, hex_string=hex_string |
| 32 |
) |
| 33 |
Path(output_file).write_text(js_content) |
| 34 |
|
| 35 |
print(f"Successfully compiled {input_file} and generated {output_file}") |
| 36 |
return 0 |
| 37 |
|
| 38 |
|
| 39 |
def main(): |
| 40 |
parser = argparse.ArgumentParser( |
| 41 |
description="Compile WebAssembly text files using wasm-as" |
| 42 |
) |
| 43 |
parser.add_argument("input_file", help="Input .wat file to compile") |
| 44 |
parser.add_argument("output_file", help="Output file name") |
| 45 |
parser.add_argument("function_name", help="Name of the export function") |
| 46 |
|
| 47 |
args = parser.parse_args() |
| 48 |
|
| 49 |
return prepare_wasm(args.input_file, args.output_file, args.function_name) |
| 50 |
|
| 51 |
|
| 52 |
if __name__ == "__main__": |
| 53 |
sys.exit(main()) |