vj-sim 0.2.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
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
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
//! Sampled value functions (sva T16/T17/T18, `docs/superpowers/plans/
//! 2026-10-03-sva.md`): LRM 1800-2023 16.5.1 (sampling), 16.9.3 (`$sampled`,
//! `$rose`, `$fell`, `$stable`, `$changed`, `$past`) and 16.9.4 (the
//! `*_gclk` families). This module is the elaboration-side half: it
//! recognises a sampled-value call in the AST ([`decode`]), enumerates every
//! call site of a module body ([`sites_of_block`]) and names the hidden state
//! the simulator keeps for them ([`hidden_slots`]). `vj-codegen::sampled`
//! lowers the uses, and `vj` shifts the history at the end of each
//! time step.
//!
//! ## The model, and the one place it deviates from plan 1.3
//!
//! Plan 1.3 sketched a whole-arena snapshot ring pushed in a new Preponed
//! region. That ring is not built, and a whole-arena copy per time step cannot
//! serve a per-call-site clock anyway: `$past(x, 2, en, @(negedge c))` needs
//! the value of `x` at the second strictly earlier time step in which
//! `negedge c iff en` occurred, a different set of steps for every call. The
//! state kept instead is exactly what the LRM defines (16.9.3):
//!
//! - per signal, one hidden **P** cell holding the value the signal had at the
//!   END OF THE PREVIOUS TIME STEP, which is its Preponed value in the step
//!   being executed (16.5.1: the sampled value of a variable at time > 0 is
//!   its value in the Preponed region; at time 0 its default sampled value,
//!   which is the cell's initial value because a hidden cell is created as a
//!   copy of its source's initial value);
//! - per call site and per signal the call reads, a history of **S** cells:
//!   `S_0` is the signal's sampled value at the most recent strictly earlier
//!   time step in which the site's clock ticked (and its `iff`/gate held),
//!   `S_1` the tick before that, and so on up to the call's depth.
//!
//! A call is then pure re-evaluation of its argument with its signal reads
//! redirected: `$sampled(e)` is `e` over P cells; `$rose/$fell/$stable/
//! $changed(e)` compare `e` over P cells with `e` over S_0 cells (so the
//! comparison is of the CURRENT time step's sampled value with the one from
//! the previous tick, 16.9.3); `$past(e, n, ...)` is `e` over S_{n-1} cells.
//! Re-evaluating the expression (rather than snapshotting its value) is what
//! makes `$past(b[i])` of a loop's automatic `i` work (16.9.3: the loop
//! variable's CURRENT value indexes the PAST value of `b`, 16.5.1). Before
//! `n` ticks have happened an S cell still holds its initial value, which is
//! the default sampled value the LRM asks for ("the default sampled value of
//! an expression is the expression evaluated on the default sampled values of
//! its variables").
//!
//! At the end of every time step the engine first shifts the history of every
//! site whose clock ticked in that step (`S_k <- S_{k-1}`, then `S_0 <- P`),
//! then copies every signal into its P cell. Whether a site ticked is decided
//! by a compiled per-site guard evaluated over the P cells (the clocking
//! event's old values) and the signals' current values (its new ones), before
//! the P cells are overwritten; see `vj-codegen::sampled`.
//!
//! A checker's `always_ff` (LRM 17.5) samples every expression but its event
//! control: it needs no call site, only the P cell of each signal it reads
//! ([`checker_ff_sampled_signals`]).
//!
//! Hidden cells are real state slots, appended after the clocking-block slots
//! by BOTH `state::layout::build_template_layout` and
//! `vj-codegen::module::signal_slots_of`, in the order [`hidden_slots`]
//! returns them, which is why that enumeration is deterministic (ordered
//! sets, source order) and shared.

use crate::symid::{SymbolId, SymbolUid};
use std::collections::BTreeSet;
use sv_lang::{EdgeKind, Expression, KnownSystemName, SemNode, Symbol, TimingControl};
use sv_lang_kinds::{ExpressionKind, SymbolKind, TimingControlKind};

/// Why a sampled-value call cannot be handled.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SampledError(pub String);

impl core::fmt::Display for SampledError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.0)
    }
}

fn err<T>(msg: impl Into<String>) -> Result<T, SampledError> {
    Err(SampledError(msg.into()))
}

/// Which sampled value function a call is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SampledOp {
    Sampled,
    Rose,
    Fell,
    Stable,
    Changed,
    Past,
    /// `$future_gclk` (16.9.4): the sampled value at the NEXT global clock
    /// tick. Legal only in a property/sequence expression.
    Future,
    Rising,
    Falling,
    Steady,
    Changing,
}

impl SampledOp {
    /// Whether this function needs the value at a FUTURE tick (16.9.4); it
    /// has no procedural form.
    pub fn is_future(self) -> bool {
        matches!(
            self,
            Self::Future | Self::Rising | Self::Falling | Self::Steady | Self::Changing
        )
    }

    /// Whether the call uses a clocking event (everything but `$sampled`).
    pub fn needs_clock(self) -> bool {
        self != Self::Sampled
    }

    /// How many past ticks of history the call reads: 0 for `$sampled`, 1 for
    /// the value-change functions, `ticks` for `$past`.
    pub fn depth(self, ticks: u32) -> u32 {
        match self {
            // The future family reads the next tick ([`n_id`]), no past one.
            Self::Sampled
            | Self::Future
            | Self::Rising
            | Self::Falling
            | Self::Steady
            | Self::Changing => 0,
            Self::Past => ticks,
            _ => 1,
        }
    }
}

/// `(op, is the *_gclk spelling)` for a system subroutine, `None` for any
/// other.
pub fn op_of(id: KnownSystemName) -> Option<(SampledOp, bool)> {
    use SampledOp as O;
    Some(match id {
        KnownSystemName::Sampled => (O::Sampled, false),
        KnownSystemName::Rose => (O::Rose, false),
        KnownSystemName::Fell => (O::Fell, false),
        KnownSystemName::Stable => (O::Stable, false),
        KnownSystemName::Changed => (O::Changed, false),
        KnownSystemName::Past => (O::Past, false),
        KnownSystemName::PastGclk => (O::Past, true),
        KnownSystemName::RoseGclk => (O::Rose, true),
        KnownSystemName::FellGclk => (O::Fell, true),
        KnownSystemName::StableGclk => (O::Stable, true),
        KnownSystemName::ChangedGclk => (O::Changed, true),
        KnownSystemName::FutureGclk => (O::Future, true),
        KnownSystemName::RisingGclk => (O::Rising, true),
        KnownSystemName::FallingGclk => (O::Falling, true),
        KnownSystemName::SteadyGclk => (O::Steady, true),
        KnownSystemName::ChangingGclk => (O::Changing, true),
        _ => return None,
    })
}

/// A clocking event the simulator can evaluate: one signal event, with an
/// optional `iff` (LRM 9.4.2). `edge == EdgeKind::None` is the bare
/// `@(sig)`, any change of the signal's value.
#[derive(Clone, Copy)]
pub struct ClockEvent<'d> {
    pub edge: EdgeKind,
    pub signal: Expression<'d>,
    pub iff: Option<Expression<'d>>,
}

/// The [`ClockEvent`] of a `SignalEvent` timing control. An event list
/// (`@(a or b)`), a delay or any other control is a named error: a clock the
/// guard cannot evaluate must not be guessed at.
pub fn clock_event_of<'d>(tc: TimingControl<'d>) -> Result<ClockEvent<'d>, SampledError> {
    let ev = assertion_clock_event_of(tc)?;
    // A sequence instance as the clock (`@seq`, LRM 16.5.2, 9.4.2.4) ticks at
    // the sequence's end points; only an assertion's own clocking event is
    // driven that way ([`assertion_clock_event_of`]), so say so by name rather
    // than fail inside expression lowering.
    if ev.signal.kind() == ExpressionKind::AssertionInstance {
        return err(
            "a sequence instance as a clocking event here (`@seq`, LRM 16.5.2) is only              supported as the clocking event of an assertion"
                .to_string(),
        );
    }
    Ok(ev)
}

/// [`clock_event_of`] for the clocking event of an assertion, which may also be
/// a sequence instance (`@seq [iff cond]`, LRM 16.5.2): `signal` is then the
/// `AssertionInstance` expression, and the clock ticks where the sequence has
/// an end point (`crate::sva::endpoint` watches it).
pub fn assertion_clock_event_of<'d>(tc: TimingControl<'d>) -> Result<ClockEvent<'d>, SampledError> {
    if tc.kind() != TimingControlKind::SignalEvent {
        return err(format!(
            "a sampled value function's clocking event is a {:?} control; only a single \
             `@(edge signal [iff cond])` event is supported",
            tc.kind()
        ));
    }
    let children = tc.children();
    let signal = children
        .first()
        .and_then(|c| c.as_expression())
        .ok_or_else(|| SampledError("a clocking event with no signal expression".into()))?;
    // `iff` is positional (see `process::cfg::extract_iff`): the second child.
    let iff = if children.len() == 2 {
        children[1].as_expression()
    } else {
        None
    };
    Ok(ClockEvent {
        edge: tc.edge(),
        signal,
        iff,
    })
}

/// Whether `tc` is the bare `@$global_clock` event control (16.9.4's
/// definition of the `*_gclk` functions is written with it).
pub fn is_global_clock_event(tc: TimingControl<'_>) -> bool {
    tc.kind() == TimingControlKind::SignalEvent
        && tc.edge() == EdgeKind::None
        && tc
            .children()
            .first()
            .and_then(|c| c.as_expression())
            .is_some_and(|x| {
                x.kind() == ExpressionKind::Call
                    && x.is_system_call() == Some(true)
                    && x.system_subroutine()
                        .is_some_and(|s| s.known_name_id() == KnownSystemName::GlobalClock)
            })
}

/// Whether `tc` is `@$global_clock` or an event list with such a member
/// (`@($global_clock or posedge rst)`, 14.14). Each member of a list is
/// resolved to the global clocking's event on its own (`process::cfg`).
pub fn mentions_global_clock_event(tc: TimingControl<'_>) -> bool {
    if tc.kind() == TimingControlKind::EventList {
        return tc
            .children()
            .into_iter()
            .filter_map(|c| c.as_timing_control())
            .any(mentions_global_clock_event);
    }
    is_global_clock_event(tc)
}

/// Whether `e` is a call of one of the global clocking FUTURE functions
/// (`$future_gclk` and friends, 16.9.4).
pub fn is_future_call(e: Expression<'_>) -> bool {
    e.kind() == ExpressionKind::Call
        && e.is_system_call() == Some(true)
        && e.system_subroutine()
            .and_then(|s| op_of(s.known_name_id()))
            .is_some_and(|(op, _)| op.is_future())
}

/// One decoded sampled-value call.
#[derive(Clone, Copy)]
pub struct SampledCall<'d> {
    pub op: SampledOp,
    /// The `*_gclk` spelling or an explicit `@$global_clock`: the clock is the
    /// global clocking's event.
    pub global: bool,
    /// The whole `Call` expression.
    pub call: Expression<'d>,
    /// `expression` / `expression1`.
    pub arg: Expression<'d>,
    /// `number_of_ticks` (`$past` only; 1 otherwise).
    pub ticks: u32,
    /// `expression2`, the gating expression (`$past` only).
    pub gate: Option<Expression<'d>>,
    /// The explicit `clocking_event` argument.
    pub clock: Option<ClockEvent<'d>>,
}

fn is_empty_arg(e: &Expression<'_>) -> bool {
    e.kind() == ExpressionKind::EmptyArgument
}

/// Decodes `e` when it is a sampled-value call; `Ok(None)` for any other
/// expression.
pub fn decode<'d>(e: Expression<'d>) -> Result<Option<SampledCall<'d>>, SampledError> {
    if e.kind() != ExpressionKind::Call || e.is_system_call() != Some(true) {
        return Ok(None);
    }
    let Some(sub) = e.system_subroutine() else {
        return Ok(None);
    };
    let Some((op, mut global)) = op_of(sub.known_name_id()) else {
        return Ok(None);
    };
    let operands = e.operands();
    let name = sub.name();
    let Some(&arg) = operands.first() else {
        return err(format!("{name} with no argument expression"));
    };
    let mut ticks = 1u32;
    let mut gate = None;
    let mut clock = None;
    for (i, o) in operands.iter().enumerate().skip(1) {
        if o.kind() == ExpressionKind::ClockingEvent {
            if clock.is_some() {
                return err(format!("{name} with two clocking events"));
            }
            let tc = o
                .as_sem_node()
                .children()
                .into_iter()
                .find_map(|c| c.as_timing_control())
                .ok_or_else(|| SampledError(format!("{name}: a clocking event with no control")))?;
            if is_global_clock_event(tc) {
                // `$past(v,,,@$global_clock)` is `$past_gclk(v)` (16.9.4).
                if global {
                    return err(format!("{name} with two clocking events"));
                }
                global = true;
            } else {
                clock = Some(clock_event_of(tc)?);
            }
        } else if is_empty_arg(o) {
            // An omitted argument ("$past(in1, , enable)", 16.9.3).
        } else if op == SampledOp::Past && i == 1 {
            let n = o
                .constant_value()
                .and_then(|cv| cv.as_i64())
                .ok_or_else(|| {
                    SampledError(
                        "$past's number_of_ticks is not an elaboration-time constant".into(),
                    )
                })?;
            if n < 1 {
                return err(format!(
                    "$past's number_of_ticks is {n}; it shall be 1 or greater"
                ));
            }
            ticks = u32::try_from(n)
                .map_err(|_| SampledError(format!("$past's number_of_ticks {n} is too large")))?;
        } else if op == SampledOp::Past && i == 2 {
            gate = Some(*o);
        } else {
            return err(format!("{name}: unexpected argument {i}"));
        }
    }
    Ok(Some(SampledCall {
        op,
        global,
        call: e,
        arg,
        ticks,
        gate,
        clock,
    }))
}

/// Whether `sym` is storage the simulator keeps in a state slot and that the
/// sampled value functions can snapshot: a static integral variable or a net.
/// What `$inferred_disable` stands for in a static checker (LRM 17.4, 16.15):
/// `None` for a symbol that is no static checker's; else the signal of the
/// `default disable iff` of the scope instantiating the checker and whether it
/// is negated, the inner `None` being the `1'b0` of a scope with no default
/// (16.15 rule c). Reading the declaration needs the design's syntax, which
/// only `vj-codegen` holds, so it installs the resolver
/// ([`set_inferred_disable_resolver`]) for the length of a lowering.
pub type InferredDisable<'d> = Option<Option<(Symbol<'d>, bool)>>;

/// A resolver of [`InferredDisable`] for any symbol of a checker's body.
pub type InferredDisableResolver = for<'d> fn(&Symbol<'d>) -> Result<InferredDisable<'d>, String>;

thread_local! {
    static INFERRED_DISABLE_RESOLVER: std::cell::Cell<Option<InferredDisableResolver>> =
        const { std::cell::Cell::new(None) };
}

/// Installs (or, with `None`, removes) the [`InferredDisableResolver`],
/// returning the one it replaces.
pub fn set_inferred_disable_resolver(
    f: Option<InferredDisableResolver>,
) -> Option<InferredDisableResolver> {
    INFERRED_DISABLE_RESOLVER.with(|c| c.replace(f))
}

/// The `$inferred_disable` of the static checker `sym` belongs to, per the
/// installed resolver; an error names why it cannot be known (no resolver, or
/// a `default disable iff` that is not a signal).
pub fn resolve_inferred_disable<'d>(sym: &Symbol<'d>) -> Result<InferredDisable<'d>, String> {
    match INFERRED_DISABLE_RESOLVER.with(std::cell::Cell::get) {
        Some(f) => f(sym),
        None => Err("the design's syntax is not available here".into()),
    }
}

fn is_inferred_disable_call(e: &Expression<'_>) -> bool {
    e.kind() == ExpressionKind::Call
        && e.call_subroutine_name().as_deref() == Some("$inferred_disable")
}

/// Whether `root`, or a user subroutine it calls (transitively), reads
/// `$inferred_disable`.
fn reads_inferred_disable(root: SemNode<'_>) -> bool {
    let mut visited = BTreeSet::new();
    let mut work = vec![root];
    while let Some(node) = work.pop() {
        let mut found = false;
        walk(node, &mut |n| {
            if let Some(e) = n.as_expression() {
                if is_inferred_disable_call(&e) {
                    found = true;
                } else if e.kind() == ExpressionKind::Call
                    && e.is_system_call() != Some(true)
                    && let Some(callee) = crate::netlist::itf::call_target(&e)
                    && visited.insert(callee.uid())
                    && let Some(body) = crate::process::cfg::proc_body(&callee)
                {
                    work.push(body.as_sem_node());
                }
            }
            !found
        });
        if found {
            return true;
        }
    }
    false
}

/// An automatic variable is deliberately not one (16.5.1: its sampled value is
/// its current value, also when a past value of it is asked for).
pub fn sampleable_symbol(sym: &Symbol<'_>) -> bool {
    let kind = sym.kind();
    if kind != SymbolKind::Net
        && !(kind == SymbolKind::Variable
            && sym.variable_lifetime() == sv_lang::VariableLifetime::Static)
    {
        return false;
    }
    sym.value_type().is_some_and(|t| t.is_integral())
}

/// A static unpacked array (of arrays) of integral elements: the memory a
/// concurrent assertion's sample row holds element by element.
fn is_integral_memory(sym: &Symbol<'_>) -> bool {
    if sym.kind() != SymbolKind::Variable && sym.kind() != SymbolKind::Net {
        return false;
    }
    let Some(ty) = sym.value_type() else {
        return false;
    };
    if !ty.is_unpacked_array() || crate::state::storage::is_collection(&ty) {
        return false;
    }
    let mut t = ty;
    while t.is_unpacked_array() {
        match t.element_type() {
            Some(e) => t = e,
            None => return false,
        }
    }
    t.is_integral()
}

/// Whether `sym` is a state-slot variable or net of ANY type (the symbols
/// `sampleable_symbol` accepts, plus the ones whose type is not supported, so
/// the use-site lowering can say why).
pub fn is_state_symbol(sym: &Symbol<'_>) -> bool {
    let kind = sym.kind();
    kind == SymbolKind::Net
        || (kind == SymbolKind::Variable
            && sym.variable_lifetime() == sv_lang::VariableLifetime::Static)
}

fn walk<'d>(node: SemNode<'d>, f: &mut impl FnMut(SemNode<'d>) -> bool) {
    let mut stack = vec![node];
    while let Some(n) = stack.pop() {
        if f(n) {
            let mut kids = crate::process::cfg::live_children(&n);
            kids.reverse();
            stack.extend(kids);
        }
    }
}

/// The sampleable signals `node` reads, in a deterministic order.
pub fn signals_in(node: SemNode<'_>) -> BTreeSet<SymbolId> {
    let mut out = BTreeSet::new();
    walk(node, &mut |n| {
        if let Some(e) = n.as_expression()
            && e.kind() == ExpressionKind::NamedValue
            && let Some(sym) = e.referenced_symbol()
            && sampleable_symbol(&sym)
        {
            out.insert(sym.uid());
        }
        true
    });
    out
}

/// [`signals_in`] for an expression the simulator will actually re-evaluate
/// over sampled values (a call's argument, gate, clock signal or `iff`): any
/// shape that would silently read a CURRENT value instead of the sampled one
/// is an error here rather than a wrong answer later.
///
/// - a state symbol of a type with no hidden-cell support (a `real`,
///   `string`, array, event, collection, handle);
/// - a hierarchical reference to anything but an integral variable or net;
/// - a user subroutine call (its body reads module signals this walk cannot
///   redirect);
/// - another sampled value function (LRM 16.9.3 allows them nested in
///   assertion expressions only, and only through the matched/sequence form).
pub fn strict_signals_in(e: Expression<'_>) -> Result<BTreeSet<SymbolId>, SampledError> {
    // A concurrent assertion's row holds every signal it reads, hierarchical
    // ones included, so a hierarchical integral signal is sampleable here.
    strict_signals(e, true, true)
}

/// [`strict_signals_in`] for a PROCEDURAL call site, where a hierarchical
/// reference to an integral variable or net is allowed: the signal of another
/// instance gets this instance's own P/S history (`hidden_slots`).
pub fn strict_site_signals_in(e: Expression<'_>) -> Result<BTreeSet<SymbolId>, SampledError> {
    strict_signals(e, true, true)
}

/// [`strict_site_signals_in`] for the enumeration of a block's hidden P/S cells
/// ([`sites_of_block`]): a memory has no hidden cell, so a procedural call over
/// one is refused here by name (only a concurrent assertion's rows hold memories).
fn strict_hidden_signals_in(e: Expression<'_>) -> Result<BTreeSet<SymbolId>, SampledError> {
    strict_signals(e, true, false)
}

fn strict_signals(
    e: Expression<'_>,
    allow_hier: bool,
    allow_mem: bool,
) -> Result<BTreeSet<SymbolId>, SampledError> {
    let mut failure = None;
    let mut hier = BTreeSet::new();
    walk(e.as_sem_node(), &mut |n| {
        if failure.is_some() {
            return false;
        }
        let Some(x) = n.as_expression() else {
            return true;
        };
        // Only these three kinds are inspected; every other expression kind
        // is fine to re-evaluate over sampled cells, so this is a kind test,
        // not a match with a catch-all arm.
        let kind = x.kind();
        if kind == ExpressionKind::HierarchicalValue {
            // A signal of another instance: this instance keeps its own P/S
            // history of it (`hidden_slots`, `foreign_args`).
            match x.referenced_symbol() {
                Some(sym) if allow_hier && sampleable_symbol(&sym) => {
                    hier.insert(sym.uid());
                }
                _ => {
                    failure = Some(SampledError(
                        "a hierarchical reference inside a sampled value function's expression \
                         is not supported unless it names an integral variable or net"
                            .into(),
                    ));
                }
            }
        } else if kind == ExpressionKind::NamedValue {
            if let Some(sym) = x.referenced_symbol()
                && is_state_symbol(&sym)
                && !sampleable_symbol(&sym)
            {
                // A concurrent assertion's row holds every element of an
                // unpacked array of integral elements (16.5.1 samples them
                // all), with the same per-tick history as any other signal.
                if allow_mem && is_integral_memory(&sym) {
                    hier.insert(sym.uid());
                    return true;
                }
                failure = Some(SampledError(format!(
                    "`{}` inside a sampled value function's expression has a type \
                     (real/string/array/event/collection/handle) whose sampled value is not \
                     supported",
                    sym.name()
                )));
            }
        } else if kind == ExpressionKind::Call {
            match decode(x) {
                Ok(Some(_)) => {
                    failure = Some(SampledError(
                        "a sampled value function nested inside the expression of another is \
                         not supported"
                            .into(),
                    ));
                }
                Ok(None) => {
                    if x.is_system_call() == Some(false) {
                        failure = Some(SampledError(
                            "a user subroutine call inside a sampled value function's expression \
                             is not supported"
                                .into(),
                        ));
                    }
                }
                Err(e) => failure = Some(e),
            }
        }
        failure.is_none()
    });
    match failure {
        Some(e) => Err(e),
        None => {
            let mut out = signals_in(e.as_sem_node());
            out.extend(hier);
            Ok(out)
        }
    }
}

/// Whether `block` is an `always_ff` of a checker (LRM 17.5), whose
/// expressions are all sampled.
pub fn is_checker_always_ff(block: &Symbol<'_>) -> bool {
    if block.kind() != SymbolKind::ProceduralBlock
        || block.procedural_block_procedure_kind() != sv_lang::ProceduralBlockKind::AlwaysFF
    {
        return false;
    }
    let mut scope = block.parent();
    while let Some(s) = scope {
        let kind = s.kind();
        if kind == SymbolKind::CheckerInstanceBody {
            return true;
        }
        if kind == SymbolKind::InstanceBody {
            return false;
        }
        scope = s.parent();
    }
    false
}

/// The signals a checker `always_ff` reads at their SAMPLED value (LRM 17.5:
/// "except for the variables used in the event control, all other expressions
/// in always_ff procedures are sampled"), empty for any other block. The
/// block's statements read each of them through its P cell
/// (`vj-codegen::process_lower::prime_external_signals`), so every one
/// gets a P cell ([`hidden_slots`]).
///
/// The signals of the event control keep their current value, and the
/// properties of a concurrent assertion are the assertion engine's (it
/// samples them itself). A read the P cells cannot serve is an error, not a
/// silent current-value read: a hierarchical reference, or a state symbol of
/// a type with no hidden-cell support.
pub fn checker_ff_sampled_signals(block: &Symbol<'_>) -> Result<BTreeSet<SymbolId>, SampledError> {
    if !is_checker_always_ff(block) {
        return Ok(BTreeSet::new());
    }
    let Some(body) = crate::process::cfg::proc_body(block) else {
        return Ok(BTreeSet::new());
    };
    let mut event = BTreeSet::new();
    let mut read = BTreeSet::new();
    let mut failure = None;
    walk(body.as_sem_node(), &mut |n| {
        if failure.is_some() {
            return false;
        }
        if n.as_assertion_expr().is_some() {
            return false;
        }
        if let Some(tc) = n.as_timing_control() {
            event.extend(signals_in(tc.as_sem_node()));
            return false;
        }
        if let Some(e) = n.as_expression() {
            let kind = e.kind();
            if kind == ExpressionKind::Assignment && e.is_nonblocking() != Some(true) {
                failure = Some(SampledError(
                    "a blocking assignment in a checker's `always_ff` (LRM 17.5 allows \
                     nonblocking assignments only there)"
                        .into(),
                ));
            } else if kind == ExpressionKind::HierarchicalValue {
                failure = Some(SampledError(
                    "a hierarchical reference inside a checker's `always_ff` cannot be \
                     sampled (LRM 17.5): its P cell lives in another instance"
                        .into(),
                ));
            } else if kind == ExpressionKind::NamedValue
                && let Some(sym) = e.referenced_symbol()
            {
                if sampleable_symbol(&sym) {
                    read.insert(sym.uid());
                } else if is_state_symbol(&sym) {
                    failure = Some(SampledError(format!(
                        "`{}` in a checker's `always_ff` has a type \
                         (real/string/array/event/collection/handle) whose sampled value (LRM \
                         17.5) is not supported",
                        sym.name()
                    )));
                }
            }
        }
        failure.is_none()
    });
    if let Some(e) = failure {
        return Err(e);
    }
    let mut sampled = &read - &event;
    // 17.4, 17.5: `$inferred_disable` (here or in a function the block calls)
    // is the SAMPLED value of the instantiating scope's `default disable iff`
    // signal, even where that signal is also in the event control.
    if reads_inferred_disable(body.as_sem_node()) {
        match resolve_inferred_disable(block) {
            Ok(Some(Some((sig, _)))) if sampleable_symbol(&sig) => {
                sampled.insert(sig.uid());
            }
            Ok(Some(None)) => {}
            Ok(Some(Some((sig, _)))) => {
                return err(format!(
                    "`$inferred_disable` in a checker's `always_ff` stands for `{}`, whose type \
                     has no sampled value (LRM 17.5)",
                    sig.name()
                ));
            }
            Ok(None) => {
                return err(
                    "`$inferred_disable` in an `always_ff` of a checker that is not a static \
                     instance has no sampled `default disable iff` (LRM 17.4)",
                );
            }
            Err(why) => {
                return err(format!(
                    "`$inferred_disable` in a checker's `always_ff`: {why}"
                ));
            }
        }
    }
    Ok(sampled)
}

/// The clocking event of `block` (written in its body, or the event of a
/// clocking block of its scope) that is the same source text as `ev`, which
/// was inferred for the same procedure of another instance of the module
/// (slang's analysis tracks one instance of each set of identical ones).
/// Both instances were elaborated from one syntax node, so the clock signal's
/// source span identifies the event.
pub fn relocate_clock<'d>(
    block: &Symbol<'d>,
    ev: &ClockEvent<'_>,
) -> Result<ClockEvent<'d>, SampledError> {
    let want = ev.signal.source_range();
    let mut found = None;
    let mut look = |root: SemNode<'d>| {
        walk(root, &mut |n| {
            if found.is_none()
                && let Some(tc) = n.as_timing_control()
                && tc.kind() == TimingControlKind::SignalEvent
                && let Ok(cand) = clock_event_of(tc)
                && cand.edge == ev.edge
                && cand.signal.source_range() == want
            {
                found = Some(cand);
            }
            found.is_none()
        });
    };
    if let Some(body) = crate::process::cfg::proc_body(block) {
        look(body.as_sem_node());
    }
    if let Some(scope) = block.parent() {
        for cb in crate::netlist::module_items(&scope)
            .into_iter()
            .filter(|m| m.kind() == SymbolKind::ClockingBlock)
        {
            if let Some(cev) = cb.clocking_block_event() {
                look(cev);
            }
        }
    }
    found.ok_or_else(|| {
        SampledError(
            "the inferred clocking event of another instance of this module has no counterpart \
             in this instance"
                .into(),
        )
    })
}

/// The timing control written in `block`'s body that is the same source text as
/// `tc` (an event inferred for `block`, or for the same procedure of another
/// instance): a `SignalEvent` of the same edge, signal text and `iff` presence.
/// `None` when the body has no such control (an inferred default clocking event,
/// which lives outside the block).
pub fn relocate_clock_node<'d>(block: &Symbol<'d>, tc: &TimingControl<'_>) -> Option<SemNode<'d>> {
    if tc.kind() != TimingControlKind::SignalEvent {
        return None;
    }
    let kids = tc.children();
    let want = kids.first()?.as_expression()?.source_range();
    let edge = tc.edge();
    let arity = kids.len();
    let mut found = None;
    walk(
        crate::process::cfg::proc_body(block)?.as_sem_node(),
        &mut |n| {
            if found.is_none()
                && let Some(cand) = n.as_timing_control()
                && cand.kind() == TimingControlKind::SignalEvent
                && cand.edge() == edge
                && cand.children().len() == arity
                && cand
                    .children()
                    .first()
                    .and_then(|c| c.as_expression())
                    .is_some_and(|e| e.source_range() == want)
            {
                found = Some(cand.as_sem_node());
            }
            found.is_none()
        },
    );
    found
}

/// One call site, with the hidden state it needs.
pub struct Site<'d> {
    pub call: SampledCall<'d>,
    /// The signals the call's argument reads (each gets an S history).
    pub arg_signals: BTreeSet<SymbolId>,
    /// Every signal that needs a P cell for this site: the argument's, the
    /// gate's and the clock candidates'.
    pub p_signals: BTreeSet<SymbolId>,
    /// The signals among those named by a hierarchical reference to ANOTHER
    /// instance (LRM 23.6), with their cell shapes: this instance keeps its
    /// own history of each ([`ForeignShape::required`]).
    pub foreign: std::collections::BTreeMap<SymbolId, ForeignShape>,
}

/// A site's identity within its owning process: `{buffer}.{offset}` of the
/// call expression's first token. Two generate-loop copies of one block share
/// it, which is why every derived id also carries the owner's uid.
pub fn site_loc(call: &Expression<'_>) -> String {
    let start = call.source_range().start;
    format!("{}.{}", start.buffer, start.offset)
}

/// Every sampled-value call under `block`'s body, in source order, each with
/// the signals it needs hidden cells for. A sampled call nested in another
/// one's argument, or one with no usable clock candidate, is an error. The calls
/// inside the property of a concurrent assertion are not sites (see above).
pub fn sites_of_block<'d>(block: &Symbol<'d>) -> Result<Vec<Site<'d>>, SampledError> {
    let Some(body) = crate::process::cfg::proc_body(block) else {
        return Ok(Vec::new());
    };
    let mut calls = Vec::new();
    let mut failure = None;
    walk(body.as_sem_node(), &mut |n| {
        if failure.is_some() {
            return false;
        }
        // The expressions of an assertion's property are not the block's own:
        // the assertion engine evaluates them over its position rows
        // (`vj-codegen`'s `sva::emit`, which finds those calls itself), so
        // they get no hidden P/S cells, and no tick guard that could not infer a
        // clock for a static assertion's wrapper block. The action blocks are
        // statements, not assertion expressions: their calls stay sites.
        if n.as_assertion_expr().is_some() {
            return false;
        }
        if let Some(e) = n.as_expression() {
            match decode(e) {
                Ok(Some(c)) => {
                    calls.push(c);
                    // A nested sampled call is checked below, per site.
                    return false;
                }
                Ok(None) => {}
                Err(e) => {
                    failure = Some(e);
                    return false;
                }
            }
        }
        true
    });
    if let Some(e) = failure {
        return Err(e);
    }
    let mut sites = Vec::new();
    let own_body = crate::netlist::enclosing_instance_body(block).map(|b| b.uid());
    for call in calls {
        let arg_signals = strict_hidden_signals_in(call.arg)?;
        let mut p_signals = arg_signals.clone();
        let mut roots = vec![call.arg];
        if let Some(g) = call.gate {
            p_signals.extend(strict_hidden_signals_in(g)?);
            roots.push(g);
        }
        if call.op.needs_clock() {
            match call.clock {
                Some(ev) => {
                    p_signals.extend(strict_hidden_signals_in(ev.signal)?);
                    roots.push(ev.signal);
                    if let Some(iff) = ev.iff {
                        p_signals.extend(strict_hidden_signals_in(iff)?);
                        roots.push(iff);
                    }
                }
                None => {
                    // The clock is inferred (16.14.6 / the global or default
                    // clocking), resolved by `vj-codegen` with the full
                    // analysis, which this crate-level enumeration cannot
                    // see. Over-approximate its signals: every signal event
                    // of the process, and every clocking block's event of
                    // the module (a default or global clocking is one).
                    walk(body.as_sem_node(), &mut |n| {
                        if let Some(tc) = n.as_timing_control()
                            && tc.kind() == TimingControlKind::SignalEvent
                        {
                            p_signals.extend(signals_in(tc.as_sem_node()));
                        }
                        true
                    });
                    if let Some(scope) = block.parent() {
                        for cb in crate::netlist::module_items(&scope)
                            .into_iter()
                            .filter(|m| m.kind() == SymbolKind::ClockingBlock)
                        {
                            if let Some(ev) = cb.clocking_block_event() {
                                p_signals.extend(signals_in(ev));
                            }
                        }
                    }
                }
            }
        }
        // The signals of other instances (hierarchical references): their
        // cells have no local slot to clone.
        let mut foreign = std::collections::BTreeMap::new();
        for root in roots {
            walk(root.as_sem_node(), &mut |n| {
                if let Some(x) = n.as_expression()
                    && x.kind() == ExpressionKind::HierarchicalValue
                    && let Some(sym) = x.referenced_symbol()
                    && sampleable_symbol(&sym)
                    && crate::netlist::enclosing_instance_body(&sym).map(|b| b.uid()) != own_body
                    && let Some(shape) = foreign_shape(&sym)
                {
                    foreign.insert(sym.uid(), shape);
                }
                true
            });
        }
        sites.push(Site {
            call,
            arg_signals,
            p_signals,
            foreign,
        });
    }
    Ok(sites)
}

/// The id of signal `sig`'s hidden P cell (its value at the end of the
/// previous time step).
pub fn p_id(sig: &SymbolId) -> SymbolId {
    sig.derive("p")
}

/// The id of the cell holding `sig`'s sampled value at the NEXT tick of the
/// global clock (16.9.4), which an assertion's position row carries.
pub fn n_id(sig: &SymbolId) -> SymbolId {
    sig.derive("n")
}

/// The id of the S_`k` cell of `sig` for the call at `loc` in `owner`.
pub fn s_id(owner: &SymbolId, loc: &str, sig: &SymbolId, k: u32) -> SymbolId {
    owner.derive(&format!("s{loc}@{}#{k}", sig.key_string()))
}

/// FNV-1a: a stable (run-independent) hash for generated symbol names.
fn fnv1a(s: &str) -> u64 {
    let mut h = 0xcbf2_9ce4_8422_2325u64;
    for b in s.bytes() {
        h ^= u64::from(b);
        h = h.wrapping_mul(0x0100_0000_01b3);
    }
    h
}

/// The name of the compiled tick guard of the call at `loc` in `owner`.
/// `vj-codegen` emits a function of this name and `vj` looks it
/// up by it, so the two never exchange a table.
pub fn guard_name(owner: &SymbolId, loc: &str) -> String {
    format!(
        "vj_sva_guard_{:016x}",
        fnv1a(&format!("{}@{loc}", owner.key_string()))
    )
}

/// One hidden cell: a clone of `source`'s slot (class, width, initial value).
#[derive(Debug, Clone, PartialEq)]
pub struct HiddenSlot {
    pub id: SymbolId,
    pub source: SymbolId,
    /// Set when `source` is NOT a signal of this body but of an enclosing
    /// instance (the event signal of a global clocking declared there, LRM
    /// 14.14): the cell then has no local slot to clone, so it carries the
    /// shape to build instead.
    pub foreign: Option<ForeignShape>,
}

/// The shape of a hidden cell whose source lives in another instance.
#[derive(Debug, Clone, PartialEq)]
pub struct ForeignShape {
    pub width: u32,
    pub signed: bool,
    /// The source's initial value (its declared initializer, else 0 for a
    /// 2-state type); `None` is all-X.
    pub initial: Option<crate::state::FourStateValue>,
    /// The source is named by the code itself (a hierarchical reference), so
    /// it MUST be a foreign slot of the instance: a missing one is an error.
    /// False for the candidate event signals of enclosing clocking blocks,
    /// of which only the one the lookup picks is registered.
    pub required: bool,
}

/// `from <- to` copy of one site's history shift.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShiftStep {
    pub from: SymbolId,
    pub to: SymbolId,
}

/// A clocked call site's end-of-step work.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SiteShift {
    /// The compiled guard (`i8 f(handle)`, 1 when the site ticked).
    pub guard_name: String,
    /// Executed in order when the guard returns 1: `S_{d-1} <- S_{d-2}`, ...,
    /// `S_1 <- S_0`, then `S_0 <- P`, per signal.
    pub shifts: Vec<ShiftStep>,
}

/// Everything hidden a module body needs.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Hidden {
    /// P cells, in `SymbolId` order.
    pub p: Vec<HiddenSlot>,
    /// S cells, in site order x signal order x k.
    pub s: Vec<HiddenSlot>,
    /// One entry per clocked site, in site order.
    pub sites: Vec<SiteShift>,
}

impl Hidden {
    /// P cells then S cells: the order they are appended after the other
    /// slots of a template.
    pub fn slots(&self) -> impl Iterator<Item = &HiddenSlot> {
        self.p.iter().chain(self.s.iter())
    }

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

/// The event signals of every clocking block declared in an instance ENCLOSING
/// `body` (any of them may be the global clocking LRM 14.14's lookup finds;
/// `vj` copies only those the lookup picks), with their cell shapes.
fn enclosing_clock_signals(body: &Symbol<'_>) -> Vec<(SymbolId, ForeignShape)> {
    let mut out = Vec::new();
    let mut cur = *body;
    while let Some(parent) = super::global_clock::parent_body(&cur) {
        for cb in crate::netlist::module_items(&parent)
            .into_iter()
            .filter(|m| m.kind() == SymbolKind::ClockingBlock)
        {
            let Some(ev) = cb.clocking_block_event() else {
                continue;
            };
            let mut syms = Vec::new();
            walk(ev, &mut |n| {
                if let Some(e) = n.as_expression()
                    && e.kind() == ExpressionKind::NamedValue
                    && let Some(sym) = e.referenced_symbol()
                    && sampleable_symbol(&sym)
                {
                    syms.push(sym);
                }
                true
            });
            for sym in syms {
                if let Some(shape) = foreign_shape(&sym) {
                    out.push((sym.uid(), shape));
                }
            }
        }
        cur = parent;
    }
    out
}

/// The cell shape of the integral variable or net `sym`.
fn foreign_shape(sym: &Symbol<'_>) -> Option<ForeignShape> {
    use crate::state::{FourStateValue, value};
    let ty = sym.value_type()?;
    let width = u32::try_from(ty.bit_width()).ok().filter(|w| *w > 0)?;
    let signed = ty.is_signed();
    let initial = sym
        .initializer()
        .and_then(|init| init.constant_value())
        .and_then(|cv| value::four_state_of_constant(&cv))
        .and_then(|fv| {
            value::owned_svint_to_four_state(&value::four_state_to_owned_svint(&fv, width, signed))
        })
        .or_else(|| {
            (!ty.is_four_state()).then(|| {
                if width <= 64 {
                    FourStateValue::Narrow(0)
                } else {
                    let words = width.div_ceil(64) as usize;
                    FourStateValue::Wide {
                        aval: vec![0; words],
                        bval: vec![0; words],
                    }
                }
            })
        });
    Some(ForeignShape {
        width,
        signed,
        initial,
        required: false,
    })
}

/// The hidden cells of every procedural block of `body` (the enumeration both
/// slot builders append, in this order).
pub fn hidden_slots(body: &Symbol<'_>) -> Result<Hidden, SampledError> {
    let mut p: BTreeSet<SymbolId> = BTreeSet::new();
    let mut foreign: std::collections::BTreeMap<SymbolId, ForeignShape> = Default::default();
    let mut out = Hidden::default();
    let mut seen = BTreeSet::new();
    for item in crate::netlist::module_items(body) {
        // A module-level subroutine owns the sites of its own body: its value
        // history depends only on the clock (16.9.3), never on the caller, so
        // every call shares it (`SymbolKind::Subroutine`).
        if !matches!(
            item.kind(),
            SymbolKind::ProceduralBlock | SymbolKind::Subroutine
        ) {
            continue;
        }
        let owner = item.uid();
        // A checker `always_ff` reads its signals through their P cells.
        if item.kind() == SymbolKind::ProceduralBlock {
            p.extend(checker_ff_sampled_signals(&item)?);
        }
        for site in sites_of_block(&item)? {
            let loc = site_loc(&site.call.call);
            if !seen.insert((owner.clone(), loc.clone())) {
                return err(format!(
                    "two sampled value calls share one source position ({loc}); a macro that \
                     expands to several of them is not supported"
                ));
            }
            p.extend(site.p_signals.iter().cloned());
            for (id, shape) in &site.foreign {
                foreign.insert(
                    id.clone(),
                    ForeignShape {
                        required: true,
                        ..shape.clone()
                    },
                );
            }
            // `$past_gclk` & co. whose global clocking may be an enclosing
            // instance's (14.14): this instance keeps the history of that
            // clock's event signals itself, a P cell per candidate that a
            // copy from the instance owning the signal keeps current.
            if site.call.global && site.call.clock.is_none() && !site.call.op.is_future() {
                for (id, shape) in enclosing_clock_signals(body) {
                    p.insert(id.clone());
                    foreign.insert(id, shape);
                }
            }
            let depth = site.call.op.depth(site.call.ticks);
            if depth == 0 || site.call.op.is_future() {
                continue;
            }
            let mut shifts = Vec::new();
            for sig in &site.arg_signals {
                for k in 0..depth {
                    out.s.push(HiddenSlot {
                        id: s_id(&owner, &loc, sig, k),
                        source: sig.clone(),
                        foreign: site.foreign.get(sig).cloned(),
                    });
                }
                for k in (1..depth).rev() {
                    shifts.push(ShiftStep {
                        from: s_id(&owner, &loc, sig, k - 1),
                        to: s_id(&owner, &loc, sig, k),
                    });
                }
                shifts.push(ShiftStep {
                    from: p_id(sig),
                    to: s_id(&owner, &loc, sig, 0),
                });
            }
            out.sites.push(SiteShift {
                guard_name: guard_name(&owner, &loc),
                shifts,
            });
        }
    }
    out.p = p
        .into_iter()
        .map(|sig| HiddenSlot {
            id: p_id(&sig),
            foreign: foreign.get(&sig).cloned(),
            source: sig,
        })
        .collect();
    Ok(out)
}

/// The hidden cells one call READS at its use site, as `(signal, cell)` pairs:
/// the argument is evaluated once over `cur` and, for the value-change
/// functions, once more over `prev`. `vj-codegen` primes exactly these and
/// lowers the call from them, so the two agree by construction.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct UseViews {
    pub cur: Vec<(SymbolId, SymbolId)>,
    pub prev: Vec<(SymbolId, SymbolId)>,
    /// The future functions' value at the next global clock tick.
    pub next: Vec<(SymbolId, SymbolId)>,
}

/// The [`UseViews`] of `call` (whose argument reads `arg_signals`) in the
/// procedural block `owner`.
pub fn use_views(
    owner: &SymbolId,
    call: &SampledCall<'_>,
    arg_signals: &BTreeSet<SymbolId>,
) -> UseViews {
    let loc = site_loc(&call.call);
    let mut v = UseViews::default();
    for sig in arg_signals {
        match call.op {
            SampledOp::Sampled => v.cur.push((sig.clone(), p_id(sig))),
            SampledOp::Rose | SampledOp::Fell | SampledOp::Stable | SampledOp::Changed => {
                v.cur.push((sig.clone(), p_id(sig)));
                v.prev.push((sig.clone(), s_id(owner, &loc, sig, 0)));
            }
            SampledOp::Past => v
                .cur
                .push((sig.clone(), s_id(owner, &loc, sig, call.ticks - 1))),
            // Only in an assertion, whose position row holds the next tick's
            // values (16.9.4); anywhere else the use-site lowering rejects them.
            SampledOp::Future
            | SampledOp::Rising
            | SampledOp::Falling
            | SampledOp::Steady
            | SampledOp::Changing => {
                v.cur.push((sig.clone(), p_id(sig)));
                v.next.push((sig.clone(), n_id(sig)));
            }
        }
    }
    v
}

/// A pure executable specification of the semantics in the module doc, on a
/// per-time-step trace of ONE 4-state scalar (`b'0'`, `b'1'`, `b'x'`,
/// `b'z'`). The simulator's own tests compare against it, and its unit tests
/// pin the LRM's Figure 16-3 and `$past` statements.
#[cfg(test)]
pub(crate) mod model {
    /// `preponed[t]` is the expression's sampled (Preponed) value in time
    /// step `t`; `tick[t]` whether the (gated) clocking event occurred in it.
    pub struct Trace<'a> {
        pub preponed: &'a [u8],
        pub tick: &'a [bool],
        /// The default sampled value (16.5.1).
        pub init: u8,
    }

    impl Trace<'_> {
        /// `$sampled` in time step `t`.
        pub fn sampled(&self, t: usize) -> u8 {
            self.preponed[t]
        }

        /// The sampled value `k` ticks strictly before time step `t`
        /// (`k >= 1`): `$past(e, k)`, or the default when fewer exist.
        pub fn past(&self, t: usize, k: usize) -> u8 {
            let ticks: Vec<usize> = (0..t).filter(|&s| self.tick[s]).collect();
            if ticks.len() >= k {
                self.preponed[ticks[ticks.len() - k]]
            } else {
                self.init
            }
        }

        pub fn rose(&self, t: usize) -> bool {
            self.sampled(t) == b'1' && self.past(t, 1) != b'1'
        }

        pub fn fell(&self, t: usize) -> bool {
            self.sampled(t) == b'0' && self.past(t, 1) != b'0'
        }

        pub fn stable(&self, t: usize) -> bool {
            self.sampled(t) == self.past(t, 1)
        }

        pub fn changed(&self, t: usize) -> bool {
            !self.stable(t)
        }
    }

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

        fn bits(s: &str) -> Vec<u8> {
            s.bytes().collect()
        }

        /// Figure 16-3: one clock tick per time step, `e1 = $rose(req)`
        /// occurs at tick 3 ("the value of req at clock tick 2 was low and
        /// the value at clock tick 3 is high") and `e2 = $fell(ack)` at tick 6
        /// ("ack was sampled as high at clock tick 5 and sampled as low at
        /// clock tick 6"). Index 0 is tick 1.
        #[test]
        fn figure_16_3_value_change_expressions() {
            let req = bits("00110001110000");
            let ack = bits("00001000110000");
            let tick = vec![true; 14];
            let rq = Trace {
                preponed: &req,
                tick: &tick,
                init: b'0',
            };
            let ak = Trace {
                preponed: &ack,
                tick: &tick,
                init: b'0',
            };
            let e1: Vec<usize> = (0..14).filter(|&t| rq.rose(t)).map(|t| t + 1).collect();
            let e2: Vec<usize> = (0..14).filter(|&t| ak.fell(t)).map(|t| t + 1).collect();
            assert_eq!(e1, [3, 8]);
            assert_eq!(e2, [6, 11]);
            assert!(e1.contains(&3) && e2.contains(&6));
        }

        /// 16.9.3: the clock ticks only in some time steps, so the previous
        /// value is the one at the previous TICK, not the previous step.
        #[test]
        fn value_change_compares_with_the_previous_tick_not_the_previous_step() {
            // x: 0 0 1 1 0 ; ticks at steps 0, 3, 4
            let x = bits("00110");
            let tick = [true, false, false, true, true];
            let t = Trace {
                preponed: &x,
                tick: &tick,
                init: b'0',
            };
            // step 3: x=1 vs the value at step 0 (0): rose.
            assert!(t.rose(3));
            // step 4: x=0 vs the value at step 3 (1): fell, changed.
            assert!(t.fell(4) && t.changed(4));
            // step 2 (no tick): still compares with the tick at step 0.
            assert!(t.rose(2));
        }

        /// 16.9.3: before the first tick the previous value is the default
        /// sampled value (X for a `logic`), so `$rose` of a first-seen 1 and
        /// `$fell` of a first-seen 0 are both true, `$stable` of X is true.
        #[test]
        fn before_the_first_tick_the_default_sampled_value_is_used() {
            let x = bits("1x0");
            let tick = [true, true, true];
            let t = Trace {
                preponed: &x,
                tick: &tick,
                init: b'x',
            };
            assert!(t.rose(0));
            assert!(!t.stable(0));
            // x vs 1: not stable, neither rose nor fell (the LSB is x).
            assert!(!t.rose(1) && !t.fell(1) && t.changed(1));
            assert!(t.fell(2));
        }

        /// `$past(e, k)` is the value at the k-th strictly earlier tick; the
        /// gate removes ticks (`posedge clk iff enable`, 16.9.3's `$past(q,
        /// 2, enable)`).
        #[test]
        fn past_counts_gated_ticks() {
            let q = bits("0101100101");
            // The gate is open at steps 1, 2, 4, 7.
            let tick = [
                false, true, true, false, true, false, false, true, false, false,
            ];
            let t = Trace {
                preponed: &q,
                tick: &tick,
                init: b'x',
            };
            // At step 9, the ticks before it are 1, 2, 4, 7: past 1 = q[7],
            // past 2 = q[4], past 4 = q[1]; past 5 does not exist.
            assert_eq!(t.past(9, 1), q[7]);
            assert_eq!(t.past(9, 2), q[4]);
            assert_eq!(t.past(9, 4), q[1]);
            assert_eq!(t.past(9, 5), b'x');
            // At step 4 the tick at step 4 itself is not strictly prior.
            assert_eq!(t.past(4, 1), q[2]);
            assert_eq!(t.past(4, 3), b'x');
        }
    }
}

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

    fn hidden_of(src: &str) -> Result<Hidden, SampledError> {
        let design = compile_source(src).expect("valid SV source compiles");
        let body = design
            .top_instances()
            .next()
            .expect("one top instance")
            .instance_body()
            .expect("instance has a body");
        hidden_slots(&body)
    }

    fn names(slots: &[HiddenSlot]) -> Vec<String> {
        slots.iter().map(|s| s.id.path().to_owned()).collect()
    }

    /// `$rose(b)` needs a P cell for `b` and the clock `clk` (the inferred
    /// clock's candidates), plus one S_0 cell and one site for `b`.
    #[test]
    fn rose_gets_p_cells_for_arg_and_clock_and_one_s_cell() {
        let h = hidden_of(
            "module top; logic clk, b, r;\n\
             always @(posedge clk) r <= $rose(b);\nendmodule\n",
        )
        .unwrap();
        assert_eq!(names(&h.p), ["top.b$p", "top.clk$p"]);
        assert_eq!(h.s.len(), 1);
        assert_eq!(h.s[0].source.path(), "top.b");
        assert_eq!(h.sites.len(), 1);
        // The shift is P -> S_0 only.
        assert_eq!(h.sites[0].shifts.len(), 1);
        assert_eq!(h.sites[0].shifts[0].from, p_id(&h.s[0].source));
        assert_eq!(h.sites[0].shifts[0].to, h.s[0].id);
    }

    /// `$past(x, 3)` keeps three S cells and shifts oldest-first.
    #[test]
    fn past_depth_n_keeps_n_cells_shifted_oldest_first() {
        let h = hidden_of(
            "module top; logic clk; logic [3:0] x, y;\n\
             always @(posedge clk) y <= $past(x, 3);\nendmodule\n",
        )
        .unwrap();
        assert_eq!(h.s.len(), 3);
        let sh = &h.sites[0].shifts;
        assert_eq!(sh.len(), 3);
        assert_eq!(sh[0].to, h.s[2].id);
        assert_eq!(sh[0].from, h.s[1].id);
        assert_eq!(sh[1].to, h.s[1].id);
        assert_eq!(sh[1].from, h.s[0].id);
        assert_eq!(sh[2].to, h.s[0].id);
        assert_eq!(sh[2].from, p_id(&h.s[0].source));
    }

    /// `$sampled` is pure P: no history and no site.
    #[test]
    fn sampled_needs_only_a_p_cell() {
        let h = hidden_of(
            "module top; logic clk, a, r;\n\
             always @(posedge clk) r <= $sampled(a);\nendmodule\n",
        )
        .unwrap();
        assert_eq!(names(&h.p), ["top.a$p"]);
        assert!(h.s.is_empty() && h.sites.is_empty());
    }

    /// The gate's signals need P cells (the guard reads them).
    #[test]
    fn past_gate_signals_get_p_cells() {
        let h = hidden_of(
            "module top; logic clk, en, q, r;\n\
             always @(posedge clk) r <= $past(q, 2, en);\nendmodule\n",
        )
        .unwrap();
        assert_eq!(names(&h.p), ["top.clk$p", "top.en$p", "top.q$p"]);
    }

    /// A design with no sampled call has no hidden cells.
    #[test]
    fn no_sampled_calls_no_hidden_cells() {
        let h = hidden_of("module top; logic clk, a; always @(posedge clk) a <= ~a;\nendmodule\n")
            .unwrap();
        assert!(h.is_empty() && h.sites.is_empty());
    }

    /// The enumeration is deterministic: two runs agree.
    #[test]
    fn enumeration_is_deterministic() {
        let src = "module top; logic clk, a, b, r;\n\
                   always @(posedge clk) r <= $rose(a) ^ $fell(b) ^ $past(a, 2);\nendmodule\n";
        assert_eq!(hidden_of(src).unwrap(), hidden_of(src).unwrap());
    }

    /// A sampled call inside another's argument is a named error.
    #[test]
    fn nested_sampled_calls_are_rejected() {
        let e = hidden_of(
            "module top; logic clk, a, r;\n\
             always @(posedge clk) r <= $past($rose(a));\nendmodule\n",
        )
        .map(|_| ())
        .unwrap_err();
        assert!(e.0.contains("nested"), "{e}");
    }

    /// An automatic loop variable is not a state slot: no cell for `i` (16.5.1:
    /// its sampled value is its current value).
    #[test]
    fn automatic_loop_variable_gets_no_cell() {
        let h = hidden_of(
            "module top; logic clk; logic [3:0] b, r1;\n\
             always @(posedge clk) for (int i = 0; i < 4; i++) r1[i] <= $past(b[i]);\n\
             endmodule\n",
        )
        .unwrap();
        assert_eq!(names(&h.p), ["top.b$p", "top.clk$p"]);
        assert_eq!(h.s.len(), 1);
    }

    /// `$past`'s tick count shall be 1 or greater (16.9.3).
    #[test]
    fn past_zero_ticks_is_rejected() {
        let e = hidden_of(
            "module top; logic clk, a, r;\n\
             always @(posedge clk) r <= $past(a, 0);\nendmodule\n",
        )
        .map(|_| ())
        .unwrap_err();
        assert!(e.0.contains("number_of_ticks"), "{e}");
    }

    /// A signal whose type has no hidden-cell support is a named error, never
    /// a silent read of its current value.
    #[test]
    fn unsampleable_signal_types_are_rejected() {
        for (decl, call) in [
            ("logic [3:0] m [0:3]; logic r;", "$past(m[1])"),
            ("real x; logic r;", "$rose(x > 1.0)"),
            ("string s; logic r;", "$changed(s == \"a\")"),
        ] {
            let src = format!(
                "module top; logic clk; {decl}\n\
                 always @(posedge clk) r <= {call};\nendmodule\n"
            );
            let e = hidden_of(&src).map(|_| ()).unwrap_err();
            assert!(
                e.0.contains("sampled value is not supported"),
                "{call}: {e}"
            );
        }
    }

    /// A user function's body reads module signals the sampled views cannot
    /// redirect, so a call inside the argument is rejected.
    #[test]
    fn user_function_call_in_the_argument_is_rejected() {
        let e = hidden_of(
            "module top; logic clk, a, r;\n\
             function logic f(logic x); return x; endfunction\n\
             always @(posedge clk) r <= $rose(f(a));\nendmodule\n",
        )
        .map(|_| ())
        .unwrap_err();
        assert!(e.0.contains("user subroutine call"), "{e}");
    }

    /// A hierarchical reference's source lives in another instance: this one
    /// keeps its own P and S cells of it, built from a shape (LRM 23.6).
    #[test]
    fn hierarchical_reference_in_the_argument_gets_foreign_cells() {
        let h = hidden_of(
            "module top; logic clk, r;\n\
             sub u();\n\
             always @(posedge clk) r <= $rose(u.v);\nendmodule\n\
             module sub; logic v; endmodule\n",
        )
        .expect("accepted");
        assert!(
            h.p.iter()
                .any(|c| c.foreign.as_ref().is_some_and(|f| f.required))
        );
        assert!(h.s.iter().all(|c| c.foreign.is_some()), "{:?}", h.s);
    }

    /// The views a call reads: `$sampled` the P cell, a value change function
    /// P (now) and S_0 (before), `$past(x, n)` the n-th history cell.
    #[test]
    fn use_views_pick_the_cell_each_function_reads() {
        let design = compile_source(
            "module top; logic clk, a, b, c, r;\n\
             always @(posedge clk) begin\n\
               r <= $sampled(a); r <= $rose(b); r <= $past(c, 3);\n\
             end\nendmodule\n",
        )
        .expect("compiles");
        let body = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let block = crate::netlist::module_items(&body)
            .into_iter()
            .find(|m| m.kind() == SymbolKind::ProceduralBlock)
            .expect("one procedural block");
        let owner = block.uid();
        let sites = sites_of_block(&block).unwrap();
        assert_eq!(sites.len(), 3);
        let views: Vec<UseViews> = sites
            .iter()
            .map(|s| use_views(&owner, &s.call, &s.arg_signals))
            .collect();
        let a = body.find("a").unwrap().uid();
        let b = body.find("b").unwrap().uid();
        let c = body.find("c").unwrap().uid();
        let loc = |i: usize| site_loc(&sites[i].call.call);
        assert_eq!(views[0].cur, [(a.clone(), p_id(&a))]);
        assert!(views[0].prev.is_empty());
        assert_eq!(views[1].cur, [(b.clone(), p_id(&b))]);
        assert_eq!(views[1].prev, [(b.clone(), s_id(&owner, &loc(1), &b, 0))]);
        assert_eq!(views[2].cur, [(c.clone(), s_id(&owner, &loc(2), &c, 2))]);
        assert!(views[2].prev.is_empty());
    }

    /// A clock inferred for one instance is found again, by source text, in
    /// the same procedure of another instance of the module.
    #[test]
    fn relocate_clock_finds_the_same_event_in_another_instance() {
        let design = compile_source(
            "module sub(input logic clk, input logic d, output logic r);\n\
               always @(negedge clk) r <= $rose(d);\nendmodule\n\
             module top; logic clk, d, r1, r2;\n\
               sub u1(clk, d, r1); sub u2(clk, d, r2);\nendmodule\n",
        )
        .expect("compiles");
        let top = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let block_of = |inst: &str| {
            let body = top.find(inst).unwrap().instance_body().unwrap();
            crate::netlist::module_items(&body)
                .into_iter()
                .find(|m| m.kind() == SymbolKind::ProceduralBlock)
                .unwrap()
        };
        let (b1, b2) = (block_of("u1"), block_of("u2"));
        let ev1 = {
            let mut found = None;
            walk(
                crate::process::cfg::proc_body(&b1).unwrap().as_sem_node(),
                &mut |n| {
                    if found.is_none() {
                        found = n.as_timing_control();
                    }
                    found.is_none()
                },
            );
            clock_event_of(found.expect("the always has an event control")).unwrap()
        };
        let ev2 = relocate_clock(&b2, &ev1).unwrap();
        assert_eq!(ev2.edge, EdgeKind::NegEdge);
        assert_eq!(
            ev2.signal.referenced_symbol().unwrap().uid().path(),
            "top.u2.clk"
        );
        assert_eq!(
            ev1.signal.referenced_symbol().unwrap().uid().path(),
            "top.u1.clk"
        );
    }

    /// 16.9.4: `$past_gclk(v)` is defined as `$past(v,,,@$global_clock)` and
    /// `$rose_gclk(v)` as `$rose(v, @$global_clock)`: both spellings decode to
    /// the same call (`global`, no explicit clock event of its own).
    #[test]
    fn gclk_spellings_and_explicit_global_clock_event_decode_alike() {
        let design = compile_source(
            "module top; logic gclk; logic [3:0] v, r;\n\
             global clocking sys @(posedge gclk); endclocking\n\
             always @(posedge gclk) begin\n\
               r <= $past_gclk(v); r <= $past(v, , , @$global_clock);\n\
               r <= $rose_gclk(v); r <= $rose(v, @$global_clock);\n\
               r <= $past_gclk(v) + $past(v, , , @(posedge gclk));\n\
             end\nendmodule\n",
        )
        .expect("compiles");
        let body = design
            .top_instances()
            .next()
            .unwrap()
            .instance_body()
            .unwrap();
        let block = crate::netlist::module_items(&body)
            .into_iter()
            .find(|m| m.kind() == SymbolKind::ProceduralBlock)
            .unwrap();
        let sites = sites_of_block(&block).unwrap();
        let shape: Vec<(SampledOp, bool, bool)> = sites
            .iter()
            .map(|s| (s.call.op, s.call.global, s.call.clock.is_some()))
            .collect();
        assert_eq!(
            shape,
            [
                (SampledOp::Past, true, false),
                (SampledOp::Past, true, false),
                (SampledOp::Rose, true, false),
                (SampledOp::Rose, true, false),
                (SampledOp::Past, true, false),
                // An ordinary explicit event is not global.
                (SampledOp::Past, false, true),
            ]
        );
        // The global clocking's signal needs a P cell for the guard.
        let h = hidden_slots(&body).unwrap();
        assert!(names(&h.p).contains(&"top.gclk$p".to_owned()), "{:?}", h.p);
    }

    /// The explicit clock's signals get P cells.
    #[test]
    fn explicit_clock_signals_get_p_cells() {
        let h = hidden_of(
            "module top; logic clk, clk2, b, r;\n\
             always @(posedge clk) r <= $rose(b, @(posedge clk2));\nendmodule\n",
        )
        .unwrap();
        assert!(names(&h.p).contains(&"top.clk2$p".to_owned()));
    }
}