vj-sim 0.3.0

Netlist, scheduler and process model of the vj SystemVerilog simulator.
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
//! STATE (`vj-sim::state`) — cross-track contract only: the Rust-owned 4-state
//! arena's SoA layout query shape, its value-change fan-out primitive, and the one
//! canonical signal read/write/subscribe interface (ARCHITECTURE §2: "Signal
//! read/write/subscribe: STATE owns the one canonical primitive; VPI/FST/debugger
//! are pure consumers"). The arena implementation itself belongs to the `state`
//! track, not this contracts wave.
//!
//! Reconciliation: state.md calls the value-change listener trait `ChangeListener`;
//! scheduler.md independently sketches the same contract under the name
//! `ValueChangeSink`. Per the task's naming and because scheduler.md's signature is
//! the more concrete of the two, this crate uses `ValueChangeSink` (ledger SC-071,
//! RT-005) and does not separately define a `ChangeListener`.
//!
//! **Task 20 (ST-130) — dependency direction is an invariant, not an accident.**
//! RUNTIME consumes STATE's reference read/write API
//! ([`SignalAccess`]/[`ValueChangeSink`]) and its `Bit`/`OwnedSVInt`-adjacent
//! [`FourStateValue`] type, never the reverse: FST/VPI/`$display` are consumers,
//! not producers, of these interfaces, and no code anywhere in `vj-sim::state`
//! calls into `vj-runtime`'s FST/VPI/`$display` formatting. This crate's own
//! `Cargo.toml` (`crates/vj-sim/Cargo.toml`) lists no `vj-runtime`
//! dependency, which is the mechanically-checkable half of this invariant.
//!
//! This is not a hypothetical edge: `vj-runtime`'s `Cargo.toml` already
//! depends on `vj-sim` (since the very first crate-skeleton commit), and
//! `vj-runtime::signal_consumer::RuntimeSignalConsumer` already consumes
//! [`SignalAccess`] directly. Both halves of the invariant — the real, present
//! edge in one direction and the absent edge in the other — are guarded by an
//! automated test: `crates/vj-sim/tests/dependency_direction.rs`. Confirm
//! live with `cargo tree -p vj-sim -i vj-runtime` (expected to report no
//! path) or `cargo test -p vj-sim --test dependency_direction`; see
//! `docs/CONTRACTS.md`'s "Wave A — wA-state notes" section for the fuller
//! writeup, including for RUNTIME's own wave to keep honoring as it grows more
//! dependencies.

use vj_abi::{Bit4, Region, SimTime};

// sv-lang value conversions, the layout builder and template dedup walk the
// frontend `Design`, so they exist only with this crate's `frontend` feature.
#[cfg(feature = "frontend")]
pub(crate) mod value;
#[cfg(feature = "frontend")]
pub use value::*;

mod arena;
pub use arena::*;

#[cfg(feature = "frontend")]
pub mod storage;

#[cfg(feature = "frontend")]
pub mod event_plan;
#[cfg(feature = "frontend")]
pub mod event_pool;

#[cfg(feature = "frontend")]
mod layout;
#[cfg(feature = "frontend")]
pub use layout::*;

#[cfg(feature = "frontend")]
mod dedup;
#[cfg(feature = "frontend")]
pub use dedup::*;

mod instance;
pub use instance::*;

mod write;

mod huge_mirror;
pub use huge_mirror::{
    HugeCommit, NbaWindow, huge_commit, huge_commit_full_done, huge_mark, huge_nba_window,
    huge_prime,
};

pub mod force;
pub use write::*;

mod driver;
pub use driver::*;

pub use crate::driver_counts::*;

mod region_check;
pub use region_check::*;

mod accessor_impl;
pub use accessor_impl::*;

mod alias;
pub use alias::{AliasChange, AliasWindow, splice_window, window_value};

mod dispatch;
pub use dispatch::*;

mod rollback;
pub use rollback::*;

mod snapshot;
pub use snapshot::*;

mod frame;
pub use frame::*;

mod introspect;
pub use introspect::*;

mod kernel_ctx;
pub use kernel_ctx::*;

mod event;
// `event`'s only top-level item is `EVENT_CELL_WIDTH`; R-run Task 16's
// `alloc_event_cell`/`trigger_event`/`clear_event_pulses` are `impl
// StateEngine` methods on the already-`pub use`d `instance::StateEngine`.
pub use event::*;

mod gvt;
// `gvt` adds no new `pub` top-level items of its own -- Task 12's
// `advance_gvt`/`drain_committed_changes` are `impl StateEngine` methods on
// the already-`pub use`d `instance::StateEngine` type, so this re-export
// currently has nothing to bring in; kept for symmetry with every other
// submodule here and so a future `pub` item added to `gvt.rs` is exported
// automatically.
#[allow(unused_imports)]
pub use gvt::*;

/// Opaque per-signal handle, STATE-assigned (scheduler.md: "STATE-owned opaque
/// handle"; ledger ST-109, ST-111, SC-037). Distinct from [`vj_abi::SlotId`]:
/// `SlotId` is the ABI-facing, compile-time-constant index CODEGEN bakes into IR;
/// `StateCellId` is the in-process (non-FFI) handle the scheduler/determinism/
/// runtime Rust code passes around at simulation time. STATE's own implementation
/// is free to make them numerically related, but the two names stay distinct
/// contract types because their callers (CODEGEN vs. the scheduler) are on
/// opposite sides of the ABI boundary.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct StateCellId(pub u64);

/// The storage tiers state.md §1 splits every slot into (ledger ST-020..ST-024,
/// CG-107, CG-163).
///
/// **Review fix (Task 14 r2, blocking finding 2) adds `ForceWide`:** the
/// Wide/Memory-class counterpart of `driver::force_driver`'s dynamically
/// -allocated contribution cell, addressing `Arena`'s separate, never-sealed
/// `force_wide_aval`/`force_wide_bval` planes (`state::arena`'s
/// `alloc_force_wide_words` doc comment has the full argument) instead of the
/// ordinary `wide_aval`/`wide_bval` planes `sv_get_wide` can seal. No
/// `SlotDescriptor`/`SlotOffset` the layout builder (Task 4/6) ever produces
/// for a real elaborated signal is `ForceWide` — it is minted exclusively by
/// `force_driver` for its own synthetic, caller-invisible contribution cell,
/// never observed by CODEGEN/the accessor ABI at all.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SlotClass {
    Inline,
    Wide,
    Memory,
    ForceWide,
}

/// Compile-time layout query result STATE hands to CODEGEN (state.md §3: "baked
/// into compiled kernels as LLVM constants"; ledger ST-027, ST-037, ST-129,
/// ST-134, ST-135). Pure Rust (not `#[repr(C)]`) — this crosses the CODEGEN/STATE
/// boundary as ordinary Rust values at *compile* time, not as bytes across the
/// compiled-kernel ABI, so it has no FFI-layout obligation.
/// Task 7 adds `PartialEq` (previously `Clone, Copy, Debug` only): `slot_of`
/// (ST-129) is required to return a byte-identical `SlotOffset` across
/// repeated calls regardless of intervening `allocate_instance` calls, and
/// the direct field-by-field way to prove that in a test is a structural
/// equality check, not a `Debug`-string comparison. Every field is itself
/// `PartialEq` (`SlotClass` already derives it; the rest are plain integers),
/// so this is a safe, non-lossy derive addition.
///
/// **Task 10 (ST-027):** state.md's original state-pointer ABI design — CODEGEN
/// inlining a raw compile-time `base + word_offset` pointer directly, bypassing
/// the accessor calls above — is **superseded** by ARCHITECTURE §7 item 1's
/// accessor-ABI (ST-026). This struct's fields stay `pub` and readable (CODEGEN
/// needs them to size/typecheck a slot at compile time — width, class, element
/// count), but no function anywhere in `vj-sim::state` hands a caller a raw
/// `*mut`/`*const` pointer it could add one of these fields to itself: the
/// actual address computation (`InstanceBase` + `SlotOffset`) happens only
/// inside `accessor_impl::slot_location_for`/`write::commit_write_at`, never
/// re-derived by a caller from these fields against a raw base pointer it also
/// holds.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct SlotOffset {
    pub class: SlotClass,
    pub word_offset: u32,
    pub bit_width: u32,
    pub elem_word_count: u32,
    pub row_stride_words: u32,
    pub num_rows: u32,
}

/// Mirrors `sv_lang::EdgeKind`'s four variants (ledger SC-045, SC-067, SC-071,
/// NL-047, NL-083). Kept as this crate's own copy (rather than a re-export)
/// because `vj-sim`'s cross-track contract layer does not depend on `sv-lang`
/// in this wave (see `docs/CONTRACTS.md` open questions); the `netlist` track owns
/// the real conversion once it wires the `sv-lang` dependency for its own
/// elaboration work.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum EdgeKind {
    None,
    Posedge,
    Negedge,
    BothEdges,
}

/// Lives here, not in the frontend-only `value` module (CONTRACTS D4): the
/// driver resolver needs it with or without the `frontend` feature.
///
/// Reads bit `i` of a `FourStateValue` back out as a `Bit4` — the inverse
/// per-bit step of [`bits_to_four_state`], used by
/// [`four_state_to_owned_svint`] to thread known/unknown bits into an
/// `sv_lang::OwnedSVInt` one bit (or run) at a time.
///
/// `pub(crate)` (Task 14 deviation, not in that task's own Files list):
/// `state::driver::resolve_net_step`'s bit-by-bit fold needs this exact same
/// per-bit extraction (ST-148's "one table" discipline — reusing this
/// function, not a second hand-rolled copy of `Bit4::from_val_unk`/
/// `from_aval_bval`'s polarity). Widening from module-private to
/// `pub(crate)` only exposes it to this crate's own `state` submodules,
/// never outside `vj-sim`.
pub(crate) fn four_state_bit_at(v: &FourStateValue, i: u32) -> Bit4 {
    match v {
        FourStateValue::Narrow(word) => {
            let val = *word as u64;
            let unk = (*word >> 64) as u64;
            Bit4::from_val_unk((val >> i) & 1 != 0, (unk >> i) & 1 != 0)
        }
        FourStateValue::Wide { aval, bval } => {
            let word = (i / 64) as usize;
            let bit = i % 64;
            let a = aval.get(word).copied().unwrap_or(0);
            let b = bval.get(word).copied().unwrap_or(0);
            Bit4::from_aval_bval((a >> bit) & 1 != 0, (b >> bit) & 1 != 0)
        }
    }
}

/// STATE's cross-subsystem four-state value representation (state.md §3/§5,
/// ledger ST-008, ST-009, ST-099, ST-120): `Narrow` mirrors the accessor ABI's
/// FIXED inline `u128` word (ARCHITECTURE §6.2 / ST-008: `val` in the low 64
/// bits, `unk`/xzmask in the high 64 bits, regardless of `bit_width` —
/// [`vj_abi::bit4`]-compatible; **not** `vj-codegen::value`'s internal,
/// width-tight `i(2N)` LLVM packing, which uses a different bit offset for any
/// width < 64 — see `vj_abi::accessor`'s doc comment); `Wide` mirrors the
/// `aval`/`bval` word planes ([`vj_abi::WideView`]-compatible).
/// Reference/introspection shape only (VPI/`$display`/debugger/harness) —
/// never the codegen-emitted hot path, which calls the accessor ABI directly.
#[derive(Clone, Debug, PartialEq)]
pub enum FourStateValue {
    Narrow(u128),
    Wide { aval: Vec<u64>, bval: Vec<u64> },
}

impl FourStateValue {
    /// The value as `(aval, bval)` plane words (`aval = val ^ unk`, `bval =
    /// unk`); a narrow value is one word.
    pub fn planes(&self) -> (Vec<u64>, Vec<u64>) {
        match self {
            FourStateValue::Narrow(w) => {
                let (val, unk) = (*w as u64, (*w >> 64) as u64);
                let (a, b) = vj_abi::bit4::narrow_word_to_wide(val, unk);
                (vec![a], vec![b])
            }
            FourStateValue::Wide { aval, bval } => (aval.clone(), bval.clone()),
        }
    }
}

/// The fixed, small listener-role table state.md §5 dispatches value changes to.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ListenerRole {
    Scheduler,
    Waveform,
    Vpi,
}

/// Called by STATE/NETS after any committed write or net resolution
/// (scheduler.md §4: "the single, uniform fan-out point for variable writes AND
/// net resolution"; ledger SC-071, RT-005).
pub trait ValueChangeSink {
    fn notify_change(&mut self, cell: StateCellId, edge: EdgeKind, at: SimTime, region: Region);

    /// Whether the sink would use a [`ChangeDelta`] for `cell` (a process
    /// waits on a bit/part select of it, LRM 9.4.2): a caller builds the delta
    /// only when this is true, so a write to an unwatched signal stays free of
    /// the per-write copy.
    fn wants_delta(&self, cell: StateCellId) -> bool {
        let _ = cell;
        false
    }

    /// The old and new plane words of the update the NEXT
    /// [`Self::notify_change`] on `cell` reports. Offered only when
    /// [`Self::wants_delta`] said so.
    fn note_delta(&mut self, cell: StateCellId, delta: ChangeDelta) {
        let _ = (cell, delta);
    }
}

/// The bits one committed update changed, as plane words (`aval`/`bval`, the
/// `Wide` encoding): `lo_word` is the plane-word index of `old_a[0]`, so a
/// windowed update of a huge vector carries only the words it touched. A
/// bit/part-select event control (LRM 9.4.2) compares the selected bits of
/// `old` and `new` to decide whether *its* operand changed, and takes an edge
/// on the select's least-significant bit.
#[derive(Clone, Debug, Default)]
pub struct ChangeDelta {
    pub lo_word: usize,
    pub old_a: Vec<u64>,
    pub old_b: Vec<u64>,
    pub new_a: Vec<u64>,
    pub new_b: Vec<u64>,
}

impl ChangeDelta {
    /// The delta between two whole values (the narrow inline word and the
    /// wide planes both decode to `aval`/`bval`).
    pub fn between(old: &FourStateValue, new: &FourStateValue) -> Self {
        let (old_a, old_b) = old.planes();
        let (new_a, new_b) = new.planes();
        Self {
            lo_word: 0,
            old_a,
            old_b,
            new_a,
            new_b,
        }
    }

    fn word(plane: &[u64], lo_word: usize, word: usize) -> Option<u64> {
        word.checked_sub(lo_word)
            .and_then(|i| plane.get(i))
            .copied()
    }

    /// Bit `index` of the value before and after, as `(aval, bval)` pairs; a
    /// bit outside the carried words did not change (`None`).
    pub fn bit(&self, index: u32) -> Option<((bool, bool), (bool, bool))> {
        let (w, b) = ((index / 64) as usize, index % 64);
        let pick = |p: &[u64]| Self::word(p, self.lo_word, w).map(|x| (x >> b) & 1 != 0);
        Some((
            (pick(&self.old_a)?, pick(&self.old_b)?),
            (pick(&self.new_a)?, pick(&self.new_b)?),
        ))
    }

    /// Whether any bit of `[lsb, lsb + width)` differs, in either plane.
    pub fn range_changed(&self, lsb: u32, width: u32) -> bool {
        let (lo, hi) = (lsb as usize, lsb as usize + width as usize);
        let first = lo / 64;
        let last = hi.saturating_sub(1) / 64;
        for w in first..=last {
            let (Some(oa), Some(ob), Some(na), Some(nb)) = (
                Self::word(&self.old_a, self.lo_word, w),
                Self::word(&self.old_b, self.lo_word, w),
                Self::word(&self.new_a, self.lo_word, w),
                Self::word(&self.new_b, self.lo_word, w),
            ) else {
                continue;
            };
            let lo_bit = lo.saturating_sub(w * 64);
            let hi_bit = (hi - w * 64).min(64);
            let mask = if hi_bit - lo_bit >= 64 {
                u64::MAX
            } else {
                ((1u64 << (hi_bit - lo_bit)) - 1) << lo_bit
            };
            if ((oa ^ na) | (ob ^ nb)) & mask != 0 {
                return true;
            }
        }
        false
    }
}

/// STATE owns the one canonical signal read/write/subscribe primitive
/// (ARCHITECTURE §2); RUNTIME's VPI/FST/`$display`/debugger hosts are pure
/// consumers of this trait, never a second implementation of signal access
/// (`vj-runtime::signal_consumer` demonstrates this by depending on it).
pub trait SignalAccess {
    fn read(&self, cell: StateCellId) -> FourStateValue;
    /// Returns `true` iff the write actually changed the stored value (the
    /// old-vs-new compare state.md §3 requires before any VC record is emitted).
    fn write(&mut self, cell: StateCellId, value: FourStateValue) -> bool;
    /// One row of a memory cell (`SlotClass::Memory`). Only implemented by
    /// the real `StateEngine`; a test double that never stages a memory NBA
    /// never reaches this.
    fn read_row(&self, cell: StateCellId, row: u64) -> FourStateValue {
        let _ = row;
        unreachable!("read_row({cell:?}) on a SignalAccess without memory rows")
    }
    /// Writes one row of a memory cell; `true` iff the row changed.
    fn write_row(&mut self, cell: StateCellId, row: u64, value: FourStateValue) -> bool {
        let _ = (row, value);
        unreachable!("write_row({cell:?}) on a SignalAccess without memory rows")
    }
    /// The plane words `[lo_word, lo_word + words)` of a wide cell, as
    /// `(aval, bval)`. The default reads the whole value; `StateEngine`
    /// reads just the window (a nonblocking write to a few bits of a huge
    /// vector must not cost `O(N)`).
    fn read_wide_window(
        &self,
        cell: StateCellId,
        lo_word: usize,
        words: usize,
    ) -> (Vec<u64>, Vec<u64>) {
        match self.read(cell) {
            FourStateValue::Wide { aval, bval } => (
                aval[lo_word..lo_word + words].to_vec(),
                bval[lo_word..lo_word + words].to_vec(),
            ),
            FourStateValue::Narrow(_) => {
                unreachable!("read_wide_window({cell:?}) on a narrow cell")
            }
        }
    }
    /// Stores the plane words `aval`/`bval` at `lo_word..` of a wide cell;
    /// `true` iff the value changed. The default patches the whole value;
    /// `StateEngine` stores just the window.
    fn write_wide_window(
        &mut self,
        cell: StateCellId,
        lo_word: usize,
        aval: &[u64],
        bval: &[u64],
    ) -> bool {
        write_wide_window_whole(self, cell, lo_word, aval, bval)
    }
    fn subscribe(
        &mut self,
        cell: StateCellId,
        role: ListenerRole,
        sink: Box<dyn ValueChangeSink + Send>,
    );
    /// Changes of other names for storage the last write touched (a window
    /// alias of a ref port, `state::alias`), drained by the scheduler after
    /// each commit so it can notify their waiters. Empty for every engine
    /// that has no window alias.
    fn take_alias_changes(&mut self) -> Vec<AliasChange> {
        Vec::new()
    }
}

/// [`SignalAccess::write_wide_window`] through the whole-value `write`: the
/// default, and what `StateEngine` falls back to for a forced cell or one
/// whose changes are recorded.
pub(crate) fn write_wide_window_whole<A: SignalAccess + ?Sized>(
    acc: &mut A,
    cell: StateCellId,
    lo_word: usize,
    aval: &[u64],
    bval: &[u64],
) -> bool {
    let FourStateValue::Wide {
        aval: mut a,
        bval: mut b,
    } = acc.read(cell)
    else {
        unreachable!("write_wide_window({cell:?}) on a narrow cell")
    };
    a[lo_word..lo_word + aval.len()].copy_from_slice(aval);
    b[lo_word..lo_word + bval.len()].copy_from_slice(bval);
    acc.write(cell, FourStateValue::Wide { aval: a, bval: b })
}

/// Compile-time layout for one unique `(module,params)` template (state.md Key
/// Data Structures; ledger ST-140). One `StateLayout` per distinct
/// [`crate::netlist::TemplateKey`] (`Task 5`'s `TemplateTable` maps keys to
/// these); `inline_words`/`wide_words` are the template-relative word counts
/// [`Arena`] bulk-allocators (Task 7) reserve per instance.
#[derive(Clone, Debug, PartialEq)]
pub struct StateLayout {
    pub slots: Vec<SlotDescriptor>,
    pub inline_words: u32,
    pub wide_words: u32,
}

/// One signal's slot within a [`StateLayout`] (state.md Key Data Structures;
/// ledger ST-141).
///
/// **Reconciliation (ST-153):** state.md's `{key, offset, initial, net_info}`
/// (adopted here) vs. runtime.md's independently drafted `{name, byte_offset,
/// bit_width, is_4state, kind}` are reconciled by *composition, not
/// duplication*, not by picking one draft wholesale:
/// - `name` is available by composing `key` with
///   [`crate::netlist::NetlistView::hierarchical_path`] — never stored a
///   second time here, since a second copy could drift from the netlist
///   track's own name table.
/// - `byte_offset`/`bit_width` are `offset.word_offset`/`offset.bit_width`
///   (already present on [`SlotOffset`] — ST-144 — no renaming needed).
/// - `is_4state` is dropped, not reconciled 1:1: 4-state-ness is a
///   whole-arena [`BuildMode`] (Task 2/10), not a per-slot property, so
///   runtime.md's per-slot field would be redundant with the arena's own
///   mode.
/// - `kind` is `net_info`'s presence/absence (`Some` => net, `None` =>
///   variable/port) plus [`NetLayout::kind`] when present.
///
/// This is the one, documented `SlotDescriptor` shape this plan's every later
/// task consumes identically, and the one CODEGEN/RUNTIME are expected to
/// consume once their own waves start.
///
/// `initial` is STATE's own sv-lang-free [`FourStateValue`], not
/// `sv_lang::OwnedSVInt`: this type is consumed by `vj-runtime`, which must
/// never reach the sv-lang family (ARCHITECTURE §3). The frontend-side layout
/// builder converts constants with `four_state_of_constant` before storing them.
#[derive(Clone, Debug, PartialEq)]
pub struct SlotDescriptor {
    pub key: crate::netlist::SymbolKey,
    pub offset: SlotOffset,
    pub initial: Option<FourStateValue>,
    pub net_info: Option<NetLayout>,
}

/// A net member's electrical classification, when known (ledger ST-141).
///
/// **Deferred conversion (see Task 3/6 of the wave-A `state` plan and the
/// plan's Deferred section):** verified against the pinned `sv-lang=0.1.9` C
/// API (`source/capi/CApiAst.cpp`) — while `slang::ast::NetSymbol` has a
/// `netType` field and slang's own Python bindings expose it, `CApiAst.cpp`
/// exposes no `slang_symbol_net_type`/equivalent accessor for it, so no
/// function in the pinned `sv-lang` Rust crate can recover a declared `Net`
/// symbol's real `NetKind` this wave. `SlotDescriptor::net_info` therefore
/// stays structurally correct (an `Option`, `None` for every real member this
/// wave's layout builder produces, `Net`-kind included) but is never `Some`
/// for a *real* elaborated net in this plan; every `Some(NetLayout{..})` this
/// plan's own tests construct (Task 14/15) is hand-built, exercising the
/// multi-driver resolution *logic*, not a connection to real elaboration.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct NetLayout {
    pub kind: NetKind,
    pub shape: NetShape,
}

/// The multi-driver resolution shape a net's storage takes (ledger ST-141):
/// how many distinct strength-bearing drivers [`NetLayout`]'s owning net has
/// and whether the full K+1 strength lattice must be evaluated to resolve it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum NetShape {
    AliasedSingleDriver,
    MultiDriverUniformStrength,
    FullStrengthLattice,
}

/// Mirrors `sv_lang::NetKind`'s variant set minus `Interconnect` (state.md §4:
/// an interconnect net never gets a slot at all, so it has no `NetLayout`
/// value to represent) and minus the `Unknown` error placeholder (never a
/// real declared net's kind). Kept as this crate's own copy rather than a
/// re-export of `sv_lang::NetKind` so this module's exhaustive-match
/// discipline (ARCHITECTURE §7 item 9) applies to a type this crate owns,
/// independent of `sv_lang`'s own variant set ever changing underneath it.
#[derive(Clone, Copy, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub enum NetKind {
    Wire,
    WAnd,
    WOr,
    Tri,
    TriAnd,
    TriOr,
    Tri0,
    Tri1,
    TriReg,
    Supply0,
    Supply1,
    UWire,
    UserDefined,
}

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

    #[test]
    fn four_state_narrow_round_trips_via_abi_bit4() {
        // Exercise the ONE documented vj_abi::bit4 conversion through STATE's
        // own FourStateValue::Narrow representation, proving the two crates agree
        // on the packed-word shape: the FIXED accessor-ABI offset (unk at bit
        // 64), not codegen's width-tight `<< width` packing (review fix -- the
        // previous version of this test hardcoded `<< 1`, which only "worked"
        // because it never exercised a width other than 1, where the two
        // conventions alias).
        for b in [Bit4::Zero, Bit4::One, Bit4::X, Bit4::Z] {
            let (val, unk) = b.to_val_unk();
            let word: u128 = (val as u128) | ((unk as u128) << 64);
            let fv = FourStateValue::Narrow(word);
            match fv {
                FourStateValue::Narrow(w) => assert_eq!(w, word),
                FourStateValue::Wide { .. } => panic!("expected Narrow"),
            }
        }
    }

    /// Review fix: a width other than 1 that actually distinguishes the FIXED
    /// accessor layout from codegen's width-tight `i(2N)` packing.
    #[test]
    fn four_state_narrow_at_width_8_uses_fixed_64_offset_not_width_offset() {
        let width: u32 = 8;
        let val: u64 = 0b1011_0010;
        let unk: u64 = 0b0000_1000;

        let fixed_word: u128 = (val as u128) | ((unk as u128) << 64);
        let width_tight_word: u128 = (val as u128) | ((unk as u128) << width);
        assert_ne!(fixed_word, width_tight_word);

        let fv = FourStateValue::Narrow(fixed_word);
        match fv {
            FourStateValue::Narrow(w) => {
                assert_eq!((w >> 64) as u64, unk);
                assert_eq!((w & u128::from(u64::MAX)) as u64, val);
            }
            FourStateValue::Wide { .. } => panic!("expected Narrow"),
        }
    }

    /// ST-140: a compile-level proof that `StateLayout` has exactly the three
    /// contracted fields, in the contracted names/order — this line fails to
    /// compile (not merely fails an assertion) if a field were added, removed,
    /// or renamed.
    #[test]
    fn state_layout_has_exactly_the_three_contracted_fields() {
        let layout = StateLayout {
            slots: vec![],
            inline_words: 0,
            wide_words: 0,
        };
        assert!(layout.slots.is_empty());
        assert_eq!(layout.inline_words, 0);
        assert_eq!(layout.wide_words, 0);
    }

    /// ST-141: a literal contract example for Task 4's real layout builder to
    /// test against later (that test asserts the *builder* produces `None` for
    /// a `logic` variable, not merely that the type allows it).
    #[test]
    fn slot_descriptor_net_info_is_none_for_a_non_net_signal() {
        let descriptor = SlotDescriptor {
            key: crate::netlist::SymbolKey(0),
            offset: SlotOffset {
                class: SlotClass::Inline,
                word_offset: 0,
                bit_width: 1,
                elem_word_count: 0,
                row_stride_words: 0,
                num_rows: 0,
            },
            initial: None,
            net_info: None,
        };
        assert!(descriptor.net_info.is_none());
    }

    /// ST-141/ST-153: an exhaustive `match` over `NetShape`'s 3 variants and
    /// `NetKind`'s 13 variants, with no wildcard arm — ARCHITECTURE §7 item 9's
    /// discipline applied to this crate's own enums, not just `sv_lang`'s.
    /// Adding or removing a variant from either enum breaks this file at
    /// compile time, which is the actual guard this test provides.
    #[test]
    fn net_shape_and_net_kind_cover_the_documented_variant_sets() {
        fn describe_shape(shape: NetShape) -> &'static str {
            match shape {
                NetShape::AliasedSingleDriver => "aliased-single-driver",
                NetShape::MultiDriverUniformStrength => "multi-driver-uniform-strength",
                NetShape::FullStrengthLattice => "full-strength-lattice",
            }
        }

        fn describe_kind(kind: NetKind) -> &'static str {
            match kind {
                NetKind::Wire => "wire",
                NetKind::WAnd => "wand",
                NetKind::WOr => "wor",
                NetKind::Tri => "tri",
                NetKind::TriAnd => "triand",
                NetKind::TriOr => "trior",
                NetKind::Tri0 => "tri0",
                NetKind::Tri1 => "tri1",
                NetKind::TriReg => "trireg",
                NetKind::Supply0 => "supply0",
                NetKind::Supply1 => "supply1",
                NetKind::UWire => "uwire",
                NetKind::UserDefined => "user-defined",
            }
        }

        for shape in [
            NetShape::AliasedSingleDriver,
            NetShape::MultiDriverUniformStrength,
            NetShape::FullStrengthLattice,
        ] {
            assert!(!describe_shape(shape).is_empty());
        }

        for kind in [
            NetKind::Wire,
            NetKind::WAnd,
            NetKind::WOr,
            NetKind::Tri,
            NetKind::TriAnd,
            NetKind::TriOr,
            NetKind::Tri0,
            NetKind::Tri1,
            NetKind::TriReg,
            NetKind::Supply0,
            NetKind::Supply1,
            NetKind::UWire,
            NetKind::UserDefined,
        ] {
            assert!(!describe_kind(kind).is_empty());
        }

        let layout = NetLayout {
            kind: NetKind::Tri,
            shape: NetShape::FullStrengthLattice,
        };
        assert_eq!(layout.kind, NetKind::Tri);
        assert_eq!(layout.shape, NetShape::FullStrengthLattice);
    }
}