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: BTreeMap<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!("cannot specify `{flag}` with another output mode already specified"),
150 }
151 Ok(())
152 }
153
154 pub fn nodejs(&mut self, node: bool) -> Result<&mut Bindgen, Error> {
155 if node {
156 self.switch_mode(OutputMode::Node { module: false }, "--target nodejs")?;
157 }
158 Ok(self)
159 }
160
161 pub fn nodejs_module(&mut self, node: bool) -> Result<&mut Bindgen, Error> {
162 if node {
163 self.switch_mode(
164 OutputMode::Node { module: true },
165 "--target experimental-nodejs-module",
166 )?;
167 }
168 Ok(self)
169 }
170
171 pub fn bundler(&mut self, bundler: bool) -> Result<&mut Bindgen, Error> {
172 if bundler {
173 self.switch_mode(
174 OutputMode::Bundler {
175 browser_only: false,
176 },
177 "--target bundler",
178 )?;
179 }
180 Ok(self)
181 }
182
183 pub fn web(&mut self, web: bool) -> Result<&mut Bindgen, Error> {
184 if web {
185 self.switch_mode(OutputMode::Web, "--target web")?;
186 }
187 Ok(self)
188 }
189
190 pub fn no_modules(&mut self, no_modules: bool) -> Result<&mut Bindgen, Error> {
191 if no_modules {
192 self.switch_mode(
193 OutputMode::NoModules {
194 global: "wasm_bindgen".to_string(),
195 },
196 "--target no-modules",
197 )?;
198 }
199 Ok(self)
200 }
201
202 pub fn browser(&mut self, browser: bool) -> Result<&mut Bindgen, Error> {
203 if browser {
204 match &mut self.mode {
205 OutputMode::Bundler { browser_only } => *browser_only = true,
206 _ => bail!("cannot specify `--browser` with other output types"),
207 }
208 }
209 Ok(self)
210 }
211
212 pub fn deno(&mut self, deno: bool) -> Result<&mut Bindgen, Error> {
213 if deno {
214 self.switch_mode(OutputMode::Deno, "--target deno")?;
215 self.encode_into(EncodeInto::Always);
216 }
217 Ok(self)
218 }
219
220 pub fn module(&mut self, source_phase: bool) -> Result<&mut Bindgen, Error> {
221 if source_phase {
222 self.switch_mode(OutputMode::Module, "--target module")?;
223 }
224 Ok(self)
225 }
226
227 pub fn no_modules_global(&mut self, name: &str) -> Result<&mut Bindgen, Error> {
228 match &mut self.mode {
229 OutputMode::NoModules { global } => *global = name.to_string(),
230 _ => bail!("can only specify `--no-modules-global` with `--target no-modules`"),
231 }
232 Ok(self)
233 }
234
235 pub fn debug(&mut self, debug: bool) -> &mut Bindgen {
236 self.debug = debug;
237 self
238 }
239
240 pub fn typescript(&mut self, typescript: bool) -> &mut Bindgen {
241 self.typescript = typescript;
242 self
243 }
244
245 pub fn omit_imports(&mut self, omit_imports: bool) -> &mut Bindgen {
246 self.omit_imports = omit_imports;
247 self
248 }
249
250 pub fn demangle(&mut self, demangle: bool) -> &mut Bindgen {
251 self.demangle = demangle;
252 self
253 }
254
255 pub fn keep_lld_exports(&mut self, keep_lld_exports: bool) -> &mut Bindgen {
256 self.keep_lld_exports = keep_lld_exports;
257 self
258 }
259
260 pub fn keep_debug(&mut self, keep_debug: bool) -> &mut Bindgen {
261 self.keep_debug = keep_debug;
262 self
263 }
264
265 pub fn remove_name_section(&mut self, remove: bool) -> &mut Bindgen {
266 self.remove_name_section = remove;
267 self
268 }
269
270 pub fn remove_producers_section(&mut self, remove: bool) -> &mut Bindgen {
271 self.remove_producers_section = remove;
272 self
273 }
274
275 pub fn emit_start(&mut self, emit: bool) -> &mut Bindgen {
276 self.emit_start = emit;
277 self
278 }
279
280 pub fn encode_into(&mut self, mode: EncodeInto) -> &mut Bindgen {
281 self.encode_into = mode;
282 self
283 }
284
285 pub fn omit_default_module_path(&mut self, omit_default_module_path: bool) -> &mut Bindgen {
286 self.omit_default_module_path = omit_default_module_path;
287 self
288 }
289
290 pub fn split_linked_modules(&mut self, split_linked_modules: bool) -> &mut Bindgen {
291 self.split_linked_modules = split_linked_modules;
292 self
293 }
294
295 pub fn reset_state_function(&mut self, generate_reset_state: bool) -> &mut Bindgen {
296 self.generate_reset_state = generate_reset_state;
297 self
298 }
299
300 pub fn generate<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
301 self.generate_output()?.emit(path.as_ref())
302 }
303
304 pub fn stem(&self) -> Result<&str, Error> {
305 Ok(match &self.input {
306 Input::None => bail!("must have an input by now"),
307 Input::Module(_, name) | Input::Bytes(_, name) => name,
308 Input::Path(path) => match &self.out_name {
309 Some(name) => name,
310 None => path.file_stem().unwrap().to_str().unwrap(),
311 },
312 })
313 }
314
315 pub fn generate_output(&mut self) -> Result<Output, Error> {
316 let mut module = match self.input {
317 Input::None => bail!("must have an input by now"),
318 Input::Module(ref mut m, _) => {
319 let blank_module = Module::default();
320 mem::replace(m, blank_module)
321 }
322 Input::Path(ref path) => {
323 let bytes = std::fs::read(path)
324 .with_context(|| format!("failed reading '{}'", path.display()))?;
325 self.module_from_bytes(&bytes).with_context(|| {
326 format!("failed getting Wasm module for '{}'", path.display())
327 })?
328 }
329 Input::Bytes(ref bytes, _) => self
330 .module_from_bytes(bytes)
331 .context("failed getting Wasm module")?,
332 };
333
334 if let Ok(true) = wasm_conventions::target_feature(&module, "reference-types") {
336 self.externref = true;
337 }
338
339 if let Ok(true) = wasm_conventions::target_feature(&module, "multivalue") {
341 self.multi_value = true;
342 }
343
344 if matches!(self.mode, OutputMode::Web)
346 && module.exports.iter().any(|export| export.name == "default")
347 {
348 bail!("exported symbol \"default\" not allowed for --target web")
349 }
350
351 if self.generate_reset_state && !matches!(self.mode, OutputMode::Module) {
353 bail!("--experimental-reset-state-function is only supported for --target module")
354 }
355
356 let thread_count = transforms::threads::run(&mut module)
357 .with_context(|| "failed to prepare module for threading")?;
358
359 if self.demangle {
362 demangle(&mut module);
363 }
364 if !self.keep_lld_exports {
365 unexported_unused_lld_things(&mut module);
366 }
367
368 module
370 .producers
371 .add_processed_by("wasm-bindgen", &wasm_bindgen_shared::version());
372
373 let mut storage = Vec::new();
382 let programs = wit::extract_programs(&mut module, &mut storage)?;
383
384 descriptors::execute(&mut module)?;
389
390 wit::process(self, &mut module, programs, thread_count)?;
396
397 if self.externref {
407 externref::process(&mut module)?;
408 } else {
409 let ids = module
410 .exports
411 .iter()
412 .filter(|e| e.name.starts_with("__externref"))
413 .map(|e| e.id())
414 .collect::<Vec<_>>();
415 for id in ids {
416 module.exports.delete(id);
417 }
418 externref::force_contiguous_elements(&mut module)?;
423 }
424
425 if self.multi_value {
428 multivalue::run(&mut module)
429 .context("failed to transform return pointers into multi-value Wasm")?;
430 }
431
432 gc_module_and_adapters(&mut module);
436
437 let stem = self.stem()?;
438
439 let aux = module
441 .customs
442 .delete_typed::<wit::WasmBindgenAux>()
443 .expect("aux section should be present");
444 let adapters = module
445 .customs
446 .delete_typed::<wit::NonstandardWitSection>()
447 .unwrap();
448 let mut cx = js::Context::new(&mut module, self, &adapters, &aux)?;
449 cx.generate()?;
450 let (js, ts, start) = cx.finalize(stem)?;
451 let generated = Generated {
452 snippets: aux.snippets.clone(),
453 local_modules: aux.local_modules.clone(),
454 mode: self.mode.clone(),
455 typescript: self.typescript,
456 npm_dependencies: cx.npm_dependencies.clone(),
457 js,
458 ts,
459 start,
460 };
461
462 Ok(Output {
463 module,
464 stem: stem.to_string(),
465 generated,
466 })
467 }
468
469 fn module_from_bytes(&self, bytes: &[u8]) -> Result<Module, Error> {
470 walrus::ModuleConfig::new()
471 .strict_validate(false)
478 .generate_dwarf(self.keep_debug)
479 .generate_name_section(!self.remove_name_section)
480 .generate_producers_section(!self.remove_producers_section)
481 .parse(bytes)
482 .context("failed to parse input as wasm")
483 }
484
485 fn local_module_name(&self, module: &str) -> String {
486 format!("./snippets/{module}")
487 }
488
489 fn inline_js_module_name(
490 &self,
491 unique_crate_identifier: &str,
492 snippet_idx_in_crate: usize,
493 ) -> String {
494 format!("./snippets/{unique_crate_identifier}/inline{snippet_idx_in_crate}.js",)
495 }
496}
497
498fn reset_indentation(s: &str) -> String {
499 let mut indent: u32 = 0;
500 let mut dst = String::new();
501
502 fn is_doc_comment(line: &str) -> bool {
503 line.starts_with("*")
504 }
505
506 for line in s.lines() {
507 let line = line.trim();
508
509 if is_doc_comment(line) {
511 for _ in 0..indent {
512 dst.push_str(" ");
513 }
514 dst.push(' ');
515 dst.push_str(line);
516 dst.push('\n');
517 continue;
518 }
519
520 if line.starts_with('}') {
521 indent = indent.saturating_sub(1);
522 }
523
524 let extra = if line.starts_with(':') || line.starts_with('?') {
525 1
526 } else {
527 0
528 };
529 if !line.is_empty() {
530 for _ in 0..indent + extra {
531 dst.push_str(" ");
532 }
533 dst.push_str(line);
534 }
535 dst.push('\n');
536
537 if line.ends_with('{') {
538 indent += 1;
539 }
540 }
541 dst
542}
543
544fn demangle(module: &mut Module) {
550 let (lower, upper) = module.funcs.iter().size_hint();
551 let mut counter: HashMap<String, i32> = HashMap::with_capacity(upper.unwrap_or(lower));
552
553 for func in module.funcs.iter_mut() {
554 let Some(name) = &func.name else {
555 continue;
556 };
557
558 let Ok(sym) = rustc_demangle::try_demangle(name) else {
559 continue;
560 };
561
562 let count = counter.entry(sym.to_string()).or_insert(0);
563
564 func.name = Some(if *count > 0 {
565 format!("{sym}[{count}]")
566 } else {
567 sym.to_string()
568 });
569
570 *count += 1;
571 }
572}
573
574impl OutputMode {
575 fn uses_es_modules(&self) -> bool {
576 matches!(
577 self,
578 OutputMode::Bundler { .. }
579 | OutputMode::Web
580 | OutputMode::Node { module: true }
581 | OutputMode::Deno
582 )
583 }
584
585 fn nodejs(&self) -> bool {
586 matches!(self, OutputMode::Node { .. })
587 }
588
589 fn no_modules(&self) -> bool {
590 matches!(self, OutputMode::NoModules { .. })
591 }
592
593 fn esm_integration(&self) -> bool {
594 matches!(
595 self,
596 OutputMode::Bundler { .. } | OutputMode::Node { module: true }
597 )
598 }
599}
600
601fn unexported_unused_lld_things(module: &mut Module) {
605 let mut to_remove = Vec::new();
606 for export in module.exports.iter() {
607 match export.name.as_str() {
608 "__heap_base" | "__data_end" | "__indirect_function_table" => {
609 to_remove.push(export.id());
610 }
611 _ => {}
612 }
613 }
614 for id in to_remove {
615 module.exports.delete(id);
616 }
617}
618
619impl Output {
620 pub fn js(&self) -> &str {
621 &self.generated.js
622 }
623
624 pub fn ts(&self) -> Option<&str> {
625 if self.generated.typescript {
626 Some(&self.generated.ts)
627 } else {
628 None
629 }
630 }
631
632 pub fn start(&self) -> Option<&String> {
633 self.generated.start.as_ref()
634 }
635
636 pub fn snippets(&self) -> &BTreeMap<String, Vec<String>> {
637 &self.generated.snippets
638 }
639
640 pub fn local_modules(&self) -> &HashMap<String, String> {
641 &self.generated.local_modules
642 }
643
644 pub fn npm_dependencies(&self) -> &HashMap<String, (PathBuf, String)> {
645 &self.generated.npm_dependencies
646 }
647
648 pub fn wasm(&self) -> &walrus::Module {
649 &self.module
650 }
651
652 pub fn wasm_mut(&mut self) -> &mut walrus::Module {
653 &mut self.module
654 }
655
656 pub fn emit(&mut self, out_dir: impl AsRef<Path>) -> Result<(), Error> {
657 self._emit(out_dir.as_ref())
658 }
659
660 fn _emit(&mut self, out_dir: &Path) -> Result<(), Error> {
661 let wasm_name = format!("{}_bg", self.stem);
662 let wasm_path = out_dir.join(&wasm_name).with_extension("wasm");
663 fs::create_dir_all(out_dir)?;
664 let wasm_bytes = self.module.emit_wasm();
665 fs::write(&wasm_path, wasm_bytes)
666 .with_context(|| format!("failed to write `{}`", wasm_path.display()))?;
667
668 let gen = &self.generated;
669
670 for (identifier, list) in gen.snippets.iter() {
673 for (i, js) in list.iter().enumerate() {
674 let name = format!("inline{i}.js");
675 let path = out_dir.join("snippets").join(identifier).join(name);
676 fs::create_dir_all(path.parent().unwrap())?;
677 fs::write(&path, js)
678 .with_context(|| format!("failed to write `{}`", path.display()))?;
679 }
680 }
681
682 for (path, contents) in gen.local_modules.iter() {
683 let path = out_dir.join("snippets").join(path);
684 fs::create_dir_all(path.parent().unwrap())?;
685 fs::write(&path, contents)
686 .with_context(|| format!("failed to write `{}`", path.display()))?;
687 }
688
689 let is_genmode_nodemodule = matches!(gen.mode, OutputMode::Node { module: true });
690 if !gen.npm_dependencies.is_empty() || is_genmode_nodemodule {
691 #[derive(serde::Serialize)]
692 struct PackageJson<'a> {
693 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
694 ty: Option<&'static str>,
695 dependencies: BTreeMap<&'a str, &'a str>,
696 }
697 let pj = PackageJson {
698 ty: is_genmode_nodemodule.then_some("module"),
699 dependencies: gen
700 .npm_dependencies
701 .iter()
702 .map(|(k, v)| (k.as_str(), v.1.as_str()))
703 .collect(),
704 };
705 let json = serde_json::to_string_pretty(&pj)?;
706 fs::write(out_dir.join("package.json"), json)?;
707 }
708
709 let extension = "js";
712
713 fn write<P, C>(path: P, contents: C) -> Result<(), anyhow::Error>
714 where
715 P: AsRef<Path>,
716 C: AsRef<[u8]>,
717 {
718 fs::write(&path, contents)
719 .with_context(|| format!("failed to write `{}`", path.as_ref().display()))
720 }
721
722 let js_path = out_dir.join(&self.stem).with_extension(extension);
723
724 if matches!(&gen.mode, OutputMode::Module) {
725 let wasm_name = format!("{}_bg", self.stem);
726 let start = gen.start.as_deref().unwrap_or("");
727
728 write(
729 &js_path,
730 format!(
731 "\
732import source wasmModule from \"./{wasm_name}.wasm\";
733
734{start}{}",
735 reset_indentation(&gen.js)
736 ),
737 )?;
738 } else if gen.mode.esm_integration() {
739 let js_name = format!("{}_bg.{extension}", self.stem);
740
741 let start = gen.start.as_deref().unwrap_or("");
742
743 if matches!(gen.mode, OutputMode::Node { .. }) {
744 write(
745 &js_path,
746 format!(
747 "\
748{start}
749export * from \"./{js_name}\";",
750 ),
751 )?;
752 } else {
753 write(
754 &js_path,
755 format!(
756 "\
757import * as wasm from \"./{wasm_name}.wasm\";
758export * from \"./{js_name}\";
759{start}"
760 ),
761 )?;
762 }
763 write(out_dir.join(&js_name), reset_indentation(&gen.js))?;
764 } else {
765 write(&js_path, reset_indentation(&gen.js))?;
766 }
767
768 if gen.typescript {
769 let ts_path = js_path.with_extension("d.ts");
770 fs::write(&ts_path, &gen.ts)
771 .with_context(|| format!("failed to write `{}`", ts_path.display()))?;
772 }
773
774 if gen.typescript {
775 let ts_path = wasm_path.with_extension("wasm.d.ts");
776 let ts = wasm2es6js::typescript(&self.module)?;
777 fs::write(&ts_path, ts)
778 .with_context(|| format!("failed to write `{}`", ts_path.display()))?;
779 }
780
781 Ok(())
782 }
783}
784
785fn gc_module_and_adapters(module: &mut Module) {
786 loop {
787 walrus::passes::gc::run(module);
791
792 let imports_remaining = module
795 .imports
796 .iter()
797 .map(|i| i.id())
798 .collect::<HashSet<_>>();
799 let mut section = module
800 .customs
801 .delete_typed::<wit::NonstandardWitSection>()
802 .unwrap();
803 section
804 .implements
805 .retain(|pair| imports_remaining.contains(&pair.0));
806
807 let any_removed = section.gc();
813 module.customs.add(*section);
814 if !any_removed {
815 break;
816 }
817 }
818}
819
820fn sorted_iter<K, V>(map: &HashMap<K, V>) -> impl Iterator<Item = (&K, &V)>
827where
828 K: Ord,
829{
830 let mut pairs = map.iter().collect::<Vec<_>>();
831 pairs.sort_by_key(|(k, _)| *k);
832 pairs.into_iter()
833}