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