Skip to main content

synth_core/
wasm_decoder.rs

1//! WASM Binary Decoder - Converts wasmparser operators to WasmOp sequences
2//!
3//! This module bridges the gap between parsed WASM binaries and any backend.
4//! It extracts function bodies and converts wasmparser operators to our internal WasmOp format.
5
6use crate::wasm_op::WasmOp;
7use anyhow::{Context, Result};
8use std::collections::HashMap;
9use wasmparser::{ExternalKind, Parser, Payload};
10
11/// Kind of a WASM import
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum ImportKind {
14    /// Imported function with type index
15    Function(u32),
16    /// Imported memory
17    Memory,
18    /// Imported table
19    Table,
20    /// Imported global
21    Global,
22}
23
24/// A WASM import entry with full metadata
25#[derive(Debug, Clone)]
26pub struct ImportEntry {
27    /// Module name (e.g., "wasi:cli/stdout" or "env")
28    pub module: String,
29    /// Field name (e.g., "write" or "memory")
30    pub name: String,
31    /// Import kind and associated data
32    pub kind: ImportKind,
33    /// Index of this import within its kind (e.g., function import index)
34    pub index: u32,
35}
36
37/// WASM linear memory specification
38#[derive(Debug, Clone)]
39pub struct WasmMemory {
40    /// Memory index
41    pub index: u32,
42    /// Initial size in pages (64KB each)
43    pub initial_pages: u32,
44    /// Maximum size in pages (if specified)
45    pub max_pages: Option<u32>,
46    /// Whether memory is shared (requires threads proposal)
47    pub shared: bool,
48}
49
50/// A WASM global's declaration — its initial value and mutability (#237).
51/// Needed so the native-pointer ABI can recognize a global whose initializer is
52/// a linear-memory address (e.g. `$__stack_pointer = 65536`) and make it
53/// `__synth_wasm_data`-relative, rather than reading it from an R9 globals table
54/// the self-contained drop-in object can't rely on.
55#[derive(Debug, Clone)]
56pub struct WasmGlobal {
57    /// Global index (defined globals; imported globals are not counted here).
58    pub index: u32,
59    /// The `i32.const` initializer value (other init exprs decode to `None`).
60    pub init_i32: Option<i32>,
61    /// Whether the global is mutable.
62    pub mutable: bool,
63}
64
65impl WasmMemory {
66    /// Get initial size in bytes
67    pub fn initial_bytes(&self) -> u32 {
68        self.initial_pages * 65536
69    }
70
71    /// Get maximum size in bytes (or initial if not specified)
72    pub fn max_bytes(&self) -> u32 {
73        self.max_pages.unwrap_or(self.initial_pages) * 65536
74    }
75}
76
77/// Decoded WASM module with functions and memory
78#[derive(Debug, Clone)]
79pub struct DecodedModule {
80    /// Decoded functions
81    pub functions: Vec<FunctionOps>,
82    /// Linear memories
83    pub memories: Vec<WasmMemory>,
84    /// Data segments (offset, data) for memory initialization
85    pub data_segments: Vec<(u32, Vec<u8>)>,
86    /// Import entries (module name, field name, kind)
87    pub imports: Vec<ImportEntry>,
88    /// Number of imported functions (for distinguishing import calls from local calls)
89    pub num_imported_funcs: u32,
90    /// AAPCS integer-argument count per function, indexed by the *full* WASM
91    /// function index (imported functions first, then locally-defined ones).
92    /// Used by the backend to marshal call arguments into R0–R3 (issue #195).
93    /// Counts every parameter as one slot (i64/f64 over-counted — see the
94    /// backend's `set_func_arg_counts` scope note).
95    pub func_arg_counts: Vec<u32>,
96    /// AAPCS integer-argument count per *function type*, indexed by type index.
97    /// Used by `call_indirect`, whose callee arg count comes from the static
98    /// type index (issue #195).
99    pub type_arg_counts: Vec<u32>,
100    /// #311: whether each *function* (full index, imports first) returns i64 —
101    /// the call lowering must tag the result as a register PAIR (r0:r1) or the
102    /// hi half is invisible to liveness and the next constant clobbers it.
103    pub func_ret_i64: Vec<bool>,
104    /// #311: whether each *function type* returns i64 (for `call_indirect`).
105    pub type_ret_i64: Vec<bool>,
106    /// #359: declared parameter widths per *function* (full index, imports
107    /// first): `func_params_i64[f][k]` is true when param `k` is i64/f64. The
108    /// AAPCS stack-argument path needs the declared widths — op-stream inference
109    /// can't see an unused i64 param that still shifts the incoming-stack layout.
110    pub func_params_i64: Vec<Vec<bool>>,
111    /// Defined globals with their initializers (#237). Empty if the module has
112    /// no global section. Used by the native-pointer ABI to make a global whose
113    /// initializer is a linear-memory address (e.g. `$__stack_pointer`)
114    /// self-contained rather than table-relative.
115    pub globals: Vec<WasmGlobal>,
116    /// Function indices that populate any table via an element segment (#275).
117    /// These are the possible `call_indirect` targets — a function reached only
118    /// through the table is invisible to direct-`call` reachability, so the
119    /// whole-graph closure must treat every table entry as reachable once any
120    /// reachable function performs a `call_indirect`. Empty for modules with no
121    /// element section (every leaf/direct-call module), keeping output identical.
122    pub elem_func_indices: Vec<u32>,
123}
124
125/// Decode a WASM binary and extract functions, memory, and data segments
126pub fn decode_wasm_module(wasm_bytes: &[u8]) -> Result<DecodedModule> {
127    let mut functions = Vec::new();
128    let mut memories = Vec::new();
129    let mut data_segments = Vec::new();
130    let mut globals: Vec<WasmGlobal> = Vec::new();
131    let mut imports = Vec::new();
132    let mut func_index = 0u32;
133    let mut num_imported_funcs = 0u32;
134    let mut export_names: HashMap<u32, String> = HashMap::new();
135    // #195: per-type AAPCS arg count (indexed by type index) and per-function
136    // arg count (indexed by full function index: imports first, then locals).
137    let mut type_arg_counts: Vec<u32> = Vec::new();
138    let mut func_arg_counts: Vec<u32> = Vec::new();
139    let mut type_ret_i64: Vec<bool> = Vec::new();
140    let mut func_ret_i64: Vec<bool> = Vec::new();
141    // #359: declared param widths per type / per function (full index).
142    let mut type_params_i64: Vec<Vec<bool>> = Vec::new();
143    let mut func_params_i64: Vec<Vec<bool>> = Vec::new();
144    let mut elem_func_indices: Vec<u32> = Vec::new();
145
146    for payload in Parser::new(0).parse_all(wasm_bytes) {
147        let payload = payload.context("Failed to parse WASM payload")?;
148
149        match payload {
150            Payload::TypeSection(reader) => {
151                // Record the parameter count of each function type so calls can
152                // marshal the right number of arguments (issue #195).
153                for rec_group in reader {
154                    let rec_group = rec_group.context("Failed to parse type")?;
155                    for sub_ty in rec_group.types() {
156                        let (count, ret_i64, params_i64) = match &sub_ty.composite_type.inner {
157                            wasmparser::CompositeInnerType::Func(func_ty) => (
158                                func_ty.params().len() as u32,
159                                func_ty
160                                    .results()
161                                    .first()
162                                    .is_some_and(|t| *t == wasmparser::ValType::I64),
163                                // #359: i64/f64 params occupy 8 bytes / a register
164                                // pair under AAPCS. f32/f64 are not in scope for the
165                                // stack-arg path (refused), but mark both 64-bit
166                                // float and i64 so the guard catches them.
167                                func_ty
168                                    .params()
169                                    .iter()
170                                    .map(|t| {
171                                        matches!(
172                                            t,
173                                            wasmparser::ValType::I64 | wasmparser::ValType::F64
174                                        )
175                                    })
176                                    .collect::<Vec<bool>>(),
177                            ),
178                            _ => (0, false, Vec::new()),
179                        };
180                        type_arg_counts.push(count);
181                        type_ret_i64.push(ret_i64);
182                        type_params_i64.push(params_i64);
183                    }
184                }
185            }
186            Payload::ImportSection(reader) => {
187                // wasmparser 0.221+ groups imports (the "compact imports"
188                // proposal): the section reader yields `Imports` groups, each of
189                // which may expand to several `Import`s. `into_imports()`
190                // flattens groups back to individual `Import`s (preserving the
191                // module/name/ty fields), keeping the per-import loop intact.
192                for import in reader.into_imports() {
193                    let import = import.context("Failed to parse import")?;
194                    let (kind, idx) = match import.ty {
195                        wasmparser::TypeRef::Func(type_idx) => {
196                            let idx = num_imported_funcs;
197                            num_imported_funcs += 1;
198                            // Record the imported function's arg count at its
199                            // full function index (imports come first).
200                            func_arg_counts
201                                .push(type_arg_counts.get(type_idx as usize).copied().unwrap_or(0));
202                            func_ret_i64.push(
203                                type_ret_i64
204                                    .get(type_idx as usize)
205                                    .copied()
206                                    .unwrap_or(false),
207                            );
208                            func_params_i64.push(
209                                type_params_i64
210                                    .get(type_idx as usize)
211                                    .cloned()
212                                    .unwrap_or_default(),
213                            );
214                            (ImportKind::Function(type_idx), idx)
215                        }
216                        wasmparser::TypeRef::Memory(_) => (ImportKind::Memory, 0),
217                        wasmparser::TypeRef::Table(_) => (ImportKind::Table, 0),
218                        wasmparser::TypeRef::Global(_) => (ImportKind::Global, 0),
219                        _ => continue,
220                    };
221                    imports.push(ImportEntry {
222                        module: import.module.to_string(),
223                        name: import.name.to_string(),
224                        kind,
225                        index: idx,
226                    });
227                }
228            }
229            Payload::FunctionSection(reader) => {
230                // Each entry gives the type index of a locally-defined function,
231                // in order. Their full function indices follow the imports, so
232                // appending to `func_arg_counts` keeps it indexed by full index
233                // (issue #195).
234                for ty in reader {
235                    let type_idx = ty.context("Failed to parse function type index")?;
236                    func_arg_counts
237                        .push(type_arg_counts.get(type_idx as usize).copied().unwrap_or(0));
238                    func_ret_i64.push(
239                        type_ret_i64
240                            .get(type_idx as usize)
241                            .copied()
242                            .unwrap_or(false),
243                    );
244                    func_params_i64.push(
245                        type_params_i64
246                            .get(type_idx as usize)
247                            .cloned()
248                            .unwrap_or_default(),
249                    );
250                }
251            }
252            Payload::MemorySection(reader) => {
253                for (idx, memory) in reader.into_iter().enumerate() {
254                    let mem = memory.context("Failed to parse memory")?;
255                    memories.push(WasmMemory {
256                        index: idx as u32,
257                        initial_pages: mem.initial as u32,
258                        max_pages: mem.maximum.map(|m| m as u32),
259                        shared: mem.shared,
260                    });
261                }
262            }
263            Payload::GlobalSection(reader) => {
264                // #237: capture each defined global's i32 initializer + mutability.
265                // The init is a const expr; we only decode a leading `i32.const`
266                // (the shape `$__stack_pointer`/data-layout globals use). Anything
267                // else (global.get, f32/f64, etc.) records `init_i32: None` and is
268                // left to the table-relative path.
269                for (idx, global) in reader.into_iter().enumerate() {
270                    let global = global.context("Failed to parse global")?;
271                    let mut init_i32 = None;
272                    let mut ops = global.init_expr.get_operators_reader();
273                    if let Ok(wasmparser::Operator::I32Const { value }) = ops.read() {
274                        init_i32 = Some(value);
275                    }
276                    globals.push(WasmGlobal {
277                        index: idx as u32,
278                        init_i32,
279                        mutable: global.ty.mutable,
280                    });
281                }
282            }
283            Payload::DataSection(reader) => {
284                for data in reader {
285                    let data = data.context("Failed to parse data segment")?;
286                    if let wasmparser::DataKind::Active {
287                        memory_index: 0,
288                        offset_expr,
289                    } = data.kind
290                    {
291                        let mut ops = offset_expr.get_operators_reader();
292                        if let Ok(wasmparser::Operator::I32Const { value }) = ops.read() {
293                            data_segments.push((value as u32, data.data.to_vec()));
294                        }
295                    }
296                }
297            }
298            Payload::ElementSection(reader) => {
299                // #275: collect every function index that initializes a table.
300                // These are the `call_indirect` targets the direct-call closure
301                // cannot see; `reachable_from_exports` unions them in when a
302                // reachable function does a `call_indirect`. Both element forms
303                // are handled: a flat function-index list, and the const-expr
304                // form whose `ref.func` entries name the functions.
305                for elem in reader {
306                    let elem = elem.context("Failed to parse element segment")?;
307                    match elem.items {
308                        wasmparser::ElementItems::Functions(funcs) => {
309                            for f in funcs {
310                                elem_func_indices
311                                    .push(f.context("Failed to parse element func index")?);
312                            }
313                        }
314                        wasmparser::ElementItems::Expressions(_, exprs) => {
315                            for expr in exprs {
316                                let expr = expr.context("Failed to parse element expr")?;
317                                for op in expr.get_operators_reader() {
318                                    if let wasmparser::Operator::RefFunc { function_index } =
319                                        op.context("Failed to parse element op")?
320                                    {
321                                        elem_func_indices.push(function_index);
322                                    }
323                                }
324                            }
325                        }
326                    }
327                }
328            }
329            Payload::ExportSection(exports) => {
330                for export in exports {
331                    let export = export.context("Failed to parse export")?;
332                    if export.kind == ExternalKind::Func {
333                        export_names.insert(export.index, export.name.to_string());
334                    }
335                }
336            }
337            Payload::CodeSectionEntry(body) => {
338                let (ops, unsupported) = decode_function_body(&body)?;
339                let actual_index = num_imported_funcs + func_index;
340                let export_name = export_names.get(&actual_index).cloned();
341
342                functions.push(FunctionOps {
343                    index: actual_index,
344                    export_name,
345                    ops,
346                    unsupported,
347                });
348                func_index += 1;
349            }
350            _ => {}
351        }
352    }
353
354    Ok(DecodedModule {
355        functions,
356        memories,
357        data_segments,
358        imports,
359        num_imported_funcs,
360        func_arg_counts,
361        type_arg_counts,
362        func_ret_i64,
363        type_ret_i64,
364        func_params_i64,
365        globals,
366        elem_func_indices,
367    })
368}
369
370/// Decode a WASM binary and extract all function bodies as WasmOp sequences
371pub fn decode_wasm_functions(wasm_bytes: &[u8]) -> Result<Vec<FunctionOps>> {
372    let mut functions = Vec::new();
373    let mut func_index = 0u32;
374    let mut num_imported_funcs = 0u32;
375    let mut export_names: HashMap<u32, String> = HashMap::new();
376
377    for payload in Parser::new(0).parse_all(wasm_bytes) {
378        let payload = payload.context("Failed to parse WASM payload")?;
379
380        match payload {
381            Payload::ImportSection(imports) => {
382                // wasmparser 0.221+ compact-imports grouping — flatten groups
383                // to individual imports (see the ImportSection handler above).
384                for import in imports.into_imports() {
385                    let import = import.context("Failed to parse import")?;
386                    if matches!(import.ty, wasmparser::TypeRef::Func(_)) {
387                        num_imported_funcs += 1;
388                    }
389                }
390            }
391            Payload::ExportSection(exports) => {
392                for export in exports {
393                    let export = export.context("Failed to parse export")?;
394                    if export.kind == ExternalKind::Func {
395                        export_names.insert(export.index, export.name.to_string());
396                    }
397                }
398            }
399            Payload::CodeSectionEntry(body) => {
400                let (ops, unsupported) = decode_function_body(&body)?;
401                let actual_index = num_imported_funcs + func_index;
402                let export_name = export_names.get(&actual_index).cloned();
403
404                functions.push(FunctionOps {
405                    index: actual_index,
406                    export_name,
407                    ops,
408                    unsupported,
409                });
410                func_index += 1;
411            }
412            _ => {}
413        }
414    }
415
416    Ok(functions)
417}
418
419/// Decoded function with its WasmOp sequence
420#[derive(Debug, Clone)]
421pub struct FunctionOps {
422    /// Function index in the module (includes imported functions)
423    pub index: u32,
424    /// Export name if this function is exported
425    pub export_name: Option<String>,
426    /// The WASM operations in this function body
427    pub ops: Vec<WasmOp>,
428    /// `Some(reason)` when the body contained a value-affecting operator the
429    /// decoder cannot lower (e.g. scalar f32/f64 — #369, bulk-memory
430    /// memory.copy/fill). Such an op would otherwise be silently *dropped*
431    /// (`convert_operator` → `None`), leaving the operand stack wrong and the
432    /// function a silent miscompile. The compile path LOUD-SKIPS a flagged
433    /// function (diagnostic + symbol absent → link error names it) instead —
434    /// the #180/#185 "unsupported op must Err, never silently continue"
435    /// contract. `None` once every op decoded or was intentionally ignorable
436    /// (Nop/Unreachable).
437    pub unsupported: Option<String>,
438}
439
440/// Decode a single function body to WasmOp sequence.
441///
442/// Returns the ops plus `Some(reason)` if any operator was a value-affecting
443/// op the decoder cannot lower (so the function must be loud-skipped, #369 —
444/// not silently miscompiled by dropping the op).
445fn decode_function_body(body: &wasmparser::FunctionBody) -> Result<(Vec<WasmOp>, Option<String>)> {
446    let mut ops = Vec::new();
447    let mut unsupported: Option<String> = None;
448
449    let ops_reader = body.get_operators_reader()?;
450    for op_result in ops_reader {
451        let op = op_result.context("Failed to read operator")?;
452
453        if let Some(wasm_op) = convert_operator(&op) {
454            ops.push(wasm_op);
455        } else if unsupported.is_none() && !is_intentionally_ignored(&op) {
456            // The op was DROPPED by `convert_operator` (`_ => None`) and is not
457            // an intentional no-op (Nop/Unreachable) — record it so the
458            // function is loud-skipped rather than silently miscompiled (#369).
459            unsupported = Some(format!("{op:?}"));
460        }
461    }
462
463    Ok((ops, unsupported))
464}
465
466/// Operators that `convert_operator` returns `None` for *on purpose* — they
467/// carry no value-affecting semantics for our backend, so dropping them is
468/// correct (NOT a silent miscompile). Everything else that decodes to `None`
469/// is an unsupported op that must loud-skip its function (#369).
470fn is_intentionally_ignored(op: &wasmparser::Operator) -> bool {
471    use wasmparser::Operator::*;
472    matches!(op, Nop | Unreachable)
473}
474
475/// Convert a wasmparser Operator to our WasmOp enum
476fn convert_operator(op: &wasmparser::Operator) -> Option<WasmOp> {
477    use wasmparser::Operator::*;
478
479    match op {
480        // Constants
481        I32Const { value } => Some(WasmOp::I32Const(*value)),
482
483        // i32 Arithmetic
484        I32Add => Some(WasmOp::I32Add),
485        I32Sub => Some(WasmOp::I32Sub),
486        I32Mul => Some(WasmOp::I32Mul),
487        I32DivS => Some(WasmOp::I32DivS),
488        I32DivU => Some(WasmOp::I32DivU),
489        I32RemS => Some(WasmOp::I32RemS),
490        I32RemU => Some(WasmOp::I32RemU),
491
492        // i64 Constants
493        I64Const { value } => Some(WasmOp::I64Const(*value)),
494
495        // i64 Arithmetic
496        I64Add => Some(WasmOp::I64Add),
497        I64Sub => Some(WasmOp::I64Sub),
498        I64Mul => Some(WasmOp::I64Mul),
499        I64DivS => Some(WasmOp::I64DivS),
500        I64DivU => Some(WasmOp::I64DivU),
501        I64RemS => Some(WasmOp::I64RemS),
502        I64RemU => Some(WasmOp::I64RemU),
503
504        // i64 Bitwise
505        I64And => Some(WasmOp::I64And),
506        I64Or => Some(WasmOp::I64Or),
507        I64Xor => Some(WasmOp::I64Xor),
508        I64Shl => Some(WasmOp::I64Shl),
509        I64ShrS => Some(WasmOp::I64ShrS),
510        I64ShrU => Some(WasmOp::I64ShrU),
511        I64Rotl => Some(WasmOp::I64Rotl),
512        I64Rotr => Some(WasmOp::I64Rotr),
513        I64Clz => Some(WasmOp::I64Clz),
514        I64Ctz => Some(WasmOp::I64Ctz),
515        I64Popcnt => Some(WasmOp::I64Popcnt),
516        I64Extend8S => Some(WasmOp::I64Extend8S),
517        I64Extend16S => Some(WasmOp::I64Extend16S),
518        I64Extend32S => Some(WasmOp::I64Extend32S),
519        // i32<->i64 width conversions. Previously UNMAPPED → silently dropped,
520        // which left an i32 value as a 64-bit operand with a garbage high half
521        // (harmless when a following `i64.shl 32` discards it, but a latent
522        // miscompile for extend-then-arithmetic, and it breaks width-correct
523        // register allocation). (#204)
524        I64ExtendI32U => Some(WasmOp::I64ExtendI32U),
525        I64ExtendI32S => Some(WasmOp::I64ExtendI32S),
526        I32WrapI64 => Some(WasmOp::I32WrapI64),
527
528        // i64 Comparison
529        I64Eqz => Some(WasmOp::I64Eqz),
530        I64Eq => Some(WasmOp::I64Eq),
531        I64Ne => Some(WasmOp::I64Ne),
532        I64LtS => Some(WasmOp::I64LtS),
533        I64LtU => Some(WasmOp::I64LtU),
534        I64LeS => Some(WasmOp::I64LeS),
535        I64LeU => Some(WasmOp::I64LeU),
536        I64GtS => Some(WasmOp::I64GtS),
537        I64GtU => Some(WasmOp::I64GtU),
538        I64GeS => Some(WasmOp::I64GeS),
539        I64GeU => Some(WasmOp::I64GeU),
540
541        // Bitwise
542        I32And => Some(WasmOp::I32And),
543        I32Or => Some(WasmOp::I32Or),
544        I32Xor => Some(WasmOp::I32Xor),
545        I32Shl => Some(WasmOp::I32Shl),
546        I32ShrS => Some(WasmOp::I32ShrS),
547        I32ShrU => Some(WasmOp::I32ShrU),
548        I32Rotl => Some(WasmOp::I32Rotl),
549        I32Rotr => Some(WasmOp::I32Rotr),
550        I32Clz => Some(WasmOp::I32Clz),
551        I32Ctz => Some(WasmOp::I32Ctz),
552        I32Popcnt => Some(WasmOp::I32Popcnt),
553        I32Extend8S => Some(WasmOp::I32Extend8S),
554        I32Extend16S => Some(WasmOp::I32Extend16S),
555
556        // Comparison
557        I32Eqz => Some(WasmOp::I32Eqz),
558        I32Eq => Some(WasmOp::I32Eq),
559        I32Ne => Some(WasmOp::I32Ne),
560        I32LtS => Some(WasmOp::I32LtS),
561        I32LtU => Some(WasmOp::I32LtU),
562        I32LeS => Some(WasmOp::I32LeS),
563        I32LeU => Some(WasmOp::I32LeU),
564        I32GtS => Some(WasmOp::I32GtS),
565        I32GtU => Some(WasmOp::I32GtU),
566        I32GeS => Some(WasmOp::I32GeS),
567        I32GeU => Some(WasmOp::I32GeU),
568
569        // Memory
570        I32Load { memarg } => Some(WasmOp::I32Load {
571            offset: memarg.offset as u32,
572            align: memarg.align as u32,
573        }),
574        I32Store { memarg } => Some(WasmOp::I32Store {
575            offset: memarg.offset as u32,
576            align: memarg.align as u32,
577        }),
578
579        // Sub-word loads (i32)
580        I32Load8S { memarg } => Some(WasmOp::I32Load8S {
581            offset: memarg.offset as u32,
582            align: memarg.align as u32,
583        }),
584        I32Load8U { memarg } => Some(WasmOp::I32Load8U {
585            offset: memarg.offset as u32,
586            align: memarg.align as u32,
587        }),
588        I32Load16S { memarg } => Some(WasmOp::I32Load16S {
589            offset: memarg.offset as u32,
590            align: memarg.align as u32,
591        }),
592        I32Load16U { memarg } => Some(WasmOp::I32Load16U {
593            offset: memarg.offset as u32,
594            align: memarg.align as u32,
595        }),
596
597        // Sub-word stores (i32)
598        I32Store8 { memarg } => Some(WasmOp::I32Store8 {
599            offset: memarg.offset as u32,
600            align: memarg.align as u32,
601        }),
602        I32Store16 { memarg } => Some(WasmOp::I32Store16 {
603            offset: memarg.offset as u32,
604            align: memarg.align as u32,
605        }),
606
607        // Local/Global
608        LocalGet { local_index } => Some(WasmOp::LocalGet(*local_index)),
609        LocalSet { local_index } => Some(WasmOp::LocalSet(*local_index)),
610        LocalTee { local_index } => Some(WasmOp::LocalTee(*local_index)),
611        GlobalGet { global_index } => Some(WasmOp::GlobalGet(*global_index)),
612        GlobalSet { global_index } => Some(WasmOp::GlobalSet(*global_index)),
613
614        // Control flow
615        Block { .. } => Some(WasmOp::Block),
616        Loop { .. } => Some(WasmOp::Loop),
617        Br { relative_depth } => Some(WasmOp::Br(*relative_depth)),
618        BrIf { relative_depth } => Some(WasmOp::BrIf(*relative_depth)),
619        // br_table: indexed multi-way branch. Previously UNMAPPED → silently
620        // dropped, so the selector never emitted the index dispatch and control
621        // fell straight into the first table arm — every br_table behaved as if
622        // it always took target 0 (gale's binary-sem WAKE path never fired). The
623        // jump-table relative depths + default depth are preserved in order.
624        BrTable { targets } => {
625            let default = targets.default();
626            let tgts: Vec<u32> = targets.targets().filter_map(Result::ok).collect();
627            Some(WasmOp::BrTable {
628                targets: tgts,
629                default,
630            })
631        }
632        Return => Some(WasmOp::Return),
633        Call { function_index } => Some(WasmOp::Call(*function_index)),
634        CallIndirect {
635            type_index,
636            table_index,
637            ..
638        } => Some(WasmOp::CallIndirect {
639            type_index: *type_index,
640            table_index: *table_index,
641        }),
642
643        // End is needed for control flow pattern matching
644        End => Some(WasmOp::End),
645
646        // Nop/Unreachable - skip these
647        Nop | Unreachable => None,
648
649        // Drop is needed for br_if pattern matching
650        Drop => Some(WasmOp::Drop),
651
652        // Select
653        Select => Some(WasmOp::Select),
654
655        // If/Else - simplified handling
656        If { .. } => Some(WasmOp::If),
657        Else => Some(WasmOp::Else),
658
659        // i64 sub-word loads
660        I64Load8S { memarg } => Some(WasmOp::I64Load8S {
661            offset: memarg.offset as u32,
662            align: memarg.align as u32,
663        }),
664        I64Load8U { memarg } => Some(WasmOp::I64Load8U {
665            offset: memarg.offset as u32,
666            align: memarg.align as u32,
667        }),
668        I64Load16S { memarg } => Some(WasmOp::I64Load16S {
669            offset: memarg.offset as u32,
670            align: memarg.align as u32,
671        }),
672        I64Load16U { memarg } => Some(WasmOp::I64Load16U {
673            offset: memarg.offset as u32,
674            align: memarg.align as u32,
675        }),
676        I64Load32S { memarg } => Some(WasmOp::I64Load32S {
677            offset: memarg.offset as u32,
678            align: memarg.align as u32,
679        }),
680        I64Load32U { memarg } => Some(WasmOp::I64Load32U {
681            offset: memarg.offset as u32,
682            align: memarg.align as u32,
683        }),
684
685        // i64 sub-word stores
686        I64Store8 { memarg } => Some(WasmOp::I64Store8 {
687            offset: memarg.offset as u32,
688            align: memarg.align as u32,
689        }),
690        I64Store16 { memarg } => Some(WasmOp::I64Store16 {
691            offset: memarg.offset as u32,
692            align: memarg.align as u32,
693        }),
694        I64Store32 { memarg } => Some(WasmOp::I64Store32 {
695            offset: memarg.offset as u32,
696            align: memarg.align as u32,
697        }),
698
699        // Memory management
700        MemorySize { mem, .. } => Some(WasmOp::MemorySize(*mem)),
701        MemoryGrow { mem, .. } => Some(WasmOp::MemoryGrow(*mem)),
702
703        // ========================================================================
704        // v128 SIMD operations (WASM SIMD proposal, 0xFD prefix)
705        // ========================================================================
706        V128Const { value } => {
707            let mut bytes = [0u8; 16];
708            bytes.copy_from_slice(value.bytes());
709            Some(WasmOp::V128Const(bytes))
710        }
711        V128Load { memarg } => Some(WasmOp::V128Load {
712            offset: memarg.offset as u32,
713            align: memarg.align as u32,
714        }),
715        V128Store { memarg } => Some(WasmOp::V128Store {
716            offset: memarg.offset as u32,
717            align: memarg.align as u32,
718        }),
719
720        // v128 bitwise
721        V128And => Some(WasmOp::V128And),
722        V128Or => Some(WasmOp::V128Or),
723        V128Xor => Some(WasmOp::V128Xor),
724        V128Not => Some(WasmOp::V128Not),
725        V128AndNot => Some(WasmOp::V128AndNot),
726
727        // i8x16
728        I8x16Add => Some(WasmOp::I8x16Add),
729        I8x16Sub => Some(WasmOp::I8x16Sub),
730        I8x16Neg => Some(WasmOp::I8x16Neg),
731        I8x16Eq => Some(WasmOp::I8x16Eq),
732        I8x16Ne => Some(WasmOp::I8x16Ne),
733        I8x16LtS => Some(WasmOp::I8x16LtS),
734        I8x16LtU => Some(WasmOp::I8x16LtU),
735        I8x16GtS => Some(WasmOp::I8x16GtS),
736        I8x16GtU => Some(WasmOp::I8x16GtU),
737        I8x16LeS => Some(WasmOp::I8x16LeS),
738        I8x16LeU => Some(WasmOp::I8x16LeU),
739        I8x16GeS => Some(WasmOp::I8x16GeS),
740        I8x16GeU => Some(WasmOp::I8x16GeU),
741        I8x16Splat => Some(WasmOp::I8x16Splat),
742        I8x16ExtractLaneS { lane } => Some(WasmOp::I8x16ExtractLaneS(*lane)),
743        I8x16ExtractLaneU { lane } => Some(WasmOp::I8x16ExtractLaneU(*lane)),
744        I8x16ReplaceLane { lane } => Some(WasmOp::I8x16ReplaceLane(*lane)),
745        I8x16Shuffle { lanes } => Some(WasmOp::I8x16Shuffle(*lanes)),
746        I8x16Swizzle => Some(WasmOp::I8x16Swizzle),
747
748        // i16x8
749        I16x8Add => Some(WasmOp::I16x8Add),
750        I16x8Sub => Some(WasmOp::I16x8Sub),
751        I16x8Mul => Some(WasmOp::I16x8Mul),
752        I16x8Neg => Some(WasmOp::I16x8Neg),
753        I16x8Eq => Some(WasmOp::I16x8Eq),
754        I16x8Ne => Some(WasmOp::I16x8Ne),
755        I16x8LtS => Some(WasmOp::I16x8LtS),
756        I16x8LtU => Some(WasmOp::I16x8LtU),
757        I16x8GtS => Some(WasmOp::I16x8GtS),
758        I16x8GtU => Some(WasmOp::I16x8GtU),
759        I16x8LeS => Some(WasmOp::I16x8LeS),
760        I16x8LeU => Some(WasmOp::I16x8LeU),
761        I16x8GeS => Some(WasmOp::I16x8GeS),
762        I16x8GeU => Some(WasmOp::I16x8GeU),
763        I16x8Splat => Some(WasmOp::I16x8Splat),
764        I16x8ExtractLaneS { lane } => Some(WasmOp::I16x8ExtractLaneS(*lane)),
765        I16x8ExtractLaneU { lane } => Some(WasmOp::I16x8ExtractLaneU(*lane)),
766        I16x8ReplaceLane { lane } => Some(WasmOp::I16x8ReplaceLane(*lane)),
767
768        // i32x4
769        I32x4Add => Some(WasmOp::I32x4Add),
770        I32x4Sub => Some(WasmOp::I32x4Sub),
771        I32x4Mul => Some(WasmOp::I32x4Mul),
772        I32x4Neg => Some(WasmOp::I32x4Neg),
773        I32x4Eq => Some(WasmOp::I32x4Eq),
774        I32x4Ne => Some(WasmOp::I32x4Ne),
775        I32x4LtS => Some(WasmOp::I32x4LtS),
776        I32x4LtU => Some(WasmOp::I32x4LtU),
777        I32x4GtS => Some(WasmOp::I32x4GtS),
778        I32x4GtU => Some(WasmOp::I32x4GtU),
779        I32x4LeS => Some(WasmOp::I32x4LeS),
780        I32x4LeU => Some(WasmOp::I32x4LeU),
781        I32x4GeS => Some(WasmOp::I32x4GeS),
782        I32x4GeU => Some(WasmOp::I32x4GeU),
783        I32x4Splat => Some(WasmOp::I32x4Splat),
784        I32x4ExtractLane { lane } => Some(WasmOp::I32x4ExtractLane(*lane)),
785        I32x4ReplaceLane { lane } => Some(WasmOp::I32x4ReplaceLane(*lane)),
786
787        // i64x2
788        I64x2Add => Some(WasmOp::I64x2Add),
789        I64x2Sub => Some(WasmOp::I64x2Sub),
790        I64x2Mul => Some(WasmOp::I64x2Mul),
791        I64x2Neg => Some(WasmOp::I64x2Neg),
792        I64x2Eq => Some(WasmOp::I64x2Eq),
793        I64x2Ne => Some(WasmOp::I64x2Ne),
794        I64x2LtS => Some(WasmOp::I64x2LtS),
795        I64x2GtS => Some(WasmOp::I64x2GtS),
796        I64x2LeS => Some(WasmOp::I64x2LeS),
797        I64x2GeS => Some(WasmOp::I64x2GeS),
798        I64x2Splat => Some(WasmOp::I64x2Splat),
799        I64x2ExtractLane { lane } => Some(WasmOp::I64x2ExtractLane(*lane)),
800        I64x2ReplaceLane { lane } => Some(WasmOp::I64x2ReplaceLane(*lane)),
801
802        // f32x4
803        F32x4Add => Some(WasmOp::F32x4Add),
804        F32x4Sub => Some(WasmOp::F32x4Sub),
805        F32x4Mul => Some(WasmOp::F32x4Mul),
806        F32x4Div => Some(WasmOp::F32x4Div),
807        F32x4Abs => Some(WasmOp::F32x4Abs),
808        F32x4Neg => Some(WasmOp::F32x4Neg),
809        F32x4Sqrt => Some(WasmOp::F32x4Sqrt),
810        F32x4Eq => Some(WasmOp::F32x4Eq),
811        F32x4Ne => Some(WasmOp::F32x4Ne),
812        F32x4Lt => Some(WasmOp::F32x4Lt),
813        F32x4Le => Some(WasmOp::F32x4Le),
814        F32x4Gt => Some(WasmOp::F32x4Gt),
815        F32x4Ge => Some(WasmOp::F32x4Ge),
816        F32x4Splat => Some(WasmOp::F32x4Splat),
817        F32x4ExtractLane { lane } => Some(WasmOp::F32x4ExtractLane(*lane)),
818        F32x4ReplaceLane { lane } => Some(WasmOp::F32x4ReplaceLane(*lane)),
819
820        // Other operators not yet supported
821        _ => None,
822    }
823}
824
825#[cfg(test)]
826mod tests {
827    use super::*;
828
829    #[test]
830    fn test_decode_simple_add() {
831        let wat = r#"
832            (module
833                (func (export "add") (param i32 i32) (result i32)
834                    local.get 0
835                    local.get 1
836                    i32.add
837                )
838            )
839        "#;
840
841        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
842        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
843
844        assert_eq!(functions.len(), 1);
845        assert_eq!(functions[0].index, 0);
846        assert_eq!(functions[0].export_name, Some("add".to_string()));
847        assert_eq!(
848            functions[0].ops,
849            vec![
850                WasmOp::LocalGet(0),
851                WasmOp::LocalGet(1),
852                WasmOp::I32Add,
853                WasmOp::End
854            ]
855        );
856    }
857
858    /// #204 regression: `i64.extend_i32_u`, `i64.extend_i32_s` and
859    /// `i32.wrap_i64` must DECODE (they were previously unmapped → silently
860    /// dropped by `convert_operator`, leaving an i32 value as a 64-bit operand
861    /// with a garbage high half — the root cause of gale's miscompiled
862    /// `(new_count << 32)` pack). The decoder must surface all three.
863    #[test]
864    fn test_decode_i64_i32_width_conversions() {
865        let wat = r#"
866            (module
867                (func (export "conv") (param i32 i64) (result i32)
868                    local.get 0
869                    i64.extend_i32_u
870                    local.get 0
871                    i64.extend_i32_s
872                    i64.add
873                    local.get 1
874                    i64.add
875                    i32.wrap_i64
876                )
877            )
878        "#;
879        let wasm = wat::parse_str(wat).expect("parse");
880        let functions = decode_wasm_functions(&wasm).expect("decode");
881        let ops = &functions[0].ops;
882        assert!(
883            ops.contains(&WasmOp::I64ExtendI32U),
884            "i64.extend_i32_u must decode (not be dropped): {ops:?}"
885        );
886        assert!(
887            ops.contains(&WasmOp::I64ExtendI32S),
888            "i64.extend_i32_s must decode (not be dropped): {ops:?}"
889        );
890        assert!(
891            ops.contains(&WasmOp::I32WrapI64),
892            "i32.wrap_i64 must decode (not be dropped): {ops:?}"
893        );
894    }
895
896    /// #204 WAKE-path regression: `br_table` must DECODE (it was unmapped in
897    /// `convert_operator` → silently dropped, so the selector emitted no index
898    /// dispatch and every `br_table` fell through to target 0 — gale's binary
899    /// semaphore never took its WAKE branch). Targets + default are preserved.
900    #[test]
901    fn test_decode_br_table() {
902        let wat = r#"
903            (module
904                (func (export "bt") (param i32) (result i32)
905                    (block (block (block
906                        local.get 0
907                        br_table 2 0 1 2)
908                      i32.const 30 return)
909                      i32.const 20 return)
910                    i32.const 10))
911        "#;
912        let wasm = wat::parse_str(wat).expect("parse");
913        let functions = decode_wasm_functions(&wasm).expect("decode");
914        let bt = functions[0]
915            .ops
916            .iter()
917            .find_map(|o| match o {
918                WasmOp::BrTable { targets, default } => Some((targets.clone(), *default)),
919                _ => None,
920            })
921            .expect("br_table must decode (not be dropped)");
922        assert_eq!(bt.0, vec![2, 0, 1], "br_table targets preserved in order");
923        assert_eq!(bt.1, 2, "br_table default preserved");
924    }
925
926    #[test]
927    fn test_decode_arithmetic() {
928        let wat = r#"
929            (module
930                (func (export "calc") (result i32)
931                    i32.const 5
932                    i32.const 3
933                    i32.mul
934                    i32.const 2
935                    i32.add
936                )
937            )
938        "#;
939
940        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
941        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
942
943        assert_eq!(functions.len(), 1);
944        assert_eq!(functions[0].export_name, Some("calc".to_string()));
945        assert_eq!(
946            functions[0].ops,
947            vec![
948                WasmOp::I32Const(5),
949                WasmOp::I32Const(3),
950                WasmOp::I32Mul,
951                WasmOp::I32Const(2),
952                WasmOp::I32Add,
953                WasmOp::End,
954            ]
955        );
956    }
957
958    #[test]
959    fn test_decode_multi_function_module() {
960        let wat = r#"
961            (module
962                (func $helper)
963                (func (export "add") (param i32 i32) (result i32)
964                    local.get 0
965                    local.get 1
966                    i32.add
967                )
968                (func (export "sub") (param i32 i32) (result i32)
969                    local.get 0
970                    local.get 1
971                    i32.sub
972                )
973            )
974        "#;
975
976        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
977        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
978
979        assert_eq!(functions.len(), 3);
980        assert_eq!(functions[0].index, 0);
981        assert_eq!(functions[0].export_name, None);
982        assert_eq!(functions[1].index, 1);
983        assert_eq!(functions[1].export_name, Some("add".to_string()));
984        assert_eq!(functions[2].index, 2);
985        assert_eq!(functions[2].export_name, Some("sub".to_string()));
986    }
987
988    #[test]
989    fn test_decode_module_with_imports() {
990        let wat = r#"
991            (module
992                (import "env" "log" (func $log (param i32)))
993                (import "env" "memory" (memory 1))
994                (func (export "run") (param i32)
995                    local.get 0
996                    call 0
997                )
998            )
999        "#;
1000
1001        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1002        let module = decode_wasm_module(&wasm).expect("Failed to decode");
1003
1004        // Should have 2 imports (1 func, 1 memory)
1005        assert_eq!(module.imports.len(), 2);
1006        assert_eq!(module.num_imported_funcs, 1);
1007
1008        // First import is the function
1009        assert_eq!(module.imports[0].module, "env");
1010        assert_eq!(module.imports[0].name, "log");
1011        assert!(matches!(module.imports[0].kind, ImportKind::Function(_)));
1012
1013        // Second import is memory
1014        assert_eq!(module.imports[1].module, "env");
1015        assert_eq!(module.imports[1].name, "memory");
1016        assert_eq!(module.imports[1].kind, ImportKind::Memory);
1017
1018        // Should have 1 local function (index 1, because import is index 0)
1019        assert_eq!(module.functions.len(), 1);
1020        assert_eq!(module.functions[0].index, 1);
1021        assert_eq!(module.functions[0].export_name, Some("run".to_string()));
1022    }
1023
1024    #[test]
1025    fn test_find_function_by_export_name() {
1026        let wat = r#"
1027            (module
1028                (func $helper)
1029                (func (export "add") (param i32 i32) (result i32)
1030                    local.get 0
1031                    local.get 1
1032                    i32.add
1033                )
1034            )
1035        "#;
1036
1037        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1038        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1039
1040        let add_func = functions
1041            .iter()
1042            .find(|f| f.export_name.as_deref() == Some("add"))
1043            .expect("Should find 'add' function");
1044
1045        assert_eq!(add_func.index, 1);
1046        assert!(add_func.ops.contains(&WasmOp::I32Add));
1047    }
1048
1049    #[test]
1050    fn test_decode_subword_loads() {
1051        let wat = r#"
1052            (module
1053                (memory 1)
1054                (func (export "test") (param i32) (result i32)
1055                    local.get 0
1056                    i32.load8_u
1057                )
1058            )
1059        "#;
1060
1061        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1062        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1063
1064        assert_eq!(functions.len(), 1);
1065        assert!(functions[0].ops.contains(&WasmOp::I32Load8U {
1066            offset: 0,
1067            align: 0,
1068        }));
1069    }
1070
1071    #[test]
1072    fn test_decode_subword_stores() {
1073        let wat = r#"
1074            (module
1075                (memory 1)
1076                (func (export "test") (param i32 i32)
1077                    local.get 0
1078                    local.get 1
1079                    i32.store8
1080                )
1081            )
1082        "#;
1083
1084        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1085        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1086
1087        assert_eq!(functions.len(), 1);
1088        assert!(functions[0].ops.contains(&WasmOp::I32Store8 {
1089            offset: 0,
1090            align: 0,
1091        }));
1092    }
1093
1094    #[test]
1095    fn test_decode_memory_size_grow() {
1096        let wat = r#"
1097            (module
1098                (memory 1)
1099                (func (export "test") (result i32)
1100                    memory.size
1101                )
1102            )
1103        "#;
1104
1105        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1106        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1107
1108        assert_eq!(functions.len(), 1);
1109        assert!(functions[0].ops.contains(&WasmOp::MemorySize(0)));
1110    }
1111
1112    #[test]
1113    fn test_decode_memory_grow() {
1114        let wat = r#"
1115            (module
1116                (memory 1)
1117                (func (export "test") (param i32) (result i32)
1118                    local.get 0
1119                    memory.grow
1120                )
1121            )
1122        "#;
1123
1124        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1125        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1126
1127        assert_eq!(functions.len(), 1);
1128        assert!(functions[0].ops.contains(&WasmOp::MemoryGrow(0)));
1129    }
1130
1131    #[test]
1132    fn test_decode_i64_subword_loads() {
1133        let wat = r#"
1134            (module
1135                (memory 1)
1136                (func (export "test") (param i32) (result i64)
1137                    local.get 0
1138                    i64.load8_s
1139                )
1140            )
1141        "#;
1142
1143        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1144        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1145
1146        assert_eq!(functions.len(), 1);
1147        assert!(functions[0].ops.contains(&WasmOp::I64Load8S {
1148            offset: 0,
1149            align: 0,
1150        }));
1151    }
1152
1153    #[test]
1154    fn test_decode_all_subword_memory_ops() {
1155        // Test that all sub-word operations are decoded from WAT
1156        let wat = r#"
1157            (module
1158                (memory 1)
1159                (func (export "test") (param i32)
1160                    ;; i32 sub-word loads
1161                    local.get 0
1162                    i32.load8_s
1163                    drop
1164                    local.get 0
1165                    i32.load8_u
1166                    drop
1167                    local.get 0
1168                    i32.load16_s
1169                    drop
1170                    local.get 0
1171                    i32.load16_u
1172                    drop
1173
1174                    ;; i32 sub-word stores
1175                    local.get 0
1176                    i32.const 42
1177                    i32.store8
1178                    local.get 0
1179                    i32.const 42
1180                    i32.store16
1181
1182                    ;; i64 sub-word loads
1183                    local.get 0
1184                    i64.load8_s
1185                    drop
1186                    local.get 0
1187                    i64.load8_u
1188                    drop
1189                    local.get 0
1190                    i64.load16_s
1191                    drop
1192                    local.get 0
1193                    i64.load16_u
1194                    drop
1195                    local.get 0
1196                    i64.load32_s
1197                    drop
1198                    local.get 0
1199                    i64.load32_u
1200                    drop
1201
1202                    ;; i64 sub-word stores
1203                    local.get 0
1204                    i64.const 42
1205                    i64.store8
1206                    local.get 0
1207                    i64.const 42
1208                    i64.store16
1209                    local.get 0
1210                    i64.const 42
1211                    i64.store32
1212                )
1213            )
1214        "#;
1215
1216        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1217        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1218
1219        assert_eq!(functions.len(), 1);
1220        let ops = &functions[0].ops;
1221
1222        // Verify i32 sub-word ops are present
1223        assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Load8S { .. })));
1224        assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Load8U { .. })));
1225        assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Load16S { .. })));
1226        assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Load16U { .. })));
1227        assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Store8 { .. })));
1228        assert!(ops.iter().any(|o| matches!(o, WasmOp::I32Store16 { .. })));
1229
1230        // Verify i64 sub-word ops are present
1231        assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load8S { .. })));
1232        assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load8U { .. })));
1233        assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load16S { .. })));
1234        assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load16U { .. })));
1235        assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load32S { .. })));
1236        assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Load32U { .. })));
1237        assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Store8 { .. })));
1238        assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Store16 { .. })));
1239        assert!(ops.iter().any(|o| matches!(o, WasmOp::I64Store32 { .. })));
1240    }
1241
1242    #[test]
1243    fn test_decode_simd_i32x4_add() {
1244        let wat = r#"
1245            (module
1246                (func (export "add_v128") (param v128 v128) (result v128)
1247                    local.get 0
1248                    local.get 1
1249                    i32x4.add
1250                )
1251            )
1252        "#;
1253
1254        let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1255        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1256
1257        assert_eq!(functions.len(), 1);
1258        assert!(
1259            functions[0].ops.contains(&WasmOp::I32x4Add),
1260            "Should decode i32x4.add: {:?}",
1261            functions[0].ops
1262        );
1263    }
1264
1265    #[test]
1266    fn test_decode_simd_v128_const() {
1267        let wat = r#"
1268            (module
1269                (func (export "const_v128") (result v128)
1270                    v128.const i32x4 1 2 3 4
1271                )
1272            )
1273        "#;
1274
1275        let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1276        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1277
1278        assert_eq!(functions.len(), 1);
1279        assert!(
1280            functions[0]
1281                .ops
1282                .iter()
1283                .any(|o| matches!(o, WasmOp::V128Const(_))),
1284            "Should decode v128.const: {:?}",
1285            functions[0].ops
1286        );
1287    }
1288
1289    #[test]
1290    fn test_decode_simd_v128_load_store() {
1291        let wat = r#"
1292            (module
1293                (memory 1)
1294                (func (export "load_store") (param i32)
1295                    local.get 0
1296                    v128.load
1297                    local.get 0
1298                    v128.store
1299                )
1300            )
1301        "#;
1302
1303        let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1304        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1305
1306        assert_eq!(functions.len(), 1);
1307        let ops = &functions[0].ops;
1308        assert!(
1309            ops.iter().any(|o| matches!(o, WasmOp::V128Load { .. })),
1310            "Should decode v128.load"
1311        );
1312        assert!(
1313            ops.iter().any(|o| matches!(o, WasmOp::V128Store { .. })),
1314            "Should decode v128.store"
1315        );
1316    }
1317
1318    #[test]
1319    fn test_decode_simd_bitwise_ops() {
1320        let wat = r#"
1321            (module
1322                (func (export "bitwise") (param v128 v128) (result v128)
1323                    local.get 0
1324                    local.get 1
1325                    v128.and
1326                )
1327            )
1328        "#;
1329
1330        let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1331        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1332
1333        assert_eq!(functions.len(), 1);
1334        assert!(functions[0].ops.contains(&WasmOp::V128And));
1335    }
1336
1337    #[test]
1338    fn test_decode_simd_splat() {
1339        let wat = r#"
1340            (module
1341                (func (export "splat") (param i32) (result v128)
1342                    local.get 0
1343                    i32x4.splat
1344                )
1345            )
1346        "#;
1347
1348        let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1349        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1350
1351        assert_eq!(functions.len(), 1);
1352        assert!(functions[0].ops.contains(&WasmOp::I32x4Splat));
1353    }
1354
1355    #[test]
1356    fn test_decode_simd_extract_lane() {
1357        let wat = r#"
1358            (module
1359                (func (export "extract") (param v128) (result i32)
1360                    local.get 0
1361                    i32x4.extract_lane 2
1362                )
1363            )
1364        "#;
1365
1366        let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1367        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1368
1369        assert_eq!(functions.len(), 1);
1370        assert!(
1371            functions[0].ops.contains(&WasmOp::I32x4ExtractLane(2)),
1372            "Should decode i32x4.extract_lane 2"
1373        );
1374    }
1375
1376    #[test]
1377    fn test_decode_simd_f32x4_arithmetic() {
1378        let wat = r#"
1379            (module
1380                (func (export "f32x4_add") (param v128 v128) (result v128)
1381                    local.get 0
1382                    local.get 1
1383                    f32x4.add
1384                )
1385            )
1386        "#;
1387
1388        let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1389        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1390
1391        assert_eq!(functions.len(), 1);
1392        assert!(functions[0].ops.contains(&WasmOp::F32x4Add));
1393    }
1394
1395    #[test]
1396    fn test_369_scalar_float_op_flags_function_unsupported_not_dropped() {
1397        // #369: a scalar f32/f64 op the decoder can't lower must FLAG the
1398        // function (-> loud skip), never be silently dropped (which left a
1399        // `mov r0,r1` wrong-value stub). A pure-integer function stays clean.
1400        let wat = r#"
1401            (module
1402                (func (export "fadd") (param f32 f32) (result f32)
1403                    local.get 0 local.get 1 f32.add)
1404                (func (export "iadd") (param i32 i32) (result i32)
1405                    local.get 0 local.get 1 i32.add))
1406        "#;
1407        let wasm = wat::parse_str(wat).expect("parse");
1408        let functions = decode_wasm_functions(&wasm).expect("decode");
1409        let fadd = functions
1410            .iter()
1411            .find(|f| f.export_name.as_deref() == Some("fadd"))
1412            .unwrap();
1413        let iadd = functions
1414            .iter()
1415            .find(|f| f.export_name.as_deref() == Some("iadd"))
1416            .unwrap();
1417        assert!(
1418            fadd.unsupported.is_some(),
1419            "f32.add must flag the function unsupported (loud-skip), got {:?}",
1420            fadd.unsupported
1421        );
1422        assert!(
1423            fadd.unsupported.as_deref().unwrap().contains("F32Add"),
1424            "diagnostic should name the op: {:?}",
1425            fadd.unsupported
1426        );
1427        assert!(
1428            iadd.unsupported.is_none(),
1429            "a pure-integer function must NOT be flagged: {:?}",
1430            iadd.unsupported
1431        );
1432    }
1433
1434    #[test]
1435    fn test_decode_simd_multiple_ops() {
1436        let wat = r#"
1437            (module
1438                (func (export "simd_ops") (param v128 v128 v128) (result v128)
1439                    ;; (a + b) * c
1440                    local.get 0
1441                    local.get 1
1442                    i32x4.add
1443                    local.get 2
1444                    i32x4.mul
1445                )
1446            )
1447        "#;
1448
1449        let wasm = wat::parse_str(wat).expect("Failed to parse WAT with SIMD");
1450        let functions = decode_wasm_functions(&wasm).expect("Failed to decode");
1451
1452        assert_eq!(functions.len(), 1);
1453        let ops = &functions[0].ops;
1454        assert!(ops.contains(&WasmOp::I32x4Add));
1455        assert!(ops.contains(&WasmOp::I32x4Mul));
1456    }
1457
1458    /// #237: the decoder captures a global's `i32.const` initializer + mutability,
1459    /// so the native-pointer ABI can recognize the stack-pointer global.
1460    #[test]
1461    fn test_decode_captures_global_initializer() {
1462        let wat = r#"
1463            (module
1464                (memory 2)
1465                (global $__stack_pointer (mut i32) (i32.const 65536))
1466                (global $immutable_const i32 (i32.const 7))
1467                (func (export "f") (result i32) global.get 0)
1468            )
1469        "#;
1470        let wasm = wat::parse_str(wat).expect("Failed to parse WAT");
1471        let module = decode_wasm_module(&wasm).expect("Failed to decode");
1472
1473        assert_eq!(module.globals.len(), 2, "both globals captured");
1474        let sp = &module.globals[0];
1475        assert_eq!(sp.index, 0);
1476        assert_eq!(sp.init_i32, Some(65536), "stack-pointer init captured");
1477        assert!(sp.mutable, "stack pointer is mutable");
1478        let c = &module.globals[1];
1479        assert_eq!(c.init_i32, Some(7));
1480        assert!(!c.mutable, "second global is immutable");
1481    }
1482}