ctb_formats_dcdata/support/
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//! WebAssembly Text Format (`.wat`) to Document Character (`.WASM` Dc stream) converter
21//! and staged Dc implementation loader (`stage_0_impls/`, `stage_1_impls/`, `impls/`).
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use crate::dc::{
31    DC_BASE64_PADDING, DC_BEGIN_IDENTIFIER, DC_BEGIN_KV_MAP, DC_BEGIN_KV_PAIR,
32    DC_BEGIN_LIST, DC_BEGIN_LITERAL, DC_BEGIN_MODULE, DC_BEGIN_TYPE_DEF,
33    DC_BEGIN_WASM_PROGRAM, DC_END_ENCAPSULATION_BINARY, DC_END_IDENTIFIER,
34    DC_END_KV_MAP, DC_END_KV_PAIR, DC_END_LIST, DC_END_LITERAL,
35    DC_END_TYPE_DEF, DC_END_WASM_PROGRAM, DC_LIST_ELEMENT_SEPARATOR,
36    DC_NEGATIVE, DC_OPTIONAL_ABSENT, DC_START_ENCAPSULATION_BINARY,
37    DC_TYPE_ANY, DC_TYPE_ROUTINE, DC_WASM_START,
38};
39use crate::dc_char::DcChar;
40use crate::dc_number_minimal::{dc_base64_digit_to_char, u128_to_dc_number_chars};
41use anyhow::anyhow;
42use ctb_storage_minimal::shorthand::DcShorthand;
43use std::collections::BTreeMap;
44use std::path::Path;
45
46const FORMAT_INTEGER: usize = 199;
47const FORMAT_I32: usize = 208;
48const FORMAT_I64: usize = 210;
49const FORMAT_I128: usize = 212;
50const FORMAT_F32: usize = 216;
51const FORMAT_F64: usize = 217;
52const SHORT_TYPE_META: u32 = 565;
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55enum WatValType {
56    I32,
57    I64,
58    F32,
59    F64,
60    V128,
61}
62
63impl WatValType {
64    fn from_name(s: &str) -> Option<Self> {
65        match s {
66            "i32" => Some(Self::I32),
67            "i64" => Some(Self::I64),
68            "f32" => Some(Self::F32),
69            "f64" => Some(Self::F64),
70            "v128" => Some(Self::V128),
71            _ => None,
72        }
73    }
74
75    const fn to_shorthand(self) -> DcShorthand {
76        match self {
77            Self::I32 => DcShorthand::Format(FORMAT_I32),
78            Self::I64 => DcShorthand::Format(FORMAT_I64),
79            Self::F32 => DcShorthand::Format(FORMAT_F32),
80            Self::F64 => DcShorthand::Format(FORMAT_F64),
81            Self::V128 => DcShorthand::Format(FORMAT_I128),
82        }
83    }
84}
85
86#[derive(Debug, Clone, PartialEq, Eq)]
87enum WatToken {
88    LParen,
89    RParen,
90    Atom(String),
91    StringLit(Vec<u8>),
92    ContextDirective(Vec<DcShorthand>),
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
96enum SExpr {
97    Atom(String),
98    StringLit(Vec<u8>),
99    List(Vec<Self>),
100    ContextDirective(Vec<DcShorthand>),
101}
102
103impl SExpr {
104    fn as_atom(&self) -> Option<&str> {
105        match self {
106            Self::Atom(s) => Some(s.as_str()),
107            _ => None,
108        }
109    }
110
111    fn as_list(&self) -> Option<&[Self]> {
112        match self {
113            Self::List(items) => Some(items.as_slice()),
114            _ => None,
115        }
116    }
117}
118
119fn dc_to_sh(dc: DcChar) -> DcShorthand {
120    DcShorthand::from_global_id(dc.to_u128())
121}
122
123/// Encodes an unsigned 128-bit integer into canonical `Dc 6 f199 ... Dc 7` shorthands.
124#[must_use]
125pub fn encode_u128_dc_shorthands(val: u128) -> Vec<DcShorthand> {
126    u128_to_dc_number_chars(val)
127        .into_iter()
128        .map(dc_to_sh)
129        .collect()
130}
131
132/// Encodes a signed 64-bit integer into canonical `Dc 6 f199 (11)? ... Dc 7` shorthands.
133#[must_use]
134pub fn encode_i64_dc_shorthands(val: i64) -> Vec<DcShorthand> {
135    if val >= 0 {
136        let abs = u128::from(val.unsigned_abs());
137        encode_u128_dc_shorthands(abs)
138    } else {
139        let abs = u128::from(val.unsigned_abs());
140        let mut toks = encode_u128_dc_shorthands(abs);
141        toks.insert(2, dc_to_sh(DC_NEGATIVE));
142        toks
143    }
144}
145
146fn encode_binary_data_shorthands(bytes: &[u8]) -> Vec<DcShorthand> {
147    let mut out = Vec::new();
148    out.push(dc_to_sh(DC_START_ENCAPSULATION_BINARY));
149    #[allow(
150        clippy::expect_used,
151        reason = "Provably infallible: usize fits in u128 on all supported 32-bit and 64-bit architectures"
152    )]
153    let len_u128 = u128::try_from(bytes.len()).expect("usize fits in u128");
154    out.extend(encode_u128_dc_shorthands(len_u128));
155
156    let mut idx = 0usize;
157    while idx < bytes.len() {
158        #[allow(
159            clippy::expect_used,
160            reason = "Range-checked bounds: loop condition idx < bytes.len() guarantees idx is in bounds"
161        )]
162        let b0 = *bytes.get(idx).expect("idx < bytes.len()");
163        let b1_opt = bytes.get(idx.saturating_add(1)).copied();
164        let b2_opt = bytes.get(idx.saturating_add(2)).copied();
165
166        let d0 = b0 >> 2;
167        // Reason for fallback: standard base64 chunk padding treats missing trailing bytes as zero.
168        let d1 = ((b0 & 0x03) << 4) | (b1_opt.unwrap_or(0) >> 4);
169        out.push(dc_to_sh(dc_base64_digit_to_char(d0)));
170        out.push(dc_to_sh(dc_base64_digit_to_char(d1)));
171
172        if let Some(b1) = b1_opt {
173            // Reason for fallback: standard base64 chunk padding treats missing trailing bytes as zero.
174            let d2 = ((b1 & 0x0F) << 2) | (b2_opt.unwrap_or(0) >> 6);
175            out.push(dc_to_sh(dc_base64_digit_to_char(d2)));
176        } else {
177            out.push(dc_to_sh(DC_BASE64_PADDING));
178        }
179
180        if let Some(b2) = b2_opt {
181            let d3 = b2 & 0x3F;
182            out.push(dc_to_sh(dc_base64_digit_to_char(d3)));
183        } else {
184            out.push(dc_to_sh(DC_BASE64_PADDING));
185        }
186
187        idx = idx.saturating_add(3);
188    }
189
190    out.push(dc_to_sh(DC_END_ENCAPSULATION_BINARY));
191    out
192}
193
194fn hex_nibble(b: u8) -> Option<u8> {
195    match b {
196        b'0'..=b'9' => Some(b.saturating_sub(b'0')),
197        b'a'..=b'f' => Some(b.saturating_sub(b'a').saturating_add(10)),
198        b'A'..=b'F' => Some(b.saturating_sub(b'A').saturating_add(10)),
199        _ => None,
200    }
201}
202
203fn parse_context_directive_comment(comment: &str) -> Result<Option<Vec<DcShorthand>>> {
204    let trimmed = comment.trim();
205    let Some(rest) = trimmed.strip_prefix("@context(") else {
206        return Ok(None);
207    };
208    let Some((inner, trailing)) = rest.split_once(')') else {
209        bail!("Unclosed `;; @context(...)` directive in WAT source");
210    };
211    let trailing_trimmed = trailing.trim();
212    ensure!(
213        trailing_trimmed.is_empty() || trailing_trimmed.starts_with(";;"),
214        "Unexpected trailing text '{trailing_trimmed}' after `;; @context(...)`"
215    );
216    let mut ctx_tokens = Vec::new();
217    for tok_str in inner.split_whitespace() {
218        let parsed = DcShorthand::parse(tok_str).map_err(|e| {
219            anyhow!("Invalid DcShorthand '{tok_str}' in `;; @context(...)`: {e}")
220        })?;
221        ctx_tokens.push(parsed);
222    }
223    ensure!(
224        !ctx_tokens.is_empty(),
225        "Empty `;; @context()` directive in WAT source"
226    );
227    Ok(Some(ctx_tokens))
228}
229
230fn tokenize_wat(src: &str) -> Result<Vec<WatToken>> {
231    tokenize_wat_inner(src, false)
232}
233
234fn tokenize_wat_inner(
235    src: &str,
236    preserve_context_directives: bool,
237) -> Result<Vec<WatToken>> {
238    let bytes = src.as_bytes();
239    let mut pos = 0usize;
240    let mut tokens = Vec::new();
241
242    while let Some(&b) = bytes.get(pos) {
243        if b.is_ascii_whitespace() {
244            pos = pos.saturating_add(1);
245            continue;
246        }
247        // Line comment `;; ...`
248        if b == b';' && bytes.get(pos.saturating_add(1)) == Some(&b';') {
249            pos = pos.saturating_add(2);
250            let comment_start = pos;
251            let mut comment_end = pos;
252            while let Some(&ch) = bytes.get(pos) {
253                pos = pos.saturating_add(1);
254                if ch == b'\n' {
255                    break;
256                }
257                comment_end = pos;
258            }
259            if preserve_context_directives
260                && let Some(comment_slice) = src.get(comment_start..comment_end)
261                && let Some(ctx_tokens) =
262                    parse_context_directive_comment(comment_slice)?
263            {
264                tokens.push(WatToken::ContextDirective(ctx_tokens));
265            }
266            continue;
267        }
268        // Block comment `(; ... ;)` (supports nesting)
269        if b == b'(' && bytes.get(pos.saturating_add(1)) == Some(&b';') {
270            pos = pos.saturating_add(2);
271            let mut depth = 1usize;
272            while depth > 0 {
273                let Some(&c0) = bytes.get(pos) else {
274                    bail!("Unclosed WAT block comment `(; ... ;)`");
275                };
276                if c0 == b'(' && bytes.get(pos.saturating_add(1)) == Some(&b';')
277                {
278                    depth = depth.saturating_add(1);
279                    pos = pos.saturating_add(2);
280                } else if c0 == b';'
281                    && bytes.get(pos.saturating_add(1)) == Some(&b')')
282                {
283                    depth = depth.saturating_sub(1);
284                    pos = pos.saturating_add(2);
285                } else {
286                    pos = pos.saturating_add(1);
287                }
288            }
289            continue;
290        }
291        if b == b'(' {
292            tokens.push(WatToken::LParen);
293            pos = pos.saturating_add(1);
294            continue;
295        }
296        if b == b')' {
297            tokens.push(WatToken::RParen);
298            pos = pos.saturating_add(1);
299            continue;
300        }
301        if b == b'"' {
302            pos = pos.saturating_add(1);
303            let mut buf = Vec::new();
304            let mut closed = false;
305            while let Some(&ch) = bytes.get(pos) {
306                pos = pos.saturating_add(1);
307                if ch == b'"' {
308                    closed = true;
309                    break;
310                }
311                if ch == b'\\' {
312                    let esc = *bytes
313                        .get(pos)
314                        .context("Truncated escape sequence in WAT string literal")?;
315                    pos = pos.saturating_add(1);
316                    match esc {
317                        b'n' => buf.push(b'\n'),
318                        b'r' => buf.push(b'\r'),
319                        b't' => buf.push(b'\t'),
320                        b'\\' => buf.push(b'\\'),
321                        b'"' => buf.push(b'"'),
322                        b'\'' => buf.push(b'\''),
323                        b'u' => {
324                            ensure!(
325                                bytes.get(pos) == Some(&b'{'),
326                                "Expected '{{' after \\u in WAT string escape"
327                            );
328                            pos = pos.saturating_add(1);
329                            let mut cp = 0u32;
330                            let mut digits = 0usize;
331                            while let Some(&hb) = bytes.get(pos) {
332                                pos = pos.saturating_add(1);
333                                if hb == b'}' {
334                                    break;
335                                }
336                                if hb == b'_' {
337                                    continue;
338                                }
339                                let nib = hex_nibble(hb).with_context(|| {
340                                    format!(
341                                        "Invalid hex digit '{}' in WAT \\u{{...}} escape",
342                                        char::from(hb)
343                                    )
344                                })?;
345                                cp = cp
346                                    .checked_mul(16)
347                                    .and_then(|v| v.checked_add(u32::from(nib)))
348                                    .context("WAT \\u{...} escape overflow")?;
349                                digits = digits.saturating_add(1);
350                            }
351                            ensure!(digits > 0, "Empty WAT \\u{{}} escape");
352                            let scalar = char::from_u32(cp).with_context(|| {
353                                format!("Invalid Unicode scalar U+{cp:04X} in WAT string")
354                            })?;
355                            let mut utf8 = [0u8; 4];
356                            buf.extend_from_slice(
357                                scalar.encode_utf8(&mut utf8).as_bytes(),
358                            );
359                        }
360                        h0 => {
361                            let n0 = hex_nibble(h0).with_context(|| {
362                                format!(
363                                    "Unsupported WAT string escape '\\{}'",
364                                    char::from(h0)
365                                )
366                            })?;
367                            let h1 = *bytes.get(pos).context(
368                                "Truncated two-digit hex escape in WAT string",
369                            )?;
370                            pos = pos.saturating_add(1);
371                            let n1 = hex_nibble(h1).with_context(|| {
372                                format!(
373                                    "Invalid second hex digit '{}' in WAT string escape",
374                                    char::from(h1)
375                                )
376                            })?;
377                            buf.push((n0 << 4) | n1);
378                        }
379                    }
380                } else {
381                    buf.push(ch);
382                }
383            }
384            ensure!(closed, "Unclosed string literal in WAT source");
385            tokens.push(WatToken::StringLit(buf));
386            continue;
387        }
388
389        let start = pos;
390        while let Some(&ch) = bytes.get(pos) {
391            if ch.is_ascii_whitespace()
392                || ch == b'('
393                || ch == b')'
394                || ch == b'"'
395                || (ch == b';'
396                    && bytes.get(pos.saturating_add(1)) == Some(&b';'))
397            {
398                break;
399            }
400            pos = pos.saturating_add(1);
401        }
402        let slice = src
403            .get(start..pos)
404            .context("Invalid UTF-8 atom slice in WAT source")?;
405        tokens.push(WatToken::Atom(slice.to_owned()));
406    }
407
408    Ok(tokens)
409}
410
411fn parse_sexprs(tokens: &[WatToken]) -> Result<Vec<SExpr>> {
412    let mut pos = 0usize;
413    let mut top = Vec::new();
414    while pos < tokens.len() {
415        top.push(parse_one_sexpr(tokens, &mut pos)?);
416    }
417    Ok(top)
418}
419
420fn parse_one_sexpr(tokens: &[WatToken], pos: &mut usize) -> Result<SExpr> {
421    let tok = tokens
422        .get(*pos)
423        .context("Unexpected end of WAT token stream")?;
424    *pos = pos.saturating_add(1);
425    match tok {
426        WatToken::Atom(s) => Ok(SExpr::Atom(s.clone())),
427        WatToken::StringLit(b) => Ok(SExpr::StringLit(b.clone())),
428        WatToken::ContextDirective(ctx) => {
429            Ok(SExpr::ContextDirective(ctx.clone()))
430        }
431        WatToken::RParen => bail!("Unexpected ')' in WAT source"),
432        WatToken::LParen => {
433            let mut items = Vec::new();
434            loop {
435                let Some(peek) = tokens.get(*pos) else {
436                    bail!("Unclosed '(' in WAT source");
437                };
438                if matches!(peek, WatToken::RParen) {
439                    *pos = pos.saturating_add(1);
440                    return Ok(SExpr::List(items));
441                }
442                items.push(parse_one_sexpr(tokens, pos)?);
443            }
444        }
445    }
446}
447
448fn parse_wat_u64(raw: &str) -> Result<u64> {
449    let clean = raw.replace('_', "");
450    if let Some(hex) = clean
451        .strip_prefix("0x")
452        .or_else(|| clean.strip_prefix("0X"))
453    {
454        u64::from_str_radix(hex, 16)
455            .with_context(|| format!("Invalid hex u64 literal '{raw}' in WAT"))
456    } else {
457        clean
458            .parse::<u64>()
459            .with_context(|| format!("Invalid u64 literal '{raw}' in WAT"))
460    }
461}
462
463fn parse_wat_u32(raw: &str) -> Result<u32> {
464    let v = parse_wat_u64(raw)?;
465    u32::try_from(v)
466        .with_context(|| format!("WAT unsigned immediate '{raw}' exceeds u32"))
467}
468
469fn parse_wat_i64(raw: &str) -> Result<i64> {
470    let clean = raw.replace('_', "");
471    let (neg, body) = if let Some(rest) = clean.strip_prefix('-') {
472        (true, rest)
473    } else if let Some(rest) = clean.strip_prefix('+') {
474        (false, rest)
475    } else {
476        (false, clean.as_str())
477    };
478    let mag = if let Some(hex) = body
479        .strip_prefix("0x")
480        .or_else(|| body.strip_prefix("0X"))
481    {
482        u64::from_str_radix(hex, 16)
483            .with_context(|| format!("Invalid hex integer '{raw}' in WAT"))?
484    } else {
485        body.parse::<u64>()
486            .with_context(|| format!("Invalid integer '{raw}' in WAT"))?
487    };
488    if neg {
489        if mag == 0x8000_0000_0000_0000 {
490            Ok(i64::MIN)
491        } else {
492            let signed = i64::try_from(mag).with_context(|| {
493                format!("Negative WAT integer '{raw}' overflows i64")
494            })?;
495            Ok(signed.wrapping_neg())
496        }
497    } else {
498        Ok(i64::from_le_bytes(mag.to_le_bytes()))
499    }
500}
501
502fn parse_wat_i32(raw: &str) -> Result<i32> {
503    let clean = raw.replace('_', "");
504    let (neg, body) = if let Some(rest) = clean.strip_prefix('-') {
505        (true, rest)
506    } else if let Some(rest) = clean.strip_prefix('+') {
507        (false, rest)
508    } else {
509        (false, clean.as_str())
510    };
511    let mag = if let Some(hex) = body
512        .strip_prefix("0x")
513        .or_else(|| body.strip_prefix("0X"))
514    {
515        u32::from_str_radix(hex, 16)
516            .with_context(|| format!("Invalid 32-bit hex integer '{raw}' in WAT"))?
517    } else {
518        body.parse::<u32>()
519            .with_context(|| format!("Invalid 32-bit integer '{raw}' in WAT"))?
520    };
521    if neg {
522        if mag == 0x8000_0000 {
523            Ok(i32::MIN)
524        } else {
525            let signed = i32::try_from(mag).with_context(|| {
526                format!("Negative WAT integer '{raw}' overflows i32")
527            })?;
528            Ok(signed.wrapping_neg())
529        }
530    } else {
531        Ok(i32::from_le_bytes(mag.to_le_bytes()))
532    }
533}
534
535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
536enum WatImmediateKind {
537    None,
538    Block,
539    Loop,
540    If,
541    Else,
542    End,
543    BrLabel,
544    BrTable,
545    FuncIdx,
546    CallIndirect,
547    LocalIdx,
548    GlobalIdx,
549    TableIdx,
550    MemIdx,
551    MemCopy,
552    MemArg { natural_align_exp: u32 },
553    I32Const,
554    I64Const,
555    F32Const,
556    F64Const,
557    ValType,
558}
559
560#[allow(
561    clippy::too_many_lines,
562    reason = "Complete WebAssembly instruction mnemonic table mapping WAT mnemonics to short Dcs and immediate kinds"
563)]
564fn lookup_wat_instruction(mnemonic: &str) -> Option<(u32, WatImmediateKind)> {
565    use WatImmediateKind as K;
566    let base = DC_WASM_START.to_short().ok()?;
567    let (offset, kind) = match mnemonic {
568        "unreachable" => (0x00, K::None),
569        "nop" => (0x01, K::None),
570        "block" => (0x02, K::Block),
571        "loop" => (0x03, K::Loop),
572        "if" => (0x04, K::If),
573        "else" => (0x05, K::Else),
574        "end" => (0x0B, K::End),
575        "br" => (0x0C, K::BrLabel),
576        "br_if" => (0x0D, K::BrLabel),
577        "br_table" => (0x0E, K::BrTable),
578        "return" => (0x0F, K::None),
579        "call" => (0x10, K::FuncIdx),
580        "call_indirect" => (0x11, K::CallIndirect),
581        "return_call" => (0x12, K::FuncIdx),
582        "return_call_indirect" => (0x13, K::CallIndirect),
583        "drop" => (0x1A, K::None),
584        "select" => (0x1B, K::None),
585        "local.get" => (0x20, K::LocalIdx),
586        "local.set" => (0x21, K::LocalIdx),
587        "local.tee" => (0x22, K::LocalIdx),
588        "global.get" => (0x23, K::GlobalIdx),
589        "global.set" => (0x24, K::GlobalIdx),
590        "table.get" => (0x25, K::TableIdx),
591        "table.set" => (0x26, K::TableIdx),
592        "i32.load" => (0x28, K::MemArg { natural_align_exp: 2 }),
593        "i64.load" => (0x29, K::MemArg { natural_align_exp: 3 }),
594        "f32.load" => (0x2A, K::MemArg { natural_align_exp: 2 }),
595        "f64.load" => (0x2B, K::MemArg { natural_align_exp: 3 }),
596        "i32.load8_s" => (0x2C, K::MemArg { natural_align_exp: 0 }),
597        "i32.load8_u" => (0x2D, K::MemArg { natural_align_exp: 0 }),
598        "i32.load16_s" => (0x2E, K::MemArg { natural_align_exp: 1 }),
599        "i32.load16_u" => (0x2F, K::MemArg { natural_align_exp: 1 }),
600        "i64.load8_s" => (0x30, K::MemArg { natural_align_exp: 0 }),
601        "i64.load8_u" => (0x31, K::MemArg { natural_align_exp: 0 }),
602        "i64.load16_s" => (0x32, K::MemArg { natural_align_exp: 1 }),
603        "i64.load16_u" => (0x33, K::MemArg { natural_align_exp: 1 }),
604        "i64.load32_s" => (0x34, K::MemArg { natural_align_exp: 2 }),
605        "i64.load32_u" => (0x35, K::MemArg { natural_align_exp: 2 }),
606        "i32.store" => (0x36, K::MemArg { natural_align_exp: 2 }),
607        "i64.store" => (0x37, K::MemArg { natural_align_exp: 3 }),
608        "f32.store" => (0x38, K::MemArg { natural_align_exp: 2 }),
609        "f64.store" => (0x39, K::MemArg { natural_align_exp: 3 }),
610        "i32.store8" => (0x3A, K::MemArg { natural_align_exp: 0 }),
611        "i32.store16" => (0x3B, K::MemArg { natural_align_exp: 1 }),
612        "i64.store8" => (0x3C, K::MemArg { natural_align_exp: 0 }),
613        "i64.store16" => (0x3D, K::MemArg { natural_align_exp: 1 }),
614        "i64.store32" => (0x3E, K::MemArg { natural_align_exp: 2 }),
615        "memory.size" => (0x3F, K::MemIdx),
616        "memory.grow" => (0x40, K::MemIdx),
617        "i32.const" => (0x41, K::I32Const),
618        "i64.const" => (0x42, K::I64Const),
619        "f32.const" => (0x43, K::F32Const),
620        "f64.const" => (0x44, K::F64Const),
621        "i32.eqz" => (0x45, K::None),
622        "i32.eq" => (0x46, K::None),
623        "i32.ne" => (0x47, K::None),
624        "i32.lt_s" => (0x48, K::None),
625        "i32.lt_u" => (0x49, K::None),
626        "i32.gt_s" => (0x4A, K::None),
627        "i32.gt_u" => (0x4B, K::None),
628        "i32.le_s" => (0x4C, K::None),
629        "i32.le_u" => (0x4D, K::None),
630        "i32.ge_s" => (0x4E, K::None),
631        "i32.ge_u" => (0x4F, K::None),
632        "i64.eqz" => (0x50, K::None),
633        "i64.eq" => (0x51, K::None),
634        "i64.ne" => (0x52, K::None),
635        "i64.lt_s" => (0x53, K::None),
636        "i64.lt_u" => (0x54, K::None),
637        "i64.gt_s" => (0x55, K::None),
638        "i64.gt_u" => (0x56, K::None),
639        "i64.le_s" => (0x57, K::None),
640        "i64.le_u" => (0x58, K::None),
641        "i64.ge_s" => (0x59, K::None),
642        "i64.ge_u" => (0x5A, K::None),
643        "f32.eq" => (0x5B, K::None),
644        "f32.ne" => (0x5C, K::None),
645        "f32.lt" => (0x5D, K::None),
646        "f32.gt" => (0x5E, K::None),
647        "f32.le" => (0x5F, K::None),
648        "f32.ge" => (0x60, K::None),
649        "f64.eq" => (0x61, K::None),
650        "f64.ne" => (0x62, K::None),
651        "f64.lt" => (0x63, K::None),
652        "f64.gt" => (0x64, K::None),
653        "f64.le" => (0x65, K::None),
654        "f64.ge" => (0x66, K::None),
655        "i32.clz" => (0x67, K::None),
656        "i32.ctz" => (0x68, K::None),
657        "i32.popcnt" => (0x69, K::None),
658        "i32.add" => (0x6A, K::None),
659        "i32.sub" => (0x6B, K::None),
660        "i32.mul" => (0x6C, K::None),
661        "i32.div_s" => (0x6D, K::None),
662        "i32.div_u" => (0x6E, K::None),
663        "i32.rem_s" => (0x6F, K::None),
664        "i32.rem_u" => (0x70, K::None),
665        "i32.and" => (0x71, K::None),
666        "i32.or" => (0x72, K::None),
667        "i32.xor" => (0x73, K::None),
668        "i32.shl" => (0x74, K::None),
669        "i32.shr_s" => (0x75, K::None),
670        "i32.shr_u" => (0x76, K::None),
671        "i32.rotl" => (0x77, K::None),
672        "i32.rotr" => (0x78, K::None),
673        "i64.clz" => (0x79, K::None),
674        "i64.ctz" => (0x7A, K::None),
675        "i64.popcnt" => (0x7B, K::None),
676        "i64.add" => (0x7C, K::None),
677        "i64.sub" => (0x7D, K::None),
678        "i64.mul" => (0x7E, K::None),
679        "i64.div_s" => (0x7F, K::None),
680        "i64.div_u" => (0x80, K::None),
681        "i64.rem_s" => (0x81, K::None),
682        "i64.rem_u" => (0x82, K::None),
683        "i64.and" => (0x83, K::None),
684        "i64.or" => (0x84, K::None),
685        "i64.xor" => (0x85, K::None),
686        "i64.shl" => (0x86, K::None),
687        "i64.shr_s" => (0x87, K::None),
688        "i64.shr_u" => (0x88, K::None),
689        "i64.rotl" => (0x89, K::None),
690        "i64.rotr" => (0x8A, K::None),
691        "f32.abs" => (0x8B, K::None),
692        "f32.neg" => (0x8C, K::None),
693        "f32.ceil" => (0x8D, K::None),
694        "f32.floor" => (0x8E, K::None),
695        "f32.trunc" => (0x8F, K::None),
696        "f32.nearest" => (0x90, K::None),
697        "f32.sqrt" => (0x91, K::None),
698        "f32.add" => (0x92, K::None),
699        "f32.sub" => (0x93, K::None),
700        "f32.mul" => (0x94, K::None),
701        "f32.div" => (0x95, K::None),
702        "f32.min" => (0x96, K::None),
703        "f32.max" => (0x97, K::None),
704        "f32.copysign" => (0x98, K::None),
705        "f64.abs" => (0x99, K::None),
706        "f64.neg" => (0x9A, K::None),
707        "f64.ceil" => (0x9B, K::None),
708        "f64.floor" => (0x9C, K::None),
709        "f64.trunc" => (0x9D, K::None),
710        "f64.nearest" => (0x9E, K::None),
711        "f64.sqrt" => (0x9F, K::None),
712        "f64.add" => (0xA0, K::None),
713        "f64.sub" => (0xA1, K::None),
714        "f64.mul" => (0xA2, K::None),
715        "f64.div" => (0xA3, K::None),
716        "f64.min" => (0xA4, K::None),
717        "f64.max" => (0xA5, K::None),
718        "f64.copysign" => (0xA6, K::None),
719        "i32.wrap_i64" => (0xA7, K::None),
720        "i32.trunc_f32_s" => (0xA8, K::None),
721        "i32.trunc_f32_u" => (0xA9, K::None),
722        "i32.trunc_f64_s" => (0xAA, K::None),
723        "i32.trunc_f64_u" => (0xAB, K::None),
724        "i64.extend_i32_s" => (0xAC, K::None),
725        "i64.extend_i32_u" => (0xAD, K::None),
726        "i64.trunc_f32_s" => (0xAE, K::None),
727        "i64.trunc_f32_u" => (0xAF, K::None),
728        "i64.trunc_f64_s" => (0xB0, K::None),
729        "i64.trunc_f64_u" => (0xB1, K::None),
730        "f32.convert_i32_s" => (0xB2, K::None),
731        "f32.convert_i32_u" => (0xB3, K::None),
732        "f32.convert_i64_s" => (0xB4, K::None),
733        "f32.convert_i64_u" => (0xB5, K::None),
734        "f32.demote_f64" => (0xB6, K::None),
735        "f64.convert_i32_s" => (0xB7, K::None),
736        "f64.convert_i32_u" => (0xB8, K::None),
737        "f64.convert_i64_s" => (0xB9, K::None),
738        "f64.convert_i64_u" => (0xBA, K::None),
739        "f64.promote_f32" => (0xBB, K::None),
740        "i32.reinterpret_f32" => (0xBC, K::None),
741        "i64.reinterpret_f64" => (0xBD, K::None),
742        "f32.reinterpret_i32" => (0xBE, K::None),
743        "f64.reinterpret_i64" => (0xBF, K::None),
744        "i32.extend8_s" => (0xC0, K::None),
745        "i32.extend16_s" => (0xC1, K::None),
746        "i64.extend8_s" => (0xC2, K::None),
747        "i64.extend16_s" => (0xC3, K::None),
748        "i64.extend32_s" => (0xC4, K::None),
749        "ref.null" => (0xD0, K::ValType),
750        "ref.is_null" => (0xD1, K::None),
751        "ref.func" => (0xD2, K::FuncIdx),
752        "ref.eq" => (0xD3, K::None),
753        "ref.as_non_null" => (0xD4, K::None),
754        "br_on_null" => (0xD5, K::BrLabel),
755        "br_on_non_null" => (0xD6, K::BrLabel),
756        // 0xFC Extended Instructions (Dc 1159 = base + 512)
757        "i32.trunc_sat_f32_s" => (512, K::None),
758        "i32.trunc_sat_f32_u" => (513, K::None),
759        "i32.trunc_sat_f64_s" => (514, K::None),
760        "i32.trunc_sat_f64_u" => (515, K::None),
761        "i64.trunc_sat_f32_s" => (516, K::None),
762        "i64.trunc_sat_f32_u" => (517, K::None),
763        "i64.trunc_sat_f64_s" => (518, K::None),
764        "i64.trunc_sat_f64_u" => (519, K::None),
765        "memory.init" => (520, K::MemCopy),
766        "data.drop" => (521, K::TableIdx),
767        "memory.copy" => (522, K::MemCopy),
768        "memory.fill" => (523, K::MemIdx),
769        "table.init" => (524, K::MemCopy),
770        "elem.drop" => (525, K::TableIdx),
771        "table.copy" => (526, K::MemCopy),
772        "table.grow" => (527, K::TableIdx),
773        "table.size" => (528, K::TableIdx),
774        "table.fill" => (529, K::TableIdx),
775        _ => return None,
776    };
777    Some((base.saturating_add(offset), kind))
778}
779
780#[derive(Debug, Default)]
781struct FuncCompileCtx {
782    func_indices: BTreeMap<String, u32>,
783    func_symbols: Option<Vec<String>>,
784    func_param_types: Vec<Vec<WatValType>>,
785    global_indices: BTreeMap<String, u32>,
786    global_symbols: Option<Vec<String>>,
787    global_types: Vec<WatValType>,
788    local_indices: BTreeMap<String, u32>,
789    local_types: Vec<WatValType>,
790    const_values: BTreeMap<String, i64>,
791    label_stack: Vec<Option<String>>,
792}
793
794impl FuncCompileCtx {
795    fn emit_func_target(&self, fn_idx: u32, out: &mut Vec<DcShorthand>) {
796        if let Some(syms) = &self.func_symbols
797            && let Ok(idx_usize) = usize::try_from(fn_idx)
798            && let Some(sym) = syms.get(idx_usize)
799        {
800            push_identifier_shorthands(sym, &[], out);
801        } else {
802            out.extend(encode_u128_dc_shorthands(u128::from(fn_idx)));
803        }
804    }
805
806    fn emit_global_target(&self, glob_idx: u32, out: &mut Vec<DcShorthand>) {
807        if let Some(syms) = &self.global_symbols
808            && let Ok(idx_usize) = usize::try_from(glob_idx)
809            && let Some(sym) = syms.get(idx_usize)
810        {
811            push_identifier_shorthands(sym, &[], out);
812        } else {
813            out.extend(encode_u128_dc_shorthands(u128::from(glob_idx)));
814        }
815    }
816
817    fn resolve_local(&self, tok: &str) -> Result<u32> {
818        if tok.starts_with('$') {
819            self.local_indices
820                .get(tok)
821                .copied()
822                .with_context(|| format!("Unknown WAT local or parameter '{tok}'"))
823        } else {
824            parse_wat_u32(tok)
825        }
826    }
827
828    fn resolve_global(&self, tok: &str) -> Result<u32> {
829        if tok.starts_with('$') {
830            self.global_indices
831                .get(tok)
832                .copied()
833                .with_context(|| format!("Unknown WAT global '{tok}'"))
834        } else {
835            parse_wat_u32(tok)
836        }
837    }
838
839    fn resolve_func(&self, tok: &str) -> Result<u32> {
840        if tok.starts_with('$') {
841            self.func_indices
842                .get(tok)
843                .copied()
844                .with_context(|| format!("Unknown WAT function '{tok}'"))
845        } else {
846            parse_wat_u32(tok)
847        }
848    }
849
850    fn resolve_i32_const(&self, tok: &str) -> Result<i32> {
851        if tok.starts_with('$') {
852            let val = self
853                .const_values
854                .get(tok)
855                .copied()
856                .with_context(|| format!("Unknown WAT constant '{tok}'"))?;
857            i32::try_from(val)
858                .or_else(|_| u32::try_from(val).map(u32::cast_signed))
859                .with_context(|| {
860                    format!("WAT constant '{tok}' ({val}) overflows i32")
861                })
862        } else {
863            parse_wat_i32(tok)
864        }
865    }
866
867    fn resolve_i64_const(&self, tok: &str) -> Result<i64> {
868        if tok.starts_with('$') {
869            self.const_values
870                .get(tok)
871                .copied()
872                .with_context(|| format!("Unknown WAT constant '{tok}'"))
873        } else {
874            parse_wat_i64(tok)
875        }
876    }
877
878    fn resolve_u64_const(&self, tok: &str) -> Result<u64> {
879        if tok.starts_with('$') {
880            let val = self
881                .const_values
882                .get(tok)
883                .copied()
884                .with_context(|| format!("Unknown WAT constant '{tok}'"))?;
885            u64::try_from(val).with_context(|| {
886                format!(
887                    "WAT constant '{tok}' ({val}) must be non-negative for unsigned offset/align"
888                )
889            })
890        } else {
891            parse_wat_u64(tok)
892        }
893    }
894
895    fn resolve_label(&self, tok: &str) -> Result<u32> {
896        if tok.starts_with('$') {
897            for (depth, entry) in self.label_stack.iter().rev().enumerate() {
898                if entry.as_deref() == Some(tok) {
899                    return u32::try_from(depth)
900                        .context("WAT label depth exceeds u32");
901                }
902            }
903            bail!("Unknown WAT branch label '{tok}'");
904        }
905        parse_wat_u32(tok)
906    }
907}
908
909fn parse_result_type_list(list: &[SExpr]) -> Result<Option<WatValType>> {
910    if list.first().and_then(SExpr::as_atom) != Some("result") {
911        return Ok(None);
912    }
913    ensure!(
914        list.len() == 2,
915        "WAT (result ...) requires a single value type"
916    );
917    let ty_name = list
918        .get(1)
919        .and_then(SExpr::as_atom)
920        .context("Expected value type atom inside (result ...)")?;
921    let vt = WatValType::from_name(ty_name)
922        .with_context(|| format!("Unsupported WAT result value type '{ty_name}'"))?;
923    Ok(Some(vt))
924}
925
926fn emit_blocktype(bt: Option<WatValType>, out: &mut Vec<DcShorthand>) {
927    if let Some(vt) = bt {
928        out.push(vt.to_shorthand());
929    } else {
930        out.push(dc_to_sh(DC_OPTIONAL_ABSENT));
931    }
932}
933
934fn emit_memarg_immediates(
935    natural_align_exp: u32,
936    memidx: u32,
937    align_exp: u32,
938    offset: u64,
939    out: &mut Vec<DcShorthand>,
940) {
941    let _ = natural_align_exp;
942    out.extend(encode_u128_dc_shorthands(u128::from(memidx)));
943    out.extend(encode_u128_dc_shorthands(u128::from(align_exp)));
944    out.extend(encode_u128_dc_shorthands(u128::from(offset)));
945}
946
947fn parse_align_exponent(raw_bytes_align: u64) -> Result<u32> {
948    ensure!(
949        raw_bytes_align > 0 && raw_bytes_align.is_power_of_two(),
950        "WAT memory align={raw_bytes_align} must be a positive power of two"
951    );
952    Ok(raw_bytes_align.trailing_zeros())
953}
954
955fn consume_memarg_from_atoms(
956    items: &[SExpr],
957    cursor: &mut usize,
958    natural_align_exp: u32,
959    ctx: &FuncCompileCtx,
960) -> Result<(u32, u32, u64)> {
961    let mut memidx = 0u32;
962    let mut align_exp = natural_align_exp;
963    let mut offset = 0u64;
964
965    if let Some(SExpr::Atom(a)) = items.get(*cursor)
966        && !a.starts_with("offset=")
967        && !a.starts_with("align=")
968        && a.chars().next().is_some_and(|c| c.is_ascii_digit())
969    {
970        memidx = parse_wat_u32(a)?;
971        *cursor = cursor.saturating_add(1);
972    }
973
974    while let Some(SExpr::Atom(a)) = items.get(*cursor) {
975        if let Some(off_str) = a.strip_prefix("offset=") {
976            offset = ctx.resolve_u64_const(off_str)?;
977            *cursor = cursor.saturating_add(1);
978        } else if let Some(align_str) = a.strip_prefix("align=") {
979            let align_bytes = ctx.resolve_u64_const(align_str)?;
980            align_exp = parse_align_exponent(align_bytes)?;
981            *cursor = cursor.saturating_add(1);
982        } else {
983            break;
984        }
985    }
986
987    Ok((memidx, align_exp, offset))
988}
989
990fn parse_const_decl(
991    sub: &[SExpr],
992    consts: &mut BTreeMap<String, i64>,
993) -> Result<()> {
994    ensure!(
995        sub.len() == 3,
996        "WAT (const $NAME <integer>) requires a $-prefixed constant name and an integer value"
997    );
998    let cname = sub
999        .get(1)
1000        .and_then(SExpr::as_atom)
1001        .context("Expected $-prefixed name in WAT (const $NAME <integer>)")?;
1002    ensure!(
1003        cname.starts_with('$'),
1004        "WAT constant name '{cname}' in (const ...) must start with '$'"
1005    );
1006    let val_tok = sub
1007        .get(2)
1008        .and_then(SExpr::as_atom)
1009        .context("Expected integer literal in WAT (const $NAME <integer>)")?;
1010    let val = if val_tok.starts_with('$') {
1011        *consts.get(val_tok).with_context(|| {
1012            format!("Unknown WAT constant '{val_tok}' referenced in (const {cname} ...)")
1013        })?
1014    } else {
1015        parse_wat_i64(val_tok)?
1016    };
1017    consts.insert(cname.to_owned(), val);
1018    Ok(())
1019}
1020
1021#[allow(
1022    clippy::too_many_lines,
1023    reason = "Compiles both flat and folded S-expression WebAssembly instructions with label scoping"
1024)]
1025fn compile_instr_sequence(
1026    items: &[SExpr],
1027    ctx: &mut FuncCompileCtx,
1028    out: &mut Vec<DcShorthand>,
1029) -> Result<()> {
1030    let mut idx = 0usize;
1031    while let Some(expr) = items.get(idx) {
1032        idx = idx.saturating_add(1);
1033        match expr {
1034            SExpr::List(list) => {
1035                if list.first().and_then(SExpr::as_atom) == Some("const") {
1036                    parse_const_decl(list, &mut ctx.const_values)?;
1037                } else {
1038                    compile_folded_sexpr(list, ctx, out)?;
1039                }
1040            }
1041            SExpr::StringLit(_) => {
1042                bail!("Unexpected string literal in WAT instruction stream");
1043            }
1044            SExpr::ContextDirective(_) => {
1045                bail!("Unexpected `;; @context(...)` directive inside WAT instruction stream");
1046            }
1047            SExpr::Atom(raw_mnemonic) => {
1048                let mnemonic = normalize_wat_mnemonic(raw_mnemonic);
1049                let (short_dc, kind) = lookup_wat_instruction(mnemonic)
1050                    .with_context(|| {
1051                        format!("Unknown or unsupported WAT instruction '{raw_mnemonic}'")
1052                    })?;
1053                match kind {
1054                    WatImmediateKind::Block | WatImmediateKind::Loop => {
1055                        let mut label = None;
1056                        if let Some(SExpr::Atom(a)) = items.get(idx)
1057                            && a.starts_with('$')
1058                        {
1059                            label = Some(a.clone());
1060                            idx = idx.saturating_add(1);
1061                        }
1062                        let mut bt = None;
1063                        if let Some(SExpr::List(sub)) = items.get(idx)
1064                            && let Some(vt) = parse_result_type_list(sub)?
1065                        {
1066                            bt = Some(vt);
1067                            idx = idx.saturating_add(1);
1068                        }
1069                        out.push(DcShorthand::Short(short_dc));
1070                        emit_blocktype(bt, out);
1071                        ctx.label_stack.push(label);
1072                    }
1073                    WatImmediateKind::If => {
1074                        let mut label = None;
1075                        if let Some(SExpr::Atom(a)) = items.get(idx)
1076                            && a.starts_with('$')
1077                        {
1078                            label = Some(a.clone());
1079                            idx = idx.saturating_add(1);
1080                        }
1081                        let mut bt = None;
1082                        if let Some(SExpr::List(sub)) = items.get(idx)
1083                            && let Some(vt) = parse_result_type_list(sub)?
1084                        {
1085                            bt = Some(vt);
1086                            idx = idx.saturating_add(1);
1087                        }
1088                        out.push(DcShorthand::Short(short_dc));
1089                        emit_blocktype(bt, out);
1090                        ctx.label_stack.push(label);
1091                    }
1092                    WatImmediateKind::Else => {
1093                        if let Some(SExpr::Atom(a)) = items.get(idx)
1094                            && a.starts_with('$')
1095                        {
1096                            idx = idx.saturating_add(1);
1097                        }
1098                        out.push(DcShorthand::Short(short_dc));
1099                    }
1100                    WatImmediateKind::End => {
1101                        if let Some(SExpr::Atom(a)) = items.get(idx)
1102                            && a.starts_with('$')
1103                        {
1104                            idx = idx.saturating_add(1);
1105                        }
1106                        let _ = ctx.label_stack.pop().context(
1107                            "Unexpected 'end' without matching block/loop/if in WAT",
1108                        )?;
1109                        out.push(DcShorthand::Short(short_dc));
1110                    }
1111                    _ => {
1112                        emit_non_control_instruction_with_immediates(
1113                            mnemonic,
1114                            short_dc,
1115                            kind,
1116                            items,
1117                            &mut idx,
1118                            ctx,
1119                            out,
1120                        )?;
1121                    }
1122                }
1123            }
1124        }
1125    }
1126    Ok(())
1127}
1128
1129fn normalize_wat_mnemonic(raw: &str) -> &str {
1130    match raw {
1131        "get" => "local.get",
1132        "set" => "local.set",
1133        "tee" => "local.tee",
1134        other => other,
1135    }
1136}
1137
1138fn expected_folded_operand_valtype(
1139    mnemonic: &str,
1140    imm_slice: &[SExpr],
1141    operand_idx: usize,
1142    ctx: &FuncCompileCtx,
1143) -> Result<WatValType> {
1144    match mnemonic {
1145        "local.set" | "local.tee" => {
1146            if let Some(tok) = imm_slice.get(1).and_then(SExpr::as_atom) {
1147                let loc_idx = usize::try_from(ctx.resolve_local(tok)?)?;
1148                if let Some(&vt) = ctx.local_types.get(loc_idx) {
1149                    return Ok(vt);
1150                }
1151            }
1152            Ok(WatValType::I32)
1153        }
1154        "global.set" => {
1155            if let Some(tok) = imm_slice.get(1).and_then(SExpr::as_atom) {
1156                let glob_idx = usize::try_from(ctx.resolve_global(tok)?)?;
1157                if let Some(&vt) = ctx.global_types.get(glob_idx) {
1158                    return Ok(vt);
1159                }
1160            }
1161            Ok(WatValType::I32)
1162        }
1163        "call" | "return_call" => {
1164            if let Some(tok) = imm_slice.get(1).and_then(SExpr::as_atom) {
1165                let fn_idx = usize::try_from(ctx.resolve_func(tok)?)?;
1166                if let Some(params) = ctx.func_param_types.get(fn_idx)
1167                    && let Some(&vt) = params.get(operand_idx)
1168                {
1169                    return Ok(vt);
1170                }
1171            }
1172            Ok(WatValType::I32)
1173        }
1174        "i32.wrap_i64"
1175        | "f32.convert_i64_s"
1176        | "f32.convert_i64_u"
1177        | "f64.convert_i64_s"
1178        | "f64.convert_i64_u" => Ok(WatValType::I64),
1179        "i64.extend_i32_s" | "i64.extend_i32_u" => Ok(WatValType::I32),
1180        _ if mnemonic.starts_with("i64.load") => Ok(WatValType::I32),
1181        _ if mnemonic.starts_with("i64.store") => {
1182            if operand_idx == 0 {
1183                Ok(WatValType::I32)
1184            } else {
1185                Ok(WatValType::I64)
1186            }
1187        }
1188        _ if mnemonic.starts_with("i64.") => Ok(WatValType::I64),
1189        _ => Ok(WatValType::I32),
1190    }
1191}
1192
1193fn compile_folded_operand(
1194    op_expr: &SExpr,
1195    expected_vt: WatValType,
1196    ctx: &mut FuncCompileCtx,
1197    out: &mut Vec<DcShorthand>,
1198) -> Result<()> {
1199    match op_expr {
1200        SExpr::List(sub) => compile_folded_sexpr(sub, ctx, out),
1201        SExpr::StringLit(_) => {
1202            bail!("Unexpected string literal operand in folded WAT instruction")
1203        }
1204        SExpr::ContextDirective(_) => {
1205            bail!("Unexpected `;; @context(...)` directive in folded WAT operand")
1206        }
1207        SExpr::Atom(atom) => {
1208            if atom.starts_with('$') {
1209                if let Some(&loc_idx) = ctx.local_indices.get(atom) {
1210                    let (dc, _) = lookup_wat_instruction("local.get")
1211                        .context("Missing local.get opcode")?;
1212                    out.push(DcShorthand::Short(dc));
1213                    out.extend(encode_u128_dc_shorthands(u128::from(loc_idx)));
1214                    return Ok(());
1215                }
1216                if let Some(&glob_idx) = ctx.global_indices.get(atom) {
1217                    let (dc, _) = lookup_wat_instruction("global.get")
1218                        .context("Missing global.get opcode")?;
1219                    out.push(DcShorthand::Short(dc));
1220                    ctx.emit_global_target(glob_idx, out);
1221                    return Ok(());
1222                }
1223                if ctx.const_values.contains_key(atom) {
1224                    if expected_vt == WatValType::I64 {
1225                        let val = ctx.resolve_i64_const(atom)?;
1226                        let (dc, _) = lookup_wat_instruction("i64.const")
1227                            .context("Missing i64.const opcode")?;
1228                        out.push(DcShorthand::Short(dc));
1229                        out.extend(encode_i64_dc_shorthands(val));
1230                    } else {
1231                        let val = ctx.resolve_i32_const(atom)?;
1232                        let (dc, _) = lookup_wat_instruction("i32.const")
1233                            .context("Missing i32.const opcode")?;
1234                        out.push(DcShorthand::Short(dc));
1235                        out.extend(encode_i64_dc_shorthands(i64::from(val)));
1236                    }
1237                    return Ok(());
1238                }
1239                bail!(
1240                    "Unknown WAT local, global, or constant '{atom}' in folded operand"
1241                );
1242            }
1243            if expected_vt == WatValType::I64 {
1244                let val = parse_wat_i64(atom)?;
1245                let (dc, _) = lookup_wat_instruction("i64.const")
1246                    .context("Missing i64.const opcode")?;
1247                out.push(DcShorthand::Short(dc));
1248                out.extend(encode_i64_dc_shorthands(val));
1249            } else {
1250                let val = parse_wat_i32(atom)?;
1251                let (dc, _) = lookup_wat_instruction("i32.const")
1252                    .context("Missing i32.const opcode")?;
1253                out.push(DcShorthand::Short(dc));
1254                out.extend(encode_i64_dc_shorthands(i64::from(val)));
1255            }
1256            Ok(())
1257        }
1258    }
1259}
1260
1261fn folded_immediate_end_index(
1262    mnemonic: &str,
1263    kind: WatImmediateKind,
1264    list: &[SExpr],
1265) -> usize {
1266    match kind {
1267        WatImmediateKind::None
1268        | WatImmediateKind::Block
1269        | WatImmediateKind::Loop
1270        | WatImmediateKind::If
1271        | WatImmediateKind::Else
1272        | WatImmediateKind::End => 1,
1273        WatImmediateKind::BrLabel
1274        | WatImmediateKind::FuncIdx
1275        | WatImmediateKind::LocalIdx
1276        | WatImmediateKind::GlobalIdx
1277        | WatImmediateKind::I32Const
1278        | WatImmediateKind::I64Const
1279        | WatImmediateKind::F32Const
1280        | WatImmediateKind::F64Const
1281        | WatImmediateKind::ValType => 2.min(list.len()),
1282        WatImmediateKind::BrTable => {
1283            let mut idx = 1usize;
1284            while matches!(list.get(idx), Some(SExpr::Atom(_))) {
1285                idx = idx.saturating_add(1);
1286            }
1287            idx
1288        }
1289        WatImmediateKind::CallIndirect => {
1290            if matches!(list.get(2), Some(SExpr::Atom(a)) if a.chars().next().is_some_and(|c| c.is_ascii_digit()))
1291            {
1292                3.min(list.len())
1293            } else {
1294                2.min(list.len())
1295            }
1296        }
1297        WatImmediateKind::TableIdx | WatImmediateKind::MemIdx => {
1298            let expected_ops = match mnemonic {
1299                "memory.size" | "table.size" | "data.drop" | "elem.drop" => 0,
1300                "memory.grow" => 1,
1301                "table.grow" => 2,
1302                "memory.fill" | "table.fill" => 3,
1303                _ => 0,
1304            };
1305            if list.len().saturating_sub(1) > expected_ops {
1306                2.min(list.len())
1307            } else {
1308                1
1309            }
1310        }
1311        WatImmediateKind::MemCopy => {
1312            let expected_ops = 3usize;
1313            let extra = list.len().saturating_sub(1).saturating_sub(expected_ops);
1314            1usize.saturating_add(extra.min(2)).min(list.len())
1315        }
1316        WatImmediateKind::MemArg { .. } => {
1317            let expected_ops = if mnemonic.contains(".store") {
1318                2usize
1319            } else {
1320                1usize
1321            };
1322            let mut idx = 1usize;
1323            let non_kv_count = list
1324                .iter()
1325                .skip(1)
1326                .filter(|item| {
1327                    !item.as_atom().is_some_and(|a| {
1328                        a.starts_with("offset=") || a.starts_with("align=")
1329                    })
1330                })
1331                .count();
1332            if non_kv_count > expected_ops
1333                && let Some(SExpr::Atom(a)) = list.get(idx)
1334                && !a.starts_with("offset=")
1335                && !a.starts_with("align=")
1336                && a.chars().next().is_some_and(|c| c.is_ascii_digit())
1337            {
1338                idx = idx.saturating_add(1);
1339            }
1340            while let Some(SExpr::Atom(a)) = list.get(idx) {
1341                if a.starts_with("offset=") || a.starts_with("align=") {
1342                    idx = idx.saturating_add(1);
1343                } else {
1344                    break;
1345                }
1346            }
1347            idx
1348        }
1349    }
1350}
1351
1352#[allow(
1353    clippy::too_many_lines,
1354    reason = "Compiles folded S-expression instructions, control blocks, and inline operands"
1355)]
1356fn compile_folded_sexpr(
1357    list: &[SExpr],
1358    ctx: &mut FuncCompileCtx,
1359    out: &mut Vec<DcShorthand>,
1360) -> Result<()> {
1361    let raw_head = list
1362        .first()
1363        .and_then(SExpr::as_atom)
1364        .context("WAT S-expression instruction must start with an opcode atom")?;
1365    if raw_head == "when" {
1366        ensure!(
1367            list.len() >= 3,
1368            "Folded WAT (when <cond> <body>...) requires a condition and at least one body instruction"
1369        );
1370        let cond_expr = list.get(1).context("Missing condition in (when ...)")?;
1371        compile_folded_operand(cond_expr, WatValType::I32, ctx, out)?;
1372        let (if_dc, _) =
1373            lookup_wat_instruction("if").context("Missing 'if' opcode")?;
1374        out.push(DcShorthand::Short(if_dc));
1375        emit_blocktype(None, out);
1376        ctx.label_stack.push(None);
1377        let body = list
1378            .get(2..)
1379            .context("Missing body instructions in folded WAT (when ...)")?;
1380        compile_instr_sequence(body, ctx, out)?;
1381        let _ = ctx.label_stack.pop();
1382        let end_dc = lookup_wat_instruction("end")
1383            .map(|(dc, _)| dc)
1384            .context("Missing 'end' opcode")?;
1385        out.push(DcShorthand::Short(end_dc));
1386        return Ok(());
1387    }
1388
1389    let head = normalize_wat_mnemonic(raw_head);
1390    let (short_dc, kind) = lookup_wat_instruction(head).with_context(|| {
1391        format!("Unknown or unsupported WAT instruction '{raw_head}'")
1392    })?;
1393
1394    match kind {
1395        WatImmediateKind::Block | WatImmediateKind::Loop => {
1396            let mut pos = 1usize;
1397            let mut label = None;
1398            if let Some(SExpr::Atom(a)) = list.get(pos)
1399                && a.starts_with('$')
1400            {
1401                label = Some(a.clone());
1402                pos = pos.saturating_add(1);
1403            }
1404            let mut bt = None;
1405            if let Some(SExpr::List(sub)) = list.get(pos)
1406                && let Some(vt) = parse_result_type_list(sub)?
1407            {
1408                bt = Some(vt);
1409                pos = pos.saturating_add(1);
1410            }
1411            out.push(DcShorthand::Short(short_dc));
1412            emit_blocktype(bt, out);
1413            ctx.label_stack.push(label);
1414            let body = list
1415                .get(pos..)
1416                .context("Invalid block/loop body instruction slice")?;
1417            compile_instr_sequence(body, ctx, out)?;
1418            let _ = ctx.label_stack.pop();
1419            let end_dc = lookup_wat_instruction("end")
1420                .map(|(dc, _)| dc)
1421                .context("Missing 'end' opcode")?;
1422            out.push(DcShorthand::Short(end_dc));
1423        }
1424        WatImmediateKind::If => {
1425            let mut pos = 1usize;
1426            let mut label = None;
1427            if let Some(SExpr::Atom(a)) = list.get(pos)
1428                && a.starts_with('$')
1429                && !ctx.local_indices.contains_key(a)
1430                && !ctx.global_indices.contains_key(a)
1431                && !ctx.const_values.contains_key(a)
1432            {
1433                label = Some(a.clone());
1434                pos = pos.saturating_add(1);
1435            }
1436            let mut bt = None;
1437            if let Some(SExpr::List(sub)) = list.get(pos)
1438                && let Some(vt) = parse_result_type_list(sub)?
1439            {
1440                bt = Some(vt);
1441                pos = pos.saturating_add(1);
1442            }
1443            // Any expressions before `(then ...)` are condition operands pushed BEFORE `if`!
1444            while let Some(item) = list.get(pos) {
1445                if item
1446                    .as_list()
1447                    .and_then(|sub| sub.first())
1448                    .and_then(SExpr::as_atom)
1449                    == Some("then")
1450                {
1451                    break;
1452                }
1453                compile_folded_operand(item, WatValType::I32, ctx, out)?;
1454                pos = pos.saturating_add(1);
1455            }
1456            let then_list = list
1457                .get(pos)
1458                .and_then(SExpr::as_list)
1459                .context("Folded WAT (if ...) requires a (then ...) clause")?;
1460            ensure!(
1461                then_list.first().and_then(SExpr::as_atom) == Some("then"),
1462                "Expected (then ...) clause in folded WAT (if ...)"
1463            );
1464            pos = pos.saturating_add(1);
1465
1466            out.push(DcShorthand::Short(short_dc));
1467            emit_blocktype(bt, out);
1468            ctx.label_stack.push(label);
1469
1470            let then_body = then_list
1471                .get(1..)
1472                .context("Invalid (then ...) clause instruction slice")?;
1473            compile_instr_sequence(then_body, ctx, out)?;
1474
1475            if let Some(else_expr) = list.get(pos) {
1476                let else_list = else_expr.as_list().context(
1477                    "Expected (else ...) list after (then ...) in folded WAT (if ...)",
1478                )?;
1479                ensure!(
1480                    else_list.first().and_then(SExpr::as_atom) == Some("else"),
1481                    "Expected (else ...) clause in folded WAT (if ...)"
1482                );
1483                pos = pos.saturating_add(1);
1484                let else_dc = lookup_wat_instruction("else")
1485                    .map(|(dc, _)| dc)
1486                    .context("Missing 'else' opcode")?;
1487                out.push(DcShorthand::Short(else_dc));
1488                let else_body = else_list
1489                    .get(1..)
1490                    .context("Invalid (else ...) clause instruction slice")?;
1491                compile_instr_sequence(else_body, ctx, out)?;
1492            }
1493            ensure!(
1494                pos == list.len(),
1495                "Unexpected trailing items in folded WAT (if ...)"
1496            );
1497            let _ = ctx.label_stack.pop();
1498            let end_dc = lookup_wat_instruction("end")
1499                .map(|(dc, _)| dc)
1500                .context("Missing 'end' opcode")?;
1501            out.push(DcShorthand::Short(end_dc));
1502        }
1503        _ => {
1504            let imm_end = folded_immediate_end_index(head, kind, list);
1505            let imm_slice = list
1506                .get(..imm_end)
1507                .context("Invalid folded instruction immediate slice")?;
1508            let operand_exprs = list
1509                .get(imm_end..)
1510                .context("Invalid folded instruction operand slice")?;
1511            for (op_idx, op_expr) in operand_exprs.iter().enumerate() {
1512                let expected_vt =
1513                    expected_folded_operand_valtype(head, imm_slice, op_idx, ctx)?;
1514                compile_folded_operand(op_expr, expected_vt, ctx, out)?;
1515            }
1516            let mut imm_cursor = 1usize;
1517            emit_non_control_instruction_with_immediates(
1518                head,
1519                short_dc,
1520                kind,
1521                imm_slice,
1522                &mut imm_cursor,
1523                ctx,
1524                out,
1525            )?;
1526            ensure!(
1527                imm_cursor == imm_end,
1528                "Unconsumed immediate arguments in folded WAT instruction '({raw_head} ...)'"
1529            );
1530        }
1531    }
1532    Ok(())
1533}
1534
1535#[allow(
1536    clippy::too_many_arguments,
1537    reason = "Emits opcode and immediate tokens from shared flat/folded immediate slice"
1538)]
1539fn emit_non_control_instruction_with_immediates(
1540    mnemonic: &str,
1541    short_dc: u32,
1542    kind: WatImmediateKind,
1543    items: &[SExpr],
1544    cursor: &mut usize,
1545    ctx: &FuncCompileCtx,
1546    out: &mut Vec<DcShorthand>,
1547) -> Result<()> {
1548    out.push(DcShorthand::Short(short_dc));
1549    match kind {
1550        WatImmediateKind::None => {}
1551        WatImmediateKind::BrLabel => {
1552            let lbl_tok = items
1553                .get(*cursor)
1554                .and_then(SExpr::as_atom)
1555                .with_context(|| {
1556                    format!("Expected label or depth immediate after '{mnemonic}'")
1557                })?;
1558            *cursor = cursor.saturating_add(1);
1559            let depth = ctx.resolve_label(lbl_tok)?;
1560            out.extend(encode_u128_dc_shorthands(u128::from(depth)));
1561        }
1562        WatImmediateKind::BrTable => {
1563            let mut depths = Vec::new();
1564            while let Some(SExpr::Atom(a)) = items.get(*cursor) {
1565                if let Ok(d) = ctx.resolve_label(a) {
1566                    depths.push(d);
1567                    *cursor = cursor.saturating_add(1);
1568                } else {
1569                    break;
1570                }
1571            }
1572            ensure!(
1573                !depths.is_empty(),
1574                "WAT 'br_table' requires at least a default label target"
1575            );
1576            let default_depth = depths
1577                .pop()
1578                .context("WAT 'br_table' missing default label")?;
1579            out.push(dc_to_sh(DC_BEGIN_LIST));
1580            out.push(DcShorthand::Format(FORMAT_INTEGER));
1581            for (i, d) in depths.iter().enumerate() {
1582                if i > 0 {
1583                    out.push(dc_to_sh(DC_LIST_ELEMENT_SEPARATOR));
1584                }
1585                out.extend(encode_u128_dc_shorthands(u128::from(*d)));
1586            }
1587            out.push(dc_to_sh(DC_END_LIST));
1588            out.extend(encode_u128_dc_shorthands(u128::from(default_depth)));
1589        }
1590        WatImmediateKind::FuncIdx => {
1591            let fn_tok = items
1592                .get(*cursor)
1593                .and_then(SExpr::as_atom)
1594                .with_context(|| {
1595                    format!("Expected function index or $name after '{mnemonic}'")
1596                })?;
1597            *cursor = cursor.saturating_add(1);
1598            let fn_idx = ctx.resolve_func(fn_tok)?;
1599            ctx.emit_func_target(fn_idx, out);
1600        }
1601        WatImmediateKind::CallIndirect => {
1602            let ty_tok = items
1603                .get(*cursor)
1604                .and_then(SExpr::as_atom)
1605                .with_context(|| {
1606                    format!("Expected type index after '{mnemonic}'")
1607                })?;
1608            *cursor = cursor.saturating_add(1);
1609            let type_idx = parse_wat_u32(ty_tok)?;
1610            let table_idx = if let Some(SExpr::Atom(a)) = items.get(*cursor)
1611                && a.chars().next().is_some_and(|c| c.is_ascii_digit())
1612            {
1613                *cursor = cursor.saturating_add(1);
1614                parse_wat_u32(a)?
1615            } else {
1616                0
1617            };
1618            out.extend(encode_u128_dc_shorthands(u128::from(type_idx)));
1619            out.extend(encode_u128_dc_shorthands(u128::from(table_idx)));
1620        }
1621        WatImmediateKind::LocalIdx => {
1622            let loc_tok = items
1623                .get(*cursor)
1624                .and_then(SExpr::as_atom)
1625                .with_context(|| {
1626                    format!("Expected local index or $name after '{mnemonic}'")
1627                })?;
1628            *cursor = cursor.saturating_add(1);
1629            let loc_idx = ctx.resolve_local(loc_tok)?;
1630            out.extend(encode_u128_dc_shorthands(u128::from(loc_idx)));
1631        }
1632        WatImmediateKind::GlobalIdx => {
1633            let glob_tok = items
1634                .get(*cursor)
1635                .and_then(SExpr::as_atom)
1636                .with_context(|| {
1637                    format!("Expected global index or $name after '{mnemonic}'")
1638                })?;
1639            *cursor = cursor.saturating_add(1);
1640            let glob_idx = ctx.resolve_global(glob_tok)?;
1641            ctx.emit_global_target(glob_idx, out);
1642        }
1643        WatImmediateKind::TableIdx | WatImmediateKind::MemIdx => {
1644            let idx_val = if let Some(SExpr::Atom(a)) = items.get(*cursor)
1645                && a.chars().next().is_some_and(|c| c.is_ascii_digit())
1646            {
1647                *cursor = cursor.saturating_add(1);
1648                parse_wat_u32(a)?
1649            } else {
1650                0
1651            };
1652            out.extend(encode_u128_dc_shorthands(u128::from(idx_val)));
1653        }
1654        WatImmediateKind::MemCopy => {
1655            let idx0 = if let Some(SExpr::Atom(a)) = items.get(*cursor)
1656                && a.chars().next().is_some_and(|c| c.is_ascii_digit())
1657            {
1658                *cursor = cursor.saturating_add(1);
1659                parse_wat_u32(a)?
1660            } else {
1661                0
1662            };
1663            let idx1 = if let Some(SExpr::Atom(a)) = items.get(*cursor)
1664                && a.chars().next().is_some_and(|c| c.is_ascii_digit())
1665            {
1666                *cursor = cursor.saturating_add(1);
1667                parse_wat_u32(a)?
1668            } else {
1669                0
1670            };
1671            out.extend(encode_u128_dc_shorthands(u128::from(idx0)));
1672            out.extend(encode_u128_dc_shorthands(u128::from(idx1)));
1673        }
1674        WatImmediateKind::MemArg { natural_align_exp } => {
1675            let (memidx, align_exp, offset) =
1676                consume_memarg_from_atoms(items, cursor, natural_align_exp, ctx)?;
1677            emit_memarg_immediates(
1678                natural_align_exp,
1679                memidx,
1680                align_exp,
1681                offset,
1682                out,
1683            );
1684        }
1685        WatImmediateKind::I32Const => {
1686            let num_tok = items
1687                .get(*cursor)
1688                .and_then(SExpr::as_atom)
1689                .context("Expected i32 literal or $const after 'i32.const'")?;
1690            *cursor = cursor.saturating_add(1);
1691            let val = ctx.resolve_i32_const(num_tok)?;
1692            out.extend(encode_i64_dc_shorthands(i64::from(val)));
1693        }
1694        WatImmediateKind::I64Const => {
1695            let num_tok = items
1696                .get(*cursor)
1697                .and_then(SExpr::as_atom)
1698                .context("Expected i64 literal or $const after 'i64.const'")?;
1699            *cursor = cursor.saturating_add(1);
1700            let val = ctx.resolve_i64_const(num_tok)?;
1701            out.extend(encode_i64_dc_shorthands(val));
1702        }
1703        WatImmediateKind::F32Const => {
1704            let num_tok = items
1705                .get(*cursor)
1706                .and_then(SExpr::as_atom)
1707                .context("Expected f32 literal after 'f32.const'")?;
1708            *cursor = cursor.saturating_add(1);
1709            let bits = if let Ok(u) = parse_wat_u32(num_tok) {
1710                u
1711            } else {
1712                let f = num_tok.parse::<f32>().with_context(|| {
1713                    format!("Invalid f32 literal '{num_tok}' in WAT")
1714                })?;
1715                f.to_bits()
1716            };
1717            out.extend(encode_u128_dc_shorthands(u128::from(bits)));
1718        }
1719        WatImmediateKind::F64Const => {
1720            let num_tok = items
1721                .get(*cursor)
1722                .and_then(SExpr::as_atom)
1723                .context("Expected f64 literal after 'f64.const'")?;
1724            *cursor = cursor.saturating_add(1);
1725            let bits = if let Ok(u) = parse_wat_u64(num_tok) {
1726                u
1727            } else {
1728                let f = num_tok.parse::<f64>().with_context(|| {
1729                    format!("Invalid f64 literal '{num_tok}' in WAT")
1730                })?;
1731                f.to_bits()
1732            };
1733            out.extend(encode_u128_dc_shorthands(u128::from(bits)));
1734        }
1735        WatImmediateKind::ValType => {
1736            let ty_tok = items
1737                .get(*cursor)
1738                .and_then(SExpr::as_atom)
1739                .with_context(|| {
1740                    format!("Expected value type after '{mnemonic}'")
1741                })?;
1742            *cursor = cursor.saturating_add(1);
1743            let vt = WatValType::from_name(ty_tok).with_context(|| {
1744                format!("Unsupported WAT value type '{ty_tok}'")
1745            })?;
1746            out.push(vt.to_shorthand());
1747        }
1748        WatImmediateKind::Block
1749        | WatImmediateKind::Loop
1750        | WatImmediateKind::If
1751        | WatImmediateKind::Else
1752        | WatImmediateKind::End => {}
1753    }
1754    Ok(())
1755}
1756
1757#[derive(Debug, Clone)]
1758struct ParsedWatFunc {
1759    id: Option<String>,
1760    export_name: Option<String>,
1761    contexts: Vec<Vec<DcShorthand>>,
1762    params: Vec<(Option<String>, WatValType)>,
1763    result: Option<WatValType>,
1764    locals: Vec<(Option<String>, WatValType)>,
1765    consts: BTreeMap<String, i64>,
1766    body: Vec<SExpr>,
1767}
1768
1769#[derive(Debug, Clone)]
1770struct ParsedWatGlobal {
1771    id: Option<String>,
1772    export_name: Option<String>,
1773    valtype: WatValType,
1774    init_val: i64,
1775}
1776
1777#[derive(Debug, Clone)]
1778struct ParsedWatData {
1779    name: String,
1780    bytes: Vec<u8>,
1781}
1782
1783fn parse_func_decl(
1784    items: &[SExpr],
1785    func_ordinal: usize,
1786    module_consts: &BTreeMap<String, i64>,
1787) -> Result<ParsedWatFunc> {
1788    let mut pos = 1usize;
1789    let mut id = None;
1790    let mut export_name = None;
1791    let mut params = Vec::new();
1792    let mut result = None;
1793    let mut locals = Vec::new();
1794    let mut consts = module_consts.clone();
1795
1796    if let Some(SExpr::Atom(a)) = items.get(pos)
1797        && a.starts_with('$')
1798    {
1799        id = Some(a.clone());
1800        pos = pos.saturating_add(1);
1801    }
1802
1803    while let Some(SExpr::List(sub)) = items.get(pos) {
1804        let Some(tag) = sub.first().and_then(SExpr::as_atom) else {
1805            break;
1806        };
1807        match tag {
1808            "export" => {
1809                let Some(SExpr::StringLit(name_bytes)) = sub.get(1) else {
1810                    bail!("WAT (export ...) in (func ...) requires a string name");
1811                };
1812                export_name = Some(
1813                    String::from_utf8(name_bytes.clone())
1814                        .context("WAT export name must be valid UTF-8")?,
1815                );
1816                pos = pos.saturating_add(1);
1817            }
1818            "param" => {
1819                if sub.len() >= 3
1820                    && let Some(SExpr::Atom(pname)) = sub.get(1)
1821                    && pname.starts_with('$')
1822                {
1823                    ensure!(
1824                        sub.len() == 3,
1825                        "Named WAT (param $name <type>) takes exactly one type"
1826                    );
1827                    let tname = sub
1828                        .get(2)
1829                        .and_then(SExpr::as_atom)
1830                        .context("Expected type in (param $name <type>)")?;
1831                    let vt = WatValType::from_name(tname).with_context(|| {
1832                        format!("Unsupported WAT param type '{tname}'")
1833                    })?;
1834                    params.push((Some(pname.clone()), vt));
1835                } else {
1836                    for item in sub.iter().skip(1) {
1837                        let tname = item
1838                            .as_atom()
1839                            .context("Expected type atom in (param ...)")?;
1840                        let vt = WatValType::from_name(tname).with_context(
1841                            || format!("Unsupported WAT param type '{tname}'"),
1842                        )?;
1843                        params.push((None, vt));
1844                    }
1845                }
1846                pos = pos.saturating_add(1);
1847            }
1848            "result" => {
1849                result = parse_result_type_list(sub)?;
1850                pos = pos.saturating_add(1);
1851            }
1852            "local" => {
1853                if sub.len() >= 3
1854                    && let Some(SExpr::Atom(lname)) = sub.get(1)
1855                    && lname.starts_with('$')
1856                {
1857                    ensure!(
1858                        sub.len() == 3,
1859                        "Named WAT (local $name <type>) takes exactly one type"
1860                    );
1861                    let tname = sub
1862                        .get(2)
1863                        .and_then(SExpr::as_atom)
1864                        .context("Expected type in (local $name <type>)")?;
1865                    let vt = WatValType::from_name(tname).with_context(|| {
1866                        format!("Unsupported WAT local type '{tname}'")
1867                    })?;
1868                    locals.push((Some(lname.clone()), vt));
1869                } else {
1870                    for item in sub.iter().skip(1) {
1871                        let tname = item
1872                            .as_atom()
1873                            .context("Expected type atom in (local ...)")?;
1874                        let vt = WatValType::from_name(tname).with_context(
1875                            || format!("Unsupported WAT local type '{tname}'"),
1876                        )?;
1877                        locals.push((None, vt));
1878                    }
1879                }
1880                pos = pos.saturating_add(1);
1881            }
1882            "const" => {
1883                parse_const_decl(sub, &mut consts)?;
1884                pos = pos.saturating_add(1);
1885            }
1886            _ => break,
1887        }
1888    }
1889
1890    let _ = func_ordinal;
1891    let body = items
1892        .get(pos..)
1893        .context("Invalid function declaration body slice")?
1894        .to_vec();
1895    Ok(ParsedWatFunc {
1896        id,
1897        export_name,
1898        contexts: Vec::new(),
1899        params,
1900        result,
1901        locals,
1902        consts,
1903        body,
1904    })
1905}
1906
1907fn parse_global_decl(
1908    items: &[SExpr],
1909    global_ordinal: usize,
1910    module_consts: &BTreeMap<String, i64>,
1911) -> Result<ParsedWatGlobal> {
1912    let mut pos = 1usize;
1913    let mut id = None;
1914    let mut export_name = None;
1915
1916    if let Some(SExpr::Atom(a)) = items.get(pos)
1917        && a.starts_with('$')
1918    {
1919        id = Some(a.clone());
1920        pos = pos.saturating_add(1);
1921    }
1922    if let Some(SExpr::List(sub)) = items.get(pos)
1923        && sub.first().and_then(SExpr::as_atom) == Some("export")
1924    {
1925        let Some(SExpr::StringLit(name_bytes)) = sub.get(1) else {
1926            bail!("WAT (export ...) in (global ...) requires a string name");
1927        };
1928        export_name = Some(
1929            String::from_utf8(name_bytes.clone())
1930                .context("WAT global export name must be valid UTF-8")?,
1931        );
1932        pos = pos.saturating_add(1);
1933    }
1934
1935    let ty_expr = items
1936        .get(pos)
1937        .context("Missing type in WAT (global ...)")?;
1938    pos = pos.saturating_add(1);
1939    let valtype = match ty_expr {
1940        SExpr::Atom(tname) => WatValType::from_name(tname).with_context(|| {
1941            format!("Unsupported WAT global type '{tname}'")
1942        })?,
1943        SExpr::List(sub) => {
1944            ensure!(
1945                sub.first().and_then(SExpr::as_atom) == Some("mut")
1946                    && sub.len() == 2,
1947                "Expected (mut <type>) in WAT global declaration"
1948            );
1949            let tname = sub
1950                .get(1)
1951                .and_then(SExpr::as_atom)
1952                .context("Expected value type inside (mut <type>)")?;
1953            WatValType::from_name(tname).with_context(|| {
1954                format!("Unsupported WAT global type '{tname}'")
1955            })?
1956        }
1957        SExpr::StringLit(_) | SExpr::ContextDirective(_) => {
1958            bail!("Invalid non-type token in WAT (global ...)")
1959        }
1960    };
1961
1962    let init_expr = items
1963        .get(pos)
1964        .and_then(SExpr::as_list)
1965        .context("Expected initializer S-expression (i32.const|i64.const <N>) in WAT (global ...)")?;
1966    let init_op = init_expr
1967        .first()
1968        .and_then(SExpr::as_atom)
1969        .context("Missing opcode in WAT global initializer")?;
1970    let init_lit = init_expr
1971        .get(1)
1972        .and_then(SExpr::as_atom)
1973        .context("Missing literal value in WAT global initializer")?;
1974    let resolved_const = if init_lit.starts_with('$') {
1975        Some(*module_consts.get(init_lit).with_context(|| {
1976            format!("Unknown WAT constant '{init_lit}' in global initializer")
1977        })?)
1978    } else {
1979        None
1980    };
1981    let init_val = match init_op {
1982        "i32.const" => {
1983            if let Some(c) = resolved_const {
1984                i64::from(i32::try_from(c).with_context(|| {
1985                    format!("WAT constant '{init_lit}' ({c}) overflows i32")
1986                })?)
1987            } else {
1988                i64::from(parse_wat_i32(init_lit)?)
1989            }
1990        }
1991        "i64.const" => {
1992            if let Some(c) = resolved_const {
1993                c
1994            } else {
1995                parse_wat_i64(init_lit)?
1996            }
1997        }
1998        other => bail!("Unsupported WAT global initializer opcode '{other}'"),
1999    };
2000    let _ = global_ordinal;
2001
2002    Ok(ParsedWatGlobal {
2003        id,
2004        export_name,
2005        valtype,
2006        init_val,
2007    })
2008}
2009
2010fn parse_data_decl(items: &[SExpr], data_ordinal: usize) -> Result<ParsedWatData> {
2011    let mut pos = 1usize;
2012    let mut name = format!("data_{data_ordinal}");
2013    if let Some(SExpr::Atom(a)) = items.get(pos)
2014        && a.starts_with('$')
2015    {
2016        name = a.trim_start_matches('$').to_owned();
2017        pos = pos.saturating_add(1);
2018    }
2019    while let Some(SExpr::List(_)) = items.get(pos) {
2020        pos = pos.saturating_add(1);
2021    }
2022    let mut bytes = Vec::new();
2023    while let Some(SExpr::StringLit(chunk)) = items.get(pos) {
2024        bytes.extend_from_slice(chunk);
2025        pos = pos.saturating_add(1);
2026    }
2027    Ok(ParsedWatData { name, bytes })
2028}
2029
2030fn push_identifier_shorthands(
2031    name: &str,
2032    type_prefix: &[DcShorthand],
2033    out: &mut Vec<DcShorthand>,
2034) {
2035    out.push(dc_to_sh(DC_BEGIN_IDENTIFIER));
2036    out.extend_from_slice(type_prefix);
2037    for ch in name.chars() {
2038        out.push(DcShorthand::Unicode(u32::from(ch)));
2039    }
2040    out.push(dc_to_sh(DC_END_IDENTIFIER));
2041}
2042
2043fn validate_memory_decl(items: &[SExpr]) -> Result<()> {
2044    let mut pos = 1usize;
2045    if let Some(SExpr::Atom(a)) = items.get(pos)
2046        && a.starts_with('$')
2047    {
2048        pos = pos.saturating_add(1);
2049    }
2050    while let Some(SExpr::List(sub)) = items.get(pos) {
2051        ensure!(
2052            sub.first().and_then(SExpr::as_atom) == Some("export"),
2053            "Unsupported list clause inside WAT (memory ...)"
2054        );
2055        pos = pos.saturating_add(1);
2056    }
2057    if let Some(SExpr::Atom(min_str)) = items.get(pos) {
2058        let min_pages = parse_wat_u32(min_str)?;
2059        ensure!(
2060            min_pages == 1,
2061            "Dc-WASM modules always instantiate 1 initial 64 KiB page and grow via (memory.grow ...); got (memory {min_pages})"
2062        );
2063        pos = pos.saturating_add(1);
2064        if let Some(SExpr::Atom(max_str)) = items.get(pos) {
2065            let max_pages = parse_wat_u32(max_str)?;
2066            ensure!(
2067                max_pages >= min_pages,
2068                "WAT (memory {min_pages} {max_pages}) maximum pages must be >= minimum pages"
2069            );
2070            pos = pos.saturating_add(1);
2071        }
2072    }
2073    ensure!(
2074        pos == items.len(),
2075        "Unexpected trailing tokens in WAT (memory ...) declaration"
2076    );
2077    Ok(())
2078}
2079
2080#[allow(
2081    clippy::too_many_arguments,
2082    reason = "Carries module-level function/global symbol tables and types into routine emission"
2083)]
2084fn emit_wasm_routine_shorthands(
2085    func: &ParsedWatFunc,
2086    func_indices: &BTreeMap<String, u32>,
2087    func_symbols: Option<&[String]>,
2088    func_param_types: &[Vec<WatValType>],
2089    global_indices: &BTreeMap<String, u32>,
2090    global_symbols: Option<&[String]>,
2091    global_types: &[WatValType],
2092    out: &mut Vec<DcShorthand>,
2093) -> Result<()> {
2094    out.push(dc_to_sh(DC_BEGIN_LITERAL));
2095    out.push(dc_to_sh(DC_BEGIN_TYPE_DEF));
2096    out.push(dc_to_sh(DC_TYPE_ROUTINE));
2097
2098    if let Some(ret_vt) = func.result {
2099        out.push(ret_vt.to_shorthand());
2100    } else if !func.params.is_empty() {
2101        out.push(dc_to_sh(DC_OPTIONAL_ABSENT));
2102    }
2103
2104    if !func.params.is_empty() {
2105        out.push(dc_to_sh(DC_BEGIN_LIST));
2106        out.push(dc_to_sh(DC_TYPE_ANY));
2107        for (idx, (pname_opt, pvt)) in func.params.iter().enumerate() {
2108            if idx > 0 {
2109                out.push(dc_to_sh(DC_LIST_ELEMENT_SEPARATOR));
2110            }
2111            let clean_name = pname_opt
2112                .as_deref()
2113                .map(|s| s.trim_start_matches('$').to_owned())
2114                // Reason for fallback: unnamed WAT parameters default to synthetic p{idx} identifier.
2115                .unwrap_or_else(|| format!("p{idx}"));
2116            push_identifier_shorthands(&clean_name, &[pvt.to_shorthand()], out);
2117        }
2118        out.push(dc_to_sh(DC_END_LIST));
2119    }
2120
2121    out.push(dc_to_sh(DC_END_TYPE_DEF));
2122
2123    if !func.locals.is_empty() {
2124        out.push(dc_to_sh(DC_BEGIN_LIST));
2125        out.push(DcShorthand::Short(SHORT_TYPE_META));
2126        for (idx, (_, lvt)) in func.locals.iter().enumerate() {
2127            if idx > 0 {
2128                out.push(dc_to_sh(DC_LIST_ELEMENT_SEPARATOR));
2129            }
2130            out.push(lvt.to_shorthand());
2131        }
2132        out.push(dc_to_sh(DC_END_LIST));
2133    }
2134
2135    let mut local_indices = BTreeMap::new();
2136    let mut local_types =
2137        Vec::with_capacity(func.params.len().saturating_add(func.locals.len()));
2138    let mut next_local = 0u32;
2139    for (pname_opt, pvt) in &func.params {
2140        if let Some(pname) = pname_opt {
2141            local_indices.insert(pname.clone(), next_local);
2142        }
2143        local_types.push(*pvt);
2144        next_local = next_local.saturating_add(1);
2145    }
2146    for (lname_opt, lvt) in &func.locals {
2147        if let Some(lname) = lname_opt {
2148            local_indices.insert(lname.clone(), next_local);
2149        }
2150        local_types.push(*lvt);
2151        next_local = next_local.saturating_add(1);
2152    }
2153
2154    let mut ctx = FuncCompileCtx {
2155        func_indices: func_indices.clone(),
2156        func_symbols: func_symbols.map(<[String]>::to_vec),
2157        func_param_types: func_param_types.to_vec(),
2158        global_indices: global_indices.clone(),
2159        global_symbols: global_symbols.map(<[String]>::to_vec),
2160        global_types: global_types.to_vec(),
2161        local_indices,
2162        local_types,
2163        const_values: func.consts.clone(),
2164        label_stack: Vec::new(),
2165    };
2166
2167    compile_instr_sequence(&func.body, &mut ctx, out)?;
2168    ensure!(
2169        ctx.label_stack.is_empty(),
2170        "Unclosed block/loop/if in WAT function body"
2171    );
2172
2173    out.push(dc_to_sh(DC_END_LITERAL));
2174    Ok(())
2175}
2176
2177fn collect_sexpr_block_labels(exprs: &[SExpr], labels: &mut std::collections::BTreeSet<String>) {
2178    let mut idx = 0usize;
2179    while let Some(expr) = exprs.get(idx) {
2180        idx = idx.saturating_add(1);
2181        match expr {
2182            SExpr::List(sub) => {
2183                if let Some(head) = sub.first().and_then(SExpr::as_atom)
2184                    && matches!(head, "block" | "loop" | "if" | "when")
2185                    && let Some(SExpr::Atom(lbl)) = sub.get(1)
2186                    && lbl.starts_with('$')
2187                {
2188                    labels.insert(lbl.clone());
2189                }
2190                collect_sexpr_block_labels(sub, labels);
2191            }
2192            SExpr::Atom(head)
2193                if matches!(head.as_str(), "block" | "loop" | "if") =>
2194            {
2195                if let Some(SExpr::Atom(lbl)) = exprs.get(idx)
2196                    && lbl.starts_with('$')
2197                {
2198                    labels.insert(lbl.clone());
2199                }
2200            }
2201            _ => {}
2202        }
2203    }
2204}
2205
2206fn collect_sexpr_dollar_refs(
2207    exprs: &[SExpr],
2208    local_or_const_or_label: &std::collections::BTreeSet<String>,
2209    func_by_id: &BTreeMap<String, usize>,
2210    global_by_id: &BTreeMap<String, usize>,
2211    ref_funcs: &mut std::collections::BTreeSet<usize>,
2212    ref_globals: &mut std::collections::BTreeSet<usize>,
2213) {
2214    for expr in exprs {
2215        match expr {
2216            SExpr::List(sub) => {
2217                if sub.first().and_then(SExpr::as_atom) == Some("const") {
2218                    continue;
2219                }
2220                collect_sexpr_dollar_refs(
2221                    sub,
2222                    local_or_const_or_label,
2223                    func_by_id,
2224                    global_by_id,
2225                    ref_funcs,
2226                    ref_globals,
2227                );
2228            }
2229            SExpr::Atom(atom) if atom.starts_with('$') => {
2230                if local_or_const_or_label.contains(atom) {
2231                    continue;
2232                }
2233                if let Some(&f_idx) = func_by_id.get(atom) {
2234                    ref_funcs.insert(f_idx);
2235                }
2236                if let Some(&g_idx) = global_by_id.get(atom) {
2237                    ref_globals.insert(g_idx);
2238                }
2239            }
2240            _ => {}
2241        }
2242    }
2243}
2244
2245fn collect_inline_const_names(
2246    exprs: &[SExpr],
2247    names: &mut std::collections::BTreeSet<String>,
2248) {
2249    for expr in exprs {
2250        if let SExpr::List(sub) = expr {
2251            if sub.first().and_then(SExpr::as_atom) == Some("const") {
2252                if let Some(SExpr::Atom(cname)) = sub.get(1) {
2253                    names.insert(cname.clone());
2254                }
2255            } else {
2256                collect_inline_const_names(sub, names);
2257            }
2258        }
2259    }
2260}
2261
2262fn emit_parsed_wat_module(
2263    funcs: &[ParsedWatFunc],
2264    globals: &[ParsedWatGlobal],
2265    datas: &[ParsedWatData],
2266) -> Result<Vec<DcShorthand>> {
2267    let mut func_indices = BTreeMap::new();
2268    let mut func_param_types = Vec::with_capacity(funcs.len());
2269    for (idx, f) in funcs.iter().enumerate() {
2270        if let Some(id) = &f.id {
2271            func_indices.insert(id.clone(), u32::try_from(idx)?);
2272        }
2273        func_param_types.push(f.params.iter().map(|(_, vt)| *vt).collect());
2274    }
2275    let mut global_indices = BTreeMap::new();
2276    let mut global_types = Vec::with_capacity(globals.len());
2277    for (idx, g) in globals.iter().enumerate() {
2278        if let Some(id) = &g.id {
2279            global_indices.insert(id.clone(), u32::try_from(idx)?);
2280        }
2281        global_types.push(g.valtype);
2282    }
2283
2284    let mut out = Vec::new();
2285    out.push(dc_to_sh(DC_BEGIN_WASM_PROGRAM));
2286
2287    // Single-function module with default `"main"` / `"_start"` export and no globals/data segments
2288    // emits the compact `1927 <wasm_routine> 1928` form.
2289    if funcs.len() == 1
2290        && globals.is_empty()
2291        && datas.is_empty()
2292        && let Some(only_fn) = funcs.first()
2293        && matches!(
2294            // Reason for fallback: unexported single function defaults to "main" export name.
2295            only_fn.export_name.as_deref().unwrap_or("main"),
2296            "main" | "_start"
2297        )
2298    {
2299        emit_wasm_routine_shorthands(
2300            only_fn,
2301            &func_indices,
2302            None,
2303            &func_param_types,
2304            &global_indices,
2305            None,
2306            &global_types,
2307            &mut out,
2308        )?;
2309        out.push(dc_to_sh(DC_END_WASM_PROGRAM));
2310        return Ok(out);
2311    }
2312
2313    // Precompute exact KV member symbol names so multi-member modules emit symbolic
2314    // `Dc 270 <name> Dc 271` immediates immune to helper/global index shifts.
2315    let mut seen_global_names = std::collections::BTreeSet::new();
2316    for d in datas {
2317        ensure!(
2318            seen_global_names.insert(d.name.clone()),
2319            "Duplicate WAT data/global member symbol '{}'",
2320            d.name
2321        );
2322    }
2323    let mut global_kv_names = Vec::with_capacity(globals.len());
2324    for (idx, g) in globals.iter().enumerate() {
2325        let gname = g
2326            .export_name
2327            .clone()
2328            .or_else(|| {
2329                g.id.as_deref()
2330                    .map(|s| s.trim_start_matches('$').to_owned())
2331            })
2332            // Reason for fallback: unnamed global defaults to synthetic global_{idx} identifier.
2333            .unwrap_or_else(|| format!("global_{idx}"));
2334        ensure!(
2335            seen_global_names.insert(gname.clone()),
2336            "Duplicate WAT data/global member symbol '{gname}'"
2337        );
2338        global_kv_names.push(gname);
2339    }
2340
2341    let mut seen_func_names = std::collections::BTreeSet::new();
2342    let mut func_kv_names = Vec::with_capacity(funcs.len());
2343    for (idx, f) in funcs.iter().enumerate() {
2344        let fname = f
2345            .export_name
2346            .clone()
2347            .or_else(|| {
2348                f.id.as_deref()
2349                    .map(|s| s.trim_start_matches('$').to_owned())
2350            })
2351            // Reason for fallback: unnamed function defaults to main for index 0 or func_{idx}.
2352            .unwrap_or_else(|| {
2353                if idx == 0 {
2354                    "main".to_owned()
2355                } else {
2356                    format!("func_{idx}")
2357                }
2358            });
2359        ensure!(
2360            seen_func_names.insert(fname.clone()),
2361            "Duplicate WAT function member symbol '{fname}'"
2362        );
2363        func_kv_names.push(fname);
2364    }
2365
2366    // Multi-member module emits an ordered key-value array (`Dc 559`..`Dc 560`)
2367    out.push(dc_to_sh(DC_BEGIN_KV_MAP));
2368    out.push(dc_to_sh(DC_TYPE_ANY));
2369    out.push(dc_to_sh(DC_TYPE_ANY));
2370
2371    for d in datas {
2372        out.push(dc_to_sh(DC_BEGIN_KV_PAIR));
2373        push_identifier_shorthands(&d.name, &[], &mut out);
2374        out.push(dc_to_sh(DC_LIST_ELEMENT_SEPARATOR));
2375        out.extend(encode_binary_data_shorthands(&d.bytes));
2376        out.push(dc_to_sh(DC_END_KV_PAIR));
2377    }
2378
2379    for (g, gname) in globals.iter().zip(global_kv_names.iter()) {
2380        out.push(dc_to_sh(DC_BEGIN_KV_PAIR));
2381        push_identifier_shorthands(
2382            gname,
2383            &[g.valtype.to_shorthand()],
2384            &mut out,
2385        );
2386        out.push(dc_to_sh(DC_LIST_ELEMENT_SEPARATOR));
2387        out.extend(encode_i64_dc_shorthands(g.init_val));
2388        out.push(dc_to_sh(DC_END_KV_PAIR));
2389    }
2390
2391    for (f, fname) in funcs.iter().zip(func_kv_names.iter()) {
2392        out.push(dc_to_sh(DC_BEGIN_KV_PAIR));
2393        push_identifier_shorthands(fname, &[], &mut out);
2394        out.push(dc_to_sh(DC_LIST_ELEMENT_SEPARATOR));
2395        emit_wasm_routine_shorthands(
2396            f,
2397            &func_indices,
2398            Some(&func_kv_names),
2399            &func_param_types,
2400            &global_indices,
2401            Some(&global_kv_names),
2402            &global_types,
2403            &mut out,
2404        )?;
2405        out.push(dc_to_sh(DC_END_KV_PAIR));
2406    }
2407
2408    out.push(dc_to_sh(DC_END_KV_MAP));
2409    out.push(dc_to_sh(DC_END_WASM_PROGRAM));
2410    Ok(out)
2411}
2412
2413#[allow(
2414    clippy::too_many_lines,
2415    reason = "Parses WAT module declarations, optional @context(...) annotations, exports, and transitive helper reachability"
2416)]
2417fn compile_wat_entries_inner(
2418    wat_src: &str,
2419    preserve_context_directives: bool,
2420) -> Result<Vec<(Vec<DcShorthand>, Vec<DcShorthand>)>> {
2421    let tokens = tokenize_wat_inner(wat_src, preserve_context_directives)?;
2422    let sexprs = parse_sexprs(&tokens)?;
2423    ensure!(!sexprs.is_empty(), "Empty WAT source");
2424
2425    let module_items: &[SExpr] = if sexprs.len() == 1
2426        && let Some(list) = sexprs.first().and_then(SExpr::as_list)
2427        && list.first().and_then(SExpr::as_atom) == Some("module")
2428    {
2429        let start = if list
2430            .get(1)
2431            .and_then(SExpr::as_atom)
2432            .is_some_and(|a| a.starts_with('$'))
2433        {
2434            2
2435        } else {
2436            1
2437        };
2438        list.get(start..)
2439            .context("Invalid module declaration item slice")?
2440    } else {
2441        sexprs.as_slice()
2442    };
2443
2444    let has_module_decls = module_items.iter().any(|item| {
2445        matches!(item, SExpr::ContextDirective(_))
2446            || item
2447                .as_list()
2448                .and_then(|l| l.first())
2449                .and_then(SExpr::as_atom)
2450                .is_some_and(|tag| {
2451                    matches!(
2452                        tag,
2453                        "func" | "global" | "data" | "memory" | "export"
2454                    )
2455                })
2456    });
2457
2458    if !has_module_decls {
2459        let mut out = Vec::new();
2460        out.push(dc_to_sh(DC_BEGIN_WASM_PROGRAM));
2461        let mut ctx = FuncCompileCtx::default();
2462        compile_instr_sequence(module_items, &mut ctx, &mut out)?;
2463        ensure!(
2464            ctx.label_stack.is_empty(),
2465            "Unclosed block/loop/if in bare WAT instruction stream"
2466        );
2467        out.push(dc_to_sh(DC_END_WASM_PROGRAM));
2468        return Ok(vec![(Vec::new(), out)]);
2469    }
2470
2471    let mut funcs = Vec::new();
2472    let mut globals = Vec::new();
2473    let mut datas = Vec::new();
2474    let mut module_consts: BTreeMap<String, i64> = BTreeMap::new();
2475    let mut pending_func_exports: Vec<(String, String)> = Vec::new();
2476    let mut pending_global_exports: Vec<(String, String)> = Vec::new();
2477    let mut pending_contexts: Vec<Vec<DcShorthand>> = Vec::new();
2478
2479    for item in module_items {
2480        if let SExpr::ContextDirective(ctx_tokens) = item {
2481            pending_contexts.push(ctx_tokens.clone());
2482            continue;
2483        }
2484        let list = item
2485            .as_list()
2486            .context("Expected top-level S-expression inside WAT module")?;
2487        let tag = list
2488            .first()
2489            .and_then(SExpr::as_atom)
2490            .context("Expected keyword at start of WAT module member")?;
2491        if tag != "func" {
2492            ensure!(
2493                pending_contexts.is_empty(),
2494                "`; @context(...)` directive in WAT must immediately precede a `(func ...)` declaration, found `({tag} ...)`"
2495            );
2496        }
2497        match tag {
2498            "memory" => {
2499                validate_memory_decl(list)?;
2500            }
2501            "const" => {
2502                parse_const_decl(list, &mut module_consts)?;
2503            }
2504            "func" => {
2505                let mut f = parse_func_decl(list, funcs.len(), &module_consts)?;
2506                f.contexts = std::mem::take(&mut pending_contexts);
2507                funcs.push(f);
2508            }
2509            "global" => {
2510                let g = parse_global_decl(list, globals.len(), &module_consts)?;
2511                globals.push(g);
2512            }
2513            "data" => {
2514                let d = parse_data_decl(list, datas.len())?;
2515                datas.push(d);
2516            }
2517            "export" => {
2518                let Some(SExpr::StringLit(exp_bytes)) = list.get(1) else {
2519                    bail!("WAT (export ...) requires an export name string");
2520                };
2521                let exp_name = String::from_utf8(exp_bytes.clone())
2522                    .context("WAT export name must be UTF-8")?;
2523                let target = list
2524                    .get(2)
2525                    .and_then(SExpr::as_list)
2526                    .context("WAT (export ...) requires target descriptor")?;
2527                let kind = target
2528                    .first()
2529                    .and_then(SExpr::as_atom)
2530                    .context("WAT (export ...) target descriptor requires an export kind")?;
2531                let target_ref = target
2532                    .get(1)
2533                    .and_then(SExpr::as_atom)
2534                    .context("WAT (export ...) target descriptor requires an identifier or index")?
2535                    .to_owned();
2536                match kind {
2537                    "func" => pending_func_exports.push((exp_name, target_ref)),
2538                    "global" => {
2539                        pending_global_exports.push((exp_name, target_ref));
2540                    }
2541                    "memory" => {}
2542                    other => bail!("Unsupported WAT export kind '{other}'"),
2543                }
2544            }
2545            other => bail!("Unsupported WAT module declaration '({other} ...)'"),
2546        }
2547    }
2548
2549    ensure!(
2550        pending_contexts.is_empty(),
2551        "Trailing `;; @context(...)` directive at end of WAT module without a following `(func ...)`"
2552    );
2553
2554    let mut func_by_id = BTreeMap::new();
2555    for (idx, f) in funcs.iter().enumerate() {
2556        if let Some(id) = &f.id {
2557            func_by_id.insert(id.clone(), idx);
2558        }
2559    }
2560    let mut global_by_id = BTreeMap::new();
2561    for (idx, g) in globals.iter().enumerate() {
2562        if let Some(id) = &g.id {
2563            global_by_id.insert(id.clone(), idx);
2564        }
2565    }
2566
2567    for (exp_name, target_ref) in pending_func_exports {
2568        let idx = if target_ref.starts_with('$') {
2569            *func_by_id.get(&target_ref).with_context(|| {
2570                format!("Unknown exported WAT function '{target_ref}'")
2571            })?
2572        } else {
2573            usize::try_from(parse_wat_u32(&target_ref)?)?
2574        };
2575        if let Some(f) = funcs.get_mut(idx) {
2576            f.export_name = Some(exp_name);
2577        }
2578    }
2579    for (exp_name, target_ref) in pending_global_exports {
2580        let idx = if target_ref.starts_with('$') {
2581            *global_by_id.get(&target_ref).with_context(|| {
2582                format!("Unknown exported WAT global '{target_ref}'")
2583            })?
2584        } else {
2585            usize::try_from(parse_wat_u32(&target_ref)?)?
2586        };
2587        if let Some(g) = globals.get_mut(idx) {
2588            g.export_name = Some(exp_name);
2589        }
2590    }
2591
2592    let has_any_context = funcs.iter().any(|f| !f.contexts.is_empty());
2593    if !preserve_context_directives || !has_any_context {
2594        let tokens = emit_parsed_wat_module(&funcs, &globals, &datas)?;
2595        return Ok(vec![(Vec::new(), tokens)]);
2596    }
2597
2598    let mut entries = Vec::new();
2599    for (entry_idx, entry_fn) in funcs.iter().enumerate() {
2600        if entry_fn.contexts.is_empty() {
2601            continue;
2602        }
2603        let mut reachable_funcs = std::collections::BTreeSet::new();
2604        let mut reachable_globals = std::collections::BTreeSet::new();
2605        let mut worklist = vec![entry_idx];
2606        reachable_funcs.insert(entry_idx);
2607
2608        while let Some(cur_idx) = worklist.pop() {
2609            let Some(cur_fn) = funcs.get(cur_idx) else {
2610                continue;
2611            };
2612            let mut shadowed = std::collections::BTreeSet::new();
2613            for (pname_opt, _) in &cur_fn.params {
2614                if let Some(pname) = pname_opt {
2615                    shadowed.insert(pname.clone());
2616                }
2617            }
2618            for (lname_opt, _) in &cur_fn.locals {
2619                if let Some(lname) = lname_opt {
2620                    shadowed.insert(lname.clone());
2621                }
2622            }
2623            for cname in cur_fn.consts.keys() {
2624                shadowed.insert(cname.clone());
2625            }
2626            collect_inline_const_names(&cur_fn.body, &mut shadowed);
2627            collect_sexpr_block_labels(&cur_fn.body, &mut shadowed);
2628
2629            let mut direct_funcs = std::collections::BTreeSet::new();
2630            collect_sexpr_dollar_refs(
2631                &cur_fn.body,
2632                &shadowed,
2633                &func_by_id,
2634                &global_by_id,
2635                &mut direct_funcs,
2636                &mut reachable_globals,
2637            );
2638            for f_idx in direct_funcs {
2639                if reachable_funcs.insert(f_idx) {
2640                    worklist.push(f_idx);
2641                }
2642            }
2643        }
2644
2645        let mut sub_funcs = Vec::with_capacity(reachable_funcs.len());
2646        let mut primary = entry_fn.clone();
2647        primary.export_name = Some("main".to_owned());
2648        sub_funcs.push(primary);
2649        for &helper_idx in &reachable_funcs {
2650            if helper_idx != entry_idx
2651                && let Some(helper_fn) = funcs.get(helper_idx)
2652            {
2653                sub_funcs.push(helper_fn.clone());
2654            }
2655        }
2656
2657        let mut sub_globals = Vec::with_capacity(reachable_globals.len());
2658        for &g_idx in &reachable_globals {
2659            if let Some(g) = globals.get(g_idx) {
2660                sub_globals.push(g.clone());
2661            }
2662        }
2663
2664        let prog_tokens =
2665            emit_parsed_wat_module(&sub_funcs, &sub_globals, &datas)?;
2666        for ctx in &entry_fn.contexts {
2667            entries.push((ctx.clone(), prog_tokens.clone()));
2668        }
2669    }
2670
2671    Ok(entries)
2672}
2673
2674/// Converts WebAssembly Text Format (`.wat`) source into a canonical `.WASM` Document
2675/// Character shorthand sequence (`Dc 1927 "Begin WASM program"` .. `Dc 1928 "End WASM program"`).
2676///
2677/// # Errors
2678/// Returns an error if the `.wat` source contains syntax errors or unknown instructions/identifiers.
2679pub fn wat_to_dc_shorthands(wat_src: &str) -> Result<Vec<DcShorthand>> {
2680    let mut entries = compile_wat_entries_inner(wat_src, false)?;
2681    entries
2682        .pop()
2683        .map(|(_, tokens)| tokens)
2684        .context("WAT compilation produced zero entries")
2685}
2686
2687/// Compiles a staged `.wat` implementation file into one or more `(context_tokens, wasm_tokens)`
2688/// pairs, splitting `;; @context(...)`-annotated `(func ...)` definitions into self-contained
2689/// `.WASM` programs (`Dc 1927 "Begin WASM program"` .. `Dc 1928 "End WASM program"`).
2690///
2691/// # Errors
2692/// Returns an error if the `.wat` source contains invalid syntax, directives, or instructions.
2693pub fn wat_to_staged_dc_entries(
2694    wat_src: &str,
2695) -> Result<Vec<(Vec<DcShorthand>, Vec<DcShorthand>)>> {
2696    compile_wat_entries_inner(wat_src, true)
2697}
2698
2699/// Converts WebAssembly Text Format (`.wat`) source into a space-separated Dc shorthand string.
2700///
2701/// # Errors
2702/// Returns an error if [`wat_to_dc_shorthands`] fails.
2703pub fn wat_to_dc_shorthand_string(wat_src: &str) -> Result<String> {
2704    let shorthands = wat_to_dc_shorthands(wat_src)?;
2705    let parts: Vec<String> =
2706        shorthands.iter().map(ToString::to_string).collect();
2707    Ok(parts.join(" "))
2708}
2709
2710/// Parses a `.dcsh` implementation file (supporting `#` and `;;` line comments and `"..."` UTF-8 strings)
2711/// into a sequence of [`DcShorthand`]s.
2712///
2713/// # Errors
2714/// Returns an error if any token is not a valid Dc shorthand or string literal.
2715pub fn parse_dcsh_impl_tokens(src: &str) -> Result<Vec<DcShorthand>> {
2716    let bytes = src.as_bytes();
2717    let mut pos = 0usize;
2718    let mut out = Vec::new();
2719
2720    while let Some(&b) = bytes.get(pos) {
2721        if b.is_ascii_whitespace() {
2722            pos = pos.saturating_add(1);
2723            continue;
2724        }
2725        if b == b'#'
2726            || (b == b';' && bytes.get(pos.saturating_add(1)) == Some(&b';'))
2727        {
2728            while let Some(&ch) = bytes.get(pos) {
2729                pos = pos.saturating_add(1);
2730                if ch == b'\n' {
2731                    break;
2732                }
2733            }
2734            continue;
2735        }
2736        if b == b'"' {
2737            pos = pos.saturating_add(1);
2738            let start = pos;
2739            while let Some(&ch) = bytes.get(pos) {
2740                if ch == b'"' {
2741                    break;
2742                }
2743                pos = pos.saturating_add(1);
2744            }
2745            ensure!(
2746                bytes.get(pos) == Some(&b'"'),
2747                "Unclosed string literal in .dcsh implementation file"
2748            );
2749            let slice = src
2750                .get(start..pos)
2751                .context("Invalid UTF-8 in .dcsh string literal")?;
2752            for c in slice.chars() {
2753                out.push(DcShorthand::Unicode(u32::from(c)));
2754            }
2755            pos = pos.saturating_add(1);
2756            continue;
2757        }
2758        let start = pos;
2759        while let Some(&ch) = bytes.get(pos) {
2760            if ch.is_ascii_whitespace() || ch == b'#' || ch == b'"' {
2761                break;
2762            }
2763            pos = pos.saturating_add(1);
2764        }
2765        let tok_str = src
2766            .get(start..pos)
2767            .context("Invalid token slice in .dcsh implementation file")?;
2768        let sh = DcShorthand::parse(tok_str).map_err(|e| {
2769            anyhow!("Invalid DcShorthand '{tok_str}' in .dcsh file: {e}")
2770        })?;
2771        out.push(sh);
2772    }
2773
2774    ensure!(
2775        !out.is_empty(),
2776        ".dcsh implementation file produced zero Dc tokens"
2777    );
2778    Ok(out)
2779}
2780
2781/// Stage classification for implementation files under `src/formats/dcdata/data-src/`.
2782#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
2783pub enum ImplStage {
2784    /// `stage_0_impls/`: Most basic language syntax Dcs and execution kernel implemented in `.wat`.
2785    Stage0,
2786    /// `stage_1_impls/`: Bootstrap StageL 3 standard library and StageR 3 compiler (`.sl3`/`.dcsh`).
2787    Stage1,
2788    /// `stage_2_impls/`: Core StageR 3 libraries and overlays (`.sr3`/`.sl3`/`.dcsh`).
2789    Stage2,
2790    /// `impls/`: General implementations of remaining Dcs (`.sr3`/`.sl3`/`.dcsh`).
2791    Impls,
2792}
2793
2794impl ImplStage {
2795    /// All implementation stages in bootstrap order.
2796    pub const ALL: [Self; 4] =
2797        [Self::Stage0, Self::Stage1, Self::Stage2, Self::Impls];
2798
2799    /// Higher-level VSO / StageR stages above `stage_0_impls/` in bootstrap order.
2800    pub const NAMESPACE_STAGES: [Self; 3] =
2801        [Self::Stage1, Self::Stage2, Self::Impls];
2802
2803    /// Relative directory name inside `src/formats/dcdata/data-src/`.
2804    #[must_use]
2805    pub const fn dir_name(self) -> &'static str {
2806        match self {
2807            Self::Stage0 => "stage_0_impls",
2808            Self::Stage1 => "stage_1_impls",
2809            Self::Stage2 => "stage_2_impls",
2810            Self::Impls => "impls",
2811        }
2812    }
2813}
2814
2815/// Callback type used to compile higher-stage `.sl3` / `.sr3` implementation files using
2816/// previously loaded lower-stage bootstrap compilers.
2817pub type StagedSourceCompiler<'a> = dyn Fn(
2818        ImplStage,
2819        &str,
2820        &str,
2821        &[StagedDcImpl],
2822    ) -> Result<Vec<DcShorthand>>
2823    + 'a;
2824
2825/// Parsed leading comment directives for a staged implementation file.
2826#[derive(Debug, Clone, PartialEq, Eq)]
2827pub(crate) struct StagedHeaderDirectives {
2828    /// Decomposition tag (`"semantic"` or `"equiv"`).
2829    pub decomp_tag: String,
2830    /// Optional 1-based line and System-block entity ID from `@dc l<id>`.
2831    pub dc_entity: Option<(usize, u128)>,
2832    /// Optional 1-based line and `(src, dst)` shorthands from `@converts(<src> <dst>)`.
2833    pub converts: Option<(usize, DcShorthand, DcShorthand)>,
2834}
2835
2836/// One compiled Dc, Format, or standalone converter Routine implementation loaded from
2837/// `stage_0_impls/`, `stage_1_impls/`, `stage_2_impls/`, or `impls/`.
2838#[derive(Debug, Clone)]
2839pub struct StagedDcImpl {
2840    /// Stage folder from which this implementation was loaded.
2841    pub stage: ImplStage,
2842    /// Repository-relative path (`src/formats/dcdata/data-src/...`).
2843    pub rel_path: String,
2844    /// Target Short Dc (`DcShorthand::Short`), Format Dc (`DcShorthand::Format`), or standalone
2845    /// System-block Routine entity (`DcShorthand::Long`) implemented by this file.
2846    pub target: DcShorthand,
2847    /// Optional `(src, dst)` conversion signature declared via `@converts(<src> <dst>)` on a
2848    /// standalone converter/compiler routine entity (`Dc 280 "Built-in type identifier: Routine"`
2849    /// with `Dc 595 "Data format or type description"` `[Dc 302 "Type conversion" <src> <dst>]`).
2850    pub converts: Option<(DcShorthand, DcShorthand)>,
2851    /// Optional `Dc 646 "In context of"` type/operation context shorthands qualifying this implementation.
2852    pub context_tokens: Vec<DcShorthand>,
2853    /// Decomposition tag (`"semantic"` or `"equiv"`).
2854    pub decomp_tag: String,
2855    /// Compiled Dc shorthand tokens.
2856    pub tokens: Vec<DcShorthand>,
2857}
2858
2859impl StagedDcImpl {
2860    /// Formats this implementation as a `<semantic>...`, `<semantic@ctx>...`, or `<equiv>...`
2861    /// decomposition entry compatible with `DcDefn::decompositions`.
2862    #[must_use]
2863    pub fn to_decomposition_entry(&self) -> String {
2864        let joined: Vec<String> =
2865            self.tokens.iter().map(ToString::to_string).collect();
2866        if self.context_tokens.is_empty() {
2867            format!("<{}>{}", self.decomp_tag, joined.join(" "))
2868        } else {
2869            let ctx_joined: Vec<String> =
2870                self.context_tokens.iter().map(ToString::to_string).collect();
2871            format!(
2872                "<{}@{}>{}",
2873                self.decomp_tag,
2874                ctx_joined.join(" "),
2875                joined.join(" ")
2876            )
2877        }
2878    }
2879}
2880
2881fn parse_target_from_stem(stem: &str, rel_path: &str) -> Result<DcShorthand> {
2882    let prefix = stem
2883        .split(['_', '-'])
2884        .next()
2885        .context("Missing filename stem prefix")?
2886        .trim();
2887    ensure!(
2888        !prefix.is_empty(),
2889        "Implementation file '{rel_path}' must start with a short Dc or format shorthand (e.g. '1936_kernel.wat'), or declare '@converts(<src> <dst>)'"
2890    );
2891    let parsed = DcShorthand::parse(prefix).map_err(|e| {
2892        anyhow!(
2893            "Implementation file '{rel_path}' stem prefix '{prefix}' is not a valid Dc shorthand ({e}); add ';; @converts(<src> <dst>)' if this is a standalone converter routine"
2894        )
2895    })?;
2896    match parsed {
2897        DcShorthand::Short(_) | DcShorthand::Format(_) => Ok(parsed),
2898        other => bail!(
2899            "Implementation file '{rel_path}' stem prefix '{other}' must be a short Dc (e.g. '1936') or transformation format Dc (e.g. 'f1680')"
2900        ),
2901    }
2902}
2903
2904pub(crate) fn parse_staged_header_directives(
2905    src: &str,
2906    rel_path: &str,
2907) -> Result<StagedHeaderDirectives> {
2908    use ctb_storage_minimal::global_graph_layout::{
2909        SYSTEM_REGION_END, SYSTEM_REGION_START,
2910    };
2911
2912    let mut decomp_tag = "semantic".to_owned();
2913    let mut dc_entity: Option<(usize, u128)> = None;
2914    let mut converts: Option<(usize, DcShorthand, DcShorthand)> = None;
2915
2916    for (line_idx, raw_line) in src.lines().enumerate() {
2917        let one_based = line_idx.saturating_add(1);
2918        let trimmed = raw_line.trim();
2919        if trimmed.is_empty() {
2920            continue;
2921        }
2922        let comment_opt = trimmed
2923            .strip_prefix(";;")
2924            .or_else(|| trimmed.strip_prefix('#'))
2925            .or_else(|| trimmed.strip_prefix(": "))
2926            .or_else(|| (trimmed == ":").then_some(""));
2927        let Some(rest) = comment_opt else {
2928            break;
2929        };
2930        let comment = rest.trim();
2931        if comment.contains("@decomp(equiv)") {
2932            decomp_tag = "equiv".to_owned();
2933        } else if comment.contains("@decomp(semantic)") {
2934            decomp_tag = "semantic".to_owned();
2935        }
2936        if let Some(after_dc) = comment.strip_prefix("@dc") {
2937            let arg = after_dc.trim();
2938            ensure!(
2939                !arg.is_empty() && !arg.contains(char::is_whitespace),
2940                "Invalid '@dc' directive at {rel_path}:{one_based}: expected '@dc l<id>'"
2941            );
2942            ensure!(
2943                dc_entity.is_none(),
2944                "Duplicate '@dc' directive at {rel_path}:{one_based}"
2945            );
2946            let parsed = DcShorthand::parse(arg).map_err(|e| {
2947                anyhow!(
2948                    "Invalid '@dc {arg}' shorthand at {rel_path}:{one_based}: {e}"
2949                )
2950            })?;
2951            let DcShorthand::Long(nid) = parsed else {
2952                bail!(
2953                    "'@dc {parsed}' at {rel_path}:{one_based} must be a System-block 'l<id>' node ID"
2954                );
2955            };
2956            ensure!(
2957                (SYSTEM_REGION_START..=SYSTEM_REGION_END).contains(&nid),
2958                "'@dc l{nid}' at {rel_path}:{one_based} is outside System region ({SYSTEM_REGION_START}..={SYSTEM_REGION_END})"
2959            );
2960            dc_entity = Some((one_based, nid));
2961        } else if let Some(after_conv) = comment.strip_prefix("@converts(") {
2962            let inner = after_conv
2963                .strip_suffix(')')
2964                .with_context(|| {
2965                    format!(
2966                        "Malformed '@converts(...)' directive at {rel_path}:{one_based}: missing closing ')'"
2967                    )
2968                })?
2969                .trim();
2970            ensure!(
2971                converts.is_none(),
2972                "Duplicate '@converts(...)' directive at {rel_path}:{one_based}"
2973            );
2974            let parts: Vec<&str> = inner.split_whitespace().collect();
2975            ensure!(
2976                parts.len() == 2,
2977                "Invalid '@converts({inner})' at {rel_path}:{one_based}: expected exactly two Dc shorthands '@converts(<src> <dst>)'"
2978            );
2979            let src_raw = parts.first().copied().context("Missing @converts src")?;
2980            let dst_raw = parts.get(1).copied().context("Missing @converts dst")?;
2981            let src_sh = DcShorthand::parse(src_raw).map_err(|e| {
2982                anyhow!(
2983                    "Invalid source shorthand '{src_raw}' in '@converts' at {rel_path}:{one_based}: {e}"
2984                )
2985            })?;
2986            let dst_sh = DcShorthand::parse(dst_raw).map_err(|e| {
2987                anyhow!(
2988                    "Invalid destination shorthand '{dst_raw}' in '@converts' at {rel_path}:{one_based}: {e}"
2989                )
2990            })?;
2991            converts = Some((one_based, src_sh, dst_sh));
2992        }
2993    }
2994
2995    Ok(StagedHeaderDirectives {
2996        decomp_tag,
2997        dc_entity,
2998        converts,
2999    })
3000}
3001
3002/// Loads and compiles all staged implementation files under `data_dir`
3003/// (`stage_0_impls/`, `stage_1_impls/`, `stage_2_impls/`, `impls/`).
3004///
3005/// # Errors
3006/// Returns an error if any implementation file fails to parse or if two files target the same
3007/// `(target, decomp_tag)` pair.
3008pub fn load_staged_dc_impls(
3009    data_dir: &Path,
3010) -> Result<(Vec<StagedDcImpl>, BTreeMap<String, Vec<u8>>)> {
3011    load_staged_dc_impls_with_compiler(data_dir, None)
3012}
3013
3014/// Loads and compiles all staged implementation files under `data_dir`, invoking `source_compiler`
3015/// when higher-stage `.sl3` (`stage_1_impls/`+) or `.sr3` (`stage_2_impls/`, `impls/`) files
3016/// are present.
3017///
3018/// # Errors
3019/// Returns an error if stage extension constraints are violated, required lower-stage language
3020/// compilers (`StageL3` / `StageR3`) are missing, duplicate targets exist, or compilation fails.
3021#[allow(
3022    clippy::too_many_lines,
3023    reason = "Validates per-stage file extension rules, bootstrap compiler prerequisites, target uniqueness, and compilation"
3024)]
3025pub fn load_staged_dc_impls_with_compiler(
3026    data_dir: &Path,
3027    source_compiler: Option<&StagedSourceCompiler<'_>>,
3028) -> Result<(Vec<StagedDcImpl>, BTreeMap<String, Vec<u8>>)> {
3029    let mut impls: Vec<StagedDcImpl> = Vec::new();
3030    let mut raw_files: BTreeMap<String, Vec<u8>> = BTreeMap::new();
3031    let mut seen_targets: BTreeMap<
3032        (String, String, Vec<DcShorthand>),
3033        String,
3034    > = BTreeMap::new();
3035    let stagel3_sh = ctb_utilities::format_id::FormatId::StageL3.shorthand();
3036    let stager3_sh = ctb_utilities::format_id::FormatId::StageR3.shorthand();
3037    let sh_begin_module = dc_to_sh(DC_BEGIN_MODULE);
3038    let sh_begin_stager_module = dc_to_sh(crate::dc::DC_BEGIN_STAGER_MODULE);
3039    let sh_begin_wasm = dc_to_sh(DC_BEGIN_WASM_PROGRAM);
3040
3041    let transformations_csv =
3042        data_dir.join("categories/formats/transformations.csv");
3043    let mut transformation_converts: BTreeMap<
3044        DcShorthand,
3045        Option<(DcShorthand, DcShorthand)>,
3046    > = BTreeMap::new();
3047    let has_formats_dir = data_dir.join("categories/formats").is_dir();
3048    if transformations_csv.is_file() {
3049        let csv_bytes = std::fs::read(&transformations_csv).with_context(|| {
3050            format!("Failed to read {}", transformations_csv.display())
3051        })?;
3052        let mut dummy_report = crate::report::ValidationReport::new();
3053        let valid_variants = std::collections::HashSet::new();
3054        let rows = crate::format::validate_formats_category_file(
3055            &csv_bytes,
3056            "categories/formats/transformations.csv",
3057            &valid_variants,
3058            &mut dummy_report,
3059        );
3060        for row in rows {
3061            if let Some(fid) = row.short_id {
3062                let conv = row
3063                    .format
3064                    .as_ref()
3065                    .and_then(|f| f.format_spec.as_ref())
3066                    .and_then(|expr| match expr {
3067                        crate::format_spec::FormatExpr::Convert(l, r) => {
3068                            match (l.as_ref(), r.as_ref()) {
3069                                (
3070                                    crate::format_spec::FormatExpr::Dc(s),
3071                                    crate::format_spec::FormatExpr::Dc(d),
3072                                ) => Some((*s, *d)),
3073                                _ => None,
3074                            }
3075                        }
3076                        _ => None,
3077                    });
3078                transformation_converts
3079                    .insert(DcShorthand::Format(fid), conv);
3080            }
3081        }
3082    }
3083
3084    for stage in ImplStage::ALL {
3085        let dir_path = data_dir.join(stage.dir_name());
3086        if !dir_path.exists() {
3087            continue;
3088        }
3089        let mut entries: Vec<_> = std::fs::read_dir(&dir_path)
3090            .with_context(|| {
3091                format!("Failed to read directory {}", dir_path.display())
3092            })?
3093            .collect::<std::result::Result<Vec<_>, _>>()?;
3094        entries.sort_by_key(std::fs::DirEntry::file_name);
3095
3096        for entry in entries {
3097            let path = entry.path();
3098            if path.is_dir() {
3099                continue;
3100            }
3101            let Some(file_name) = path.file_name().and_then(|n| n.to_str())
3102            else {
3103                continue;
3104            };
3105            if file_name.starts_with('.') || file_name.ends_with(".md") {
3106                continue;
3107            }
3108            // Reason for fallback: files without an extension default to empty extension.
3109            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
3110            match stage {
3111                ImplStage::Stage0 => {
3112                    ensure!(
3113                        ext == "wat",
3114                        "stage_0_impls file '{}' must be a .wat file",
3115                        path.display()
3116                    );
3117                }
3118                ImplStage::Stage1 => {
3119                    if ext == "wat" {
3120                        bail!(
3121                            "stage_1_impls file '{}' cannot be a .wat file (.wat is restricted to stage_0_impls/)",
3122                            path.display()
3123                        );
3124                    }
3125                    ensure!(
3126                        matches!(ext, "dcsh" | "sl3"),
3127                        "Unsupported file extension '.{ext}' in {}: expected .dcsh or .sl3",
3128                        path.display()
3129                    );
3130                }
3131                ImplStage::Stage2 | ImplStage::Impls => {
3132                    if ext == "wat" {
3133                        bail!(
3134                            "{} file '{}' cannot be a .wat file (.wat is restricted to stage_0_impls/)",
3135                            stage.dir_name(),
3136                            path.display()
3137                        );
3138                    }
3139                    ensure!(
3140                        matches!(ext, "dcsh" | "sl3" | "sr3"),
3141                        "Unsupported file extension '.{ext}' in {}: expected .dcsh, .sl3, or .sr3",
3142                        path.display()
3143                    );
3144                }
3145            }
3146
3147            let rel_path = format!(
3148                "src/formats/dcdata/data-src/{}/{file_name}",
3149                stage.dir_name()
3150            );
3151            let bytes = std::fs::read(&path).with_context(|| {
3152                format!("Failed to read {}", path.display())
3153            })?;
3154            let src = std::str::from_utf8(&bytes).with_context(|| {
3155                format!("Implementation file {rel_path} is not valid UTF-8")
3156            })?;
3157            let stem = path
3158                .file_stem()
3159                .and_then(|s| s.to_str())
3160                // Reason for fallback: files without stem default to entire file name.
3161                .unwrap_or(file_name);
3162            let directives = parse_staged_header_directives(src, &rel_path)?;
3163            let (target, converts) = match (
3164                directives.converts,
3165                directives.dc_entity,
3166            ) {
3167                (Some((conv_line, src_sh, dst_sh)), Some((_, nid))) => {
3168                    ensure!(
3169                        parse_target_from_stem(stem, &rel_path).is_err(),
3170                        "Standalone '@converts({src_sh} {dst_sh})' file '{rel_path}' must use a descriptive stem (e.g. 'stagel3_to_wasm.wat'), not a Short or Format Dc stem"
3171                    );
3172                    (DcShorthand::Long(nid), Some((src_sh, dst_sh)))
3173                }
3174                (Some((conv_line, src_sh, dst_sh)), None) => {
3175                    bail!(
3176                        "Standalone '@converts({src_sh} {dst_sh})' file '{rel_path}' (line {conv_line}) is missing '@dc l<id>'; run validate-data-tables --write to allocate an entity ID"
3177                    );
3178                }
3179                (None, Some((dc_line, nid))) => {
3180                    bail!(
3181                        "'@dc l{nid}' at {rel_path}:{dc_line} is only permitted on standalone '@converts(<src> <dst>)' converter files in {} (Short/Format targets use filename stems)",
3182                        stage.dir_name()
3183                    );
3184                }
3185                (None, None) => (parse_target_from_stem(stem, &rel_path)?, None),
3186            };
3187            if has_formats_dir
3188                && let DcShorthand::Format(fid) = target
3189                && !transformation_converts.contains_key(&target)
3190            {
3191                bail!(
3192                    "Implementation file '{rel_path}' cannot target Format Dc f{fid}: only document transformations (.Formats:transformation in transformations.csv) may own direct implementations"
3193                );
3194            }
3195            let effective_converts = converts.or_else(|| {
3196                transformation_converts.get(&target).copied().flatten()
3197            });
3198            let target_key = target.to_string();
3199            let decomp_tag = directives.decomp_tag;
3200            let stagel3_fmt_sh = DcShorthand::parse(&stagel3_sh)
3201                .context("Invalid StageL3 format shorthand")?;
3202            let stager3_fmt_sh = DcShorthand::parse(&stager3_sh)
3203                .context("Invalid StageR3 format shorthand")?;
3204
3205            let compiled_entries: Vec<(Vec<DcShorthand>, Vec<DcShorthand>)> =
3206                match ext {
3207                    "wat" => wat_to_staged_dc_entries(src)
3208                        .with_context(|| format!("Failed to compile {rel_path}"))?,
3209                    "dcsh" => vec![(
3210                        Vec::new(),
3211                        parse_dcsh_impl_tokens(src)
3212                            .with_context(|| format!("Failed to parse {rel_path}"))?,
3213                    )],
3214                    "sl3" => {
3215                        let has_sl3_compiler = impls.iter().any(|prior| {
3216                            prior.stage == ImplStage::Stage0
3217                                && (prior.converts
3218                                    == Some((
3219                                        sh_begin_module,
3220                                        sh_begin_wasm,
3221                                    ))
3222                                    || prior.converts
3223                                        == Some((
3224                                            stagel3_fmt_sh,
3225                                            sh_begin_wasm,
3226                                        )))
3227                        });
3228                        ensure!(
3229                            has_sl3_compiler,
3230                            "Cannot compile '{rel_path}': StageL 3 transformation (@chain(2192 > 1927) or @converts(2192 1927)) must be defined in stage_0_impls/ first"
3231                        );
3232                        let compiler = source_compiler.with_context(|| {
3233                            format!(
3234                                "Cannot compile '{rel_path}': no StageL 3 bootstrap execution hook was provided to load_staged_dc_impls_with_compiler"
3235                            )
3236                        })?;
3237                        vec![(
3238                            Vec::new(),
3239                            compiler(stage, ext, src, &impls).with_context(
3240                                || format!("Failed to compile {rel_path}"),
3241                            )?,
3242                        )]
3243                    }
3244                    "sr3" => {
3245                        let has_sr3_compiler = impls.iter().any(|prior| {
3246                            prior.stage < stage
3247                                && (prior.converts
3248                                    == Some((
3249                                        sh_begin_stager_module,
3250                                        sh_begin_module,
3251                                    ))
3252                                    || prior.converts
3253                                        == Some((
3254                                            sh_begin_stager_module,
3255                                            sh_begin_wasm,
3256                                        ))
3257                                    || prior.converts
3258                                        == Some((
3259                                            stager3_fmt_sh,
3260                                            sh_begin_wasm,
3261                                        )))
3262                        });
3263                        ensure!(
3264                            has_sr3_compiler,
3265                            "Cannot compile '{rel_path}': StageR 3 transformation (@chain(2221 > 2192) or @converts({stager3_sh} 1927)) must be defined in stage_0_impls/ or stage_1_impls/ first"
3266                        );
3267                        let compiler = source_compiler.with_context(|| {
3268                            format!(
3269                                "Cannot compile '{rel_path}': no StageR 3 bootstrap execution hook was provided to load_staged_dc_impls_with_compiler"
3270                            )
3271                        })?;
3272                        vec![(
3273                            Vec::new(),
3274                            compiler(stage, ext, src, &impls).with_context(
3275                                || format!("Failed to compile {rel_path}"),
3276                            )?,
3277                        )]
3278                    }
3279                    _ => {
3280                        bail!("Unhandled staged implementation extension '.{ext}'")
3281                    }
3282                };
3283
3284            raw_files.insert(rel_path.clone(), bytes);
3285            for (context_tokens, tokens) in compiled_entries {
3286                if let Some(prev_path) = seen_targets.insert(
3287                    (
3288                        target_key.clone(),
3289                        decomp_tag.clone(),
3290                        context_tokens.clone(),
3291                    ),
3292                    rel_path.clone(),
3293                ) {
3294                    let ctx_desc = if context_tokens.is_empty() {
3295                        String::new()
3296                    } else {
3297                        let joined: Vec<String> = context_tokens
3298                            .iter()
3299                            .map(ToString::to_string)
3300                            .collect();
3301                        format!(" @context({})", joined.join(" "))
3302                    };
3303                    bail!(
3304                        "Duplicate <{decomp_tag}>{ctx_desc} implementation for {target_key} in '{rel_path}' and '{prev_path}'"
3305                    );
3306                }
3307                impls.push(StagedDcImpl {
3308                    stage,
3309                    rel_path: rel_path.clone(),
3310                    target,
3311                    converts: effective_converts,
3312                    context_tokens,
3313                    decomp_tag: decomp_tag.clone(),
3314                    tokens,
3315                });
3316            }
3317        }
3318    }
3319
3320    Ok((impls, raw_files))
3321}
3322
3323#[cfg(test)]
3324#[allow(
3325    clippy::panic,
3326    clippy::expect_used,
3327    clippy::unwrap_used,
3328    clippy::unwrap_in_result,
3329    clippy::panic_in_result_fn,
3330    clippy::indexing_slicing,
3331    clippy::arithmetic_side_effects,
3332    reason = "Standard repository test boilerplate"
3333)]
3334mod tests {
3335    use super::*;
3336
3337    #[crate::ctb_test]
3338    fn test_wat_single_function_and_folded_sexprs_to_shorthands() -> Result<()> {
3339        let wat = r#"
3340            ;; Workspace supervisor echo step
3341            (module
3342              (func (export "main") (result i32)
3343                (i32.store (i32.const 8) (i32.load (i32.const 0)))
3344                (i32.store (i32.const 12) (i32.load (i32.const 4)))
3345                (i32.const 0)))
3346        "#;
3347        let shorthands = wat_to_dc_shorthands(wat)?;
3348        let rendered = wat_to_dc_shorthand_string(wat)?;
3349        assert_eq!(
3350            rendered,
3351            "1927 260 262 280 f208 263 712 6 f199 135 7 712 6 f199 127 7 687 6 f199 127 7 6 f199 129 7 6 f199 127 7 701 6 f199 127 7 6 f199 129 7 6 f199 127 7 712 6 f199 139 7 712 6 f199 131 7 687 6 f199 127 7 6 f199 129 7 6 f199 127 7 701 6 f199 127 7 6 f199 129 7 6 f199 127 7 712 6 f199 127 7 261 1928"
3352        );
3353        assert_eq!(shorthands.first(), Some(&DcShorthand::Short(1927)));
3354        assert_eq!(shorthands.last(), Some(&DcShorthand::Short(1928)));
3355        Ok(())
3356    }
3357
3358    #[crate::ctb_test]
3359    fn test_wat_named_locals_labels_and_if_else() -> Result<()> {
3360        let wat = r#"
3361            (module
3362              (func (export "main") (local $ptr i32) (local $end i32) (result i32)
3363                (local.set $ptr (i32.load (i32.const 0)))
3364                (local.set $end (i32.add (local.get $ptr) (i32.load (i32.const 4))))
3365                (block $exit
3366                  (loop $top
3367                    (br_if $exit (i32.eq (local.get $ptr) (local.get $end)))
3368                    (local.set $ptr (i32.add (local.get $ptr) (i32.const 1)))
3369                    (br $top)))
3370                (if (result i32) (i32.eq (local.get $ptr) (local.get $end))
3371                  (then (i32.const 0))
3372                  (else (unreachable)))))
3373        "#;
3374        let shorthands = wat_to_dc_shorthands(wat)?;
3375        assert!(shorthands.contains(&DcShorthand::Short(649))); // block
3376        assert!(shorthands.contains(&DcShorthand::Short(650))); // loop
3377        assert!(shorthands.contains(&DcShorthand::Short(651))); // if
3378        assert!(shorthands.contains(&DcShorthand::Short(652))); // else
3379        assert!(shorthands.contains(&DcShorthand::Short(660))); // br_if
3380        Ok(())
3381    }
3382
3383    #[crate::ctb_test]
3384    fn test_wat_readability_sugar_consts_inline_operands_and_when() -> Result<()> {
3385        let verbose_wat = r#"
3386            (module
3387              (func (export "_start") (result i32)
3388                (local $ptr i32)
3389                (local $val i32)
3390                (local.set $ptr (i32.load align=4 offset=0 (i32.const 0)))
3391                (if (i32.ge_u (local.get $ptr) (i32.const 64))
3392                  (then (unreachable)))
3393                (local.set $val (i32.load8_u align=1 offset=64 (local.get $ptr)))
3394                (i32.store align=4 offset=0 (i32.const 8) (i32.add (local.get $val) (i32.const 1)))
3395                (i64.store align=1 offset=0 (i32.const 68) (i64.const 1000000))
3396                (i32.const 0)))
3397        "#;
3398        let concise_wat = r#"
3399            (module
3400              (const $MB_IN_PTR 0)
3401              (const $MB_OUT_PTR 8)
3402              (const $CFG_BASE 64)
3403              (const $CFG_COMPUTE_QUOTA 68)
3404              (func (export "_start") (result i32)
3405                (local $ptr i32)
3406                (local $val i32)
3407                (set $ptr (i32.load $MB_IN_PTR))
3408                (when (i32.ge_u $ptr $CFG_BASE) (unreachable))
3409                (set $val (i32.load8_u offset=$CFG_BASE $ptr))
3410                (i32.store $MB_OUT_PTR (i32.add $val 1))
3411                (i64.store align=1 $CFG_COMPUTE_QUOTA 1000000)
3412                (i32.const 0)))
3413        "#;
3414        assert_eq!(
3415            wat_to_dc_shorthands(concise_wat)?,
3416            wat_to_dc_shorthands(verbose_wat)?
3417        );
3418        Ok(())
3419    }
3420
3421    #[crate::ctb_test]
3422    fn test_wat_folded_i64_operand_inference_and_memory_validation() -> Result<()> {
3423        let explicit_wat = r#"
3424            (module
3425              (memory (export "memory") 1)
3426              (global $g64 (mut i64) (i64.const 0))
3427              (func $helper (param $a i64) (param $b i32) (result i32)
3428                (i32.add (i32.wrap_i64 (local.get $a)) (local.get $b)))
3429              (func (export "main") (result i32)
3430                (local $x64 i64)
3431                (local.set $x64 (i64.const 0x1_0000_0005))
3432                (global.set $g64 (local.tee $x64 (i64.extend_i32_u (i32.const 42))))
3433                (return_call $helper (i64.const -9) (i32.wrap_i64 (i64.const 51)))))
3434        "#;
3435        let inferred_wat = r#"
3436            (module
3437              (memory (export "memory") 1)
3438              (const $FIFTY_ONE 51)
3439              (global $g64 (mut i64) (i64.const 0))
3440              (func $helper (param $a i64) (param $b i32) (result i32)
3441                (i32.add (i32.wrap_i64 $a) $b))
3442              (func (export "main") (result i32)
3443                (local $x64 i64)
3444                (set $x64 0x1_0000_0005)
3445                (global.set $g64 (tee $x64 (i64.extend_i32_u 42)))
3446                (return_call $helper -9 (i32.wrap_i64 $FIFTY_ONE))))
3447        "#;
3448        assert_eq!(
3449            wat_to_dc_shorthands(inferred_wat)?,
3450            wat_to_dc_shorthands(explicit_wat)?
3451        );
3452
3453        let invalid_mem_wat = r#"
3454            (module
3455              (memory 2)
3456              (func (export "main") (result i32) (i32.const 0)))
3457        "#;
3458        assert!(wat_to_dc_shorthands(invalid_mem_wat).is_err());
3459        Ok(())
3460    }
3461
3462    #[crate::ctb_test]
3463    fn test_load_staged_dc_impls_supports_format_stems_and_stage_gating() -> Result<()> {
3464        let tmp = tempfile::tempdir()?;
3465        let s0 = tmp.path().join("stage_0_impls");
3466        let s1 = tmp.path().join("stage_1_impls");
3467        let s2 = tmp.path().join("stage_2_impls");
3468        let imp = tmp.path().join("impls");
3469        let fmt_dir = tmp.path().join("categories/formats");
3470        std::fs::create_dir_all(&s0)?;
3471        std::fs::create_dir_all(&s1)?;
3472        std::fs::create_dir_all(&s2)?;
3473        std::fs::create_dir_all(&imp)?;
3474        std::fs::create_dir_all(&fmt_dir)?;
3475
3476        std::fs::write(
3477            fmt_dir.join("programming.csv"),
3478            "Dc,Short,Ident,Title,Category,Base,Extensions,MIME,Magic,Syntax,Nickname,Import support,Export support,Tests,Security audit,Comments,External links\n2228880,656,StageL3,StageL 3,programming,,,,,,sl3,,,,,,\n",
3479        )?;
3480        std::fs::write(
3481            fmt_dir.join("transformations.csv"),
3482            "Dc,Short,Ident,Title,Category,Base,Extensions,MIME,Magic,Syntax,Nickname,Import support,Export support,Tests,Security audit,Comments,External links\n2229904,1680,StageL3ToWasm,StageL 3 Dcs to WASM,transformation,@chain(2192 > 1927),,,,,stagel3_to_wasm,,,,,,\n2229905,1681,StageR3ToStageL3,StageR 3 Dcs to StageL 3 Dcs,transformation,@chain(2221 > 2192),,,,,stager3_to_stagel3,,,,,,\n",
3483        )?;
3484
3485        let minimal_wat =
3486            r#"(module (func (export "main") (result i32) (i32.const 0)))"#;
3487
3488        // `.sl3` in stage_1_impls without StageL3ToWasm in stage_0_impls must fail.
3489        std::fs::write(
3490            s1.join("f1681_stager3_to_stagel3.sl3"),
3491            ": @decomp(equiv)\nv/void/noop :: do ::.\n",
3492        )?;
3493        assert!(
3494            load_staged_dc_impls_with_compiler(
3495                tmp.path(),
3496                Some(&|_, _, _, _| Ok(vec![DcShorthand::Short(1927), DcShorthand::Short(1928)]))
3497            )
3498            .is_err()
3499        );
3500
3501        // Attaching `.wat` directly to non-transformation format `f656` must fail!
3502        std::fs::write(s0.join("f656_stagel3.wat"), minimal_wat)?;
3503        assert!(
3504            load_staged_dc_impls_with_compiler(
3505                tmp.path(),
3506                Some(&|_, _, _, _| Ok(vec![DcShorthand::Short(1927), DcShorthand::Short(1928)]))
3507            )
3508            .is_err()
3509        );
3510        std::fs::remove_file(s0.join("f656_stagel3.wat"))?;
3511
3512        // Adding `f1680_stagel3_to_wasm.wat` in stage_0_impls unlocks `.sl3` in stage_1_impls,
3513        // and `f1681_stager3_to_stagel3.sl3` in stage_1_impls unlocks `.sr3` in stage_2_impls/ and impls/.
3514        std::fs::write(s0.join("f1680_stagel3_to_wasm.wat"), minimal_wat)?;
3515        std::fs::write(s2.join("258_stage2.sr3"), "v/void/stageTwo :: do ::.\n")?;
3516        std::fs::write(imp.join("256_say.sr3"), "v/void/say :: do ::.\n")?;
3517
3518        let (loaded, _raw) = load_staged_dc_impls_with_compiler(
3519            tmp.path(),
3520            Some(&|_stage, _ext, _src, _prior| {
3521                Ok(vec![DcShorthand::Short(1927), DcShorthand::Short(1928)])
3522            }),
3523        )?;
3524        assert_eq!(loaded.len(), 4);
3525        assert_eq!(loaded[0].target.to_string(), "f1680");
3526        assert_eq!(loaded[0].decomp_tag, "semantic");
3527        assert_eq!(loaded[1].target.to_string(), "f1681");
3528        assert_eq!(loaded[1].decomp_tag, "equiv");
3529        assert_eq!(loaded[2].stage, ImplStage::Stage2);
3530        assert_eq!(loaded[2].target, DcShorthand::Short(258));
3531        assert_eq!(loaded[3].stage, ImplStage::Impls);
3532        assert_eq!(loaded[3].target, DcShorthand::Short(256));
3533
3534        // `.sr3` is rejected in stage_1_impls/.
3535        std::fs::write(s1.join("257_bad.sr3"), "v/void/bad :: do ::.\n")?;
3536        assert!(
3537            load_staged_dc_impls_with_compiler(
3538                tmp.path(),
3539                Some(&|_, _, _, _| Ok(vec![DcShorthand::Short(1927), DcShorthand::Short(1928)]))
3540            )
3541            .is_err()
3542        );
3543        Ok(())
3544    }
3545
3546    #[crate::ctb_test]
3547    fn test_wat_context_directives_and_helper_reachability() -> Result<()> {
3548        let wat = r#"
3549            (module
3550              (memory (export "memory") 1)
3551              (global $__heap_ptr (mut i32) (i32.const 256))
3552
3553              (func $_alloc (param $n i32) (result i32)
3554                (local $p i32)
3555                (set $p $__heap_ptr)
3556                (global.set $__heap_ptr (i32.add $p $n))
3557                (get $p))
3558
3559              ;; @context(f208)
3560              ;; @context(f207)
3561              (func $i32_u32 (param $a i32) (param $b i32) (result i32)
3562                (i32.add $a $b))
3563
3564              ;; @context(2576 275)
3565              (func $alloc_hdr (result i32)
3566                (call $_alloc 16)))
3567        "#;
3568        let entries = wat_to_staged_dc_entries(wat)?;
3569        assert_eq!(entries.len(), 3);
3570        assert_eq!(entries[0].0, vec![DcShorthand::Format(208)]);
3571        assert_eq!(entries[1].0, vec![DcShorthand::Format(207)]);
3572        assert_eq!(entries[0].1, entries[1].1);
3573        // Single-function entry without helpers/globals emits compact `1927 260 ... 261 1928`.
3574        assert_eq!(entries[0].1[1], dc_to_sh(DC_BEGIN_LITERAL));
3575
3576        assert_eq!(
3577            entries[2].0,
3578            vec![DcShorthand::Short(2576), DcShorthand::Short(275)]
3579        );
3580        // Entry reaching `$_alloc` and `$__heap_ptr` emits `1927 559 ... 560 1928`.
3581        assert_eq!(entries[2].1[1], dc_to_sh(DC_BEGIN_KV_MAP));
3582        Ok(())
3583    }
3584
3585    #[crate::ctb_test]
3586    fn test_load_staged_dc_impls_supports_standalone_converter_routines() -> Result<()> {
3587        let tmp = tempfile::tempdir()?;
3588        let s0 = tmp.path().join("stage_0_impls");
3589        let s1 = tmp.path().join("stage_1_impls");
3590        std::fs::create_dir_all(&s0)?;
3591        std::fs::create_dir_all(&s1)?;
3592
3593        // Missing `@dc` on `@converts` must fail until allocated.
3594        std::fs::write(
3595            s0.join("stagel3_to_wasm.wat"),
3596            ";; @converts(2192 1927)\n(module (func (export \"main\") (result i32) (i32.const 0)))\n",
3597        )?;
3598        assert!(load_staged_dc_impls(tmp.path()).is_err());
3599
3600        // With `@dc l8589935000` + `@converts(2192 1927)`, loads as standalone Long target and unlocks `.sl3` in Stage 1.
3601        std::fs::write(
3602            s0.join("stagel3_to_wasm.wat"),
3603            ";; @dc l8589935000\n;; @converts(2192 1927)\n(module (func (export \"main\") (result i32) (i32.const 0)))\n",
3604        )?;
3605        std::fs::write(s1.join("256_say.sl3"), "v/void/say :: do ::.\n")?;
3606
3607        let (loaded, _raw) = load_staged_dc_impls_with_compiler(
3608            tmp.path(),
3609            Some(&|_stage, _ext, _src, _prior| {
3610                Ok(vec![DcShorthand::Short(1927), DcShorthand::Short(1928)])
3611            }),
3612        )?;
3613        assert_eq!(loaded.len(), 2);
3614        assert_eq!(loaded[0].target, DcShorthand::Long(8_589_935_000));
3615        assert_eq!(
3616            loaded[0].converts,
3617            Some((DcShorthand::Short(2192), DcShorthand::Short(1927)))
3618        );
3619        assert_eq!(loaded[1].target, DcShorthand::Short(256));
3620        Ok(())
3621    }
3622
3623    #[crate::ctb_test]
3624    fn test_wat_multi_member_emits_symbolic_call_and_global_targets_immune_to_helper_insertion()
3625     -> Result<()> {
3626        let wat_v1 = r#"
3627            (module
3628              (memory (export "memory") 1)
3629              (global $g_acc (mut i32) (i32.const 10))
3630              (func $helper (param $x i32) (result i32)
3631                (i32.add $x $g_acc))
3632              (func (export "main") (param $n i32) (result i32)
3633                (global.set $g_acc (call $helper $n))
3634                (return_call $helper (global.get $g_acc))))
3635        "#;
3636        let wat_v2 = r#"
3637            (module
3638              (memory (export "memory") 1)
3639              (global $g_extra (mut i32) (i32.const 99))
3640              (global $g_acc (mut i32) (i32.const 10))
3641              (func $inserted_before (param $z i32) (result i32)
3642                (i32.sub $z $g_extra))
3643              (func $helper (param $x i32) (result i32)
3644                (i32.add $x $g_acc))
3645              (func (export "main") (param $n i32) (result i32)
3646                (global.set $g_acc (call $helper $n))
3647                (return_call $helper (global.get $g_acc))))
3648        "#;
3649        let toks_v1 = wat_to_dc_shorthands(wat_v1)?;
3650        let toks_v2 = wat_to_dc_shorthands(wat_v2)?;
3651
3652        // Extract the trailing `(export "main")` `Dc 260..261` routine literal from both modules:
3653        // despite shifting both `$g_acc` (0 -> 1) and `$helper` (0 -> 1), `main`'s Dc routine is identical!
3654        let extract_last_routine = |toks: &[DcShorthand]| -> Vec<DcShorthand> {
3655            let start = toks
3656                .iter()
3657                .rposition(|&t| t == dc_to_sh(DC_BEGIN_LITERAL))
3658                .unwrap();
3659            let end = toks[start..]
3660                .iter()
3661                .position(|&t| t == dc_to_sh(DC_END_LITERAL))
3662                .unwrap();
3663            toks[start..=start + end].to_vec()
3664        };
3665        let main_v1 = extract_last_routine(&toks_v1);
3666        let main_v2 = extract_last_routine(&toks_v2);
3667        assert_eq!(main_v1, main_v2);
3668        assert!(main_v1.contains(&dc_to_sh(DC_BEGIN_IDENTIFIER)));
3669        Ok(())
3670    }
3671}