Skip to main content

moonproof_runtime/ir/
vm_decode.rs

1//! Decode IR `vm-ops` JSON into ledger `Op<ResultModeGather, InMemoryDB>`.
2//!
3//! Each `vm-op` JSON object is one VM instruction the on-chain runtime
4//! consumes (`push`, `idx`, `addi`, `ins`, ...). The IR emitter
5//! pre-expands the recipe so consumers see concrete ops, but argument
6//! values can still reference runtime-evaluated expressions via
7//! `{"vm": "ref", "type": <descriptor>, "value": <expression>}`. The
8//! decoder resolves those refs against the current scope before
9//! constructing the typed `Op`.
10
11use std::borrow::Cow;
12use std::sync::Arc;
13
14use moonproof_ledger::base_crypto::fab::AlignedValue;
15use moonproof_ledger::onchain_runtime::ops::{Key, Op};
16use moonproof_ledger::onchain_runtime::result_mode::ResultModeGather;
17use moonproof_ledger::onchain_runtime::state::{AlignedValueChecked, StateValue};
18use moonproof_ledger::storage::arena::Sp;
19use moonproof_ledger::storage::db::InMemoryDB;
20use moonproof_ledger::storage::storage::Array as StorageArray;
21use moonproof_runtime_ir::ir::{MoonIr, VmInstr};
22use moonproof_runtime_ir::RuntimeValue as Value;
23use rustc_hash::FxHashMap;
24
25use super::descriptor::{
26    encode_bool, encode_bytes, encode_default, encode_field, encode_literal, encode_uint,
27    json_as_u128, FabPlan,
28};
29use super::error::{IrDriverError, Result};
30use super::vm_val::VmVal;
31
32/// Evaluation scope passed to the vm-op decoder so `vm: ref` refs can
33/// resolve to concrete values.
34pub struct EvalScope<'a> {
35    /// IR root — for descriptor lookups (used by future expansions
36    /// that resolve runtime-typed paths).
37    #[allow(dead_code)]
38    pub ir: &'a MoonIr,
39    /// Local variable bindings from `Statement::Const`.
40    pub locals: &'a FxHashMap<String, Value>,
41    /// Circuit arguments from the caller. Looked up by `resolve_expr`
42    /// when a `Var` reference matches an argument name.
43    pub args: &'a FxHashMap<String, Value>,
44}
45
46impl EvalScope<'_> {
47    /// Fast-path resolver for an expression stored as a `RuntimeValue`
48    /// inside a VM-op `{vm: "ref", value: ...}` slot. Handles the
49    /// overwhelming common case (`{"expr": "var", "name": "..."}`) with
50    /// zero allocations and zero `serde` deserialization, borrowing
51    /// directly from `args` / `locals`.
52    fn resolve_ref_value<'s>(&'s self, inner: &'s Value) -> Result<Cow<'s, Value>> {
53        if let Some(obj) = inner.as_object() {
54            match obj.get("expr").and_then(Value::as_str) {
55                Some("var") => {
56                    if let Some(name) = obj.get("name").and_then(Value::as_str) {
57                        return self.lookup_var(name);
58                    }
59                }
60                Some("literal") => {
61                    if let Some(v) = obj.get("value") {
62                        return Ok(Cow::Borrowed(v));
63                    }
64                }
65                _ => {}
66            }
67        }
68        let expr: moonproof_runtime_ir::ir::Expression = crate::ir::interp::decode_value_as(inner)
69            .map_err(|e| IrDriverError::InvalidIr(format!("ref.value not an Expression: {e}")))?;
70        self.resolve_expr(&expr).map(Cow::Owned)
71    }
72
73    #[inline]
74    fn lookup_var(&self, name: &str) -> Result<Cow<'_, Value>> {
75        if let Some(v) = self.args.get(name) {
76            return Ok(Cow::Borrowed(v));
77        }
78        self.locals
79            .get(name)
80            .map(Cow::Borrowed)
81            .ok_or_else(|| IrDriverError::UnboundVariable(name.to_owned()))
82    }
83    /// Resolve an expression IR node against the current scope to a
84    /// JSON value. Used by VM-op decoding to turn `{vm: ref, value:
85    /// <expr>}` runtime-typed values into JSON for re-encoding via
86    /// the descriptor. The scope here is read-only — only pure
87    /// expressions (`Var`, `Literal`, `EnumRef`, `Default`) are
88    /// supported. Side-effecting expressions (`Call`, `AdtOp`)
89    /// don't reach this decoder; they live in the `arguments` slot
90    /// of an `AdtOpInvocation`, where they're evaluated by the
91    /// interpreter before the vm-op is decoded.
92    pub fn resolve_expr(&self, expr: &moonproof_runtime_ir::ir::Expression) -> Result<Value> {
93        use moonproof_runtime_ir::ir::Expression as E;
94        use moonproof_runtime_ir::ir::TypeDescriptor as T;
95        match expr {
96            E::Var { name } => {
97                if let Some(v) = self.args.get(name) {
98                    return Ok(v.clone());
99                }
100                self.locals
101                    .get(name)
102                    .cloned()
103                    .ok_or_else(|| IrDriverError::UnboundVariable(name.clone()))
104            }
105            E::Literal { value } => Ok(value.clone()),
106            E::EnumRef { of_type, variant } => match of_type {
107                T::Enum { elements, name } => {
108                    if !elements.iter().any(|v| v == variant) {
109                        return Err(IrDriverError::TypeMismatch(format!(
110                            "enum {name} has no variant '{variant}' (variants: {elements:?})"
111                        )));
112                    }
113                    Ok(Value::String(variant.clone()))
114                }
115                other => Err(IrDriverError::TypeMismatch(format!(
116                    "enum-ref descriptor not an Enum: {other:?}"
117                ))),
118            },
119            // `(default type)` — returns the wire-format zero of the
120            // descriptor as JSON. We materialize it by encoding the
121            // default AlignedValue and decoding it back through the
122            // same descriptor, so the JSON shape matches what
123            // `encode_literal` would produce for an explicit zero.
124            // Used by stdlib helpers like `default<Bytes<32>>` and
125            // `default<Field>` (e.g. `tiny.compact`'s `clear` circuit
126            // that resets the authority field to its default).
127            E::Default { of_type } => {
128                let av = super::descriptor::encode_default(of_type)?;
129                super::descriptor::decode_aligned_value_full(of_type, &av)
130            }
131            // `emit(ShieldedSpend { nullifier: n })` lowers to vm-ops
132            // whose refs project fields out of the event value.
133            E::New { of_type, arguments } => {
134                let values = arguments
135                    .iter()
136                    .map(|a| self.resolve_expr(a))
137                    .collect::<Result<Vec<_>>>()?;
138                super::interp::construct(of_type, values)
139            }
140            E::EltRef { value, field, .. } => {
141                let v = self.resolve_expr(value)?;
142                v.as_object()
143                    .and_then(|obj| obj.get(field).cloned())
144                    .ok_or_else(|| {
145                        IrDriverError::TypeMismatch(format!("field '{field}' not in struct {v}"))
146                    })
147            }
148            other => Err(IrDriverError::unimplemented(format!(
149                "expression in vm-op ref position: {other:?}"
150            ))),
151        }
152    }
153}
154
155/// Decode one vm-instr into a typed `Op<ResultModeGather, InMemoryDB>`.
156pub fn decode_op(
157    instr: &VmInstr,
158    scope: &EvalScope<'_>,
159) -> Result<Op<ResultModeGather, InMemoryDB>> {
160    let op_name = instr
161        .op()
162        .ok_or_else(|| IrDriverError::InvalidIr("vm-op missing 'op' key".into()))?;
163    match op_name {
164        "push" => {
165            let storage = instr_field_bool(instr, "storage")?;
166            let value = instr_field(instr, "value")?;
167            let state_value = checked_state_value(&decode_state_value(value, scope)?)?;
168            Ok(Op::Push {
169                storage,
170                value: state_value,
171            })
172        }
173        "idx" => {
174            let cached = instr_field_bool(instr, "cached")?;
175            let push_path = instr_field_bool(instr, "pushPath")?;
176            let path = instr_field(instr, "path")?;
177            let path_keys = decode_path(path, scope)?;
178            Ok(Op::Idx {
179                cached,
180                push_path,
181                path: StorageArray::from(path_keys),
182            })
183        }
184        "ins" => {
185            let cached = instr_field_bool(instr, "cached")?;
186            let n = instr_int(instr, "ins", "n", scope)?;
187            Ok(Op::Ins { cached, n })
188        }
189        "addi" => Ok(Op::Addi {
190            immediate: instr_int(instr, "addi", "immediate", scope)?,
191        }),
192        "subi" => Ok(Op::Subi {
193            immediate: instr_int(instr, "subi", "immediate", scope)?,
194        }),
195        "popeq" => {
196            let cached = instr_field_bool(instr, "cached")?;
197            // The result-descriptor field tells consumers what type
198            // the popeq read produces; the `result` payload itself is
199            // computed from the gathered read at execution time.
200            // For ResultModeGather the result slot is `()`.
201            Ok(Op::Popeq { cached, result: () })
202        }
203        "noop" => {
204            let n_raw =
205                decode_int_arg(instr_field(instr, "n").unwrap_or(&Value::Null), scope).unwrap_or(0);
206            let n_u32 = u32::try_from(n_raw).unwrap_or(0);
207            Ok(Op::Noop { n: n_u32 })
208        }
209        "pop" => Ok(Op::Pop),
210        "lt" => Ok(Op::Lt),
211        "eq" => Ok(Op::Eq),
212        "neg" => Ok(Op::Neg),
213        "size" => Ok(Op::Size),
214        "member" => Ok(Op::Member),
215        "rem" => {
216            let cached = instr_field_bool(instr, "cached")?;
217            Ok(Op::Rem { cached })
218        }
219        "dup" => Ok(Op::Dup {
220            n: instr_int(instr, "dup", "n", scope)?,
221        }),
222        "swap" => Ok(Op::Swap {
223            n: instr_int(instr, "swap", "n", scope)?,
224        }),
225        "concat" => {
226            let cached = instr_field_bool(instr, "cached")?;
227            let n = instr_int(instr, "concat", "n", scope)?;
228            Ok(Op::Concat { cached, n })
229        }
230        "ckpt" => Ok(Op::Ckpt),
231        // Untyped numeric add (`Op::Add` at `onchain-vm/src/ops.rs:150`):
232        // pops two stack-tops and pushes their sum. Used by
233        // `mintShieldedToken`'s "increment existing entry in
234        // shielded_mints" path.
235        "add" => Ok(Op::Add),
236        "sub" => Ok(Op::Sub),
237        // `Op::Branch{skip}` — conditional skip when the top-of-stack
238        // is a `Cell(false)` value (`onchain-vm/src/ops.rs:136`). Used
239        // by mint's `if member` short-circuit, and any contract
240        // emitting an `if`-with-state inside a kernel call.
241        "branch" => Ok(Op::Branch {
242            skip: instr_int(instr, "branch", "skip", scope)?,
243        }),
244        "jmp" => Ok(Op::Jmp {
245            skip: instr_int(instr, "jmp", "skip", scope)?,
246        }),
247        "and" => Ok(Op::And),
248        "or" => Ok(Op::Or),
249        "new" => Ok(Op::New),
250        "type" => Ok(Op::Type),
251        "log" => Ok(Op::Log),
252        "root" => Ok(Op::Root),
253        other => Err(IrDriverError::unimplemented(format!(
254            "vm op '{other}' not yet handled by the IR driver"
255        ))),
256    }
257}
258
259fn instr_field<'a>(instr: &'a VmInstr, key: &str) -> Result<&'a Value> {
260    instr
261        .0
262        .get(key)
263        .ok_or_else(|| IrDriverError::InvalidIr(format!("vm-op missing field '{key}'")))
264}
265
266/// Integer field `key` of vm-op `op`, narrowed to the width `Op` stores.
267fn instr_int<T: TryFrom<u128>>(
268    instr: &VmInstr,
269    op: &str,
270    key: &str,
271    scope: &EvalScope<'_>,
272) -> Result<T> {
273    let n = decode_int_arg(instr_field(instr, key)?, scope)?;
274    T::try_from(n).map_err(|_| {
275        IrDriverError::TypeMismatch(format!(
276            "{op}.{key} out of {}: {n}",
277            std::any::type_name::<T>()
278        ))
279    })
280}
281
282fn instr_field_bool(instr: &VmInstr, key: &str) -> Result<bool> {
283    instr
284        .0
285        .get(key)
286        .and_then(Value::as_bool)
287        .ok_or_else(|| IrDriverError::InvalidIr(format!("vm-op field '{key}' not a bool")))
288}
289
290/// Decode a value that should resolve to an integer. Handles raw JSON
291/// numbers, `{vm: align, value, bytes}` literal-aligned values, and
292/// `{vm: value->int, value: <ref-or-align>}` runtime helpers.
293pub fn decode_int_arg(value: &Value, scope: &EvalScope<'_>) -> Result<u128> {
294    if value.is_number() || value.is_string() {
295        return json_as_u128(value);
296    }
297    let obj = value
298        .as_object()
299        .ok_or_else(|| IrDriverError::InvalidIr(format!("expected object int arg, got {value}")))?;
300    if let Some(vm_kind) = obj.get("vm").and_then(Value::as_str) {
301        match vm_kind {
302            "align" => {
303                let v = obj
304                    .get("value")
305                    .ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
306                json_as_u128(v)
307            }
308            "value->int" => {
309                let inner = obj
310                    .get("value")
311                    .ok_or_else(|| IrDriverError::InvalidIr("value->int missing 'value'".into()))?;
312                decode_int_arg(inner, scope)
313            }
314            "ref" => {
315                let inner = obj
316                    .get("value")
317                    .ok_or_else(|| IrDriverError::InvalidIr("ref missing 'value'".into()))?;
318                let resolved = scope.resolve_ref_value(inner)?;
319                json_as_u128(&resolved)
320            }
321            // `{vm: add, left: <int-arg>, right: <int-arg>}` — pure
322            // numeric addition at the VM-record level. Compactc
323            // emits this when the standard library wraps an
324            // expression like `(+ 2 (rt-max-sizeof T))` for
325            // `concat.n`.
326            "add" => {
327                let left = obj
328                    .get("left")
329                    .ok_or_else(|| IrDriverError::InvalidIr("vm:add missing 'left'".into()))?;
330                let right = obj
331                    .get("right")
332                    .ok_or_else(|| IrDriverError::InvalidIr("vm:add missing 'right'".into()))?;
333                let l = decode_int_arg(left, scope)?;
334                let r = decode_int_arg(right, scope)?;
335                l.checked_add(r).ok_or_else(|| {
336                    IrDriverError::TypeMismatch(format!("vm:add overflow: {l} + {r} exceeds u128"))
337                })
338            }
339            // `{vm: max-sizeof, type: T}` — produces the maximum
340            // encoded byte size for any value of type `T`. Mirrors
341            // the canonical Rust impl `<T>::alignment().max_aligned_size()`
342            // surfaced via [`AlignmentExt`]. Compactc emits this in
343            // the `n` slot of `concat` ops inside `List.head`'s
344            // recipe (and any future stdlib helper wrapping a
345            // value of dynamic type in a single fixed-size slot).
346            "max-sizeof" => {
347                use moonproof_ledger::transient_crypto::fab::AlignmentExt;
348                let type_obj = obj.get("type").ok_or_else(|| {
349                    IrDriverError::InvalidIr("vm:max-sizeof missing 'type'".into())
350                })?;
351                let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
352                    crate::ir::interp::decode_value_as(type_obj).map_err(|e| {
353                        IrDriverError::InvalidIr(format!(
354                            "vm:max-sizeof.type not a TypeDescriptor: {e}"
355                        ))
356                    })?;
357                // Encode the descriptor's default value to materialize
358                // its concrete `Alignment`, then take `max_aligned_size()`.
359                // The concrete value's bytes don't matter — only the
360                // alignment shape is consulted.
361                let av = encode_default(&descriptor)?;
362                Ok(av.alignment.max_aligned_size() as u128)
363            }
364            other => Err(IrDriverError::unimplemented(format!(
365                "vm wrapper '{other}' in int arg position"
366            ))),
367        }
368    } else {
369        Err(IrDriverError::InvalidIr(format!(
370            "object int arg has no 'vm' key: {value}"
371        )))
372    }
373}
374
375/// Decode a path JSON array (each element is an `align` literal or a
376/// `ref` expression) into a list of `Key` entries.
377fn decode_path(value: &Value, scope: &EvalScope<'_>) -> Result<Vec<Key>> {
378    let arr = value
379        .as_array()
380        .ok_or_else(|| IrDriverError::InvalidIr(format!("path not an array: {value}")))?;
381    let mut out = Vec::with_capacity(arr.len());
382    for elt in arr {
383        out.push(decode_path_elt(elt, scope)?);
384    }
385    Ok(out)
386}
387
388/// Fast-path encoder for `{vm: "ref", type: <descriptor>, value: ...}`
389/// avoiding `serde` `TypeDescriptor` deserialization for primitive leaf
390/// types (`Bytes`, `Boolean`, `Field`, `Uint`).
391fn encode_ref_with_type_value(type_obj: &Value, resolved: &Value) -> Result<AlignedValue> {
392    if let Some(obj) = type_obj.as_object() {
393        match obj.get("type-name").and_then(Value::as_str) {
394            Some("Bytes") => {
395                if let Some(len) = obj.get("length").and_then(Value::as_u64) {
396                    if let Ok(len32) = u32::try_from(len) {
397                        return encode_bytes(len32, resolved);
398                    }
399                }
400            }
401            Some("Boolean") => return encode_bool(resolved),
402            Some("Field") => return encode_field(resolved),
403            Some("Uint") => {
404                if let Some(max_v) = obj.get("maxval") {
405                    if let Ok(max_u128) = json_as_u128(max_v) {
406                        let max_lit = moonproof_runtime_ir::ir::IntLit::from_u128(max_u128);
407                        return encode_uint(&max_lit, resolved);
408                    }
409                }
410            }
411            _ => {}
412        }
413    }
414    let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
415        crate::ir::interp::decode_value_as(type_obj)
416            .map_err(|e| IrDriverError::InvalidIr(format!("ref.type not a TypeDescriptor: {e}")))?;
417    encode_literal(&descriptor, resolved)
418}
419
420fn decode_path_elt(value: &Value, scope: &EvalScope<'_>) -> Result<Key> {
421    // The IR's `vmop->json` line 273 emits VMstack as the bare string
422    // `"@stack"`, not a wrapped object. Match that shape directly.
423    if value.as_str() == Some("@stack") {
424        return Ok(Key::Stack);
425    }
426    let obj = value
427        .as_object()
428        .ok_or_else(|| IrDriverError::InvalidIr(format!("path elt not an object: {value}")))?;
429    if let Some(vm_kind) = obj.get("vm").and_then(Value::as_str) {
430        match vm_kind {
431            "align" => {
432                let v = obj
433                    .get("value")
434                    .ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
435                let bytes = obj.get("bytes").and_then(Value::as_u64).unwrap_or(1);
436                let n = json_as_u128(v)?;
437                let av = align_value_with_bytes(n, bytes)?;
438                Ok(Key::Value(checked_key(av)?))
439            }
440            "stack" => Ok(Key::Stack),
441            "ref" => {
442                let inner = obj
443                    .get("value")
444                    .ok_or_else(|| IrDriverError::InvalidIr("path ref missing 'value'".into()))?;
445                let resolved = scope.resolve_ref_value(inner)?;
446                // For runtime-computed paths we encode the resolved JSON
447                // through the reference type descriptor if present.
448                if let Some(type_obj) = obj.get("type") {
449                    let av = encode_ref_with_type_value(type_obj, &resolved)?;
450                    Ok(Key::Value(checked_key(av)?))
451                } else {
452                    let n = json_as_u128(&resolved)?;
453                    Ok(Key::Value(checked_key(align_value_with_bytes(n, 1)?)?))
454                }
455            }
456            other => Err(IrDriverError::unimplemented(format!(
457                "path elt vm wrapper '{other}'"
458            ))),
459        }
460    } else {
461        Err(IrDriverError::InvalidIr(format!(
462            "path elt has no 'vm' key: {value}"
463        )))
464    }
465}
466
467/// Decode a `vm: state-value` object into a ledger `StateValue`.
468pub fn decode_state_value(value: &Value, scope: &EvalScope<'_>) -> Result<StateValue<InMemoryDB>> {
469    let obj = value
470        .as_object()
471        .ok_or_else(|| IrDriverError::InvalidIr(format!("state-value not an object: {value}")))?;
472    if obj.get("vm").and_then(Value::as_str) != Some("state-value") {
473        return Err(IrDriverError::InvalidIr(format!(
474            "expected vm=state-value, got {value}"
475        )));
476    }
477    let kind = obj
478        .get("kind")
479        .and_then(Value::as_str)
480        .ok_or_else(|| IrDriverError::InvalidIr("state-value missing 'kind'".into()))?;
481    match kind {
482        "null" => Ok(StateValue::Null),
483        "cell" | "adt" => {
484            // `cell` and `adt` both produce a `StateValue::Cell`
485            // holding a typed AlignedValue. The Compact emitter
486            // prefers `adt` when the cell is wrapping a typed value
487            // produced via a runtime-evaluated ref (e.g. Map.insert
488            // pushes an `adt` state-value carrying the typed value).
489            // The semantics are identical: a single AlignedValue
490            // wrapped in a Cell.
491            let inner = obj.get("value").ok_or_else(|| {
492                IrDriverError::InvalidIr(format!("state-value {kind} missing 'value'"))
493            })?;
494            let av = decode_aligned_value(inner, scope)?;
495            Ok(StateValue::Cell(Sp::new(av)))
496        }
497        "map" => {
498            // `Map.resetToDefault` and `Set.resetToDefault` both
499            // emit `{vm: state-value, kind: map, entries: [...]}`.
500            // The runtime represents both as `StateValue::Map` with
501            // an `AlignedValue → StateValue` table; an empty map is
502            // the reset state. Non-empty entries are not produced by
503            // any init-op we've seen — only by user-side
504            // operations (`Map.insert`) — so they'd surface here
505            // only if a contract pre-populated a map at construction
506            // time, which the IR shapes today don't.
507            let entries = obj.get("entries").and_then(Value::as_array);
508            if let Some(entries) = entries {
509                if !entries.is_empty() {
510                    return Err(IrDriverError::unimplemented(
511                        "state-value map with non-empty entries (no contract shape uses this yet)",
512                    ));
513                }
514            }
515            Ok(StateValue::Map(
516                moonproof_ledger::storage::storage::HashMap::new(),
517            ))
518        }
519        "array" => {
520            // `state-value: array` carries a list of nested
521            // state-values to construct an `Array(Vec<StateValue>)`.
522            // identity_registry's `MerkleTree.resetToDefault` emits
523            // an Array of `[merkle-tree, cell(u64(0))]` (the tree
524            // pairs with a Counter for the next-leaf index).
525            let values = obj.get("values").and_then(Value::as_array).ok_or_else(|| {
526                IrDriverError::InvalidIr("state-value array missing 'values'".into())
527            })?;
528            let inner: Result<Vec<StateValue<InMemoryDB>>> = values
529                .iter()
530                .map(|v| decode_state_value(v, scope))
531                .collect();
532            Ok(StateValue::Array(StorageArray::from(inner?)))
533        }
534        "merkle-tree" => {
535            // `MerkleTree.resetToDefault` emits a blank merkle tree
536            // of declared depth. Non-empty entries would only show
537            // up if a contract pre-populated the tree at construction
538            // time (none of the committed test fixtures do this today).
539            let depth_v = obj
540                .get("depth")
541                .ok_or_else(|| IrDriverError::InvalidIr("merkle-tree missing 'depth'".into()))?;
542            let depth_u128 = json_as_u128(depth_v)?;
543            let depth = u8::try_from(depth_u128).map_err(|_| {
544                IrDriverError::TypeMismatch(format!(
545                    "merkle-tree depth out of u8 range: {depth_u128}"
546                ))
547            })?;
548            let entries = obj.get("entries").and_then(Value::as_array);
549            if let Some(entries) = entries {
550                if !entries.is_empty() {
551                    return Err(IrDriverError::unimplemented(
552                        "state-value merkle-tree with pre-populated entries",
553                    ));
554                }
555            }
556            Ok(StateValue::BoundedMerkleTree(
557                moonproof_ledger::transient_crypto::merkle_tree::MerkleTree::<(), InMemoryDB>::blank(depth),
558            ))
559        }
560        other => Err(IrDriverError::unimplemented(format!(
561            "state-value kind '{other}'"
562        ))),
563    }
564}
565
566/// Decode an aligned-value description (typically `{vm: align, value,
567/// bytes}` for literals or `{vm: ref, ...}` for runtime-computed
568/// values).
569fn decode_aligned_value(value: &Value, scope: &EvalScope<'_>) -> Result<AlignedValue> {
570    let obj = value
571        .as_object()
572        .ok_or_else(|| IrDriverError::InvalidIr(format!("aligned-value not an object: {value}")))?;
573    let kind = obj
574        .get("vm")
575        .and_then(Value::as_str)
576        .ok_or_else(|| IrDriverError::InvalidIr("aligned-value missing 'vm'".into()))?;
577    match kind {
578        "align" => {
579            let v = obj
580                .get("value")
581                .ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
582            let bytes = obj.get("bytes").and_then(Value::as_u64).unwrap_or(1);
583            let n = json_as_u128(v)?;
584            align_value_with_bytes(n, bytes)
585        }
586        "ref" => {
587            let type_obj = obj.get("type").ok_or_else(|| {
588                IrDriverError::InvalidIr("aligned-value ref missing 'type'".into())
589            })?;
590            let inner = obj.get("value").ok_or_else(|| {
591                IrDriverError::InvalidIr("aligned-value ref missing 'value'".into())
592            })?;
593            let resolved = scope.resolve_ref_value(inner)?;
594            encode_ref_with_type_value(type_obj, &resolved)
595        }
596        "null" => {
597            // `{vm: null, type: <descriptor>}` is the IR's
598            // "wire-format zero of T" pushdown, used by every
599            // `Cell.resetToDefault` init-op. The encoded bytes match
600            // what the JS emitter produces via `_descriptor_N.alignment().toBytes(default)`.
601            let type_obj = obj.get("type").ok_or_else(|| {
602                IrDriverError::InvalidIr("aligned-value null missing 'type'".into())
603            })?;
604            let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
605                crate::ir::interp::decode_value_as(type_obj).map_err(|e| {
606                    IrDriverError::InvalidIr(format!("null.type not a TypeDescriptor: {e}"))
607                })?;
608            encode_default(&descriptor)
609        }
610        "aligned-concat" => {
611            // `{vm: aligned-concat, values: [<aligned-value>...]}` —
612            // recursively decode each inner aligned-value and
613            // concatenate via `AlignedValue::concat`. Mirrors the
614            // `VMaligned-concat` emit in `runtime-ir-passes.ss:288`,
615            // used when a kernel ADT-op constructs a multi-atom
616            // AlignedValue from individual fields.
617            let values = obj.get("values").and_then(Value::as_array).ok_or_else(|| {
618                IrDriverError::InvalidIr("aligned-concat missing 'values' array".into())
619            })?;
620            let avs: Result<Vec<AlignedValue>> = values
621                .iter()
622                .map(|v| decode_aligned_value(v, scope))
623                .collect();
624            let avs = avs?;
625            Ok(AlignedValue::concat(avs.iter()))
626        }
627        "coin-commit" => {
628            // `{vm: coin-commit, coin: <aligned-value>, recipient: <aligned-value>}`
629            // — produces the 32-byte coin commitment.
630            //
631            // Mirrors `onchain-runtime-wasm/src/primitives.rs:135`'s
632            // `runtimeCoinCommitment(coin, recipient)`:
633            //   1. Convert the coin AlignedValue → typed `CoinInfo`
634            //      (nonce + type_ + value).
635            //   2. Convert the recipient AlignedValue → typed
636            //      `Recipient::User(...)` or `Recipient::Contract(...)`
637            //      (the Either's active branch — the inactive branch's
638            //      bytes are NOT included in the commitment).
639            //   3. Call `CoinInfo::commitment(&recipient)` which writes
640            //      `b"midnight:zswap-cc[v1]" + coin.binary_repr() +
641            //      (is_user, addr.0).binary_repr()` and SHA-256s it.
642            //
643            // The earlier raw-`binary_repr`-of-aligned-value approach
644            // was wrong: an Either AlignedValue includes both branches'
645            // bytes (1+32+32=65), but the canonical commitment only
646            // includes the active branch (1+32=33). Going via the
647            // typed `Recipient::try_from` conversion gets it right.
648            let coin_inner = obj
649                .get("coin")
650                .ok_or_else(|| IrDriverError::InvalidIr("coin-commit missing 'coin'".into()))?;
651            let recipient_inner = obj.get("recipient").ok_or_else(|| {
652                IrDriverError::InvalidIr("coin-commit missing 'recipient'".into())
653            })?;
654            let coin_av = decode_aligned_value(coin_inner, scope)?;
655            let recipient_av = decode_aligned_value(recipient_inner, scope)?;
656            coin_commit_aligned(&coin_av, &recipient_av)
657        }
658        "leaf-hash" => {
659            // `{vm: leaf-hash, value: <inner aligned-value>}` —
660            // produces the 32-byte tree-leaf hash for the inner
661            // value. Mirrors `transient_crypto::merkle_tree::leaf_hash`
662            // (domain-separated SHA-256 over the value's binary repr).
663            let inner = obj
664                .get("value")
665                .ok_or_else(|| IrDriverError::InvalidIr("leaf-hash missing 'value'".into()))?;
666            let inner_av = decode_aligned_value(inner, scope)?;
667            Ok(leaf_hash_aligned(inner_av))
668        }
669        other => Err(IrDriverError::unimplemented(format!(
670            "aligned-value vm wrapper '{other}'"
671        ))),
672    }
673}
674
675fn coin_commit_aligned(
676    coin_av: &AlignedValue,
677    recipient_av: &AlignedValue,
678) -> Result<AlignedValue> {
679    let coin: moonproof_ledger::coin_structure::coin::Info =
680        moonproof_ledger::coin_structure::coin::Info::try_from(&**AsRef::<
681            moonproof_ledger::base_crypto::fab::Value,
682        >::as_ref(coin_av))
683        .map_err(|e| IrDriverError::TypeMismatch(format!("coin-commit coin → CoinInfo: {e:?}")))?;
684    let recipient: moonproof_ledger::coin_structure::transfer::Recipient =
685        moonproof_ledger::coin_structure::transfer::Recipient::try_from(&**AsRef::<
686            moonproof_ledger::base_crypto::fab::Value,
687        >::as_ref(
688            recipient_av
689        ))
690        .map_err(|e| {
691            IrDriverError::TypeMismatch(format!("coin-commit recipient → Recipient: {e:?}"))
692        })?;
693    Ok(AlignedValue::from(coin.commitment(&recipient)))
694}
695
696fn leaf_hash_aligned(inner_av: AlignedValue) -> AlignedValue {
697    let hash = moonproof_ledger::transient_crypto::merkle_tree::leaf_hash(
698        &moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue(inner_av),
699    );
700    let moonproof_ledger::base_crypto::hash::HashOutput(bytes) = hash;
701    AlignedValue::from(bytes)
702}
703
704fn checked_cell_value(av: AlignedValue) -> Result<AlignedValueChecked> {
705    AlignedValueChecked::try_from(av).map_err(|()| {
706        IrDriverError::InvalidIr(
707            "push value is not canonical: a field atom is not below the field modulus, \
708             or a Merkle tree is not blank"
709                .into(),
710        )
711    })
712}
713
714/// The VM only pushes canonical values: every field atom below the
715/// field modulus and every Merkle tree blank. A freshly decoded value
716/// shares no children, so the tree walk in `try_into_checked` stays
717/// linear in its size.
718pub(crate) fn checked_state_value(
719    value: &StateValue<InMemoryDB>,
720) -> Result<StateValue<InMemoryDB, AlignedValueChecked>> {
721    value.try_into_checked().map_err(|()| {
722        IrDriverError::InvalidIr(
723            "push value is not canonical: a field atom is not below the field modulus, \
724             or a Merkle tree is not blank"
725                .into(),
726        )
727    })
728}
729
730/// The VM only indexes by canonical values, so a key whose field atom
731/// would alias another key through modular reduction is refused here.
732pub(crate) fn checked_key(av: AlignedValue) -> Result<AlignedValueChecked> {
733    AlignedValueChecked::try_from(av).map_err(|()| {
734        IrDriverError::InvalidIr(
735            "path key has a field atom that is not below the field modulus".into(),
736        )
737    })
738}
739
740/// Build an `AlignedValue` from a u128 with a specific byte width.
741fn align_value_with_bytes(value: u128, bytes: u64) -> Result<AlignedValue> {
742    let too_wide = |_| {
743        IrDriverError::TypeMismatch(format!("align value {value} does not fit in {bytes} bytes"))
744    };
745    match bytes {
746        1 => Ok(AlignedValue::from(u8::try_from(value).map_err(too_wide)?)),
747        2 => Ok(AlignedValue::from(u16::try_from(value).map_err(too_wide)?)),
748        4 => Ok(AlignedValue::from(u32::try_from(value).map_err(too_wide)?)),
749        8 => Ok(AlignedValue::from(u64::try_from(value).map_err(too_wide)?)),
750        16 => Ok(AlignedValue::from(value)),
751        other => Err(IrDriverError::unimplemented(format!(
752            "align width {other} bytes"
753        ))),
754    }
755}
756
757// ===========================================================================
758// Pre-compiled VM-op query templates (zero BTreeMap / serde on hot path)
759// ===========================================================================
760
761/// Static summary of which VM stack slots a ledger query may touch.
762///
763/// Every ledger VM query begins with a 3-slot stack:
764/// `[0: call context (Weak), 1: effects (Weak), 2: contract state (Strong)]`.
765///
766/// Computed conservatively: any control-flow op (`Branch`, `Jmp`), dynamic
767/// stack-depth integer (`Dup`/`Swap`/`Ins` with a runtime ref), or stack
768/// underflow sets all flags to `true` so correctness is never compromised.
769#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770pub struct QueryFlags {
771    /// Query may read or touch stack index 0 (call context: address,
772    /// coin commitments, block timestamp, balance, caller, etc.).
773    pub reads_context: bool,
774    /// Query may read or mutate stack index 1 (`Effects`).
775    pub touches_effects: bool,
776    /// Query may mutate or replace stack index 2 (contract `StateValue`).
777    pub mutates_state: bool,
778}
779
780impl QueryFlags {
781    /// Conservative fallback assuming context, effects, and state are all touched.
782    pub const ALL: Self = Self {
783        reads_context: true,
784        touches_effects: true,
785        mutates_state: true,
786    };
787
788    /// Pure read-only state query (no context read, no effects touch, no state mutation).
789    pub const READ_ONLY_STATE: Self = Self {
790        reads_context: false,
791        touches_effects: false,
792        mutates_state: false,
793    };
794
795    /// Combine two flag sets (logical OR of every field).
796    #[inline]
797    #[must_use]
798    pub const fn union(self, other: Self) -> Self {
799        Self {
800            reads_context: self.reads_context || other.reads_context,
801            touches_effects: self.touches_effects || other.touches_effects,
802            mutates_state: self.mutates_state || other.mutates_state,
803        }
804    }
805}
806
807struct StackTracker {
808    height: usize,
809    flags: QueryFlags,
810}
811
812impl StackTracker {
813    fn new() -> Self {
814        Self {
815            height: 3,
816            flags: QueryFlags::READ_ONLY_STATE,
817        }
818    }
819
820    fn note_read(&mut self, idx: usize) {
821        if idx == 0 {
822            self.flags.reads_context = true;
823        } else if idx == 1 {
824            self.flags.touches_effects = true;
825        }
826    }
827
828    fn note_write(&mut self, idx: usize) {
829        if idx == 0 {
830            self.flags.reads_context = true;
831        }
832        if idx <= 1 {
833            self.flags.touches_effects = true;
834        }
835        if idx <= 2 {
836            self.flags.mutates_state = true;
837        }
838    }
839
840    fn pop(&mut self, n: usize) -> bool {
841        if self.height < n {
842            self.flags = QueryFlags::ALL;
843            return false;
844        }
845        if n > 0 {
846            let lowest = self.height - n;
847            self.note_write(lowest);
848            self.height = lowest;
849        }
850        true
851    }
852
853    fn step_op(&mut self, op: &Op<ResultModeGather, InMemoryDB>) -> bool {
854        match op {
855            Op::Noop { .. } => true,
856            Op::Ckpt => {
857                self.flags.touches_effects = true;
858                true
859            }
860            Op::Push { .. } => {
861                self.height += 1;
862                true
863            }
864            Op::Pop | Op::Popeq { .. } | Op::Log => self.pop(1),
865            Op::Type
866            | Op::Size
867            | Op::New
868            | Op::Neg
869            | Op::Root
870            | Op::Addi { .. }
871            | Op::Subi { .. } => {
872                if !self.pop(1) {
873                    return false;
874                }
875                self.height += 1;
876                true
877            }
878            Op::Lt
879            | Op::Eq
880            | Op::And
881            | Op::Or
882            | Op::Add
883            | Op::Sub
884            | Op::Concat { .. }
885            | Op::Member => {
886                if !self.pop(2) {
887                    return false;
888                }
889                self.height += 1;
890                true
891            }
892            Op::Rem { .. } => {
893                self.flags.mutates_state = true;
894                if !self.pop(2) {
895                    return false;
896                }
897                self.height += 1;
898                true
899            }
900            Op::Dup { n } => {
901                let depth = usize::from(*n);
902                if self.height <= depth {
903                    self.flags = QueryFlags::ALL;
904                    return false;
905                }
906                let idx = self.height - 1 - depth;
907                self.note_read(idx);
908                self.height += 1;
909                true
910            }
911            Op::Swap { n } => {
912                let depth = usize::from(*n);
913                if self.height < depth + 2 {
914                    self.flags = QueryFlags::ALL;
915                    return false;
916                }
917                let top = self.height - 1;
918                let other = self.height - 2 - depth;
919                self.note_write(top);
920                self.note_write(other);
921                true
922            }
923            Op::Idx {
924                push_path, path, ..
925            } => {
926                let stack_keys = path.iter().filter(|k| **k == Key::Stack).count();
927                if !self.pop(stack_keys + 1) {
928                    return false;
929                }
930                if *push_path {
931                    self.height += 2 * path.len();
932                }
933                self.height += 1;
934                true
935            }
936            Op::Ins { n, .. } => {
937                self.flags.mutates_state = true;
938                let popped = usize::from(*n) * 2 + 1;
939                if !self.pop(popped) {
940                    return false;
941                }
942                self.height += 1;
943                true
944            }
945            Op::Branch { .. } | Op::Jmp { .. } | _ => {
946                self.flags = QueryFlags::ALL;
947                false
948            }
949        }
950    }
951
952    fn step_compiled_op(&mut self, op: &CompiledOp) -> bool {
953        match op {
954            CompiledOp::Static(raw) => self.step_op(raw),
955            CompiledOp::Push { .. } => {
956                self.height += 1;
957                true
958            }
959            CompiledOp::Idx {
960                push_path, path, ..
961            } => {
962                let stack_keys = path
963                    .iter()
964                    .filter(|k| matches!(k, CompiledPathKey::Static(Key::Stack)))
965                    .count();
966                if !self.pop(stack_keys + 1) {
967                    return false;
968                }
969                if *push_path {
970                    self.height += 2 * path.len();
971                }
972                self.height += 1;
973                true
974            }
975            CompiledOp::Ins { n, .. } => {
976                self.flags.mutates_state = true;
977                let CompiledIntArg::Static(val) = n else {
978                    self.flags = QueryFlags::ALL;
979                    return false;
980                };
981                let Ok(count) = usize::try_from(*val) else {
982                    self.flags = QueryFlags::ALL;
983                    return false;
984                };
985                let Some(popped) = count.checked_mul(2).and_then(|v| v.checked_add(1)) else {
986                    self.flags = QueryFlags::ALL;
987                    return false;
988                };
989                if !self.pop(popped) {
990                    return false;
991                }
992                self.height += 1;
993                true
994            }
995            CompiledOp::Addi { .. } | CompiledOp::Subi { .. } => {
996                if !self.pop(1) {
997                    return false;
998                }
999                self.height += 1;
1000                true
1001            }
1002            CompiledOp::Noop { .. } => true,
1003            CompiledOp::Concat { .. } => {
1004                if !self.pop(2) {
1005                    return false;
1006                }
1007                self.height += 1;
1008                true
1009            }
1010            CompiledOp::Dup { n } => {
1011                let CompiledIntArg::Static(val) = n else {
1012                    self.flags = QueryFlags::ALL;
1013                    return false;
1014                };
1015                let Ok(depth) = usize::try_from(*val) else {
1016                    self.flags = QueryFlags::ALL;
1017                    return false;
1018                };
1019                if self.height <= depth {
1020                    self.flags = QueryFlags::ALL;
1021                    return false;
1022                }
1023                let idx = self.height - 1 - depth;
1024                self.note_read(idx);
1025                self.height += 1;
1026                true
1027            }
1028            CompiledOp::Swap { n } => {
1029                let CompiledIntArg::Static(val) = n else {
1030                    self.flags = QueryFlags::ALL;
1031                    return false;
1032                };
1033                let Ok(depth) = usize::try_from(*val) else {
1034                    self.flags = QueryFlags::ALL;
1035                    return false;
1036                };
1037                if self.height < depth + 2 {
1038                    self.flags = QueryFlags::ALL;
1039                    return false;
1040                }
1041                let top = self.height - 1;
1042                let other = self.height - 2 - depth;
1043                self.note_write(top);
1044                self.note_write(other);
1045                true
1046            }
1047            CompiledOp::Branch { .. } | CompiledOp::Jmp { .. } => {
1048                self.flags = QueryFlags::ALL;
1049                false
1050            }
1051        }
1052    }
1053}
1054
1055/// Conservatively analyze a concrete VM-op slice for context/effects/state access.
1056#[must_use]
1057pub fn analyze_ops(ops: &[Op<ResultModeGather, InMemoryDB>]) -> QueryFlags {
1058    let mut tracker = StackTracker::new();
1059    for op in ops {
1060        if !tracker.step_op(op) {
1061            break;
1062        }
1063    }
1064    tracker.flags
1065}
1066
1067/// Conservatively analyze a compiled dynamic VM-op slice for context/effects/state access.
1068#[must_use]
1069pub fn analyze_compiled_ops(ops: &[CompiledOp]) -> QueryFlags {
1070    let mut tracker = StackTracker::new();
1071    for op in ops {
1072        if !tracker.step_compiled_op(op) {
1073            break;
1074        }
1075    }
1076    tracker.flags
1077}
1078
1079/// Pre-compiled ledger VM query for a `vm-ops` instruction list, paired
1080/// with conservative static [`QueryFlags`] for lazy context/effects/state handling.
1081///
1082/// Static queries require zero per-call decoding or scratch `Vec<Op>`
1083/// allocation; dynamic queries resolve only their runtime variable refs
1084/// through pre-compiled [`FabPlan`]s.
1085#[derive(Debug, Clone)]
1086pub struct CompiledLedgerQuery {
1087    pub flags: QueryFlags,
1088    pub body: CompiledQueryBody,
1089}
1090
1091/// Instruction payload of a [`CompiledLedgerQuery`].
1092#[derive(Debug, Clone)]
1093pub enum CompiledQueryBody {
1094    /// Every instruction in the query is independent of runtime scope.
1095    Static(Vec<Op<ResultModeGather, InMemoryDB>>),
1096    /// At least one instruction references runtime arguments or locals.
1097    Dynamic(Vec<CompiledOp>),
1098}
1099
1100impl CompiledLedgerQuery {
1101    /// Materialize a dynamic query into concrete VM ops for `scope`.
1102    pub fn materialize_dynamic(
1103        ops: &[CompiledOp],
1104        scope: &EvalScope<'_>,
1105    ) -> Result<Vec<Op<ResultModeGather, InMemoryDB>>> {
1106        let mut out = Vec::with_capacity(ops.len());
1107        for op in ops {
1108            out.push(op.materialize(scope)?);
1109        }
1110        Ok(out)
1111    }
1112}
1113
1114/// One pre-compiled VM instruction inside a [`CompiledLedgerQuery`].
1115#[derive(Debug, Clone)]
1116pub enum CompiledOp {
1117    Static(Op<ResultModeGather, InMemoryDB>),
1118    Push {
1119        storage: bool,
1120        value: CompiledStateValue,
1121    },
1122    Idx {
1123        cached: bool,
1124        push_path: bool,
1125        path: Vec<CompiledPathKey>,
1126    },
1127    Ins {
1128        cached: bool,
1129        n: CompiledIntArg,
1130    },
1131    Addi {
1132        immediate: CompiledIntArg,
1133    },
1134    Subi {
1135        immediate: CompiledIntArg,
1136    },
1137    Noop {
1138        n: CompiledIntArg,
1139    },
1140    Dup {
1141        n: CompiledIntArg,
1142    },
1143    Swap {
1144        n: CompiledIntArg,
1145    },
1146    Concat {
1147        cached: bool,
1148        n: CompiledIntArg,
1149    },
1150    Branch {
1151        skip: CompiledIntArg,
1152    },
1153    Jmp {
1154        skip: CompiledIntArg,
1155    },
1156}
1157
1158#[derive(Debug, Clone)]
1159pub enum CompiledStateValue {
1160    Static(StateValue<InMemoryDB, AlignedValueChecked>),
1161    Cell(CompiledAlignedValue),
1162    Array(Vec<CompiledStateValue>),
1163}
1164
1165#[derive(Debug, Clone)]
1166pub enum CompiledAlignedValue {
1167    Static(AlignedValue),
1168    Ref {
1169        expr: CompiledRefExpr,
1170        plan: FabPlan,
1171    },
1172    AlignedConcat(Vec<CompiledAlignedValue>),
1173    CoinCommit {
1174        coin: Box<CompiledAlignedValue>,
1175        recipient: Box<CompiledAlignedValue>,
1176    },
1177    LeafHash(Box<CompiledAlignedValue>),
1178}
1179
1180#[derive(Debug, Clone)]
1181pub enum CompiledPathKey {
1182    Static(Key),
1183    DynamicRef {
1184        expr: CompiledRefExpr,
1185        plan: Option<FabPlan>,
1186    },
1187}
1188
1189#[derive(Debug, Clone)]
1190pub enum CompiledIntArg {
1191    Static(u128),
1192    Ref(CompiledRefExpr),
1193    Add(Box<CompiledIntArg>, Box<CompiledIntArg>),
1194}
1195
1196#[derive(Debug, Clone)]
1197pub enum CompiledRefExpr {
1198    Var(String),
1199    Literal(Value),
1200    Expr(Box<moonproof_runtime_ir::ir::Expression>),
1201}
1202
1203/// Pre-compile a slice of raw IR `VmInstr` objects into a
1204/// [`CompiledLedgerQuery`].
1205///
1206/// Returns `None` if any instruction contains an unimplemented or malformed
1207/// shape so `IrExecutable::new` remains infallible and runtime execution falls
1208/// back to [`decode_op`] to surface the exact error if that site is reached.
1209#[must_use]
1210pub fn compile_vm_ops(vm_ops: &[VmInstr]) -> Option<CompiledLedgerQuery> {
1211    let mut compiled = Vec::with_capacity(vm_ops.len());
1212    let mut all_static = true;
1213    for instr in vm_ops {
1214        let op = compile_op(instr).ok()?;
1215        if !matches!(op, CompiledOp::Static(_)) {
1216            all_static = false;
1217        }
1218        compiled.push(op);
1219    }
1220    if all_static {
1221        let static_ops: Vec<Op<ResultModeGather, InMemoryDB>> = compiled
1222            .into_iter()
1223            .map(|op| match op {
1224                CompiledOp::Static(raw) => raw,
1225                _ => unreachable!("all_static verified"),
1226            })
1227            .collect();
1228        let flags = analyze_ops(&static_ops);
1229        Some(CompiledLedgerQuery {
1230            flags,
1231            body: CompiledQueryBody::Static(static_ops),
1232        })
1233    } else {
1234        let flags = analyze_compiled_ops(&compiled);
1235        Some(CompiledLedgerQuery {
1236            flags,
1237            body: CompiledQueryBody::Dynamic(compiled),
1238        })
1239    }
1240}
1241
1242fn narrow_int<T: TryFrom<u128>>(op: &str, key: &str, n: u128) -> Result<T> {
1243    T::try_from(n).map_err(|_| {
1244        IrDriverError::TypeMismatch(format!(
1245            "{op}.{key} out of {}: {n}",
1246            std::any::type_name::<T>()
1247        ))
1248    })
1249}
1250
1251fn compile_int_op(op_name: &str, instr: &VmInstr) -> Result<CompiledOp> {
1252    match op_name {
1253        "ins" => {
1254            let cached = instr_field_bool(instr, "cached")?;
1255            match compile_int_arg(instr_field(instr, "n")?)? {
1256                CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Ins {
1257                    cached,
1258                    n: narrow_int("ins", "n", n)?,
1259                })),
1260                dynamic => Ok(CompiledOp::Ins { cached, n: dynamic }),
1261            }
1262        }
1263        "addi" => match compile_int_arg(instr_field(instr, "immediate")?)? {
1264            CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Addi {
1265                immediate: narrow_int("addi", "immediate", n)?,
1266            })),
1267            dynamic => Ok(CompiledOp::Addi { immediate: dynamic }),
1268        },
1269        "subi" => match compile_int_arg(instr_field(instr, "immediate")?)? {
1270            CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Subi {
1271                immediate: narrow_int("subi", "immediate", n)?,
1272            })),
1273            dynamic => Ok(CompiledOp::Subi { immediate: dynamic }),
1274        },
1275        "noop" => match instr.0.get("n") {
1276            None | Some(Value::Null) => Ok(CompiledOp::Static(Op::Noop { n: 0 })),
1277            Some(v) => match compile_int_arg(v) {
1278                Ok(CompiledIntArg::Static(n)) => Ok(CompiledOp::Static(Op::Noop {
1279                    n: u32::try_from(n).unwrap_or(0),
1280                })),
1281                Ok(dynamic) => Ok(CompiledOp::Noop { n: dynamic }),
1282                Err(_) => Ok(CompiledOp::Static(Op::Noop { n: 0 })),
1283            },
1284        },
1285        "dup" => match compile_int_arg(instr_field(instr, "n")?)? {
1286            CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Dup {
1287                n: narrow_int("dup", "n", n)?,
1288            })),
1289            dynamic => Ok(CompiledOp::Dup { n: dynamic }),
1290        },
1291        "swap" => match compile_int_arg(instr_field(instr, "n")?)? {
1292            CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Swap {
1293                n: narrow_int("swap", "n", n)?,
1294            })),
1295            dynamic => Ok(CompiledOp::Swap { n: dynamic }),
1296        },
1297        "concat" => {
1298            let cached = instr_field_bool(instr, "cached")?;
1299            match compile_int_arg(instr_field(instr, "n")?)? {
1300                CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Concat {
1301                    cached,
1302                    n: narrow_int("concat", "n", n)?,
1303                })),
1304                dynamic => Ok(CompiledOp::Concat { cached, n: dynamic }),
1305            }
1306        }
1307        "branch" => match compile_int_arg(instr_field(instr, "skip")?)? {
1308            CompiledIntArg::Static(skip) => Ok(CompiledOp::Static(Op::Branch {
1309                skip: narrow_int("branch", "skip", skip)?,
1310            })),
1311            dynamic => Ok(CompiledOp::Branch { skip: dynamic }),
1312        },
1313        "jmp" => match compile_int_arg(instr_field(instr, "skip")?)? {
1314            CompiledIntArg::Static(skip) => Ok(CompiledOp::Static(Op::Jmp {
1315                skip: narrow_int("jmp", "skip", skip)?,
1316            })),
1317            dynamic => Ok(CompiledOp::Jmp { skip: dynamic }),
1318        },
1319        other => Err(IrDriverError::unimplemented(format!(
1320            "vm op '{other}' not yet handled by the IR driver"
1321        ))),
1322    }
1323}
1324
1325fn compile_op(instr: &VmInstr) -> Result<CompiledOp> {
1326    let op_name = instr
1327        .op()
1328        .ok_or_else(|| IrDriverError::InvalidIr("vm-op missing 'op' key".into()))?;
1329    match op_name {
1330        "push" => {
1331            let storage = instr_field_bool(instr, "storage")?;
1332            let value = compile_state_value(instr_field(instr, "value")?)?;
1333            match value {
1334                CompiledStateValue::Static(sv) => {
1335                    Ok(CompiledOp::Static(Op::Push { storage, value: sv }))
1336                }
1337                dynamic => Ok(CompiledOp::Push {
1338                    storage,
1339                    value: dynamic,
1340                }),
1341            }
1342        }
1343        "idx" => {
1344            let cached = instr_field_bool(instr, "cached")?;
1345            let push_path = instr_field_bool(instr, "pushPath")?;
1346            let path = compile_path(instr_field(instr, "path")?)?;
1347            if path.iter().all(|k| matches!(k, CompiledPathKey::Static(_))) {
1348                let keys: Vec<Key> = path
1349                    .into_iter()
1350                    .map(|k| match k {
1351                        CompiledPathKey::Static(key) => key,
1352                        CompiledPathKey::DynamicRef { .. } => unreachable!(),
1353                    })
1354                    .collect();
1355                Ok(CompiledOp::Static(Op::Idx {
1356                    cached,
1357                    push_path,
1358                    path: StorageArray::from(keys),
1359                }))
1360            } else {
1361                Ok(CompiledOp::Idx {
1362                    cached,
1363                    push_path,
1364                    path,
1365                })
1366            }
1367        }
1368        "ins" | "addi" | "subi" | "noop" | "dup" | "swap" | "concat" | "branch" | "jmp" => {
1369            compile_int_op(op_name, instr)
1370        }
1371        "popeq" => Ok(CompiledOp::Static(Op::Popeq {
1372            cached: instr_field_bool(instr, "cached")?,
1373            result: (),
1374        })),
1375        "rem" => Ok(CompiledOp::Static(Op::Rem {
1376            cached: instr_field_bool(instr, "cached")?,
1377        })),
1378        "pop" => Ok(CompiledOp::Static(Op::Pop)),
1379        "lt" => Ok(CompiledOp::Static(Op::Lt)),
1380        "eq" => Ok(CompiledOp::Static(Op::Eq)),
1381        "neg" => Ok(CompiledOp::Static(Op::Neg)),
1382        "size" => Ok(CompiledOp::Static(Op::Size)),
1383        "member" => Ok(CompiledOp::Static(Op::Member)),
1384        "ckpt" => Ok(CompiledOp::Static(Op::Ckpt)),
1385        "add" => Ok(CompiledOp::Static(Op::Add)),
1386        "sub" => Ok(CompiledOp::Static(Op::Sub)),
1387        "and" => Ok(CompiledOp::Static(Op::And)),
1388        "or" => Ok(CompiledOp::Static(Op::Or)),
1389        "new" => Ok(CompiledOp::Static(Op::New)),
1390        "type" => Ok(CompiledOp::Static(Op::Type)),
1391        "log" => Ok(CompiledOp::Static(Op::Log)),
1392        "root" => Ok(CompiledOp::Static(Op::Root)),
1393        other => Err(IrDriverError::unimplemented(format!(
1394            "vm op '{other}' not yet handled by the IR driver"
1395        ))),
1396    }
1397}
1398
1399fn compile_ref_expr(inner: &Value) -> Result<CompiledRefExpr> {
1400    if let Some(obj) = inner.as_object() {
1401        match obj.get("expr").and_then(Value::as_str) {
1402            Some("var") => {
1403                if let Some(name) = obj.get("name").and_then(Value::as_str) {
1404                    return Ok(CompiledRefExpr::Var(name.to_owned()));
1405                }
1406            }
1407            Some("literal") => {
1408                if let Some(v) = obj.get("value") {
1409                    return Ok(CompiledRefExpr::Literal(v.clone()));
1410                }
1411            }
1412            _ => {}
1413        }
1414    }
1415    let expr: moonproof_runtime_ir::ir::Expression = crate::ir::interp::decode_value_as(inner)
1416        .map_err(|e| IrDriverError::InvalidIr(format!("ref.value not an Expression: {e}")))?;
1417    match expr {
1418        moonproof_runtime_ir::ir::Expression::Var { name } => Ok(CompiledRefExpr::Var(name)),
1419        moonproof_runtime_ir::ir::Expression::Literal { value } => {
1420            Ok(CompiledRefExpr::Literal(value))
1421        }
1422        moonproof_runtime_ir::ir::Expression::EnumRef { of_type, variant } => match of_type {
1423            moonproof_runtime_ir::ir::TypeDescriptor::Enum { elements, name } => {
1424                if !elements.iter().any(|v| v == &variant) {
1425                    return Err(IrDriverError::TypeMismatch(format!(
1426                        "enum {name} has no variant '{variant}' (variants: {elements:?})"
1427                    )));
1428                }
1429                Ok(CompiledRefExpr::Literal(Value::String(variant)))
1430            }
1431            other => Err(IrDriverError::TypeMismatch(format!(
1432                "enum-ref descriptor not an Enum: {other:?}"
1433            ))),
1434        },
1435        moonproof_runtime_ir::ir::Expression::Default { of_type } => {
1436            let av = encode_default(&of_type)?;
1437            let v = super::descriptor::decode_aligned_value_full(&of_type, &av)?;
1438            Ok(CompiledRefExpr::Literal(v))
1439        }
1440        other => Ok(CompiledRefExpr::Expr(Box::new(other))),
1441    }
1442}
1443
1444fn compile_type_plan(type_obj: &Value) -> Result<FabPlan> {
1445    let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
1446        crate::ir::interp::decode_value_as(type_obj)
1447            .map_err(|e| IrDriverError::InvalidIr(format!("ref.type not a TypeDescriptor: {e}")))?;
1448    FabPlan::compile(&descriptor).ok_or_else(|| {
1449        IrDriverError::unimplemented(format!("FabPlan unsupported for descriptor {descriptor:?}"))
1450    })
1451}
1452
1453fn compile_int_arg(value: &Value) -> Result<CompiledIntArg> {
1454    if value.is_number() || value.is_string() {
1455        return Ok(CompiledIntArg::Static(json_as_u128(value)?));
1456    }
1457    let obj = value
1458        .as_object()
1459        .ok_or_else(|| IrDriverError::InvalidIr(format!("expected object int arg, got {value}")))?;
1460    let vm_kind = obj.get("vm").and_then(Value::as_str).ok_or_else(|| {
1461        IrDriverError::InvalidIr(format!("object int arg has no 'vm' key: {value}"))
1462    })?;
1463    match vm_kind {
1464        "align" => {
1465            let v = obj
1466                .get("value")
1467                .ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
1468            Ok(CompiledIntArg::Static(json_as_u128(v)?))
1469        }
1470        "value->int" => {
1471            let inner = obj
1472                .get("value")
1473                .ok_or_else(|| IrDriverError::InvalidIr("value->int missing 'value'".into()))?;
1474            compile_int_arg(inner)
1475        }
1476        "ref" => {
1477            let inner = obj
1478                .get("value")
1479                .ok_or_else(|| IrDriverError::InvalidIr("ref missing 'value'".into()))?;
1480            match compile_ref_expr(inner)? {
1481                CompiledRefExpr::Literal(v) => Ok(CompiledIntArg::Static(json_as_u128(&v)?)),
1482                dynamic => Ok(CompiledIntArg::Ref(dynamic)),
1483            }
1484        }
1485        "add" => {
1486            let left = obj
1487                .get("left")
1488                .ok_or_else(|| IrDriverError::InvalidIr("vm:add missing 'left'".into()))?;
1489            let right = obj
1490                .get("right")
1491                .ok_or_else(|| IrDriverError::InvalidIr("vm:add missing 'right'".into()))?;
1492            let l = compile_int_arg(left)?;
1493            let r = compile_int_arg(right)?;
1494            match (l, r) {
1495                (CompiledIntArg::Static(lv), CompiledIntArg::Static(rv)) => {
1496                    let sum = lv.checked_add(rv).ok_or_else(|| {
1497                        IrDriverError::TypeMismatch(format!(
1498                            "vm:add overflow: {lv} + {rv} exceeds u128"
1499                        ))
1500                    })?;
1501                    Ok(CompiledIntArg::Static(sum))
1502                }
1503                (l, r) => Ok(CompiledIntArg::Add(Box::new(l), Box::new(r))),
1504            }
1505        }
1506        "max-sizeof" => {
1507            let type_obj = obj
1508                .get("type")
1509                .ok_or_else(|| IrDriverError::InvalidIr("vm:max-sizeof missing 'type'".into()))?;
1510            let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
1511                crate::ir::interp::decode_value_as(type_obj).map_err(|e| {
1512                    IrDriverError::InvalidIr(format!(
1513                        "vm:max-sizeof.type not a TypeDescriptor: {e}"
1514                    ))
1515                })?;
1516            let size = if let Some(plan) = FabPlan::compile(&descriptor) {
1517                plan.max_aligned_size()
1518            } else {
1519                use moonproof_ledger::transient_crypto::fab::AlignmentExt;
1520                encode_default(&descriptor)?.alignment.max_aligned_size()
1521            };
1522            Ok(CompiledIntArg::Static(size as u128))
1523        }
1524        other => Err(IrDriverError::unimplemented(format!(
1525            "vm wrapper '{other}' in int arg position"
1526        ))),
1527    }
1528}
1529
1530fn compile_path(value: &Value) -> Result<Vec<CompiledPathKey>> {
1531    let arr = value
1532        .as_array()
1533        .ok_or_else(|| IrDriverError::InvalidIr(format!("path not an array: {value}")))?;
1534    let mut out = Vec::with_capacity(arr.len());
1535    for elt in arr {
1536        out.push(compile_path_elt(elt)?);
1537    }
1538    Ok(out)
1539}
1540
1541fn compile_path_elt(value: &Value) -> Result<CompiledPathKey> {
1542    if value.as_str() == Some("@stack") {
1543        return Ok(CompiledPathKey::Static(Key::Stack));
1544    }
1545    let obj = value
1546        .as_object()
1547        .ok_or_else(|| IrDriverError::InvalidIr(format!("path elt not an object: {value}")))?;
1548    let vm_kind = obj
1549        .get("vm")
1550        .and_then(Value::as_str)
1551        .ok_or_else(|| IrDriverError::InvalidIr(format!("path elt has no 'vm' key: {value}")))?;
1552    match vm_kind {
1553        "align" => {
1554            let v = obj
1555                .get("value")
1556                .ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
1557            let bytes = obj.get("bytes").and_then(Value::as_u64).unwrap_or(1);
1558            let n = json_as_u128(v)?;
1559            let av = align_value_with_bytes(n, bytes)?;
1560            Ok(CompiledPathKey::Static(Key::Value(checked_key(av)?)))
1561        }
1562        "stack" => Ok(CompiledPathKey::Static(Key::Stack)),
1563        "ref" => {
1564            let inner = obj
1565                .get("value")
1566                .ok_or_else(|| IrDriverError::InvalidIr("path ref missing 'value'".into()))?;
1567            let expr = compile_ref_expr(inner)?;
1568            let plan = obj.get("type").map(compile_type_plan).transpose()?;
1569            if let CompiledRefExpr::Literal(val) = expr {
1570                let av = if let Some(ref p) = plan {
1571                    p.encode(&val)?
1572                } else {
1573                    align_value_with_bytes(json_as_u128(&val)?, 1)?
1574                };
1575                return Ok(CompiledPathKey::Static(Key::Value(checked_key(av)?)));
1576            }
1577            Ok(CompiledPathKey::DynamicRef { expr, plan })
1578        }
1579        other => Err(IrDriverError::unimplemented(format!(
1580            "path elt vm wrapper '{other}'"
1581        ))),
1582    }
1583}
1584
1585fn compile_state_value(value: &Value) -> Result<CompiledStateValue> {
1586    let obj = value
1587        .as_object()
1588        .ok_or_else(|| IrDriverError::InvalidIr(format!("state-value not an object: {value}")))?;
1589    if obj.get("vm").and_then(Value::as_str) != Some("state-value") {
1590        return Err(IrDriverError::InvalidIr(format!(
1591            "expected vm=state-value, got {value}"
1592        )));
1593    }
1594    let kind = obj
1595        .get("kind")
1596        .and_then(Value::as_str)
1597        .ok_or_else(|| IrDriverError::InvalidIr("state-value missing 'kind'".into()))?;
1598    match kind {
1599        "null" => Ok(CompiledStateValue::Static(checked_state_value(
1600            &StateValue::Null,
1601        )?)),
1602        "cell" | "adt" => {
1603            let inner = obj.get("value").ok_or_else(|| {
1604                IrDriverError::InvalidIr(format!("state-value {kind} missing 'value'"))
1605            })?;
1606            match compile_aligned_value(inner)? {
1607                CompiledAlignedValue::Static(av) => {
1608                    let checked = checked_cell_value(av)?;
1609                    Ok(CompiledStateValue::Static(StateValue::Cell(Sp::new(
1610                        checked,
1611                    ))))
1612                }
1613                dynamic => Ok(CompiledStateValue::Cell(dynamic)),
1614            }
1615        }
1616        "map" => {
1617            if let Some(entries) = obj.get("entries").and_then(Value::as_array) {
1618                if !entries.is_empty() {
1619                    return Err(IrDriverError::unimplemented(
1620                        "state-value map with non-empty entries (no contract shape uses this yet)",
1621                    ));
1622                }
1623            }
1624            Ok(CompiledStateValue::Static(checked_state_value(
1625                &StateValue::Map(moonproof_ledger::storage::storage::HashMap::new()),
1626            )?))
1627        }
1628        "array" => {
1629            let values = obj.get("values").and_then(Value::as_array).ok_or_else(|| {
1630                IrDriverError::InvalidIr("state-value array missing 'values'".into())
1631            })?;
1632            let mut items = Vec::with_capacity(values.len());
1633            let mut all_static = true;
1634            for v in values {
1635                let compiled = compile_state_value(v)?;
1636                if !matches!(compiled, CompiledStateValue::Static(_)) {
1637                    all_static = false;
1638                }
1639                items.push(compiled);
1640            }
1641            if all_static {
1642                let static_items: Vec<StateValue<InMemoryDB, AlignedValueChecked>> = items
1643                    .into_iter()
1644                    .map(|c| match c {
1645                        CompiledStateValue::Static(sv) => sv,
1646                        _ => unreachable!(),
1647                    })
1648                    .collect();
1649                Ok(CompiledStateValue::Static(StateValue::Array(
1650                    StorageArray::from(static_items),
1651                )))
1652            } else {
1653                Ok(CompiledStateValue::Array(items))
1654            }
1655        }
1656        "merkle-tree" => {
1657            let depth_v = obj
1658                .get("depth")
1659                .ok_or_else(|| IrDriverError::InvalidIr("merkle-tree missing 'depth'".into()))?;
1660            let depth_u128 = json_as_u128(depth_v)?;
1661            let depth = u8::try_from(depth_u128).map_err(|_| {
1662                IrDriverError::TypeMismatch(format!(
1663                    "merkle-tree depth out of u8 range: {depth_u128}"
1664                ))
1665            })?;
1666            if let Some(entries) = obj.get("entries").and_then(Value::as_array) {
1667                if !entries.is_empty() {
1668                    return Err(IrDriverError::unimplemented(
1669                        "state-value merkle-tree with pre-populated entries",
1670                    ));
1671                }
1672            }
1673            let tree = StateValue::BoundedMerkleTree(
1674                moonproof_ledger::transient_crypto::merkle_tree::MerkleTree::<(), InMemoryDB>::blank(
1675                    depth,
1676                ),
1677            );
1678            Ok(CompiledStateValue::Static(checked_state_value(&tree)?))
1679        }
1680        other => Err(IrDriverError::unimplemented(format!(
1681            "state-value kind '{other}'"
1682        ))),
1683    }
1684}
1685
1686fn compile_aligned_concat(values: &[Value]) -> Result<CompiledAlignedValue> {
1687    let mut items = Vec::with_capacity(values.len());
1688    let mut all_static = true;
1689    for v in values {
1690        let c = compile_aligned_value(v)?;
1691        if !matches!(c, CompiledAlignedValue::Static(_)) {
1692            all_static = false;
1693        }
1694        items.push(c);
1695    }
1696    if all_static {
1697        let avs: Vec<AlignedValue> = items
1698            .into_iter()
1699            .map(|c| match c {
1700                CompiledAlignedValue::Static(av) => av,
1701                _ => unreachable!(),
1702            })
1703            .collect();
1704        Ok(CompiledAlignedValue::Static(AlignedValue::concat(
1705            avs.iter(),
1706        )))
1707    } else {
1708        Ok(CompiledAlignedValue::AlignedConcat(items))
1709    }
1710}
1711
1712fn compile_aligned_value(value: &Value) -> Result<CompiledAlignedValue> {
1713    let obj = value
1714        .as_object()
1715        .ok_or_else(|| IrDriverError::InvalidIr(format!("aligned-value not an object: {value}")))?;
1716    let kind = obj
1717        .get("vm")
1718        .and_then(Value::as_str)
1719        .ok_or_else(|| IrDriverError::InvalidIr("aligned-value missing 'vm'".into()))?;
1720    match kind {
1721        "align" => {
1722            let v = obj
1723                .get("value")
1724                .ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
1725            let bytes = obj.get("bytes").and_then(Value::as_u64).unwrap_or(1);
1726            let n = json_as_u128(v)?;
1727            Ok(CompiledAlignedValue::Static(align_value_with_bytes(
1728                n, bytes,
1729            )?))
1730        }
1731        "ref" => {
1732            let type_obj = obj.get("type").ok_or_else(|| {
1733                IrDriverError::InvalidIr("aligned-value ref missing 'type'".into())
1734            })?;
1735            let inner = obj.get("value").ok_or_else(|| {
1736                IrDriverError::InvalidIr("aligned-value ref missing 'value'".into())
1737            })?;
1738            let plan = compile_type_plan(type_obj)?;
1739            let expr = compile_ref_expr(inner)?;
1740            if let CompiledRefExpr::Literal(val) = expr {
1741                return Ok(CompiledAlignedValue::Static(plan.encode(&val)?));
1742            }
1743            Ok(CompiledAlignedValue::Ref { expr, plan })
1744        }
1745        "null" => {
1746            let type_obj = obj.get("type").ok_or_else(|| {
1747                IrDriverError::InvalidIr("aligned-value null missing 'type'".into())
1748            })?;
1749            let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
1750                crate::ir::interp::decode_value_as(type_obj).map_err(|e| {
1751                    IrDriverError::InvalidIr(format!("null.type not a TypeDescriptor: {e}"))
1752                })?;
1753            Ok(CompiledAlignedValue::Static(encode_default(&descriptor)?))
1754        }
1755        "aligned-concat" => {
1756            let values = obj.get("values").and_then(Value::as_array).ok_or_else(|| {
1757                IrDriverError::InvalidIr("aligned-concat missing 'values' array".into())
1758            })?;
1759            compile_aligned_concat(values)
1760        }
1761        "coin-commit" => {
1762            let coin_inner = obj
1763                .get("coin")
1764                .ok_or_else(|| IrDriverError::InvalidIr("coin-commit missing 'coin'".into()))?;
1765            let recipient_inner = obj.get("recipient").ok_or_else(|| {
1766                IrDriverError::InvalidIr("coin-commit missing 'recipient'".into())
1767            })?;
1768            let coin = compile_aligned_value(coin_inner)?;
1769            let recipient = compile_aligned_value(recipient_inner)?;
1770            match (coin, recipient) {
1771                (CompiledAlignedValue::Static(c), CompiledAlignedValue::Static(r)) => {
1772                    Ok(CompiledAlignedValue::Static(coin_commit_aligned(&c, &r)?))
1773                }
1774                (coin, recipient) => Ok(CompiledAlignedValue::CoinCommit {
1775                    coin: Box::new(coin),
1776                    recipient: Box::new(recipient),
1777                }),
1778            }
1779        }
1780        "leaf-hash" => {
1781            let inner = obj
1782                .get("value")
1783                .ok_or_else(|| IrDriverError::InvalidIr("leaf-hash missing 'value'".into()))?;
1784            match compile_aligned_value(inner)? {
1785                CompiledAlignedValue::Static(av) => {
1786                    Ok(CompiledAlignedValue::Static(leaf_hash_aligned(av)))
1787                }
1788                dynamic => Ok(CompiledAlignedValue::LeafHash(Box::new(dynamic))),
1789            }
1790        }
1791        other => Err(IrDriverError::unimplemented(format!(
1792            "aligned-value vm wrapper '{other}'"
1793        ))),
1794    }
1795}
1796
1797impl CompiledRefExpr {
1798    fn resolve<'s>(&'s self, scope: &'s EvalScope<'_>) -> Result<Cow<'s, Value>> {
1799        match self {
1800            Self::Var(name) => scope.lookup_var(name),
1801            Self::Literal(v) => Ok(Cow::Borrowed(v)),
1802            Self::Expr(expr) => scope.resolve_expr(expr).map(Cow::Owned),
1803        }
1804    }
1805}
1806
1807impl CompiledIntArg {
1808    fn eval(&self, scope: &EvalScope<'_>) -> Result<u128> {
1809        match self {
1810            Self::Static(n) => Ok(*n),
1811            Self::Ref(expr) => {
1812                let resolved = expr.resolve(scope)?;
1813                json_as_u128(&resolved)
1814            }
1815            Self::Add(left, right) => {
1816                let l = left.eval(scope)?;
1817                let r = right.eval(scope)?;
1818                l.checked_add(r).ok_or_else(|| {
1819                    IrDriverError::TypeMismatch(format!("vm:add overflow: {l} + {r} exceeds u128"))
1820                })
1821            }
1822        }
1823    }
1824}
1825
1826impl CompiledAlignedValue {
1827    fn materialize(&self, scope: &EvalScope<'_>) -> Result<AlignedValue> {
1828        match self {
1829            Self::Static(av) => Ok(av.clone()),
1830            Self::Ref { expr, plan } => {
1831                let resolved = expr.resolve(scope)?;
1832                plan.encode(&resolved)
1833            }
1834            Self::AlignedConcat(items) => {
1835                let mut avs = Vec::with_capacity(items.len());
1836                for item in items {
1837                    avs.push(item.materialize(scope)?);
1838                }
1839                Ok(AlignedValue::concat(avs.iter()))
1840            }
1841            Self::CoinCommit { coin, recipient } => {
1842                let coin_av = coin.materialize(scope)?;
1843                let recipient_av = recipient.materialize(scope)?;
1844                coin_commit_aligned(&coin_av, &recipient_av)
1845            }
1846            Self::LeafHash(inner) => {
1847                let inner_av = inner.materialize(scope)?;
1848                Ok(leaf_hash_aligned(inner_av))
1849            }
1850        }
1851    }
1852}
1853
1854impl CompiledStateValue {
1855    fn materialize(
1856        &self,
1857        scope: &EvalScope<'_>,
1858    ) -> Result<StateValue<InMemoryDB, AlignedValueChecked>> {
1859        match self {
1860            Self::Static(sv) => Ok(sv.clone()),
1861            Self::Cell(cav) => {
1862                let av = cav.materialize(scope)?;
1863                let checked = checked_cell_value(av)?;
1864                Ok(StateValue::Cell(Sp::new(checked)))
1865            }
1866            Self::Array(items) => {
1867                let mut resolved = Vec::with_capacity(items.len());
1868                for item in items {
1869                    resolved.push(item.materialize(scope)?);
1870                }
1871                Ok(StateValue::Array(StorageArray::from(resolved)))
1872            }
1873        }
1874    }
1875}
1876
1877impl CompiledPathKey {
1878    fn materialize(&self, scope: &EvalScope<'_>) -> Result<Key> {
1879        match self {
1880            Self::Static(key) => Ok(key.clone()),
1881            Self::DynamicRef { expr, plan } => {
1882                let resolved = expr.resolve(scope)?;
1883                let av = if let Some(p) = plan {
1884                    p.encode(&resolved)?
1885                } else {
1886                    align_value_with_bytes(json_as_u128(&resolved)?, 1)?
1887                };
1888                Ok(Key::Value(checked_key(av)?))
1889            }
1890        }
1891    }
1892}
1893
1894impl CompiledOp {
1895    /// Materialize one pre-compiled VM instruction into a concrete ledger `Op`.
1896    pub fn materialize(&self, scope: &EvalScope<'_>) -> Result<Op<ResultModeGather, InMemoryDB>> {
1897        match self {
1898            Self::Static(op) => Ok(op.clone()),
1899            Self::Push { storage, value } => Ok(Op::Push {
1900                storage: *storage,
1901                value: value.materialize(scope)?,
1902            }),
1903            Self::Idx {
1904                cached,
1905                push_path,
1906                path,
1907            } => {
1908                let mut keys = Vec::with_capacity(path.len());
1909                for elt in path {
1910                    keys.push(elt.materialize(scope)?);
1911                }
1912                Ok(Op::Idx {
1913                    cached: *cached,
1914                    push_path: *push_path,
1915                    path: StorageArray::from(keys),
1916                })
1917            }
1918            Self::Ins { cached, n } => Ok(Op::Ins {
1919                cached: *cached,
1920                n: narrow_int("ins", "n", n.eval(scope)?)?,
1921            }),
1922            Self::Addi { immediate } => Ok(Op::Addi {
1923                immediate: narrow_int("addi", "immediate", immediate.eval(scope)?)?,
1924            }),
1925            Self::Subi { immediate } => Ok(Op::Subi {
1926                immediate: narrow_int("subi", "immediate", immediate.eval(scope)?)?,
1927            }),
1928            Self::Noop { n } => {
1929                let n_raw = n.eval(scope).unwrap_or(0);
1930                Ok(Op::Noop {
1931                    n: u32::try_from(n_raw).unwrap_or(0),
1932                })
1933            }
1934            Self::Dup { n } => Ok(Op::Dup {
1935                n: narrow_int("dup", "n", n.eval(scope)?)?,
1936            }),
1937            Self::Swap { n } => Ok(Op::Swap {
1938                n: narrow_int("swap", "n", n.eval(scope)?)?,
1939            }),
1940            Self::Concat { cached, n } => Ok(Op::Concat {
1941                cached: *cached,
1942                n: narrow_int("concat", "n", n.eval(scope)?)?,
1943            }),
1944            Self::Branch { skip } => Ok(Op::Branch {
1945                skip: narrow_int("branch", "skip", skip.eval(scope)?)?,
1946            }),
1947            Self::Jmp { skip } => Ok(Op::Jmp {
1948                skip: narrow_int("jmp", "skip", skip.eval(scope)?)?,
1949            }),
1950        }
1951    }
1952}
1953
1954// ===========================================================================
1955// Register-slot-bound compiled VM queries (zero HashMap lookup at runtime)
1956// ===========================================================================
1957
1958/// A [`CompiledLedgerQuery`] whose `vm:ref` variable references have been
1959/// resolved at bytecode compile time to dense register slot indices.
1960#[derive(Debug, Clone)]
1961pub(crate) struct SlotCompiledQuery {
1962    pub(crate) flags: QueryFlags,
1963    pub(crate) body: SlotQueryBody,
1964}
1965
1966#[derive(Debug, Clone)]
1967pub(crate) enum SlotQueryBody {
1968    Static(Box<[Op<ResultModeGather, InMemoryDB>]>),
1969    Dynamic(Box<[SlotCompiledOp]>),
1970}
1971
1972#[derive(Debug, Clone)]
1973pub(crate) enum SlotCompiledOp {
1974    Static(Op<ResultModeGather, InMemoryDB>),
1975    Push {
1976        storage: bool,
1977        value: SlotStateValue,
1978    },
1979    Idx {
1980        cached: bool,
1981        push_path: bool,
1982        path: Box<[SlotPathKey]>,
1983    },
1984    Ins {
1985        cached: bool,
1986        n: SlotIntArg,
1987    },
1988    Addi {
1989        immediate: SlotIntArg,
1990    },
1991    Subi {
1992        immediate: SlotIntArg,
1993    },
1994    Noop {
1995        n: SlotIntArg,
1996    },
1997    Dup {
1998        n: SlotIntArg,
1999    },
2000    Swap {
2001        n: SlotIntArg,
2002    },
2003    Concat {
2004        cached: bool,
2005        n: SlotIntArg,
2006    },
2007    Branch {
2008        skip: SlotIntArg,
2009    },
2010    Jmp {
2011        skip: SlotIntArg,
2012    },
2013}
2014
2015#[derive(Debug, Clone)]
2016pub(crate) enum SlotStateValue {
2017    Static(StateValue<InMemoryDB, AlignedValueChecked>),
2018    Cell(SlotAlignedValue),
2019    Array(Box<[SlotStateValue]>),
2020}
2021
2022#[derive(Debug, Clone)]
2023pub(crate) enum SlotAlignedValue {
2024    Static(AlignedValue),
2025    Ref {
2026        expr: SlotRefExpr,
2027        plan: FabPlan,
2028    },
2029    AlignedConcat(Box<[SlotAlignedValue]>),
2030    CoinCommit {
2031        coin: Box<SlotAlignedValue>,
2032        recipient: Box<SlotAlignedValue>,
2033    },
2034    LeafHash(Box<SlotAlignedValue>),
2035}
2036
2037#[derive(Debug, Clone)]
2038pub(crate) enum SlotPathKey {
2039    Static(Key),
2040    DynamicRef {
2041        expr: SlotRefExpr,
2042        plan: Option<FabPlan>,
2043    },
2044}
2045
2046#[derive(Debug, Clone)]
2047pub(crate) enum SlotIntArg {
2048    Static(u128),
2049    Ref(SlotRefExpr),
2050    Add(Box<SlotIntArg>, Box<SlotIntArg>),
2051}
2052
2053#[derive(Debug, Clone)]
2054pub(crate) enum SlotRefExpr {
2055    Slot(u16),
2056    Const(VmVal),
2057    EltRef {
2058        base: Box<SlotRefExpr>,
2059        field: Arc<str>,
2060    },
2061    NewStruct {
2062        fields: Box<[Arc<str>]>,
2063        args: Box<[SlotRefExpr]>,
2064    },
2065    NewArray(Box<[SlotRefExpr]>),
2066}
2067
2068impl SlotCompiledQuery {
2069    /// Bind every variable in `query` to a register slot via `resolve_var`.
2070    /// Returns `None` if any `vm:ref` expression cannot be statically bound.
2071    #[must_use]
2072    pub(crate) fn from_compiled(
2073        query: &CompiledLedgerQuery,
2074        resolve_var: &impl Fn(&str) -> Option<u16>,
2075    ) -> Option<Self> {
2076        let body = match &query.body {
2077            CompiledQueryBody::Static(ops) => SlotQueryBody::Static(ops.clone().into_boxed_slice()),
2078            CompiledQueryBody::Dynamic(ops) => {
2079                let mut bound = Vec::with_capacity(ops.len());
2080                for op in ops {
2081                    bound.push(bind_slot_op(op, resolve_var)?);
2082                }
2083                SlotQueryBody::Dynamic(bound.into_boxed_slice())
2084            }
2085        };
2086        Some(Self {
2087            flags: query.flags,
2088            body,
2089        })
2090    }
2091
2092    /// Materialize dynamic ops directly from a slice of frame register slots.
2093    pub(crate) fn materialize_dynamic(
2094        ops: &[SlotCompiledOp],
2095        frame: &[VmVal],
2096    ) -> Result<Vec<Op<ResultModeGather, InMemoryDB>>> {
2097        let mut out = Vec::with_capacity(ops.len());
2098        for op in ops {
2099            out.push(op.materialize(frame)?);
2100        }
2101        Ok(out)
2102    }
2103}
2104
2105fn bind_slot_op(
2106    op: &CompiledOp,
2107    resolve_var: &impl Fn(&str) -> Option<u16>,
2108) -> Option<SlotCompiledOp> {
2109    Some(match op {
2110        CompiledOp::Static(raw) => SlotCompiledOp::Static(raw.clone()),
2111        CompiledOp::Push { storage, value } => SlotCompiledOp::Push {
2112            storage: *storage,
2113            value: bind_slot_state_value(value, resolve_var)?,
2114        },
2115        CompiledOp::Idx {
2116            cached,
2117            push_path,
2118            path,
2119        } => {
2120            let mut keys = Vec::with_capacity(path.len());
2121            for k in path {
2122                keys.push(bind_slot_path_key(k, resolve_var)?);
2123            }
2124            SlotCompiledOp::Idx {
2125                cached: *cached,
2126                push_path: *push_path,
2127                path: keys.into_boxed_slice(),
2128            }
2129        }
2130        CompiledOp::Ins { cached, n } => SlotCompiledOp::Ins {
2131            cached: *cached,
2132            n: bind_slot_int_arg(n, resolve_var)?,
2133        },
2134        CompiledOp::Addi { immediate } => SlotCompiledOp::Addi {
2135            immediate: bind_slot_int_arg(immediate, resolve_var)?,
2136        },
2137        CompiledOp::Subi { immediate } => SlotCompiledOp::Subi {
2138            immediate: bind_slot_int_arg(immediate, resolve_var)?,
2139        },
2140        CompiledOp::Noop { n } => SlotCompiledOp::Noop {
2141            n: bind_slot_int_arg(n, resolve_var)?,
2142        },
2143        CompiledOp::Dup { n } => SlotCompiledOp::Dup {
2144            n: bind_slot_int_arg(n, resolve_var)?,
2145        },
2146        CompiledOp::Swap { n } => SlotCompiledOp::Swap {
2147            n: bind_slot_int_arg(n, resolve_var)?,
2148        },
2149        CompiledOp::Concat { cached, n } => SlotCompiledOp::Concat {
2150            cached: *cached,
2151            n: bind_slot_int_arg(n, resolve_var)?,
2152        },
2153        CompiledOp::Branch { skip } => SlotCompiledOp::Branch {
2154            skip: bind_slot_int_arg(skip, resolve_var)?,
2155        },
2156        CompiledOp::Jmp { skip } => SlotCompiledOp::Jmp {
2157            skip: bind_slot_int_arg(skip, resolve_var)?,
2158        },
2159    })
2160}
2161
2162fn bind_slot_state_value(
2163    sv: &CompiledStateValue,
2164    resolve_var: &impl Fn(&str) -> Option<u16>,
2165) -> Option<SlotStateValue> {
2166    Some(match sv {
2167        CompiledStateValue::Static(s) => SlotStateValue::Static(s.clone()),
2168        CompiledStateValue::Cell(av) => {
2169            SlotStateValue::Cell(bind_slot_aligned_value(av, resolve_var)?)
2170        }
2171        CompiledStateValue::Array(items) => {
2172            let mut out = Vec::with_capacity(items.len());
2173            for item in items {
2174                out.push(bind_slot_state_value(item, resolve_var)?);
2175            }
2176            SlotStateValue::Array(out.into_boxed_slice())
2177        }
2178    })
2179}
2180
2181fn bind_slot_aligned_value(
2182    av: &CompiledAlignedValue,
2183    resolve_var: &impl Fn(&str) -> Option<u16>,
2184) -> Option<SlotAlignedValue> {
2185    Some(match av {
2186        CompiledAlignedValue::Static(s) => SlotAlignedValue::Static(s.clone()),
2187        CompiledAlignedValue::Ref { expr, plan } => SlotAlignedValue::Ref {
2188            expr: bind_slot_ref_expr(expr, resolve_var)?,
2189            plan: plan.clone(),
2190        },
2191        CompiledAlignedValue::AlignedConcat(items) => {
2192            let mut out = Vec::with_capacity(items.len());
2193            for item in items {
2194                out.push(bind_slot_aligned_value(item, resolve_var)?);
2195            }
2196            SlotAlignedValue::AlignedConcat(out.into_boxed_slice())
2197        }
2198        CompiledAlignedValue::CoinCommit { coin, recipient } => SlotAlignedValue::CoinCommit {
2199            coin: Box::new(bind_slot_aligned_value(coin, resolve_var)?),
2200            recipient: Box::new(bind_slot_aligned_value(recipient, resolve_var)?),
2201        },
2202        CompiledAlignedValue::LeafHash(inner) => {
2203            SlotAlignedValue::LeafHash(Box::new(bind_slot_aligned_value(inner, resolve_var)?))
2204        }
2205    })
2206}
2207
2208fn bind_slot_path_key(
2209    key: &CompiledPathKey,
2210    resolve_var: &impl Fn(&str) -> Option<u16>,
2211) -> Option<SlotPathKey> {
2212    Some(match key {
2213        CompiledPathKey::Static(k) => SlotPathKey::Static(k.clone()),
2214        CompiledPathKey::DynamicRef { expr, plan } => SlotPathKey::DynamicRef {
2215            expr: bind_slot_ref_expr(expr, resolve_var)?,
2216            plan: plan.clone(),
2217        },
2218    })
2219}
2220
2221fn bind_slot_int_arg(
2222    arg: &CompiledIntArg,
2223    resolve_var: &impl Fn(&str) -> Option<u16>,
2224) -> Option<SlotIntArg> {
2225    Some(match arg {
2226        CompiledIntArg::Static(n) => SlotIntArg::Static(*n),
2227        CompiledIntArg::Ref(expr) => SlotIntArg::Ref(bind_slot_ref_expr(expr, resolve_var)?),
2228        CompiledIntArg::Add(l, r) => SlotIntArg::Add(
2229            Box::new(bind_slot_int_arg(l, resolve_var)?),
2230            Box::new(bind_slot_int_arg(r, resolve_var)?),
2231        ),
2232    })
2233}
2234
2235fn bind_slot_ref_expr(
2236    expr: &CompiledRefExpr,
2237    resolve_var: &impl Fn(&str) -> Option<u16>,
2238) -> Option<SlotRefExpr> {
2239    match expr {
2240        CompiledRefExpr::Var(name) => Some(SlotRefExpr::Slot(resolve_var(name)?)),
2241        CompiledRefExpr::Literal(v) => Some(SlotRefExpr::Const(VmVal::from_runtime_value(v))),
2242        CompiledRefExpr::Expr(e) => bind_slot_ir_expr(e, resolve_var),
2243    }
2244}
2245
2246fn bind_slot_ir_expr(
2247    expr: &moonproof_runtime_ir::ir::Expression,
2248    resolve_var: &impl Fn(&str) -> Option<u16>,
2249) -> Option<SlotRefExpr> {
2250    use moonproof_runtime_ir::ir::{Expression as E, TypeDescriptor as T};
2251    match expr {
2252        E::Var { name } => Some(SlotRefExpr::Slot(resolve_var(name)?)),
2253        E::Literal { value } => Some(SlotRefExpr::Const(VmVal::from_runtime_value(value))),
2254        E::EnumRef { of_type, variant } => match of_type {
2255            T::Enum { elements, .. } if elements.iter().any(|v| v == variant) => {
2256                Some(SlotRefExpr::Const(VmVal::Str(Arc::from(variant.as_str()))))
2257            }
2258            _ => None,
2259        },
2260        E::Default { of_type } => {
2261            let v = super::vm_val::default_vm_val(of_type).ok()?;
2262            Some(SlotRefExpr::Const(v))
2263        }
2264        E::EltRef { value, field, .. } => Some(SlotRefExpr::EltRef {
2265            base: Box::new(bind_slot_ir_expr(value, resolve_var)?),
2266            field: Arc::from(field.as_str()),
2267        }),
2268        E::New { of_type, arguments } => {
2269            let mut ty = of_type;
2270            while let T::Alias { of, .. } = ty {
2271                ty = of;
2272            }
2273            let mut args = Vec::with_capacity(arguments.len());
2274            for a in arguments {
2275                args.push(bind_slot_ir_expr(a, resolve_var)?);
2276            }
2277            match ty {
2278                T::Struct { elements, .. } if elements.len() == args.len() => {
2279                    let fields: Vec<Arc<str>> = elements
2280                        .iter()
2281                        .map(|f| Arc::from(f.name.as_str()))
2282                        .collect();
2283                    Some(SlotRefExpr::NewStruct {
2284                        fields: fields.into_boxed_slice(),
2285                        args: args.into_boxed_slice(),
2286                    })
2287                }
2288                T::Tuple { types } if types.len() == args.len() => {
2289                    Some(SlotRefExpr::NewArray(args.into_boxed_slice()))
2290                }
2291                T::Vector { length, .. } if *length as usize == args.len() => {
2292                    Some(SlotRefExpr::NewArray(args.into_boxed_slice()))
2293                }
2294                _ => None,
2295            }
2296        }
2297        _ => None,
2298    }
2299}
2300
2301impl SlotRefExpr {
2302    #[inline]
2303    fn resolve<'a>(&'a self, frame: &'a [VmVal]) -> Result<Cow<'a, VmVal>> {
2304        match self {
2305            Self::Slot(slot) => Ok(Cow::Borrowed(&frame[usize::from(*slot)])),
2306            Self::Const(v) => Ok(Cow::Borrowed(v)),
2307            Self::EltRef { base, field } => {
2308                let v = base.resolve(frame)?;
2309                let found = v.get_field(field, None).ok_or_else(|| {
2310                    IrDriverError::TypeMismatch(format!(
2311                        "field '{field}' not in struct {}",
2312                        v.to_runtime_value()
2313                    ))
2314                })?;
2315                Ok(Cow::Owned(found.clone()))
2316            }
2317            Self::NewStruct { fields, args } => {
2318                let mut out = Vec::with_capacity(fields.len());
2319                for (name, arg) in fields.iter().zip(args.iter()) {
2320                    out.push((Arc::clone(name), arg.resolve(frame)?.into_owned()));
2321                }
2322                Ok(Cow::Owned(VmVal::Object(Arc::from(out))))
2323            }
2324            Self::NewArray(args) => {
2325                let mut out = Vec::with_capacity(args.len());
2326                for arg in args {
2327                    out.push(arg.resolve(frame)?.into_owned());
2328                }
2329                Ok(Cow::Owned(VmVal::Array(Arc::from(out))))
2330            }
2331        }
2332    }
2333}
2334
2335impl SlotIntArg {
2336    fn eval(&self, frame: &[VmVal]) -> Result<u128> {
2337        match self {
2338            Self::Static(n) => Ok(*n),
2339            Self::Ref(expr) => expr.resolve(frame)?.as_u128_parsed(),
2340            Self::Add(left, right) => {
2341                let l = left.eval(frame)?;
2342                let r = right.eval(frame)?;
2343                l.checked_add(r).ok_or_else(|| {
2344                    IrDriverError::TypeMismatch(format!("vm:add overflow: {l} + {r} exceeds u128"))
2345                })
2346            }
2347        }
2348    }
2349}
2350
2351impl SlotAlignedValue {
2352    fn materialize(&self, frame: &[VmVal]) -> Result<AlignedValue> {
2353        match self {
2354            Self::Static(av) => Ok(av.clone()),
2355            Self::Ref { expr, plan } => {
2356                let resolved = expr.resolve(frame)?;
2357                plan.encode_vm_val(&resolved)
2358            }
2359            Self::AlignedConcat(items) => {
2360                let mut avs = Vec::with_capacity(items.len());
2361                for item in items {
2362                    avs.push(item.materialize(frame)?);
2363                }
2364                Ok(AlignedValue::concat(avs.iter()))
2365            }
2366            Self::CoinCommit { coin, recipient } => {
2367                let coin_av = coin.materialize(frame)?;
2368                let recipient_av = recipient.materialize(frame)?;
2369                coin_commit_aligned(&coin_av, &recipient_av)
2370            }
2371            Self::LeafHash(inner) => {
2372                let inner_av = inner.materialize(frame)?;
2373                Ok(leaf_hash_aligned(inner_av))
2374            }
2375        }
2376    }
2377}
2378
2379impl SlotStateValue {
2380    fn materialize(&self, frame: &[VmVal]) -> Result<StateValue<InMemoryDB, AlignedValueChecked>> {
2381        match self {
2382            Self::Static(sv) => Ok(sv.clone()),
2383            Self::Cell(cav) => {
2384                let av = cav.materialize(frame)?;
2385                let checked = checked_cell_value(av)?;
2386                Ok(StateValue::Cell(Sp::new(checked)))
2387            }
2388            Self::Array(items) => {
2389                let mut resolved = Vec::with_capacity(items.len());
2390                for item in items {
2391                    resolved.push(item.materialize(frame)?);
2392                }
2393                Ok(StateValue::Array(StorageArray::from(resolved)))
2394            }
2395        }
2396    }
2397}
2398
2399impl SlotPathKey {
2400    fn materialize(&self, frame: &[VmVal]) -> Result<Key> {
2401        match self {
2402            Self::Static(key) => Ok(key.clone()),
2403            Self::DynamicRef { expr, plan } => {
2404                let resolved = expr.resolve(frame)?;
2405                let av = if let Some(p) = plan {
2406                    p.encode_vm_val(&resolved)?
2407                } else {
2408                    align_value_with_bytes(resolved.as_u128_parsed()?, 1)?
2409                };
2410                Ok(Key::Value(checked_key(av)?))
2411            }
2412        }
2413    }
2414}
2415
2416impl SlotCompiledOp {
2417    fn materialize(&self, frame: &[VmVal]) -> Result<Op<ResultModeGather, InMemoryDB>> {
2418        match self {
2419            Self::Static(op) => Ok(op.clone()),
2420            Self::Push { storage, value } => Ok(Op::Push {
2421                storage: *storage,
2422                value: value.materialize(frame)?,
2423            }),
2424            Self::Idx {
2425                cached,
2426                push_path,
2427                path,
2428            } => {
2429                let mut keys = Vec::with_capacity(path.len());
2430                for elt in path {
2431                    keys.push(elt.materialize(frame)?);
2432                }
2433                Ok(Op::Idx {
2434                    cached: *cached,
2435                    push_path: *push_path,
2436                    path: StorageArray::from(keys),
2437                })
2438            }
2439            Self::Ins { cached, n } => Ok(Op::Ins {
2440                cached: *cached,
2441                n: narrow_int("ins", "n", n.eval(frame)?)?,
2442            }),
2443            Self::Addi { immediate } => Ok(Op::Addi {
2444                immediate: narrow_int("addi", "immediate", immediate.eval(frame)?)?,
2445            }),
2446            Self::Subi { immediate } => Ok(Op::Subi {
2447                immediate: narrow_int("subi", "immediate", immediate.eval(frame)?)?,
2448            }),
2449            Self::Noop { n } => {
2450                let n_raw = n.eval(frame).unwrap_or(0);
2451                Ok(Op::Noop {
2452                    n: u32::try_from(n_raw).unwrap_or(0),
2453                })
2454            }
2455            Self::Dup { n } => Ok(Op::Dup {
2456                n: narrow_int("dup", "n", n.eval(frame)?)?,
2457            }),
2458            Self::Swap { n } => Ok(Op::Swap {
2459                n: narrow_int("swap", "n", n.eval(frame)?)?,
2460            }),
2461            Self::Concat { cached, n } => Ok(Op::Concat {
2462                cached: *cached,
2463                n: narrow_int("concat", "n", n.eval(frame)?)?,
2464            }),
2465            Self::Branch { skip } => Ok(Op::Branch {
2466                skip: narrow_int("branch", "skip", skip.eval(frame)?)?,
2467            }),
2468            Self::Jmp { skip } => Ok(Op::Jmp {
2469                skip: narrow_int("jmp", "skip", skip.eval(frame)?)?,
2470            }),
2471        }
2472    }
2473}
2474
2475#[cfg(test)]
2476mod tests {
2477    use super::*;
2478    use moonproof_ledger::base_crypto::fab::{
2479        Alignment, AlignmentAtom, Value as FabValue, ValueAtom,
2480    };
2481
2482    /// A `Field` atom of 32 `0xff` bytes, far above the field modulus,
2483    /// so it aliases a smaller value under modular reduction.
2484    fn oversized_field() -> AlignedValue {
2485        AlignedValue::new(
2486            FabValue(vec![ValueAtom(vec![0xff; 32])]),
2487            Alignment::singleton(AlignmentAtom::Field),
2488        )
2489        .expect("32 bytes fit a field atom's alignment")
2490    }
2491
2492    #[test]
2493    fn checked_key_accepts_a_canonical_value() {
2494        assert!(checked_key(AlignedValue::from(7u8)).is_ok());
2495    }
2496
2497    #[test]
2498    fn checked_key_refuses_a_field_atom_above_the_modulus() {
2499        assert!(matches!(
2500            checked_key(oversized_field()),
2501            Err(IrDriverError::InvalidIr(_))
2502        ));
2503    }
2504
2505    #[test]
2506    fn checked_state_value_accepts_a_canonical_cell() {
2507        let cell = StateValue::Cell(Sp::new(AlignedValue::from(7u8)));
2508        assert!(checked_state_value(&cell).is_ok());
2509    }
2510
2511    #[test]
2512    fn checked_state_value_refuses_a_non_canonical_cell() {
2513        let cell = StateValue::Cell(Sp::new(oversized_field()));
2514        assert!(matches!(
2515            checked_state_value(&cell),
2516            Err(IrDriverError::InvalidIr(_))
2517        ));
2518    }
2519
2520    #[test]
2521    fn analyze_ops_classifies_read_write_context_effects_and_branches() {
2522        let key0 = Key::Value(checked_key(AlignedValue::from(0u8)).unwrap());
2523
2524        // Read-only cell read: Dup(0) -> Idx([0]) -> Popeq
2525        let read_ops = vec![
2526            Op::Dup { n: 0 },
2527            Op::Idx {
2528                cached: false,
2529                push_path: false,
2530                path: StorageArray::from(vec![key0.clone()]),
2531            },
2532            Op::Popeq {
2533                cached: false,
2534                result: (),
2535            },
2536        ];
2537        assert_eq!(
2538            analyze_ops(&read_ops),
2539            QueryFlags {
2540                reads_context: false,
2541                touches_effects: false,
2542                mutates_state: false,
2543            }
2544        );
2545
2546        // State mutation: Idx(push_path: true) -> Push -> Ins(1)
2547        let write_ops = vec![
2548            Op::Idx {
2549                cached: false,
2550                push_path: true,
2551                path: StorageArray::from(vec![key0.clone()]),
2552            },
2553            Op::Push {
2554                storage: true,
2555                value: checked_state_value(&StateValue::Cell(Sp::new(AlignedValue::from(1u8))))
2556                    .unwrap(),
2557            },
2558            Op::Ins {
2559                cached: false,
2560                n: 1,
2561            },
2562        ];
2563        assert_eq!(
2564            analyze_ops(&write_ops),
2565            QueryFlags {
2566                reads_context: false,
2567                touches_effects: false,
2568                mutates_state: true,
2569            }
2570        );
2571
2572        // Context read: Dup(2) reaches stack index 0
2573        let ctx_ops = vec![
2574            Op::Dup { n: 2 },
2575            Op::Idx {
2576                cached: true,
2577                push_path: false,
2578                path: StorageArray::from(vec![key0]),
2579            },
2580            Op::Popeq {
2581                cached: true,
2582                result: (),
2583            },
2584        ];
2585        assert_eq!(
2586            analyze_ops(&ctx_ops),
2587            QueryFlags {
2588                reads_context: true,
2589                touches_effects: false,
2590                mutates_state: false,
2591            }
2592        );
2593
2594        // Effects touch: Swap(0) at height 3 touches index 1 and index 2
2595        let eff_ops = vec![Op::Swap { n: 0 }, Op::Swap { n: 0 }];
2596        assert!(analyze_ops(&eff_ops).touches_effects);
2597        assert!(!analyze_ops(&eff_ops).reads_context);
2598
2599        // Control flow bails conservatively to ALL
2600        let branch_ops = vec![
2601            Op::Push {
2602                storage: false,
2603                value: checked_state_value(&StateValue::Cell(Sp::new(AlignedValue::from(true))))
2604                    .unwrap(),
2605            },
2606            Op::Branch { skip: 0 },
2607        ];
2608        assert_eq!(analyze_ops(&branch_ops), QueryFlags::ALL);
2609    }
2610}