ctb_formats_dcstring/converters/
wat.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Converter from WebAssembly Text Format (`.wat`) to `.WASM` Document Character
21//! streams ([`DcMstring`], [`DcString`], [`DcList`]) and binary `.wasm` modules.
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use crate::converters::dctext::DcList;
31use crate::converters::wasm::{
32    dcmstring_to_wasm, dcmstring_to_wasm_with_resolver,
33};
34use crate::{DcChar, DcMstring, DcProjectionPolicy, DcString};
35use ctb_formats_dcdata::syntax::{SyntaxRuleResolver, default_syntax_resolver};
36pub use ctb_formats_dcdata::wat::{
37    wat_to_dc_shorthand_string, wat_to_dc_shorthands,
38};
39
40/// Converts WebAssembly Text Format (`.wat`) source into a [`DcString`] containing
41/// a `.WASM` Document Character stream (`Dc 1927`..`Dc 1928`).
42///
43/// # Errors
44/// Returns an error if the `.wat` source fails to parse or contains unsupported instructions.
45pub fn wat_to_dcstring(wat_src: &str) -> Result<DcString> {
46    let shorthands = wat_to_dc_shorthands(wat_src)?;
47    let mut dc_str = DcString::new();
48    for sh in shorthands {
49        dc_str.push(DcChar::from_u128(sh.to_global_id()?));
50    }
51    Ok(dc_str)
52}
53
54/// Converts WebAssembly Text Format (`.wat`) source into a [`DcList`] of Global Graph IDs.
55///
56/// # Errors
57/// Returns an error if the `.wat` source fails to parse or contains unsupported instructions.
58pub fn wat_to_dclist(wat_src: &str) -> Result<DcList> {
59    let shorthands = wat_to_dc_shorthands(wat_src)?;
60    shorthands
61        .into_iter()
62        .map(|s| s.to_global_id().map_err(anyhow::Error::from))
63        .collect()
64}
65
66/// Converts WebAssembly Text Format (`.wat`) source into a [`DcMstring`] containing
67/// a `.WASM` Document Character stream (`Dc 1927`..`Dc 1928`).
68///
69/// # Errors
70/// Returns an error if the `.wat` source fails to parse or cannot be encoded into `DcMstring`.
71pub fn wat_to_dcmstring(wat_src: &str) -> Result<DcMstring> {
72    let resolver = default_syntax_resolver();
73    wat_to_dcmstring_with_resolver(wat_src, resolver.as_ref())
74}
75
76/// Converts WebAssembly Text Format (`.wat`) source into a [`DcMstring`] using `resolver`.
77///
78/// # Errors
79/// Returns an error if the `.wat` source fails to parse or cannot be encoded into `DcMstring`.
80pub fn wat_to_dcmstring_with_resolver(
81    wat_src: &str,
82    resolver: &dyn SyntaxRuleResolver,
83) -> Result<DcMstring> {
84    let dc_str = wat_to_dcstring(wat_src)?;
85    DcMstring::from_dc_str_with_policy_and_resolver(
86        &dc_str,
87        &DcProjectionPolicy::strict(),
88        resolver,
89    )
90}
91
92/// Converts WebAssembly Text Format (`.wat`) source into a binary `.wasm` module
93/// via the canonical `.WASM` Document Character pipeline (`wat -> DcMstring -> .wasm`).
94///
95/// # Errors
96/// Returns an error if the `.wat` source fails to parse or assemble into binary WebAssembly.
97pub fn wat_to_wasm(wat_src: &str) -> Result<Vec<u8>> {
98    let mstr = wat_to_dcmstring(wat_src)?;
99    dcmstring_to_wasm(&mstr)
100}
101
102/// Converts WebAssembly Text Format (`.wat`) source into a binary `.wasm` module
103/// using `resolver`.
104///
105/// # Errors
106/// Returns an error if the `.wat` source fails to parse or assemble into binary WebAssembly.
107pub fn wat_to_wasm_with_resolver(
108    wat_src: &str,
109    resolver: &dyn SyntaxRuleResolver,
110) -> Result<Vec<u8>> {
111    let mstr = wat_to_dcmstring_with_resolver(wat_src, resolver)?;
112    dcmstring_to_wasm_with_resolver(&mstr, resolver)
113}
114
115#[cfg(test)]
116#[allow(
117    clippy::panic,
118    clippy::expect_used,
119    clippy::unwrap_used,
120    clippy::unwrap_in_result,
121    clippy::panic_in_result_fn,
122    clippy::indexing_slicing,
123    clippy::arithmetic_side_effects,
124    reason = "Standard repository test boilerplate"
125)]
126mod tests {
127    use super::*;
128    use crate::converters::wasm::{DcWasmSession, WasmStepOutcome};
129
130    #[crate::ctb_test]
131    fn test_wat_to_dcmstring_and_tinywasm_execution() -> Result<()> {
132        let wat = r#"
133            (module
134              (func (export "main") (result i32)
135                ;; Copy input mailbox (0..8) to output mailbox (8..16)
136                (i32.store (i32.const 8) (i32.load (i32.const 0)))
137                (i32.store (i32.const 12) (i32.load (i32.const 4)))
138                (i32.const 0)))
139        "#;
140        let mstr = wat_to_dcmstring(wat)?;
141        let mut input = DcMstring::new();
142        input.push_str("Hello from WAT!");
143        let mut session = DcWasmSession::from_dc_wasm(&mstr, &input, None)?;
144        let WasmStepOutcome::Complete(out) = session.step()? else {
145            bail!("Expected Complete step outcome");
146        };
147        assert_eq!(out.to_dc_string()?, input.to_dc_string()?);
148        Ok(())
149    }
150
151    #[crate::ctb_test]
152    fn test_wat_mutual_return_call_constant_stack_and_quota_resumption()
153    -> Result<()> {
154        // 5,000 mutual tail-recursive calls between `$ping` and `$pong` (nearly 5x
155        // `tinywasm`'s `MAX_CALL_STACK_SIZE = 1024`), including dead intermediate
156        // values and nested `block`/`if` frames that must be unwound on `return_call`.
157        let wat = r#"
158            (module
159              (func $ping (param $n i32) (param $acc i32) (result i32)
160                (if (result i32) (i32.le_s (local.get $n) (i32.const 0))
161                  (then (local.get $acc))
162                  (else
163                    (block (result i32)
164                      ;; Push a dead intermediate value onto the stack before preparing
165                      ;; tail-call arguments inside a nested block, then `return_call`.
166                      (i32.const 999999)
167                      (return_call $pong
168                        (i32.sub (local.get $n) (i32.const 1))
169                        (i32.add (local.get $acc) (i32.const 1)))))))
170              (func $pong (param $n i32) (param $acc i32) (result i32)
171                (if (result i32) (i32.le_s (local.get $n) (i32.const 0))
172                  (then (local.get $acc))
173                  (else
174                    (return_call $ping
175                      (i32.sub (local.get $n) (i32.const 1))
176                      (i32.add (local.get $acc) (i32.const 2))))))
177              (func (export "main") (result i32)
178                ;; Store sum in scratch linear memory at 64, echo input mailbox, return 0
179                (i32.store (i32.const 64) (call $ping (i32.const 5000) (i32.const 0)))
180                (i32.store (i32.const 8) (i32.load (i32.const 0)))
181                (i32.store (i32.const 12) (i32.load (i32.const 4)))
182                (i32.const 0)))
183        "#;
184        let mstr = wat_to_dcmstring(wat)?;
185        let mut input = DcMstring::new();
186        input.push_str("ok");
187
188        let resolver = ctb_formats_dcdata::syntax::default_syntax_resolver();
189        let limits = crate::converters::wasm::DcWasmResourceLimits::default()
190            .with_max_instructions_per_step(5_000);
191        let mut session = DcWasmSession::from_dc_wasm_with_limits(
192            &mstr,
193            &input,
194            None,
195            resolver.as_ref(),
196            limits,
197        )?;
198        let err = session
199            .step()
200            .expect_err("5,000 mutual tail calls must suspend at initial quota");
201        assert!(
202            err.downcast_ref::<crate::converters::wasm::WasmResourceInterruption>()
203                .is_some()
204        );
205
206        session.increase_compute_quota(100_000);
207        let WasmStepOutcome::Complete(out) = session.step()? else {
208            bail!("Expected Complete step outcome after quota resumption");
209        };
210        assert_eq!(out.to_dc_string()?, input.to_dc_string()?);
211        // 2,500 `$ping` steps (+1 each) + 2,500 `$pong` steps (+2 each) = 7,500
212        assert_eq!(session.read_memory(64, 4)?, 7_500_i32.to_le_bytes());
213        Ok(())
214    }
215
216    #[crate::ctb_test]
217    fn test_tinywasm_return_call_indirect_constant_stack() -> Result<()> {
218        // Minimal raw WASM module with a 2-entry `funcref` table (`$even_step` = 0, `$odd_step` = 1)
219        // performing 4,000 mutual `return_call_indirect` hops (> 1,024 frame limit).
220        let wasm_bytes: Vec<u8> = vec![
221            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // magic + version
222            // Section 1: Type — type 0: (i32, i32) -> i32, type 1: () -> i32
223            0x01, 0x0b, 0x02,
224            0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f,
225            0x60, 0x00, 0x01, 0x7f,
226            // Section 3: Function — func 0 (type 0), func 1 (type 0), func 2 (type 1)
227            0x03, 0x04, 0x03, 0x00, 0x00, 0x01,
228            // Section 4: Table — 1 funcref table, min 2 max 2
229            0x04, 0x05, 0x01, 0x70, 0x01, 0x02, 0x02,
230            // Section 5: Memory — 1 page
231            0x05, 0x03, 0x01, 0x00, 0x01,
232            // Section 7: Export — "memory" (mem 0) and "main" (func 2)
233            0x07, 0x11, 0x02,
234            0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
235            0x04, b'm', b'a', b'i', b'n', 0x00, 0x02,
236            // Section 9: Element — active table 0 at offset 0: [func 0, func 1]
237            0x09, 0x08, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x02, 0x00, 0x01,
238            // Section 10: Code (1 + 31 + 29 + 17 = 78 = 0x4e)
239            0x0a, 0x4e, 0x03,
240            // func 0 ($step0, 30 = 0x1e bytes): if local 0 <= 0 { local 1 } else { return_call_indirect(type 0, table 0) (local0 - 1, local1 + 3, idx = 1) }
241            0x1e, 0x00,
242            0x20, 0x00, 0x41, 0x00, 0x4c, // i32.le_s(n, 0)
243            0x04, 0x7f, // if (result i32)
244            0x20, 0x01, // then: acc
245            0x05,       // else:
246            0x41, 0x2a, // dead stack value 42 before tail call args
247            0x20, 0x00, 0x41, 0x01, 0x6b, // n - 1
248            0x20, 0x01, 0x41, 0x03, 0x6a, // acc + 3
249            0x41, 0x01, // table index 1
250            0x13, 0x00, 0x00, // return_call_indirect type=0 table=0
251            0x0b, 0x0b,
252            // func 1 ($step1, 28 = 0x1c bytes): if local 0 <= 0 { local 1 } else { return_call_indirect(type 0, table 0) (local0 - 1, local1 + 1, idx = 0) }
253            0x1c, 0x00,
254            0x20, 0x00, 0x41, 0x00, 0x4c,
255            0x04, 0x7f,
256            0x20, 0x01,
257            0x05,
258            0x20, 0x00, 0x41, 0x01, 0x6b, // n - 1
259            0x20, 0x01, 0x41, 0x01, 0x6a, // acc + 1
260            0x41, 0x00, // table index 0
261            0x13, 0x00, 0x00, // return_call_indirect type=0 table=0
262            0x0b, 0x0b,
263            // func 2 (main): mem[32] = call 0(4000, 0); return 0
264            0x10, 0x00,
265            0x41, 0x20, // addr 32
266            0x41, 0xa0, 0x1f, // 4000
267            0x41, 0x00, // 0
268            0x10, 0x00, // call 0
269            0x36, 0x02, 0x00, // i32.store
270            0x41, 0x00, // 0
271            0x0b,
272        ];
273        let mut session = DcWasmSession::from_wasm_bytes(
274            &wasm_bytes,
275            &DcMstring::new(),
276            None,
277        )?;
278        let outcome = session.step()?;
279        assert!(matches!(outcome, WasmStepOutcome::Complete(_)));
280        // 2,000 steps of +3 and 2,000 steps of +1 = 8,000
281        assert_eq!(session.read_memory(32, 4)?, 8_000_i32.to_le_bytes());
282        Ok(())
283    }
284}