Skip to main content

moonproof_runtime/ir/
index.rs

1//! Pre-built O(1) lookup tables and pre-compiled VM / FAB caches over a
2//! [`MoonIr`].
3//!
4//! Constructed once in [`IrExecutable::new`](crate::IrExecutable::new) (and
5//! when binding a cross-contract callee) so hot-path circuit execution avoids
6//! linear scans, `BTreeMap` VM-op parsing, serde `TypeDescriptor`
7//! deserialization, and repeated `Alignment` construction on every call.
8
9use std::sync::OnceLock;
10
11use moonproof_runtime_ir::ir::{
12    CircuitBody, Expression, MoonIr, Native, PathElement, Statement, TypeDescriptor, VmInstr,
13    Witness,
14};
15use rustc_hash::{FxBuildHasher, FxHashMap};
16
17use super::bytecode::{compile_circuit, compile_constructor, CompiledCircuit};
18use super::descriptor::{CircuitInputPlan, FabPlan};
19use super::vm_decode::{compile_vm_ops, CompiledLedgerQuery};
20
21/// Upper cap for initial `public_transcript` `Vec::with_capacity` hint so
22/// pathological/unbounded estimates never over-allocate.
23const MAX_TRANSCRIPT_CAPACITY_HINT: usize = 4096;
24
25/// Number of VM ops emitted by `claim_contract_call_ops` per `ContractCall`.
26const CLAIM_CONTRACT_CALL_OP_COUNT: usize = 9;
27
28/// Pre-compiled input and output [`FabPlan`]s for one [`CircuitBody`].
29#[derive(Debug, Clone)]
30pub struct CircuitIoPlan {
31    pub input: Option<CircuitInputPlan>,
32    pub output: Option<FabPlan>,
33}
34
35/// Pre-compiled argument and result [`FabPlan`]s for one [`Native`].
36#[derive(Debug, Clone)]
37pub struct NativeFabPlans {
38    pub args: Vec<Option<FabPlan>>,
39    pub result: Option<FabPlan>,
40}
41
42/// O(1) indices and lazily-compiled query / FAB caches for a [`MoonIr`].
43///
44/// All symbol entries store indices into the owning `MoonIr` so the index
45/// carries no AST clones and stays cheap to share via `Arc`. Query and
46/// circuit-I/O caches are keyed by stable heap addresses of slices/elements
47/// owned by the `Arc<MoonIr>` (zero `unsafe`) and compile on first use via
48/// wait-free [`OnceLock`] slots so `IrIndex::build` performs zero upfront
49/// MPT construction or SHA-256 hashing for unexecuted circuits.
50#[derive(Debug, Default)]
51pub struct IrIndex {
52    ir_ptr: usize,
53    witnesses_by_name: FxHashMap<String, usize>,
54    natives_by_uniq: FxHashMap<u64, usize>,
55    natives_by_name: FxHashMap<String, Vec<usize>>,
56    circuits_by_uniq: FxHashMap<u64, usize>,
57    circuits_by_name: FxHashMap<String, Vec<usize>>,
58    exported_circuits_by_name: FxHashMap<String, usize>,
59    compiled_queries: FxHashMap<(usize, usize), OnceLock<Option<CompiledLedgerQuery>>>,
60    circuit_idx_by_ptr: FxHashMap<usize, usize>,
61    circuit_io_plans: Vec<OnceLock<CircuitIoPlan>>,
62    estimated_transcript_ops: Vec<usize>,
63    witness_result_plans: Vec<OnceLock<Option<FabPlan>>>,
64    native_idx_by_ptr: FxHashMap<usize, usize>,
65    native_plans: Vec<OnceLock<NativeFabPlans>>,
66    compiled_circuits: Vec<OnceLock<Option<CompiledCircuit>>>,
67    compiled_constructor: OnceLock<Option<CompiledCircuit>>,
68}
69
70impl IrIndex {
71    /// Build O(1) symbol lookup tables, lazy query/FAB cache slots, and
72    /// per-circuit transcript capacity hints for `ir`.
73    #[must_use]
74    pub fn build(ir: &MoonIr) -> Self {
75        let ir_ptr = std::ptr::from_ref(ir) as usize;
76        let mut witnesses_by_name =
77            FxHashMap::with_capacity_and_hasher(ir.witnesses.len(), FxBuildHasher);
78        let mut witness_result_plans = Vec::with_capacity(ir.witnesses.len());
79        for (idx, w) in ir.witnesses.iter().enumerate() {
80            witnesses_by_name.entry(w.name.clone()).or_insert(idx);
81            witness_result_plans.push(OnceLock::new());
82        }
83
84        let mut natives_by_uniq =
85            FxHashMap::with_capacity_and_hasher(ir.natives.len(), FxBuildHasher);
86        let mut natives_by_name: FxHashMap<String, Vec<usize>> =
87            FxHashMap::with_capacity_and_hasher(ir.natives.len(), FxBuildHasher);
88        let mut native_idx_by_ptr =
89            FxHashMap::with_capacity_and_hasher(ir.natives.len(), FxBuildHasher);
90        let mut native_plans = Vec::with_capacity(ir.natives.len());
91        for (idx, n) in ir.natives.iter().enumerate() {
92            if let Some(u) = n.internal_uniq {
93                natives_by_uniq.insert(u, idx);
94            }
95            natives_by_name.entry(n.name.clone()).or_default().push(idx);
96            native_idx_by_ptr.insert(std::ptr::from_ref(n) as usize, idx);
97            native_plans.push(OnceLock::new());
98        }
99
100        let mut circuits_by_uniq =
101            FxHashMap::with_capacity_and_hasher(ir.circuits.len(), FxBuildHasher);
102        let mut circuits_by_name: FxHashMap<String, Vec<usize>> =
103            FxHashMap::with_capacity_and_hasher(ir.circuits.len(), FxBuildHasher);
104        let mut exported_circuits_by_name =
105            FxHashMap::with_capacity_and_hasher(ir.circuits.len(), FxBuildHasher);
106        let mut circuit_idx_by_ptr =
107            FxHashMap::with_capacity_and_hasher(ir.circuits.len(), FxBuildHasher);
108        let mut circuit_io_plans = Vec::with_capacity(ir.circuits.len());
109
110        for (idx, c) in ir.circuits.iter().enumerate() {
111            if let Some(u) = c.internal_uniq {
112                circuits_by_uniq.insert(u, idx);
113            }
114            circuits_by_name
115                .entry(c.name.clone())
116                .or_default()
117                .push(idx);
118            if c.exported {
119                exported_circuits_by_name
120                    .entry(c.name.clone())
121                    .or_insert(idx);
122            }
123            circuit_idx_by_ptr.insert(std::ptr::from_ref(c) as usize, idx);
124            circuit_io_plans.push(OnceLock::new());
125        }
126
127        let mut compiled_queries = FxHashMap::default();
128        let mut ctor_acc = QueryScanAcc::default();
129        for init_op in &ir.constructor.init_ops {
130            collect_expr_queries(init_op, &mut compiled_queries, &mut ctor_acc);
131        }
132        collect_stmt_queries(&ir.constructor.body, &mut compiled_queries, &mut ctor_acc);
133
134        let mut direct_ops = Vec::with_capacity(ir.circuits.len());
135        let mut call_refs: Vec<Vec<(Option<u64>, &str)>> = Vec::with_capacity(ir.circuits.len());
136        for c in &ir.circuits {
137            let mut acc = QueryScanAcc::default();
138            collect_stmt_queries(&c.body, &mut compiled_queries, &mut acc);
139            direct_ops.push(acc.direct_transcript_ops);
140            call_refs.push(acc.callees);
141        }
142
143        let mut estimated_transcript_ops = Vec::with_capacity(ir.circuits.len());
144        let mut visited = vec![false; ir.circuits.len()];
145        for idx in 0..ir.circuits.len() {
146            visited.fill(false);
147            let total = estimate_circuit_ops(
148                idx,
149                &direct_ops,
150                &call_refs,
151                &circuits_by_uniq,
152                &circuits_by_name,
153                &mut visited,
154            );
155            estimated_transcript_ops.push(total.min(MAX_TRANSCRIPT_CAPACITY_HINT));
156        }
157
158        let mut compiled_circuits = Vec::with_capacity(ir.circuits.len());
159        for _ in 0..ir.circuits.len() {
160            compiled_circuits.push(OnceLock::new());
161        }
162
163        Self {
164            ir_ptr,
165            witnesses_by_name,
166            natives_by_uniq,
167            natives_by_name,
168            circuits_by_uniq,
169            circuits_by_name,
170            exported_circuits_by_name,
171            compiled_queries,
172            circuit_idx_by_ptr,
173            circuit_io_plans,
174            estimated_transcript_ops,
175            witness_result_plans,
176            native_idx_by_ptr,
177            native_plans,
178            compiled_circuits,
179            compiled_constructor: OnceLock::new(),
180        }
181    }
182
183    /// Return `true` when this index was built for the exact `MoonIr`
184    /// allocation at `ir`. Guards every pointer- and index-based lookup
185    /// against accidental reuse with a moved or distinct IR instance.
186    #[inline]
187    #[must_use]
188    pub fn matches_ir(&self, ir: &MoonIr) -> bool {
189        self.ir_ptr != 0 && self.ir_ptr == std::ptr::from_ref(ir) as usize
190    }
191
192    #[inline]
193    #[must_use]
194    pub fn witness<'ir>(&self, ir: &'ir MoonIr, name: &str) -> Option<&'ir Witness> {
195        if !self.matches_ir(ir) {
196            return None;
197        }
198        let &idx = self.witnesses_by_name.get(name)?;
199        ir.witnesses.get(idx)
200    }
201
202    #[inline]
203    #[must_use]
204    pub fn witness_with_plan<'a, 'ir>(
205        &'a self,
206        ir: &'ir MoonIr,
207        name: &str,
208    ) -> Option<(&'ir Witness, Option<&'a FabPlan>)> {
209        if !self.matches_ir(ir) {
210            return None;
211        }
212        let &idx = self.witnesses_by_name.get(name)?;
213        let witness = ir.witnesses.get(idx)?;
214        let plan = self
215            .witness_result_plans
216            .get(idx)?
217            .get_or_init(|| FabPlan::compile(&witness.result_type))
218            .as_ref();
219        Some((witness, plan))
220    }
221
222    #[inline]
223    #[must_use]
224    pub fn native_by_uniq<'ir>(&self, ir: &'ir MoonIr, uniq: u64) -> Option<&'ir Native> {
225        if !self.matches_ir(ir) {
226            return None;
227        }
228        let &idx = self.natives_by_uniq.get(&uniq)?;
229        ir.natives.get(idx)
230    }
231
232    #[inline]
233    #[must_use]
234    pub fn native_indices_by_name(&self, ir: &MoonIr, name: &str) -> Option<&[usize]> {
235        if !self.matches_ir(ir) {
236            return None;
237        }
238        self.natives_by_name.get(name).map(Vec::as_slice)
239    }
240
241    #[inline]
242    #[must_use]
243    pub fn native_plans(&self, ir: &MoonIr, native: &Native) -> Option<&NativeFabPlans> {
244        if !self.matches_ir(ir) {
245            return None;
246        }
247        let &idx = self
248            .native_idx_by_ptr
249            .get(&(std::ptr::from_ref(native) as usize))?;
250        let slot = self.native_plans.get(idx)?;
251        Some(slot.get_or_init(|| {
252            NativeFabPlans {
253                args: native
254                    .arguments
255                    .iter()
256                    .map(|a| FabPlan::compile(&a.arg_type))
257                    .collect(),
258                result: FabPlan::compile(&native.result_type),
259            }
260        }))
261    }
262
263    #[inline]
264    #[must_use]
265    pub fn circuit_by_uniq<'ir>(&self, ir: &'ir MoonIr, uniq: u64) -> Option<&'ir CircuitBody> {
266        if !self.matches_ir(ir) {
267            return None;
268        }
269        let &idx = self.circuits_by_uniq.get(&uniq)?;
270        ir.circuits.get(idx)
271    }
272
273    #[inline]
274    #[must_use]
275    pub fn circuit_indices_by_name(&self, ir: &MoonIr, name: &str) -> Option<&[usize]> {
276        if !self.matches_ir(ir) {
277            return None;
278        }
279        self.circuits_by_name.get(name).map(Vec::as_slice)
280    }
281
282    #[inline]
283    #[must_use]
284    pub fn first_circuit<'ir>(&self, ir: &'ir MoonIr, name: &str) -> Option<&'ir CircuitBody> {
285        if !self.matches_ir(ir) {
286            return None;
287        }
288        let indices = self.circuits_by_name.get(name)?;
289        let &idx = indices.first()?;
290        ir.circuits.get(idx)
291    }
292
293    #[inline]
294    #[must_use]
295    pub fn exported_circuit<'ir>(&self, ir: &'ir MoonIr, name: &str) -> Option<&'ir CircuitBody> {
296        if !self.matches_ir(ir) {
297            return None;
298        }
299        let &idx = self.exported_circuits_by_name.get(name)?;
300        ir.circuits.get(idx)
301    }
302
303    #[inline]
304    #[must_use]
305    pub fn compiled_query(&self, ir: &MoonIr, vm_ops: &[VmInstr]) -> Option<&CompiledLedgerQuery> {
306        if !self.matches_ir(ir) || vm_ops.is_empty() {
307            return None;
308        }
309        let slot = self
310            .compiled_queries
311            .get(&(vm_ops.as_ptr() as usize, vm_ops.len()))?;
312        slot.get_or_init(|| compile_vm_ops(vm_ops)).as_ref()
313    }
314
315    #[inline]
316    #[must_use]
317    pub fn circuit_io_plan(&self, ir: &MoonIr, circuit: &CircuitBody) -> Option<&CircuitIoPlan> {
318        if !self.matches_ir(ir) {
319            return None;
320        }
321        let &idx = self
322            .circuit_idx_by_ptr
323            .get(&(std::ptr::from_ref(circuit) as usize))?;
324        let slot = self.circuit_io_plans.get(idx)?;
325        Some(slot.get_or_init(|| {
326            let input = CircuitInputPlan::compile(&circuit.arguments);
327            let output = if matches!(&circuit.result_type, TypeDescriptor::Tuple { types } if types.is_empty())
328            {
329                None
330            } else {
331                FabPlan::compile(&circuit.result_type)
332            };
333            CircuitIoPlan { input, output }
334        }))
335    }
336
337    /// Pre-computed initial capacity hint for `public_transcript` when
338    /// executing `circuit`.
339    #[inline]
340    #[must_use]
341    pub fn estimated_transcript_ops(&self, ir: &MoonIr, circuit: &CircuitBody) -> usize {
342        if !self.matches_ir(ir) {
343            return 0;
344        }
345        self.circuit_idx_by_ptr
346            .get(&(std::ptr::from_ref(circuit) as usize))
347            .and_then(|&idx| self.estimated_transcript_ops.get(idx).copied())
348            .unwrap_or(0)
349    }
350
351    /// Number of VM-op query sites indexed in this table.
352    #[must_use]
353    pub fn compiled_query_count(&self) -> usize {
354        self.compiled_queries.len()
355    }
356
357    #[inline]
358    #[must_use]
359    pub(crate) fn witness_index(&self, ir: &MoonIr, name: &str) -> Option<usize> {
360        if !self.matches_ir(ir) {
361            return None;
362        }
363        self.witnesses_by_name.get(name).copied()
364    }
365
366    #[inline]
367    #[must_use]
368    pub(crate) fn witness_result_plan_by_index(&self, ir: &MoonIr, idx: usize) -> Option<&FabPlan> {
369        if !self.matches_ir(ir) {
370            return None;
371        }
372        let witness = ir.witnesses.get(idx)?;
373        self.witness_result_plans
374            .get(idx)?
375            .get_or_init(|| FabPlan::compile(&witness.result_type))
376            .as_ref()
377    }
378
379    #[inline]
380    #[must_use]
381    pub(crate) fn native_index_by_uniq(&self, ir: &MoonIr, uniq: u64) -> Option<usize> {
382        if !self.matches_ir(ir) {
383            return None;
384        }
385        self.natives_by_uniq.get(&uniq).copied()
386    }
387
388    #[inline]
389    #[must_use]
390    pub(crate) fn circuit_index_by_uniq(&self, ir: &MoonIr, uniq: u64) -> Option<usize> {
391        if !self.matches_ir(ir) {
392            return None;
393        }
394        self.circuits_by_uniq.get(&uniq).copied()
395    }
396
397    #[inline]
398    #[must_use]
399    pub(crate) fn first_circuit_index(&self, ir: &MoonIr, name: &str) -> Option<usize> {
400        if !self.matches_ir(ir) {
401            return None;
402        }
403        self.circuits_by_name.get(name)?.first().copied()
404    }
405
406    /// Lazily compile and return the flat register bytecode for `ir.circuits[idx]`.
407    #[inline]
408    #[must_use]
409    pub(crate) fn compiled_circuit(&self, ir: &MoonIr, idx: usize) -> Option<&CompiledCircuit> {
410        if !self.matches_ir(ir) {
411            return None;
412        }
413        let circuit = ir.circuits.get(idx)?;
414        let slot = self.compiled_circuits.get(idx)?;
415        slot.get_or_init(|| compile_circuit(ir, self, circuit))
416            .as_ref()
417    }
418
419    /// Lazily compile and return the flat register bytecode for `ir.constructor`.
420    #[inline]
421    #[must_use]
422    pub(crate) fn compiled_constructor(&self, ir: &MoonIr) -> Option<&CompiledCircuit> {
423        if !self.matches_ir(ir) {
424            return None;
425        }
426        self.compiled_constructor
427            .get_or_init(|| compile_constructor(ir, self, &ir.constructor))
428            .as_ref()
429    }
430}
431
432#[derive(Default)]
433struct QueryScanAcc<'ir> {
434    direct_transcript_ops: usize,
435    callees: Vec<(Option<u64>, &'ir str)>,
436}
437
438fn estimate_circuit_ops(
439    idx: usize,
440    direct_ops: &[usize],
441    call_refs: &[Vec<(Option<u64>, &str)>],
442    circuits_by_uniq: &FxHashMap<u64, usize>,
443    circuits_by_name: &FxHashMap<String, Vec<usize>>,
444    visited: &mut [bool],
445) -> usize {
446    if visited[idx] {
447        return 0;
448    }
449    visited[idx] = true;
450    let mut total = direct_ops[idx];
451    for &(uniq, name) in &call_refs[idx] {
452        let callee_idx = uniq
453            .and_then(|u| circuits_by_uniq.get(&u).copied())
454            .or_else(|| circuits_by_name.get(name).and_then(|v| v.first().copied()));
455        if let Some(cidx) = callee_idx {
456            total = total.saturating_add(estimate_circuit_ops(
457                cidx,
458                direct_ops,
459                call_refs,
460                circuits_by_uniq,
461                circuits_by_name,
462                visited,
463            ));
464        }
465    }
466    total
467}
468
469fn register_vm_ops(
470    vm_ops: &[VmInstr],
471    out: &mut FxHashMap<(usize, usize), OnceLock<Option<CompiledLedgerQuery>>>,
472    acc: &mut QueryScanAcc<'_>,
473) {
474    if vm_ops.is_empty() {
475        return;
476    }
477    acc.direct_transcript_ops = acc.direct_transcript_ops.saturating_add(vm_ops.len());
478    out.entry((vm_ops.as_ptr() as usize, vm_ops.len()))
479        .or_default();
480}
481
482fn collect_stmt_queries<'ir>(
483    stmt: &'ir Statement,
484    out: &mut FxHashMap<(usize, usize), OnceLock<Option<CompiledLedgerQuery>>>,
485    acc: &mut QueryScanAcc<'ir>,
486) {
487    match stmt {
488        Statement::Seq { items } => {
489            for item in items {
490                collect_stmt_queries(item, out, acc);
491            }
492        }
493        Statement::If { cond, then, r#else } => {
494            collect_expr_queries(cond, out, acc);
495            collect_stmt_queries(then, out, acc);
496            if let Some(else_branch) = r#else {
497                collect_stmt_queries(else_branch, out, acc);
498            }
499        }
500        Statement::Const { value, .. } | Statement::Expr { value } => {
501            collect_expr_queries(value, out, acc);
502        }
503        Statement::ConstDestructure { .. } | Statement::Unimplemented | Statement::Noop => {}
504    }
505}
506
507#[allow(clippy::too_many_lines)]
508fn collect_expr_queries<'ir>(
509    expr: &'ir Expression,
510    out: &mut FxHashMap<(usize, usize), OnceLock<Option<CompiledLedgerQuery>>>,
511    acc: &mut QueryScanAcc<'ir>,
512) {
513    match expr {
514        Expression::AdtOp(inv) => {
515            register_vm_ops(&inv.vm_ops, out, acc);
516            for elem in &inv.field_path {
517                if let PathElement::Expr { value, .. } = elem {
518                    collect_expr_queries(value, out, acc);
519                }
520            }
521            for arg in &inv.arguments {
522                collect_expr_queries(arg, out, acc);
523            }
524        }
525        Expression::Emit {
526            payload, vm_ops, ..
527        } => {
528            register_vm_ops(vm_ops, out, acc);
529            collect_expr_queries(payload, out, acc);
530        }
531        Expression::If { cond, then, r#else } => {
532            collect_expr_queries(cond, out, acc);
533            collect_expr_queries(then, out, acc);
534            collect_expr_queries(r#else, out, acc);
535        }
536        Expression::Tuple { items } | Expression::Vector { items } => {
537            for item in items {
538                collect_expr_queries(&item.value, out, acc);
539            }
540        }
541        Expression::Seq { items }
542        | Expression::New {
543            arguments: items, ..
544        } => {
545            for item in items {
546                collect_expr_queries(item, out, acc);
547            }
548        }
549        Expression::Call {
550            function,
551            function_uniq,
552            arguments,
553        } => {
554            acc.callees.push((*function_uniq, function.as_str()));
555            for arg in arguments {
556                collect_expr_queries(arg, out, acc);
557            }
558        }
559        Expression::ContractCall {
560            address, arguments, ..
561        } => {
562            acc.direct_transcript_ops = acc
563                .direct_transcript_ops
564                .saturating_add(CLAIM_CONTRACT_CALL_OP_COUNT);
565            collect_expr_queries(address, out, acc);
566            for arg in arguments {
567                collect_expr_queries(arg, out, acc);
568            }
569        }
570        Expression::Binop { left, right, .. }
571        | Expression::Eq { left, right, .. }
572        | Expression::Neq { left, right, .. }
573        | Expression::And { left, right }
574        | Expression::Or { left, right } => {
575            collect_expr_queries(left, out, acc);
576            collect_expr_queries(right, out, acc);
577        }
578        Expression::VectorRef { value, index, .. } | Expression::BytesRef { value, index, .. } => {
579            collect_expr_queries(value, out, acc);
580            collect_expr_queries(index, out, acc);
581        }
582        Expression::VectorSlice { value, start, .. }
583        | Expression::BytesSlice { value, start, .. } => {
584            collect_expr_queries(value, out, acc);
585            collect_expr_queries(start, out, acc);
586        }
587        Expression::Assert { cond, .. } => collect_expr_queries(cond, out, acc),
588        Expression::EltRef { value, .. }
589        | Expression::TupleRef { value, .. }
590        | Expression::TupleSlice { value, .. }
591        | Expression::Not { value }
592        | Expression::Assign { value, .. }
593        | Expression::Cast { value, .. }
594        | Expression::SafeCast { value, .. }
595        | Expression::DowncastUnsigned { value, .. }
596        | Expression::FieldToBytes { value, .. }
597        | Expression::CastToField { value, .. }
598        | Expression::CastFromField { value, .. }
599        | Expression::CastFromBytes { value, .. }
600        | Expression::VectorToBytes { value, .. }
601        | Expression::BytesToVector { value, .. }
602        | Expression::CastFromEnum { value, .. }
603        | Expression::CastToEnum { value, .. } => {
604            collect_expr_queries(value, out, acc);
605        }
606        Expression::Literal { .. }
607        | Expression::Var { .. }
608        | Expression::Default { .. }
609        | Expression::EnumRef { .. }
610        | Expression::Map { .. }
611        | Expression::Fold { .. }
612        | Expression::Unimplemented => {}
613    }
614}