celox-design 0.11.0

Source-independent elaborated design model for Celox
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
//! Source-language-independent design identities and semantic vocabulary.

use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet};
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeSet, fmt};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DomainKind {
    ClockPosedge,
    ClockNegedge,
    ResetAsyncHigh,
    ResetAsyncLow,
    Other,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TriggerIdWithKind {
    pub kind: DomainKind,
    pub id: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum PortTypeKind {
    Clock,
    ResetAsyncHigh,
    ResetAsyncLow,
    ResetSyncHigh,
    ResetSyncLow,
    Logic,
    Bit,
    Other,
}

/// Source-independent metadata for one elaborated design variable.
///
/// Source IDs, source paths, and declaration syntax belong to the frontend and
/// deliberately are not part of this type.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct VariableMetadata {
    pub width: usize,
    pub is_4state: bool,
    pub kind: DomainKind,
    pub type_kind: PortTypeKind,
    /// Per-dimension sizes for array ports (for example, `[4]` for `logic<32>[4]`).
    /// Empty means scalar.
    pub array_dims: Vec<usize>,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct TriggerSet<A> {
    pub clock: A,
    pub resets: Vec<A>,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum RuntimeEventKind {
    Display,
    Write,
    AssertContinue,
    AssertFatal,
    /// `$finish` executed by the design (IEEE 1800-2023 20.2).
    Finish,
}

/// How a runtime event site sizes its formatted arguments.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum DisplaySizing {
    /// The formatting of Veryl's simulator: radices at the argument's width,
    /// decimals at their minimum, and C-style field widths that never
    /// truncate.
    #[default]
    Veryl,
    /// Automatic sizing and field widths of IEEE 1800-2023 21.2.1.2.
    Ieee,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RuntimeEventSite {
    pub kind: RuntimeEventKind,
    pub template: Option<String>,
    #[serde(default)]
    pub sizing: DisplaySizing,
    /// Fully elaborated module-instance scope that emitted this event.
    pub scope: Option<String>,
    pub arg_widths: Vec<usize>,
    pub arg_signed: Vec<bool>,
    pub arg_is_string: Vec<bool>,
}

/// A function in the host's C ABI that the design calls, such as a
/// SystemVerilog DPI-C import. `ExternCall` instructions index the design's
/// table of these.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExternFunction {
    /// The C symbol the function is linked by.
    pub name: String,
    /// The prototype every call of `name` must share (IEEE 1800-2023
    /// 35.5.4).
    pub signature: ExternSignature,
}

/// The prototype of an [`ExternFunction`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExternSignature {
    /// Whether the function is declared `pure`.
    pub pure: bool,
    /// The result, or `None` for a `void` function.
    pub result: Option<ExternType>,
    pub arguments: Vec<ExternType>,
}

/// A type an [`ExternFunction`] passes or returns.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ExternType {
    /// `bit`, passed as `svBit`.
    Bit,
    /// `logic`, passed as `svLogic`.
    Logic,
    /// `byte`, `shortint`, `int` or `longint`, passed as the C integer of
    /// that width.
    Integer { width: usize, signed: bool },
}

impl fmt::Display for ExternType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (name, signed) = match *self {
            ExternType::Bit => return f.write_str("bit"),
            ExternType::Logic => return f.write_str("logic"),
            ExternType::Integer { width: 8, signed } => ("byte", signed),
            ExternType::Integer { width: 16, signed } => ("shortint", signed),
            ExternType::Integer { width: 32, signed } => ("int", signed),
            ExternType::Integer { width: 64, signed } => ("longint", signed),
            ExternType::Integer { width, signed } => {
                return write!(f, "{}{width}", if signed { "i" } else { "u" });
            }
        };
        f.write_str(name)?;
        if !signed {
            f.write_str(" unsigned")?;
        }
        Ok(())
    }
}

impl fmt::Display for ExternFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let signature = &self.signature;
        if signature.pure {
            f.write_str("pure ")?;
        }
        f.write_str("function ")?;
        match signature.result {
            Some(result) => write!(f, "{result}")?,
            None => f.write_str("void")?,
        }
        write!(f, " {}(", self.name)?;
        for (index, argument) in signature.arguments.iter().enumerate() {
            if index > 0 {
                f.write_str(", ")?;
            }
            write!(f, "input {argument}")?;
        }
        f.write_str(")")
    }
}

/// Runtime activation recipe for one combinational event site.
///
/// Expression trees used to emit the event have already been lowered into
/// SIR.  The runtime only retains the persistent-state ranges needed to detect
/// whether the corresponding combinational process must be observed again.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RuntimeCombObserver<A> {
    pub site_id: u32,
    pub activation_group: u32,
    pub sensitivity: Vec<VarAtomBase<A>>,
    pub written_inputs: Vec<A>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InitialStateWriteRun {
    pub bit_offset: usize,
    pub bit_width: usize,
    pub value_bytes: Vec<u8>,
    pub mask_bytes: Vec<u8>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum InitialStateData {
    Packed {
        value: BigUint,
        mask: BigUint,
        written_mask: BigUint,
    },
    Writes(Vec<InitialStateWriteRun>),
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InitialStateValue<A> {
    pub address: A,
    pub data: InitialStateData,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuntimeErrorInfo<A> {
    pub message: String,
    pub signals: Vec<A>,
}

/// How a process kernel returned control to the runtime, as stored in its
/// [`ProcessSlots::status`] slot.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ProcessStatus {
    /// Resume after the number of time units stored in [`ProcessSlots::delay`].
    Delay,
    /// The process ran to the end of its body.
    Done,
    /// The process requested the end of the simulation.
    Finish,
}

impl ProcessStatus {
    /// Encoding in the status slot. Zero is never written, so a kernel that
    /// returned without reporting a status is detected.
    pub const fn code(self) -> u8 {
        match self {
            Self::Delay => 1,
            Self::Done => 2,
            Self::Finish => 3,
        }
    }

    pub const fn from_code(code: u8) -> Option<Self> {
        match code {
            1 => Some(Self::Delay),
            2 => Some(Self::Done),
            3 => Some(Self::Finish),
            _ => None,
        }
    }
}

/// State through which one process kernel exchanges control with the runtime.
///
/// A process kernel is a resumable function. On entry it reads `resume` to
/// find where it stopped; before returning it stores the next resume point,
/// a [`ProcessStatus`] code in `status` and, for a delay, the number of time
/// units in `delay`. All three are ordinary two-state state objects, so
/// checkpoints capture a suspended process.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ProcessSlots<A> {
    pub resume: A,
    pub status: A,
    pub delay: A,
}

impl<A> ProcessSlots<A> {
    pub fn map<B>(self, mut map: impl FnMut(A) -> B) -> ProcessSlots<B> {
        ProcessSlots {
            resume: map(self.resume),
            status: map(self.status),
            delay: map(self.delay),
        }
    }

    pub fn iter(&self) -> impl Iterator<Item = &A> {
        [&self.resume, &self.status, &self.delay].into_iter()
    }
}

/// Width of [`ProcessSlots::status`].
pub const PROCESS_STATUS_WIDTH: usize = 8;
/// Width of [`ProcessSlots::delay`].
pub const PROCESS_DELAY_WIDTH: usize = 64;

/// Controls which combinational stores dead store elimination preserves.
///
/// The policy is part of the runtime contract: host-side handles resolve
/// only to state the policy guarantees to keep, so a design that happens to
/// read a signal today cannot make a testbench depend on it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum DeadStorePolicy {
    /// Keep all stores (no dead store elimination). Default for user-facing builds.
    #[default]
    Off,
    /// Eliminate stores except those explicitly marked live via `live_signal()`
    /// and those loaded by execution units.
    PreserveListedSignals,
    /// Eliminate stores except those to top-module ports and those loaded by EUs.
    PreserveTopPorts,
    /// Eliminate stores except those to ports of *all* instances and those loaded by EUs.
    PreserveAllPorts,
}

/// Source-independent runtime diagnostics and observable event descriptions.
#[derive(Clone, Debug)]
pub struct RuntimeSchema<A> {
    pub runtime_errors: HashMap<i64, RuntimeErrorInfo<A>>,
    pub runtime_event_sites: Vec<RuntimeEventSite>,
    /// Extern functions called by `ExternCall`, by index.
    pub extern_functions: Vec<ExternFunction>,
    pub comb_observers: Vec<RuntimeCombObserver<A>>,
    /// Persistent state read directly by host-side testbench execution. These
    /// are optimization roots even when no SIR instruction loads them.
    pub testbench_read_roots: HashSet<A>,
    /// Bit ranges written by RTL execution units. External component outputs
    /// may not overlap these ranges because that would create multiple drivers.
    pub rtl_writes: HashSet<VarAtomBase<A>>,
    /// State objects written by combinational logic. Their values are
    /// derived from the other state, so state files recompute rather than
    /// compare them.
    pub comb_writes: HashSet<A>,
    /// Dead store elimination policy the program was compiled with. Together
    /// with `live_signals` and the design it decides which combinationally
    /// written state the host may observe.
    pub dead_store_policy: DeadStorePolicy,
    /// State explicitly declared observable for dead store elimination.
    pub live_signals: HashSet<A>,
    /// Control slots of the process kernels, in kernel order.
    pub processes: Vec<ProcessSlots<A>>,
}

impl<A> Default for RuntimeSchema<A> {
    fn default() -> Self {
        Self {
            runtime_errors: HashMap::default(),
            runtime_event_sites: Vec::new(),
            extern_functions: Vec::new(),
            comb_observers: Vec::new(),
            testbench_read_roots: HashSet::default(),
            rtl_writes: HashSet::default(),
            comb_writes: HashSet::default(),
            dead_store_policy: DeadStorePolicy::Off,
            live_signals: HashSet::default(),
            processes: Vec::new(),
        }
    }
}

/// Source-independent event-domain topology after elaboration.
///
/// Addresses are already flattened. Source paths and frontend IDs used only
/// for diagnostics or lookup deliberately live outside this structure.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound(
    serialize = "A: Serialize + Eq + std::hash::Hash + Ord",
    deserialize = "A: Deserialize<'de> + Eq + std::hash::Hash + Ord"
))]
pub struct EventTopology<A> {
    /// Alias event address to the canonical event-domain address.
    pub aliases: HashMap<A, A>,
    /// Canonical event domains in evaluation order.
    pub ordered_events: Vec<A>,
    /// Canonical clocks whose value may be changed by another event domain.
    pub cascaded_events: BTreeSet<A>,
    /// Canonical asynchronous/synchronous reset to its canonical clock.
    pub reset_clocks: HashMap<A, A>,
}

impl<A> Default for EventTopology<A> {
    fn default() -> Self {
        Self {
            aliases: HashMap::default(),
            ordered_events: Vec::new(),
            cascaded_events: BTreeSet::new(),
            reset_clocks: HashMap::default(),
        }
    }
}

impl<A: Copy + Eq + std::hash::Hash> EventTopology<A> {
    pub fn canonical(&self, address: A) -> A {
        self.aliases.get(&address).copied().unwrap_or(address)
    }

    pub fn len(&self) -> usize {
        self.ordered_events.len()
    }

    pub fn is_empty(&self) -> bool {
        self.ordered_events.is_empty()
    }
}

/// Backend-neutral semantic design data after hierarchy flattening.
///
/// This is intentionally not a frontend lookup table: every state object is
/// keyed by its flattened semantic address, and no source-language AST or path
/// type is retained.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound(
    serialize = "A: Serialize + Eq + std::hash::Hash + Ord",
    deserialize = "A: Deserialize<'de> + Eq + std::hash::Hash + Ord"
))]
pub struct ElaboratedDesign<A> {
    pub state_objects: HashMap<A, VariableMetadata>,
    pub events: EventTopology<A>,
    pub initial_state: Vec<InitialStateValue<A>>,
}

impl<A> Default for ElaboratedDesign<A> {
    fn default() -> Self {
        Self {
            state_objects: HashMap::default(),
            events: EventTopology::default(),
            initial_state: Vec::new(),
        }
    }
}

impl<A: Copy + Eq + std::hash::Hash> ElaboratedDesign<A> {
    /// Effective kinds of canonical event domains. Infer only unambiguous
    /// one-bit alias edges; declaration metadata and signal types stay intact.
    /// Opposite edges on one net require separate dispatch domains and retain
    /// their existing canonical kind here.
    pub fn event_kinds(&self) -> HashMap<A, DomainKind> {
        let mut inferred: HashMap<A, Option<DomainKind>> = HashMap::default();
        for (address, metadata) in &self.state_objects {
            if metadata.width != 1
                || !matches!(
                    metadata.kind,
                    DomainKind::ClockPosedge
                        | DomainKind::ClockNegedge
                        | DomainKind::ResetAsyncHigh
                        | DomainKind::ResetAsyncLow
                )
            {
                continue;
            }
            let canonical = self.events.canonical(*address);
            let kind = inferred.entry(canonical).or_insert(Some(metadata.kind));
            if kind.is_some_and(|kind| kind != metadata.kind) {
                *kind = None;
            }
        }
        self.events
            .ordered_events
            .iter()
            .filter_map(|address| {
                let metadata = self.state_objects.get(address)?;
                let kind = if metadata.kind == DomainKind::Other && metadata.width == 1 {
                    inferred
                        .get(address)
                        .copied()
                        .flatten()
                        .unwrap_or(metadata.kind)
                } else {
                    metadata.kind
                };
                Some((*address, kind))
            })
            .collect()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum BinaryOp {
    Add,
    Sub,
    Mul,
    DivU,
    DivS,
    RemU,
    RemS,
    And,
    Or,
    Xor,
    Shl, // Logical Shift Left (<<)
    Shr, // Logical Shift Right (>>)
    Sar, // Arithmetic Shift Right (>>>)
    Eq,
    Ne,
    EqCase,
    NeCase,
    LtU,
    LtS, // Less Than (Unsigned / Signed)
    LeU,
    LeS, // Less Equal
    GtU,
    GtS, // Greater Than
    GeU,
    GeS, // Greater Equal
    LogicAnd,
    LogicOr,
    EqWildcard,
    NeWildcard,
}

impl BinaryOp {
    /// Whether the operation is commutative (a op b == b op a).
    pub fn is_commutative(&self) -> bool {
        matches!(
            self,
            BinaryOp::Add
                | BinaryOp::Mul
                | BinaryOp::And
                | BinaryOp::Or
                | BinaryOp::Xor
                | BinaryOp::Eq
                | BinaryOp::Ne
                | BinaryOp::EqCase
                | BinaryOp::NeCase
                | BinaryOp::LogicAnd
                | BinaryOp::LogicOr
        )
    }
}

impl fmt::Display for BinaryOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let op_str = match self {
            BinaryOp::Add => "Add",
            BinaryOp::Sub => "Sub",
            BinaryOp::Mul => "Mul",
            BinaryOp::DivU => "DivU",
            BinaryOp::DivS => "DivS",
            BinaryOp::RemU => "RemU",
            BinaryOp::RemS => "RemS",
            BinaryOp::And => "And",
            BinaryOp::Or => "Or",
            BinaryOp::Xor => "Xor",
            BinaryOp::Shl => "Shl",
            BinaryOp::Shr => "Shr",
            BinaryOp::Sar => "Sar",
            BinaryOp::Eq => "Eq",
            BinaryOp::Ne => "Ne",
            BinaryOp::EqCase => "EqCase",
            BinaryOp::NeCase => "NeCase",
            BinaryOp::LtU => "LtU",
            BinaryOp::LtS => "LtS",
            BinaryOp::LeU => "LeU",
            BinaryOp::LeS => "LeS",
            BinaryOp::GtU => "GtU",
            BinaryOp::GtS => "GtS",
            BinaryOp::GeU => "GeU",
            BinaryOp::GeS => "GeS",
            BinaryOp::LogicAnd => "LogicAnd",
            BinaryOp::LogicOr => "LogicOr",
            BinaryOp::EqWildcard => "EqWildcard",
            BinaryOp::NeWildcard => "NeWildcard",
        };
        write!(f, "{}", op_str)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum UnaryOp {
    Ident,
    /// Convert a four-state value to two-state form. Unknown bits become zero:
    /// `(value, mask) -> (value & !mask, 0)`.
    ToTwoState,
    Minus,
    BitNot,
    LogicNot,
    And,
    Or,
    Xor,
    PopCount,
    CountLeadingZeros,
    CountTrailingZeros,
}

impl UnaryOp {
    /// Return the canonical result width for an operand of `operand_width` bits.
    ///
    /// Bit-count operations return a value in `0..=operand_width`, which needs
    /// `ceil(log2(operand_width + 1))` bits.  Computing that as the bit length
    /// of `operand_width` avoids overflowing when the operand width is
    /// `usize::MAX`.
    pub fn result_width(self, operand_width: usize) -> usize {
        match self {
            UnaryOp::LogicNot | UnaryOp::And | UnaryOp::Or | UnaryOp::Xor => 1,
            UnaryOp::Ident | UnaryOp::ToTwoState | UnaryOp::Minus | UnaryOp::BitNot => {
                operand_width
            }
            UnaryOp::PopCount | UnaryOp::CountLeadingZeros | UnaryOp::CountTrailingZeros => {
                usize::BITS as usize - operand_width.leading_zeros() as usize
            }
        }
    }
}

impl fmt::Display for UnaryOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let op_str = match self {
            UnaryOp::Ident => "Ident",
            UnaryOp::ToTwoState => "ToTwoState",
            UnaryOp::Minus => "Minus",
            UnaryOp::BitNot => "BitNot",
            UnaryOp::LogicNot => "LogicNot",
            UnaryOp::And => "And",
            UnaryOp::Or => "Or",
            UnaryOp::Xor => "Xor",
            UnaryOp::PopCount => "PopCount",
            UnaryOp::CountLeadingZeros => "CountLeadingZeros",
            UnaryOp::CountTrailingZeros => "CountTrailingZeros",
        };
        write!(f, "{}", op_str)
    }
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
pub struct BitAccess {
    pub lsb: usize,
    pub msb: usize,
}
impl BitAccess {
    pub fn new(lsb: usize, msb: usize) -> Self {
        debug_assert!(lsb <= msb, "lsb must be less than or equal to msb");
        Self { lsb, msb }
    }
    pub fn overlaps(&self, other: &Self) -> bool {
        !(self.msb < other.lsb || other.msb < self.lsb)
    }

    /// Calculates the atomic bit ranges for a given access range and a set of boundaries.
    pub fn calculate_atoms(&self, bounds: &BTreeSet<usize>) -> Vec<Self> {
        use std::ops::Bound::*;
        let mut atoms = Vec::new();
        let mut current_lsb = self.lsb;

        // Iterate through the boundaries that are within the access range
        // Excluded(lsb) to Included(msb) handles lsb == msb case naturally (returns empty iterator)
        for &bound in bounds.range((Excluded(self.lsb), Included(self.msb))) {
            atoms.push(Self::new(current_lsb, bound - 1));
            current_lsb = bound;
        }

        // Add the last atom
        if current_lsb <= self.msb {
            atoms.push(Self::new(current_lsb, self.msb));
        }

        atoms
    }
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
pub struct VarAtomBase<A> {
    pub id: A,
    pub access: BitAccess,
}
impl<A> VarAtomBase<A> {
    pub fn new(id: A, lsb: usize, msb: usize) -> Self {
        Self {
            id,
            access: BitAccess { lsb, msb },
        }
    }
}
impl fmt::Display for BitAccess {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.lsb == self.msb {
            write!(f, "[{}]", self.lsb)
        } else {
            write!(f, "[{}:{}]", self.msb, self.lsb)
        }
    }
}

impl<A> fmt::Display for VarAtomBase<A>
where
    A: fmt::Display + std::hash::Hash + Eq,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.id, self.access)
    }
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ModuleId(pub usize);

impl fmt::Display for ModuleId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "mod{}", self.0)
    }
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct InstanceId(pub usize);

impl fmt::Display for InstanceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "inst{}", self.0)
    }
}

/// Dense source-independent identity of one flattened state object.
///
/// Frontends assign this identity during design projection. Source variable
/// IDs must not cross into SIR optimization, layout, or backend code.
#[derive(
    Debug, Clone, Copy, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
)]
pub struct StateObjectId(pub u32);

impl StateObjectId {
    pub const fn from_raw(value: u32) -> Self {
        Self(value)
    }
}

impl fmt::Display for StateObjectId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "state{}", self.0)
    }
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct AbsoluteAddrBase<V> {
    pub instance_id: InstanceId,
    pub var_id: V,
}

impl<V: fmt::Display> fmt::Display for AbsoluteAddrBase<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AbsoluteAddr({}, {})", self.instance_id, self.var_id)
    }
}

pub const STABLE_REGION: u32 = 0;
pub const WORKING_REGION: u32 = 1;
pub const SPARSE_WORKING_REGION: u32 = 2;

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RegionedVarAddrBase<V> {
    pub region: u32,
    pub var_id: V,
}

impl<V: fmt::Display> fmt::Display for RegionedVarAddrBase<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "RegionedVarAddr(region={}, {})",
            self.region, self.var_id
        )
    }
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RegionedAbsoluteAddrBase<V> {
    pub region: u32,
    pub instance_id: InstanceId,
    pub var_id: V,
}

pub type StateAddr = AbsoluteAddrBase<StateObjectId>;
pub type RegionedStateAddr = RegionedAbsoluteAddrBase<StateObjectId>;

impl<V: Copy> RegionedAbsoluteAddrBase<V> {
    pub fn from_absolute_addr(region: u32, addr: AbsoluteAddrBase<V>) -> Self {
        Self {
            region,
            instance_id: addr.instance_id,
            var_id: addr.var_id,
        }
    }

    pub fn absolute_addr(&self) -> AbsoluteAddrBase<V> {
        AbsoluteAddrBase {
            instance_id: self.instance_id,
            var_id: self.var_id,
        }
    }
}

impl<V: fmt::Display> fmt::Display for RegionedAbsoluteAddrBase<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "RegionedAbsoluteAddr(region={}, {}, {})",
            self.region, self.instance_id, self.var_id
        )
    }
}

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

    #[test]
    fn bit_access_splits_only_at_internal_boundaries() {
        let access = BitAccess::new(4, 11);
        let bounds = [0, 4, 7, 12, 20].into_iter().collect();

        assert_eq!(
            access.calculate_atoms(&bounds),
            vec![BitAccess::new(4, 6), BitAccess::new(7, 11)]
        );
    }

    #[test]
    fn design_ids_and_addresses_have_stable_display() {
        let address = AbsoluteAddrBase {
            instance_id: InstanceId(42),
            var_id: 7,
        };

        assert_eq!(ModuleId(3).to_string(), "mod3");
        assert_eq!(InstanceId(42).to_string(), "inst42");
        assert_eq!(StateObjectId(7).to_string(), "state7");
        assert_eq!(address.to_string(), "AbsoluteAddr(inst42, 7)");
    }

    #[test]
    fn regioned_address_round_trips_semantic_identity() {
        let address = AbsoluteAddrBase {
            instance_id: InstanceId(2),
            var_id: 9,
        };
        let regioned = RegionedAbsoluteAddrBase::from_absolute_addr(WORKING_REGION, address);

        assert_eq!(regioned.absolute_addr(), address);
        assert_eq!(regioned.region, WORKING_REGION);
    }

    #[test]
    fn semantic_operator_contracts_are_source_independent() {
        assert!(BinaryOp::Add.is_commutative());
        assert!(!BinaryOp::Sub.is_commutative());
        assert_eq!(UnaryOp::LogicNot.result_width(128), 1);
        assert_eq!(UnaryOp::PopCount.result_width(128), 8);
    }

    #[test]
    fn initial_state_and_runtime_error_schemas_accept_design_owned_ids() {
        let initial = InitialStateValue {
            address: AbsoluteAddrBase {
                instance_id: InstanceId(1),
                var_id: 7u32,
            },
            data: InitialStateData::Writes(vec![InitialStateWriteRun {
                bit_offset: 3,
                bit_width: 5,
                value_bytes: vec![0x15],
                mask_bytes: vec![0],
            }]),
        };
        let error = RuntimeErrorInfo {
            message: "failed".to_string(),
            signals: vec![initial.address],
        };
        let mut runtime = RuntimeSchema::default();
        runtime.runtime_errors.insert(1, error.clone());
        runtime.runtime_event_sites.push(RuntimeEventSite {
            kind: RuntimeEventKind::AssertFatal,
            template: Some("failed".to_string()),
            sizing: DisplaySizing::Veryl,
            scope: None,
            arg_widths: Vec::new(),
            arg_signed: Vec::new(),
            arg_is_string: Vec::new(),
        });
        runtime.comb_observers.push(RuntimeCombObserver {
            site_id: 0,
            activation_group: 0,
            sensitivity: vec![VarAtomBase {
                id: initial.address,
                access: BitAccess { lsb: 3, msb: 7 },
            }],
            written_inputs: vec![initial.address],
        });
        runtime.testbench_read_roots.insert(initial.address);

        assert_eq!(error.signals, vec![initial.address]);
        assert!(matches!(initial.data, InitialStateData::Writes(_)));
        assert_eq!(runtime.runtime_errors[&1], error);
        assert_eq!(runtime.runtime_event_sites.len(), 1);
        assert_eq!(runtime.comb_observers[0].sensitivity[0].id, initial.address);
        assert!(runtime.testbench_read_roots.contains(&initial.address));
    }

    #[test]
    fn variable_metadata_preserves_elaborated_shape_and_domain() {
        let metadata = VariableMetadata {
            width: 32,
            is_4state: true,
            kind: DomainKind::Other,
            type_kind: PortTypeKind::Logic,
            array_dims: vec![4],
        };

        assert_eq!(metadata.width, 32);
        assert_eq!(metadata.array_dims, vec![4]);
    }

    #[test]
    fn elaborated_design_uses_flat_addresses_and_canonical_event_topology() {
        let mut design = ElaboratedDesign::<u32>::default();
        design.state_objects.insert(
            10,
            VariableMetadata {
                width: 1,
                is_4state: false,
                kind: DomainKind::ClockPosedge,
                type_kind: PortTypeKind::Clock,
                array_dims: Vec::new(),
            },
        );
        design.events.aliases.insert(11, 10);
        design.events.ordered_events.push(10);

        assert_eq!(design.events.canonical(11), 10);
        assert_eq!(design.events.canonical(12), 12);
        assert_eq!(design.events.len(), 1);
        assert!(!design.events.is_empty());
        assert_eq!(design.state_objects[&10].width, 1);
    }
    #[test]
    fn alias_event_kinds_are_separate_from_declaration_metadata() {
        let mut design = ElaboratedDesign::<u32>::default();
        for (address, kind) in [
            (10, DomainKind::Other),
            (11, DomainKind::ClockPosedge),
            (20, DomainKind::Other),
            (21, DomainKind::ClockNegedge),
            (30, DomainKind::Other),
            (31, DomainKind::ClockPosedge),
            (32, DomainKind::ClockNegedge),
        ] {
            design.state_objects.insert(
                address,
                VariableMetadata {
                    width: 1,
                    is_4state: false,
                    kind,
                    type_kind: PortTypeKind::Logic,
                    array_dims: Vec::new(),
                },
            );
        }
        design.events.ordered_events = vec![10, 20, 30];
        for (alias, canonical) in [(11, 10), (21, 20), (31, 30), (32, 30)] {
            design.events.aliases.insert(alias, canonical);
        }
        let kinds = design.event_kinds();
        assert_eq!(kinds[&10], DomainKind::ClockPosedge);
        assert_eq!(kinds[&20], DomainKind::ClockNegedge);
        assert_eq!(
            kinds[&30],
            DomainKind::Other,
            "conflicting aliases do not select one edge"
        );
        assert_eq!(design.state_objects[&10].kind, DomainKind::Other);
        assert_eq!(design.state_objects[&20].type_kind, PortTypeKind::Logic);
    }
}