1use camino::Utf8PathBuf;
2use clap::{Args as ClapArgs, Parser, Subcommand};
3use eyre::Context as _;
4use std::str::FromStr;
5
6use crate::{generator::WasmPath, util::ResultUtil as _};
7
8#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct ModuleStackSize {
11 pub module: String,
13 pub bytes: u32,
15}
16
17impl FromStr for ModuleStackSize {
18 type Err = String;
19
20 fn from_str(value: &str) -> Result<Self, Self::Err> {
21 let (module, size) = value
22 .split_once('=')
23 .ok_or_else(|| "expected MODULE=SIZE".to_string())?;
24 if module.is_empty() {
25 return Err("module name must not be empty".to_string());
26 }
27
28 let size = size.trim();
29 let (digits, multiplier) = if let Some(digits) = size.strip_suffix("MiB") {
30 (digits, 1024_u64 * 1024)
31 } else if let Some(digits) = size.strip_suffix("KiB") {
32 (digits, 1024)
33 } else if let Some(digits) = size.strip_suffix("M") {
34 (digits, 1024_u64 * 1024)
35 } else if let Some(digits) = size.strip_suffix("K") {
36 (digits, 1024)
37 } else {
38 (size, 1)
39 };
40 let bytes = digits
41 .parse::<u64>()
42 .map_err(|_| format!("invalid stack size `{size}`"))?
43 .checked_mul(multiplier)
44 .ok_or_else(|| format!("stack size `{size}` overflows"))?;
45 let bytes = u32::try_from(bytes)
46 .map_err(|_| format!("stack size `{size}` exceeds the wasm32 address space"))?;
47 if bytes == 0 {
48 return Err("stack size must be greater than zero".to_string());
49 }
50
51 Ok(Self {
52 module: module.to_string(),
53 bytes,
54 })
55 }
56}
57
58#[derive(Clone, Debug, Eq, PartialEq)]
60pub struct ModuleStackSlots {
61 pub module: String,
63 pub slots: u32,
65}
66
67impl FromStr for ModuleStackSlots {
68 type Err = String;
69
70 fn from_str(value: &str) -> Result<Self, Self::Err> {
71 let (module, slots) = value
72 .split_once('=')
73 .ok_or_else(|| "expected MODULE=COUNT".to_string())?;
74 if module.is_empty() {
75 return Err("module name must not be empty".to_string());
76 }
77 let slots = slots
78 .parse::<u32>()
79 .map_err(|_| format!("invalid stack slot count `{slots}`"))?;
80 if slots == 0 {
81 return Err("stack slot count must be greater than zero".to_string());
82 }
83 Ok(Self {
84 module: module.to_string(),
85 slots,
86 })
87 }
88}
89
90#[derive(ClapArgs, Clone, Debug, Default)]
92pub struct StackOptions {
93 #[arg(long = "stack-size", value_name = "MODULE=SIZE")]
98 pub sizes: Vec<ModuleStackSize>,
99
100 #[arg(long = "stack-slots", value_name = "MODULE=COUNT")]
104 pub slots: Vec<ModuleStackSlots>,
105}
106
107pub trait PostBuildContext {
109 fn out_dir(&self) -> &Utf8PathBuf;
111 fn keep_build_artifacts(&self) -> bool;
113 fn adjust_abi(&self) -> bool;
115 fn transpile_to_js(
117 &self,
118 component: &[u8],
119 name: impl AsRef<str>,
120 ) -> Result<js_component_bindgen::Transpiled, eyre::Error>;
121 fn dev(&self) -> bool;
123}
124
125#[derive(Parser, Debug)]
127#[clap(author, version, about, long_about = None, help_template = "
128{name} {version}
129{author}
130{about}
131
132{usage-heading} {usage}
133
134{all-args}")]
135#[clap(propagate_version = true)]
136pub struct Cli {
137 #[clap(subcommand)]
139 pub command: Command,
140}
141
142#[derive(Subcommand, Debug)]
143#[clap(author, version, about, long_about = None, help_template = "
144{name} {version}
145{author}
146{about}
147
148{usage-heading} {usage}
149
150{all-args}")]
151pub enum Command {
153 Build(BuildArgs),
155 Prebuild(PreBuildArgs),
157 Postbuild(PostBuildArgs),
159 New(NewArgs),
161}
162
163#[derive(Parser, Debug)]
164#[clap(author, version, about, long_about = None, help_template = "
165{name} {version}
166{author}
167{about}
168
169{usage-heading} {usage}
170
171{all-args}")]
172pub struct NewArgs {
174 #[arg(value_name = "PATH")]
176 pub path: Utf8PathBuf,
177
178 #[arg(long, default_value = "false")]
180 pub threads: bool,
181}
182
183#[derive(Parser, Debug)]
184#[clap(author, version, about, long_about = None, help_template = "
185{name} {version}
186{author}
187{about}
188
189{usage-heading} {usage}
190
191{all-args}")]
192pub struct BuildArgs {
194 pub wasm: Vec<WasmPath>,
201
202 #[arg(short, long)]
204 package: Option<WasmPath>,
205
206 #[arg(long)]
208 pub manifest_path: Option<Utf8PathBuf>,
209
210 #[arg(long)]
212 wasm_memory_hint: Vec<isize>,
213
214 #[arg(long = "wasm-unwind")]
216 pub wasm_unwind: Vec<bool>,
217
218 #[arg(long, default_value = "./dist")]
220 pub out_dir: Utf8PathBuf,
221
222 #[arg(short, long)]
225 pub target_memory_type: Option<TargetMemoryType>,
226
227 #[command(flatten)]
230 pub transpile_opts: TranspileOpts,
231
232 #[arg(long)]
235 pub threads: Option<bool>,
236
237 #[arg(long)]
241 pub dwarf: Option<bool>,
242
243 #[arg(long, default_value = "false")]
246 pub adjust_abi: bool,
247
248 #[arg(long, default_value = "false")]
250 pub keep_build_artifacts: bool,
251
252 #[arg(long, default_value = "false")]
254 pub dev: bool,
255
256 #[command(flatten)]
258 pub vfs_build_opts: VfsBuildOptions,
259
260 #[arg(skip)]
262 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
263
264 #[arg(long, default_value = "false")]
266 pub own_memory: bool,
267
268 #[command(flatten)]
270 pub stack_options: StackOptions,
271}
272
273impl BuildArgs {
274 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
276 self.wasm_memory_hint
277 .iter()
278 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
279 .chain(std::iter::repeat(None))
280 .take(self.wasm.len())
281 .collect::<Box<_>>()
282 }
283
284 pub fn get_wasm_unwinds(&self) -> Box<[bool]> {
286 self.wasm_unwind
287 .iter()
288 .copied()
289 .chain(std::iter::repeat(false))
290 .take(self.wasm.len())
291 .collect::<Box<_>>()
292 }
293
294 pub fn get_package(&self) -> eyre::Result<WasmPath> {
296 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
297 if let Some(ref manifest) = self.manifest_path {
298 WasmPath::with_maybe_only_manifest(manifest.clone())
299 } else {
300 WasmPath::with_maybe_none()
301 }
302 })?;
303 if let Some(ref manifest) = self.manifest_path {
304 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
305 *manifest_path = manifest.clone();
306 }
307 }
308 Ok(p)
309 }
310
311 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
313 let mut paths = self.wasm.clone();
314 if let Some(ref manifest) = self.manifest_path {
315 for p in &mut paths {
316 if let WasmPath::Maybe { manifest_path, .. } = p {
317 *manifest_path = manifest.clone();
318 }
319 }
320 }
321 paths.into_boxed_slice()
322 }
323}
324
325impl PostBuildContext for BuildArgs {
326 fn out_dir(&self) -> &Utf8PathBuf {
327 &self.out_dir
328 }
329
330 fn keep_build_artifacts(&self) -> bool {
331 self.keep_build_artifacts
332 }
333
334 fn adjust_abi(&self) -> bool {
335 self.adjust_abi
336 }
337
338 fn transpile_to_js(
339 &self,
340 component: &[u8],
341 name: impl AsRef<str>,
342 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
343 self.transpile_opts.transpile_to_js(component, name)
344 }
345
346 fn dev(&self) -> bool {
347 self.dev
348 }
349}
350
351#[derive(Parser, Debug)]
352#[clap(author, version, about, long_about = None, help_template = "
353{name} {version}
354{author}
355{about}
356
357{usage-heading} {usage}
358
359{all-args}")]
360pub struct PreBuildArgs {
362 pub wasm: Vec<WasmPath>,
369
370 #[arg(short, long)]
372 package: Option<WasmPath>,
373
374 #[arg(long)]
376 pub manifest_path: Option<Utf8PathBuf>,
377
378 #[arg(long)]
380 wasm_memory_hint: Vec<isize>,
381
382 #[arg(long = "wasm-unwind")]
384 pub wasm_unwind: Vec<bool>,
385
386 #[arg(long, default_value = "./dist")]
388 pub out_dir: Utf8PathBuf,
389
390 #[arg(short, long)]
393 pub target_memory_type: Option<TargetMemoryType>,
394
395 #[arg(long)]
398 pub threads: Option<bool>,
399
400 #[arg(long)]
404 pub dwarf: Option<bool>,
405
406 #[arg(long, default_value = "false")]
409 pub adjust_abi: bool,
410
411 #[arg(long, default_value = "false")]
413 pub keep_build_artifacts: bool,
414
415 #[arg(long, default_value = "false")]
417 pub dev: bool,
418
419 #[command(flatten)]
421 pub vfs_build_opts: VfsBuildOptions,
422
423 #[arg(skip)]
425 pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
426
427 #[arg(long, default_value = "false")]
429 pub own_memory: bool,
430
431 #[command(flatten)]
433 pub stack_options: StackOptions,
434}
435
436impl PreBuildArgs {
437 pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
439 self.wasm_memory_hint
440 .iter()
441 .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
442 .chain(std::iter::repeat(None))
443 .take(self.wasm.len())
444 .collect::<Box<_>>()
445 }
446
447 pub fn get_wasm_unwinds(&self) -> Box<[bool]> {
449 self.wasm_unwind
450 .iter()
451 .copied()
452 .chain(std::iter::repeat(false))
453 .take(self.wasm.len())
454 .collect::<Box<_>>()
455 }
456
457 pub fn get_package(&self) -> eyre::Result<WasmPath> {
459 let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
460 if let Some(ref manifest) = self.manifest_path {
461 WasmPath::with_maybe_only_manifest(manifest.clone())
462 } else {
463 WasmPath::with_maybe_none()
464 }
465 })?;
466 if let Some(ref manifest) = self.manifest_path {
467 if let WasmPath::Maybe { manifest_path, .. } = &mut p {
468 *manifest_path = manifest.clone();
469 }
470 }
471 Ok(p)
472 }
473
474 pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
476 let mut paths = self.wasm.clone();
477 if let Some(ref manifest) = self.manifest_path {
478 for p in &mut paths {
479 if let WasmPath::Maybe { manifest_path, .. } = p {
480 *manifest_path = manifest.clone();
481 }
482 }
483 }
484 paths.into_boxed_slice()
485 }
486}
487
488#[derive(Parser, Debug)]
489#[clap(author, version, about, long_about = None, help_template = "
490{name} {version}
491{author}
492{about}
493
494{usage-heading} {usage}
495
496{all-args}")]
497pub struct PostBuildArgs {
499 #[arg(short, long)]
501 pub package: WasmPath,
502
503 #[arg(long, default_value = "./dist")]
505 pub out_dir: Utf8PathBuf,
506
507 #[command(flatten)]
509 pub transpile_opts: TranspileOpts,
510
511 #[arg(long)]
513 pub dwarf: Option<bool>,
514
515 #[arg(long, default_value = "false")]
518 pub adjust_abi: bool,
519
520 #[arg(long, default_value = "false")]
522 pub keep_build_artifacts: bool,
523
524 #[arg(long, default_value = "false")]
526 pub dev: bool,
527}
528
529impl PostBuildContext for PostBuildArgs {
530 fn out_dir(&self) -> &Utf8PathBuf {
531 &self.out_dir
532 }
533
534 fn keep_build_artifacts(&self) -> bool {
535 self.keep_build_artifacts
536 }
537
538 fn adjust_abi(&self) -> bool {
539 self.adjust_abi
540 }
541
542 fn transpile_to_js(
543 &self,
544 component: &[u8],
545 name: impl AsRef<str>,
546 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
547 self.transpile_opts.transpile_to_js(component, name)
548 }
549
550 fn dev(&self) -> bool {
551 self.dev
552 }
553}
554
555#[derive(Parser, Debug)]
557#[clap(author, version, about, long_about = None, help_template = "
558{name} {version}
559{author}
560{about}
561
562{usage-heading} {usage}
563
564{all-args}")]
565pub struct TranspileOpts {
566 #[arg(long, default_value = "false")]
568 no_typescript: bool,
569
570 #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
573 instantiation: CustomInstantiationMode,
574
575 #[arg(long, value_parser = analysis::analysis_import_bindings)]
577 import_bindings: Option<js_component_bindgen::BindingsMode>,
578
579 #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
581 map: Vec<(String, String)>,
582
583 #[arg(long, default_value = "false")]
585 no_nodejs_compat: bool,
586
587 #[arg(long, default_value = "0")]
589 base64_cutoff: usize,
590
591 #[arg(long, default_value = "false")]
593 tla_compat: bool,
594
595 #[arg(long, default_value = "false")]
597 valid_lifting_optimization: bool,
598
599 #[arg(long, default_value = "false")]
601 tracing: bool,
602
603 #[arg(long, default_value = "false")]
605 no_namespaced_exports: bool,
606
607 #[arg(long, default_value = "false")]
609 pub guest: bool,
610}
611
612impl TranspileOpts {
613 pub fn transpile_to_js(
615 &self,
616 component: &[u8],
617 name: impl AsRef<str>,
618 ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
619 js_component_bindgen::transpile(
620 component,
621 js_component_bindgen::TranspileOpts {
622 name: name.as_ref().to_string(),
623 no_typescript: self.no_typescript,
624 instantiation_mode: self.instantiation.clone().0,
625 import_bindings: self.import_bindings.clone(),
626 map: if !self.map.is_empty() {
627 Some(self.map.iter().cloned().collect())
628 } else {
629 None
630 },
631 nodejs_compat_disabled: self.no_nodejs_compat,
632 base64_cutoff: self.base64_cutoff,
633 tla_compat: self.tla_compat,
634 valid_lifting_optimization: self.valid_lifting_optimization,
635 tracing: self.tracing,
636 no_namespaced_exports: self.no_namespaced_exports,
637 multi_memory: true,
638 guest: self.guest,
639 async_mode: None,
640 strict: false,
641 asmjs: false,
642 },
643 )
644 .to_eyre()
645 .wrap_err("Failed to transpile to JS.")
646 }
647}
648
649#[derive(Clone, Debug)]
651pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
652
653pub(super) mod analysis {
654 use js_component_bindgen::{BindingsMode, InstantiationMode};
655
656 use super::CustomInstantiationMode;
657
658 pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
659 match s {
660 "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
661 "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
662 "Normal" => Ok(CustomInstantiationMode(None)),
663 _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
664 }
665 }
666
667 pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
668 match s {
669 "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
670 "Js" => Ok(Some(BindingsMode::Js)),
671 "Optimized" => Ok(Some(BindingsMode::Optimized)),
672 "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
673 _ => Ok(None),
674 }
675 }
676
677 pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
678 let parts: Vec<&str> = s.splitn(2, '=').collect();
679 if parts.len() != 2 {
680 return Err(format!("Invalid mapping format: '{}'", s));
681 }
682 Ok((parts[0].to_string(), parts[1].to_string()))
683 }
684}
685
686#[derive(
688 Debug,
689 Clone,
690 Copy,
691 PartialEq,
692 strum::EnumString,
693 strum::Display,
694 serde::Serialize,
695 serde::Deserialize,
696)]
697pub enum TargetMemoryType {
698 #[strum(ascii_case_insensitive)]
700 Single,
701 #[strum(ascii_case_insensitive)]
703 Multi,
704}
705
706impl TargetMemoryType {
707 pub fn is_multi(&self) -> bool {
709 matches!(self, TargetMemoryType::Multi)
710 }
711
712 pub fn is_single(&self) -> bool {
714 matches!(self, TargetMemoryType::Single)
715 }
716}
717
718#[derive(Parser, Debug, Clone, Default)]
720pub struct VfsBuildOptions {
721 #[arg(long, action = clap::ArgAction::Append)]
723 pub features: Vec<String>,
724
725 #[arg(long, action = clap::ArgAction::Count)]
727 pub no_default_features: u8,
728
729 #[arg(long = "vfs-unwind", default_value = "false")]
731 pub unwind: bool,
732
733 #[arg(long, action = clap::ArgAction::Count)]
735 pub no_opt: u8,
736
737 #[arg(long, action = clap::ArgAction::Count)]
739 pub no_opt_all: u8,
740}