1use anyhow::{bail, Context, Error};
2use std::collections::{hash_map::Entry, 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 static TAB: &str = " ";
507
508 for line in s.trim().lines() {
509 let line = line.trim();
510
511 if is_doc_comment(line) {
513 for _ in 0..indent {
514 dst.push_str(TAB);
515 }
516 dst.push(' ');
517 dst.push_str(line);
518 dst.push('\n');
519 continue;
520 }
521
522 if line.starts_with('}') {
523 indent = indent.saturating_sub(1);
524 }
525
526 let extra = if line.starts_with(':') || line.starts_with('?') {
527 1
528 } else {
529 0
530 };
531 if !line.is_empty() {
532 for _ in 0..indent + extra {
533 dst.push_str(TAB);
534 }
535 dst.push_str(line);
536 }
537 dst.push('\n');
538
539 if line.ends_with('{') {
540 indent += 1;
541 }
542 }
543 dst
544}
545
546fn demangle(module: &mut Module) {
552 let (lower, upper) = module.funcs.iter().size_hint();
553 let mut counter: HashMap<String, i32> = HashMap::with_capacity(upper.unwrap_or(lower));
554
555 for func in module.funcs.iter_mut() {
556 let Some(name) = &func.name else {
557 continue;
558 };
559
560 let Ok(sym) = rustc_demangle::try_demangle(name) else {
561 continue;
562 };
563
564 let demangled = sym.to_string();
565 match counter.entry(demangled) {
566 Entry::Occupied(mut entry) => {
567 func.name = Some(format!("{}[{}]", entry.key(), entry.get()));
568 *entry.get_mut() += 1;
569 }
570 Entry::Vacant(entry) => {
571 func.name = Some(entry.key().clone());
572 entry.insert(1);
573 }
574 }
575 }
576}
577
578impl OutputMode {
579 fn uses_es_modules(&self) -> bool {
580 matches!(
581 self,
582 OutputMode::Bundler { .. }
583 | OutputMode::Web
584 | OutputMode::Node { module: true }
585 | OutputMode::Deno
586 | OutputMode::Module
587 )
588 }
589
590 fn nodejs(&self) -> bool {
591 matches!(self, OutputMode::Node { .. })
592 }
593
594 fn no_modules(&self) -> bool {
595 matches!(self, OutputMode::NoModules { .. })
596 }
597
598 fn bundler(&self) -> bool {
599 matches!(self, OutputMode::Bundler { .. })
600 }
601}
602
603fn unexported_unused_lld_things(module: &mut Module) {
607 let mut to_remove = Vec::new();
608 for export in module.exports.iter() {
609 match export.name.as_str() {
610 "__heap_base" | "__data_end" | "__indirect_function_table" => {
611 to_remove.push(export.id());
612 }
613 _ => {}
614 }
615 }
616 for id in to_remove {
617 module.exports.delete(id);
618 }
619}
620
621impl Output {
622 pub fn js(&self) -> &str {
623 &self.generated.js
624 }
625
626 pub fn ts(&self) -> Option<&str> {
627 if self.generated.typescript {
628 Some(&self.generated.ts)
629 } else {
630 None
631 }
632 }
633
634 pub fn start(&self) -> Option<&String> {
635 self.generated.start.as_ref()
636 }
637
638 pub fn snippets(&self) -> &BTreeMap<String, Vec<String>> {
639 &self.generated.snippets
640 }
641
642 pub fn local_modules(&self) -> &HashMap<String, String> {
643 &self.generated.local_modules
644 }
645
646 pub fn npm_dependencies(&self) -> &HashMap<String, (PathBuf, String)> {
647 &self.generated.npm_dependencies
648 }
649
650 pub fn wasm(&self) -> &walrus::Module {
651 &self.module
652 }
653
654 pub fn wasm_mut(&mut self) -> &mut walrus::Module {
655 &mut self.module
656 }
657
658 pub fn emit(&mut self, out_dir: impl AsRef<Path>) -> Result<(), Error> {
659 self._emit(out_dir.as_ref())
660 }
661
662 fn _emit(&mut self, out_dir: &Path) -> Result<(), Error> {
663 let wasm_name = format!("{}_bg", self.stem);
664 let wasm_path = out_dir.join(&wasm_name).with_extension("wasm");
665 fs::create_dir_all(out_dir)?;
666
667 let wasm_bytes = self.module.emit_wasm();
668 fs::write(&wasm_path, wasm_bytes)
669 .with_context(|| format!("failed to write `{}`", wasm_path.display()))?;
670
671 let gen = &self.generated;
672
673 for (identifier, list) in gen.snippets.iter() {
676 for (i, js) in list.iter().enumerate() {
677 let name = format!("inline{i}.js");
678 let path = out_dir.join("snippets").join(identifier).join(name);
679 fs::create_dir_all(path.parent().unwrap())?;
680 fs::write(&path, js)
681 .with_context(|| format!("failed to write `{}`", path.display()))?;
682 }
683 }
684
685 for (path, contents) in gen.local_modules.iter() {
686 let path = out_dir.join("snippets").join(path);
687 fs::create_dir_all(path.parent().unwrap())?;
688 fs::write(&path, contents)
689 .with_context(|| format!("failed to write `{}`", path.display()))?;
690 }
691
692 let is_genmode_nodemodule = matches!(gen.mode, OutputMode::Node { module: true });
693 if !gen.npm_dependencies.is_empty() || is_genmode_nodemodule {
694 #[derive(serde::Serialize)]
695 struct PackageJson<'a> {
696 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
697 ty: Option<&'static str>,
698 dependencies: BTreeMap<&'a str, &'a str>,
699 }
700 let pj = PackageJson {
701 ty: is_genmode_nodemodule.then_some("module"),
702 dependencies: gen
703 .npm_dependencies
704 .iter()
705 .map(|(k, v)| (k.as_str(), v.1.as_str()))
706 .collect(),
707 };
708 let json = serde_json::to_string_pretty(&pj)?;
709 fs::write(out_dir.join("package.json"), json)?;
710 }
711
712 let extension = "js";
715
716 fn write<P, C>(path: P, contents: C) -> Result<(), anyhow::Error>
717 where
718 P: AsRef<Path>,
719 C: AsRef<[u8]>,
720 {
721 fs::write(&path, contents)
722 .with_context(|| format!("failed to write `{}`", path.as_ref().display()))
723 }
724
725 let js_path = out_dir.join(&self.stem).with_extension(extension);
726 write(&js_path, reset_indentation(&gen.js))?;
727
728 if let Some(start) = &gen.start {
729 let js_path = out_dir.join(wasm_name).with_extension(extension);
730 write(&js_path, reset_indentation(start))?;
731 }
732
733 if gen.typescript {
734 let ts_path = js_path.with_extension("d.ts");
735 fs::write(&ts_path, reset_indentation(&gen.ts))
736 .with_context(|| format!("failed to write `{}`", ts_path.display()))?;
737 }
738
739 if gen.typescript {
740 let ts_path = wasm_path.with_extension("wasm.d.ts");
741 let ts = wasm2es6js::typescript(&self.module)?;
742 fs::write(&ts_path, reset_indentation(&ts))
743 .with_context(|| format!("failed to write `{}`", ts_path.display()))?;
744 }
745
746 Ok(())
747 }
748}
749
750fn gc_module_and_adapters(module: &mut Module) {
751 loop {
752 walrus::passes::gc::run(module);
756
757 let imports_remaining = module
760 .imports
761 .iter()
762 .map(|i| i.id())
763 .collect::<HashSet<_>>();
764 let mut section = module
765 .customs
766 .delete_typed::<wit::NonstandardWitSection>()
767 .unwrap();
768 section
769 .implements
770 .retain(|pair| imports_remaining.contains(&pair.0));
771
772 let any_removed = section.gc();
778 module.customs.add(*section);
779 if !any_removed {
780 break;
781 }
782 }
783}
784
785fn sorted_iter<K, V>(map: &HashMap<K, V>) -> impl Iterator<Item = (&K, &V)>
792where
793 K: Ord,
794{
795 let mut pairs = map.iter().collect::<Vec<_>>();
796 pairs.sort_by_key(|(k, _)| *k);
797 pairs.into_iter()
798}