Skip to main content

moonproof_runtime_ir/
ir.rs

1//! Typed IR mirroring the contract.mpir schema 1:1.
2//!
3//! The JSON schema is specified at `compact/doc/runtime-ir.md`.  Every
4//! variant here corresponds to exactly one shape produced by the
5//! emitter pass `compiler/runtime-ir-passes.ss`.
6
7use ethnum::I256;
8use indexmap::IndexMap;
9use serde::de::{self, Visitor};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11
12use crate::RuntimeValue;
13
14/// An integer literal as it appears anywhere in the runtime IR.
15///
16/// Newtype over [`ethnum::I256`], following the same precedent as
17/// [`moonproof_wallet::Amount`] (see `crates/wallet/src/types.rs`):
18/// 256 bits is wide enough for any Compact `Uint<128>` (the largest
19/// fixed-width unsigned type the language supports), stack-allocated
20/// and `Copy`, ~2-3× the cost of `i128` per arithmetic op without the
21/// soundness gap that smaller types have for full-range u128 inputs.
22///
23/// The IR-emitter pass writes integer literals two ways depending on
24/// magnitude — JSON `number` for values in JSON's safe integer range
25/// (±2^53), decimal `string` for anything wider so the wire format
26/// never silently truncates a big int.  The deserializer here accepts
27/// both; the serializer emits a `number` if it fits in `i64` and a
28/// string otherwise (matching the emitter's convention).
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
30pub struct IntLit(pub I256);
31
32impl IntLit {
33    pub const ZERO: Self = Self(I256::ZERO);
34    pub const ONE: Self = Self(I256::ONE);
35
36    #[must_use]
37    pub fn from_i128(v: i128) -> Self {
38        Self(I256::from(v))
39    }
40
41    #[must_use]
42    pub fn from_u128(v: u128) -> Self {
43        Self(I256::from(v))
44    }
45
46    /// Try to render as a `u128`. Returns `None` if negative or > 2^128 − 1.
47    #[must_use]
48    pub fn as_u128(&self) -> Option<u128> {
49        if self.0 < I256::ZERO {
50            return None;
51        }
52        let (hi, lo) = self.0.into_words();
53        if hi != 0 {
54            return None;
55        }
56        Some(u128::from_ne_bytes(lo.to_ne_bytes()))
57    }
58
59    /// Try to render as an `i128`. Returns `None` if out of `i128` range.
60    #[must_use]
61    pub fn as_i128(&self) -> Option<i128> {
62        let min = I256::from(i128::MIN);
63        let max = I256::from(i128::MAX);
64        if self.0 < min || self.0 > max {
65            return None;
66        }
67        let (_hi, lo) = self.0.into_words();
68        Some(lo)
69    }
70
71    /// Try to render as a `u32` (used for VM-op `n` / `length` fields).
72    #[must_use]
73    pub fn as_u32(&self) -> Option<u32> {
74        self.as_u128().and_then(|v| u32::try_from(v).ok())
75    }
76
77    /// Try to render as a `u64`.
78    #[must_use]
79    pub fn as_u64(&self) -> Option<u64> {
80        self.as_u128().and_then(|v| u64::try_from(v).ok())
81    }
82}
83
84/// A type as a person reads it, in Compact's spelling: `Uint<0..255>`,
85/// `Bytes<32>`, `Map<Field, Boolean>`, `Struct<Point>`.
86impl std::fmt::Display for TypeDescriptor {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        let joined = |types: &[TypeDescriptor]| {
89            types
90                .iter()
91                .map(ToString::to_string)
92                .collect::<Vec<_>>()
93                .join(", ")
94        };
95        match self {
96            Self::Boolean => f.write_str("Boolean"),
97            Self::Field => f.write_str("Field"),
98            Self::JubjubScalar => f.write_str("JubjubScalar"),
99            Self::Secp256k1Base => f.write_str("Secp256k1Base"),
100            Self::Secp256k1Scalar => f.write_str("Secp256k1Scalar"),
101            Self::Secp256r1Base => f.write_str("Secp256r1Base"),
102            Self::Secp256r1Scalar => f.write_str("Secp256r1Scalar"),
103            Self::Curve25519Base => f.write_str("Curve25519Base"),
104            Self::Curve25519Scalar => f.write_str("Curve25519Scalar"),
105            Self::JubjubPoint => f.write_str("JubjubPoint"),
106            Self::Secp256k1Point => f.write_str("Secp256k1Point"),
107            Self::Secp256r1Point => f.write_str("Secp256r1Point"),
108            Self::Curve25519Point => f.write_str("Curve25519Point"),
109            Self::Uint { maxval, .. } => write!(f, "Uint<0..{maxval}>"),
110            Self::Bytes { length } => write!(f, "Bytes<{length}>"),
111            Self::Opaque { ts_type } => write!(f, "Opaque<{ts_type}>"),
112            Self::Tuple { types } => write!(f, "Tuple<{}>", joined(types)),
113            Self::Vector { length, elt_type } => write!(f, "Vector<{length}, {elt_type}>"),
114            Self::Set { of } => write!(f, "Set<{of}>"),
115            Self::List { of } => write!(f, "List<{of}>"),
116            Self::Map { key, value } => write!(f, "Map<{key}, {value}>"),
117            Self::MerkleTree { depth, of } => write!(f, "MerkleTree<{depth}, {of}>"),
118            Self::HistoricMerkleTree { depth, of } => {
119                write!(f, "HistoricMerkleTree<{depth}, {of}>")
120            }
121            Self::Counter => f.write_str("Counter"),
122            Self::Cell { of } => write!(f, "Cell<{of}>"),
123            Self::Struct { name, .. } => write!(f, "Struct<{name}>"),
124            Self::Enum { name, .. } => write!(f, "Enum<{name}>"),
125            Self::Alias { name, .. } => write!(f, "Alias<{name}>"),
126            Self::Contract { name, .. } => write!(f, "Contract<{name}>"),
127            Self::Unknown => f.write_str("Unknown"),
128        }
129    }
130}
131
132impl std::fmt::Display for IntLit {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        write!(f, "{}", self.0)
135    }
136}
137
138impl Serialize for IntLit {
139    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
140        match self.as_i128().and_then(|v| i64::try_from(v).ok()) {
141            // Fits in i64 — emit as a JSON number.
142            Some(v) => s.serialize_i64(v),
143            None => s.serialize_str(&self.0.to_string()),
144        }
145    }
146}
147
148impl<'de> Deserialize<'de> for IntLit {
149    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
150        struct V;
151        impl Visitor<'_> for V {
152            type Value = IntLit;
153            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154                f.write_str("an integer (JSON number or decimal string)")
155            }
156            fn visit_u64<E: de::Error>(self, v: u64) -> Result<IntLit, E> {
157                Ok(IntLit(I256::from(v)))
158            }
159            fn visit_i64<E: de::Error>(self, v: i64) -> Result<IntLit, E> {
160                Ok(IntLit(I256::from(v)))
161            }
162            fn visit_u128<E: de::Error>(self, v: u128) -> Result<IntLit, E> {
163                Ok(IntLit(I256::from(v)))
164            }
165            fn visit_i128<E: de::Error>(self, v: i128) -> Result<IntLit, E> {
166                Ok(IntLit(I256::from(v)))
167            }
168            fn visit_str<E: de::Error>(self, v: &str) -> Result<IntLit, E> {
169                v.parse::<I256>()
170                    .map(IntLit)
171                    .map_err(|e| E::custom(format!("invalid integer literal '{v}': {e}")))
172            }
173            fn visit_string<E: de::Error>(self, v: String) -> Result<IntLit, E> {
174                self.visit_str(&v)
175            }
176        }
177        d.deserialize_any(V)
178    }
179}
180
181// ===========================================================================
182// Top-level
183// ===========================================================================
184
185#[derive(Debug, Clone, Serialize, Deserialize)]
186pub struct MoonIr {
187    #[serde(rename = "schema-version")]
188    pub schema_version: u32,
189    #[serde(rename = "compiler-version")]
190    pub compiler_version: String,
191    #[serde(rename = "language-version")]
192    pub language_version: String,
193    #[serde(rename = "runtime-version")]
194    pub runtime_version: String,
195
196    /// Subcontract types the contract declares. A contract passed only
197    /// as a circuit argument never reaches a ledger field, so this is
198    /// the only record of its circuit signatures. Each entry is a
199    /// [`TypeDescriptor::Contract`].
200    #[serde(default)]
201    pub contracts: Vec<TypeDescriptor>,
202    #[serde(default)]
203    pub ledger: Vec<LedgerField>,
204    #[serde(default)]
205    pub witnesses: Vec<Witness>,
206    #[serde(default)]
207    pub natives: Vec<Native>,
208    #[serde(default)]
209    pub circuits: Vec<CircuitBody>,
210    #[serde(default)]
211    pub descriptors: IndexMap<String, TypeDescriptor>,
212    pub constructor: Constructor,
213    #[serde(rename = "external-contracts", default)]
214    pub external_contracts: Vec<RuntimeValue>,
215    #[serde(rename = "pure-circuits", default)]
216    pub pure_circuits: Vec<RuntimeValue>,
217
218    /// Source frontend identification (schema v3, optional).
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub frontend: Option<FrontendMeta>,
221    /// Source file & span mapping for diagnostics and debugging (schema v3, optional).
222    #[serde(
223        rename = "debug-info",
224        default,
225        skip_serializing_if = "Option::is_none"
226    )]
227    pub debug_info: Option<DebugInfo>,
228    /// Governance and capability-model declarations (schema v3, optional).
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub capabilities: Option<CapabilitiesMeta>,
231    /// Multi-step workflow declarations such as Pact `defpact` (schema v3, optional).
232    #[serde(default, skip_serializing_if = "Vec::is_empty")]
233    pub workflows: Vec<WorkflowMeta>,
234    /// Static privacy classification and circuit resource bounds (schema v3, optional).
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub privacy: Option<PrivacyMeta>,
237    /// Semantic roles attached to descriptor keys for frontend-rich types
238    /// lowered onto core IR primitives (schema v3, optional).
239    #[serde(
240        rename = "type-roles",
241        default,
242        skip_serializing_if = "IndexMap::is_empty"
243    )]
244    pub type_roles: IndexMap<String, SemanticTypeRole>,
245}
246
247impl MoonIr {
248    /// Construct an empty schema-v3 [`MoonIr`] with default constructor
249    /// and no optional metadata populated.
250    #[must_use]
251    pub fn new_v3(
252        compiler_version: impl Into<String>,
253        language_version: impl Into<String>,
254        runtime_version: impl Into<String>,
255    ) -> Self {
256        Self {
257            schema_version: crate::loader::SUPPORTED_SCHEMA_VERSION,
258            compiler_version: compiler_version.into(),
259            language_version: language_version.into(),
260            runtime_version: runtime_version.into(),
261            contracts: Vec::new(),
262            ledger: Vec::new(),
263            witnesses: Vec::new(),
264            natives: Vec::new(),
265            circuits: Vec::new(),
266            descriptors: IndexMap::new(),
267            constructor: Constructor::default(),
268            external_contracts: Vec::new(),
269            pure_circuits: Vec::new(),
270            frontend: None,
271            debug_info: None,
272            capabilities: None,
273            workflows: Vec::new(),
274            privacy: None,
275            type_roles: IndexMap::new(),
276        }
277    }
278
279    #[must_use]
280    pub fn with_frontend(mut self, frontend: FrontendMeta) -> Self {
281        self.frontend = Some(frontend);
282        self
283    }
284
285    #[must_use]
286    pub fn with_debug_info(mut self, debug_info: DebugInfo) -> Self {
287        self.debug_info = Some(debug_info);
288        self
289    }
290
291    #[must_use]
292    pub fn with_capabilities(mut self, capabilities: CapabilitiesMeta) -> Self {
293        self.capabilities = Some(capabilities);
294        self
295    }
296
297    #[must_use]
298    pub fn with_workflows(mut self, workflows: Vec<WorkflowMeta>) -> Self {
299        self.workflows = workflows;
300        self
301    }
302
303    #[must_use]
304    pub fn with_privacy(mut self, privacy: PrivacyMeta) -> Self {
305        self.privacy = Some(privacy);
306        self
307    }
308
309    #[must_use]
310    pub fn with_type_roles(mut self, type_roles: IndexMap<String, SemanticTypeRole>) -> Self {
311        self.type_roles = type_roles;
312        self
313    }
314
315    #[must_use]
316    pub fn with_type_role(
317        mut self,
318        descriptor_key: impl Into<String>,
319        role: SemanticTypeRole,
320    ) -> Self {
321        self.type_roles.insert(descriptor_key.into(), role);
322        self
323    }
324
325    #[must_use]
326    pub fn with_constructor(mut self, constructor: Constructor) -> Self {
327        self.constructor = constructor;
328        self
329    }
330
331    pub fn add_ledger_field(&mut self, field: LedgerField) -> &mut Self {
332        self.ledger.push(field);
333        self
334    }
335
336    pub fn add_witness(&mut self, witness: Witness) -> &mut Self {
337        self.witnesses.push(witness);
338        self
339    }
340
341    pub fn add_native(&mut self, native: Native) -> &mut Self {
342        self.natives.push(native);
343        self
344    }
345
346    pub fn add_circuit(&mut self, circuit: CircuitBody) -> &mut Self {
347        self.circuits.push(circuit);
348        self
349    }
350
351    pub fn add_descriptor(
352        &mut self,
353        key: impl Into<String>,
354        descriptor: TypeDescriptor,
355    ) -> &mut Self {
356        self.descriptors.insert(key.into(), descriptor);
357        self
358    }
359
360    pub fn add_workflow(&mut self, workflow: WorkflowMeta) -> &mut Self {
361        self.workflows.push(workflow);
362        self
363    }
364}
365
366// ===========================================================================
367// Schema v3 language-agnostic contract metadata
368// ===========================================================================
369
370/// Source frontend language that produced a [`MoonIr`].
371#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
372#[serde(rename_all = "kebab-case")]
373pub enum FrontendLanguage {
374    Compact,
375    Pact5,
376    Custom(String),
377}
378
379/// Identifying metadata for the compiler frontend that emitted the IR.
380#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
381pub struct FrontendMeta {
382    pub language: FrontendLanguage,
383    #[serde(rename = "frontend-version")]
384    pub frontend_version: String,
385    #[serde(
386        rename = "source-module",
387        default,
388        skip_serializing_if = "Option::is_none"
389    )]
390    pub source_module: Option<String>,
391    #[serde(
392        rename = "source-hash",
393        default,
394        skip_serializing_if = "Option::is_none"
395    )]
396    pub source_hash: Option<String>,
397    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
398    pub metadata: IndexMap<String, String>,
399}
400
401/// Source-code span for diagnostics, coverage, and debugging.
402#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
403pub struct SourceSpan {
404    #[serde(default, skip_serializing_if = "Option::is_none")]
405    pub file: Option<String>,
406    #[serde(rename = "start-line")]
407    pub start_line: u32,
408    #[serde(rename = "start-col")]
409    pub start_col: u32,
410    #[serde(rename = "end-line")]
411    pub end_line: u32,
412    #[serde(rename = "end-col")]
413    pub end_col: u32,
414}
415
416/// Source file list and symbol-to-span maps.
417#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
418pub struct DebugInfo {
419    #[serde(default, skip_serializing_if = "Vec::is_empty")]
420    pub sources: Vec<String>,
421    #[serde(
422        rename = "circuit-spans",
423        default,
424        skip_serializing_if = "IndexMap::is_empty"
425    )]
426    pub circuit_spans: IndexMap<String, SourceSpan>,
427    #[serde(
428        rename = "field-spans",
429        default,
430        skip_serializing_if = "IndexMap::is_empty"
431    )]
432    pub field_spans: IndexMap<String, SourceSpan>,
433}
434
435/// Contract upgrade / administration governance declaration.
436#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
437#[serde(tag = "kind", rename_all = "kebab-case")]
438pub enum GovernanceSpec {
439    Keyset { name: String },
440    Capability { name: String },
441    Custom { description: String },
442}
443
444/// Classification of a declared contract capability.
445#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
446#[serde(rename_all = "kebab-case")]
447pub enum CapabilityKind {
448    Basic,
449    Managed,
450    Event,
451}
452
453/// Declaration of a contract capability (e.g. Pact `defcap`).
454#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
455pub struct CapabilityDef {
456    pub name: String,
457    pub kind: CapabilityKind,
458    #[serde(default, skip_serializing_if = "Vec::is_empty")]
459    pub arguments: Vec<Argument>,
460    #[serde(
461        rename = "managed-param",
462        default,
463        skip_serializing_if = "Option::is_none"
464    )]
465    pub managed_param: Option<String>,
466    #[serde(
467        rename = "manager-circuit",
468        default,
469        skip_serializing_if = "Option::is_none"
470    )]
471    pub manager_circuit: Option<String>,
472    #[serde(default, skip_serializing_if = "Vec::is_empty")]
473    pub composes: Vec<String>,
474}
475
476/// Per-circuit summary of capabilities acquired, required, or emitted.
477#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
478pub struct CircuitCapUsage {
479    #[serde(default, skip_serializing_if = "Vec::is_empty")]
480    pub acquires: Vec<String>,
481    #[serde(default, skip_serializing_if = "Vec::is_empty")]
482    pub requires: Vec<String>,
483    #[serde(default, skip_serializing_if = "Vec::is_empty")]
484    pub emits: Vec<String>,
485}
486
487/// Contract-wide governance and capability metadata.
488#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
489pub struct CapabilitiesMeta {
490    #[serde(default, skip_serializing_if = "Option::is_none")]
491    pub governance: Option<GovernanceSpec>,
492    #[serde(default, skip_serializing_if = "Vec::is_empty")]
493    pub capabilities: Vec<CapabilityDef>,
494    #[serde(
495        rename = "circuit-usage",
496        default,
497        skip_serializing_if = "IndexMap::is_empty"
498    )]
499    pub circuit_usage: IndexMap<String, CircuitCapUsage>,
500}
501
502/// One step in a multi-step workflow (e.g. a Pact `defpact` step).
503#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
504pub struct WorkflowStepMeta {
505    pub index: u32,
506    pub circuit: String,
507    #[serde(
508        rename = "rollback-circuit",
509        default,
510        skip_serializing_if = "Option::is_none"
511    )]
512    pub rollback_circuit: Option<String>,
513    #[serde(default, skip_serializing_if = "Option::is_none")]
514    pub entity: Option<String>,
515    #[serde(default, skip_serializing_if = "Vec::is_empty")]
516    pub yields: Vec<String>,
517}
518
519/// Multi-step workflow definition grouping ordered step circuits.
520#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
521pub struct WorkflowMeta {
522    pub name: String,
523    #[serde(default, skip_serializing_if = "Vec::is_empty")]
524    pub steps: Vec<WorkflowStepMeta>,
525}
526
527/// Privacy classification for a contract field or value flow.
528#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
529#[serde(rename_all = "kebab-case")]
530pub enum PrivacyClass {
531    Public,
532    Private,
533    Shielded,
534    Disclosed,
535}
536
537/// Architectural role of a ledger field for auditing and tooling.
538#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
539#[serde(rename_all = "kebab-case")]
540pub enum FieldRole {
541    State,
542    Commitment,
543    Nullifier,
544    Ciphertext,
545    Authority,
546    Balance,
547}
548
549/// Static resource bounds for a single circuit.
550#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
551pub struct CircuitBoundsMeta {
552    #[serde(
553        rename = "max-constraints",
554        default,
555        skip_serializing_if = "Option::is_none"
556    )]
557    pub max_constraints: Option<u64>,
558    #[serde(
559        rename = "max-public-inputs",
560        default,
561        skip_serializing_if = "Option::is_none"
562    )]
563    pub max_public_inputs: Option<u32>,
564    #[serde(
565        rename = "max-witness-elements",
566        default,
567        skip_serializing_if = "Option::is_none"
568    )]
569    pub max_witness_elements: Option<u32>,
570}
571
572/// Contract-wide privacy annotations and circuit bounds.
573#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
574pub struct PrivacyMeta {
575    #[serde(
576        rename = "field-classes",
577        default,
578        skip_serializing_if = "IndexMap::is_empty"
579    )]
580    pub field_classes: IndexMap<String, PrivacyClass>,
581    #[serde(
582        rename = "field-roles",
583        default,
584        skip_serializing_if = "IndexMap::is_empty"
585    )]
586    pub field_roles: IndexMap<String, FieldRole>,
587    #[serde(
588        rename = "circuit-bounds",
589        default,
590        skip_serializing_if = "IndexMap::is_empty"
591    )]
592    pub circuit_bounds: IndexMap<String, CircuitBoundsMeta>,
593}
594
595/// Higher-level semantic role attached to a descriptor entry so codegen
596/// and host tooling can recover frontend types lowered onto core IR primitives.
597#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
598#[serde(tag = "role", rename_all = "kebab-case")]
599pub enum SemanticTypeRole {
600    FixedDecimal {
601        scale: u8,
602        signed: bool,
603    },
604    SignedInt {
605        bits: u16,
606    },
607    BoundedList {
608        #[serde(rename = "max-len")]
609        max_len: u32,
610    },
611    Guard,
612    Timestamp,
613}
614
615// ===========================================================================
616// Type descriptors
617// ===========================================================================
618
619/// Which field an operation works in. Spelled exactly as compactc's
620/// `extract-contract-info.ss` spells the corresponding type names, so a
621/// `field-type` string and a `type-name` string are the same vocabulary.
622///
623/// The jubjub base field is the native field, so there is no separate
624/// variant for it — upstream emits neither.
625#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
626pub enum FieldType {
627    Field,
628    JubjubScalar,
629    Secp256k1Base,
630    Secp256k1Scalar,
631    Secp256r1Base,
632    Secp256r1Scalar,
633    Curve25519Base,
634    Curve25519Scalar,
635}
636
637impl FieldType {
638    /// The type descriptor a value of this field is encoded as.
639    #[must_use]
640    pub fn descriptor(self) -> TypeDescriptor {
641        match self {
642            FieldType::Field => TypeDescriptor::Field,
643            FieldType::JubjubScalar => TypeDescriptor::JubjubScalar,
644            FieldType::Secp256k1Base => TypeDescriptor::Secp256k1Base,
645            FieldType::Secp256k1Scalar => TypeDescriptor::Secp256k1Scalar,
646            FieldType::Secp256r1Base => TypeDescriptor::Secp256r1Base,
647            FieldType::Secp256r1Scalar => TypeDescriptor::Secp256r1Scalar,
648            FieldType::Curve25519Base => TypeDescriptor::Curve25519Base,
649            FieldType::Curve25519Scalar => TypeDescriptor::Curve25519Scalar,
650        }
651    }
652
653    /// The field a descriptor's values live in, the inverse of
654    /// [`FieldType::descriptor`]. `None` for anything that is not a
655    /// field.
656    #[must_use]
657    pub fn of_descriptor(descriptor: &TypeDescriptor) -> Option<FieldType> {
658        Some(match descriptor {
659            TypeDescriptor::Field => FieldType::Field,
660            TypeDescriptor::JubjubScalar => FieldType::JubjubScalar,
661            TypeDescriptor::Secp256k1Base => FieldType::Secp256k1Base,
662            TypeDescriptor::Secp256k1Scalar => FieldType::Secp256k1Scalar,
663            TypeDescriptor::Secp256r1Base => FieldType::Secp256r1Base,
664            TypeDescriptor::Secp256r1Scalar => FieldType::Secp256r1Scalar,
665            TypeDescriptor::Curve25519Base => FieldType::Curve25519Base,
666            TypeDescriptor::Curve25519Scalar => FieldType::Curve25519Scalar,
667            _ => return None,
668        })
669    }
670}
671
672#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
673#[serde(tag = "type-name")]
674pub enum TypeDescriptor {
675    Boolean,
676    Field,
677    /// Scalar field of the Jubjub curve. Shares `Field`'s single-atom
678    /// alignment and encoding; only the valid range differs
679    /// (`JUBJUB_SCALAR_MODULUS - 1`). compactc 0.33 promoted this from
680    /// an opaque builtin to a standard-library type.
681    JubjubScalar,
682    /// Base field of secp256k1. Two atoms — `bytes:24` holding the low
683    /// 192 bits, `bytes:8` the high 64 — with the value rotated by one
684    /// (`0` maps to the modulus-1, everything else to `v - 1`) because
685    /// that is what the ZKIR representation stores.
686    Secp256k1Base,
687    /// Scalar field of secp256k1. Same two-atom layout and rotation as
688    /// [`TypeDescriptor::Secp256k1Base`], different modulus.
689    Secp256k1Scalar,
690    /// Base field of secp256r1 (P-256). Same two-atom layout and
691    /// rotation as [`TypeDescriptor::Secp256k1Base`].
692    Secp256r1Base,
693    /// Scalar field of secp256r1. Same layout as
694    /// [`TypeDescriptor::Secp256k1Base`].
695    Secp256r1Scalar,
696    /// Base field of Curve25519. Same layout as
697    /// [`TypeDescriptor::Secp256k1Base`].
698    Curve25519Base,
699    /// Scalar field of Curve25519. Two atoms split at bit 204 rather
700    /// than 192 — `bytes:26` then `bytes:7` — with the same rotation.
701    Curve25519Scalar,
702    /// Point on the Jubjub curve: two native field atoms, `x` then `y`.
703    JubjubPoint,
704    /// Point on secp256k1: `x` and `y` each as a `Secp256k1Base` pair,
705    /// then a native field atom holding the identity flag.
706    Secp256k1Point,
707    /// Point on secp256r1, laid out as [`TypeDescriptor::Secp256k1Point`]
708    /// over `Secp256r1Base`.
709    Secp256r1Point,
710    /// Point on Curve25519 in Edwards form: `x` then `y`, each a
711    /// `Curve25519Base` pair. No identity flag; the identity is `(0, 1)`.
712    Curve25519Point,
713    /// Element type of an empty vector literal (`[]`). The compact
714    /// fork emits `{"type-name": "Unknown"}` here, mirroring the
715    /// TypeScript emitter's `format-type`. Never reaches the
716    /// `descriptors` map — only appears inline in circuit bodies.
717    Unknown,
718    Uint {
719        maxval: IntLit,
720        #[serde(default, rename = "alignment-bytes")]
721        alignment_bytes: Option<u32>,
722    },
723    Bytes {
724        length: u32,
725    },
726    Opaque {
727        #[serde(rename = "tsType")]
728        ts_type: String,
729    },
730    Vector {
731        length: u32,
732        #[serde(rename = "type")]
733        elt_type: Box<TypeDescriptor>,
734    },
735    Tuple {
736        types: Vec<TypeDescriptor>,
737    },
738    Struct {
739        name: String,
740        elements: Vec<StructField>,
741    },
742    Enum {
743        name: String,
744        elements: Vec<String>,
745    },
746    Alias {
747        name: String,
748        #[serde(rename = "type")]
749        of: Box<TypeDescriptor>,
750    },
751    Contract {
752        name: String,
753        circuits: Vec<ContractCircuitSig>,
754    },
755    Cell {
756        #[serde(rename = "type")]
757        of: Box<TypeDescriptor>,
758    },
759    Counter,
760    Map {
761        key: Box<TypeDescriptor>,
762        value: Box<TypeDescriptor>,
763    },
764    Set {
765        #[serde(rename = "type")]
766        of: Box<TypeDescriptor>,
767    },
768    List {
769        #[serde(rename = "type")]
770        of: Box<TypeDescriptor>,
771    },
772    MerkleTree {
773        depth: IntLit,
774        #[serde(rename = "type")]
775        of: Box<TypeDescriptor>,
776    },
777    HistoricMerkleTree {
778        depth: IntLit,
779        #[serde(rename = "type")]
780        of: Box<TypeDescriptor>,
781    },
782}
783
784impl TypeDescriptor {
785    /// The standard library's `ContractAddress` struct. A value of a
786    /// contract type is the address of a contract implementing it, and
787    /// compactc stores and passes it as this struct (`subst-tcontract`
788    /// in print-typescript.ss).
789    #[must_use]
790    pub fn contract_address() -> Self {
791        TypeDescriptor::Struct {
792            name: "ContractAddress".to_owned(),
793            elements: vec![StructField {
794                name: "bytes".to_owned(),
795                field_type: TypeDescriptor::Bytes { length: 32 },
796            }],
797        }
798    }
799}
800
801#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
802pub struct StructField {
803    pub name: String,
804    #[serde(rename = "type")]
805    pub field_type: TypeDescriptor,
806}
807
808#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
809pub struct ContractCircuitSig {
810    pub name: String,
811    #[serde(rename = "argument-types")]
812    pub argument_types: Vec<TypeDescriptor>,
813    #[serde(rename = "result-type")]
814    pub result_type: TypeDescriptor,
815}
816
817// ===========================================================================
818// Ledger fields, witnesses, natives
819// ===========================================================================
820
821#[derive(Debug, Clone, Serialize, Deserialize)]
822pub struct LedgerField {
823    pub name: String,
824    /// Field index in the on-chain ledger layout. Older compactc
825    /// emits a scalar (`0`); newer compactc emits a path-style array
826    /// (`[0, 2]`) for nested module layouts. Stored as a `Vec<u32>`
827    /// either way — single-element vec for the scalar form. The
828    /// runtime currently only consumes the leaf via
829    /// [`Self::leaf_index`]; the rest of the path is preserved for
830    /// future codegen / inspect tooling.
831    ///
832    /// Wire-format preservation: a single-element vec serializes back
833    /// as a scalar so round-tripping through ciborium produces
834    /// byte-identical CBOR for the older single-int shape (matters
835    /// for `ir_sha256` stability in codegen-emitted headers).
836    #[serde(
837        deserialize_with = "deserialize_field_index",
838        serialize_with = "serialize_field_index"
839    )]
840    pub index: Vec<u32>,
841    pub exported: bool,
842    #[serde(flatten)]
843    pub storage: Storage,
844}
845
846impl LedgerField {
847    /// Leaf index in the flat on-chain layout — equivalent to the old
848    /// scalar `index` field.
849    #[must_use]
850    pub fn leaf_index(&self) -> u32 {
851        self.index.last().copied().unwrap_or(0)
852    }
853}
854
855fn serialize_field_index<S>(v: &[u32], s: S) -> Result<S::Ok, S::Error>
856where
857    S: serde::Serializer,
858{
859    use serde::ser::SerializeSeq;
860    if v.len() == 1 {
861        s.serialize_u32(v[0])
862    } else {
863        let mut seq = s.serialize_seq(Some(v.len()))?;
864        for n in v {
865            seq.serialize_element(n)?;
866        }
867        seq.end()
868    }
869}
870
871fn deserialize_field_index<'de, D>(d: D) -> Result<Vec<u32>, D::Error>
872where
873    D: serde::Deserializer<'de>,
874{
875    use serde::de::{self, Error, SeqAccess, Visitor};
876    use std::fmt;
877
878    struct V;
879    impl<'de> Visitor<'de> for V {
880        type Value = Vec<u32>;
881        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882            f.write_str("a non-negative integer or an array of non-negative integers")
883        }
884        fn visit_u64<E: Error>(self, v: u64) -> Result<Vec<u32>, E> {
885            u32::try_from(v)
886                .map(|n| vec![n])
887                .map_err(|_| Error::custom(format!("ledger field index {v} exceeds u32::MAX")))
888        }
889        fn visit_i64<E: Error>(self, v: i64) -> Result<Vec<u32>, E> {
890            u32::try_from(v)
891                .map(|n| vec![n])
892                .map_err(|_| Error::custom(format!("ledger field index {v} not in u32 range")))
893        }
894        fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u32>, A::Error> {
895            let mut out: Vec<u32> = Vec::new();
896            while let Some(elem) = seq.next_element::<i64>()? {
897                let n = u32::try_from(elem).map_err(|_| {
898                    de::Error::custom(format!(
899                        "ledger field index path entry {elem} not in u32 range"
900                    ))
901                })?;
902                out.push(n);
903            }
904            Ok(out)
905        }
906    }
907    d.deserialize_any(V)
908}
909
910/// Storage shape of a ledger field. Discriminated on a `"storage"`
911/// JSON tag — the wire format compactc emits is:
912///
913/// ```text
914/// { "storage": "Counter" }
915/// { "storage": "Cell",  "type":  <TypeDescriptor> }
916/// { "storage": "Map",   "key":   <TypeDescriptor>, "value": <TypeDescriptor> }
917/// { "storage": "Set",   "type":  <TypeDescriptor> }
918/// { "storage": "List",  "type":  <TypeDescriptor> }
919/// { "storage": "MerkleTree",         "type": <TypeDescriptor> }
920/// { "storage": "HistoricMerkleTree", "type": <TypeDescriptor> }
921/// ```
922///
923/// Typed here so codegen + runtime can `match` on the enum directly
924/// instead of reaching into `serde_json::Value` to sniff a
925/// discriminant. Mirrors the pattern `RuntimeValue` introduced for
926/// values: anywhere we used to carry raw `serde_json::Value`, we
927/// carry a typed moonproof enum instead.
928#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
929#[serde(tag = "storage")]
930pub enum Storage {
931    Counter,
932    Cell {
933        #[serde(rename = "type")]
934        of: TypeDescriptor,
935    },
936    Map {
937        key: TypeDescriptor,
938        value: TypeDescriptor,
939    },
940    Set {
941        #[serde(rename = "type")]
942        of: TypeDescriptor,
943    },
944    List {
945        #[serde(rename = "type")]
946        of: TypeDescriptor,
947    },
948    MerkleTree {
949        #[serde(rename = "type")]
950        of: TypeDescriptor,
951    },
952    HistoricMerkleTree {
953        #[serde(rename = "type")]
954        of: TypeDescriptor,
955    },
956}
957
958impl Storage {
959    /// Stable string id for the discriminant — useful for error
960    /// messages and existing emit paths that key on the variant name.
961    #[must_use]
962    pub fn kind(&self) -> &'static str {
963        match self {
964            Self::Counter => "Counter",
965            Self::Cell { .. } => "Cell",
966            Self::Map { .. } => "Map",
967            Self::Set { .. } => "Set",
968            Self::List { .. } => "List",
969            Self::MerkleTree { .. } => "MerkleTree",
970            Self::HistoricMerkleTree { .. } => "HistoricMerkleTree",
971        }
972    }
973}
974
975#[derive(Debug, Clone, Serialize, Deserialize)]
976pub struct Witness {
977    pub name: String,
978    #[serde(default)]
979    pub arguments: Vec<Argument>,
980    #[serde(rename = "result-type")]
981    pub result_type: TypeDescriptor,
982}
983
984#[derive(Debug, Clone, Serialize, Deserialize)]
985pub struct Native {
986    pub name: String,
987    /// Which of the natives sharing `name` this is (`ecAdd` on each
988    /// curve, each instantiation of a generic), matched against
989    /// `Expression::Call::function_uniq`. Absent in older fixtures.
990    #[serde(rename = "internal-uniq", default)]
991    pub internal_uniq: Option<u64>,
992    #[serde(rename = "host-symbol")]
993    pub host_symbol: String,
994    /// Language-agnostic intrinsic name (schema v3, optional). When
995    /// absent, [`Self::resolve_intrinsic`] falls back to stripping any
996    /// `"__compactRuntime."` prefix from [`Self::host_symbol`].
997    #[serde(default, skip_serializing_if = "Option::is_none")]
998    pub intrinsic: Option<String>,
999    pub class: String,
1000    #[serde(default)]
1001    pub arguments: Vec<Argument>,
1002    #[serde(rename = "result-type")]
1003    pub result_type: TypeDescriptor,
1004}
1005
1006impl Native {
1007    /// Construct a language-agnostic native entry carrying an explicit
1008    /// `intrinsic` identifier.
1009    #[must_use]
1010    pub fn new_intrinsic(
1011        name: impl Into<String>,
1012        intrinsic: impl Into<String>,
1013        class: impl Into<String>,
1014        arguments: Vec<Argument>,
1015        result_type: TypeDescriptor,
1016    ) -> Self {
1017        let intr = intrinsic.into();
1018        Self {
1019            name: name.into(),
1020            internal_uniq: None,
1021            host_symbol: intr.clone(),
1022            intrinsic: Some(intr),
1023            class: class.into(),
1024            arguments,
1025            result_type,
1026        }
1027    }
1028
1029    /// Resolve the canonical intrinsic name for this native declaration.
1030    ///
1031    /// Uses [`Self::intrinsic`] when present; otherwise strips a leading
1032    /// `"__compactRuntime."` prefix from [`Self::host_symbol`], returning
1033    /// the raw `host_symbol` if no such prefix exists.
1034    #[must_use]
1035    pub fn resolve_intrinsic(&self) -> &str {
1036        if let Some(ref intrinsic) = self.intrinsic {
1037            intrinsic.as_str()
1038        } else {
1039            self.host_symbol
1040                .strip_prefix("__compactRuntime.")
1041                .unwrap_or(&self.host_symbol)
1042        }
1043    }
1044}
1045
1046/// Normalize a Compact bare native name, `"__compactRuntime.*"` host symbol,
1047/// or language-agnostic `"mp:*"` intrinsic URI to the single canonical
1048/// intrinsic identifier shared across the runtime, privacy auditor, ZKIR
1049/// compiler, and multi-language frontends.
1050#[must_use]
1051pub fn canonical_intrinsic_name(raw: &str) -> &str {
1052    let trimmed = raw.strip_prefix("__compactRuntime.").unwrap_or(raw);
1053    match trimmed {
1054        // Hashing & field/byte conversions
1055        "mp:hash/persistent" => "persistentHash",
1056        "mp:hash/transient" | "mp:hash/poseidon" => "transientHash",
1057        "mp:commit/persistent" | "mp:hash/persistent-commit" => "persistentCommit",
1058        "mp:commit/transient" | "mp:hash/transient-commit" => "transientCommit",
1059        "mp:hash/degrade-to-transient" => "degradeToTransient",
1060        "mp:hash/upgrade-from-transient" => "upgradeFromTransient",
1061        "mp:hash/keccak256" => "keccak256",
1062        "mp:hash/sha512" => "sha512",
1063        "mp:hash/to-curve" | "mp:curve/hash-to-curve" => "hashToCurve",
1064
1065        // Coin / zswap / execution context
1066        "mp:coin/commitment" | "mp:zswap/coin-commitment" => "coinCommitment",
1067        "mp:coin/token-type" | "mp:zswap/token-type" => "tokenType",
1068        "mp:context/own-public-key"
1069        | "mp:zswap/own-public-key"
1070        | "mp:auth/own-public-key"
1071        | "mp:ledger/own-public-key" => "ownPublicKey",
1072        "mp:zswap/create-output" => "createZswapOutput",
1073        "mp:zswap/create-input" => "createZswapInput",
1074
1075        // Embedded Jubjub & foreign elliptic-curve primitives
1076        "mp:curve/jubjub-point-x" | "mp:ec/jubjub-point-x" => "jubjubPointX",
1077        "mp:curve/jubjub-point-y" | "mp:ec/jubjub-point-y" => "jubjubPointY",
1078        "mp:curve/jubjub-construct" | "mp:ec/jubjub-construct" => "constructJubjubPoint",
1079        "mp:curve/jubjub-add" | "mp:ec/add" | "mp:ec/jubjub-add" => "ecAdd",
1080        "mp:curve/jubjub-mul" | "mp:ec/mul" | "mp:ec/jubjub-mul" => "ecMul",
1081        "mp:curve/jubjub-mul-generator" | "mp:ec/mul-generator" | "mp:ec/jubjub-mul-generator" => {
1082            "ecMulGenerator"
1083        }
1084        "mp:curve/jubjub-neg" | "mp:ec/neg" | "mp:ec/jubjub-neg" => "ecNeg",
1085        "mp:curve/jubjub-scalar-from-native"
1086        | "mp:ec/jubjub-scalar-from-native"
1087        | "reduceModJubjubOrder" => "jubjubScalarFromNative",
1088        "mp:curve/secp256k1-add" | "mp:ec/secp256k1-add" => "secp256k1Add",
1089        "mp:curve/secp256r1-add" | "mp:ec/secp256r1-add" => "secp256r1Add",
1090        "mp:curve/curve25519-add" | "mp:ec/curve25519-add" => "curve25519Add",
1091        "mp:curve/secp256k1-mul" | "mp:ec/secp256k1-mul" => "secp256k1Mul",
1092        "mp:curve/secp256r1-mul" | "mp:ec/secp256r1-mul" => "secp256r1Mul",
1093        "mp:curve/curve25519-mul" | "mp:ec/curve25519-mul" => "curve25519Mul",
1094        "mp:curve/secp256k1-mul-generator" | "mp:ec/secp256k1-mul-generator" => {
1095            "secp256k1MulGenerator"
1096        }
1097        "mp:curve/secp256r1-mul-generator" | "mp:ec/secp256r1-mul-generator" => {
1098            "secp256r1MulGenerator"
1099        }
1100        "mp:curve/curve25519-mul-generator" | "mp:ec/curve25519-mul-generator" => {
1101            "curve25519MulGenerator"
1102        }
1103
1104        // Merkle tree path root verification
1105        "mp:merkle/path-root" => "merkleTreePathRoot",
1106        "mp:merkle/path-root-no-leaf-hash" => "merkleTreePathRootNoLeafHash",
1107
1108        // Signature verification
1109        "mp:crypto/ed25519-verify" | "mp:sig/ed25519-verify" => "ed25519Verify",
1110        "mp:crypto/secp256r1-ecdsa-verify"
1111        | "mp:sig/secp256r1-ecdsa-verify"
1112        | "mp:crypto/ecdsa-p256-verify" => "secp256r1EcdsaVerify",
1113        "mp:crypto/secp256k1-ecdsa-verify"
1114        | "mp:sig/secp256k1-ecdsa-verify"
1115        | "mp:crypto/ecdsa-secp256k1-verify" => "secp256k1EcdsaVerify",
1116
1117        other => other,
1118    }
1119}
1120
1121#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1122pub struct Argument {
1123    pub name: String,
1124    #[serde(rename = "type")]
1125    pub arg_type: TypeDescriptor,
1126}
1127
1128// ===========================================================================
1129// Constructor
1130// ===========================================================================
1131
1132#[derive(Debug, Clone, Serialize, Deserialize)]
1133pub struct Constructor {
1134    #[serde(default)]
1135    pub arguments: Vec<Argument>,
1136    #[serde(rename = "initial-state")]
1137    pub initial_state: StateValue,
1138    #[serde(rename = "init-ops", default)]
1139    pub init_ops: Vec<Expression>,
1140    #[serde(rename = "register-operations", default)]
1141    pub register_operations: Vec<String>,
1142    pub body: Statement,
1143}
1144
1145impl Default for Constructor {
1146    fn default() -> Self {
1147        Self {
1148            arguments: Vec::new(),
1149            initial_state: StateValue::Null,
1150            init_ops: Vec::new(),
1151            register_operations: Vec::new(),
1152            body: Statement::Noop,
1153        }
1154    }
1155}
1156
1157// ===========================================================================
1158// Circuit body
1159// ===========================================================================
1160
1161#[derive(Debug, Clone, Serialize, Deserialize)]
1162pub struct CircuitBody {
1163    pub name: String,
1164    #[serde(rename = "internal-name")]
1165    pub internal_name: String,
1166    /// Disambiguator for monomorphized generic circuits — see
1167    /// `Expression::Call::function_uniq`. Optional; absent in older
1168    /// fixtures.
1169    #[serde(rename = "internal-uniq", default)]
1170    pub internal_uniq: Option<u64>,
1171    pub exported: bool,
1172    pub pure: bool,
1173    pub proof: bool,
1174    #[serde(default)]
1175    pub arguments: Vec<Argument>,
1176    #[serde(rename = "result-type")]
1177    pub result_type: TypeDescriptor,
1178    pub body: Statement,
1179}
1180
1181// ===========================================================================
1182// Statement IR
1183// ===========================================================================
1184
1185#[derive(Debug, Clone, Serialize, Deserialize)]
1186#[serde(tag = "stmt", rename_all = "kebab-case")]
1187pub enum Statement {
1188    Seq {
1189        items: Vec<Statement>,
1190    },
1191    If {
1192        cond: Expression,
1193        then: Box<Statement>,
1194        #[serde(default)]
1195        r#else: Option<Box<Statement>>,
1196    },
1197    Const {
1198        binding: BindingTarget,
1199        value: Expression,
1200    },
1201    ConstDestructure {
1202        bindings: Vec<BindingTarget>,
1203    },
1204    Expr {
1205        value: Expression,
1206    },
1207    /// Sentinel for an unimplemented body slot.  Useful during emitter
1208    /// development; runtime should reject this.
1209    Unimplemented,
1210    /// Sentinel for "no operation" (used when there's no constructor body).
1211    Noop,
1212}
1213
1214#[derive(Debug, Clone, Serialize, Deserialize)]
1215pub struct BindingTarget {
1216    pub name: String,
1217    #[serde(rename = "type")]
1218    pub binding_type: TypeDescriptor,
1219}
1220
1221// ===========================================================================
1222// Expression IR
1223// ===========================================================================
1224
1225#[derive(Debug, Clone, Serialize, Deserialize)]
1226#[serde(tag = "expr", rename_all = "kebab-case")]
1227pub enum Expression {
1228    Literal {
1229        value: crate::value::RuntimeValue,
1230    },
1231    Var {
1232        name: String,
1233    },
1234    Default {
1235        #[serde(rename = "type")]
1236        of_type: TypeDescriptor,
1237    },
1238    If {
1239        cond: Box<Expression>,
1240        then: Box<Expression>,
1241        r#else: Box<Expression>,
1242    },
1243    EltRef {
1244        value: Box<Expression>,
1245        field: String,
1246        index: IntLit,
1247    },
1248    EnumRef {
1249        #[serde(rename = "type")]
1250        of_type: TypeDescriptor,
1251        variant: String,
1252    },
1253    Tuple {
1254        items: Vec<TupleItem>,
1255    },
1256    Vector {
1257        items: Vec<TupleItem>,
1258    },
1259    TupleRef {
1260        value: Box<Expression>,
1261        index: IntLit,
1262    },
1263    TupleSlice {
1264        value: Box<Expression>,
1265        start: IntLit,
1266        length: IntLit,
1267        #[serde(rename = "result-type")]
1268        result_type: TypeDescriptor,
1269    },
1270    VectorRef {
1271        value: Box<Expression>,
1272        index: Box<Expression>,
1273        #[serde(rename = "result-type")]
1274        result_type: TypeDescriptor,
1275    },
1276    VectorSlice {
1277        value: Box<Expression>,
1278        start: Box<Expression>,
1279        length: IntLit,
1280        #[serde(rename = "result-type")]
1281        result_type: TypeDescriptor,
1282    },
1283    BytesRef {
1284        value: Box<Expression>,
1285        index: Box<Expression>,
1286        #[serde(rename = "result-type")]
1287        result_type: TypeDescriptor,
1288    },
1289    BytesSlice {
1290        value: Box<Expression>,
1291        start: Box<Expression>,
1292        length: IntLit,
1293        #[serde(rename = "result-type")]
1294        result_type: TypeDescriptor,
1295    },
1296    Binop {
1297        op: String,
1298        /// Operand width for the comparisons (`<`, `<=`, `>`, `>=`).
1299        #[serde(default)]
1300        bits: Option<u32>,
1301        /// Operand type for the arithmetic ops (`+`, `-`, `*`). Since
1302        /// 0.33 these carry a full type rather than a width, because a
1303        /// curve field wraps at its own modulus — the type is what
1304        /// selects the implementation.
1305        #[serde(rename = "type", default)]
1306        of_type: Option<TypeDescriptor>,
1307        left: Box<Expression>,
1308        right: Box<Expression>,
1309    },
1310    Eq {
1311        #[serde(rename = "type", default)]
1312        of_type: Option<TypeDescriptor>,
1313        left: Box<Expression>,
1314        right: Box<Expression>,
1315    },
1316    Neq {
1317        #[serde(rename = "type", default)]
1318        of_type: Option<TypeDescriptor>,
1319        left: Box<Expression>,
1320        right: Box<Expression>,
1321    },
1322    And {
1323        left: Box<Expression>,
1324        right: Box<Expression>,
1325    },
1326    Or {
1327        left: Box<Expression>,
1328        right: Box<Expression>,
1329    },
1330    Not {
1331        value: Box<Expression>,
1332    },
1333    Assign {
1334        name: String,
1335        value: Box<Expression>,
1336    },
1337    Call {
1338        function: String,
1339        /// Optional disambiguator for monomorphized generics — the
1340        /// patched compactc fork emits `function-uniq: <number>` so
1341        /// consumers can pick the right instantiation among multiple
1342        /// circuits sharing the same source-level `name`. Older
1343        /// fixtures don't carry this field; consumers fall back to
1344        /// "first match by name" when absent.
1345        #[serde(rename = "function-uniq", default)]
1346        function_uniq: Option<u64>,
1347        arguments: Vec<Expression>,
1348    },
1349    New {
1350        #[serde(rename = "type")]
1351        of_type: TypeDescriptor,
1352        arguments: Vec<Expression>,
1353    },
1354    Seq {
1355        items: Vec<Expression>,
1356    },
1357    Cast {
1358        to: TypeDescriptor,
1359        value: Box<Expression>,
1360    },
1361    SafeCast {
1362        to: TypeDescriptor,
1363        from: TypeDescriptor,
1364        value: Box<Expression>,
1365    },
1366    DowncastUnsigned {
1367        #[serde(rename = "from-bits")]
1368        from_bits: Option<IntLit>,
1369        #[serde(rename = "to-bits")]
1370        to_bits: IntLit,
1371        value: Box<Expression>,
1372    },
1373    #[serde(rename = "field->bytes")]
1374    FieldToBytes {
1375        length: u32,
1376        /// Which field the operand is drawn from. Absent in schema 1,
1377        /// where the only field was the native one.
1378        #[serde(rename = "field-type", default)]
1379        field_type: Option<FieldType>,
1380        value: Box<Expression>,
1381    },
1382    /// Widen a value into a field element. `field-type` names the target
1383    /// field, `from` the operand's type.
1384    #[serde(rename = "cast-to-field")]
1385    CastToField {
1386        #[serde(rename = "field-type")]
1387        field_type: FieldType,
1388        from: TypeDescriptor,
1389        value: Box<Expression>,
1390    },
1391    /// Narrow a field element to a `Uint` bounded by `maxval`, failing
1392    /// if the value does not fit.
1393    #[serde(rename = "cast-from-field")]
1394    CastFromField {
1395        maxval: IntLit,
1396        #[serde(rename = "field-type")]
1397        field_type: FieldType,
1398        value: Box<Expression>,
1399    },
1400    /// Emit a contract event (MIP-0002). `payload` evaluates to the
1401    /// serialized bytes; `vm-ops` is the ledger-query sequence that
1402    /// records the event, matching what the TypeScript emitter runs.
1403    Emit {
1404        #[serde(rename = "event-version")]
1405        event_version: u32,
1406        #[serde(rename = "event-tag")]
1407        event_tag: u32,
1408        #[serde(rename = "payload-length")]
1409        payload_length: u32,
1410        payload: Box<Expression>,
1411        #[serde(rename = "vm-ops", default)]
1412        vm_ops: Vec<VmInstr>,
1413    },
1414    #[serde(rename = "cast-from-bytes")]
1415    CastFromBytes {
1416        to: TypeDescriptor,
1417        length: u32,
1418        value: Box<Expression>,
1419    },
1420    #[serde(rename = "vector->bytes")]
1421    VectorToBytes {
1422        length: u32,
1423        value: Box<Expression>,
1424    },
1425    #[serde(rename = "bytes->vector")]
1426    BytesToVector {
1427        length: u32,
1428        value: Box<Expression>,
1429    },
1430    CastFromEnum {
1431        from: TypeDescriptor,
1432        to: TypeDescriptor,
1433        value: Box<Expression>,
1434    },
1435    CastToEnum {
1436        from: TypeDescriptor,
1437        to: TypeDescriptor,
1438        value: Box<Expression>,
1439    },
1440    Assert {
1441        cond: Box<Expression>,
1442        message: String,
1443    },
1444    Map {
1445        length: IntLit,
1446        function: crate::value::RuntimeValue,
1447        arguments: Vec<crate::value::RuntimeValue>,
1448    },
1449    Fold {
1450        length: IntLit,
1451        function: crate::value::RuntimeValue,
1452        initial: crate::value::RuntimeValue,
1453        arguments: Vec<crate::value::RuntimeValue>,
1454    },
1455    AdtOp(AdtOpInvocation),
1456    ContractCall {
1457        circuit: String,
1458        address: Box<Expression>,
1459        #[serde(rename = "address-type")]
1460        address_type: TypeDescriptor,
1461        arguments: Vec<Expression>,
1462    },
1463    /// Sentinel for unimplemented expression (development-time only).
1464    Unimplemented,
1465}
1466
1467#[derive(Debug, Clone, Serialize, Deserialize)]
1468pub struct TupleItem {
1469    pub kind: String, // "single" or "spread"
1470    #[serde(default)]
1471    pub length: Option<IntLit>,
1472    pub value: Expression,
1473}
1474
1475// ===========================================================================
1476// ADT-Op invocation (the load-bearing thing — kernel + ledger ops)
1477// ===========================================================================
1478
1479#[derive(Debug, Clone, Serialize, Deserialize)]
1480pub struct AdtOpInvocation {
1481    pub adt: String,
1482    pub operation: String,
1483    #[serde(rename = "op-class")]
1484    pub op_class: String,
1485    /// Positional index of the coin argument when `op-class` is the
1486    /// parameterised `update-with-coin-check` variant. The patched
1487    /// compactc fork emits this for any ADT-Op invocation whose
1488    /// op-class records a coin argument index (e.g. micro-dao's
1489    /// `cashOut` / `buyIn`). Consumers that need to anchor the coin
1490    /// against the on-chain commitment tree read this to find which
1491    /// arg slot carries the coin info.
1492    #[serde(rename = "op-class-coin-index", default)]
1493    pub op_class_coin_index: Option<u32>,
1494    /// Positional index of the recipient argument when the op-class
1495    /// records one. Same emission rule as
1496    /// [`op_class_coin_index`](Self::op_class_coin_index).
1497    #[serde(rename = "op-class-recipient-index", default)]
1498    pub op_class_recipient_index: Option<u32>,
1499    #[serde(default)]
1500    pub field: Option<String>,
1501    #[serde(rename = "field-path", default)]
1502    pub field_path: Vec<PathElement>,
1503    #[serde(default)]
1504    pub arguments: Vec<Expression>,
1505    #[serde(rename = "result-type")]
1506    pub result_type: TypeDescriptor,
1507    #[serde(rename = "vm-ops")]
1508    pub vm_ops: Vec<VmInstr>,
1509}
1510
1511#[derive(Debug, Clone, Serialize, Deserialize)]
1512#[serde(tag = "kind", rename_all = "kebab-case")]
1513pub enum PathElement {
1514    Literal {
1515        index: u32,
1516    },
1517    Expr {
1518        #[serde(rename = "type")]
1519        of_type: TypeDescriptor,
1520        // Boxed to keep the enum small — `Expression` is large and this
1521        // variant is rare. `Box` is serde-transparent, so the wire shape
1522        // is unchanged.
1523        value: Box<Expression>,
1524    },
1525}
1526
1527// ===========================================================================
1528// VM ops (stored as opaque JSON; the consumer interprets via op-name dispatch)
1529// ===========================================================================
1530
1531/// One VM instruction.  We capture the op name + remaining keys as a
1532/// raw JSON object since the op-arg shape varies per op.  Consumers
1533/// that need typed access can match on `op` and decode manually, or
1534/// use the helpers in `crate::vm`.
1535#[derive(Debug, Clone, Serialize, Deserialize)]
1536pub struct VmInstr(pub std::collections::BTreeMap<String, crate::value::RuntimeValue>);
1537
1538impl VmInstr {
1539    #[must_use]
1540    pub fn op(&self) -> Option<&str> {
1541        self.0
1542            .get("op")
1543            .and_then(crate::value::RuntimeValue::as_str)
1544    }
1545}
1546
1547/// One VM-op argument value.  This is a recursive structure because
1548/// VM ops can carry nested values: `{"vm": "state-value", "kind": "cell",
1549/// "value": {"vm": "align", ...}}`.  We model it as untyped
1550/// [`RuntimeValue`] for flexibility — `crate::vm::VmValue` provides
1551/// a typed interpretation.
1552pub type VmOp = crate::value::RuntimeValue;
1553
1554// ===========================================================================
1555// Initial state-value tree (for constructor.initial-state)
1556// ===========================================================================
1557
1558#[derive(Debug, Clone, Serialize, Deserialize)]
1559#[serde(tag = "kind", rename_all = "kebab-case")]
1560pub enum StateValue {
1561    Null,
1562    Cell {
1563        #[serde(default)]
1564        descriptor: Option<String>,
1565        value: crate::value::RuntimeValue,
1566    },
1567    CellExpr {
1568        #[serde(default)]
1569        descriptor: Option<String>,
1570        // Boxed to keep the enum small (serde-transparent; wire-compatible).
1571        value: Box<Expression>,
1572    },
1573    Array {
1574        items: Vec<StateValue>,
1575    },
1576    Map {
1577        entries: Vec<MapEntry>,
1578    },
1579    MerkleTree {
1580        depth: IntLit,
1581        #[serde(default)]
1582        entries: Vec<MapEntry>,
1583    },
1584}
1585
1586#[derive(Debug, Clone, Serialize, Deserialize)]
1587pub struct MapEntry {
1588    pub key: StateValue,
1589    pub value: StateValue,
1590}