miden-core 0.28.0

Miden VM core components
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
use core::fmt;

use super::{EventId, EventName};

// SYSTEM EVENTS
// ================================================================================================

/// Defines a set of host-side actions which can be initiated from the VM.
///
/// Most actions update or query one of the three advice-provider components: Merkle store, advice
/// stack, or advice map. Deferred-DAG actions update host-side deferred state, and evaluation may
/// also push canonical node data to the advice stack.
///
/// All actions, except for `MerkleNodeMerge`, `Ext2Inv` and `UpdateMerkleNode` can be invoked
/// directly from Miden assembly via dedicated instructions.
///
/// System event IDs are derived from blake3-hashing their names (prefixed with "sys::").
///
/// The enum variant order matches the indices in SYSTEM_EVENT_LOOKUP, allowing efficient const
/// lookup via `to_event_id()`. The discriminants are implicitly 0, 1, 2, ... `COUNT - 1`.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum SystemEvent {
    // MERKLE STORE EVENTS
    // --------------------------------------------------------------------------------------------
    /// Creates a new Merkle tree in the advice provider by combining Merkle trees with the
    /// specified roots. The root of the new tree is defined as `Hash(LEFT_ROOT, RIGHT_ROOT)`.
    ///
    /// Inputs:
    ///   Operand stack: [LEFT_ROOT, RIGHT_ROOT, ...]
    ///   Merkle store: {LEFT_ROOT, RIGHT_ROOT}
    ///
    /// Outputs:
    ///   Operand stack: [LEFT_ROOT, RIGHT_ROOT, ...]
    ///   Merkle store: {LEFT_ROOT, RIGHT_ROOT, hash(LEFT_ROOT, RIGHT_ROOT)}
    ///
    /// After the operation, both the original trees and the new tree remains in the advice
    /// provider (i.e., the input trees are not removed).
    MerkleNodeMerge,

    // ADVICE STACK SYSTEM EVENTS
    // --------------------------------------------------------------------------------------------
    /// Pushes a node of the Merkle tree specified by the values on the top of the operand stack
    /// onto the advice stack in structural order for consumption by `AdvPopW`.
    ///
    /// Inputs:
    ///   Operand stack: [depth, index, TREE_ROOT, ...]
    ///   Advice stack: [...]
    ///   Merkle store: {TREE_ROOT<-NODE}
    ///
    /// Outputs:
    ///   Operand stack: [depth, index, TREE_ROOT, ...]
    ///   Advice stack: [NODE, ...]
    ///   Merkle store: {TREE_ROOT<-NODE}
    MerkleNodeToStack,

    /// Pushes a list of field elements onto the advice stack. The list is looked up in the advice
    /// map using the specified word from the operand stack as the key.
    ///
    /// Inputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack: [...]
    ///   Advice map: {KEY: values}
    ///
    /// Outputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack: [values, ...]
    ///   Advice map: {KEY: values}
    MapValueToStack,

    /// Pushes the number of elements in a list of field elements onto the advice stack. The list is
    /// looked up in the advice map using the specified word from the operand stack as the key.
    ///
    /// Inputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack: [...]
    ///   Advice map: {KEY: values}
    ///
    /// Outputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack: [values.len(), ...]
    ///   Advice map: {KEY: values}
    MapValueCountToStack,

    /// Pushes a list of field elements onto the advice stack, along with the number of elements in
    /// that list. The list is looked up in the advice map using the word at the top of the operand
    /// stack as the key.
    ///
    /// Notice that the resulting elements list is not padded.
    ///
    /// Inputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack: [...]
    ///   Advice map: {KEY: values}
    ///
    /// Outputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack: [num_values, values, ...]
    ///   Advice map: {KEY: values}
    MapValueToStackN0,

    /// Pushes a padded list of field elements onto the advice stack, along with the number of
    /// elements in that list. The list is looked up in the advice map using the word at the top of
    /// the operand stack as the key.
    ///
    /// Notice that the elements list obtained from the advice map will be padded with zeros,
    /// increasing its length to the next multiple of 4.
    ///
    /// Inputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack: [...]
    ///   Advice map: {KEY: values}
    ///
    /// Outputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack: [num_values, values, padding, ...]
    ///   Advice map: {KEY: values}
    MapValueToStackN4,

    /// Pushes a padded list of field elements onto the advice stack, along with the number of
    /// elements in that list. The list is looked up in the advice map using the word at the top of
    /// the operand stack as the key.
    ///
    /// Notice that the elements list obtained from the advice map will be padded with zeros,
    /// increasing its length to the next multiple of 8.
    ///
    /// Inputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack: [...]
    ///   Advice map: {KEY: values}
    ///
    /// Outputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack: [num_values, values, padding, ...]
    ///   Advice map: {KEY: values}
    MapValueToStackN8,

    /// Pushes a flag onto the advice stack whether advice map has an entry with specified key.
    ///
    /// If the advice map has the entry with the key equal to the key placed at the top of the
    /// operand stack, `1` will be pushed to the advice stack and `0` otherwise.
    ///
    /// Inputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack:  [...]
    ///
    /// Outputs:
    ///   Operand stack: [KEY, ...]
    ///   Advice stack:  [has_mapkey, ...]
    HasMapKey,

    /// Given an element in a quadratic extension field on the top of the stack (i.e., a0, b1),
    /// computes its multiplicative inverse and push the result onto the advice stack.
    ///
    /// Inputs:
    ///   Operand stack: [a1, a0, ...]
    ///   Advice stack: [...]
    ///
    /// Outputs:
    ///   Operand stack: [a1, a0, ...]
    ///   Advice stack: [b0, b1...]
    ///
    /// Where (b0, b1) is the multiplicative inverse of the extension field element (a0, a1) at the
    /// top of the stack.
    Ext2Inv,

    /// Pushes the number of the leading zeros of the top stack element onto the advice stack.
    ///
    /// Inputs:
    ///   Operand stack: [n, ...]
    ///   Advice stack: [...]
    ///
    /// Outputs:
    ///   Operand stack: [n, ...]
    ///   Advice stack: [leading_zeros, ...]
    U32Clz,

    /// Pushes the number of the trailing zeros of the top stack element onto the advice stack.
    ///
    /// Inputs:
    ///   Operand stack: [n, ...]
    ///   Advice stack: [...]
    ///
    /// Outputs:
    ///   Operand stack: [n, ...]
    ///   Advice stack: [trailing_zeros, ...]
    U32Ctz,

    /// Pushes the number of the leading ones of the top stack element onto the advice stack.
    ///
    /// Inputs:
    ///   Operand stack: [n, ...]
    ///   Advice stack: [...]
    ///
    /// Outputs:
    ///   Operand stack: [n, ...]
    ///   Advice stack: [leading_ones, ...]
    U32Clo,

    /// Pushes the number of the trailing ones of the top stack element onto the advice stack.
    ///
    /// Inputs:
    ///   Operand stack: [n, ...]
    ///   Advice stack: [...]
    ///
    /// Outputs:
    ///   Operand stack: [n, ...]
    ///   Advice stack: [trailing_ones, ...]
    U32Cto,

    /// Pushes the base 2 logarithm of the top stack element, rounded down.
    /// Inputs:
    ///   Operand stack: [n, ...]
    ///   Advice stack: [...]
    ///
    /// Outputs:
    ///   Operand stack: [n, ...]
    ///   Advice stack: [ilog2(n), ...]
    ILog2,

    // ADVICE MAP SYSTEM EVENTS
    // --------------------------------------------------------------------------------------------
    /// Reads words from memory at the specified range and inserts them into the advice map under
    /// the key `KEY` located at the top of the stack.
    ///
    /// Inputs:
    ///   Operand stack: [KEY, start_addr, end_addr, ...]
    ///   Advice map: {...}
    ///
    /// Outputs:
    ///   Operand stack: [KEY, start_addr, end_addr, ...]
    ///   Advice map: {KEY: values}
    ///
    /// Where `values` are the elements located in memory[start_addr..end_addr].
    MemToMap,

    /// Reads two word from the operand stack and inserts them into the advice map under the key
    /// defined by the hash of these words.
    ///
    /// Inputs:
    ///   Operand stack: [A, B, ...]
    ///   Advice map: {...}
    ///
    /// Outputs:
    ///   Operand stack: [A, B, ...]
    ///   Advice map: {KEY: [a0, a1, a2, a3, b0, b1, b2, b3]}
    ///
    /// Where KEY is computed as hash(A || B, domain=0).
    HdwordToMap,

    /// Reads two words from the operand stack and inserts them into the advice map under the key
    /// defined by the hash of these words (using `d` as the domain).
    ///
    /// Inputs:
    ///   Operand stack: [A, B, d, ...]
    ///   Advice map: {...}
    ///
    /// Outputs:
    ///   Operand stack: [A, B, d, ...]
    ///   Advice map: {KEY: [a0, a1, a2, a3, b0, b1, b2, b3]}
    ///
    /// Where KEY is computed as hash(A || B, d).
    HdwordToMapWithDomain,

    /// Reads four words from the operand stack and inserts them into the advice map under the key
    /// defined by the hash of these words.
    ///
    /// Inputs:
    ///   Operand stack: [A, B, C, D, ...]
    ///   Advice map: {...}
    ///
    /// Outputs:
    ///   Operand stack: [A, B, C, D, ...]
    ///   Advice map: {KEY: [A, B, C, D]} (16 elements)
    ///
    /// Where:
    /// - KEY is computed as hash_elements([A, B, C, D]) using the sponge construction (sequential
    ///   absorption; two rounds for four words).
    HqwordToMap,

    /// Reads three words from the operand stack and inserts the top two words into the advice map
    /// under the key defined by applying a Poseidon2 permutation to all three words.
    ///
    /// Inputs:
    ///   Operand stack: [A, B, C, ...]
    ///   Advice map: {...}
    ///
    /// Outputs:
    ///   Operand stack: [A, B, C, ...]
    ///   Advice map: {KEY: [a0, a1, a2, a3, b0, b1, b2, b3]}
    ///
    /// Where KEY is computed by extracting the digest elements from hperm([C, A, B]). For example,
    /// if C is [0, d, 0, 0], KEY will be set as hash(A || B, d).
    HpermToMap,

    // DEFERRED-DAG SYSTEM EVENTS
    // --------------------------------------------------------------------------------------------
    /// Registers and eagerly evaluates a deferred node whose full payload is on the operand stack.
    ///
    /// `TAG` is one word (4 field elements). `PAYLOAD_LO || PAYLOAD_HI` is eight field elements:
    /// either one [`crate::deferred::DataChunk`], two child digests (`lhs || rhs`) for a join, or
    /// one `lhs || rhs` pair for a pair-list node. Exact [`crate::deferred::Tag::CHUNKS`]
    /// (`[2, 0, 0, 0]`) is framework-owned opaque data; malformed id-2 tags are rejected during tag
    /// decode. The installed registry decodes `TAG` via
    /// [`crate::deferred::DeferredState::decode`]; `TRUE` is not accepted by this event. Tags that
    /// semantically require more data chunks or pairs are rejected during precompile-specific
    /// evaluation. Registration is performed by [`crate::deferred::DeferredState::register`], so
    /// semantic failures surface immediately.
    ///
    /// This event does not push advice or return the node digest. The stack arguments are visible
    /// in the VM execution trace, but the host-side registration is not constrained by the event.
    /// Assembly code that later relies on the digest must compute it inside the VM from the same
    /// `TAG` and payload.
    ///
    /// Inputs:
    ///   Operand stack: [event_id, PAYLOAD_LO, PAYLOAD_HI, TAG, ...]
    ///
    /// Outputs:
    ///   Operand stack:  unchanged
    ///   Advice stack:   unchanged
    ///   Deferred state: node registered and semantically evaluated
    DeferredRegister,

    /// Evaluates a registered deferred node and pushes its canonical tag and payload as advice.
    ///
    /// `NODE_DIGEST` is one word (4 field elements) and must already be registered in deferred
    /// state. The handler evaluates it with [`crate::deferred::DeferredState::evaluate_digest`],
    /// fetches the canonical node, and pushes its tag followed by its payload to the advice stack.
    ///
    /// The tag is emitted first in advice-pop order so `adv_pushw adv_pushw adv_pushw` leaves
    /// `[PAYLOAD_LO, PAYLOAD_HI, TAG, ...]` on the operand stack for a single 8-felt payload. Data
    /// payloads push two words per 8-felt chunk in advice order `HIGH, LOW`, preserving canonical
    /// chunk order. Join payloads use the same two-word LIFO convention, leaving
    /// `[lhs, rhs, TAG, ...]`. `TRUE` pushes only `Tag::TRUE`. These felts are unbound host hints.
    /// Before proof-relevant use, assembly code must relate them with VM instructions to values
    /// established independently of that advice.
    ///
    /// Inputs:
    ///   Operand stack: [event_id, NODE_DIGEST, ...]
    ///
    /// Outputs:
    ///   Operand stack: unchanged
    ///   Advice stack:  canonical tag, then canonical payload words for `adv_pushw` LIFO
    /// consumption
    DeferredEvaluate,

    /// Evaluates a registered deferred node and pushes only its canonical tag as advice.
    ///
    /// `NODE_DIGEST` is one word (4 field elements) and must already be registered in deferred
    /// state. `TRUE` pushes `Tag::TRUE`. The returned tag is an unbound host hint; before
    /// proof-relevant use, assembly code must relate it with VM instructions to a value established
    /// independently of that advice.
    ///
    /// Inputs:
    ///   Operand stack: [event_id, NODE_DIGEST, ...]
    ///
    /// Outputs:
    ///   Operand stack: unchanged
    ///   Advice stack:  canonical tag only
    DeferredEvaluateTag,

    /// Evaluates a registered deferred node and pushes only its canonical payload as advice.
    ///
    /// This is the payload-only compatibility event. Data payloads push two words per 8-felt chunk
    /// in advice order `HIGH, LOW` so `adv_pushw adv_pushw` leaves `[LOW, HIGH, ...]` on the
    /// operand stack for that chunk. Chunks are emitted in canonical chunk order. Join payloads use
    /// the same two-word LIFO convention, leaving `[lhs, rhs, ...]` after two `adv_pushw`s. `TRUE`
    /// pushes no advice. These felts are unbound host hints. Before proof-relevant use, assembly
    /// code must relate them with VM instructions to values established independently of that
    /// advice.
    ///
    /// Inputs:
    ///   Operand stack: [event_id, NODE_DIGEST, ...]
    ///
    /// Outputs:
    ///   Operand stack: unchanged
    ///   Advice stack:  canonical payload only, word-ordered for `adv_pushw` LIFO consumption
    DeferredEvaluatePayload,

    /// Registers and eagerly evaluates a memory-backed deferred node.
    ///
    /// `TAG` is one word (4 field elements), and the installed registry decodes it to determine the
    /// memory-backed payload shape. The stack-supplied `ptr` and `n_chunks` are visible in the VM
    /// execution trace and select the range `[ptr, ptr + 8 * n_chunks)`. The host reads `n_chunks`
    /// 8-felt [`crate::deferred::DataChunk`] values from that range, but this event adds no AIR
    /// constraint tying the registered contents to those memory cells.
    ///
    /// Exact [`crate::deferred::Tag::CHUNKS`] (`[2, 0, 0, 0]`) registers the chunks as
    /// framework-owned opaque data, while other data tags remain precompile-owned. Malformed id-2
    /// tags are rejected during tag decode. Pair-list tags interpret chunks as `lhs || rhs` pairs.
    /// Join tags require `n_chunks == 1` and interpret the single chunk as `lhs || rhs`. `TRUE` is
    /// not accepted. The handler performs a cheap budget pre-check before allocating or reading
    /// memory, then delegates registration to [`crate::deferred::DeferredState::register`].
    ///
    /// This event does not push advice or return the node digest. A program that relies on the
    /// registered node must compute its digest with VM instructions from the same `TAG` and ordered
    /// chunk sequence. The `register_mem` MASM wrapper does this by applying a Poseidon2 linear
    /// hash to the same range, with one absorption per chunk and `TAG` as the initial capacity
    /// word. If the event and the VM hash different chunk sequences, the VM-computed digest
    /// does not identify the host-registered node and cannot bind that registration into a
    /// proof-relevant deferred claim.
    ///
    /// Inputs:
    ///   Operand stack: [event_id, TAG, ptr, n_chunks, ...]
    ///
    /// Outputs:
    ///   Operand stack:  unchanged
    ///   Advice stack:   unchanged
    ///   Deferred state: node registered and semantically evaluated
    DeferredRegisterData,

    // NON-MUTATING SYSTEM EVENTS
    // --------------------------------------------------------------------------------------------
    /// Signals an optional, read-only trace event to the host.
    ///
    /// When `emit` observes this system event ID at stack position 0, the VM forwards the user
    /// trace event ID at stack position 1 to the host's trace handler. This is typically emitted
    /// as `push.<user_trace_id> push.<sys::trace_event> emit`. Trace handlers can observe
    /// the processor state, but cannot mutate VM state or the advice provider. If no handler is
    /// registered for the user trace event ID, the event is a no-op.
    ///
    /// Hosts are expected to not raise an error if they encounter a `user_trace_id` for which no
    /// trace handler is registered.
    ///
    /// Inputs:
    ///   Operand stack: [sys::trace_event, user_trace_id, ...]
    ///
    /// Outputs:
    ///   Operand stack: unchanged
    ///   Advice provider: unchanged
    TraceEvent,
}

impl SystemEvent {
    /// Attempts to convert an EventId into a SystemEvent by looking it up in the const table.
    ///
    /// Returns `Some(SystemEvent)` if the ID matches a known system event, `None` otherwise.
    /// This uses a const lookup table with hardcoded EventIds, avoiding runtime hash computation.
    pub const fn from_event_id(event_id: EventId) -> Option<Self> {
        let lookup = Self::LOOKUP;
        let mut i = 0;
        while i < lookup.len() {
            if lookup[i].id.as_u64() == event_id.as_u64() {
                return Some(lookup[i].event);
            }
            i += 1;
        }
        None
    }

    /// Attempts to convert a name into a SystemEvent by looking it up in the const table.
    ///
    /// Returns `Some(SystemEvent)` if the name matches a known system event, `None` otherwise.
    /// This uses const string comparison against the lookup table.
    pub const fn from_name(name: &str) -> Option<Self> {
        let lookup = Self::LOOKUP;
        let mut i = 0;
        while i < lookup.len() {
            if str_eq(name, lookup[i].name) {
                return Some(lookup[i].event);
            }
            i += 1;
        }
        None
    }

    /// Returns the human-readable name of this system event as an [`EventName`].
    ///
    /// System event names are prefixed with `sys::` to distinguish them from user-defined events.
    pub const fn event_name(&self) -> EventName {
        EventName::new(Self::LOOKUP[*self as usize].name)
    }

    /// Returns the [`EventId`] for this system event.
    ///
    /// The ID is looked up from the const LOOKUP table using the enum's discriminant
    /// as the index. The discriminants are explicitly set to match the array indices.
    pub const fn event_id(&self) -> EventId {
        Self::LOOKUP[*self as usize].id
    }

    /// Returns an array of all system event variants.
    pub const fn all() -> [Self; Self::COUNT] {
        [
            Self::MerkleNodeMerge,
            Self::MerkleNodeToStack,
            Self::MapValueToStack,
            Self::MapValueCountToStack,
            Self::MapValueToStackN0,
            Self::MapValueToStackN4,
            Self::MapValueToStackN8,
            Self::HasMapKey,
            Self::Ext2Inv,
            Self::U32Clz,
            Self::U32Ctz,
            Self::U32Clo,
            Self::U32Cto,
            Self::ILog2,
            Self::MemToMap,
            Self::HdwordToMap,
            Self::HdwordToMapWithDomain,
            Self::HqwordToMap,
            Self::HpermToMap,
            Self::DeferredRegister,
            Self::DeferredEvaluate,
            Self::DeferredEvaluateTag,
            Self::DeferredEvaluatePayload,
            Self::DeferredRegisterData,
            Self::TraceEvent,
        ]
    }
}

impl From<SystemEvent> for EventName {
    fn from(system_event: SystemEvent) -> Self {
        system_event.event_name()
    }
}

impl crate::prettier::PrettyPrint for SystemEvent {
    fn render(&self) -> crate::prettier::Document {
        crate::prettier::display(self)
    }
}

impl fmt::Display for SystemEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        const PREFIX_LEN: usize = "sys::".len();

        let (_prefix, rest) = Self::LOOKUP[*self as usize].name.split_at(PREFIX_LEN);
        write!(f, "{rest}")
    }
}

// LOOKUP TABLE
// ================================================================================================

/// An entry in the system event lookup table, containing all metadata for a system event.
#[derive(Copy, Clone, Debug)]
pub(crate) struct SystemEventEntry {
    /// The unique event ID (hash of the name)
    pub id: EventId,
    /// The system event variant
    pub event: SystemEvent,
    /// The full event name string (e.g., "sys::merkle_node_merge")
    pub name: &'static str,
}

impl SystemEvent {
    /// The total number of system events.
    pub const COUNT: usize = 25;

    /// Lookup table mapping system events to their metadata.
    ///
    /// The enum variant order matches the indices in this table, allowing efficient const
    /// lookup via array indexing using discriminants.
    const LOOKUP: [SystemEventEntry; Self::COUNT] = [
        SystemEventEntry {
            id: EventId::from_u64(7243907139105902342),
            event: SystemEvent::MerkleNodeMerge,
            name: "sys::merkle_node_merge",
        },
        SystemEventEntry {
            id: EventId::from_u64(6873007751276594108),
            event: SystemEvent::MerkleNodeToStack,
            name: "sys::merkle_node_to_stack",
        },
        SystemEventEntry {
            id: EventId::from_u64(17843484659000820118),
            event: SystemEvent::MapValueToStack,
            name: "sys::map_value_to_stack",
        },
        SystemEventEntry {
            id: EventId::from_u64(3470274154276391308),
            event: SystemEvent::MapValueCountToStack,
            name: "sys::map_value_count_to_stack",
        },
        SystemEventEntry {
            id: EventId::from_u64(11775886982554463322),
            event: SystemEvent::MapValueToStackN0,
            name: "sys::map_value_to_stack_n_0",
        },
        SystemEventEntry {
            id: EventId::from_u64(3443305460233942990),
            event: SystemEvent::MapValueToStackN4,
            name: "sys::map_value_to_stack_n_4",
        },
        SystemEventEntry {
            id: EventId::from_u64(1741586542981559489),
            event: SystemEvent::MapValueToStackN8,
            name: "sys::map_value_to_stack_n_8",
        },
        SystemEventEntry {
            id: EventId::from_u64(5642583036089175977),
            event: SystemEvent::HasMapKey,
            name: "sys::has_map_key",
        },
        SystemEventEntry {
            id: EventId::from_u64(9660728691489438960),
            event: SystemEvent::Ext2Inv,
            name: "sys::ext2_inv",
        },
        SystemEventEntry {
            id: EventId::from_u64(1503707361178382932),
            event: SystemEvent::U32Clz,
            name: "sys::u32_clz",
        },
        SystemEventEntry {
            id: EventId::from_u64(10656887096526143429),
            event: SystemEvent::U32Ctz,
            name: "sys::u32_ctz",
        },
        SystemEventEntry {
            id: EventId::from_u64(12846584985739176048),
            event: SystemEvent::U32Clo,
            name: "sys::u32_clo",
        },
        SystemEventEntry {
            id: EventId::from_u64(6773574803673468616),
            event: SystemEvent::U32Cto,
            name: "sys::u32_cto",
        },
        SystemEventEntry {
            id: EventId::from_u64(7444351342957461231),
            event: SystemEvent::ILog2,
            name: "sys::ilog2",
        },
        SystemEventEntry {
            id: EventId::from_u64(5768534446586058686),
            event: SystemEvent::MemToMap,
            name: "sys::mem_to_map",
        },
        SystemEventEntry {
            id: EventId::from_u64(5988159172915333521),
            event: SystemEvent::HdwordToMap,
            name: "sys::hdword_to_map",
        },
        SystemEventEntry {
            id: EventId::from_u64(6143777601072385586),
            event: SystemEvent::HdwordToMapWithDomain,
            name: "sys::hdword_to_map_with_domain",
        },
        SystemEventEntry {
            id: EventId::from_u64(11723176702659679401),
            event: SystemEvent::HqwordToMap,
            name: "sys::hqword_to_map",
        },
        SystemEventEntry {
            id: EventId::from_u64(6190830263511605775),
            event: SystemEvent::HpermToMap,
            name: "sys::hperm_to_map",
        },
        SystemEventEntry {
            id: EventId::from_u64(3200266522440553751),
            event: SystemEvent::DeferredRegister,
            name: "sys::adv::register_deferred",
        },
        SystemEventEntry {
            id: EventId::from_u64(12566028600487412345),
            event: SystemEvent::DeferredEvaluate,
            name: "sys::adv::evaluate_deferred",
        },
        SystemEventEntry {
            id: EventId::from_u64(15463062559264590613),
            event: SystemEvent::DeferredEvaluateTag,
            name: "sys::adv::evaluate_deferred_tag",
        },
        SystemEventEntry {
            id: EventId::from_u64(8091749904895009326),
            event: SystemEvent::DeferredEvaluatePayload,
            name: "sys::adv::evaluate_deferred_payload",
        },
        SystemEventEntry {
            id: EventId::from_u64(13021247594355482329),
            event: SystemEvent::DeferredRegisterData,
            name: "sys::adv::register_deferred_data",
        },
        SystemEventEntry {
            id: EventId::from_u64(1768618069850226410),
            event: SystemEvent::TraceEvent,
            name: "sys::trace_event",
        },
    ];
}

// HELPERS
// ================================================================================================

/// Const-compatible string equality check.
const fn str_eq(a: &str, b: &str) -> bool {
    let a_bytes = a.as_bytes();
    let b_bytes = b.as_bytes();

    if a_bytes.len() != b_bytes.len() {
        return false;
    }

    let mut i = 0;
    while i < a_bytes.len() {
        if a_bytes[i] != b_bytes[i] {
            return false;
        }
        i += 1;
    }
    true
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_system_events() {
        // Comprehensive test verifying consistency between SystemEvent::all() and
        // SystemEvent::LOOKUP. This ensures all() and LOOKUP are in sync, lookup table has
        // correct IDs/names, and all variants are covered.

        // Verify lengths match COUNT
        assert_eq!(SystemEvent::all().len(), SystemEvent::COUNT);
        assert_eq!(SystemEvent::LOOKUP.len(), SystemEvent::COUNT);

        // Iterate through both all() and LOOKUP together, checking all invariants
        for (i, (event, entry)) in
            SystemEvent::all().iter().zip(SystemEvent::LOOKUP.iter()).enumerate()
        {
            // Verify LOOKUP entry matches the event at the same index
            assert_eq!(
                entry.event, *event,
                "LOOKUP[{}].event ({:?}) doesn't match all()[{}] ({:?})",
                i, entry.event, i, event
            );

            // Verify LOOKUP entry ID matches enum lookup.
            let looked_up_id = event.event_id();
            assert_eq!(
                entry.id,
                looked_up_id,
                "LOOKUP[{}].id is EventId::from_u64({}), but {:?}.event_id() returns EventId::from_u64({})",
                i,
                entry.id.as_u64(),
                event,
                looked_up_id.as_u64()
            );

            // Verify name has correct "sys::" prefix
            assert!(
                entry.name.starts_with("sys::"),
                "SystemEvent name should start with 'sys::': {}",
                entry.name
            );

            // Verify from_event_id lookup works
            let looked_up =
                SystemEvent::from_event_id(entry.id).expect("SystemEvent should be found by ID");
            assert_eq!(looked_up, *event);

            // Verify from_name lookup works
            let looked_up_by_name =
                SystemEvent::from_name(entry.name).expect("SystemEvent should be found by name");
            assert_eq!(looked_up_by_name, *event);

            // Verify EventName conversion works
            let event_name = event.event_name();
            assert_eq!(event_name.as_str(), entry.name);
            assert!(SystemEvent::from_name(event_name.as_str()).is_some());
            let event_name_from_into: EventName = (*event).into();
            assert_eq!(event_name_from_into.as_str(), entry.name);
            assert!(SystemEvent::from_name(event_name_from_into.as_str()).is_some());

            // Exhaustive match to ensure compile-time error when adding new variants
            match event {
                SystemEvent::MerkleNodeMerge
                | SystemEvent::MerkleNodeToStack
                | SystemEvent::MapValueToStack
                | SystemEvent::MapValueCountToStack
                | SystemEvent::MapValueToStackN0
                | SystemEvent::MapValueToStackN4
                | SystemEvent::MapValueToStackN8
                | SystemEvent::HasMapKey
                | SystemEvent::Ext2Inv
                | SystemEvent::U32Clz
                | SystemEvent::U32Ctz
                | SystemEvent::U32Clo
                | SystemEvent::U32Cto
                | SystemEvent::ILog2
                | SystemEvent::MemToMap
                | SystemEvent::HdwordToMap
                | SystemEvent::HdwordToMapWithDomain
                | SystemEvent::HqwordToMap
                | SystemEvent::HpermToMap
                | SystemEvent::DeferredRegister
                | SystemEvent::DeferredEvaluate
                | SystemEvent::DeferredEvaluateTag
                | SystemEvent::DeferredEvaluatePayload
                | SystemEvent::DeferredRegisterData
                | SystemEvent::TraceEvent => {},
            }
        }
    }
}