1use anyhow::{bail, Context, Error};
2use std::collections::{BTreeMap, HashMap, HashSet};
3use std::env;
4use std::fs;
5use std::mem;
6use std::path::{Path, PathBuf};
7use std::str;
8use walrus::Module;
9
10pub(crate) const PLACEHOLDER_MODULE: &str = "__wbindgen_placeholder__";
11
12mod decode;
13mod descriptor;
14mod descriptors;
15mod externref;
16mod interpreter;
17mod intrinsic;
18mod js;
19mod multivalue;
20mod transforms;
21pub mod wasm2es6js;
22mod wasm_conventions;
23mod wit;
24
25pub struct Bindgen {
26 input: Input,
27 out_name: Option<String>,
28 mode: OutputMode,
29 debug: bool,
30 typescript: bool,
31 omit_imports: bool,
32 demangle: bool,
33 keep_lld_exports: bool,
34 keep_debug: bool,
35 remove_name_section: bool,
36 remove_producers_section: bool,
37 omit_default_module_path: bool,
38 emit_start: bool,
39 externref: bool,
40 multi_value: bool,
41 encode_into: EncodeInto,
42 split_linked_modules: bool,
43 generate_reset_state: bool,
44}
45
46pub struct Output {
47 module: walrus::Module,
48 stem: String,
49 generated: Generated,
50}
51
52struct Generated {
53 mode: OutputMode,
54 js: String,
55 ts: String,
56 start: Option<String>,
57 snippets: HashMap<String, Vec<String>>,
58 local_modules: HashMap<String, String>,
59 npm_dependencies: HashMap<String, (PathBuf, String)>,
60 typescript: bool,
61}
62
63#[derive(Clone)]
64enum OutputMode {
65 Bundler { browser_only: bool },
66 Web,
67 NoModules { global: String },
68 Node { module: bool },
69 Deno,
70 Module,
71}
72
73enum Input {
74 Path(PathBuf),
75 Module(Module, String),
76 Bytes(Vec<u8>, String),
77 None,
78}
79
80#[derive(Debug, Clone, Copy)]
81pub enum EncodeInto {
82 Test,
83 Always,
84 Never,
85}
86
87impl Bindgen {
88 pub fn new() -> Bindgen {
89 let externref =
90 env::var("WASM_BINDGEN_ANYREF").is_ok() || env::var("WASM_BINDGEN_EXTERNREF").is_ok();
91 let multi_value = env::var("WASM_BINDGEN_MULTI_VALUE").is_ok();
92 Bindgen {
93 input: Input::None,
94 out_name: None,
95 mode: OutputMode::Bundler {
96 browser_only: false,
97 },
98 debug: false,
99 typescript: false,
100 omit_imports: false,
101 demangle: true,
102 keep_lld_exports: false,
103 keep_debug: false,
104 remove_name_section: false,
105 remove_producers_section: false,
106 emit_start: true,
107 externref,
108 multi_value,
109 encode_into: EncodeInto::Test,
110 omit_default_module_path: true,
111 split_linked_modules: false,
112 generate_reset_state: false,
113 }
114 }
115
116 pub fn input_path<P: AsRef<Path>>(&mut self, path: P) -> &mut Bindgen {
117 self.input = Input::Path(path.as_ref().to_path_buf());
118 self
119 }
120
121 pub fn out_name(&mut self, name: &str) -> &mut Bindgen {
122 self.out_name = Some(name.to_string());
123 self
124 }
125
126 #[deprecated = "automatically detected via `-Ctarget-feature=+reference-types`"]
127 pub fn reference_types(&mut self, enable: bool) -> &mut Bindgen {
128 self.externref = enable;
129 self
130 }
131
132 pub fn input_module(&mut self, name: &str, module: Module) -> &mut Bindgen {
134 let name = name.to_string();
135 self.input = Input::Module(module, name);
136 self
137 }
138
139 pub fn input_bytes(&mut self, name: &str, bytes: Vec<u8>) -> &mut Bindgen {
141 let name = name.to_string();
142 self.input = Input::Bytes(bytes, name);
143 self
144 }
145
146 fn switch_mode(&mut self, mode: OutputMode, flag: &str) -> Result<(), Error> {
147 match self.mode {
148 OutputMode::Bundler { .. } => self.mode = mode,
149 _ => bail!(
150 "cannot specify `{}` with another output mode already specified",
151 flag
152 ),
153 }
154 Ok(())
155 }
156
157 pub fn nodejs(&mut self, node: bool) -> Result<&mut Bindgen, Error> {
158 if node {
159 self.switch_mode(OutputMode::Node { module: false }, "--target nodejs")?;
160 }
161 Ok(self)
162 }
163
164 pub fn nodejs_module(&mut self, node: bool) -> Result<&mut Bindgen, Error> {
165 if node {
166 self.switch_mode(
167 OutputMode::Node { module: true },
168 "--target experimental-nodejs-module",
169 )?;
170 }
171 Ok(self)
172 }
173
174 pub fn bundler(&mut self, bundler: bool) -> Result<&mut Bindgen, Error> {
175 if bundler {
176 self.switch_mode(
177 OutputMode::Bundler {
178 browser_only: false,
179 },
180 "--target bundler",
181 )?;
182 }
183 Ok(self)
184 }
185
186 pub fn web(&mut self, web: bool) -> Result<&mut Bindgen, Error> {
187 if web {
188 self.switch_mode(OutputMode::Web, "--target web")?;
189 }
190 Ok(self)
191 }
192
193 pub fn no_modules(&mut self, no_modules: bool) -> Result<&mut Bindgen, Error> {
194 if no_modules {
195 self.switch_mode(
196 OutputMode::NoModules {
197 global: "wasm_bindgen".to_string(),
198 },
199 "--target no-modules",
200 )?;
201 }
202 Ok(self)
203 }
204
205 pub fn browser(&mut self, browser: bool) -> Result<&mut Bindgen, Error> {
206 if browser {
207 match &mut self.mode {
208 OutputMode::Bundler { browser_only } => *browser_only = true,
209 _ => bail!("cannot specify `--browser` with other output types"),
210 }
211 }
212 Ok(self)
213 }
214
215 pub fn deno(&mut self, deno: bool) -> Result<&mut Bindgen, Error> {
216 if deno {
217 self.switch_mode(OutputMode::Deno, "--target deno")?;
218 self.encode_into(EncodeInto::Always);
219 }
220 Ok(self)
221 }
222
223 pub fn module(&mut self, source_phase: bool) -> Result<&mut Bindgen, Error> {
224 if source_phase {
225 self.switch_mode(OutputMode::Module, "--target module")?;
226 }
227 Ok(self)
228 }
229
230 pub fn no_modules_global(&mut self, name: &str) -> Result<&mut Bindgen, Error> {
231 match &mut self.mode {
232 OutputMode::NoModules { global } => *global = name.to_string(),
233 _ => bail!("can only specify `--no-modules-global` with `--target no-modules`"),
234 }
235 Ok(self)
236 }
237
238 pub fn debug(&mut self, debug: bool) -> &mut Bindgen {
239 self.debug = debug;
240 self
241 }
242
243 pub fn typescript(&mut self, typescript: bool) -> &mut Bindgen {
244 self.typescript = typescript;
245 self
246 }
247
248 pub fn omit_imports(&mut self, omit_imports: bool) -> &mut Bindgen {
249 self.omit_imports = omit_imports;
250 self
251 }
252
253 pub fn demangle(&mut self, demangle: bool) -> &mut Bindgen {
254 self.demangle = demangle;
255 self
256 }
257
258 pub fn keep_lld_exports(&mut self, keep_lld_exports: bool) -> &mut Bindgen {
259 self.keep_lld_exports = keep_lld_exports;
260 self
261 }
262
263 pub fn keep_debug(&mut self, keep_debug: bool) -> &mut Bindgen {
264 self.keep_debug = keep_debug;
265 self
266 }
267
268 pub fn remove_name_section(&mut self, remove: bool) -> &mut Bindgen {
269 self.remove_name_section = remove;
270 self
271 }
272
273 pub fn remove_producers_section(&mut self, remove: bool) -> &mut Bindgen {
274 self.remove_producers_section = remove;
275 self
276 }
277
278 pub fn emit_start(&mut self, emit: bool) -> &mut Bindgen {
279 self.emit_start = emit;
280 self
281 }
282
283 pub fn encode_into(&mut self, mode: EncodeInto) -> &mut Bindgen {
284 self.encode_into = mode;
285 self
286 }
287
288 pub fn omit_default_module_path(&mut self, omit_default_module_path: bool) -> &mut Bindgen {
289 self.omit_default_module_path = omit_default_module_path;
290 self
291 }
292
293 pub fn split_linked_modules(&mut self, split_linked_modules: bool) -> &mut Bindgen {
294 self.split_linked_modules = split_linked_modules;
295 self
296 }
297
298 pub fn reset_state_function(&mut self, generate_reset_state: bool) -> &mut Bindgen {
299 self.generate_reset_state = generate_reset_state;
300 self
301 }
302
303 pub fn generate<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
304 self.generate_output()?.emit(path.as_ref())
305 }
306
307 pub fn stem(&self) -> Result<&str, Error> {
308 Ok(match &self.input {
309 Input::None => bail!("must have an input by now"),
310 Input::Module(_, name) | Input::Bytes(_, name) => name,
311 Input::Path(path) => match &self.out_name {
312 Some(name) => name,
313 None => path.file_stem().unwrap().to_str().unwrap(),
314 },
315 })
316 }
317
318 pub fn generate_output(&mut self) -> Result<Output, Error> {
319 let mut module = match self.input {
320 Input::None => bail!("must have an input by now"),
321 Input::Module(ref mut m, _) => {
322 let blank_module = Module::default();
323 mem::replace(m, blank_module)
324 }
325 Input::Path(ref path) => {
326 let bytes = std::fs::read(path)
327 .with_context(|| format!("failed reading '{}'", path.display()))?;
328 self.module_from_bytes(&bytes).with_context(|| {
329 format!("failed getting Wasm module for '{}'", path.display())
330 })?
331 }
332 Input::Bytes(ref bytes, _) => self
333 .module_from_bytes(bytes)
334 .context("failed getting Wasm module")?,
335 };
336
337 if let Ok(true) = wasm_conventions::target_feature(&module, "reference-types") {
339 self.externref = true;
340 }
341
342 if let Ok(true) = wasm_conventions::target_feature(&module, "multivalue") {
344 self.multi_value = true;
345 }
346
347 if matches!(self.mode, OutputMode::Web)
349 && module.exports.iter().any(|export| export.name == "default")
350 {
351 bail!("exported symbol \"default\" not allowed for --target web")
352 }
353
354 if self.generate_reset_state && !matches!(self.mode, OutputMode::Module) {
356 bail!("--experimental-reset-state-function is only supported for --target module")
357 }
358
359 let thread_count = transforms::threads::run(&mut module)
360 .with_context(|| "failed to prepare module for threading")?;
361
362 if self.demangle {
365 demangle(&mut module);
366 }
367 if !self.keep_lld_exports {
368 unexported_unused_lld_things(&mut module);
369 }
370
371 module
373 .producers
374 .add_processed_by("wasm-bindgen", &wasm_bindgen_shared::version());
375
376 let mut storage = Vec::new();
385 let programs = wit::extract_programs(&mut module, &mut storage)?;
386
387 descriptors::execute(&mut module)?;
392
393 wit::process(self, &mut module, programs, thread_count)?;
399
400 if self.externref {
410 externref::process(&mut module)?;
411 } else {
412 let ids = module
413 .exports
414 .iter()
415 .filter(|e| e.name.starts_with("__externref"))
416 .map(|e| e.id())
417 .collect::<Vec<_>>();
418 for id in ids {
419 module.exports.delete(id);
420 }
421 externref::force_contiguous_elements(&mut module)?;
426 }
427
428 if self.multi_value {
431 multivalue::run(&mut module)
432 .context("failed to transform return pointers into multi-value Wasm")?;
433 }
434
435 gc_module_and_adapters(&mut module);
439
440 let stem = self.stem()?;
441
442 let aux = module
444 .customs
445 .delete_typed::<wit::WasmBindgenAux>()
446 .expect("aux section should be present");
447 let adapters = module
448 .customs
449 .delete_typed::<wit::NonstandardWitSection>()
450 .unwrap();
451 let mut cx = js::Context::new(&mut module, self, &adapters, &aux)?;
452 cx.generate()?;
453 let (js, ts, start) = cx.finalize(stem)?;
454 let generated = Generated {
455 snippets: aux.snippets.clone(),
456 local_modules: aux.local_modules.clone(),
457 mode: self.mode.clone(),
458 typescript: self.typescript,
459 npm_dependencies: cx.npm_dependencies.clone(),
460 js,
461 ts,
462 start,
463 };
464
465 Ok(Output {
466 module,
467 stem: stem.to_string(),
468 generated,
469 })
470 }
471
472 fn module_from_bytes(&self, bytes: &[u8]) -> Result<Module, Error> {
473 walrus::ModuleConfig::new()
474 .strict_validate(false)
481 .generate_dwarf(self.keep_debug)
482 .generate_name_section(!self.remove_name_section)
483 .generate_producers_section(!self.remove_producers_section)
484 .parse(bytes)
485 .context("failed to parse input as wasm")
486 }
487
488 fn local_module_name(&self, module: &str) -> String {
489 format!("./snippets/{module}")
490 }
491
492 fn inline_js_module_name(
493 &self,
494 unique_crate_identifier: &str,
495 snippet_idx_in_crate: usize,
496 ) -> String {
497 format!("./snippets/{unique_crate_identifier}/inline{snippet_idx_in_crate}.js",)
498 }
499}
500
501fn reset_indentation(s: &str) -> String {
502 let mut indent: u32 = 0;
503 let mut dst = String::new();
504
505 fn is_doc_comment(line: &str) -> bool {
506 line.starts_with("*")
507 }
508
509 for line in s.lines() {
510 let line = line.trim();
511
512 if is_doc_comment(line) {
514 for _ in 0..indent {
515 dst.push_str(" ");
516 }
517 dst.push(' ');
518 dst.push_str(line);
519 dst.push('\n');
520 continue;
521 }
522
523 if line.starts_with('}') {
524 indent = indent.saturating_sub(1);
525 }
526
527 let extra = if line.starts_with(':') || line.starts_with('?') {
528 1
529 } else {
530 0
531 };
532 if !line.is_empty() {
533 for _ in 0..indent + extra {
534 dst.push_str(" ");
535 }
536 dst.push_str(line);
537 }
538 dst.push('\n');
539
540 if line.ends_with('{') {
541 indent += 1;
542 }
543 }
544 dst
545}
546
547fn demangle(module: &mut Module) {
548 for func in module.funcs.iter_mut() {
549 let name = match &func.name {
550 Some(name) => name,
551 None => continue,
552 };
553 if let Ok(sym) = rustc_demangle::try_demangle(name) {
554 func.name = Some(sym.to_string());
555 }
556 }
557}
558
559impl OutputMode {
560 fn uses_es_modules(&self) -> bool {
561 matches!(
562 self,
563 OutputMode::Bundler { .. }
564 | OutputMode::Web
565 | OutputMode::Node { module: true }
566 | OutputMode::Deno
567 )
568 }
569
570 fn nodejs(&self) -> bool {
571 matches!(self, OutputMode::Node { .. })
572 }
573
574 fn no_modules(&self) -> bool {
575 matches!(self, OutputMode::NoModules { .. })
576 }
577
578 fn esm_integration(&self) -> bool {
579 matches!(
580 self,
581 OutputMode::Bundler { .. } | OutputMode::Node { module: true }
582 )
583 }
584}
585
586fn unexported_unused_lld_things(module: &mut Module) {
590 let mut to_remove = Vec::new();
591 for export in module.exports.iter() {
592 match export.name.as_str() {
593 "__heap_base" | "__data_end" | "__indirect_function_table" => {
594 to_remove.push(export.id());
595 }
596 _ => {}
597 }
598 }
599 for id in to_remove {
600 module.exports.delete(id);
601 }
602}
603
604impl Output {
605 pub fn js(&self) -> &str {
606 &self.generated.js
607 }
608
609 pub fn ts(&self) -> Option<&str> {
610 if self.generated.typescript {
611 Some(&self.generated.ts)
612 } else {
613 None
614 }
615 }
616
617 pub fn start(&self) -> Option<&String> {
618 self.generated.start.as_ref()
619 }
620
621 pub fn snippets(&self) -> &HashMap<String, Vec<String>> {
622 &self.generated.snippets
623 }
624
625 pub fn local_modules(&self) -> &HashMap<String, String> {
626 &self.generated.local_modules
627 }
628
629 pub fn npm_dependencies(&self) -> &HashMap<String, (PathBuf, String)> {
630 &self.generated.npm_dependencies
631 }
632
633 pub fn wasm(&self) -> &walrus::Module {
634 &self.module
635 }
636
637 pub fn wasm_mut(&mut self) -> &mut walrus::Module {
638 &mut self.module
639 }
640
641 pub fn emit(&mut self, out_dir: impl AsRef<Path>) -> Result<(), Error> {
642 self._emit(out_dir.as_ref())
643 }
644
645 fn _emit(&mut self, out_dir: &Path) -> Result<(), Error> {
646 let wasm_name = format!("{}_bg", self.stem);
647 let wasm_path = out_dir.join(&wasm_name).with_extension("wasm");
648 fs::create_dir_all(out_dir)?;
649 let wasm_bytes = self.module.emit_wasm();
650 fs::write(&wasm_path, wasm_bytes)
651 .with_context(|| format!("failed to write `{}`", wasm_path.display()))?;
652
653 let gen = &self.generated;
654
655 for (identifier, list) in gen.snippets.iter() {
658 for (i, js) in list.iter().enumerate() {
659 let name = format!("inline{i}.js");
660 let path = out_dir.join("snippets").join(identifier).join(name);
661 fs::create_dir_all(path.parent().unwrap())?;
662 fs::write(&path, js)
663 .with_context(|| format!("failed to write `{}`", path.display()))?;
664 }
665 }
666
667 for (path, contents) in gen.local_modules.iter() {
668 let path = out_dir.join("snippets").join(path);
669 fs::create_dir_all(path.parent().unwrap())?;
670 fs::write(&path, contents)
671 .with_context(|| format!("failed to write `{}`", path.display()))?;
672 }
673
674 let is_genmode_nodemodule = matches!(gen.mode, OutputMode::Node { module: true });
675 if !gen.npm_dependencies.is_empty() || is_genmode_nodemodule {
676 #[derive(serde::Serialize)]
677 struct PackageJson<'a> {
678 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
679 ty: Option<&'static str>,
680 dependencies: BTreeMap<&'a str, &'a str>,
681 }
682 let pj = PackageJson {
683 ty: is_genmode_nodemodule.then_some("module"),
684 dependencies: gen
685 .npm_dependencies
686 .iter()
687 .map(|(k, v)| (k.as_str(), v.1.as_str()))
688 .collect(),
689 };
690 let json = serde_json::to_string_pretty(&pj)?;
691 fs::write(out_dir.join("package.json"), json)?;
692 }
693
694 let extension = "js";
697
698 fn write<P, C>(path: P, contents: C) -> Result<(), anyhow::Error>
699 where
700 P: AsRef<Path>,
701 C: AsRef<[u8]>,
702 {
703 fs::write(&path, contents)
704 .with_context(|| format!("failed to write `{}`", path.as_ref().display()))
705 }
706
707 let js_path = out_dir.join(&self.stem).with_extension(extension);
708
709 if matches!(&gen.mode, OutputMode::Module) {
710 let wasm_name = format!("{}_bg", self.stem);
711 let start = gen.start.as_deref().unwrap_or("");
712
713 write(
714 &js_path,
715 format!(
716 "\
717import source wasmModule from \"./{wasm_name}.wasm\";
718
719{start}{}",
720 reset_indentation(&gen.js)
721 ),
722 )?;
723 } else if gen.mode.esm_integration() {
724 let js_name = format!("{}_bg.{}", self.stem, extension);
725
726 let start = gen.start.as_deref().unwrap_or("");
727
728 if matches!(gen.mode, OutputMode::Node { .. }) {
729 write(
730 &js_path,
731 format!(
732 "\
733{start}
734export * from \"./{js_name}\";",
735 ),
736 )?;
737 } else {
738 write(
739 &js_path,
740 format!(
741 "\
742import * as wasm from \"./{wasm_name}.wasm\";
743export * from \"./{js_name}\";
744{start}"
745 ),
746 )?;
747 }
748 write(out_dir.join(&js_name), reset_indentation(&gen.js))?;
749 } else {
750 write(&js_path, reset_indentation(&gen.js))?;
751 }
752
753 if gen.typescript {
754 let ts_path = js_path.with_extension("d.ts");
755 fs::write(&ts_path, &gen.ts)
756 .with_context(|| format!("failed to write `{}`", ts_path.display()))?;
757 }
758
759 if gen.typescript {
760 let ts_path = wasm_path.with_extension("wasm.d.ts");
761 let ts = wasm2es6js::typescript(&self.module)?;
762 fs::write(&ts_path, ts)
763 .with_context(|| format!("failed to write `{}`", ts_path.display()))?;
764 }
765
766 Ok(())
767 }
768}
769
770fn gc_module_and_adapters(module: &mut Module) {
771 loop {
772 walrus::passes::gc::run(module);
776
777 let imports_remaining = module
780 .imports
781 .iter()
782 .map(|i| i.id())
783 .collect::<HashSet<_>>();
784 let mut section = module
785 .customs
786 .delete_typed::<wit::NonstandardWitSection>()
787 .unwrap();
788 section
789 .implements
790 .retain(|pair| imports_remaining.contains(&pair.0));
791
792 let any_removed = section.gc();
798 module.customs.add(*section);
799 if !any_removed {
800 break;
801 }
802 }
803}
804
805fn sorted_iter<K, V>(map: &HashMap<K, V>) -> impl Iterator<Item = (&K, &V)>
812where
813 K: Ord,
814{
815 let mut pairs = map.iter().collect::<Vec<_>>();
816 pairs.sort_by_key(|(k, _)| *k);
817 pairs.into_iter()
818}