wasm_bindgen_cli_support/
wasm2es6js.rs

1use anyhow::{bail, Error};
2use base64::{prelude::BASE64_STANDARD, Engine as _};
3use std::collections::HashSet;
4use std::fmt::Write;
5use walrus::Module;
6
7pub struct Config {
8    base64: bool,
9    fetch_path: Option<String>,
10}
11
12pub struct Output {
13    module: Module,
14    base64: bool,
15    fetch_path: Option<String>,
16}
17
18impl Config {
19    pub fn new() -> Config {
20        Config {
21            base64: false,
22            fetch_path: None,
23        }
24    }
25
26    pub fn base64(&mut self, base64: bool) -> &mut Self {
27        self.base64 = base64;
28        self
29    }
30
31    pub fn fetch(&mut self, path: Option<String>) -> &mut Self {
32        self.fetch_path = path;
33        self
34    }
35
36    pub fn generate(&mut self, wasm: &[u8]) -> Result<Output, Error> {
37        if !self.base64 && self.fetch_path.is_none() {
38            bail!("one of --base64 or --fetch is required");
39        }
40        let module = Module::from_buffer(wasm)?;
41        Ok(Output {
42            module,
43            base64: self.base64,
44            fetch_path: self.fetch_path.clone(),
45        })
46    }
47}
48
49// Function to ensure we always append a valid typescript parameter name based
50// on parameter index
51fn push_index_identifier(i: usize, s: &mut String) {
52    let letter = b'a' + ((i % 26) as u8);
53    s.push(letter as char);
54    if i >= 26 {
55        write!(s, "{}", i / 26).unwrap();
56    }
57}
58
59fn args_are_optional(name: &str) -> bool {
60    name == "__wbindgen_thread_destroy"
61}
62
63pub fn interface(module: &Module) -> Result<String, Error> {
64    let mut exports = String::new();
65    module_export_types(module, |name, ty| {
66        writeln!(exports, "  readonly {}: {};", name, ty).unwrap();
67    });
68    Ok(exports)
69}
70
71pub fn typescript(module: &Module) -> Result<String, Error> {
72    let mut exports = "/* tslint:disable */\n/* eslint-disable */\n".to_string();
73    module_export_types(module, |name, ty| {
74        writeln!(exports, "export const {}: {};", name, ty).unwrap();
75    });
76    Ok(exports)
77}
78
79/// Iterates over all the exports in a module and generates TypeScript types. All
80/// name-type pairs are passed to the `export` function.
81fn module_export_types(module: &Module, mut export: impl FnMut(&str, &str)) {
82    for entry in module.exports.iter() {
83        match entry.item {
84            walrus::ExportItem::Function(id) => {
85                let func = module.funcs.get(id);
86                let ty = module.types.get(func.ty());
87                let ts_type = function_type_to_ts(ty, args_are_optional(&entry.name));
88                export(&entry.name, &ts_type);
89            }
90            walrus::ExportItem::Memory(_) => export(&entry.name, "WebAssembly.Memory"),
91            walrus::ExportItem::Table(_) => export(&entry.name, "WebAssembly.Table"),
92            walrus::ExportItem::Global(_) => continue,
93        };
94    }
95}
96fn val_type_to_ts(ty: walrus::ValType) -> &'static str {
97    // see https://webassembly.github.io/spec/js-api/index.html#towebassemblyvalue
98    // and https://webassembly.github.io/spec/js-api/index.html#tojsvalue
99    match ty {
100        walrus::ValType::I32 | walrus::ValType::F32 | walrus::ValType::F64 => "number",
101        walrus::ValType::I64 => "bigint",
102        // there could be anything behind a reference
103        walrus::ValType::Ref(_) => "any",
104        // V128 currently isn't supported in JS and therefore doesn't have a
105        // specific type in the spec. When it does get support, this type will
106        // still be technically correct, but should be updated to something more
107        // specific.
108        walrus::ValType::V128 => "any",
109    }
110}
111fn function_type_to_ts(function: &walrus::Type, all_args_optional: bool) -> String {
112    let mut out = String::new();
113
114    // parameters
115    out.push('(');
116    for (i, arg_type) in function.params().iter().enumerate() {
117        if i > 0 {
118            out.push_str(", ");
119        }
120
121        push_index_identifier(i, &mut out);
122        if all_args_optional {
123            out.push('?');
124        }
125        out.push_str(": ");
126        out.push_str(val_type_to_ts(*arg_type));
127    }
128    out.push(')');
129
130    // arrow
131    out.push_str(" => ");
132
133    // results
134    let results = function.results();
135    // this match follows the spec:
136    // https://webassembly.github.io/spec/js-api/index.html#exported-function-exotic-objects
137    match results.len() {
138        0 => out.push_str("void"),
139        1 => out.push_str(val_type_to_ts(results[0])),
140        _ => {
141            out.push('[');
142            for (i, result) in results.iter().enumerate() {
143                if i > 0 {
144                    out.push_str(", ");
145                }
146                out.push_str(val_type_to_ts(*result));
147            }
148            out.push(']');
149        }
150    }
151
152    out
153}
154
155impl Output {
156    pub fn typescript(&self) -> Result<String, Error> {
157        let mut ts = typescript(&self.module)?;
158        if self.base64 {
159            ts.push_str("export const booted: Promise<boolean>;\n");
160        }
161        Ok(ts)
162    }
163
164    pub fn js_and_wasm(mut self) -> Result<(String, Option<Vec<u8>>), Error> {
165        let mut js_imports = String::new();
166        let mut exports = String::new();
167        let mut set_exports = String::new();
168        let mut imports = String::new();
169
170        let mut set = HashSet::new();
171        for entry in self.module.imports.iter() {
172            if !set.insert(&entry.module) {
173                continue;
174            }
175
176            let mut name = String::new();
177            push_index_identifier(set.len(), &mut name);
178
179            js_imports.push_str(&format!(
180                "import * as import_{} from '{}';\n",
181                name, entry.module
182            ));
183            imports.push_str(&format!("'{}': import_{}, ", entry.module, name));
184        }
185
186        for entry in self.module.exports.iter() {
187            exports.push_str("export let ");
188            exports.push_str(&entry.name);
189            exports.push_str(";\n");
190            set_exports.push_str(&entry.name);
191            set_exports.push_str(" = wasm.exports.");
192            set_exports.push_str(&entry.name);
193            set_exports.push_str(";\n");
194        }
195
196        // This is sort of tricky, but the gist of it is that if there's a start
197        // function we want to defer execution of the start function until after
198        // all our module's exports are bound. That way we'll execute it as soon
199        // as we're ready, but the module's imports and such will be able to
200        // work as everything is wired up.
201        //
202        // This ends up helping out in situations such as:
203        //
204        // * The start function calls an imported function
205        // * That imported function in turn tries to access the Wasm module
206        //
207        // If we don't do this then the second step won't work because the start
208        // function is automatically executed before the promise of
209        // instantiation resolves, meaning that we won't actually have anything
210        // bound for it to access.
211        //
212        // If we remove the start function here (via `unstart`) then we'll
213        // reexport it as `__wasm2es6js_start` so be manually executed here.
214        if self.unstart() {
215            set_exports.push_str("wasm.exports.__wasm2es6js_start();\n");
216        }
217
218        let inst = format!(
219            "
220            WebAssembly.instantiate(bytes,{{ {imports} }})
221                .then(obj => {{
222                    const wasm = obj.instance;
223                    {set_exports}
224                }})
225            ",
226            imports = imports,
227            set_exports = set_exports,
228        );
229        let wasm = self.module.emit_wasm();
230        let (bytes, booted) = if self.base64 {
231            (
232                format!(
233                    "
234                    let bytes;
235                    const base64 = \"{base64}\";
236                    if (typeof Buffer === 'undefined') {{
237                        bytes = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
238                    }} else {{
239                        bytes = Buffer.from(base64, 'base64');
240                    }}
241                    ",
242                    base64 = BASE64_STANDARD.encode(&wasm)
243                ),
244                inst,
245            )
246        } else if let Some(ref path) = self.fetch_path {
247            (
248                String::new(),
249                format!(
250                    "
251                    fetch('{path}')
252                        .then(res => res.arrayBuffer())
253                        .then(bytes => {inst})
254                    ",
255                    path = path,
256                    inst = inst
257                ),
258            )
259        } else {
260            bail!("the option --base64 or --fetch is required");
261        };
262        let js = format!(
263            "\
264            {js_imports}
265            {bytes}
266            export const booted = {booted};
267            {exports}
268            ",
269            bytes = bytes,
270            booted = booted,
271            js_imports = js_imports,
272            exports = exports,
273        );
274        let wasm = if self.base64 { None } else { Some(wasm) };
275        Ok((js, wasm))
276    }
277
278    /// See comments above for what this is doing, but in a nutshell this
279    /// removes the start section, if any, and moves it to an exported function.
280    /// Returns whether a start function was found and removed.
281    fn unstart(&mut self) -> bool {
282        let start = match self.module.start.take() {
283            Some(id) => id,
284            None => return false,
285        };
286        self.module.exports.add("__wasm2es6js_start", start);
287        true
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn test_push_index_identifier() {
297        fn index_identifier(i: usize) -> String {
298            let mut s = String::new();
299            push_index_identifier(i, &mut s);
300            s
301        }
302
303        assert_eq!(index_identifier(0), "a");
304        assert_eq!(index_identifier(1), "b");
305        assert_eq!(index_identifier(25), "z");
306        assert_eq!(index_identifier(26), "a1");
307        assert_eq!(index_identifier(27), "b1");
308        assert_eq!(index_identifier(51), "z1");
309        assert_eq!(index_identifier(52), "a2");
310        assert_eq!(index_identifier(53), "b2");
311        assert_eq!(index_identifier(260), "a10");
312        assert_eq!(index_identifier(261), "b10");
313    }
314}