1#[allow(
24 unused_imports,
25 clippy::wildcard_imports,
26 reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use std::collections::{BTreeMap, BTreeSet};
31use std::fmt::Write as _;
32
33use anyhow::anyhow;
34use ctb_formats_dcdata::tinywasm::types::{
35 ConstInstruction, DataKind, ElementItem, ElementKind, ExternalKind,
36 FuncType, Global, MemoryArch, TinyWasmModule, ValType,
37};
38use sha2::{Digest, Sha256};
39
40use super::wasm::WASM_RESOURCE_ACCOUNTING_VERSION;
41use super::wasm_quota::{
42 CTB_CAPABILITY_YIELD_EXPORT, SEC_CODE, V2CheckpointPlanner, WASM_HEADER,
43 WasmBlockType, compute_static_data_end, eval_const_offset, read_blocktype,
44 read_byte, read_memarg, read_sleb_i32, read_sleb_i64, read_uleb_u32,
45};
46
47const MAX_ITEMS_PER_CHUNK_FILE: usize = 120;
48const INLINE_NEVER_BYTECODE_THRESHOLD: usize = 512;
49
50#[derive(Debug, Clone, Copy, Default)]
52pub struct TranspileWasmOptions<'a> {
53 pub name: &'a str,
55 pub input_sha256_hex: Option<&'a str>,
57}
58
59#[derive(Debug, Clone, Copy)]
61pub struct SubstituteBundleInput<'a> {
62 pub chunk_prefix: &'a str,
64 pub label: &'a str,
66 pub wasm_bytes: &'a [u8],
68 pub graph_target: Option<(u128, [u8; 32])>,
70}
71
72#[must_use]
75pub fn transpiler_fingerprint_sha256() -> [u8; 32] {
76 let mut hasher = Sha256::new();
77 hasher.update(b"ctb-wasm-to-rust-v3");
78 hasher.update(WASM_RESOURCE_ACCOUNTING_VERSION.to_le_bytes());
79 hasher.update(include_bytes!("wasm_to_rust.rs"));
80 hasher.update(include_bytes!("wasm_quota.rs"));
81 hasher.finalize().into()
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
85enum RustValTy {
86 I32,
87 I64,
88 F32,
89 F64,
90 Ref,
91}
92
93impl RustValTy {
94 fn from_val_type(vt: ValType) -> Result<Self> {
95 match vt {
96 ValType::I32 => Ok(Self::I32),
97 ValType::I64 => Ok(Self::I64),
98 ValType::F32 => Ok(Self::F32),
99 ValType::F64 => Ok(Self::F64),
100 ValType::RefFunc | ValType::RefExtern => Ok(Self::Ref),
101 ValType::V128 => {
102 bail!("WebAssembly SIMD v128 values are not supported in native substitutes")
103 }
104 }
105 }
106
107 fn from_wire_byte(b: u8) -> Result<Self> {
108 match b {
109 0x7F => Ok(Self::I32),
110 0x7E => Ok(Self::I64),
111 0x7D => Ok(Self::F32),
112 0x7C => Ok(Self::F64),
113 0x70 | 0x6F => Ok(Self::Ref),
114 0x7B => bail!(
115 "WebAssembly SIMD v128 locals/blocks are not supported in native substitutes"
116 ),
117 other => {
118 bail!("Unsupported WebAssembly value type byte {other:#04x}")
119 }
120 }
121 }
122
123 const fn rust_ty(self) -> &'static str {
124 match self {
125 Self::I32 => "i32",
126 Self::I64 => "i64",
127 Self::F32 => "f32",
128 Self::F64 => "f64",
129 Self::Ref => "Option<u32>",
130 }
131 }
132
133 const fn zero_expr(self) -> &'static str {
134 match self {
135 Self::I32 => "0i32",
136 Self::I64 => "0i64",
137 Self::F32 => "0.0f32",
138 Self::F64 => "0.0f64",
139 Self::Ref => "None",
140 }
141 }
142
143 const fn slug(self) -> &'static str {
144 match self {
145 Self::I32 => "i32",
146 Self::I64 => "i64",
147 Self::F32 => "f32",
148 Self::F64 => "f64",
149 Self::Ref => "ref",
150 }
151 }
152
153 const fn wire_tag(self) -> u8 {
154 match self {
155 Self::I32 => 1,
156 Self::I64 => 2,
157 Self::F32 => 3,
158 Self::F64 => 4,
159 Self::Ref => 5,
160 }
161 }
162
163 const fn array_idx(self) -> usize {
164 match self {
165 Self::I32 => 0,
166 Self::I64 => 1,
167 Self::F32 => 2,
168 Self::F64 => 3,
169 Self::Ref => 4,
170 }
171 }
172}
173
174fn slot_ident(depth: usize, ty: RustValTy) -> String {
175 format!("s_{}_{depth}", ty.slug())
176}
177
178fn ret_type_expr(results: &[RustValTy]) -> String {
179 match results {
180 [] => "()".to_owned(),
181 [single] => single.rust_ty().to_owned(),
182 many => {
183 let parts: Vec<&str> = many.iter().map(|t| t.rust_ty()).collect();
184 format!("({})", parts.join(", "))
185 }
186 }
187}
188
189fn ret_sig_slug(results: &[RustValTy]) -> String {
190 if results.is_empty() {
191 "void".to_owned()
192 } else {
193 let parts: Vec<&str> = results.iter().map(|t| t.slug()).collect();
194 parts.join("_")
195 }
196}
197
198fn full_fn_sig_slug(sig: &FnSigInfo) -> String {
199 let params_part = if sig.params.is_empty() {
200 "unit".to_owned()
201 } else {
202 let parts: Vec<&str> = sig.params.iter().map(|t| t.slug()).collect();
203 parts.join("_")
204 };
205 format!("p_{params_part}_ret_{}", ret_sig_slug(&sig.results))
206}
207
208fn rust_i32_literal(v: i32) -> String {
209 if v == i32::MIN {
210 "i32::MIN".to_owned()
211 } else {
212 format!("{v}i32")
213 }
214}
215
216fn rust_i64_literal(v: i64) -> String {
217 if v == i64::MIN {
218 "i64::MIN".to_owned()
219 } else {
220 format!("{v}i64")
221 }
222}
223
224fn rust_f32_literal(v: f32) -> String {
225 format!("f32::from_bits(0x{:08x}u32)", v.to_bits())
226}
227
228fn rust_f64_literal(v: f64) -> String {
229 format!("f64::from_bits(0x{:016x}u64)", v.to_bits())
230}
231
232fn emit_agpl_banner(out: &mut String) {
233 out.push_str(
234 "// SPDX-License-Identifier: AGPL-3.0-or-later\n\
235 /*\n\
236 This file is part of Collective Toolbox, a database and document workspace and utilities.\n\
237 Copyright (C) 2026 Collective Toolbox Developers\n\
238 Contact: info@collectivetoolbox.com\n\
239 \n\
240 This program is free software: you can redistribute it and/or modify it under\n\
241 the terms of the GNU Affero General Public License as published by the Free\n\
242 Software Foundation, either version 3 of the License, or (at your option) any\n\
243 later version.\n\
244 \n\
245 This program is distributed in the hope that it will be useful, but WITHOUT ANY\n\
246 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n\
247 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\n\
248 \n\
249 You should have received a copy of the GNU Affero General Public License along\n\
250 with this program. If not, see <https://www.gnu.org/licenses/>.\n\
251 */\n\
252 \n",
253 );
254}
255
256fn emit_agpl_header(
257 out: &mut String,
258 module_name: &str,
259 input_sha256_hex: Option<&str>,
260) {
261 emit_agpl_banner(out);
262 let _ = writeln!(
263 out,
264 "//! Generated native Rust WebAssembly substitute for `{module_name}`."
265 );
266 out.push_str(
267 "//! Do not edit by hand; regenerate via `./scripts/generate-wasm-substitutes`.\n",
268 );
269 if let Some(hex) = input_sha256_hex {
270 let _ = writeln!(out, "// input-sha256: {hex}");
271 }
272 out.push_str(
273 "\n#[allow(\n unused_imports,\n clippy::wildcard_imports,\n reason = \"Standard workspace module prelude\"\n)]\nuse crate::utilities::*;\n\n\
274 #[allow(\n unused_imports,\n reason = \"Generated substitute runtime imports\"\n)]\n\
275 use ctb_wasm_substitute_rt::{\n\
276 \x20 InitFnPtr, SubstituteModuleMeta, SubstituteVm, WasmLinearMemory,\n\
277 \x20 WasmSubstituteDescriptor, WasmSubstituteHost, WasmSubstituteInstance,\n\
278 \x20 WasmTable, WasmTrap, ops,\n\
279 };\n\n",
280 );
281}
282
283fn emit_chunk_file_header(out: &mut String, file_stem: &str) {
284 emit_agpl_banner(out);
285 let _ = writeln!(
286 out,
287 "//! Generated native Rust WebAssembly substitute chunk `{file_stem}`."
288 );
289 out.push_str(
290 "//! Do not edit by hand; regenerate via `./scripts/generate-wasm-substitutes`.\n\n\
291 #[allow(\n unused_imports,\n clippy::wildcard_imports,\n reason = \"Standard workspace module prelude\"\n)]\nuse crate::utilities::*;\n\n\
292 #[allow(\n unused_imports,\n reason = \"Generated substitute chunk runtime imports\"\n)]\n\
293 use ctb_wasm_substitute_rt::{\n\
294 \x20 SubstituteModuleMeta, SubstituteVm, WasmLinearMemory,\n\
295 \x20 WasmSubstituteDescriptor, WasmSubstituteHost, WasmSubstituteInstance,\n\
296 \x20 WasmTable, WasmTrap, ops,\n\
297 };\n\n",
298 );
299}
300
301fn emit_registry_header(out: &mut String, input_sha256_hex: Option<&str>) {
302 emit_agpl_banner(out);
303 out.push_str(
304 "// @generated by ctb-wasm-substitutes-gen\n\
305 // Do not edit by hand; regenerate via `./scripts/generate-wasm-substitutes`.\n",
306 );
307 if let Some(hex) = input_sha256_hex {
308 let _ = writeln!(out, "// input-sha256: {hex}");
309 }
310 out.push_str(
311 "\n#[allow(\n unused_imports,\n reason = \"Generated substitute registry runtime imports\"\n)]\n\
312 use ctb_wasm_substitute_rt::{\n\
313 \x20 SubstituteVm, WasmSubstituteHost, WasmTrap,\n\
314 };\n\n",
315 );
316}
317
318fn emit_bytes_const(out: &mut String, const_name: &str, bytes: &[u8]) {
319 let _ = writeln!(out, "const {const_name}: &[u8] = b\"\\");
320 let mut line = String::from(" ");
321 for &b in bytes {
322 let piece = if b == b'\\' {
323 "\\\\".to_owned()
324 } else if b == b'"' {
325 "\\\"".to_owned()
326 } else if b.is_ascii_graphic() {
327 char::from(b).to_string()
328 } else {
329 format!("\\x{b:02x}")
330 };
331 if line.len().saturating_add(piece.len()) > 78 {
332 line.push('\\');
333 out.push_str(&line);
334 out.push('\n');
335 line.clear();
336 line.push_str(" ");
337 }
338 line.push_str(&piece);
339 }
340 line.push_str("\";\n");
341 out.push_str(&line);
342}
343
344struct CodeBodyRaw<'a> {
345 non_param_locals: Vec<RustValTy>,
346 code_bytes: &'a [u8],
347}
348
349fn extract_raw_code_bodies(wasm_bytes: &[u8]) -> Result<Vec<CodeBodyRaw<'_>>> {
350 ensure!(
351 wasm_bytes.len() >= WASM_HEADER.len()
352 && wasm_bytes.get(..WASM_HEADER.len()) == Some(&WASM_HEADER),
353 "Invalid WASM header when extracting Section 10 code bodies"
354 );
355 let mut pos = WASM_HEADER.len();
356 let mut code_payload: Option<&[u8]> = None;
357 while pos < wasm_bytes.len() {
358 let sec_id = read_byte(wasm_bytes, &mut pos)?;
359 let sec_len = usize::try_from(read_uleb_u32(wasm_bytes, &mut pos)?)?;
360 let end = pos
361 .checked_add(sec_len)
362 .context("WASM section length overflow")?;
363 let payload = wasm_bytes
364 .get(pos..end)
365 .context("WASM section extends past EOF")?;
366 pos = end;
367 if sec_id == SEC_CODE {
368 code_payload = Some(payload);
369 break;
370 }
371 }
372 let Some(code_bytes) = code_payload else {
373 return Ok(Vec::new());
374 };
375 let mut cpos = 0usize;
376 let body_count = usize::try_from(read_uleb_u32(code_bytes, &mut cpos)?)?;
377 let mut bodies = Vec::with_capacity(body_count);
378 for _ in 0..body_count {
379 let body_len = usize::try_from(read_uleb_u32(code_bytes, &mut cpos)?)?;
380 let body_end = cpos
381 .checked_add(body_len)
382 .context("WASM function body length overflow")?;
383 let raw = code_bytes
384 .get(cpos..body_end)
385 .context("WASM function body extends past Section 10")?;
386 cpos = body_end;
387
388 let mut bpos = 0usize;
389 let group_count = read_uleb_u32(raw, &mut bpos)?;
390 let mut non_param_locals = Vec::new();
391 for _ in 0..group_count {
392 let count = usize::try_from(read_uleb_u32(raw, &mut bpos)?)?;
393 let vt = RustValTy::from_wire_byte(read_byte(raw, &mut bpos)?)?;
394 non_param_locals.resize(
395 non_param_locals.len().saturating_add(count),
396 vt,
397 );
398 }
399 let instr_slice = raw
400 .get(bpos..)
401 .context("WASM function body truncated before instruction stream")?;
402 bodies.push(CodeBodyRaw {
403 non_param_locals,
404 code_bytes: instr_slice,
405 });
406 }
407 Ok(bodies)
408}
409
410#[derive(Debug, Clone)]
411struct FnSigInfo {
412 params: Vec<RustValTy>,
413 results: Vec<RustValTy>,
414}
415
416fn convert_func_type(ft: &FuncType) -> Result<FnSigInfo> {
417 let mut params = Vec::with_capacity(ft.params.len());
418 for &p in &ft.params {
419 params.push(RustValTy::from_val_type(p)?);
420 }
421 let mut results = Vec::with_capacity(ft.results.len());
422 for &r in &ft.results {
423 results.push(RustValTy::from_val_type(r)?);
424 }
425 Ok(FnSigInfo { params, results })
426}
427
428#[derive(Debug, Clone, Copy, PartialEq, Eq)]
429enum EntrySignatureKind {
430 UnitToI32,
431 I32PairToI32,
432 UnitToUnit,
433 I32PairToUnit,
434}
435
436fn classify_entry_sig(sig: &FnSigInfo) -> Result<EntrySignatureKind> {
437 match (sig.params.as_slice(), sig.results.as_slice()) {
438 ([], [RustValTy::I32]) => Ok(EntrySignatureKind::UnitToI32),
439 ([RustValTy::I32, RustValTy::I32], [RustValTy::I32]) => {
440 Ok(EntrySignatureKind::I32PairToI32)
441 }
442 ([], []) => Ok(EntrySignatureKind::UnitToUnit),
443 ([RustValTy::I32, RustValTy::I32], []) => {
444 Ok(EntrySignatureKind::I32PairToUnit)
445 }
446 _ => bail!(
447 "Exported WASM entry function must have signature () -> i32, (i32, i32) -> i32, () -> (), or (i32, i32) -> ()"
448 ),
449 }
450}
451
452fn emit_const_instruction(
453 instr: &ConstInstruction,
454 globals: &[Global],
455 global_prefix: &str,
456) -> Result<String> {
457 match instr {
458 ConstInstruction::I32Const(v) => Ok(rust_i32_literal(*v)),
459 ConstInstruction::I64Const(v) => Ok(rust_i64_literal(*v)),
460 ConstInstruction::F32Const(v) => Ok(rust_f32_literal(*v)),
461 ConstInstruction::F64Const(v) => Ok(rust_f64_literal(*v)),
462 ConstInstruction::GlobalGet(idx) => {
463 let idx_usize = usize::try_from(*idx)?;
464 ensure!(
465 idx_usize < globals.len(),
466 "Constant expression global.get {idx_usize} out of bounds"
467 );
468 Ok(format!("{global_prefix}g{idx_usize}"))
469 }
470 ConstInstruction::RefNull(_) => Ok("None".to_owned()),
471 ConstInstruction::RefFunc(idx) => Ok(format!("Some({idx}u32)")),
472 }
473}
474
475fn eval_const_usize_expr(
476 instr: &ConstInstruction,
477 globals: &[Global],
478) -> Result<usize> {
479 if let Some(off) = eval_const_offset(instr, globals) {
480 return Ok(off);
481 }
482 bail!("Unsupported active segment constant offset expression: {instr:?}")
483}
484
485#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
486enum GlobalSlot {
487 HeapPtr,
488 Typed(RustValTy, usize),
489}
490
491#[derive(Debug, Clone)]
492struct FuncNormalizedInfo {
493 hash: [u8; 32],
494 own_globals: Vec<(RustValTy, usize)>,
495 own_callees: Vec<usize>,
496}
497
498struct NormalizedFnTarget {
499 hash: [u8; 32],
500 symbol_name: String,
501 file_stem: String,
502 rust_mod_ident: String,
503 repr_mod_idx: usize,
504 repr_fn_idx: usize,
505}
506
507struct AnalyzedModule<'a> {
508 chunk_prefix: &'a str,
509 name: &'a str,
510 wasm_sha256: [u8; 32],
511 graph_targets: Vec<(u128, [u8; 32])>,
512 parsed: TinyWasmModule,
513 code_bodies: Vec<CodeBodyRaw<'a>>,
514 initial_memory_pages: usize,
515 initial_table_elements: usize,
516 static_data_end: usize,
517 block_types: Vec<FnSigInfo>,
518 fn_sigs: Vec<FnSigInfo>,
519 entry_name: &'static str,
520 entry_idx: usize,
521 entry_sig: EntrySignatureKind,
522 memory_export_idx: Option<usize>,
523 cap_yield_func_idx: Option<usize>,
524 heap_ptr_global_idx: Option<usize>,
525 global_slots: Vec<GlobalSlot>,
526 scc_id: Vec<usize>,
527 tail_target_fns: BTreeSet<usize>,
528 has_self_tail: Vec<bool>,
529 norm_info: Vec<Option<FuncNormalizedInfo>>,
530 bound_idx_by_fn: Vec<Option<(String, usize)>>,
531}
532
533struct CallGraphSummary {
534 scc_id: Vec<usize>,
535 tail_target_fns: BTreeSet<usize>,
536 has_self_tail: Vec<bool>,
537}
538
539fn tarjan_scc_bottom_up(
540 adj: &[Vec<usize>],
541) -> Result<(Vec<usize>, Vec<usize>, Vec<Vec<usize>>)> {
542 struct Frame {
543 u: usize,
544 edge_pos: usize,
545 }
546
547 let n = adj.len();
548 let mut index: Vec<Option<usize>> = vec![None; n];
549 let mut lowlink: Vec<usize> = vec![0; n];
550 let mut on_stack: Vec<bool> = vec![false; n];
551 let mut stack: Vec<usize> = Vec::new();
552 let mut call_stack: Vec<Frame> = Vec::new();
553 let mut next_index = 0usize;
554 let mut sccs: Vec<Vec<usize>> = Vec::new();
555 let mut scc_id: Vec<usize> = vec![0; n];
556
557 for start in 0..n {
558 if index.get(start).copied().flatten().is_some() {
559 continue;
560 }
561 if let Some(slot) = index.get_mut(start) {
562 *slot = Some(next_index);
563 }
564 if let Some(slot) = lowlink.get_mut(start) {
565 *slot = next_index;
566 }
567 next_index = next_index.saturating_add(1);
568 if let Some(slot) = on_stack.get_mut(start) {
569 *slot = true;
570 }
571 stack.push(start);
572 call_stack.push(Frame { u: start, edge_pos: 0 });
573
574 while let Some(top) = call_stack.last_mut() {
575 let u = top.u;
576 let edge_idx = top.edge_pos;
577 let next_neighbor =
578 adj.get(u).and_then(|edges| edges.get(edge_idx)).copied();
579 if let Some(v) = next_neighbor {
580 top.edge_pos = edge_idx.saturating_add(1);
581 if index.get(v).copied().flatten().is_none() {
582 if let Some(slot) = index.get_mut(v) {
583 *slot = Some(next_index);
584 }
585 if let Some(slot) = lowlink.get_mut(v) {
586 *slot = next_index;
587 }
588 next_index = next_index.saturating_add(1);
589 if let Some(slot) = on_stack.get_mut(v) {
590 *slot = true;
591 }
592 stack.push(v);
593 call_stack.push(Frame { u: v, edge_pos: 0 });
594 } else if *on_stack
595 .get(v)
596 .context("Tarjan SCC neighbor out of bounds in on_stack")?
597 {
598 if let Some(v_idx) = index.get(v).copied().flatten()
599 && let Some(u_low) = lowlink.get_mut(u)
600 {
601 *u_low = (*u_low).min(v_idx);
602 }
603 }
604 continue;
605 }
606
607 let finished = call_stack.pop();
608 let Some(Frame { u, .. }) = finished else {
609 break;
610 };
611 let u_low = *lowlink
612 .get(u)
613 .context("Tarjan SCC node out of bounds in lowlink")?;
614 if let Some(parent) = call_stack.last()
615 && let Some(p_low) = lowlink.get_mut(parent.u)
616 {
617 *p_low = (*p_low).min(u_low);
618 }
619 let u_idx = index
620 .get(u)
621 .copied()
622 .flatten()
623 .context("Tarjan SCC node missing DFS index")?;
624 if u_low == u_idx {
625 let id = sccs.len();
626 let mut component = Vec::new();
627 while let Some(w) = stack.pop() {
628 if let Some(slot) = on_stack.get_mut(w) {
629 *slot = false;
630 }
631 if let Some(slot) = scc_id.get_mut(w) {
632 *slot = id;
633 }
634 component.push(w);
635 if w == u {
636 break;
637 }
638 }
639 sccs.push(component);
640 }
641 }
642 }
643
644 let mut scc_size = vec![1usize; n];
645 for component in &sccs {
646 let len = component.len();
647 for &node in component {
648 if let Some(slot) = scc_size.get_mut(node) {
649 *slot = len;
650 }
651 }
652 }
653 Ok((scc_id, scc_size, sccs))
654}
655
656fn compute_call_graph_and_sccs(
657 bodies: &[CodeBodyRaw<'_>],
658 fn_sigs: &[FnSigInfo],
659 block_types: &[FnSigInfo],
660) -> Result<CallGraphSummary> {
661 let n = bodies.len();
662 let mut adj_sets: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); n];
663 let mut distinct_callers: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); n];
664 let mut has_self_tail: Vec<bool> = vec![false; n];
665 let mut indirect_tail_targets: BTreeSet<usize> = BTreeSet::new();
666 let mut cross_return_edges: Vec<(usize, usize)> = Vec::new();
667
668 for (fn_idx, body) in bodies.iter().enumerate() {
669 let bytes = body.code_bytes;
670 let mut pos = 0usize;
671 while pos < bytes.len() {
672 let opcode = read_byte(bytes, &mut pos)?;
673 match opcode {
674 0x10 => {
675 let target =
676 usize::try_from(read_uleb_u32(bytes, &mut pos)?)?;
677 if let Some(set) = adj_sets.get_mut(fn_idx) {
678 set.insert(target);
679 }
680 if target != fn_idx
681 && let Some(callers) = distinct_callers.get_mut(target)
682 {
683 callers.insert(fn_idx);
684 }
685 }
686 0x11 => {
687 let type_idx =
688 usize::try_from(read_uleb_u32(bytes, &mut pos)?)?;
689 let _table_idx = read_uleb_u32(bytes, &mut pos)?;
690 let expected_sig = block_types
691 .get(type_idx)
692 .with_context(|| {
693 format!(
694 "call_indirect type {type_idx} out of bounds"
695 )
696 })?;
697 for (cand_idx, cand_sig) in fn_sigs.iter().enumerate() {
698 if cand_sig.params == expected_sig.params
699 && cand_sig.results == expected_sig.results
700 && let Some(set) = adj_sets.get_mut(fn_idx)
701 {
702 set.insert(cand_idx);
703 }
704 }
705 }
706 0x12 => {
707 let target =
708 usize::try_from(read_uleb_u32(bytes, &mut pos)?)?;
709 if let Some(set) = adj_sets.get_mut(fn_idx) {
710 set.insert(target);
711 }
712 if target == fn_idx {
713 if let Some(slot) = has_self_tail.get_mut(fn_idx) {
714 *slot = true;
715 }
716 } else {
717 cross_return_edges.push((fn_idx, target));
718 if let Some(callers) = distinct_callers.get_mut(target)
719 {
720 callers.insert(fn_idx);
721 }
722 }
723 }
724 0x13 => {
725 let type_idx =
726 usize::try_from(read_uleb_u32(bytes, &mut pos)?)?;
727 let _table_idx = read_uleb_u32(bytes, &mut pos)?;
728 let expected_sig = block_types
729 .get(type_idx)
730 .with_context(|| {
731 format!(
732 "return_call_indirect type {type_idx} out of bounds"
733 )
734 })?;
735 for (cand_idx, cand_sig) in fn_sigs.iter().enumerate() {
736 if cand_sig.params == expected_sig.params
737 && cand_sig.results == expected_sig.results
738 {
739 indirect_tail_targets.insert(cand_idx);
740 if let Some(set) = adj_sets.get_mut(fn_idx) {
741 set.insert(cand_idx);
742 }
743 }
744 }
745 }
746 _ => {
747 skip_instruction_immediates(opcode, bytes, &mut pos)?;
748 }
749 }
750 }
751 }
752
753 let adj: Vec<Vec<usize>> = adj_sets
754 .into_iter()
755 .map(|s| s.into_iter().collect())
756 .collect();
757 let (scc_id, _scc_size, _topo_sccs_bottom_up) = tarjan_scc_bottom_up(&adj)?;
758 let _ = distinct_callers;
759
760 let mut tail_target_fns = indirect_tail_targets;
761 for (caller, target) in cross_return_edges {
762 if scc_id.get(caller) == scc_id.get(target) {
763 tail_target_fns.insert(target);
764 }
765 }
766
767 Ok(CallGraphSummary {
768 scc_id,
769 tail_target_fns,
770 has_self_tail,
771 })
772}
773
774#[allow(
775 clippy::too_many_arguments,
776 reason = "Canonicalizes one WASM function body into a signature-normalized SHA-256 hash"
777)]
778fn canonicalize_and_hash_function(
779 fn_idx: usize,
780 sig: &FnSigInfo,
781 body: &CodeBodyRaw<'_>,
782 fn_sigs: &[FnSigInfo],
783 block_types: &[FnSigInfo],
784 global_slots: &[GlobalSlot],
785 cap_yield_func_idx: Option<usize>,
786 scc_id: &[usize],
787) -> Result<Option<FuncNormalizedInfo>> {
788 let mut hasher = Sha256::new();
789 hasher.update(b"ctb-wasm-norm-v3");
790 hasher.update(u64::try_from(sig.params.len())?.to_le_bytes());
791 for p in &sig.params {
792 hasher.update([p.wire_tag()]);
793 }
794 hasher.update(u64::try_from(sig.results.len())?.to_le_bytes());
795 for r in &sig.results {
796 hasher.update([r.wire_tag()]);
797 }
798 hasher.update(u64::try_from(body.non_param_locals.len())?.to_le_bytes());
799 for l in &body.non_param_locals {
800 hasher.update([l.wire_tag()]);
801 }
802
803 let mut own_globals: Vec<(RustValTy, usize)> = Vec::new();
804 let mut global_pos_map: BTreeMap<(RustValTy, usize), usize> = BTreeMap::new();
805 let mut own_callees: Vec<usize> = Vec::new();
806 let mut callee_pos_map: BTreeMap<usize, usize> = BTreeMap::new();
807 let bytes = body.code_bytes;
808 let mut pos = 0usize;
809
810 let register_global = |ty: RustValTy,
811 slot: usize,
812 own_globals: &mut Vec<(RustValTy, usize)>,
813 pos_map: &mut BTreeMap<(RustValTy, usize), usize>|
814 -> usize {
815 if let Some(&existing) = pos_map.get(&(ty, slot)) {
816 return existing;
817 }
818 let next_idx = own_globals.len();
819 own_globals.push((ty, slot));
820 pos_map.insert((ty, slot), next_idx);
821 next_idx
822 };
823
824 while pos < bytes.len() {
825 let opcode = read_byte(bytes, &mut pos)?;
826 hasher.update([opcode]);
827 match opcode {
828 0x02 | 0x03 | 0x04 => {
829 let bt = read_blocktype(bytes, &mut pos)?;
830 let (b_params, b_results) = match bt {
831 WasmBlockType::Empty => (Vec::new(), Vec::new()),
832 WasmBlockType::ValType(b) => {
833 (Vec::new(), vec![RustValTy::from_wire_byte(b)?])
834 }
835 WasmBlockType::TypeIdx(idx) => {
836 let s = block_types
837 .get(usize::try_from(idx)?)
838 .with_context(|| {
839 format!("WASM blocktype index {idx} out of bounds")
840 })?;
841 (s.params.clone(), s.results.clone())
842 }
843 };
844 hasher.update([0xA0]);
845 hasher.update(u64::try_from(b_params.len())?.to_le_bytes());
846 for p in b_params {
847 hasher.update([p.wire_tag()]);
848 }
849 hasher.update(u64::try_from(b_results.len())?.to_le_bytes());
850 for r in b_results {
851 hasher.update([r.wire_tag()]);
852 }
853 }
854 0x0C | 0x0D | 0x20 | 0x21 | 0x22 | 0x25 | 0x26 | 0x3F | 0x40 => {
855 let v = read_uleb_u32(bytes, &mut pos)?;
856 hasher.update(v.to_le_bytes());
857 }
858 0x0E => {
859 let count = read_uleb_u32(bytes, &mut pos)?;
860 hasher.update(count.to_le_bytes());
861 for _ in 0..count {
862 hasher.update(read_uleb_u32(bytes, &mut pos)?.to_le_bytes());
863 }
864 hasher.update(read_uleb_u32(bytes, &mut pos)?.to_le_bytes());
865 }
866 0x10 | 0x12 => {
867 let target_idx =
868 usize::try_from(read_uleb_u32(bytes, &mut pos)?)?;
869 if target_idx == fn_idx {
870 hasher.update([0x01]);
871 } else if Some(target_idx) == cap_yield_func_idx {
872 hasher.update([0x02]);
873 } else if opcode == 0x12
874 && scc_id.get(fn_idx) == scc_id.get(target_idx)
875 {
876 return Ok(None);
877 } else {
878 let callee_sig = fn_sigs.get(target_idx).with_context(|| {
879 format!("WASM callee index {target_idx} out of bounds")
880 })?;
881 let local_c_pos = if let Some(&existing) =
882 callee_pos_map.get(&target_idx)
883 {
884 existing
885 } else {
886 let next_c = own_callees.len();
887 own_callees.push(target_idx);
888 callee_pos_map.insert(target_idx, next_c);
889 next_c
890 };
891 hasher.update([0x04]);
892 hasher.update(u32::try_from(local_c_pos)?.to_le_bytes());
893 hasher.update(
894 u64::try_from(callee_sig.params.len())?.to_le_bytes(),
895 );
896 for p in &callee_sig.params {
897 hasher.update([p.wire_tag()]);
898 }
899 hasher.update(
900 u64::try_from(callee_sig.results.len())?.to_le_bytes(),
901 );
902 for r in &callee_sig.results {
903 hasher.update([r.wire_tag()]);
904 }
905 }
906 }
907 0x11 | 0x13 | 0xD2 => return Ok(None),
908 0x1C => {
909 let count = read_uleb_u32(bytes, &mut pos)?;
910 hasher.update(count.to_le_bytes());
911 for _ in 0..count {
912 hasher.update([read_byte(bytes, &mut pos)?]);
913 }
914 }
915 0x23 | 0x24 => {
916 let g_idx = usize::try_from(read_uleb_u32(bytes, &mut pos)?)?;
917 let slot = global_slots.get(g_idx).with_context(|| {
918 format!("WASM global index {g_idx} out of bounds")
919 })?;
920 match slot {
921 GlobalSlot::HeapPtr => {
922 hasher.update([0x10]);
923 }
924 GlobalSlot::Typed(ty, per_type_slot) => {
925 let mapped_pos = register_global(
926 *ty,
927 *per_type_slot,
928 &mut own_globals,
929 &mut global_pos_map,
930 );
931 hasher.update([0x11, ty.wire_tag()]);
932 hasher.update(u32::try_from(mapped_pos)?.to_le_bytes());
933 }
934 }
935 }
936 0x28..=0x3E => {
937 let (mem_idx, offset) = read_memarg(bytes, &mut pos)?;
938 hasher.update(u32::try_from(mem_idx)?.to_le_bytes());
939 hasher.update(offset.to_le_bytes());
940 }
941 0x41 => {
942 hasher.update(read_sleb_i32(bytes, &mut pos)?.to_le_bytes());
943 }
944 0x42 | 0xD0 => {
945 hasher.update(read_sleb_i64(bytes, &mut pos)?.to_le_bytes());
946 }
947 0x43 => {
948 let end = pos
949 .checked_add(4)
950 .context("Unexpected EOF reading f32.const")?;
951 let slice = bytes
952 .get(pos..end)
953 .context("Unexpected EOF reading f32.const")?;
954 pos = end;
955 hasher.update(slice);
956 }
957 0x44 => {
958 let end = pos
959 .checked_add(8)
960 .context("Unexpected EOF reading f64.const")?;
961 let slice = bytes
962 .get(pos..end)
963 .context("Unexpected EOF reading f64.const")?;
964 pos = end;
965 hasher.update(slice);
966 }
967 0xFC => {
968 let subop = read_uleb_u32(bytes, &mut pos)?;
969 hasher.update(subop.to_le_bytes());
970 match subop {
971 0..=7 => {}
972 8 | 9 | 12 | 13 => return Ok(None),
973 10 | 14 => {
974 hasher.update(
975 read_uleb_u32(bytes, &mut pos)?.to_le_bytes(),
976 );
977 hasher.update(
978 read_uleb_u32(bytes, &mut pos)?.to_le_bytes(),
979 );
980 }
981 11 | 15 | 16 | 17 => {
982 hasher.update(
983 read_uleb_u32(bytes, &mut pos)?.to_le_bytes(),
984 );
985 }
986 other => {
987 bail!(
988 "Unsupported 0xFC sub-opcode {other} in native substitute transpiler"
989 );
990 }
991 }
992 }
993 0xFD => {
994 bail!(
995 "WebAssembly SIMD (0xFD) instructions are not supported in native substitutes"
996 );
997 }
998 _ => {}
999 }
1000 }
1001
1002 hasher.update(u64::try_from(own_globals.len())?.to_le_bytes());
1003 for &(g_ty, _) in &own_globals {
1004 hasher.update([g_ty.wire_tag()]);
1005 }
1006 Ok(Some(FuncNormalizedInfo {
1007 hash: hasher.finalize().into(),
1008 own_globals,
1009 own_callees,
1010 }))
1011}
1012
1013#[allow(
1014 clippy::too_many_arguments,
1015 reason = "Computes signature-normalized per-function hashes across module functions"
1016)]
1017fn compute_module_normalized_info(
1018 code_bodies: &[CodeBodyRaw<'_>],
1019 fn_sigs: &[FnSigInfo],
1020 block_types: &[FnSigInfo],
1021 global_slots: &[GlobalSlot],
1022 cap_yield_func_idx: Option<usize>,
1023 tail_target_fns: &BTreeSet<usize>,
1024 scc_id: &[usize],
1025) -> Result<Vec<Option<FuncNormalizedInfo>>> {
1026 let mut info: Vec<Option<FuncNormalizedInfo>> =
1027 Vec::with_capacity(code_bodies.len());
1028 for (fn_idx, body) in code_bodies.iter().enumerate() {
1029 if Some(fn_idx) == cap_yield_func_idx
1030 || tail_target_fns.contains(&fn_idx)
1031 {
1032 info.push(None);
1033 continue;
1034 }
1035 let sig = fn_sigs
1036 .get(fn_idx)
1037 .with_context(|| format!("Function signature {fn_idx} missing"))?;
1038 info.push(canonicalize_and_hash_function(
1039 fn_idx,
1040 sig,
1041 body,
1042 fn_sigs,
1043 block_types,
1044 global_slots,
1045 cap_yield_func_idx,
1046 scc_id,
1047 )?);
1048 }
1049 Ok(info)
1050}
1051
1052fn build_global_slots(
1053 globals: &[Global],
1054 heap_ptr_global_idx: Option<usize>,
1055) -> Result<Vec<GlobalSlot>> {
1056 let mut counts = [0usize; 5];
1057 let mut slots = Vec::with_capacity(globals.len());
1058 for (idx, g) in globals.iter().enumerate() {
1059 if Some(idx) == heap_ptr_global_idx {
1060 slots.push(GlobalSlot::HeapPtr);
1061 } else {
1062 let ty = RustValTy::from_val_type(g.ty.ty)?;
1063 let arr_i = ty.array_idx();
1064 let slot_idx = *counts
1065 .get(arr_i)
1066 .context("Global type array index out of bounds")?;
1067 if let Some(c) = counts.get_mut(arr_i) {
1068 *c = slot_idx.saturating_add(1);
1069 }
1070 slots.push(GlobalSlot::Typed(ty, slot_idx));
1071 }
1072 }
1073 Ok(slots)
1074}
1075
1076fn analyze_module<'a>(
1077 chunk_prefix: &'a str,
1078 name: &'a str,
1079 wasm_bytes: &'a [u8],
1080) -> Result<AnalyzedModule<'a>> {
1081 let parsed = ctb_formats_dcdata::tinywasm::parser::Parser::new()
1082 .parse_module_bytes(wasm_bytes)
1083 .map_err(|error| {
1084 anyhow!("Failed to parse WASM binary in tinywasm: {error:?}")
1085 })?;
1086 let code_bodies = extract_raw_code_bodies(wasm_bytes)?;
1087 let (initial_memory_pages, initial_table_elements) =
1088 validate_transpilable_module(wasm_bytes, &parsed, &code_bodies)?;
1089
1090 let block_types: Vec<FnSigInfo> = parsed
1091 .func_types
1092 .iter()
1093 .map(convert_func_type)
1094 .collect::<Result<_>>()?;
1095 let fn_sigs: Vec<FnSigInfo> = parsed
1096 .funcs
1097 .iter()
1098 .map(|f| convert_func_type(&f.ty))
1099 .collect::<Result<_>>()?;
1100
1101 let (
1102 entry_name,
1103 entry_idx,
1104 entry_sig,
1105 memory_export_idx,
1106 cap_yield_func_idx,
1107 heap_ptr_global_idx,
1108 ) = resolve_entry_and_specials(&parsed, &fn_sigs)?;
1109
1110 let global_slots = build_global_slots(&parsed.globals, heap_ptr_global_idx)?;
1111 let cg =
1112 compute_call_graph_and_sccs(&code_bodies, &fn_sigs, &block_types)?;
1113 let norm_info = compute_module_normalized_info(
1114 &code_bodies,
1115 &fn_sigs,
1116 &block_types,
1117 &global_slots,
1118 cap_yield_func_idx,
1119 &cg.tail_target_fns,
1120 &cg.scc_id,
1121 )?;
1122
1123 let mut per_sig_counts: BTreeMap<String, usize> = BTreeMap::new();
1124 let mut bound_idx_by_fn: Vec<Option<(String, usize)>> =
1125 Vec::with_capacity(fn_sigs.len());
1126 for (fn_idx, sig) in fn_sigs.iter().enumerate() {
1127 if Some(fn_idx) == cap_yield_func_idx {
1128 bound_idx_by_fn.push(None);
1129 } else {
1130 let slug = full_fn_sig_slug(sig);
1131 let slot_entry = per_sig_counts.entry(slug.clone()).or_insert(0);
1132 let assigned = *slot_entry;
1133 *slot_entry = assigned.saturating_add(1);
1134 bound_idx_by_fn.push(Some((slug, assigned)));
1135 }
1136 }
1137
1138 let wasm_sha256: [u8; 32] = Sha256::digest(wasm_bytes).into();
1139 let static_data_end = compute_static_data_end(&parsed);
1140
1141 Ok(AnalyzedModule {
1142 chunk_prefix,
1143 name,
1144 wasm_sha256,
1145 graph_targets: Vec::new(),
1146 parsed,
1147 code_bodies,
1148 initial_memory_pages,
1149 initial_table_elements,
1150 static_data_end,
1151 block_types,
1152 fn_sigs,
1153 entry_name,
1154 entry_idx,
1155 entry_sig,
1156 memory_export_idx,
1157 cap_yield_func_idx,
1158 heap_ptr_global_idx,
1159 global_slots,
1160 scc_id: cg.scc_id,
1161 tail_target_fns: cg.tail_target_fns,
1162 has_self_tail: cg.has_self_tail,
1163 norm_info,
1164 bound_idx_by_fn,
1165 })
1166}
1167
1168fn skip_instruction_immediates(
1169 opcode: u8,
1170 bytes: &[u8],
1171 pos: &mut usize,
1172) -> Result<()> {
1173 match opcode {
1174 0x02 | 0x03 | 0x04 => {
1175 let _ = read_blocktype(bytes, pos)?;
1176 }
1177 0x0C | 0x0D | 0x10 | 0x12 | 0x20 | 0x21 | 0x22 | 0x23 | 0x24
1178 | 0x25 | 0x26 | 0x3F | 0x40 | 0xD2 => {
1179 let _ = read_uleb_u32(bytes, pos)?;
1180 }
1181 0x0E => {
1182 let count = read_uleb_u32(bytes, pos)?;
1183 for _ in 0..count {
1184 let _ = read_uleb_u32(bytes, pos)?;
1185 }
1186 let _ = read_uleb_u32(bytes, pos)?;
1187 }
1188 0x11 | 0x13 => {
1189 let _ = read_uleb_u32(bytes, pos)?;
1190 let _ = read_uleb_u32(bytes, pos)?;
1191 }
1192 0x1C => {
1193 let count = read_uleb_u32(bytes, pos)?;
1194 for _ in 0..count {
1195 let _ = read_byte(bytes, pos)?;
1196 }
1197 }
1198 0x28..=0x3E => {
1199 let _ = read_memarg(bytes, pos)?;
1200 }
1201 0x41 => {
1202 let _ = read_sleb_i32(bytes, pos)?;
1203 }
1204 0x42 | 0xD0 => {
1205 let _ = read_sleb_i64(bytes, pos)?;
1206 }
1207 0x43 => {
1208 *pos = pos
1209 .checked_add(4)
1210 .context("Unexpected EOF reading f32.const")?;
1211 }
1212 0x44 => {
1213 *pos = pos
1214 .checked_add(8)
1215 .context("Unexpected EOF reading f64.const")?;
1216 }
1217 0xFC => {
1218 let subop = read_uleb_u32(bytes, pos)?;
1219 match subop {
1220 0..=7 => {}
1221 8 | 10 | 12 | 14 => {
1222 let _ = read_uleb_u32(bytes, pos)?;
1223 let _ = read_uleb_u32(bytes, pos)?;
1224 }
1225 9 | 11 | 13 | 15 | 16 | 17 => {
1226 let _ = read_uleb_u32(bytes, pos)?;
1227 }
1228 other => {
1229 bail!(
1230 "Unsupported 0xFC sub-opcode {other} in native substitute transpiler"
1231 );
1232 }
1233 }
1234 }
1235 0xFD => {
1236 bail!(
1237 "WebAssembly SIMD (0xFD) instructions are not supported in native substitutes"
1238 );
1239 }
1240 _ => {}
1241 }
1242 Ok(())
1243}
1244
1245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1246enum CtrlKind {
1247 Function,
1248 Block,
1249 Loop,
1250 If { has_else: bool },
1251}
1252
1253#[derive(Debug, Clone)]
1254struct CtrlFrame {
1255 kind: CtrlKind,
1256 label_id: usize,
1257 indent: usize,
1258 params: Vec<RustValTy>,
1259 results: Vec<RustValTy>,
1260 stack_base: usize,
1261 parent_unreachable: bool,
1262 unreachable: bool,
1263}
1264
1265enum BundleCallMode<'a> {
1266 StandaloneSingleModule,
1267 BundleDescriptorLocal,
1268 NormalizedChunkFn {
1269 self_symbol_name: &'a str,
1270 global_pos_map: BTreeMap<(RustValTy, usize), usize>,
1271 callee_pos_map: BTreeMap<usize, usize>,
1272 },
1273}
1274
1275fn format_call_invocation(
1276 target_idx: usize,
1277 arg_exprs: &[String],
1278 module: &AnalyzedModule<'_>,
1279 call_mode: &BundleCallMode<'_>,
1280 caller_fn_idx: Option<usize>,
1281) -> Result<String> {
1282 if Some(target_idx) == module.cap_yield_func_idx {
1283 return Ok("{ vm.sync_fast_budget(); let __cap_res = host.request_capability(vm); vm.rearm_fast_budget(); __cap_res }".to_owned());
1284 }
1285
1286 match call_mode {
1287 BundleCallMode::StandaloneSingleModule => {
1288 let mut call_args =
1289 Vec::with_capacity(arg_exprs.len().saturating_add(2));
1290 call_args.push("vm".to_owned());
1291 call_args.extend(arg_exprs.iter().cloned());
1292 call_args.push("host".to_owned());
1293 Ok(format!(
1294 "SubstituteInstance::fn_{target_idx}({})",
1295 call_args.join(", ")
1296 ))
1297 }
1298 BundleCallMode::BundleDescriptorLocal => {
1299 let (sig_slug, bound_idx) = module
1300 .bound_idx_by_fn
1301 .get(target_idx)
1302 .and_then(Option::as_ref)
1303 .with_context(|| {
1304 format!(
1305 "Callee fn_{target_idx} missing from module dispatch table"
1306 )
1307 })?;
1308 let mut call_args =
1309 Vec::with_capacity(arg_exprs.len().saturating_add(3));
1310 call_args.push("vm".to_owned());
1311 call_args.push(format!("{bound_idx}usize"));
1312 call_args.extend(arg_exprs.iter().cloned());
1313 call_args.push("host".to_owned());
1314 Ok(format!(
1315 "DISPATCH.call_direct_{sig_slug}({})",
1316 call_args.join(", ")
1317 ))
1318 }
1319 BundleCallMode::NormalizedChunkFn {
1320 self_symbol_name,
1321 callee_pos_map,
1322 ..
1323 } => {
1324 if caller_fn_idx == Some(target_idx) {
1325 let mut call_args =
1326 Vec::with_capacity(arg_exprs.len().saturating_add(5));
1327 call_args.push("vm".to_owned());
1328 call_args.push("dispatch".to_owned());
1329 call_args.push("g_map".to_owned());
1330 call_args.push("c_map".to_owned());
1331 call_args.extend(arg_exprs.iter().cloned());
1332 call_args.push("host".to_owned());
1333 return Ok(format!(
1334 "Self::{self_symbol_name}({})",
1335 call_args.join(", ")
1336 ));
1337 }
1338 let local_c_pos = callee_pos_map
1339 .get(&target_idx)
1340 .copied()
1341 .with_context(|| {
1342 format!(
1343 "Normalized function missing local callee slot for fn_{target_idx}"
1344 )
1345 })?;
1346 let callee_sig =
1347 module.fn_sigs.get(target_idx).with_context(|| {
1348 format!("Callee signature fn_{target_idx} out of bounds")
1349 })?;
1350 let sig_slug = full_fn_sig_slug(callee_sig);
1351 let mut call_args =
1352 Vec::with_capacity(arg_exprs.len().saturating_add(4));
1353 call_args.push("vm".to_owned());
1354 call_args.push("c_map".to_owned());
1355 call_args.push(format!("{local_c_pos}usize"));
1356 call_args.extend(arg_exprs.iter().cloned());
1357 call_args.push("host".to_owned());
1358 Ok(format!(
1359 "dispatch.call_{sig_slug}({})",
1360 call_args.join(", ")
1361 ))
1362 }
1363 }
1364}
1365
1366struct FuncLowerer<'a> {
1367 fn_idx: usize,
1368 fn_results: Vec<RustValTy>,
1369 module: &'a AnalyzedModule<'a>,
1370 call_mode: &'a BundleCallMode<'a>,
1371 locals: Vec<RustValTy>,
1372 num_params: usize,
1373 val_stack: Vec<RustValTy>,
1374 ctrl_stack: Vec<CtrlFrame>,
1375 used_slots: BTreeSet<(usize, RustValTy)>,
1376 planner: V2CheckpointPlanner,
1377 body_out: String,
1378 next_label: usize,
1379 next_temp: usize,
1380 is_cross_tail_step: bool,
1381 use_self_tail_loop: bool,
1382}
1383
1384impl<'a> FuncLowerer<'a> {
1385 fn new(
1386 fn_idx: usize,
1387 module: &'a AnalyzedModule<'a>,
1388 call_mode: &'a BundleCallMode<'a>,
1389 is_cross_tail_step: bool,
1390 use_self_tail_loop: bool,
1391 ) -> Result<Self> {
1392 let sig = module
1393 .fn_sigs
1394 .get(fn_idx)
1395 .context("Function signature out of bounds during lowering")?;
1396 let body = module
1397 .code_bodies
1398 .get(fn_idx)
1399 .context("Function body out of bounds during lowering")?;
1400 let num_params = sig.params.len();
1401 let mut locals = sig.params.clone();
1402 locals.extend_from_slice(&body.non_param_locals);
1403
1404 let initial_indent = if use_self_tail_loop { 2 } else { 1 };
1405 let fn_results = sig.results.clone();
1406 let fn_frame = CtrlFrame {
1407 kind: CtrlKind::Function,
1408 label_id: 0,
1409 indent: initial_indent,
1410 params: Vec::new(),
1411 results: fn_results.clone(),
1412 stack_base: 0,
1413 parent_unreachable: false,
1414 unreachable: false,
1415 };
1416
1417 Ok(Self {
1418 fn_idx,
1419 fn_results,
1420 module,
1421 call_mode,
1422 locals,
1423 num_params,
1424 val_stack: Vec::new(),
1425 ctrl_stack: vec![fn_frame],
1426 used_slots: BTreeSet::new(),
1427 planner: V2CheckpointPlanner::new(),
1428 body_out: String::new(),
1429 next_label: 1,
1430 next_temp: 0,
1431 is_cross_tail_step,
1432 use_self_tail_loop,
1433 })
1434 }
1435
1436 fn current_frame(&self) -> Result<&CtrlFrame> {
1437 self.ctrl_stack
1438 .last()
1439 .context("Control stack unexpectedly empty during WASM lowering")
1440 }
1441
1442 fn current_frame_mut(&mut self) -> Result<&mut CtrlFrame> {
1443 self.ctrl_stack
1444 .last_mut()
1445 .context("Control stack unexpectedly empty during WASM lowering")
1446 }
1447
1448 fn is_unreachable(&self) -> Result<bool> {
1449 Ok(self.current_frame()?.unreachable)
1450 }
1451
1452 fn set_unreachable(&mut self) -> Result<()> {
1453 self.current_frame_mut()?.unreachable = true;
1454 Ok(())
1455 }
1456
1457 fn current_indent(&self) -> usize {
1458 self.ctrl_stack.last().map_or(1, |f| f.indent)
1460 }
1461
1462 fn emit_line(&mut self, line: &str) {
1463 let indent = self.current_indent();
1464 for _ in 0..indent {
1465 self.body_out.push_str(" ");
1466 }
1467 self.body_out.push_str(line);
1468 self.body_out.push('\n');
1469 }
1470
1471 fn emit_line_at(&mut self, indent: usize, line: &str) {
1472 for _ in 0..indent {
1473 self.body_out.push_str(" ");
1474 }
1475 self.body_out.push_str(line);
1476 self.body_out.push('\n');
1477 }
1478
1479 fn alloc_temp(&mut self) -> String {
1480 let id = self.next_temp;
1481 self.next_temp = self.next_temp.saturating_add(1);
1482 format!("__t{id}")
1483 }
1484
1485 fn use_slot(&mut self, depth: usize, ty: RustValTy) -> String {
1486 self.used_slots.insert((depth, ty));
1487 slot_ident(depth, ty)
1488 }
1489
1490 fn push_val(&mut self, ty: RustValTy, expr: &str) {
1491 let depth = self.val_stack.len();
1492 let slot = self.use_slot(depth, ty);
1493 self.val_stack.push(ty);
1494 self.emit_line(&format!("{slot} = {expr};"));
1495 }
1496
1497 fn pop_val(&mut self, expected: Option<RustValTy>) -> Result<(String, RustValTy)> {
1498 let ty = self
1499 .val_stack
1500 .pop()
1501 .context("WebAssembly value stack underflow during lowering")?;
1502 if let Some(exp) = expected {
1503 ensure!(
1504 ty == exp,
1505 "WebAssembly stack type mismatch: expected {exp:?}, found {ty:?}"
1506 );
1507 }
1508 let depth = self.val_stack.len();
1509 let slot = self.use_slot(depth, ty);
1510 Ok((slot, ty))
1511 }
1512
1513 fn peek_top_n(&mut self, types: &[RustValTy]) -> Result<Vec<String>> {
1514 let n = types.len();
1515 ensure!(
1516 self.val_stack.len() >= n,
1517 "WebAssembly stack underflow reading {n} branch operands"
1518 );
1519 let start = self.val_stack.len().saturating_sub(n);
1520 let mut slots = Vec::with_capacity(n);
1521 for (i, &ty) in types.iter().enumerate() {
1522 let depth = start.saturating_add(i);
1523 let actual = *self
1524 .val_stack
1525 .get(depth)
1526 .context("Stack slot index out of range")?;
1527 ensure!(
1528 actual == ty,
1529 "Branch operand type mismatch: expected {ty:?}, found {actual:?}"
1530 );
1531 slots.push(self.use_slot(depth, ty));
1532 }
1533 Ok(slots)
1534 }
1535
1536 fn maybe_emit_ordinary_deduct(&mut self) -> Result<()> {
1537 let emit_check = self.planner.before_ordinary_op();
1538 if emit_check && !self.is_unreachable()? {
1539 self.emit_line("vm.deduct_1(host)?;");
1540 }
1541 Ok(())
1542 }
1543
1544 fn decode_blocktype_sig(
1545 &self,
1546 bt: WasmBlockType,
1547 ) -> Result<(Vec<RustValTy>, Vec<RustValTy>)> {
1548 match bt {
1549 WasmBlockType::Empty => Ok((Vec::new(), Vec::new())),
1550 WasmBlockType::ValType(b) => {
1551 Ok((Vec::new(), vec![RustValTy::from_wire_byte(b)?]))
1552 }
1553 WasmBlockType::TypeIdx(idx) => {
1554 let sig = self
1555 .module
1556 .block_types
1557 .get(usize::try_from(idx)?)
1558 .with_context(|| {
1559 format!("WASM blocktype index {idx} out of bounds")
1560 })?;
1561 Ok((sig.params.clone(), sig.results.clone()))
1562 }
1563 }
1564 }
1565
1566 fn return_expr_from_slots(&self, slots: &[String]) -> String {
1567 let inner = match slots {
1568 [] => "()".to_owned(),
1569 [single] => single.clone(),
1570 many => format!("({})", many.join(", ")),
1571 };
1572 if self.is_cross_tail_step {
1573 let ret_slug = ret_sig_slug(&self.fn_results);
1574 format!("TailStep_{ret_slug}::Done({inner})")
1575 } else {
1576 inner
1577 }
1578 }
1579
1580 fn return_expr_from_top(&mut self) -> Result<String> {
1581 let ret_types = self.fn_results.clone();
1582 let slots = self.peek_top_n(&ret_types)?;
1583 Ok(self.return_expr_from_slots(&slots))
1584 }
1585
1586 fn emit_branch_to_depth(&mut self, depth: u32, indent: usize) -> Result<()> {
1587 let depth_usize = usize::try_from(depth)?;
1588 let frame_idx = self
1589 .ctrl_stack
1590 .len()
1591 .checked_sub(depth_usize.saturating_add(1))
1592 .with_context(|| {
1593 format!("WebAssembly branch depth {depth_usize} out of range")
1594 })?;
1595 let target = self
1596 .ctrl_stack
1597 .get(frame_idx)
1598 .context("Branch target frame missing")?
1599 .clone();
1600 let arity_types = if target.kind == CtrlKind::Loop {
1601 target.params
1602 } else {
1603 target.results
1604 };
1605 let src_slots = self.peek_top_n(&arity_types)?;
1606
1607 if target.kind == CtrlKind::Function {
1608 let temps: Vec<String> = src_slots
1609 .iter()
1610 .map(|src| {
1611 let t = self.alloc_temp();
1612 self.emit_line_at(indent, &format!("let {t} = {src};"));
1613 t
1614 })
1615 .collect();
1616 let ret_expr = self.return_expr_from_slots(&temps);
1617 self.emit_line_at(indent, &format!("return Ok({ret_expr});"));
1618 return Ok(());
1619 }
1620
1621 let mut temps = Vec::with_capacity(arity_types.len());
1622 for src in &src_slots {
1623 let t = self.alloc_temp();
1624 self.emit_line_at(indent, &format!("let {t} = {src};"));
1625 temps.push(t);
1626 }
1627 for (i, (t, &ty)) in temps.iter().zip(arity_types.iter()).enumerate() {
1628 let dst = self.use_slot(target.stack_base.saturating_add(i), ty);
1629 self.emit_line_at(indent, &format!("{dst} = {t};"));
1630 }
1631 if target.kind == CtrlKind::Loop {
1632 self.emit_line_at(indent, &format!("continue 'blk_{};", target.label_id));
1633 } else {
1634 self.emit_line_at(indent, &format!("break 'blk_{};", target.label_id));
1635 }
1636 Ok(())
1637 }
1638
1639 #[allow(
1640 clippy::too_many_lines,
1641 reason = "Dispatches core WebAssembly opcodes identically to V2CheckpointPlanner"
1642 )]
1643 fn lower_body(&mut self, bytes: &[u8]) -> Result<String> {
1644 let is_cap_yield = self.module.cap_yield_func_idx == Some(self.fn_idx);
1645 if is_cap_yield {
1646 self.emit_line("vm.sync_fast_budget();");
1647 self.emit_line("let __cap_res = host.request_capability(vm);");
1648 self.emit_line("vm.rearm_fast_budget();");
1649 self.emit_line("__cap_res?;");
1650 let ret_expr = self.return_expr_from_slots(&[]);
1651 self.emit_line(&format!("return Ok({ret_expr});"));
1652 return Ok(self.finalize_function_source());
1653 }
1654
1655 if !self.use_self_tail_loop {
1656 self.emit_line("vm.deduct_1(host)?;");
1657 } else {
1658 self.emit_line_at(1, "'self_tail: loop {");
1659 self.emit_line("vm.deduct_1(host)?;");
1660 for idx in self.num_params..self.locals.len() {
1661 let ty = *self
1662 .locals
1663 .get(idx)
1664 .context("Local variable index out of range")?;
1665 self.emit_line(&format!(
1666 "let mut l{idx}: {} = {};",
1667 ty.rust_ty(),
1668 ty.zero_expr()
1669 ));
1670 }
1671 }
1672
1673 let mut pos = 0usize;
1674 while pos < bytes.len() {
1675 let opcode = read_byte(bytes, &mut pos)?;
1676
1677 if opcode == 0x05 {
1679 self.planner.on_else();
1680 let (frame_indent, parent_unreach, stack_base, params) = {
1681 let top = self.current_frame()?;
1682 ensure!(
1683 matches!(top.kind, CtrlKind::If { has_else: false }),
1684 "Unexpected `else` (0x05) without matching `if`"
1685 );
1686 (
1687 top.indent,
1688 top.parent_unreachable,
1689 top.stack_base,
1690 top.params.clone(),
1691 )
1692 };
1693 if !parent_unreach {
1694 let outer_indent = frame_indent.saturating_sub(1);
1695 self.emit_line_at(outer_indent, "} else {");
1696 self.val_stack.truncate(stack_base);
1697 self.val_stack.extend(params);
1698 }
1699 let top_mut = self.current_frame_mut()?;
1700 top_mut.kind = CtrlKind::If { has_else: true };
1701 top_mut.unreachable = parent_unreach;
1702 continue;
1703 }
1704
1705 if opcode == 0x0B {
1707 self.planner.on_end();
1708 let popped = self
1709 .ctrl_stack
1710 .pop()
1711 .context("Unexpected `end` (0x0B) with empty control stack")?;
1712 if popped.kind == CtrlKind::Function {
1713 if !popped.unreachable {
1714 let ret_expr = self.return_expr_from_top()?;
1715 self.emit_line_at(
1716 popped.indent,
1717 &format!("return Ok({ret_expr});"),
1718 );
1719 }
1720 if self.use_self_tail_loop {
1721 if popped.unreachable {
1722 self.emit_line_at(
1723 popped.indent,
1724 "return Err(WasmTrap::Unreachable);",
1725 );
1726 }
1727 self.emit_line_at(1, "}");
1728 }
1729 break;
1730 }
1731
1732 if !popped.parent_unreachable {
1733 let outer_indent = popped.indent.saturating_sub(1);
1734 match popped.kind {
1735 CtrlKind::Block => {
1736 self.emit_line_at(outer_indent, "}");
1737 }
1738 CtrlKind::Loop => {
1739 self.emit_line_at(
1740 popped.indent,
1741 &format!("break 'blk_{};", popped.label_id),
1742 );
1743 self.emit_line_at(outer_indent, "}");
1744 }
1745 CtrlKind::If { .. } => {
1746 let if_indent = outer_indent.saturating_sub(1);
1747 self.emit_line_at(outer_indent, "}");
1748 self.emit_line_at(if_indent, "}");
1749 }
1750 CtrlKind::Function => {}
1751 }
1752 self.val_stack.truncate(popped.stack_base);
1753 for &ty in &popped.results {
1754 let d = self.val_stack.len();
1755 let _ = self.use_slot(d, ty);
1756 self.val_stack.push(ty);
1757 }
1758 }
1759 continue;
1760 }
1761
1762 if opcode == 0x03 {
1764 let bt = read_blocktype(bytes, &mut pos)?;
1765 let (params, results) = self.decode_blocktype_sig(bt)?;
1766 self.planner.on_loop_header();
1767 let parent_unreach = self.is_unreachable()?;
1768 let label_id = self.next_label;
1769 self.next_label = self.next_label.saturating_add(1);
1770 let base_indent = self.current_indent();
1771 let stack_base = if parent_unreach {
1772 self.val_stack.len()
1773 } else {
1774 ensure!(
1775 self.val_stack.len() >= params.len(),
1776 "Stack underflow entering `loop` block parameters"
1777 );
1778 self.val_stack.len().saturating_sub(params.len())
1779 };
1780 if !parent_unreach {
1781 self.emit_line_at(
1782 base_indent,
1783 &format!("'blk_{label_id}: loop {{"),
1784 );
1785 self.emit_line_at(
1786 base_indent.saturating_add(1),
1787 "vm.deduct_1(host)?;",
1788 );
1789 }
1790 self.ctrl_stack.push(CtrlFrame {
1791 kind: CtrlKind::Loop,
1792 label_id,
1793 indent: if parent_unreach {
1794 base_indent
1795 } else {
1796 base_indent.saturating_add(1)
1797 },
1798 params,
1799 results,
1800 stack_base,
1801 parent_unreachable: parent_unreach,
1802 unreachable: parent_unreach,
1803 });
1804 continue;
1805 }
1806
1807 if opcode == 0x02 || opcode == 0x04 {
1809 let bt = read_blocktype(bytes, &mut pos)?;
1810 let (params, results) = self.decode_blocktype_sig(bt)?;
1811 let emit_check = self.planner.before_block_or_if();
1812 let parent_unreach = self.is_unreachable()?;
1813 if emit_check && !parent_unreach {
1814 self.emit_line("vm.deduct_1(host)?;");
1815 }
1816 let label_id = self.next_label;
1817 self.next_label = self.next_label.saturating_add(1);
1818 let base_indent = self.current_indent();
1819
1820 if opcode == 0x02 {
1821 let stack_base = if parent_unreach {
1822 self.val_stack.len()
1823 } else {
1824 ensure!(
1825 self.val_stack.len() >= params.len(),
1826 "Stack underflow entering `block` parameters"
1827 );
1828 self.val_stack.len().saturating_sub(params.len())
1829 };
1830 if !parent_unreach {
1831 self.emit_line_at(
1832 base_indent,
1833 &format!("'blk_{label_id}: {{"),
1834 );
1835 }
1836 self.ctrl_stack.push(CtrlFrame {
1837 kind: CtrlKind::Block,
1838 label_id,
1839 indent: if parent_unreach {
1840 base_indent
1841 } else {
1842 base_indent.saturating_add(1)
1843 },
1844 params,
1845 results,
1846 stack_base,
1847 parent_unreachable: parent_unreach,
1848 unreachable: parent_unreach,
1849 });
1850 } else {
1851 let cond_slot = if !parent_unreach {
1852 Some(self.pop_val(Some(RustValTy::I32))?.0)
1853 } else {
1854 None
1855 };
1856 let stack_base = if parent_unreach {
1857 self.val_stack.len()
1858 } else {
1859 ensure!(
1860 self.val_stack.len() >= params.len(),
1861 "Stack underflow entering `if` parameters"
1862 );
1863 self.val_stack.len().saturating_sub(params.len())
1864 };
1865 if let Some(cond) = cond_slot {
1866 self.emit_line_at(
1867 base_indent,
1868 &format!("'blk_{label_id}: {{"),
1869 );
1870 self.emit_line_at(
1871 base_indent.saturating_add(1),
1872 &format!("if {cond} != 0 {{"),
1873 );
1874 }
1875 self.ctrl_stack.push(CtrlFrame {
1876 kind: CtrlKind::If { has_else: false },
1877 label_id,
1878 indent: if parent_unreach {
1879 base_indent
1880 } else {
1881 base_indent.saturating_add(2)
1882 },
1883 params,
1884 results,
1885 stack_base,
1886 parent_unreachable: parent_unreach,
1887 unreachable: parent_unreach,
1888 });
1889 }
1890 continue;
1891 }
1892
1893 if opcode == 0x40 {
1895 self.planner.before_bulk_or_grow_op();
1896 let mem_idx = usize::try_from(read_uleb_u32(bytes, &mut pos)?)?;
1897 if !self.is_unreachable()? {
1898 let (delta_slot, _) = self.pop_val(Some(RustValTy::I32))?;
1899 let res = format!(
1900 "vm.memory_grow({mem_idx}, {delta_slot}, host)?"
1901 );
1902 self.push_val(RustValTy::I32, &res);
1903 }
1904 continue;
1905 }
1906
1907 if opcode == 0xFC {
1909 let subop = read_uleb_u32(bytes, &mut pos)?;
1910 self.lower_fc_subop(subop, bytes, &mut pos)?;
1911 continue;
1912 }
1913
1914 self.maybe_emit_ordinary_deduct()?;
1916 if self.is_unreachable()? {
1917 skip_instruction_immediates(opcode, bytes, &mut pos)?;
1918 continue;
1919 }
1920 self.lower_ordinary_op(opcode, bytes, &mut pos)?;
1921 }
1922
1923 Ok(self.finalize_function_source())
1924 }
1925
1926 fn lower_fc_subop(
1927 &mut self,
1928 subop: u32,
1929 bytes: &[u8],
1930 pos: &mut usize,
1931 ) -> Result<()> {
1932 match subop {
1933 8 => {
1934 self.planner.before_bulk_or_grow_op();
1936 let seg_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
1937 let mem_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
1938 if !self.is_unreachable()? {
1939 let (len, _) = self.pop_val(Some(RustValTy::I32))?;
1940 let (src, _) = self.pop_val(Some(RustValTy::I32))?;
1941 let (dst, _) = self.pop_val(Some(RustValTy::I32))?;
1942 self.emit_line(&format!(
1943 "vm.memory_init({mem_idx}, {seg_idx}, {dst}, {src}, {len}, host)?;"
1944 ));
1945 }
1946 }
1947 10 => {
1948 self.planner.before_bulk_or_grow_op();
1950 let dst_mem = usize::try_from(read_uleb_u32(bytes, pos)?)?;
1951 let src_mem = usize::try_from(read_uleb_u32(bytes, pos)?)?;
1952 if !self.is_unreachable()? {
1953 let (len, _) = self.pop_val(Some(RustValTy::I32))?;
1954 let (src, _) = self.pop_val(Some(RustValTy::I32))?;
1955 let (dst, _) = self.pop_val(Some(RustValTy::I32))?;
1956 self.emit_line(&format!(
1957 "vm.memory_copy({dst_mem}, {src_mem}, {dst}, {src}, {len}, host)?;"
1958 ));
1959 }
1960 }
1961 11 => {
1962 self.planner.before_bulk_or_grow_op();
1964 let mem_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
1965 if !self.is_unreachable()? {
1966 let (len, _) = self.pop_val(Some(RustValTy::I32))?;
1967 let (val, _) = self.pop_val(Some(RustValTy::I32))?;
1968 let (dst, _) = self.pop_val(Some(RustValTy::I32))?;
1969 self.emit_line(&format!(
1970 "vm.memory_fill({mem_idx}, {dst}, {val}, {len}, host)?;"
1971 ));
1972 }
1973 }
1974 12 => {
1975 self.planner.before_bulk_or_grow_op();
1977 let seg_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
1978 let tbl_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
1979 if !self.is_unreachable()? {
1980 let (len, _) = self.pop_val(Some(RustValTy::I32))?;
1981 let (src, _) = self.pop_val(Some(RustValTy::I32))?;
1982 let (dst, _) = self.pop_val(Some(RustValTy::I32))?;
1983 self.emit_line(&format!(
1984 "vm.table_init({tbl_idx}, {seg_idx}, {dst}, {src}, {len}, host)?;"
1985 ));
1986 }
1987 }
1988 14 => {
1989 self.planner.before_bulk_or_grow_op();
1991 let dst_tbl = usize::try_from(read_uleb_u32(bytes, pos)?)?;
1992 let src_tbl = usize::try_from(read_uleb_u32(bytes, pos)?)?;
1993 if !self.is_unreachable()? {
1994 let (len, _) = self.pop_val(Some(RustValTy::I32))?;
1995 let (src, _) = self.pop_val(Some(RustValTy::I32))?;
1996 let (dst, _) = self.pop_val(Some(RustValTy::I32))?;
1997 self.emit_line(&format!(
1998 "vm.table_copy({dst_tbl}, {src_tbl}, {dst}, {src}, {len}, host)?;"
1999 ));
2000 }
2001 }
2002 15 => {
2003 self.planner.before_bulk_or_grow_op();
2005 let tbl_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2006 if !self.is_unreachable()? {
2007 let (delta, _) = self.pop_val(Some(RustValTy::I32))?;
2008 let (init_val, _) = self.pop_val(Some(RustValTy::Ref))?;
2009 let res = format!(
2010 "vm.table_grow({tbl_idx}, {init_val}, {delta}, host)?"
2011 );
2012 self.push_val(RustValTy::I32, &res);
2013 }
2014 }
2015 17 => {
2016 self.planner.before_bulk_or_grow_op();
2018 let tbl_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2019 if !self.is_unreachable()? {
2020 let (len, _) = self.pop_val(Some(RustValTy::I32))?;
2021 let (val, _) = self.pop_val(Some(RustValTy::Ref))?;
2022 let (dst, _) = self.pop_val(Some(RustValTy::I32))?;
2023 self.emit_line(&format!(
2024 "vm.table_fill({tbl_idx}, {dst}, {val}, {len}, host)?;"
2025 ));
2026 }
2027 }
2028 0..=7 => {
2029 self.maybe_emit_ordinary_deduct()?;
2030 if !self.is_unreachable()? {
2031 let (helper, src_ty, dst_ty) = match subop {
2032 0 => (
2033 "i32_trunc_sat_f32_s",
2034 RustValTy::F32,
2035 RustValTy::I32,
2036 ),
2037 1 => (
2038 "i32_trunc_sat_f32_u",
2039 RustValTy::F32,
2040 RustValTy::I32,
2041 ),
2042 2 => (
2043 "i32_trunc_sat_f64_s",
2044 RustValTy::F64,
2045 RustValTy::I32,
2046 ),
2047 3 => (
2048 "i32_trunc_sat_f64_u",
2049 RustValTy::F64,
2050 RustValTy::I32,
2051 ),
2052 4 => (
2053 "i64_trunc_sat_f32_s",
2054 RustValTy::F32,
2055 RustValTy::I64,
2056 ),
2057 5 => (
2058 "i64_trunc_sat_f32_u",
2059 RustValTy::F32,
2060 RustValTy::I64,
2061 ),
2062 6 => (
2063 "i64_trunc_sat_f64_s",
2064 RustValTy::F64,
2065 RustValTy::I64,
2066 ),
2067 _ => (
2068 "i64_trunc_sat_f64_u",
2069 RustValTy::F64,
2070 RustValTy::I64,
2071 ),
2072 };
2073 let (a, _) = self.pop_val(Some(src_ty))?;
2074 self.push_val(dst_ty, &format!("ops::{helper}({a})"));
2075 }
2076 }
2077 9 => {
2078 let seg_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2079 self.maybe_emit_ordinary_deduct()?;
2080 if !self.is_unreachable()? {
2081 self.emit_line(&format!("vm.data_drop({seg_idx});"));
2082 }
2083 }
2084 13 => {
2085 let seg_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2086 self.maybe_emit_ordinary_deduct()?;
2087 if !self.is_unreachable()? {
2088 self.emit_line(&format!("vm.elem_drop({seg_idx});"));
2089 }
2090 }
2091 16 => {
2092 let tbl_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2093 self.maybe_emit_ordinary_deduct()?;
2094 if !self.is_unreachable()? {
2095 self.push_val(
2096 RustValTy::I32,
2097 &format!("vm.table_size({tbl_idx})?"),
2098 );
2099 }
2100 }
2101 other => {
2102 bail!("Unsupported 0xFC sub-opcode {other} in native substitute transpiler");
2103 }
2104 }
2105 Ok(())
2106 }
2107
2108 fn emit_call_and_push_results(
2109 &mut self,
2110 call_expr: &str,
2111 results: &[RustValTy],
2112 ) {
2113 self.emit_line("vm.enter_call()?;");
2114 self.emit_line(&format!("let __call_res = {call_expr};"));
2115 self.emit_line("vm.exit_call();");
2116 match results {
2117 [] => {
2118 self.emit_line("__call_res?;");
2119 }
2120 [single] => {
2121 let r = self.alloc_temp();
2122 self.emit_line(&format!("let {r} = __call_res?;"));
2123 self.push_val(*single, &r);
2124 }
2125 many => {
2126 let temps: Vec<String> =
2127 (0..many.len()).map(|_| self.alloc_temp()).collect();
2128 self.emit_line(&format!(
2129 "let ({}) = __call_res?;",
2130 temps.join(", ")
2131 ));
2132 for (t, &ty) in temps.iter().zip(many.iter()) {
2133 self.push_val(ty, t);
2134 }
2135 }
2136 }
2137 }
2138
2139 fn lower_ordinary_op(
2140 &mut self,
2141 opcode: u8,
2142 bytes: &[u8],
2143 pos: &mut usize,
2144 ) -> Result<()> {
2145 match opcode {
2146 0x00 => {
2147 self.emit_line("return Err(WasmTrap::Unreachable);");
2148 self.set_unreachable()?;
2149 }
2150 0x01 => {}
2151 0x0C => {
2152 let depth = read_uleb_u32(bytes, pos)?;
2153 let indent = self.current_indent();
2154 self.emit_branch_to_depth(depth, indent)?;
2155 self.set_unreachable()?;
2156 }
2157 0x0D => {
2158 let depth = read_uleb_u32(bytes, pos)?;
2159 let (cond, _) = self.pop_val(Some(RustValTy::I32))?;
2160 let indent = self.current_indent();
2161 self.emit_line(&format!("if {cond} != 0 {{"));
2162 self.emit_branch_to_depth(depth, indent.saturating_add(1))?;
2163 self.emit_line("}");
2164 }
2165 0x0E => {
2166 let count = read_uleb_u32(bytes, pos)?;
2167 let mut targets = Vec::with_capacity(usize::try_from(count)?);
2168 for _ in 0..count {
2169 targets.push(read_uleb_u32(bytes, pos)?);
2170 }
2171 let default_depth = read_uleb_u32(bytes, pos)?;
2172 let (idx, _) = self.pop_val(Some(RustValTy::I32))?;
2173 let base_indent = self.current_indent();
2174 self.emit_line(&format!("match {idx} {{"));
2175 for (arm_idx, &depth) in targets.iter().enumerate() {
2176 let arm_i32 = i32::try_from(arm_idx).context(
2177 "br_table target index exceeds i32::MAX",
2178 )?;
2179 self.emit_line_at(
2180 base_indent.saturating_add(1),
2181 &format!("{arm_i32}i32 => {{"),
2182 );
2183 self.emit_branch_to_depth(
2184 depth,
2185 base_indent.saturating_add(2),
2186 )?;
2187 self.emit_line_at(base_indent.saturating_add(1), "}");
2188 }
2189 self.emit_line_at(base_indent.saturating_add(1), "_ => {");
2190 self.emit_branch_to_depth(
2191 default_depth,
2192 base_indent.saturating_add(2),
2193 )?;
2194 self.emit_line_at(base_indent.saturating_add(1), "}");
2195 self.emit_line("}");
2196 self.set_unreachable()?;
2197 }
2198 0x0F => {
2199 let ret_expr = self.return_expr_from_top()?;
2200 self.emit_line(&format!("return Ok({ret_expr});"));
2201 self.set_unreachable()?;
2202 }
2203 0x10 => {
2204 let fn_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2205 let callee_sig = self
2206 .module
2207 .fn_sigs
2208 .get(fn_idx)
2209 .with_context(|| format!("call fn_{fn_idx} out of bounds"))?
2210 .clone();
2211 let mut arg_slots = Vec::with_capacity(callee_sig.params.len());
2212 for &pt in callee_sig.params.iter().rev() {
2213 arg_slots.push(self.pop_val(Some(pt))?.0);
2214 }
2215 arg_slots.reverse();
2216 let expr = format_call_invocation(
2217 fn_idx,
2218 &arg_slots,
2219 self.module,
2220 self.call_mode,
2221 Some(self.fn_idx),
2222 )?;
2223 self.emit_call_and_push_results(&expr, &callee_sig.results);
2224 }
2225 0x11 => {
2226 let type_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2227 let table_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2228 let expected_sig = self
2229 .module
2230 .block_types
2231 .get(type_idx)
2232 .with_context(|| {
2233 format!("call_indirect type {type_idx} out of bounds")
2234 })?
2235 .clone();
2236 let (elem_slot, _) = self.pop_val(Some(RustValTy::I32))?;
2237 let mut arg_slots =
2238 Vec::with_capacity(expected_sig.params.len());
2239 for &pt in expected_sig.params.iter().rev() {
2240 arg_slots.push(self.pop_val(Some(pt))?.0);
2241 }
2242 arg_slots.reverse();
2243
2244 let temps: Vec<String> = arg_slots
2245 .iter()
2246 .map(|slot| {
2247 let t = self.alloc_temp();
2248 self.emit_line(&format!("let {t} = {slot};"));
2249 t
2250 })
2251 .collect();
2252 let target_var = self.alloc_temp();
2253 self.emit_line(&format!(
2254 "let {target_var} = vm.call_indirect_target({table_idx}, {elem_slot})?;"
2255 ));
2256
2257 self.emit_line("vm.enter_call()?;");
2258 let res_var = self.alloc_temp();
2259 let indent = self.current_indent();
2260 self.emit_line(&format!("let {res_var} = match {target_var} {{"));
2261 for (cand_idx, cand_sig) in self.module.fn_sigs.iter().enumerate()
2262 {
2263 if cand_sig.params == expected_sig.params
2264 && cand_sig.results == expected_sig.results
2265 {
2266 let cand_call = format_call_invocation(
2267 cand_idx,
2268 &temps,
2269 self.module,
2270 self.call_mode,
2271 None,
2272 )?;
2273 self.emit_line_at(
2274 indent.saturating_add(1),
2275 &format!("{cand_idx}u32 => {cand_call},"),
2276 );
2277 }
2278 }
2279 self.emit_line_at(
2280 indent.saturating_add(1),
2281 "_ => Err(WasmTrap::IndirectCallTypeMismatch),",
2282 );
2283 self.emit_line("};");
2284 self.emit_line("vm.exit_call();");
2285 match expected_sig.results.as_slice() {
2286 [] => {
2287 self.emit_line(&format!("{res_var}?;"));
2288 }
2289 [single] => {
2290 let out_t = self.alloc_temp();
2291 self.emit_line(&format!("let {out_t} = {res_var}?;"));
2292 self.push_val(*single, &out_t);
2293 }
2294 many => {
2295 let out_ts: Vec<String> =
2296 (0..many.len()).map(|_| self.alloc_temp()).collect();
2297 self.emit_line(&format!(
2298 "let ({}) = {res_var}?;",
2299 out_ts.join(", ")
2300 ));
2301 for (t, &ty) in out_ts.iter().zip(many.iter()) {
2302 self.push_val(ty, t);
2303 }
2304 }
2305 }
2306 }
2307 0x12 => {
2308 let target_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2310 let callee_sig = self
2311 .module
2312 .fn_sigs
2313 .get(target_idx)
2314 .with_context(|| {
2315 format!("return_call fn_{target_idx} out of bounds")
2316 })?
2317 .clone();
2318 let mut arg_slots = Vec::with_capacity(callee_sig.params.len());
2319 for &pt in callee_sig.params.iter().rev() {
2320 arg_slots.push(self.pop_val(Some(pt))?.0);
2321 }
2322 arg_slots.reverse();
2323 let temps: Vec<String> = arg_slots
2324 .iter()
2325 .map(|s| {
2326 let t = self.alloc_temp();
2327 self.emit_line(&format!("let {t} = {s};"));
2328 t
2329 })
2330 .collect();
2331 if target_idx == self.fn_idx {
2332 for (i, t) in temps.iter().enumerate() {
2333 self.emit_line(&format!("l{i} = {t};"));
2334 }
2335 self.emit_line("continue 'self_tail;");
2336 } else if Some(target_idx) == self.module.cap_yield_func_idx {
2337 self.emit_line("vm.sync_fast_budget();");
2338 self.emit_line("let __cap_res = host.request_capability(vm);");
2339 self.emit_line("vm.rearm_fast_budget();");
2340 self.emit_line("__cap_res?;");
2341 let done_expr = self.return_expr_from_slots(&[]);
2342 self.emit_line(&format!("return Ok({done_expr});"));
2343 } else {
2344 let caller_scc = self.module.scc_id.get(self.fn_idx);
2345 let target_scc = self.module.scc_id.get(target_idx);
2346 if caller_scc == target_scc {
2347 let ret_slug = ret_sig_slug(&callee_sig.results);
2348 let arg_str = temps.join(", ");
2349 if self.is_cross_tail_step {
2350 self.emit_line(&format!(
2351 "return Ok(TailStep_{ret_slug}::Tail(TailTarget_{ret_slug}::Func{target_idx}({arg_str})));"
2352 ));
2353 } else {
2354 self.emit_line(&format!(
2355 "return SubstituteInstance::tail_dispatch_{ret_slug}(vm, TailStep_{ret_slug}::Tail(TailTarget_{ret_slug}::Func{target_idx}({arg_str})), host);"
2356 ));
2357 }
2358 } else {
2359 let call_expr = format_call_invocation(
2363 target_idx,
2364 &temps,
2365 self.module,
2366 self.call_mode,
2367 Some(self.fn_idx),
2368 )?;
2369 if self.is_cross_tail_step {
2370 let ret_slug = ret_sig_slug(&callee_sig.results);
2371 self.emit_line(&format!(
2372 "return {call_expr}.map(TailStep_{ret_slug}::Done);"
2373 ));
2374 } else {
2375 self.emit_line(&format!("return {call_expr};"));
2376 }
2377 }
2378 }
2379 self.set_unreachable()?;
2380 }
2381 0x13 => {
2382 let type_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2384 let table_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2385 let expected_sig = self
2386 .module
2387 .block_types
2388 .get(type_idx)
2389 .with_context(|| {
2390 format!(
2391 "return_call_indirect type {type_idx} out of bounds"
2392 )
2393 })?
2394 .clone();
2395 let (elem_slot, _) = self.pop_val(Some(RustValTy::I32))?;
2396 let mut arg_slots =
2397 Vec::with_capacity(expected_sig.params.len());
2398 for &pt in expected_sig.params.iter().rev() {
2399 arg_slots.push(self.pop_val(Some(pt))?.0);
2400 }
2401 arg_slots.reverse();
2402 let temps: Vec<String> = arg_slots
2403 .iter()
2404 .map(|s| {
2405 let t = self.alloc_temp();
2406 self.emit_line(&format!("let {t} = {s};"));
2407 t
2408 })
2409 .collect();
2410 let target_var = self.alloc_temp();
2411 self.emit_line(&format!(
2412 "let {target_var} = vm.call_indirect_target({table_idx}, {elem_slot})?;"
2413 ));
2414 let ret_slug = ret_sig_slug(&expected_sig.results);
2415 let arg_str = temps.join(", ");
2416 let indent = self.current_indent();
2417 if self.is_cross_tail_step {
2418 self.emit_line(&format!("return match {target_var} {{"));
2419 for (cand_idx, cand_sig) in
2420 self.module.fn_sigs.iter().enumerate()
2421 {
2422 if cand_sig.params == expected_sig.params
2423 && cand_sig.results == expected_sig.results
2424 {
2425 self.emit_line_at(
2426 indent.saturating_add(1),
2427 &format!(
2428 "{cand_idx}u32 => Ok(TailStep_{ret_slug}::Tail(TailTarget_{ret_slug}::Func{cand_idx}({arg_str}))),"
2429 ),
2430 );
2431 }
2432 }
2433 self.emit_line_at(
2434 indent.saturating_add(1),
2435 "_ => Err(WasmTrap::IndirectCallTypeMismatch),",
2436 );
2437 self.emit_line("};");
2438 } else {
2439 let step_var = self.alloc_temp();
2440 self.emit_line(&format!("let {step_var} = match {target_var} {{"));
2441 for (cand_idx, cand_sig) in
2442 self.module.fn_sigs.iter().enumerate()
2443 {
2444 if cand_sig.params == expected_sig.params
2445 && cand_sig.results == expected_sig.results
2446 {
2447 self.emit_line_at(
2448 indent.saturating_add(1),
2449 &format!(
2450 "{cand_idx}u32 => TailStep_{ret_slug}::Tail(TailTarget_{ret_slug}::Func{cand_idx}({arg_str})),"
2451 ),
2452 );
2453 }
2454 }
2455 self.emit_line_at(
2456 indent.saturating_add(1),
2457 "_ => return Err(WasmTrap::IndirectCallTypeMismatch),",
2458 );
2459 self.emit_line("};");
2460 self.emit_line(&format!(
2461 "return SubstituteInstance::tail_dispatch_{ret_slug}(vm, {step_var}, host);"
2462 ));
2463 }
2464 self.set_unreachable()?;
2465 }
2466 0x1A => {
2467 let _ = self.pop_val(None)?;
2468 }
2469 0x1B => {
2470 let (cond, _) = self.pop_val(Some(RustValTy::I32))?;
2471 let (v2, t2) = self.pop_val(None)?;
2472 let (v1, t1) = self.pop_val(Some(t2))?;
2473 self.push_val(t1, &format!("if {cond} != 0 {{ {v1} }} else {{ {v2} }}"));
2474 }
2475 0x1C => {
2476 let cnt = read_uleb_u32(bytes, pos)?;
2477 ensure!(cnt == 1, "Typed select must specify exactly 1 type");
2478 let ty = RustValTy::from_wire_byte(read_byte(bytes, pos)?)?;
2479 let (cond, _) = self.pop_val(Some(RustValTy::I32))?;
2480 let (v2, _) = self.pop_val(Some(ty))?;
2481 let (v1, _) = self.pop_val(Some(ty))?;
2482 self.push_val(ty, &format!("if {cond} != 0 {{ {v1} }} else {{ {v2} }}"));
2483 }
2484 0x20 => {
2485 let idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2486 let ty = *self
2487 .locals
2488 .get(idx)
2489 .with_context(|| format!("local.get {idx} out of bounds"))?;
2490 self.push_val(ty, &format!("l{idx}"));
2491 }
2492 0x21 => {
2493 let idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2494 let ty = *self
2495 .locals
2496 .get(idx)
2497 .with_context(|| format!("local.set {idx} out of bounds"))?;
2498 let (val, _) = self.pop_val(Some(ty))?;
2499 self.emit_line(&format!("l{idx} = {val};"));
2500 }
2501 0x22 => {
2502 let idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2503 let ty = *self
2504 .locals
2505 .get(idx)
2506 .with_context(|| format!("local.tee {idx} out of bounds"))?;
2507 let (val, _) = self.pop_val(Some(ty))?;
2508 self.emit_line(&format!("l{idx} = {val};"));
2509 self.push_val(ty, &format!("l{idx}"));
2510 }
2511 0x23 => {
2512 let idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2513 let slot = self
2514 .module
2515 .global_slots
2516 .get(idx)
2517 .with_context(|| format!("global.get {idx} out of bounds"))?;
2518 match slot {
2519 GlobalSlot::HeapPtr => {
2520 self.push_val(RustValTy::I32, "vm.heap_ptr");
2521 }
2522 GlobalSlot::Typed(ty, per_type_slot) => {
2523 let expr = if let BundleCallMode::NormalizedChunkFn {
2524 global_pos_map,
2525 ..
2526 } = self.call_mode
2527 {
2528 let param_pos = global_pos_map
2529 .get(&(*ty, *per_type_slot))
2530 .copied()
2531 .context("Normalized global.get slot missing")?;
2532 format!(
2533 "vm.get_{}(*g_map.get({param_pos}usize).ok_or(WasmTrap::Unreachable)?)?",
2534 ty.slug()
2535 )
2536 } else {
2537 format!("vm.get_{}({per_type_slot}usize)?", ty.slug())
2538 };
2539 self.push_val(*ty, &expr);
2540 }
2541 }
2542 }
2543 0x24 => {
2544 let idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2545 let slot = self
2546 .module
2547 .global_slots
2548 .get(idx)
2549 .with_context(|| format!("global.set {idx} out of bounds"))?;
2550 match slot {
2551 GlobalSlot::HeapPtr => {
2552 let (val, _) = self.pop_val(Some(RustValTy::I32))?;
2553 self.emit_line(&format!("vm.heap_ptr = {val};"));
2554 }
2555 GlobalSlot::Typed(ty, per_type_slot) => {
2556 let (val, _) = self.pop_val(Some(*ty))?;
2557 if let BundleCallMode::NormalizedChunkFn {
2558 global_pos_map,
2559 ..
2560 } = self.call_mode
2561 {
2562 let param_pos = global_pos_map
2563 .get(&(*ty, *per_type_slot))
2564 .copied()
2565 .context("Normalized global.set slot missing")?;
2566 self.emit_line(&format!(
2567 "vm.set_{}(*g_map.get({param_pos}usize).ok_or(WasmTrap::Unreachable)?, {val})?;",
2568 ty.slug()
2569 ));
2570 } else {
2571 self.emit_line(&format!(
2572 "vm.set_{}({per_type_slot}usize, {val})?;",
2573 ty.slug()
2574 ));
2575 }
2576 }
2577 }
2578 }
2579 0x25 => {
2580 let tbl_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2581 let (idx, _) = self.pop_val(Some(RustValTy::I32))?;
2582 self.push_val(
2583 RustValTy::Ref,
2584 &format!("vm.table_get({tbl_idx}, {idx})?"),
2585 );
2586 }
2587 0x26 => {
2588 let tbl_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2589 let (val, _) = self.pop_val(Some(RustValTy::Ref))?;
2590 let (idx, _) = self.pop_val(Some(RustValTy::I32))?;
2591 self.emit_line(&format!(
2592 "vm.table_set({tbl_idx}, {idx}, {val})?;"
2593 ));
2594 }
2595 0x28..=0x35 => self.lower_mem_load(opcode, bytes, pos)?,
2596 0x36..=0x3E => self.lower_mem_store(opcode, bytes, pos)?,
2597 0x3F => {
2598 let mem_idx = usize::try_from(read_uleb_u32(bytes, pos)?)?;
2599 self.push_val(
2600 RustValTy::I32,
2601 &format!("vm.memory_size({mem_idx})?"),
2602 );
2603 }
2604 0x41 => {
2605 let v = read_sleb_i32(bytes, pos)?;
2606 self.push_val(RustValTy::I32, &rust_i32_literal(v));
2607 }
2608 0x42 => {
2609 let v = read_sleb_i64(bytes, pos)?;
2610 self.push_val(RustValTy::I64, &rust_i64_literal(v));
2611 }
2612 0x43 => {
2613 let end = pos
2614 .checked_add(4)
2615 .context("Unexpected EOF reading f32.const")?;
2616 let slice = bytes
2617 .get(*pos..end)
2618 .context("Unexpected EOF reading f32.const")?;
2619 *pos = end;
2620 let arr: [u8; 4] = slice.try_into()?;
2621 self.push_val(
2622 RustValTy::F32,
2623 &rust_f32_literal(f32::from_le_bytes(arr)),
2624 );
2625 }
2626 0x44 => {
2627 let end = pos
2628 .checked_add(8)
2629 .context("Unexpected EOF reading f64.const")?;
2630 let slice = bytes
2631 .get(*pos..end)
2632 .context("Unexpected EOF reading f64.const")?;
2633 *pos = end;
2634 let arr: [u8; 8] = slice.try_into()?;
2635 self.push_val(
2636 RustValTy::F64,
2637 &rust_f64_literal(f64::from_le_bytes(arr)),
2638 );
2639 }
2640 0xD0 => {
2641 let _heap_ty = read_sleb_i64(bytes, pos)?;
2642 self.push_val(RustValTy::Ref, "None");
2643 }
2644 0xD1 => {
2645 let (r, _) = self.pop_val(Some(RustValTy::Ref))?;
2646 self.push_val(RustValTy::I32, &format!("i32::from({r}.is_none())"));
2647 }
2648 0xD2 => {
2649 let fn_idx = read_uleb_u32(bytes, pos)?;
2650 self.push_val(RustValTy::Ref, &format!("Some({fn_idx}u32)"));
2651 }
2652 0x45..=0xC4 => self.lower_numeric_op(opcode)?,
2653 other => {
2654 bail!("Unsupported WASM opcode {other:#04x} in native substitute transpiler");
2655 }
2656 }
2657 Ok(())
2658 }
2659
2660 fn lower_mem_load(
2661 &mut self,
2662 opcode: u8,
2663 bytes: &[u8],
2664 pos: &mut usize,
2665 ) -> Result<()> {
2666 let (mem_idx, offset) = read_memarg(bytes, pos)?;
2667 let (addr, _) = self.pop_val(Some(RustValTy::I32))?;
2668 let (helper, dst_ty) = match opcode {
2669 0x28 => ("i32_load", RustValTy::I32),
2670 0x29 => ("i64_load", RustValTy::I64),
2671 0x2A => ("f32_load", RustValTy::F32),
2672 0x2B => ("f64_load", RustValTy::F64),
2673 0x2C => ("i32_load8_s", RustValTy::I32),
2674 0x2D => ("i32_load8_u", RustValTy::I32),
2675 0x2E => ("i32_load16_s", RustValTy::I32),
2676 0x2F => ("i32_load16_u", RustValTy::I32),
2677 0x30 => ("i64_load8_s", RustValTy::I64),
2678 0x31 => ("i64_load8_u", RustValTy::I64),
2679 0x32 => ("i64_load16_s", RustValTy::I64),
2680 0x33 => ("i64_load16_u", RustValTy::I64),
2681 0x34 => ("i64_load32_s", RustValTy::I64),
2682 0x35 => ("i64_load32_u", RustValTy::I64),
2683 other => bail!("Unexpected load opcode {other:#04x}"),
2684 };
2685 self.push_val(
2686 dst_ty,
2687 &format!("ops::{helper}(vm, {mem_idx}, {addr}, {offset}u32)?"),
2688 );
2689 Ok(())
2690 }
2691
2692 fn lower_mem_store(
2693 &mut self,
2694 opcode: u8,
2695 bytes: &[u8],
2696 pos: &mut usize,
2697 ) -> Result<()> {
2698 let (mem_idx, offset) = read_memarg(bytes, pos)?;
2699 let (helper, val_ty) = match opcode {
2700 0x36 => ("i32_store", RustValTy::I32),
2701 0x37 => ("i64_store", RustValTy::I64),
2702 0x38 => ("f32_store", RustValTy::F32),
2703 0x39 => ("f64_store", RustValTy::F64),
2704 0x3A => ("i32_store8", RustValTy::I32),
2705 0x3B => ("i32_store16", RustValTy::I32),
2706 0x3C => ("i64_store8", RustValTy::I64),
2707 0x3D => ("i64_store16", RustValTy::I64),
2708 0x3E => ("i64_store32", RustValTy::I64),
2709 other => bail!("Unexpected store opcode {other:#04x}"),
2710 };
2711 let (val, _) = self.pop_val(Some(val_ty))?;
2712 let (addr, _) = self.pop_val(Some(RustValTy::I32))?;
2713 self.emit_line(&format!(
2714 "ops::{helper}(vm, {mem_idx}, {addr}, {offset}u32, {val})?;"
2715 ));
2716 Ok(())
2717 }
2718
2719 fn lower_numeric_op(&mut self, opcode: u8) -> Result<()> {
2720 match opcode {
2721 0x45 => self.unary_op(RustValTy::I32, RustValTy::I32, "i32_eqz", false),
2722 0x50 => self.unary_op(RustValTy::I64, RustValTy::I32, "i64_eqz", false),
2723
2724 0x46 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_eq", false),
2725 0x47 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_ne", false),
2726 0x48 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_lt_s", false),
2727 0x49 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_lt_u", false),
2728 0x4A => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_gt_s", false),
2729 0x4B => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_gt_u", false),
2730 0x4C => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_le_s", false),
2731 0x4D => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_le_u", false),
2732 0x4E => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_ge_s", false),
2733 0x4F => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_ge_u", false),
2734
2735 0x51 => self.bin_op(RustValTy::I64, RustValTy::I32, "i64_eq", false),
2736 0x52 => self.bin_op(RustValTy::I64, RustValTy::I32, "i64_ne", false),
2737 0x53 => self.bin_op(RustValTy::I64, RustValTy::I32, "i64_lt_s", false),
2738 0x54 => self.bin_op(RustValTy::I64, RustValTy::I32, "i64_lt_u", false),
2739 0x55 => self.bin_op(RustValTy::I64, RustValTy::I32, "i64_gt_s", false),
2740 0x56 => self.bin_op(RustValTy::I64, RustValTy::I32, "i64_gt_u", false),
2741 0x57 => self.bin_op(RustValTy::I64, RustValTy::I32, "i64_le_s", false),
2742 0x58 => self.bin_op(RustValTy::I64, RustValTy::I32, "i64_le_u", false),
2743 0x59 => self.bin_op(RustValTy::I64, RustValTy::I32, "i64_ge_s", false),
2744 0x5A => self.bin_op(RustValTy::I64, RustValTy::I32, "i64_ge_u", false),
2745
2746 0x5B => self.bin_op(RustValTy::F32, RustValTy::I32, "f32_eq", false),
2747 0x5C => self.bin_op(RustValTy::F32, RustValTy::I32, "f32_ne", false),
2748 0x5D => self.bin_op(RustValTy::F32, RustValTy::I32, "f32_lt", false),
2749 0x5E => self.bin_op(RustValTy::F32, RustValTy::I32, "f32_gt", false),
2750 0x5F => self.bin_op(RustValTy::F32, RustValTy::I32, "f32_le", false),
2751 0x60 => self.bin_op(RustValTy::F32, RustValTy::I32, "f32_ge", false),
2752
2753 0x61 => self.bin_op(RustValTy::F64, RustValTy::I32, "f64_eq", false),
2754 0x62 => self.bin_op(RustValTy::F64, RustValTy::I32, "f64_ne", false),
2755 0x63 => self.bin_op(RustValTy::F64, RustValTy::I32, "f64_lt", false),
2756 0x64 => self.bin_op(RustValTy::F64, RustValTy::I32, "f64_gt", false),
2757 0x65 => self.bin_op(RustValTy::F64, RustValTy::I32, "f64_le", false),
2758 0x66 => self.bin_op(RustValTy::F64, RustValTy::I32, "f64_ge", false),
2759
2760 0x67 => self.unary_op(RustValTy::I32, RustValTy::I32, "i32_clz", false),
2761 0x68 => self.unary_op(RustValTy::I32, RustValTy::I32, "i32_ctz", false),
2762 0x69 => self.unary_op(RustValTy::I32, RustValTy::I32, "i32_popcnt", false),
2763 0x6A => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_add", false),
2764 0x6B => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_sub", false),
2765 0x6C => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_mul", false),
2766 0x6D => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_div_s", true),
2767 0x6E => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_div_u", true),
2768 0x6F => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_rem_s", true),
2769 0x70 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_rem_u", true),
2770 0x71 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_and", false),
2771 0x72 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_or", false),
2772 0x73 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_xor", false),
2773 0x74 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_shl", false),
2774 0x75 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_shr_s", false),
2775 0x76 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_shr_u", false),
2776 0x77 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_rotl", false),
2777 0x78 => self.bin_op(RustValTy::I32, RustValTy::I32, "i32_rotr", false),
2778
2779 0x79 => self.unary_op(RustValTy::I64, RustValTy::I64, "i64_clz", false),
2780 0x7A => self.unary_op(RustValTy::I64, RustValTy::I64, "i64_ctz", false),
2781 0x7B => self.unary_op(RustValTy::I64, RustValTy::I64, "i64_popcnt", false),
2782 0x7C => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_add", false),
2783 0x7D => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_sub", false),
2784 0x7E => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_mul", false),
2785 0x7F => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_div_s", true),
2786 0x80 => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_div_u", true),
2787 0x81 => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_rem_s", true),
2788 0x82 => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_rem_u", true),
2789 0x83 => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_and", false),
2790 0x84 => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_or", false),
2791 0x85 => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_xor", false),
2792 0x86 => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_shl", false),
2793 0x87 => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_shr_s", false),
2794 0x88 => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_shr_u", false),
2795 0x89 => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_rotl", false),
2796 0x8A => self.bin_op(RustValTy::I64, RustValTy::I64, "i64_rotr", false),
2797
2798 0x8B => self.unary_op(RustValTy::F32, RustValTy::F32, "f32_abs", false),
2799 0x8C => self.unary_op(RustValTy::F32, RustValTy::F32, "f32_neg", false),
2800 0x8D => self.unary_op(RustValTy::F32, RustValTy::F32, "f32_ceil", false),
2801 0x8E => self.unary_op(RustValTy::F32, RustValTy::F32, "f32_floor", false),
2802 0x8F => self.unary_op(RustValTy::F32, RustValTy::F32, "f32_trunc", false),
2803 0x90 => self.unary_op(RustValTy::F32, RustValTy::F32, "f32_nearest", false),
2804 0x91 => self.unary_op(RustValTy::F32, RustValTy::F32, "f32_sqrt", false),
2805 0x92 => self.bin_op(RustValTy::F32, RustValTy::F32, "f32_add", false),
2806 0x93 => self.bin_op(RustValTy::F32, RustValTy::F32, "f32_sub", false),
2807 0x94 => self.bin_op(RustValTy::F32, RustValTy::F32, "f32_mul", false),
2808 0x95 => self.bin_op(RustValTy::F32, RustValTy::F32, "f32_div", false),
2809 0x96 => self.bin_op(RustValTy::F32, RustValTy::F32, "f32_min", false),
2810 0x97 => self.bin_op(RustValTy::F32, RustValTy::F32, "f32_max", false),
2811 0x98 => self.bin_op(RustValTy::F32, RustValTy::F32, "f32_copysign", false),
2812
2813 0x99 => self.unary_op(RustValTy::F64, RustValTy::F64, "f64_abs", false),
2814 0x9A => self.unary_op(RustValTy::F64, RustValTy::F64, "f64_neg", false),
2815 0x9B => self.unary_op(RustValTy::F64, RustValTy::F64, "f64_ceil", false),
2816 0x9C => self.unary_op(RustValTy::F64, RustValTy::F64, "f64_floor", false),
2817 0x9D => self.unary_op(RustValTy::F64, RustValTy::F64, "f64_trunc", false),
2818 0x9E => self.unary_op(RustValTy::F64, RustValTy::F64, "f64_nearest", false),
2819 0x9F => self.unary_op(RustValTy::F64, RustValTy::F64, "f64_sqrt", false),
2820 0xA0 => self.bin_op(RustValTy::F64, RustValTy::F64, "f64_add", false),
2821 0xA1 => self.bin_op(RustValTy::F64, RustValTy::F64, "f64_sub", false),
2822 0xA2 => self.bin_op(RustValTy::F64, RustValTy::F64, "f64_mul", false),
2823 0xA3 => self.bin_op(RustValTy::F64, RustValTy::F64, "f64_div", false),
2824 0xA4 => self.bin_op(RustValTy::F64, RustValTy::F64, "f64_min", false),
2825 0xA5 => self.bin_op(RustValTy::F64, RustValTy::F64, "f64_max", false),
2826 0xA6 => self.bin_op(RustValTy::F64, RustValTy::F64, "f64_copysign", false),
2827
2828 0xA7 => self.unary_op(RustValTy::I64, RustValTy::I32, "i32_wrap_i64", false),
2829 0xA8 => self.unary_op(RustValTy::F32, RustValTy::I32, "i32_trunc_f32_s", true),
2830 0xA9 => self.unary_op(RustValTy::F32, RustValTy::I32, "i32_trunc_f32_u", true),
2831 0xAA => self.unary_op(RustValTy::F64, RustValTy::I32, "i32_trunc_f64_s", true),
2832 0xAB => self.unary_op(RustValTy::F64, RustValTy::I32, "i32_trunc_f64_u", true),
2833 0xAC => self.unary_op(RustValTy::I32, RustValTy::I64, "i64_extend_i32_s", false),
2834 0xAD => self.unary_op(RustValTy::I32, RustValTy::I64, "i64_extend_i32_u", false),
2835 0xAE => self.unary_op(RustValTy::F32, RustValTy::I64, "i64_trunc_f32_s", true),
2836 0xAF => self.unary_op(RustValTy::F32, RustValTy::I64, "i64_trunc_f32_u", true),
2837 0xB0 => self.unary_op(RustValTy::F64, RustValTy::I64, "i64_trunc_f64_s", true),
2838 0xB1 => self.unary_op(RustValTy::F64, RustValTy::I64, "i64_trunc_f64_u", true),
2839 0xB2 => self.unary_op(RustValTy::I32, RustValTy::F32, "f32_convert_i32_s", false),
2840 0xB3 => self.unary_op(RustValTy::I32, RustValTy::F32, "f32_convert_i32_u", false),
2841 0xB4 => self.unary_op(RustValTy::I64, RustValTy::F32, "f32_convert_i64_s", false),
2842 0xB5 => self.unary_op(RustValTy::I64, RustValTy::F32, "f32_convert_i64_u", false),
2843 0xB6 => self.unary_op(RustValTy::F64, RustValTy::F32, "f32_demote_f64", false),
2844 0xB7 => self.unary_op(RustValTy::I32, RustValTy::F64, "f64_convert_i32_s", false),
2845 0xB8 => self.unary_op(RustValTy::I32, RustValTy::F64, "f64_convert_i32_u", false),
2846 0xB9 => self.unary_op(RustValTy::I64, RustValTy::F64, "f64_convert_i64_s", false),
2847 0xBA => self.unary_op(RustValTy::I64, RustValTy::F64, "f64_convert_i64_u", false),
2848 0xBB => self.unary_op(RustValTy::F32, RustValTy::F64, "f64_promote_f32", false),
2849 0xBC => self.unary_op(RustValTy::F32, RustValTy::I32, "i32_reinterpret_f32", false),
2850 0xBD => self.unary_op(RustValTy::F64, RustValTy::I64, "i64_reinterpret_f64", false),
2851 0xBE => self.unary_op(RustValTy::I32, RustValTy::F32, "f32_reinterpret_i32", false),
2852 0xBF => self.unary_op(RustValTy::I64, RustValTy::F64, "f64_reinterpret_i64", false),
2853
2854 0xC0 => self.unary_op(RustValTy::I32, RustValTy::I32, "i32_extend8_s", false),
2855 0xC1 => self.unary_op(RustValTy::I32, RustValTy::I32, "i32_extend16_s", false),
2856 0xC2 => self.unary_op(RustValTy::I64, RustValTy::I64, "i64_extend8_s", false),
2857 0xC3 => self.unary_op(RustValTy::I64, RustValTy::I64, "i64_extend16_s", false),
2858 0xC4 => self.unary_op(RustValTy::I64, RustValTy::I64, "i64_extend32_s", false),
2859 other => bail!("Unsupported numeric opcode {other:#04x}"),
2860 }
2861 }
2862
2863 fn unary_op(
2864 &mut self,
2865 src: RustValTy,
2866 dst: RustValTy,
2867 helper: &str,
2868 fallible: bool,
2869 ) -> Result<()> {
2870 let (a, _) = self.pop_val(Some(src))?;
2871 let suffix = if fallible { "?" } else { "" };
2872 self.push_val(dst, &format!("ops::{helper}({a}){suffix}"));
2873 Ok(())
2874 }
2875
2876 fn bin_op(
2877 &mut self,
2878 op_ty: RustValTy,
2879 dst: RustValTy,
2880 helper: &str,
2881 fallible: bool,
2882 ) -> Result<()> {
2883 let (b, _) = self.pop_val(Some(op_ty))?;
2884 let (a, _) = self.pop_val(Some(op_ty))?;
2885 let suffix = if fallible { "?" } else { "" };
2886 self.push_val(dst, &format!("ops::{helper}({a}, {b}){suffix}"));
2887 Ok(())
2888 }
2889
2890 fn finalize_function_source(&self) -> String {
2891 let mut header = String::new();
2892 for idx in 0..self.num_params {
2893 if let Some(ty) = self.locals.get(idx) {
2894 let _ = writeln!(
2895 header,
2896 " let mut l{idx}: {} = p{idx};",
2897 ty.rust_ty()
2898 );
2899 }
2900 }
2901 if !self.use_self_tail_loop {
2902 for idx in self.num_params..self.locals.len() {
2903 if let Some(ty) = self.locals.get(idx) {
2904 let _ = writeln!(
2905 header,
2906 " let mut l{idx}: {} = {};",
2907 ty.rust_ty(),
2908 ty.zero_expr()
2909 );
2910 }
2911 }
2912 }
2913 for &(depth, ty) in &self.used_slots {
2914 let ident = slot_ident(depth, ty);
2915 let _ = writeln!(
2916 header,
2917 " let mut {ident}: {} = {};",
2918 ty.rust_ty(),
2919 ty.zero_expr()
2920 );
2921 }
2922 format!("{header}{}", self.body_out)
2923 }
2924}
2925
2926fn emit_generated_allows(out: &mut String, indent: usize) {
2927 for _ in 0..indent {
2928 out.push_str(" ");
2929 }
2930 out.push_str(
2931 "#[allow(\n\
2932 dead_code,\n\
2933 non_camel_case_types,\n\
2934 unused_mut,\n\
2935 unused_variables,\n\
2936 unused_assignments,\n\
2937 unreachable_code,\n\
2938 clippy::too_many_lines,\n\
2939 clippy::cognitive_complexity,\n\
2940 clippy::needless_continue,\n\
2941 clippy::redundant_else,\n\
2942 clippy::collapsible_if,\n\
2943 clippy::collapsible_else_if,\n\
2944 clippy::unnecessary_wraps,\n\
2945 clippy::match_same_arms,\n\
2946 clippy::single_match_else,\n\
2947 clippy::too_many_arguments,\n\
2948 clippy::let_and_return,\n\
2949 clippy::manual_let_else,\n\
2950 clippy::shadow_unrelated,\n\
2951 clippy::type_complexity,\n\
2952 clippy::almost_swapped,\n\
2953 reason = \"Generated WASM-to-Rust substitute function\"\n\
2954 )]\n",
2955 );
2956}
2957
2958fn validate_transpilable_module(
2959 wasm_bytes: &[u8],
2960 parsed: &TinyWasmModule,
2961 code_bodies: &[CodeBodyRaw<'_>],
2962) -> Result<(usize, usize)> {
2963 ensure!(
2964 parsed.imports.is_empty(),
2965 "WebAssembly modules with host imports are not supported in native substitutes"
2966 );
2967 ensure!(
2968 parsed.funcs.len() == code_bodies.len(),
2969 "WASM Section 10 body count ({}) does not match parsed function count ({})",
2970 code_bodies.len(),
2971 parsed.funcs.len()
2972 );
2973 ensure!(
2974 parsed
2975 .exports
2976 .iter()
2977 .all(|exp| {
2978 !exp.name.starts_with("__ctb_")
2979 || exp.name.as_ref() == CTB_CAPABILITY_YIELD_EXPORT
2980 }),
2981 "WebAssembly module must not declare reserved '__ctb_*' exports"
2982 );
2983 let initial_memory_pages = parsed
2984 .memory_types
2985 .iter()
2986 .try_fold(0usize, |acc, m| -> Result<usize> {
2987 ensure!(
2988 m.arch == MemoryArch::I32,
2989 "memory64 is not supported in native substitutes"
2990 );
2991 let init = usize::try_from(m.page_count_initial)?;
2992 Ok(acc.saturating_add(init))
2993 })?;
2994 let initial_table_elements =
2995 parsed
2996 .table_types
2997 .iter()
2998 .try_fold(0usize, |acc, t| -> Result<usize> {
2999 let init = usize::try_from(t.size_initial)?;
3000 Ok(acc.saturating_add(init))
3001 })?;
3002 let _ = wasm_bytes;
3003 Ok((initial_memory_pages, initial_table_elements))
3004}
3005
3006fn resolve_entry_and_specials(
3007 parsed: &TinyWasmModule,
3008 fn_sigs: &[FnSigInfo],
3009) -> Result<(
3010 &'static str,
3011 usize,
3012 EntrySignatureKind,
3013 Option<usize>,
3014 Option<usize>,
3015 Option<usize>,
3016)> {
3017 let step_exp = parsed
3018 .exports
3019 .iter()
3020 .find(|e| e.kind == ExternalKind::Func && e.name.as_ref() == "step");
3021 let main_exp = parsed
3022 .exports
3023 .iter()
3024 .find(|e| e.kind == ExternalKind::Func && e.name.as_ref() == "main");
3025 let (entry_name, entry_idx) = match (step_exp, main_exp) {
3026 (Some(exp), _) => ("step", usize::try_from(exp.index)?),
3027 (None, Some(exp)) => ("main", usize::try_from(exp.index)?),
3028 (None, None) => {
3029 bail!("WebAssembly module must export a 'step' or 'main' entry function")
3030 }
3031 };
3032 let entry_sig = classify_entry_sig(
3033 fn_sigs
3034 .get(entry_idx)
3035 .context("Exported entry function index out of bounds")?,
3036 )?;
3037
3038 let memory_export_idx = parsed
3039 .exports
3040 .iter()
3041 .find(|e| e.kind == ExternalKind::Memory && e.name.as_ref() == "memory")
3042 .map(|e| usize::try_from(e.index))
3043 .transpose()?;
3044
3045 let mut cap_yield_func_idx = None;
3046 if let Some(exp) = parsed
3047 .exports
3048 .iter()
3049 .find(|e| e.name.as_ref() == CTB_CAPABILITY_YIELD_EXPORT)
3050 {
3051 ensure!(
3052 exp.kind == ExternalKind::Func,
3053 "Reserved export '{CTB_CAPABILITY_YIELD_EXPORT}' must be a function"
3054 );
3055 let idx = usize::try_from(exp.index)?;
3056 let sig = fn_sigs
3057 .get(idx)
3058 .context("Reserved capability yield index out of bounds")?;
3059 ensure!(
3060 sig.params.is_empty() && sig.results.is_empty(),
3061 "Reserved export '{CTB_CAPABILITY_YIELD_EXPORT}' must have signature () -> ()"
3062 );
3063 cap_yield_func_idx = Some(idx);
3064 }
3065
3066 let heap_ptr_global_idx = parsed
3067 .exports
3068 .iter()
3069 .find(|e| {
3070 e.kind == ExternalKind::Global && e.name.as_ref() == "__heap_ptr"
3071 })
3072 .and_then(|e| {
3073 let idx = usize::try_from(e.index).ok()?;
3074 let g = parsed.globals.get(idx)?;
3075 (g.ty.mutable && g.ty.ty == ValType::I32).then_some(idx)
3076 });
3077
3078 Ok((
3079 entry_name,
3080 entry_idx,
3081 entry_sig,
3082 memory_export_idx,
3083 cap_yield_func_idx,
3084 heap_ptr_global_idx,
3085 ))
3086}
3087
3088fn emit_tail_call_types_and_dispatch(
3089 out: &mut String,
3090 tail_target_fns: &BTreeSet<usize>,
3091 fn_sigs: &[FnSigInfo],
3092) {
3093 let mut grouped: BTreeMap<String, (&[RustValTy], Vec<(usize, &FnSigInfo)>)> =
3094 BTreeMap::new();
3095 for (idx, sig) in fn_sigs.iter().enumerate() {
3096 if tail_target_fns.contains(&idx) {
3097 let slug = ret_sig_slug(&sig.results);
3098 let entry = grouped
3099 .entry(slug)
3100 .or_insert_with(|| (&sig.results, Vec::new()));
3101 entry.1.push((idx, sig));
3102 }
3103 }
3104
3105 for (slug, (ret_tys, members)) in &grouped {
3106 let ret_ty = ret_type_expr(ret_tys);
3107 emit_generated_allows(out, 0);
3108 let _ = writeln!(out, "enum TailTarget_{slug} {{");
3109 for &(fn_idx, sig) in members {
3110 let ptys: Vec<&str> = sig.params.iter().map(|t| t.rust_ty()).collect();
3111 let _ = writeln!(out, " Func{fn_idx}({}),", ptys.join(", "));
3112 }
3113 out.push_str("}\n\n");
3114
3115 emit_generated_allows(out, 0);
3116 let _ = writeln!(out, "enum TailStep_{slug} {{");
3117 let _ = writeln!(out, " Done({ret_ty}),");
3118 let _ = writeln!(out, " Tail(TailTarget_{slug}),");
3119 out.push_str("}\n\n");
3120 }
3121
3122 if !grouped.is_empty() {
3123 emit_generated_allows(out, 0);
3124 out.push_str("impl SubstituteInstance {\n");
3125 for (slug, (ret_tys, members)) in &grouped {
3126 let ret_ty = ret_type_expr(ret_tys);
3127 out.push_str(" #[inline(never)]\n");
3128 let _ = writeln!(
3129 out,
3130 " fn tail_dispatch_{slug}(vm: &mut SubstituteVm, mut step_val: TailStep_{slug}, host: &mut dyn WasmSubstituteHost) -> std::result::Result<{ret_ty}, WasmTrap> {{"
3131 );
3132 out.push_str(" loop {\n");
3133 out.push_str(" match step_val {\n");
3134 out.push_str(" TailStep_");
3135 out.push_str(slug);
3136 out.push_str("::Done(res) => return Ok(res),\n");
3137 out.push_str(" TailStep_");
3138 out.push_str(slug);
3139 out.push_str("::Tail(target) => match target {\n");
3140 for &(fn_idx, sig) in members {
3141 let pnames: Vec<String> =
3142 (0..sig.params.len()).map(|i| format!("p{i}")).collect();
3143 let mut call_args = Vec::with_capacity(pnames.len().saturating_add(2));
3144 call_args.push("vm".to_owned());
3145 call_args.extend(pnames.iter().cloned());
3146 call_args.push("host".to_owned());
3147 let _ = writeln!(
3148 out,
3149 " TailTarget_{slug}::Func{fn_idx}({}) => step_val = SubstituteInstance::fn_{fn_idx}_step({})?,",
3150 pnames.join(", "),
3151 call_args.join(", ")
3152 );
3153 }
3154 out.push_str(" },\n");
3155 out.push_str(" }\n");
3156 out.push_str(" }\n");
3157 out.push_str(" }\n\n");
3158 }
3159 out.push_str("}\n\n");
3160 }
3161}
3162
3163fn emit_data_and_elem_consts(out: &mut String, parsed: &TinyWasmModule) {
3164 for (i, seg) in parsed.data.iter().enumerate() {
3165 emit_bytes_const(out, &format!("DATA_SEG_{i}"), &seg.data);
3166 }
3167 if !parsed.data.is_empty() {
3168 out.push('\n');
3169 }
3170
3171 for (i, seg) in parsed.elements.iter().enumerate() {
3172 let mut items = Vec::with_capacity(seg.items.len());
3173 for item in &seg.items {
3174 match item {
3175 ElementItem::Func(idx)
3176 | ElementItem::Expr(ConstInstruction::RefFunc(idx)) => {
3177 items.push(format!("Some({idx}u32)"));
3178 }
3179 ElementItem::Expr(ConstInstruction::RefNull(_)) => {
3180 items.push("None".to_owned());
3181 }
3182 other => {
3183 let _ = other;
3184 items.push("None".to_owned());
3185 }
3186 }
3187 }
3188 let _ = writeln!(
3189 out,
3190 "const ELEM_SEG_{i}: &[Option<u32>] = &[{}];",
3191 items.join(", ")
3192 );
3193 }
3194 if !parsed.elements.is_empty() {
3195 out.push('\n');
3196 }
3197}
3198
3199fn emit_struct_and_instantiate(
3200 out: &mut String,
3201 module: &AnalyzedModule<'_>,
3202) -> Result<()> {
3203 emit_generated_allows(out, 0);
3204 out.push_str("struct SubstituteInstance {\n vm: SubstituteVm,\n}\n\n");
3205
3206 let hex_bytes: Vec<String> =
3207 module.wasm_sha256.iter().map(|b| format!("0x{b:02x}")).collect();
3208 let graph_targets_ref = if module.graph_targets.is_empty() {
3209 "&[]".to_owned()
3210 } else {
3211 let mut items: Vec<String> =
3212 Vec::with_capacity(module.graph_targets.len());
3213 for &(gid, rev) in &module.graph_targets {
3214 let rev_hex: Vec<String> =
3215 rev.iter().map(|b| format!("0x{b:02x}")).collect();
3216 items.push(format!(" ({gid}u128, [{}]),", rev_hex.join(", ")));
3217 }
3218 let _ = writeln!(
3219 out,
3220 "const GRAPH_TARGETS: &[(u128, [u8; 32])] = &[\n{}\n];\n",
3221 items.join("\n")
3222 );
3223 "GRAPH_TARGETS".to_owned()
3224 };
3225 let _ = writeln!(
3226 out,
3227 "const MODULE_META: SubstituteModuleMeta = SubstituteModuleMeta {{\n\
3228 \x20 name: {:?},\n\
3229 \x20 accounting_version: {WASM_RESOURCE_ACCOUNTING_VERSION}u32,\n\
3230 \x20 wasm_sha256: [{}],\n\
3231 \x20 entry_func_name: {:?},\n\
3232 \x20 has_start_func: {},\n\
3233 \x20 initial_memory_pages: {}usize,\n\
3234 \x20 initial_table_elements: {}usize,\n\
3235 \x20 static_data_end: {}usize,\n\
3236 \x20 num_memories: {}usize,\n\
3237 \x20 num_tables: {}usize,\n\
3238 \x20 graph_targets: {graph_targets_ref},\n\
3239 }};\n\n",
3240 module.name,
3241 hex_bytes.join(", "),
3242 module.entry_name,
3243 module.parsed.start_func.is_some(),
3244 module.initial_memory_pages,
3245 module.initial_table_elements,
3246 module.static_data_end,
3247 module.parsed.memory_types.len(),
3248 module.parsed.table_types.len(),
3249 );
3250
3251 emit_generated_allows(out, 0);
3252 out.push_str("fn instantiate_substitute() -> Box<dyn WasmSubstituteInstance> {\n");
3253 for (i, g) in module.parsed.globals.iter().enumerate() {
3254 let prefix_globals = module
3255 .parsed
3256 .globals
3257 .get(..i)
3258 .context("WASM global prefix index out of bounds")?;
3259 let expr = emit_const_instruction(&g.init, prefix_globals, "")?;
3260 let ty = RustValTy::from_val_type(g.ty.ty)?;
3261 let _ = writeln!(out, " let g{i}: {} = {expr};", ty.rust_ty());
3262 }
3263 out.push_str(" let memories = vec![\n");
3264 for m in &module.parsed.memory_types {
3265 let init = u32::try_from(m.page_count_initial)?;
3266 let max_s = match m.page_count_max {
3267 Some(max_p) => format!("Some({}u32)", u32::try_from(max_p)?),
3268 None => "None".to_owned(),
3269 };
3270 let _ = writeln!(
3271 out,
3272 " WasmLinearMemory::new({init}u32, {max_s}),"
3273 );
3274 }
3275 out.push_str(" ];\n");
3276 out.push_str(" let tables = vec![\n");
3277 for t in &module.parsed.table_types {
3278 let max_s = match t.size_max {
3279 Some(m) => format!("Some({m}u32)"),
3280 None => "None".to_owned(),
3281 };
3282 let _ = writeln!(
3283 out,
3284 " WasmTable::new({}u32, {max_s}),",
3285 t.size_initial
3286 );
3287 }
3288 out.push_str(" ];\n");
3289 out.push_str(" let passive_data: Vec<Option<&'static [u8]>> = vec![\n");
3290 for (i, seg) in module.parsed.data.iter().enumerate() {
3291 if matches!(seg.kind, DataKind::Passive) {
3292 let _ = writeln!(out, " Some(DATA_SEG_{i}),");
3293 } else {
3294 out.push_str(" None,\n");
3295 }
3296 }
3297 out.push_str(" ];\n");
3298 out.push_str(
3299 " let passive_elems: Vec<Option<&'static [Option<u32>]>> = vec![\n",
3300 );
3301 for (i, seg) in module.parsed.elements.iter().enumerate() {
3302 if matches!(seg.kind, ElementKind::Passive) {
3303 let _ = writeln!(out, " Some(ELEM_SEG_{i}),");
3304 } else {
3305 out.push_str(" None,\n");
3306 }
3307 }
3308 out.push_str(" ];\n");
3309 out.push_str(
3310 " let mut vm = SubstituteVm::new(memories, tables, passive_data, passive_elems);\n",
3311 );
3312
3313 if let Some(hp_idx) = module.heap_ptr_global_idx {
3314 let _ = writeln!(out, " vm.heap_ptr = g{hp_idx};");
3315 out.push_str(" vm.has_heap_ptr = true;\n");
3316 }
3317
3318 let mut typed_inits: [Vec<String>; 5] = Default::default();
3319 for (i, slot) in module.global_slots.iter().enumerate() {
3320 if let GlobalSlot::Typed(ty, _) = slot
3321 && let Some(bucket) = typed_inits.get_mut(ty.array_idx())
3322 {
3323 bucket.push(format!("g{i}"));
3324 }
3325 }
3326 let field_names = [
3327 "globals_i32",
3328 "globals_i64",
3329 "globals_f32",
3330 "globals_f64",
3331 "globals_ref",
3332 ];
3333 for (field, bucket) in field_names.into_iter().zip(typed_inits.iter()) {
3334 if !bucket.is_empty() {
3335 let _ = writeln!(out, " vm.{field} = vec![{}];", bucket.join(", "));
3336 }
3337 }
3338
3339 for (i, seg) in module.parsed.data.iter().enumerate() {
3340 if let DataKind::Active { mem, offset } = &seg.kind {
3341 let off = eval_const_usize_expr(offset, &module.parsed.globals)?;
3342 let _ = writeln!(
3343 out,
3344 " let _ = vm.init_active_data({mem}usize, {off}usize, DATA_SEG_{i});"
3345 );
3346 }
3347 }
3348 for (i, seg) in module.parsed.elements.iter().enumerate() {
3349 if let ElementKind::Active { table, offset } = &seg.kind {
3350 let off = eval_const_usize_expr(offset, &module.parsed.globals)?;
3351 let _ = writeln!(
3352 out,
3353 " let _ = vm.init_active_elem({table}usize, {off}usize, ELEM_SEG_{i});"
3354 );
3355 }
3356 }
3357
3358 out.push_str(" Box::new(SubstituteInstance { vm })\n}\n\n");
3359 Ok(())
3360}
3361
3362fn emit_trait_impl(
3363 out: &mut String,
3364 module: &AnalyzedModule<'_>,
3365 call_mode: &BundleCallMode<'_>,
3366) -> Result<()> {
3367 emit_generated_allows(out, 0);
3368 out.push_str("impl WasmSubstituteInstance for SubstituteInstance {\n");
3369 out.push_str(
3370 " fn meta(&self) -> SubstituteModuleMeta {\n MODULE_META\n }\n\n",
3371 );
3372 out.push_str(
3373 " fn vm(&self) -> &SubstituteVm {\n &self.vm\n }\n\n",
3374 );
3375 out.push_str(
3376 " fn vm_mut(&mut self) -> &mut SubstituteVm {\n &mut self.vm\n }\n\n",
3377 );
3378 match module.memory_export_idx {
3379 Some(idx) => {
3380 let _ = writeln!(
3381 out,
3382 " fn exported_memory_index(&self) -> Option<usize> {{\n Some({idx}usize)\n }}\n"
3383 );
3384 }
3385 None => {
3386 out.push_str(
3387 " fn exported_memory_index(&self) -> Option<usize> {\n None\n }\n\n",
3388 );
3389 }
3390 }
3391
3392 out.push_str(" fn exported_global_i32(&self, name: &str) -> Option<i32> {\n match name {\n");
3393 for exp in &module.parsed.exports {
3394 if exp.kind == ExternalKind::Global {
3395 let idx = usize::try_from(exp.index)?;
3396 if let Some(slot) = module.global_slots.get(idx) {
3397 match slot {
3398 GlobalSlot::HeapPtr => {
3399 let _ = writeln!(
3400 out,
3401 " {:?} => Some(self.vm.heap_ptr),",
3402 exp.name.as_ref()
3403 );
3404 }
3405 GlobalSlot::Typed(RustValTy::I32, per_type_slot) => {
3406 let _ = writeln!(
3407 out,
3408 " {:?} => self.vm.globals_i32.get({per_type_slot}usize).copied(),",
3409 exp.name.as_ref()
3410 );
3411 }
3412 GlobalSlot::Typed(_, _) => {}
3413 }
3414 }
3415 }
3416 }
3417 out.push_str(" _ => None,\n }\n }\n\n");
3418
3419 out.push_str(" fn exported_global_i64(&self, name: &str) -> Option<i64> {\n match name {\n");
3420 for exp in &module.parsed.exports {
3421 if exp.kind == ExternalKind::Global {
3422 let idx = usize::try_from(exp.index)?;
3423 if let Some(GlobalSlot::Typed(RustValTy::I64, per_type_slot)) =
3424 module.global_slots.get(idx)
3425 {
3426 let _ = writeln!(
3427 out,
3428 " {:?} => self.vm.globals_i64.get({per_type_slot}usize).copied(),",
3429 exp.name.as_ref()
3430 );
3431 }
3432 }
3433 }
3434 out.push_str(" _ => None,\n }\n }\n\n");
3435
3436 if module.heap_ptr_global_idx.is_some() {
3437 out.push_str(
3438 " fn set_heap_ptr(&mut self, val: i32) -> bool {\n self.vm.heap_ptr = val;\n true\n }\n\n",
3439 );
3440 } else {
3441 out.push_str(
3442 " fn set_heap_ptr(&mut self, _val: i32) -> bool {\n false\n }\n\n",
3443 );
3444 }
3445
3446 match module.parsed.start_func {
3447 Some(start_u32) => {
3448 let start_idx = usize::try_from(start_u32)?;
3449 let start_call = format_call_invocation(
3450 start_idx,
3451 &[],
3452 module,
3453 call_mode,
3454 None,
3455 )?;
3456 let _ = writeln!(
3457 out,
3458 " fn call_start(&mut self, host: &mut dyn WasmSubstituteHost) -> std::result::Result<(), WasmTrap> {{\n\
3459 \x20 let vm = &mut self.vm;\n\
3460 \x20 vm.enter_call()?;\n\
3461 \x20 vm.begin_fast_epoch();\n\
3462 \x20 let res = {start_call};\n\
3463 \x20 vm.end_fast_epoch();\n\
3464 \x20 vm.exit_call();\n\
3465 \x20 res\n\
3466 \x20 }}\n"
3467 );
3468 }
3469 None => {
3470 out.push_str(
3471 " fn call_start(&mut self, _host: &mut dyn WasmSubstituteHost) -> std::result::Result<(), WasmTrap> {\n Ok(())\n }\n\n",
3472 );
3473 }
3474 }
3475
3476 let raw_entry_args: Vec<String> = match module.entry_sig {
3477 EntrySignatureKind::UnitToI32 | EntrySignatureKind::UnitToUnit => {
3478 Vec::new()
3479 }
3480 EntrySignatureKind::I32PairToI32 | EntrySignatureKind::I32PairToUnit => {
3481 vec!["in_ptr".to_owned(), "in_len".to_owned()]
3482 }
3483 };
3484 let entry_call = format_call_invocation(
3485 module.entry_idx,
3486 &raw_entry_args,
3487 module,
3488 call_mode,
3489 None,
3490 )?;
3491 let entry_body = match module.entry_sig {
3492 EntrySignatureKind::UnitToI32 | EntrySignatureKind::I32PairToI32 => {
3493 entry_call
3494 }
3495 EntrySignatureKind::UnitToUnit | EntrySignatureKind::I32PairToUnit => {
3496 format!("{entry_call}.map(|()| 0i32)")
3497 }
3498 };
3499 let _ = writeln!(
3500 out,
3501 " fn call_entry(&mut self, in_ptr: i32, in_len: i32, host: &mut dyn WasmSubstituteHost) -> std::result::Result<i32, WasmTrap> {{\n\
3502 \x20 let _ = (in_ptr, in_len);\n\
3503 \x20 let vm = &mut self.vm;\n\
3504 \x20 vm.enter_call()?;\n\
3505 \x20 vm.begin_fast_epoch();\n\
3506 \x20 let res = {entry_body};\n\
3507 \x20 vm.end_fast_epoch();\n\
3508 \x20 vm.exit_call();\n\
3509 \x20 res\n\
3510 \x20 }}\n\
3511 }}\n"
3512 );
3513 Ok(())
3514}
3515
3516fn emit_local_functions_impl(
3517 out: &mut String,
3518 module: &AnalyzedModule<'_>,
3519 local_fn_indices: &[usize],
3520 call_mode: &BundleCallMode<'_>,
3521) -> Result<()> {
3522 if local_fn_indices.is_empty() {
3523 return Ok(());
3524 }
3525 emit_generated_allows(out, 0);
3526 out.push_str("impl SubstituteInstance {\n");
3527 for &fn_idx in local_fn_indices {
3528 let body = module
3529 .code_bodies
3530 .get(fn_idx)
3531 .context("Code body out of bounds during emission")?;
3532 let sig = module
3533 .fn_sigs
3534 .get(fn_idx)
3535 .context("Function signature out of bounds during emission")?;
3536 let ret_slug = ret_sig_slug(&sig.results);
3537 let is_cross_tail_step = module.tail_target_fns.contains(&fn_idx);
3538 let use_self_tail = *module
3539 .has_self_tail
3540 .get(fn_idx)
3541 .context("Function index out of bounds in has_self_tail")?;
3542
3543 let mut params_decl = vec!["vm: &mut SubstituteVm".to_owned()];
3544 let mut forward_args =
3545 Vec::with_capacity(sig.params.len().saturating_add(2));
3546 forward_args.push("vm".to_owned());
3547 for (i, pt) in sig.params.iter().enumerate() {
3548 params_decl.push(format!("p{i}: {}", pt.rust_ty()));
3549 forward_args.push(format!("p{i}"));
3550 }
3551 params_decl.push("host: &mut dyn WasmSubstituteHost".to_owned());
3552 forward_args.push("host".to_owned());
3553
3554 let ret_ty = ret_type_expr(&sig.results);
3555 let mut lowerer = FuncLowerer::new(
3556 fn_idx,
3557 module,
3558 call_mode,
3559 is_cross_tail_step,
3560 use_self_tail,
3561 )?;
3562 let lowered_body = lowerer.lower_body(body.code_bytes)?;
3563
3564 if is_cross_tail_step {
3565 out.push_str(" #[inline(never)]\n");
3566 let _ = writeln!(
3567 out,
3568 " fn fn_{fn_idx}_step({}) -> std::result::Result<TailStep_{ret_slug}, WasmTrap> {{",
3569 params_decl.join(", ")
3570 );
3571 out.push_str(&lowered_body);
3572 out.push_str(" }\n\n");
3573
3574 let _ = writeln!(
3575 out,
3576 " fn fn_{fn_idx}({}) -> std::result::Result<{ret_ty}, WasmTrap> {{",
3577 params_decl.join(", ")
3578 );
3579 let _ = writeln!(
3580 out,
3581 " let step = SubstituteInstance::fn_{fn_idx}_step({})?;",
3582 forward_args.join(", ")
3583 );
3584 let _ = writeln!(
3585 out,
3586 " SubstituteInstance::tail_dispatch_{ret_slug}(vm, step, host)"
3587 );
3588 out.push_str(" }\n\n");
3589 } else {
3590 if body.code_bytes.len() > INLINE_NEVER_BYTECODE_THRESHOLD {
3591 out.push_str(" #[inline(never)]\n");
3592 }
3593 let _ = writeln!(
3594 out,
3595 " fn fn_{fn_idx}({}) -> std::result::Result<{ret_ty}, WasmTrap> {{",
3596 params_decl.join(", ")
3597 );
3598 out.push_str(&lowered_body);
3599 out.push_str(" }\n\n");
3600 }
3601 }
3602 out.push_str("}\n\n");
3603 Ok(())
3604}
3605
3606fn emit_standalone_module_source(
3607 module: &AnalyzedModule<'_>,
3608 input_sha256_hex: Option<&str>,
3609) -> Result<String> {
3610 let mut out =
3611 String::with_capacity(module.code_bodies.len().saturating_mul(256));
3612 emit_agpl_header(&mut out, module.name, input_sha256_hex);
3613 emit_data_and_elem_consts(&mut out, &module.parsed);
3614 emit_struct_and_instantiate(&mut out, module)?;
3615 emit_tail_call_types_and_dispatch(
3616 &mut out,
3617 &module.tail_target_fns,
3618 &module.fn_sigs,
3619 );
3620
3621 let all_fn_indices: Vec<usize> = (0..module.code_bodies.len()).collect();
3622 let call_mode = BundleCallMode::StandaloneSingleModule;
3623 emit_local_functions_impl(&mut out, module, &all_fn_indices, &call_mode)?;
3624 emit_trait_impl(&mut out, module, &call_mode)?;
3625
3626 let _ = writeln!(
3627 out,
3628 "/// Returns the native WebAssembly substitute descriptor for `{}`.\n\
3629 #[must_use]\n\
3630 pub fn descriptor() -> WasmSubstituteDescriptor {{\n\
3631 \x20 WasmSubstituteDescriptor {{\n\
3632 \x20 meta: MODULE_META,\n\
3633 \x20 instantiate: instantiate_substitute,\n\
3634 \x20 }}\n\
3635 }}",
3636 module.name
3637 );
3638 Ok(out)
3639}
3640
3641fn encode_hex_prefix_lower(bytes: &[u8], hex_chars: usize) -> String {
3642 let mut out = String::with_capacity(hex_chars);
3643 for &b in bytes {
3644 if out.len() >= hex_chars {
3645 break;
3646 }
3647 let _ = write!(out, "{b:02x}");
3648 }
3649 out.truncate(hex_chars);
3650 out
3651}
3652
3653fn validate_bundle_chunk_prefix(prefix: &str) -> Result<()> {
3654 ensure!(
3655 !prefix.is_empty(),
3656 "Substitute bundle chunk prefix must not be empty"
3657 );
3658 ensure!(
3659 prefix != "registry" && !prefix.starts_with("shared_"),
3660 "Reserved substitute bundle chunk prefix '{prefix}'"
3661 );
3662 ensure!(
3663 !prefix.starts_with('_') && !prefix.ends_with('_'),
3664 "Substitute bundle chunk prefix '{prefix}' must not start or end with '_'"
3665 );
3666 ensure!(
3667 prefix
3668 .chars()
3669 .all(|c| c.is_ascii_alphanumeric() || c == '_'),
3670 "Substitute bundle chunk prefix '{prefix}' contains invalid characters"
3671 );
3672 Ok(())
3673}
3674
3675fn emit_bundle_descriptor_submodule(
3676 out: &mut String,
3677 local_desc_idx: usize,
3678 module: &AnalyzedModule<'_>,
3679 norm_by_hash: &BTreeMap<[u8; 32], NormalizedFnTarget>,
3680 bundle_sigs: &BTreeMap<String, FnSigInfo>,
3681) -> Result<()> {
3682 emit_generated_allows(out, 0);
3683 let _ = writeln!(out, "pub(crate) mod desc_{local_desc_idx} {{");
3684 out.push_str(
3685 "#[allow(\n unused_imports,\n clippy::wildcard_imports,\n reason = \"Standard workspace module prelude\"\n)]\nuse crate::utilities::*;\n\
3686 #[allow(\n unused_imports,\n clippy::wildcard_imports,\n reason = \"Generated descriptor submodule imports\"\n)]\nuse super::*;\n\n",
3687 );
3688
3689 let mut inner =
3690 String::with_capacity(module.code_bodies.len().saturating_mul(128));
3691 emit_data_and_elem_consts(&mut inner, &module.parsed);
3692
3693 let mut local_fn_indices: Vec<usize> = Vec::new();
3694 for fn_idx in 0..module.code_bodies.len() {
3695 if Some(fn_idx) == module.cap_yield_func_idx {
3696 continue;
3697 }
3698 if let Some(Some(norm)) = module.norm_info.get(fn_idx) {
3699 if !norm.own_globals.is_empty() {
3700 let g_vals: Vec<String> = norm
3701 .own_globals
3702 .iter()
3703 .map(|&(_ty, slot)| format!("{slot}usize"))
3704 .collect();
3705 let _ = writeln!(
3706 inner,
3707 "const FN_{fn_idx}_GLOBALS: &[usize] = &[{}];",
3708 g_vals.join(", ")
3709 );
3710 }
3711 if !norm.own_callees.is_empty() {
3712 let mut c_vals: Vec<String> =
3713 Vec::with_capacity(norm.own_callees.len());
3714 for &callee_fn_idx in &norm.own_callees {
3715 let (_, bound_idx) = module
3716 .bound_idx_by_fn
3717 .get(callee_fn_idx)
3718 .and_then(Option::as_ref)
3719 .with_context(|| {
3720 format!(
3721 "Normalized callee fn_{callee_fn_idx} missing bound dispatch slot"
3722 )
3723 })?;
3724 c_vals.push(format!("{bound_idx}usize"));
3725 }
3726 let _ = writeln!(
3727 inner,
3728 "const FN_{fn_idx}_CALLEES: &[usize] = &[{}];",
3729 c_vals.join(", ")
3730 );
3731 }
3732 } else {
3733 local_fn_indices.push(fn_idx);
3734 let sig = module
3735 .fn_sigs
3736 .get(fn_idx)
3737 .context("Local function signature out of bounds")?;
3738 let mut adapter_params = vec![
3739 "vm: &mut SubstituteVm".to_owned(),
3740 "_dispatch: &'static crate::ModuleDispatch".to_owned(),
3741 "_g_map: &'static [usize]".to_owned(),
3742 "_c_map: &'static [usize]".to_owned(),
3743 ];
3744 let mut fwd_args =
3745 Vec::with_capacity(sig.params.len().saturating_add(2));
3746 fwd_args.push("vm".to_owned());
3747 for (i, pt) in sig.params.iter().enumerate() {
3748 adapter_params.push(format!("p{i}: {}", pt.rust_ty()));
3749 fwd_args.push(format!("p{i}"));
3750 }
3751 adapter_params
3752 .push("host: &mut dyn WasmSubstituteHost".to_owned());
3753 fwd_args.push("host".to_owned());
3754 let ret_ty = ret_type_expr(&sig.results);
3755 emit_generated_allows(&mut inner, 0);
3756 let _ = writeln!(
3757 inner,
3758 "fn bound_adapter_{fn_idx}({}) -> std::result::Result<{ret_ty}, WasmTrap> {{\n SubstituteInstance::fn_{fn_idx}({})\n}}\n",
3759 adapter_params.join(", "),
3760 fwd_args.join(", ")
3761 );
3762 }
3763 }
3764
3765 for sig_slug in bundle_sigs.keys() {
3766 let mut entries: Vec<String> = Vec::new();
3767 for fn_idx in 0..module.fn_sigs.len() {
3768 let Some((f_slug, _)) =
3769 module.bound_idx_by_fn.get(fn_idx).and_then(Option::as_ref)
3770 else {
3771 continue;
3772 };
3773 if f_slug != sig_slug {
3774 continue;
3775 }
3776 if let Some(Some(norm)) = module.norm_info.get(fn_idx) {
3777 let target = norm_by_hash.get(&norm.hash).with_context(|| {
3778 format!(
3779 "Normalized hash missing for fn_{fn_idx} in '{}'",
3780 module.name
3781 )
3782 })?;
3783 let g_ref = if norm.own_globals.is_empty() {
3784 "&[]".to_owned()
3785 } else {
3786 format!("FN_{fn_idx}_GLOBALS")
3787 };
3788 let c_ref = if norm.own_callees.is_empty() {
3789 "&[]".to_owned()
3790 } else {
3791 format!("FN_{fn_idx}_CALLEES")
3792 };
3793 entries.push(format!(
3794 " crate::Bound_{sig_slug} {{ func: crate::{}::ChunkFns::{}, globals: {g_ref}, callees: {c_ref} }},",
3795 target.rust_mod_ident, target.symbol_name
3796 ));
3797 } else {
3798 entries.push(format!(
3799 " crate::Bound_{sig_slug} {{ func: bound_adapter_{fn_idx}, globals: &[], callees: &[] }},"
3800 ));
3801 }
3802 }
3803 if !entries.is_empty() {
3804 let sig_upper = sig_slug.to_ascii_uppercase();
3805 emit_generated_allows(&mut inner, 0);
3806 let _ = writeln!(
3807 inner,
3808 "static BOUND_SIG_{sig_upper}: &[crate::Bound_{sig_slug}] = &[\n{}\n];\n",
3809 entries.join("\n")
3810 );
3811 }
3812 }
3813
3814 emit_generated_allows(&mut inner, 0);
3815 inner.push_str("static DISPATCH: crate::ModuleDispatch = crate::ModuleDispatch {\n");
3816 for sig_slug in bundle_sigs.keys() {
3817 let has_any = module
3818 .bound_idx_by_fn
3819 .iter()
3820 .flatten()
3821 .any(|(s, _)| s == sig_slug);
3822 if has_any {
3823 let sig_upper = sig_slug.to_ascii_uppercase();
3824 let _ = writeln!(
3825 inner,
3826 " sig_{sig_slug}: BOUND_SIG_{sig_upper},"
3827 );
3828 } else {
3829 let _ = writeln!(inner, " sig_{sig_slug}: &[],");
3830 }
3831 }
3832 inner.push_str("};\n\n");
3833
3834 emit_struct_and_instantiate(&mut inner, module)?;
3835 emit_tail_call_types_and_dispatch(
3836 &mut inner,
3837 &module.tail_target_fns,
3838 &module.fn_sigs,
3839 );
3840 let call_mode = BundleCallMode::BundleDescriptorLocal;
3841 emit_local_functions_impl(&mut inner, module, &local_fn_indices, &call_mode)?;
3842 emit_trait_impl(&mut inner, module, &call_mode)?;
3843
3844 let _ = writeln!(
3845 inner,
3846 "#[must_use]\n\
3847 pub(crate) fn descriptor() -> WasmSubstituteDescriptor {{\n\
3848 \x20 WasmSubstituteDescriptor {{\n\
3849 \x20 meta: MODULE_META,\n\
3850 \x20 instantiate: instantiate_substitute,\n\
3851 \x20 }}\n\
3852 }}"
3853 );
3854
3855 out.push_str(&inner);
3856 out.push_str("}\n\n");
3857 Ok(())
3858}
3859
3860fn emit_chunk_shard_source(
3861 file_stem: &str,
3862 fn_targets: &[&NormalizedFnTarget],
3863 desc_mod_indices: &[usize],
3864 analyzed_modules: &[AnalyzedModule<'_>],
3865 norm_by_hash: &BTreeMap<[u8; 32], NormalizedFnTarget>,
3866 bundle_sigs: &BTreeMap<String, FnSigInfo>,
3867) -> Result<String> {
3868 let mut out = String::with_capacity(
3869 fn_targets
3870 .len()
3871 .saturating_add(desc_mod_indices.len())
3872 .saturating_mul(256),
3873 );
3874 emit_chunk_file_header(&mut out, file_stem);
3875
3876 if !fn_targets.is_empty() {
3877 out.push_str(
3878 "/// Signature-normalized deduplicated WebAssembly functions first defined in this `.ctbnodes` chunk.\npub(crate) struct ChunkFns;\n\n",
3879 );
3880 emit_generated_allows(&mut out, 0);
3881 out.push_str("impl ChunkFns {\n");
3882 for target in fn_targets {
3883 let module = analyzed_modules
3884 .get(target.repr_mod_idx)
3885 .context("Representative module index out of bounds")?;
3886 let fn_idx = target.repr_fn_idx;
3887 let body = module
3888 .code_bodies
3889 .get(fn_idx)
3890 .context("Representative code body out of bounds")?;
3891 let sig = module
3892 .fn_sigs
3893 .get(fn_idx)
3894 .context("Representative signature out of bounds")?;
3895 let norm = module
3896 .norm_info
3897 .get(fn_idx)
3898 .and_then(Option::as_ref)
3899 .context("Normalized function missing metadata")?;
3900
3901 let mut global_pos_map: BTreeMap<(RustValTy, usize), usize> =
3902 BTreeMap::new();
3903 for (pos, &g_key) in norm.own_globals.iter().enumerate() {
3904 global_pos_map.insert(g_key, pos);
3905 }
3906 let mut callee_pos_map: BTreeMap<usize, usize> = BTreeMap::new();
3907 for (pos, &c_idx) in norm.own_callees.iter().enumerate() {
3908 callee_pos_map.insert(c_idx, pos);
3909 }
3910 let call_mode = BundleCallMode::NormalizedChunkFn {
3911 self_symbol_name: &target.symbol_name,
3912 global_pos_map,
3913 callee_pos_map,
3914 };
3915
3916 let use_self_tail = *module
3917 .has_self_tail
3918 .get(fn_idx)
3919 .context("Function index out of bounds in has_self_tail")?;
3920 let mut lowerer = FuncLowerer::new(
3921 fn_idx,
3922 module,
3923 &call_mode,
3924 false,
3925 use_self_tail,
3926 )?;
3927 let lowered_body = lowerer.lower_body(body.code_bytes)?;
3928
3929 let mut params_decl = vec![
3930 "vm: &mut SubstituteVm".to_owned(),
3931 "dispatch: &'static crate::ModuleDispatch".to_owned(),
3932 "g_map: &'static [usize]".to_owned(),
3933 "c_map: &'static [usize]".to_owned(),
3934 ];
3935 for (i, pt) in sig.params.iter().enumerate() {
3936 params_decl.push(format!("p{i}: {}", pt.rust_ty()));
3937 }
3938 params_decl.push("host: &mut dyn WasmSubstituteHost".to_owned());
3939
3940 let ret_ty = ret_type_expr(&sig.results);
3941 if body.code_bytes.len() > INLINE_NEVER_BYTECODE_THRESHOLD {
3942 out.push_str(" #[inline(never)]\n");
3943 }
3944 let _ = writeln!(
3945 out,
3946 " pub(crate) fn {}({}) -> std::result::Result<{ret_ty}, WasmTrap> {{",
3947 target.symbol_name,
3948 params_decl.join(", ")
3949 );
3950 out.push_str(&lowered_body);
3951 out.push_str(" }\n\n");
3952 }
3953 out.push_str("}\n\n");
3954 }
3955
3956 for (local_desc_idx, &mod_idx) in desc_mod_indices.iter().enumerate() {
3957 let module = analyzed_modules
3958 .get(mod_idx)
3959 .context("Descriptor module index out of bounds")?;
3960 emit_bundle_descriptor_submodule(
3961 &mut out,
3962 local_desc_idx,
3963 module,
3964 norm_by_hash,
3965 bundle_sigs,
3966 )?;
3967 }
3968
3969 Ok(out)
3970}
3971
3972fn emit_registry_dispatch_types(
3973 reg_out: &mut String,
3974 bundle_sigs: &BTreeMap<String, FnSigInfo>,
3975) {
3976 for (sig_slug, sig) in bundle_sigs {
3977 let mut fn_ptr_params = vec![
3978 "&mut SubstituteVm".to_owned(),
3979 "&'static ModuleDispatch".to_owned(),
3980 "&'static [usize]".to_owned(),
3981 "&'static [usize]".to_owned(),
3982 ];
3983 for pt in &sig.params {
3984 fn_ptr_params.push(pt.rust_ty().to_owned());
3985 }
3986 fn_ptr_params.push("&mut dyn WasmSubstituteHost".to_owned());
3987 let ret_ty = ret_type_expr(&sig.results);
3988 emit_generated_allows(reg_out, 0);
3989 let _ = writeln!(
3990 reg_out,
3991 "pub(crate) type Callee_{sig_slug} = fn({}) -> std::result::Result<{ret_ty}, WasmTrap>;\n",
3992 fn_ptr_params.join(", ")
3993 );
3994 emit_generated_allows(reg_out, 0);
3995 let _ = writeln!(
3996 reg_out,
3997 "#[derive(Clone, Copy)]\npub(crate) struct Bound_{sig_slug} {{\n pub(crate) func: Callee_{sig_slug},\n pub(crate) globals: &'static [usize],\n pub(crate) callees: &'static [usize],\n}}\n"
3998 );
3999 }
4000
4001 emit_generated_allows(reg_out, 0);
4002 reg_out.push_str("pub(crate) struct ModuleDispatch {\n");
4003 for sig_slug in bundle_sigs.keys() {
4004 let _ = writeln!(
4005 reg_out,
4006 " pub(crate) sig_{sig_slug}: &'static [Bound_{sig_slug}],",
4007 );
4008 }
4009 reg_out.push_str("}\n\n");
4010
4011 if !bundle_sigs.is_empty() {
4012 emit_generated_allows(reg_out, 0);
4013 reg_out.push_str("impl ModuleDispatch {\n");
4014 for (sig_slug, sig) in bundle_sigs {
4015 let ret_ty = ret_type_expr(&sig.results);
4016 let mut call_params = vec![
4017 "&'static self".to_owned(),
4018 "vm: &mut SubstituteVm".to_owned(),
4019 "c_map: &'static [usize]".to_owned(),
4020 "local_slot: usize".to_owned(),
4021 ];
4022 let mut direct_params = vec![
4023 "&'static self".to_owned(),
4024 "vm: &mut SubstituteVm".to_owned(),
4025 "bound_idx: usize".to_owned(),
4026 ];
4027 let mut invoke_args = vec![
4028 "vm".to_owned(),
4029 "self".to_owned(),
4030 "bound.globals".to_owned(),
4031 "bound.callees".to_owned(),
4032 ];
4033 for (i, pt) in sig.params.iter().enumerate() {
4034 let p_decl = format!("p{i}: {}", pt.rust_ty());
4035 call_params.push(p_decl.clone());
4036 direct_params.push(p_decl);
4037 invoke_args.push(format!("p{i}"));
4038 }
4039 call_params.push("host: &mut dyn WasmSubstituteHost".to_owned());
4040 direct_params.push("host: &mut dyn WasmSubstituteHost".to_owned());
4041 invoke_args.push("host".to_owned());
4042 let invoke_str = invoke_args.join(", ");
4043
4044 let _ = writeln!(
4045 reg_out,
4046 " #[inline(always)]\n pub(crate) fn call_{sig_slug}({}) -> std::result::Result<{ret_ty}, WasmTrap> {{\n let idx = *c_map.get(local_slot).ok_or(WasmTrap::Unreachable)?;\n let bound = self.sig_{sig_slug}.get(idx).ok_or(WasmTrap::Unreachable)?;\n (bound.func)({invoke_str})\n }}\n",
4047 call_params.join(", ")
4048 );
4049 let _ = writeln!(
4050 reg_out,
4051 " #[inline(always)]\n pub(crate) fn call_direct_{sig_slug}({}) -> std::result::Result<{ret_ty}, WasmTrap> {{\n let bound = self.sig_{sig_slug}.get(bound_idx).ok_or(WasmTrap::Unreachable)?;\n (bound.func)({invoke_str})\n }}\n",
4052 direct_params.join(", ")
4053 );
4054 }
4055 reg_out.push_str("}\n\n");
4056 }
4057}
4058
4059pub fn transpile_wasm_bundle_to_safe_rust(
4072 inputs: &[SubstituteBundleInput<'_>],
4073 input_sha256_hex: Option<&str>,
4074) -> Result<BTreeMap<String, String>> {
4075 #[derive(Clone, Copy)]
4076 enum ChunkItem {
4077 NormFn([u8; 32]),
4078 Descriptor(usize),
4079 }
4080
4081 let mut mod_idx_by_wasm_sha256: BTreeMap<[u8; 32], usize> = BTreeMap::new();
4082 let mut analyzed_modules: Vec<AnalyzedModule<'_>> =
4083 Vec::with_capacity(inputs.len());
4084 for input in inputs {
4085 validate_bundle_chunk_prefix(input.chunk_prefix)?;
4086 let digest: [u8; 32] = Sha256::digest(input.wasm_bytes).into();
4087 if let Some(&existing_idx) = mod_idx_by_wasm_sha256.get(&digest) {
4088 if let Some(gt) = input.graph_target
4089 && let Some(existing_mod) =
4090 analyzed_modules.get_mut(existing_idx)
4091 && !existing_mod.graph_targets.contains(>)
4092 {
4093 existing_mod.graph_targets.push(gt);
4094 }
4095 continue;
4096 }
4097 let mut analyzed = analyze_module(
4098 input.chunk_prefix,
4099 input.label,
4100 input.wasm_bytes,
4101 )?;
4102 if let Some(gt) = input.graph_target {
4103 analyzed.graph_targets.push(gt);
4104 }
4105 let assigned_idx = analyzed_modules.len();
4106 analyzed_modules.push(analyzed);
4107 mod_idx_by_wasm_sha256.insert(digest, assigned_idx);
4108 }
4109
4110 let mut bundle_sigs: BTreeMap<String, FnSigInfo> = BTreeMap::new();
4111 let mut first_repr: BTreeMap<[u8; 32], (usize, usize)> = BTreeMap::new();
4112 let mut chunk_items_by_prefix: BTreeMap<String, Vec<ChunkItem>> =
4113 BTreeMap::new();
4114
4115 for (mod_idx, m) in analyzed_modules.iter().enumerate() {
4116 for (fn_idx, sig) in m.fn_sigs.iter().enumerate() {
4117 if Some(fn_idx) != m.cap_yield_func_idx {
4118 let slug = full_fn_sig_slug(sig);
4119 bundle_sigs.entry(slug).or_insert_with(|| sig.clone());
4120 }
4121 }
4122 for (fn_idx, info_opt) in m.norm_info.iter().enumerate() {
4123 if let Some(info) = info_opt
4124 && !first_repr.contains_key(&info.hash)
4125 {
4126 first_repr.insert(info.hash, (mod_idx, fn_idx));
4127 chunk_items_by_prefix
4128 .entry(m.chunk_prefix.to_owned())
4129 .or_default()
4130 .push(ChunkItem::NormFn(info.hash));
4131 }
4132 }
4133 chunk_items_by_prefix
4134 .entry(m.chunk_prefix.to_owned())
4135 .or_default()
4136 .push(ChunkItem::Descriptor(mod_idx));
4137 }
4138
4139 let all_norm_hashes: Vec<[u8; 32]> = first_repr.keys().copied().collect();
4140 let mut prefix_hex_len = 12usize;
4141 for candidate_len in [12usize, 16, 24, 64] {
4142 let mut names_check: BTreeSet<String> = BTreeSet::new();
4143 let all_unique = all_norm_hashes.iter().all(|h| {
4144 names_check.insert(encode_hex_prefix_lower(h, candidate_len))
4145 });
4146 if all_unique {
4147 prefix_hex_len = candidate_len;
4148 break;
4149 }
4150 }
4151
4152 struct PlannedShard {
4154 file_stem: String,
4155 rust_mod_ident: String,
4156 fn_hashes: Vec<[u8; 32]>,
4157 desc_mod_indices: Vec<usize>,
4158 }
4159
4160 let mut planned_shards: Vec<PlannedShard> = Vec::new();
4161 let mut norm_by_hash: BTreeMap<[u8; 32], NormalizedFnTarget> =
4162 BTreeMap::new();
4163
4164 for (chunk_prefix, items) in &chunk_items_by_prefix {
4165 for (sub_idx, slice) in items.chunks(MAX_ITEMS_PER_CHUNK_FILE).enumerate()
4166 {
4167 let file_stem = if sub_idx == 0 {
4168 chunk_prefix.clone()
4169 } else {
4170 format!("{chunk_prefix}_{sub_idx}")
4171 };
4172 let rust_mod_ident = format!("c_{file_stem}");
4173 let mut fn_hashes = Vec::new();
4174 let mut desc_mod_indices = Vec::new();
4175 for &item in slice {
4176 match item {
4177 ChunkItem::NormFn(hash) => {
4178 let &(repr_mod_idx, repr_fn_idx) = first_repr
4179 .get(&hash)
4180 .context("Normalized hash missing representative")?;
4181 let hex_prefix =
4182 encode_hex_prefix_lower(&hash, prefix_hex_len);
4183 norm_by_hash.insert(
4184 hash,
4185 NormalizedFnTarget {
4186 hash,
4187 symbol_name: format!("f_{hex_prefix}"),
4188 file_stem: file_stem.clone(),
4189 rust_mod_ident: rust_mod_ident.clone(),
4190 repr_mod_idx,
4191 repr_fn_idx,
4192 },
4193 );
4194 fn_hashes.push(hash);
4195 }
4196 ChunkItem::Descriptor(mod_idx) => {
4197 desc_mod_indices.push(mod_idx);
4198 }
4199 }
4200 }
4201 planned_shards.push(PlannedShard {
4202 file_stem,
4203 rust_mod_ident,
4204 fn_hashes,
4205 desc_mod_indices,
4206 });
4207 }
4208 }
4209
4210 let mut files: BTreeMap<String, String> = BTreeMap::new();
4211 let mut reg_descriptors: Vec<(String, usize)> = Vec::new();
4212
4213 for shard in &planned_shards {
4214 let mut fn_targets: Vec<&NormalizedFnTarget> =
4215 Vec::with_capacity(shard.fn_hashes.len());
4216 for h in &shard.fn_hashes {
4217 fn_targets.push(
4218 norm_by_hash
4219 .get(h)
4220 .context("Planned normalized hash missing target entry")?,
4221 );
4222 }
4223 let src = emit_chunk_shard_source(
4224 &shard.file_stem,
4225 &fn_targets,
4226 &shard.desc_mod_indices,
4227 &analyzed_modules,
4228 &norm_by_hash,
4229 &bundle_sigs,
4230 )?;
4231 files.insert(format!("{}.generated.rs", shard.file_stem), src);
4232 for local_d in 0..shard.desc_mod_indices.len() {
4233 reg_descriptors.push((shard.rust_mod_ident.clone(), local_d));
4234 }
4235 }
4236
4237 let mut reg_out = String::new();
4238 emit_registry_header(&mut reg_out, input_sha256_hex);
4239 emit_registry_dispatch_types(&mut reg_out, &bundle_sigs);
4240 for shard in &planned_shards {
4241 let _ = writeln!(
4242 reg_out,
4243 "#[path = \"{}.generated.rs\"]\nmod {};",
4244 shard.file_stem, shard.rust_mod_ident
4245 );
4246 }
4247 emit_generated_allows(&mut reg_out, 0);
4248 reg_out.push_str("\nfn register_all_substitutes() {\n");
4249 for (rust_mod_ident, local_d) in ®_descriptors {
4250 let _ = writeln!(
4251 reg_out,
4252 " ctb_wasm_substitute_rt::register_substitute({rust_mod_ident}::desc_{local_d}::descriptor());"
4253 );
4254 }
4255 reg_out.push_str("}\n");
4256 files.insert("registry.generated.rs".to_owned(), reg_out);
4257
4258 Ok(files)
4259}
4260
4261pub fn validate_wasm_for_substitute(
4268 name: &str,
4269 wasm_bytes: &[u8],
4270) -> Result<()> {
4271 let _ = analyze_module(name, name, wasm_bytes)?;
4272 Ok(())
4273}
4274
4275pub fn transpile_wasm_to_safe_rust(
4284 wasm_bytes: &[u8],
4285 opts: &TranspileWasmOptions<'_>,
4286) -> Result<String> {
4287 let analyzed = analyze_module(opts.name, opts.name, wasm_bytes)?;
4288 emit_standalone_module_source(&analyzed, opts.input_sha256_hex)
4289}
4290
4291#[cfg(test)]
4292#[allow(
4293 clippy::panic,
4294 clippy::expect_used,
4295 clippy::unwrap_used,
4296 clippy::unwrap_in_result,
4297 clippy::panic_in_result_fn,
4298 clippy::indexing_slicing,
4299 clippy::arithmetic_side_effects,
4300 reason = "Standard repository test boilerplate"
4301)]
4302mod tests {
4303 use super::*;
4304 use crate::converters::wasm::{
4305 dcmstring_to_wasm_with_resolver,
4306 expand_graph_wasm_shorthands_to_dcmstring,
4307 };
4308 use crate::converters::wat::wat_to_wasm;
4309 use ctb_formats_dcdata::syntax::{SyntaxRuleResolver, default_syntax_resolver};
4310 use ctb_storage_minimal::shorthand::DcShorthand;
4311
4312 fn assert_clean_rust_common(src: &str) {
4313 assert!(!src.contains("#![allow"), "Unexpected crate-level allow");
4314 let after_header = src
4315 .split_once("use crate::utilities::*;")
4316 .expect("Generated file missing standard prelude")
4317 .1;
4318 let code_lines: String = after_header
4319 .lines()
4320 .filter(|l| {
4321 let t = l.trim_start();
4322 !t.starts_with("//")
4323 && !t.starts_with("const DATA_SEG_")
4324 && !l.ends_with('\\')
4325 && !t.ends_with("\";")
4326 })
4327 .collect::<Vec<_>>()
4328 .join("\n");
4329 assert!(
4330 !code_lines.contains(" as "),
4331 "Unexpected `as` cast in generated code"
4332 );
4333 assert!(
4334 !code_lines.contains(".unwrap("),
4335 "Unexpected `.unwrap(` in generated code"
4336 );
4337 assert!(
4338 !code_lines.contains(".expect("),
4339 "Unexpected `.expect(` in generated code"
4340 );
4341 assert!(
4342 !code_lines.contains(".unwrap_or("),
4343 "Unexpected `.unwrap_or(` in generated code"
4344 );
4345 assert!(
4346 !code_lines.contains("unsafe"),
4347 "Unexpected `unsafe` block in generated code"
4348 );
4349 }
4350
4351 fn assert_clean_generated_rust(src: &str) {
4352 assert_clean_rust_common(src);
4353 assert!(src.contains("pub fn descriptor() -> WasmSubstituteDescriptor"));
4354 }
4355
4356 #[crate::ctb_test]
4357 fn test_transpile_structured_control_flow_tail_calls_and_segments() {
4358 let wat = r#"(module
4359 (memory 1 4)
4360 (global $__heap_ptr (export "__heap_ptr") (mut i32) (i32.const 1024))
4361 (data (i32.const 64) "hello\00world")
4362 (func $__ctb_capability_yield (export "__ctb_capability_yield")
4363 nop
4364 )
4365 (func $dag_leaf (param $x i32) (result i32)
4366 (i32.add (local.get $x) (i32.const 7))
4367 )
4368 (func $dag_caller (param $x i32) (result i32)
4369 (return_call $dag_leaf (i32.add (local.get $x) (i32.const 1)))
4370 )
4371 (func $even (param $n i32) (result i32)
4372 (if (result i32) (i32.eqz (local.get $n))
4373 (then (i32.const 1))
4374 (else (return_call $odd (i32.sub (local.get $n) (i32.const 1))))
4375 )
4376 )
4377 (func $odd (param $n i32) (result i32)
4378 (if (result i32) (i32.eqz (local.get $n))
4379 (then (i32.const 0))
4380 (else (return_call $even (i32.sub (local.get $n) (i32.const 1))))
4381 )
4382 )
4383 (func $self_tail (param $n i32) (param $acc i32) (result i32)
4384 (if (result i32) (i32.eqz (local.get $n))
4385 (then (local.get $acc))
4386 (else
4387 (return_call $self_tail
4388 (i32.sub (local.get $n) (i32.const 1))
4389 (i32.add (local.get $acc) (i32.const 2))
4390 )
4391 )
4392 )
4393 )
4394 (func (export "step") (result i32)
4395 (local $i i32)
4396 (call $__ctb_capability_yield)
4397 (drop (call $dag_caller (i32.const 3)))
4398 (drop (call $even (i32.const 5)))
4399 (drop (call $self_tail (i32.const 4) (i32.const 0)))
4400 (drop (memory.grow (i32.const 1)))
4401 (loop $l
4402 (local.set $i (i32.add (local.get $i) (i32.const 1)))
4403 (br_if $l (i32.lt_s (local.get $i) (i32.const 3)))
4404 )
4405 (block
4406 (br_table 0 0 (i32.const 1))
4407 (drop (i32.const 999))
4408 )
4409 (i32.const 0)
4410 )
4411 )"#;
4412 let wasm_bytes = wat_to_wasm(wat).expect("WAT compilation must succeed");
4413 let generated = transpile_wasm_to_safe_rust(
4414 &wasm_bytes,
4415 &TranspileWasmOptions {
4416 name: "unit_smoke",
4417 input_sha256_hex: Some("deadbeef"),
4418 },
4419 )
4420 .expect("Transpiling test WASM must succeed");
4421
4422 assert_clean_generated_rust(&generated);
4423 assert!(generated.contains("TailTarget_i32"));
4424 assert!(!generated.contains("TailTarget_i32::Func1("));
4426 assert!(generated.contains("return SubstituteInstance::fn_1(vm, "));
4427 assert!(generated.contains("'self_tail: loop"));
4428 assert!(generated.contains("host.request_capability(vm)"));
4429 assert!(generated.contains("vm.memory_grow("));
4430 assert!(generated.contains("input-sha256: deadbeef"));
4431 }
4432
4433 #[crate::ctb_test]
4434 fn test_transpile_raw_binary_indirect_calls_passive_data_and_start() {
4435 let mut raw_wasm = WASM_HEADER.to_vec();
4436 let push_sec = |id: u8, payload: &[u8], out: &mut Vec<u8>| {
4437 out.push(id);
4438 out.push(u8::try_from(payload.len()).unwrap());
4439 out.extend_from_slice(payload);
4440 };
4441 push_sec(
4443 1,
4444 &[3, 0x60, 2, 0x7F, 0x7F, 1, 0x7F, 0x60, 0, 0, 0x60, 0, 1, 0x7F],
4445 &mut raw_wasm,
4446 );
4447 push_sec(3, &[3, 1, 0, 2], &mut raw_wasm);
4449 push_sec(4, &[1, 0x70, 0, 2], &mut raw_wasm);
4451 push_sec(5, &[1, 0, 1], &mut raw_wasm);
4453 push_sec(
4455 7,
4456 &[
4457 2, 6, b'm', b'e', b'm', b'o', b'r', b'y', 2, 0, 4, b'm',
4458 b'a', b'i', b'n', 0, 2,
4459 ],
4460 &mut raw_wasm,
4461 );
4462 push_sec(8, &[0], &mut raw_wasm);
4464 push_sec(9, &[1, 0, 0x41, 0, 0x0B, 1, 1], &mut raw_wasm);
4466 push_sec(12, &[1], &mut raw_wasm);
4468 #[rustfmt::skip]
4470 let bodies: [&[u8]; 3] = [
4471 &[0, 0x01, 0x0B],
4473 &[
4475 0,
4476 0x20, 0x00, 0x45,
4477 0x04, 0x7F,
4478 0x20, 0x01,
4479 0x05,
4480 0x20, 0x00, 0x41, 0x01, 0x6B,
4481 0x20, 0x01, 0x41, 0x01, 0x6A,
4482 0x41, 0x00,
4483 0x13, 0x00, 0x00,
4484 0x0B,
4485 0x0B,
4486 ],
4487 &[
4489 0,
4490 0x41, 0x10, 0x41, 0x00, 0x41, 0x02, 0xFC, 0x08, 0x00, 0x00,
4491 0xFC, 0x09, 0x00,
4492 0x41, 0x02, 0x41, 0x0A, 0x41, 0x00, 0x11, 0x00, 0x00,
4493 0x0B,
4494 ],
4495 ];
4496 let mut code_payload = vec![u8::try_from(bodies.len()).unwrap()];
4497 for body in bodies {
4498 code_payload.push(u8::try_from(body.len()).unwrap());
4499 code_payload.extend_from_slice(body);
4500 }
4501 push_sec(10, &code_payload, &mut raw_wasm);
4502 push_sec(11, &[1, 1, 2, b'o', b'k'], &mut raw_wasm);
4504
4505 let generated = transpile_wasm_to_safe_rust(
4506 &raw_wasm,
4507 &TranspileWasmOptions {
4508 name: "raw_smoke",
4509 input_sha256_hex: None,
4510 },
4511 )
4512 .expect("Transpiling raw binary must succeed");
4513 assert_clean_generated_rust(&generated);
4514 assert!(generated.contains("call_indirect_target"));
4515 assert!(generated.contains("vm.memory_init("));
4516 assert!(generated.contains("vm.data_drop("));
4517 assert!(generated.contains("TailTarget_i32"));
4518 assert!(generated.contains("has_start_func: true"));
4519 }
4520
4521 #[crate::ctb_test]
4522 fn test_transpile_wasm_bundle_merkle_dedup_and_global_remapping()
4523 -> Result<()> {
4524 let wat_a = r#"(module
4527 (memory (export "memory") 1)
4528 (global $cnt (mut i32) (i32.const 10))
4529 (global $__heap_ptr (export "__heap_ptr") (mut i32) (i32.const 256))
4530 (func $init_vals
4531 (global.set $cnt (i32.const 20))
4532 )
4533 (func $sum_rec (param $n i32) (param $acc i32) (result i32)
4534 (if (result i32) (i32.eqz (local.get $n))
4535 (then (local.get $acc))
4536 (else
4537 (return_call $sum_rec
4538 (i32.sub (local.get $n) (i32.const 1))
4539 (i32.add (local.get $acc) (local.get $n))
4540 )
4541 )
4542 )
4543 )
4544 (func $work (param $x i32) (result i32)
4545 (call $init_vals)
4546 (block (result i32)
4547 (i32.add (local.get $x) (global.get $cnt))
4548 (global.set $__heap_ptr (i32.add (global.get $__heap_ptr) (i32.const 8)))
4549 )
4550 (return_call $sum_rec (i32.const 4))
4551 )
4552 (func (export "step") (result i32)
4553 (call $init_vals)
4554 (i32.add (call $work (i32.const 5)) (global.get $cnt))
4555 )
4556 )"#;
4557
4558 let wat_b = r#"(module
4562 (memory (export "memory") 1)
4563 (global $__heap_ptr (export "__heap_ptr") (mut i32) (i32.const 512))
4564 (global $pad (mut i32) (i32.const 99))
4565 (global $cnt (mut i32) (i32.const 30))
4566 (func $extra_sig (param $v i64) (result i64)
4567 (i64.add (local.get $v) (i64.const 1))
4568 )
4569 (func $init_vals_b
4570 (global.set $cnt (i32.add (global.get $pad) (i32.const 1)))
4571 )
4572 (func $sum_rec (param $n i32) (param $acc i32) (result i32)
4573 (if (result i32) (i32.eqz (local.get $n))
4574 (then (local.get $acc))
4575 (else
4576 (return_call $sum_rec
4577 (i32.sub (local.get $n) (i32.const 1))
4578 (i32.add (local.get $acc) (local.get $n))
4579 )
4580 )
4581 )
4582 )
4583 (func $work (param $x i32) (result i32)
4584 (call $init_vals_b)
4585 (block (result i32)
4586 (i32.add (local.get $x) (global.get $cnt))
4587 (global.set $__heap_ptr (i32.add (global.get $__heap_ptr) (i32.const 8)))
4588 )
4589 (return_call $sum_rec (i32.const 4))
4590 )
4591 (func (export "step") (result i32)
4592 (call $init_vals_b)
4593 (drop (call $extra_sig (i64.const 7)))
4594 (i32.mul (call $work (i32.const 6)) (i32.const 2))
4595 )
4596 )"#;
4597
4598 let wasm_a = wat_to_wasm(wat_a)?;
4599 let wasm_b = wat_to_wasm(wat_b)?;
4600 let files = transpile_wasm_bundle_to_safe_rust(
4601 &[
4602 SubstituteBundleInput {
4603 chunk_prefix: "85899_34592",
4604 label: "85899_34592/rev1",
4605 wasm_bytes: &wasm_a,
4606 graph_target: Some((1936, [0x11; 32])),
4607 },
4608 SubstituteBundleInput {
4609 chunk_prefix: "85899_34692",
4610 label: "85899_34692/rev2",
4611 wasm_bytes: &wasm_b,
4612 graph_target: Some((2608, [0x22; 32])),
4613 },
4614 ],
4615 Some("bundle123"),
4616 )?;
4617
4618 let keys: Vec<&str> = files.keys().map(String::as_str).collect();
4619 assert_eq!(
4620 keys,
4621 vec![
4622 "85899_34592.generated.rs",
4623 "85899_34692.generated.rs",
4624 "registry.generated.rs",
4625 ]
4626 );
4627
4628 let chunk_a_rs = files
4629 .get("85899_34592.generated.rs")
4630 .context("Missing 85899_34592.generated.rs")?;
4631 let chunk_b_rs = files
4632 .get("85899_34692.generated.rs")
4633 .context("Missing 85899_34692.generated.rs")?;
4634 assert_clean_rust_common(chunk_a_rs);
4635 assert_clean_rust_common(chunk_b_rs);
4636 assert!(chunk_a_rs.contains("pub(crate) struct ChunkFns;"));
4637 assert!(chunk_b_rs.contains("pub(crate) struct ChunkFns;"));
4638 assert!(chunk_a_rs.contains("vm.heap_ptr"));
4639 assert!(chunk_a_rs.contains("'self_tail: loop"));
4640 let (chunk_a_fns, _) = chunk_a_rs
4646 .split_once("pub(crate) mod desc_0")
4647 .context("Missing desc_0 in chunk A")?;
4648 let (chunk_b_fns, _) = chunk_b_rs
4649 .split_once("pub(crate) mod desc_0")
4650 .context("Missing desc_0 in chunk B")?;
4651 assert_eq!(chunk_a_fns.matches("pub(crate) fn f_").count(), 4);
4652 assert_eq!(chunk_b_fns.matches("pub(crate) fn f_").count(), 3);
4653 assert!(!chunk_b_rs.contains("'self_tail: loop"));
4654 assert!(!chunk_b_fns.contains("vm.heap_ptr"));
4655 assert!(chunk_b_rs.contains("crate::c_85899_34592::ChunkFns::f_"));
4656 assert!(chunk_a_rs.contains("&[0usize]"));
4658 assert!(chunk_b_rs.contains("&[1usize]"));
4659
4660 let reg_rs = files
4661 .get("registry.generated.rs")
4662 .context("Missing registry.generated.rs")?;
4663 assert!(reg_rs.contains("// @generated by ctb-wasm-substitutes-gen"));
4664 assert!(reg_rs.contains("// input-sha256: bundle123"));
4665 assert!(reg_rs.contains("pub(crate) struct ModuleDispatch"));
4666 assert!(reg_rs.contains("#[path = \"85899_34592.generated.rs\"]\nmod c_85899_34592;"));
4667 assert!(reg_rs.contains("#[path = \"85899_34692.generated.rs\"]\nmod c_85899_34692;"));
4668 assert!(reg_rs.contains("register_substitute(c_85899_34592::desc_0::descriptor());"));
4669 assert!(reg_rs.contains("register_substitute(c_85899_34692::desc_0::descriptor());"));
4670 Ok(())
4671 }
4672
4673 #[crate::ctb_test]
4674 fn test_transpile_real_dc_1936_and_f1680_from_seed_graph() -> Result<()> {
4675 let resolver = default_syntax_resolver();
4676 let sg = resolver
4677 .seed_graph()
4678 .context("Default resolver missing seed_graph")?;
4679
4680 let kernel_sh = DcShorthand::from_global_id(
4682 ctb_formats_dcdata::dc::DC_DC_DOCUMENT_EXECUTION_KERNEL.to_u128(),
4683 );
4684 let (_, kernel_tokens) = sg
4685 .resolve_wasm_helper_shorthand(kernel_sh)?
4686 .context("Dc 1936 missing active WASM decomposition")?;
4687 let kernel_doc = expand_graph_wasm_shorthands_to_dcmstring(
4688 kernel_tokens,
4689 resolver.as_ref(),
4690 )?;
4691 let kernel_wasm =
4692 dcmstring_to_wasm_with_resolver(&kernel_doc, resolver.as_ref())?;
4693 let kernel_rs = transpile_wasm_to_safe_rust(
4694 &kernel_wasm,
4695 &TranspileWasmOptions {
4696 name: "dc_1936",
4697 input_sha256_hex: None,
4698 },
4699 )?;
4700 assert_clean_generated_rust(&kernel_rs);
4701 assert!(
4702 kernel_rs.contains("entry_func_name: \"main\"")
4703 || kernel_rs.contains("entry_func_name: \"step\"")
4704 );
4705
4706 let stagel_src = DcShorthand::from_global_id(
4708 ctb_formats_dcdata::dc::DC_BEGIN_MODULE.to_u128(),
4709 );
4710 let wasm_dst = DcShorthand::from_global_id(
4711 ctb_formats_dcdata::dc::DC_BEGIN_WASM_PROGRAM.to_u128(),
4712 );
4713 let (_, f1680_tokens) = sg
4714 .resolve_active_converter_routine(stagel_src, wasm_dst)?
4715 .context("Dc f1680 missing active WASM converter routine")?;
4716 let f1680_doc = expand_graph_wasm_shorthands_to_dcmstring(
4717 f1680_tokens,
4718 resolver.as_ref(),
4719 )?;
4720 let f1680_wasm =
4721 dcmstring_to_wasm_with_resolver(&f1680_doc, resolver.as_ref())?;
4722 let f1680_rs = transpile_wasm_to_safe_rust(
4723 &f1680_wasm,
4724 &TranspileWasmOptions {
4725 name: "f1680",
4726 input_sha256_hex: None,
4727 },
4728 )?;
4729 assert_clean_generated_rust(&f1680_rs);
4730 assert!(f1680_rs.contains("entry_func_name: \"step\"") || f1680_rs.contains("entry_func_name: \"main\""));
4731
4732 Ok(())
4733 }
4734}