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
//! SCHED::SENSITIVITY — the inverted-index `SensitivityTable`, static
//! registration, and the `ValueChangeSink` adapter that routes a committed
//! value change to the set of processes it must wake (scheduler.md §4;
//! ARCHITECTURE §6.3; ledger SC-045, SC-046, SC-067, SC-071).
//!
//! `notify_change` (Task 7/8's `commit_nba`/`commit_blocking_write`) is the
//! *only* production caller of [`SensitivityTable::matches`], reached
//! through the thin [`SensitivityLookupSink`] adapter defined here — this
//! module owns the lookup, not the decision of what to do with a match (that
//! is Task 10's `queued_this_pass` dedup and the ready-set push, layered on
//! top of the `ProcessId`s this module yields).
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
use crate::process::PredicateFn;
use crate::sched::{EventTerm, EventWaitSet, ProcessId, StaticSensitivity, edge_between};
use crate::state::{ChangeDelta, EdgeKind, StateCellId, ValueChangeSink};
use vj_abi::{Bit4, Region, SimTime};
/// One row of the inverted index (scheduler.md §4's literal shape): `Static`
/// entries are installed once, at process-registration time, from
/// codegen-supplied `StaticSensitivity` metadata; `Dynamic` entries are
/// installed/removed every time a process suspends/resumes on a general
/// `@(...)`/`wait(...)` (built from the live [`EventWaitSet`] at that exact
/// suspend point) and are gone from the table the instant the owning process
/// resumes.
///
/// `Static::edge == None` means "any change" (`always_comb`/`always_latch`'s
/// LRM-implicit "all variables read" sensitivity); `Static::edge ==
/// Some(k)` means "only transitions classifying as `k`" (`always_ff`'s
/// explicit clock/reset edge). `Dynamic::edge` is not wrapped in `Option`
/// because scheduler.md's `EventWaitSet`/`EventTerm` family never produces an
/// untyped "no edge" dynamic term — an any-change dynamic wakeup (e.g. an
/// `ImplicitAny` disjunct, or a named-event trigger pulse) is represented
/// directly as `EdgeKind::None`, the same sentinel [`SensitivityTable::matches`]
/// treats as an unconditional match (any call into `matches` already implies
/// a real change happened — see `matches`'s doc comment) for `Static`
/// entries — so one matching rule serves both variants uniformly.
#[derive(Clone, Copy, Debug)]
pub enum SensitivityEntry {
Static {
proc: ProcessId,
/// The edge's index in `StaticSensitivity::edges` (reported as the fired
/// term, so a native process can tell which member of its event list fired).
term_index: usize,
edge: Option<EdgeKind>,
/// `Some((lsb, width))` for an `always_comb`/`always_latch` that reads
/// only a constant bit/part select of the cell (LRM 9.2.2.2.1: the
/// longest static prefix, not the whole variable, is in the implicit
/// sensitivity list): the entry matches only an update that changed
/// those bits (see [`SensitivityTable::narrow_static`]).
sel: Option<(u32, u32)>,
},
Dynamic {
proc: ProcessId,
term_index: usize,
edge: EdgeKind,
iff: Option<PredicateFn>,
/// `Some(count)` iff this row was installed from the *inner* term of
/// an `EventTerm::Repeat { count, inner }` (ledger SC-052) — `None`
/// for an ordinary `Edge`/`ImplicitAny`/`NamedEventTrigger` term.
/// `matches` surfaces this so `sched::control`'s
/// `EngineNotifySink::notify_change` can route a matching firing
/// through `RepeatCounters::on_term_fired` before ever enqueueing —
/// the sensitivity table itself only tracks *whether* a row is
/// repeat-sourced and its declared total, never a live remaining
/// count (that lives in `sched::repeat::RepeatCounters`, keyed by
/// `(proc, term_index)`, not here).
repeat_total: Option<u64>,
/// `Some((lsb, width))` for a wait on a bit/part select of the cell
/// (`@(v[3])`, `@(posedge v[5:4])`, LRM 9.4.2): the entry matches only
/// an update that changed those bits (and, for an edge, whose
/// transition on bit `lsb` is that edge) -- decided from the update's
/// [`ChangeDelta`], not from the cell's own bit-0 classification.
sel: Option<(u32, u32)>,
},
}
/// The inverted index itself: `StateCellId -> SmallVec<SensitivityEntry>`
/// (scheduler.md §4). `SmallVec<[_; 4]>` per the plan's literal type —
/// most cells are read by a small, fixed number of always-blocks, so this
/// avoids a heap allocation per row in the common case.
#[derive(Default)]
pub struct SensitivityTable {
table: FxHashMap<StateCellId, SmallVec<[SensitivityEntry; 4]>>,
/// Reverse index for [`Self::remove_dynamic`]: every cell on whose row a
/// `Dynamic` entry of the process was installed since its last removal.
/// Lets removal touch only those rows instead of scanning every row of
/// `table`. A cell may appear more than once (one entry per installed
/// term); removal is idempotent per row, so duplicates are harmless.
dynamic_cells: FxHashMap<ProcessId, SmallVec<[StateCellId; 4]>>,
}
impl SensitivityTable {
pub fn new() -> Self {
Self {
table: FxHashMap::default(),
dynamic_cells: FxHashMap::default(),
}
}
/// Pushes one `Dynamic` row for `proc` on `cell` and records the cell in
/// the reverse index.
fn push_dynamic(&mut self, cell: StateCellId, proc: ProcessId, entry: SensitivityEntry) {
self.table.entry(cell).or_default().push(entry);
self.dynamic_cells.entry(proc).or_default().push(cell);
}
/// Installs one `SensitivityEntry::Static` per `(cell, edge)` pair in
/// `sensitivity.edges` — the exact codegen-supplied read-set -> table-row
/// translation (SC-045/SC-046). Called exactly once per process, at
/// registration time; the production call site (`Engine::register_process`,
/// gated on `sensitivity.is_some()`) is Task 18's, not this module's —
/// this method itself has no idempotence guard because nothing here can
/// tell "first call" from "second call" for the same process, so that
/// invariant is the caller's obligation (proved by Task 18's dedicated
/// production-call-site test, per this task's own plan text).
pub fn install_static(&mut self, sensitivity: &StaticSensitivity, proc: ProcessId) {
for (term_index, &(cell, edge)) in sensitivity.edges.iter().enumerate() {
self.table
.entry(cell)
.or_default()
.push(SensitivityEntry::Static {
proc,
term_index,
edge,
sel: None,
});
}
}
/// Narrows `proc`'s installed `Static` entries on `cell` to the bit
/// windows `(lsb, width)` it actually reads (LRM 9.2.2.2.1): each entry
/// becomes one per window, matching only an update that changed that
/// window. A no-op for an empty `windows`; the per-process dedup gate
/// makes several matching windows of one update wake the process once.
pub fn narrow_static(&mut self, proc: ProcessId, cell: StateCellId, windows: &[(u32, u32)]) {
let Some(row) = self.table.get_mut(&cell) else {
return;
};
let mut narrowed: SmallVec<[SensitivityEntry; 4]> = SmallVec::new();
row.retain(|e| match *e {
SensitivityEntry::Static {
proc: p,
term_index,
edge: None,
sel: None,
} if p == proc => {
for &w in windows {
narrowed.push(SensitivityEntry::Static {
proc,
term_index,
edge: None,
sel: Some(w),
});
}
false
}
_ => true,
});
row.extend(narrowed);
}
/// Installs one `SensitivityEntry::Dynamic` per `(cell, term)` pair a
/// suspended `wait(...)`/`@(...)` implies, keyed by that term's index in
/// `wait.terms` (the same index `ResumeArg::EventFired { term_index }`
/// reports back on the firing wakeup). Recurses through
/// `EventTerm::Repeat` to its `inner` term, keeping the *outer* Repeat
/// term's index — the repeat *count* is resume-orchestration state (Task
/// 12/13's concern: how many times the inner event must fire before the
/// process actually resumes), not something the sensitivity table itself
/// tracks or needs to.
pub fn install_dynamic(&mut self, wait: &EventWaitSet, proc: ProcessId) {
for (term_index, term) in wait.terms.iter().enumerate() {
self.install_term(term, proc, term_index, None);
}
}
/// `repeat_total` is `None` for every top-level term except when
/// recursing into an `EventTerm::Repeat`'s `inner` term, where it becomes
/// `Some(count)` — threaded down so whatever leaf row(s) `inner`
/// installs (an `Edge`/`ImplicitAny`/`NamedEventTrigger`, or, in
/// principle, a further nested `Repeat`) carry the declared count `Task
/// 3` (ledger SC-052) needs at match time.
fn install_term(
&mut self,
term: &EventTerm,
proc: ProcessId,
term_index: usize,
repeat_total: Option<u64>,
) {
match term {
EventTerm::Edge { cell, edge, iff } => {
self.push_dynamic(
*cell,
proc,
SensitivityEntry::Dynamic {
proc,
term_index,
edge: *edge,
iff: *iff,
repeat_total,
sel: None,
},
);
}
EventTerm::ImplicitAny(cells) => {
for &cell in cells {
self.push_dynamic(
cell,
proc,
SensitivityEntry::Dynamic {
proc,
term_index,
edge: EdgeKind::None,
iff: None,
repeat_total,
sel: None,
},
);
}
}
EventTerm::Select {
cell,
edge,
lsb,
width,
} => {
self.push_dynamic(
*cell,
proc,
SensitivityEntry::Dynamic {
proc,
term_index,
edge: *edge,
iff: None,
repeat_total,
sel: Some((*lsb, *width)),
},
);
}
EventTerm::NamedEventTrigger(cell) => {
// scheduler.md §8: a named event's "write" is a pure trigger
// pulse with no persistent value — matched the same way an
// any-change disjunct is (any non-`None` classified change on
// its reserved `StateCellId` wakes the waiter).
self.push_dynamic(
*cell,
proc,
SensitivityEntry::Dynamic {
proc,
term_index,
edge: EdgeKind::None,
iff: None,
repeat_total,
sel: None,
},
);
}
EventTerm::Repeat { count, inner } => {
self.install_term(inner, proc, term_index, Some(*count));
}
}
}
/// Removes every `Dynamic` entry belonging to `proc`, from every cell —
/// "removed the instant the owning process resumes" (scheduler.md §4).
/// `Static` entries are untouched: they are installed once at
/// registration and must survive for the process's entire lifetime.
pub fn remove_dynamic(&mut self, proc: ProcessId) {
// Only the rows the process installed onto can hold its `Dynamic`
// entries (`push_dynamic` is the sole writer), so visit just those.
let Some(cells) = self.dynamic_cells.remove(&proc) else {
return;
};
for cell in cells {
if let Some(entries) = self.table.get_mut(&cell) {
entries.retain(|entry| {
!matches!(
entry,
SensitivityEntry::Dynamic { proc: p, .. } if *p == proc
)
});
}
}
}
/// Yields every `ProcessId` whose sensitivity entry on `cell` matches the
/// just-committed transition classified as `edge`.
///
/// `edge` is only ever `infer_edge`'s classification of *bit 0* of the
/// old/new value (`sched/notify.rs`'s LRM Table 9-1 scalar posedge/
/// negedge table) — it is not a "did the whole cell change" signal, and
/// a multi-bit cell can genuinely change (`SignalAccess::write` returns
/// `true`) while bit 0 itself stays fixed (e.g. `Narrow(0b10) ->
/// Narrow(0b110)`), in which case `infer_edge` reports `EdgeKind::None`
/// for a real change. Both production callers of this table
/// (`commit_nba`/`commit_blocking_write`, via `notify_change` /
/// [`SensitivityLookupSink`]) call in *only* for a write
/// `SignalAccess::write` reported as an actual change — so any call
/// reaching `matches` at all, regardless of what `edge` it carries,
/// represents a real change on `cell`. A "any change" entry
/// (`always_comb`/`always_latch`'s LRM-implicit read-set sensitivity,
/// SC-046) must therefore fire on *every* such call, not just the ones
/// where `infer_edge` happened to classify bit 0 as non-`None` — that is
/// the only reading consistent with "wake on any read-set change" rather
/// than "wake only when bit 0 of the read-set changes".
///
/// Matching rule (uniform across `Static`/`Dynamic`, unifying `Static`'s
/// `Option<EdgeKind>` to the same `EdgeKind` sentinel `Dynamic` already
/// uses via `.unwrap_or(EdgeKind::None)`):
/// - an entry whose edge is `EdgeKind::None` ("any change") matches
/// unconditionally — every call into `matches` is already gated, by
/// its callers, on a real change having happened, so the incoming
/// `edge` classification (which only speaks to bit 0) cannot be used
/// to veto an any-change waiter;
/// - an entry whose edge is `EdgeKind::BothEdges` (SV's `edge` keyword,
/// `@(edge sig)`) matches any real committed transition, i.e. an
/// incoming `Posedge` or `Negedge` — `infer_edge` (sched/notify.rs) is
/// documented and proved to never itself produce `BothEdges`, so this
/// is the entry-side wildcard for that keyword, not the incoming-side
/// one;
/// - any other edge-qualified entry matches that exact incoming `edge`,
/// or an incoming `EdgeKind::BothEdges` — kept for forward-compatibility
/// even though no production caller passes `BothEdges` as the
/// *incoming* classification today. An edge-qualified (`always_ff`)
/// entry is correctly *not* woken by a bit0-unchanged multi-bit change
/// it wasn't watching for — only the any-change case needs the
/// incoming-`edge`-is-imprecise fix above.
///
/// Returns, for every entry matching `(cell, edge)`, the tuple `(proc,
/// term_index, repeat_total, iff)` — `term_index` and `repeat_total` are
/// `0`/`None` respectively for a `Static` entry (which has no term-index
/// concept and is never `Repeat`-sourced); a `Dynamic` entry reports its
/// own installed `term_index`/`repeat_total` (Task 3, ledger SC-052 —
/// see [`SensitivityEntry::Dynamic`]'s own doc comment). Callers that
/// only need the `ProcessId` (every caller predating Task 3) destructure
/// and use only the first element.
///
/// **Task 5 (ledger SC-068) addition:** `iff` is the fourth element —
/// always `None` for a `Static` entry (that variant carries no `iff`
/// field: `always_comb`/`always_latch`'s implicit sensitivity has no LRM
/// `iff` clause) and a `Dynamic` entry's own installed
/// `iff: Option<PredicateFn>` otherwise. This method deliberately does
/// NOT evaluate `iff` — it has no `SimHandle`/arena access to call
/// through — so a match here means only "this entry's edge/cell
/// condition fired," not "the process should wake." The one production
/// caller with the access needed to actually invoke a `Some(iff)`
/// predicate before deciding to enqueue is `sched::control`'s
/// `EngineNotifySink::notify_change`.
pub fn matches(
&self,
cell: StateCellId,
edge: EdgeKind,
) -> impl Iterator<Item = (ProcessId, usize, Option<u64>, Option<PredicateFn>)> + '_ {
self.matches_delta(cell, edge, None)
}
/// The processes whose wait list holds `cell` now, first-registered
/// first, each once: the `Dynamic` rows of a suspended `@`/`wait` and the
/// `Static` rows of a procedure's implicit sensitivity (LRM 1800-2023
/// 37.27 detail 1, "all waiting processes, static or dynamic"). Read-only.
pub fn waiting_on(&self, cell: StateCellId) -> Vec<ProcessId> {
let mut out: Vec<ProcessId> = Vec::new();
for e in self.table.get(&cell).into_iter().flatten() {
let (SensitivityEntry::Static { proc, .. } | SensitivityEntry::Dynamic { proc, .. }) =
*e;
if !out.contains(&proc) {
out.push(proc);
}
}
out
}
/// Whether any entry on `cell` waits on a bit/part select of it, i.e.
/// whether a committed update needs to carry a [`ChangeDelta`].
pub fn has_select(&self, cell: StateCellId) -> bool {
self.table.get(&cell).is_some_and(|row| {
row.iter().any(|e| {
matches!(
e,
SensitivityEntry::Dynamic { sel: Some(_), .. }
| SensitivityEntry::Static { sel: Some(_), .. }
)
})
})
}
/// [`Self::matches`] with the update's old/new words: a select entry
/// (`EventTerm::Select`) matches only if the update changed its bits, and
/// takes its edge from bit `lsb` of the transition -- not from the cell's
/// own bit 0, which `edge` classifies. With no `delta` a select entry
/// falls back to the whole-cell rule (a superset: it can wake for a change
/// of a bit it does not select, never miss one).
pub fn matches_delta<'a>(
&'a self,
cell: StateCellId,
edge: EdgeKind,
delta: Option<&'a ChangeDelta>,
) -> impl Iterator<Item = (ProcessId, usize, Option<u64>, Option<PredicateFn>)> + 'a {
self.table
.get(&cell)
.into_iter()
.flatten()
.filter_map(move |entry| {
let (entry_proc, entry_edge, term_index, repeat_total, iff, sel) = match entry {
SensitivityEntry::Static {
proc,
term_index,
edge,
sel,
} => (
*proc,
edge.unwrap_or(EdgeKind::None),
*term_index,
None,
None,
*sel,
),
SensitivityEntry::Dynamic {
proc,
edge,
term_index,
repeat_total,
iff,
sel,
} => (*proc, *edge, *term_index, *repeat_total, *iff, *sel),
};
// The edge the entry is judged against: a select entry with a
// delta looks at its own bit, everything else at the cell's.
let mut edge = edge;
if let (Some((lsb, width)), Some(d)) = (sel, delta) {
if !d.range_changed(lsb, width) {
return None;
}
edge = d.bit(lsb).map_or(EdgeKind::None, |((oa, ob), (na, nb))| {
edge_between(Bit4::from_aval_bval(oa, ob), Bit4::from_aval_bval(na, nb))
});
}
let is_match = match (entry_edge, edge) {
(EdgeKind::None, _) => true,
(EdgeKind::BothEdges, e) => e == EdgeKind::Posedge || e == EdgeKind::Negedge,
(qualified, e) => e == qualified || e == EdgeKind::BothEdges,
};
is_match.then_some((entry_proc, term_index, repeat_total, iff))
})
}
/// **NEW (Task 18, `wA-sched` plan) — the `#[cfg(test)]`-only production
/// backing for `Engine::test_sensitivity_entry_count`** (SC-045's "exactly
/// once, at registration" proof; see `sched::control`'s deviations note).
/// Total entry count across every cell's row, `Static` and `Dynamic`
/// combined. `sched::control` (Task 18) is the same `sched` track that
/// owns this file, so this is an in-track, additive extension, not a
/// foreign-contract change; the method itself is not test-gated (a plain
/// `pub fn`, cheap and side-effect-free) so no `#[cfg(test)]` plumbing is
/// needed here, only at the `Engine` accessor's own call site.
pub fn entry_count(&self) -> usize {
self.table.values().map(|v| v.len()).sum()
}
}
/// A thin [`ValueChangeSink`] adapter over a [`SensitivityTable`]: routes
/// `notify_change` straight through `SensitivityTable::matches` into a
/// caller-owned `Vec<ProcessId>` (SC-071 — "a mock STATE implementation
/// calling `notify_change` is correctly routed to sensitivity lookup").
/// Task 7/8's `commit_nba`/`commit_blocking_write` take `&mut dyn
/// ValueChangeSink`, so wrapping a real `SensitivityTable` in this adapter is
/// how those two production call sites reach real sensitivity matching.
pub struct SensitivityLookupSink<'a> {
table: &'a SensitivityTable,
out: &'a mut Vec<ProcessId>,
}
impl<'a> SensitivityLookupSink<'a> {
pub fn new(table: &'a SensitivityTable, out: &'a mut Vec<ProcessId>) -> Self {
Self { table, out }
}
}
impl ValueChangeSink for SensitivityLookupSink<'_> {
fn notify_change(&mut self, cell: StateCellId, edge: EdgeKind, _at: SimTime, _region: Region) {
// This sink's own callers (`notify.rs`'s test module) only ever need
// the `ProcessId` half of `matches`'s richer tuple — repeat
// counting and `iff` evaluation are `EngineNotifySink`'s concern
// (`sched::control`), not this thin adapter's.
self.out
.extend(self.table.matches(cell, edge).map(|(p, _, _, _)| p));
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::state::FourStateValue;
const PROC_MAIN: ProcessId = 1;
// --- install_static / matches (SC-045, SC-046) ---
#[test]
fn always_comb_static_sensitivity_registers_one_entry_per_read_set_member() {
let a = StateCellId(1);
let b = StateCellId(2);
let c = StateCellId(3);
let sensitivity = StaticSensitivity {
edges: vec![(a, None), (b, None), (c, None)],
};
let mut table = SensitivityTable::new();
table.install_static(&sensitivity, PROC_MAIN);
for cell in [a, b, c] {
let hits: Vec<ProcessId> = table
.matches(cell, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect();
assert_eq!(
hits,
vec![PROC_MAIN],
"cell {cell:?} must wake the comb process on any change"
);
}
let total: usize = table.table.values().map(|v| v.len()).sum();
assert_eq!(total, 3, "exactly one entry per read-set member, no more");
}
#[test]
fn always_ff_static_sensitivity_registers_one_edge_qualified_entry() {
let clk = StateCellId(10);
let sensitivity = StaticSensitivity {
edges: vec![(clk, Some(EdgeKind::Posedge))],
};
let mut table = SensitivityTable::new();
table.install_static(&sensitivity, PROC_MAIN);
let posedge_hits: Vec<ProcessId> = table
.matches(clk, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect();
assert_eq!(posedge_hits, vec![PROC_MAIN]);
let negedge_hits: Vec<ProcessId> = table
.matches(clk, EdgeKind::Negedge)
.map(|(p, _, _, _)| p)
.collect();
assert!(
negedge_hits.is_empty(),
"an edge-qualified always_ff entry must not fire on the opposite edge"
);
}
#[test]
fn static_entries_survive_many_other_processes_suspend_resume_cycles() {
let watched = StateCellId(20);
let sensitivity = StaticSensitivity {
edges: vec![(watched, None)],
};
let mut table = SensitivityTable::new();
table.install_static(&sensitivity, PROC_MAIN);
// Five unrelated dynamic install/remove churn cycles for other
// processes, none of which touch `watched`'s static entry.
for other_proc in 100u32..105u32 {
let other_cell = StateCellId(1000 + u64::from(other_proc));
let wait = EventWaitSet {
terms: vec![EventTerm::Edge {
cell: other_cell,
edge: EdgeKind::Posedge,
iff: None,
}],
..Default::default()
};
table.install_dynamic(&wait, other_proc);
table.remove_dynamic(other_proc);
}
let hits: Vec<ProcessId> = table
.matches(watched, EdgeKind::Negedge)
.map(|(p, _, _, _)| p)
.collect();
assert_eq!(
hits,
vec![PROC_MAIN],
"the static entry must still match after unrelated dynamic churn"
);
}
#[test]
fn static_entries_installed_exactly_once_at_registration() {
let cell = StateCellId(30);
let sensitivity = StaticSensitivity {
edges: vec![(cell, None)],
};
let mut table = SensitivityTable::new();
table.install_static(&sensitivity, PROC_MAIN);
let total: usize = table.table.values().map(|v| v.len()).sum();
assert_eq!(
total, 1,
"install_static called once must produce exactly one entry"
);
}
// --- install_dynamic / remove_dynamic (feeds SC-055/SC-056, Task 10) ---
#[test]
fn dynamic_entry_removed_on_resume_is_gone_from_matches() {
let cell = StateCellId(40);
let wait = EventWaitSet {
terms: vec![EventTerm::Edge {
cell,
edge: EdgeKind::Posedge,
iff: None,
}],
..Default::default()
};
let mut table = SensitivityTable::new();
table.install_dynamic(&wait, PROC_MAIN);
assert_eq!(
table
.matches(cell, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN],
"dynamic entry must be visible to matches before resume"
);
table.remove_dynamic(PROC_MAIN);
assert!(
table.matches(cell, EdgeKind::Posedge).next().is_none(),
"dynamic entry must be gone from matches after remove_dynamic"
);
}
// --- ValueChangeSink routing (SC-071) ---
#[test]
fn notify_change_routes_through_sensitivity_lookup() {
let cell = StateCellId(50);
let sensitivity = StaticSensitivity {
edges: vec![(cell, None)],
};
let mut table = SensitivityTable::new();
table.install_static(&sensitivity, PROC_MAIN);
let mut woken: Vec<ProcessId> = Vec::new();
{
let mut sink = SensitivityLookupSink::new(&table, &mut woken);
sink.notify_change(
cell,
EdgeKind::Posedge,
SimTime {
sim_units: 0,
delta: 0,
},
Region::Nba,
);
}
assert_eq!(
woken,
vec![PROC_MAIN],
"notify_change through SensitivityLookupSink must be routed to matches"
);
}
#[test]
fn implicit_any_dynamic_term_matches_every_listed_cell() {
let a = StateCellId(60);
let b = StateCellId(61);
let wait = EventWaitSet {
terms: vec![EventTerm::ImplicitAny(vec![a, b])],
..Default::default()
};
let mut table = SensitivityTable::new();
table.install_dynamic(&wait, PROC_MAIN);
for cell in [a, b] {
assert_eq!(
table
.matches(cell, EdgeKind::Negedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN],
"ImplicitAny must register an any-change entry for every listed cell"
);
}
}
#[test]
fn select_term_matches_only_when_its_own_bits_change() {
// LRM 9.4.2: `@(posedge v[1])` and `@(v[5:4])` look at the selected
// bits of the operand, not at the whole signal.
let v = StateCellId(70);
let wait = EventWaitSet {
terms: vec![
EventTerm::Select {
cell: v,
edge: EdgeKind::Posedge,
lsb: 1,
width: 1,
},
EventTerm::Select {
cell: v,
edge: EdgeKind::None,
lsb: 4,
width: 2,
},
],
..Default::default()
};
let mut table = SensitivityTable::new();
table.install_dynamic(&wait, PROC_MAIN);
assert!(table.has_select(v));
let narrow = |val: u64| FourStateValue::Narrow(u128::from(val));
let terms = |old: u64, new: u64| -> Vec<usize> {
let d = ChangeDelta::between(&narrow(old), &narrow(new));
// The cell's own bit 0 is deliberately a bystander.
let edge = if (old ^ new) & 1 != 0 {
EdgeKind::Posedge
} else {
EdgeKind::None
};
table
.matches_delta(v, edge, Some(&d))
.map(|(_, term, _, _)| term)
.collect()
};
assert_eq!(terms(0b0000, 0b0010), vec![0], "v[1] rose");
assert_eq!(terms(0b0010, 0b0000), Vec::<usize>::new(), "v[1] fell");
assert_eq!(
terms(0b0000, 0b0001),
Vec::<usize>::new(),
"only v[0] moved"
);
assert_eq!(terms(0b00_0000, 0b01_0000), vec![1], "v[4] moved");
assert_eq!(terms(0b00_0000, 0b10_0000), vec![1], "v[5] moved");
assert_eq!(
terms(0b01_0000, 0b01_0010),
vec![0],
"v[1] rose, v[5:4] kept"
);
}
#[test]
fn named_event_trigger_term_installs_an_any_change_dynamic_entry() {
// scheduler.md §8's open design question: a named event's "write" is
// matched the same way an any-change disjunct is (any non-`None`
// classified change on its reserved StateCellId wakes the waiter).
// Mirrors `implicit_any_dynamic_term_matches_every_listed_cell`'s
// shape — this branch previously had zero test coverage anywhere in
// this file despite being an explicitly-flagged, non-trivial
// interpretation.
let ev = StateCellId(65);
let wait = EventWaitSet {
terms: vec![EventTerm::NamedEventTrigger(ev)],
..Default::default()
};
let mut table = SensitivityTable::new();
table.install_dynamic(&wait, PROC_MAIN);
assert_eq!(
table
.matches(ev, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN],
"NamedEventTrigger must register an any-change entry that wakes on a real committed transition"
);
let total: usize = table.table.values().map(|v| v.len()).sum();
assert_eq!(
total, 1,
"exactly one entry for the one NamedEventTrigger term"
);
}
#[test]
fn repeat_term_installs_its_inner_edge_at_the_outer_term_index() {
// The Repeat term sits at a non-zero outer index (1), behind an
// unrelated leading term at index 0, so a threading bug that used
// the wrong index (e.g. always 0, or the inner term's own
// nonexistent index) is distinguishable from the correct behavior —
// `matches()` alone can't see `term_index` (it only yields
// `ProcessId`), so this reads the installed entry's `term_index`
// directly out of the table's private `table` field.
let other = StateCellId(71);
let clk = StateCellId(70);
let wait = EventWaitSet {
terms: vec![
EventTerm::Edge {
cell: other,
edge: EdgeKind::Posedge,
iff: None,
},
EventTerm::Repeat {
count: 3,
inner: Box::new(EventTerm::Edge {
cell: clk,
edge: EdgeKind::Posedge,
iff: None,
}),
},
],
..Default::default()
};
let mut table = SensitivityTable::new();
table.install_dynamic(&wait, PROC_MAIN);
assert_eq!(
table
.matches(clk, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN]
);
let clk_entries = table
.table
.get(&clk)
.expect("clk must have an installed entry");
assert_eq!(
clk_entries.len(),
1,
"Repeat must install exactly its inner term's entries, not duplicate them"
);
match clk_entries[0] {
SensitivityEntry::Dynamic {
term_index,
repeat_total,
..
} => {
assert_eq!(
term_index, 1,
"Repeat must thread the OUTER term's index (1), not the inner term's own (nonexistent) index or a stale 0"
);
assert_eq!(
repeat_total,
Some(3),
"Task 3: the inner term's installed row must carry the Repeat's own \
declared count (3), for EngineNotifySink to decrement at match time"
);
}
SensitivityEntry::Static { .. } => {
panic!("install_dynamic must never produce a Static entry")
}
}
// The leading, non-Repeat Edge term at index 0 must carry no
// repeat_total at all -- proves install_term's default threading
// (`None` for every ordinary term) isn't accidentally contaminated
// by the Repeat sibling's count.
let other_entries = table
.table
.get(&other)
.expect("other must have an installed entry");
match other_entries[0] {
SensitivityEntry::Dynamic { repeat_total, .. } => {
assert_eq!(
repeat_total, None,
"an ordinary (non-Repeat) Edge term must install repeat_total: None"
);
}
SensitivityEntry::Static { .. } => {
panic!("install_dynamic must never produce a Static entry")
}
}
let total: usize = table.table.values().map(|v| v.len()).sum();
assert_eq!(
total, 2,
"one entry for the leading Edge term plus one for the Repeat's inner Edge term"
);
}
#[test]
fn both_edges_incoming_change_matches_either_edge_qualified_waiter() {
let clk = StateCellId(80);
let mut table = SensitivityTable::new();
table.install_static(
&StaticSensitivity {
edges: vec![(clk, Some(EdgeKind::Posedge))],
},
10,
);
table.install_static(
&StaticSensitivity {
edges: vec![(clk, Some(EdgeKind::Negedge))],
},
20,
);
let mut hits: Vec<ProcessId> = table
.matches(clk, EdgeKind::BothEdges)
.map(|(p, _, _, _)| p)
.collect();
hits.sort_unstable();
assert_eq!(
hits,
vec![10, 20],
"an incoming BothEdges change must match both a Posedge- and a Negedge-qualified waiter"
);
}
/// The actually-reachable direction of the `edge` keyword case
/// (`@(edge sig)`): the *entry* itself carries `EdgeKind::BothEdges`
/// (both `Static::edge: Some(BothEdges)` and
/// `Dynamic`/`EventTerm::Edge { edge: BothEdges, .. }` can produce this),
/// while `infer_edge` (sched/notify.rs) only ever hands `matches` a real
/// `Posedge`/`Negedge`/`None` classification — never `BothEdges` — as the
/// incoming committed-transition `edge`. A `BothEdges`-qualified entry
/// must therefore match both an incoming `Posedge` and an incoming
/// `Negedge`, and must not match a vacuous `None`.
#[test]
fn both_edges_qualified_entry_matches_incoming_posedge_and_negedge() {
let clk = StateCellId(90);
// Static::edge carrying Some(BothEdges).
let mut static_table = SensitivityTable::new();
static_table.install_static(
&StaticSensitivity {
edges: vec![(clk, Some(EdgeKind::BothEdges))],
},
PROC_MAIN,
);
assert_eq!(
static_table
.matches(clk, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN],
"a Static BothEdges-qualified entry must match a real incoming Posedge"
);
assert_eq!(
static_table
.matches(clk, EdgeKind::Negedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN],
"a Static BothEdges-qualified entry must match a real incoming Negedge"
);
assert!(
static_table.matches(clk, EdgeKind::None).next().is_none(),
"a Static BothEdges-qualified entry must not match a vacuous None classification"
);
// Dynamic EventTerm::Edge carrying edge: BothEdges (the literal
// `@(edge clk)` waitset shape).
let mut dynamic_table = SensitivityTable::new();
let wait = EventWaitSet {
terms: vec![EventTerm::Edge {
cell: clk,
edge: EdgeKind::BothEdges,
iff: None,
}],
..Default::default()
};
dynamic_table.install_dynamic(&wait, PROC_MAIN);
assert_eq!(
dynamic_table
.matches(clk, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN],
"a Dynamic BothEdges-qualified entry must match a real incoming Posedge"
);
assert_eq!(
dynamic_table
.matches(clk, EdgeKind::Negedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN],
"a Dynamic BothEdges-qualified entry must match a real incoming Negedge"
);
assert!(
dynamic_table.matches(clk, EdgeKind::None).next().is_none(),
"a Dynamic BothEdges-qualified entry must not match a vacuous None classification"
);
}
// --- Task 5 (B-sched, ledger SC-065, SC-066, SC-047, SC-048, SC-068):
// EventTerm/EventWaitSet shape + static/dynamic sensitivity closure ---
/// SC-065's literal acceptance: `EventWaitSet`'s only real semantics is
/// `WaitKind::Any` -- the first satisfied term wakes the process, with
/// no requirement that any *other* term in the set also match.
/// `install_dynamic` installs every term of a 3-term set as an
/// independent OR-alternative row, so matching on any ONE of the three
/// cells alone -- with the other two never having changed at all --
/// must already yield the process. Fails if a future refactor changes
/// `install_dynamic`/`matches` to require joint (AND) satisfaction of
/// every term before a process is reported as matched.
#[test]
fn sc065_event_wait_set_wakes_on_the_first_of_three_or_terms_to_match() {
let cell_1 = StateCellId(200);
let cell_2 = StateCellId(201);
let cell_3 = StateCellId(202);
let wait = EventWaitSet {
terms: vec![
EventTerm::Edge {
cell: cell_1,
edge: EdgeKind::Posedge,
iff: None,
},
EventTerm::Edge {
cell: cell_2,
edge: EdgeKind::Posedge,
iff: None,
},
EventTerm::Edge {
cell: cell_3,
edge: EdgeKind::Posedge,
iff: None,
},
],
..Default::default()
};
let mut table = SensitivityTable::new();
table.install_dynamic(&wait, PROC_MAIN);
// Only cell_2 changes -- cell_1/cell_3 are never touched by this
// test at all. A wrongly "joint" implementation has no way to
// report a match here (it would need evidence all three fired).
assert_eq!(
table
.matches(cell_2, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN],
"the first of three OR terms to match alone must wake the process"
);
// Independently, cell_1 alone (a *different* single term) must also
// wake it on its own -- proving no term is privileged/required.
assert_eq!(
table
.matches(cell_1, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN],
"any single OR term matching alone must wake the process, not just the last one"
);
}
/// SC-066's literal acceptance: `EventTerm` has exactly 5 variants (the
/// fifth, `Select`, is the bit/part-select wait of LRM 9.4.2). A
/// `match` with no wildcard arm over one instance of each is the
/// compile-time proof -- this fails to compile (not merely fails at
/// runtime) the moment a 6th variant is added without updating this
/// test, or if any of the 5 named ones is ever removed/renamed.
#[test]
fn sc066_event_term_has_exactly_five_variants_each_constructible() {
let cell = StateCellId(210);
let terms = [
EventTerm::Edge {
cell,
edge: EdgeKind::Posedge,
iff: None,
},
EventTerm::ImplicitAny(vec![cell]),
EventTerm::Select {
cell,
edge: EdgeKind::None,
lsb: 1,
width: 1,
},
EventTerm::NamedEventTrigger(cell),
EventTerm::Repeat {
count: 1,
inner: Box::new(EventTerm::Edge {
cell,
edge: EdgeKind::Posedge,
iff: None,
}),
},
];
for term in &terms {
// No wildcard arm: exhaustiveness itself is the SC-066 proof.
// Each arm cross-references the already-passing test that
// exercises that variant's firing/matching behavior elsewhere
// in this module.
match term {
// See `sc065_event_wait_set_wakes_on_the_first_of_three_or_
// terms_to_match` and `dynamic_entry_removed_on_resume_is_
// gone_from_matches` above.
EventTerm::Edge { .. } => {}
// See `implicit_any_dynamic_term_matches_every_listed_cell`.
EventTerm::ImplicitAny(_) => {}
// See `select_term_*` below.
EventTerm::Select { .. } => {}
// See `named_event_trigger_term_installs_an_any_change_
// dynamic_entry`.
EventTerm::NamedEventTrigger(_) => {}
// See `repeat_term_installs_its_inner_edge_at_the_outer_
// term_index`.
EventTerm::Repeat { .. } => {}
}
}
assert_eq!(terms.len(), 5, "exactly 5 EventTerm variants constructed");
}
/// SC-047, distinct from `dynamic_entry_removed_on_resume_is_gone_from_
/// matches` (which only proves removal happens) -- this proves survival
/// *until* removal, and that `remove_dynamic` is scoped strictly per-
/// process: installing and removing an unrelated process B's own
/// dynamic entry must never disturb process A's still-live one. A wrong
/// "clear everything" implementation of `remove_dynamic` would pass the
/// existing removal test but fail this one.
#[test]
fn sc047_dynamic_entry_for_a_proc_survives_until_that_procs_own_resume_removes_it() {
const PROC_A: ProcessId = 300;
const PROC_B: ProcessId = 301;
let cell_a = StateCellId(220);
let cell_b = StateCellId(221);
let mut table = SensitivityTable::new();
table.install_dynamic(
&EventWaitSet {
terms: vec![EventTerm::Edge {
cell: cell_a,
edge: EdgeKind::Posedge,
iff: None,
}],
..Default::default()
},
PROC_A,
);
// Unrelated process B installs and fully resumes (install then
// remove) its own dynamic wait -- must not touch A's entry at all.
table.install_dynamic(
&EventWaitSet {
terms: vec![EventTerm::Edge {
cell: cell_b,
edge: EdgeKind::Posedge,
iff: None,
}],
..Default::default()
},
PROC_B,
);
table.remove_dynamic(PROC_B);
assert_eq!(
table
.matches(cell_a, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_A],
"process A's dynamic entry must still be live after an unrelated process B's own \
install+remove cycle"
);
assert!(
table.matches(cell_b, EdgeKind::Posedge).next().is_none(),
"process B's own entry must be gone after its own remove_dynamic"
);
}
/// SC-048: a dynamic `EventWaitSet` is built fresh at each suspend point
/// and torn down the instant its owner resumes -- so a SAME process
/// suspending twice in succession on two DIFFERENT-shaped wait sets
/// (e.g. a process whose `@(...)` list changes between loop iterations)
/// must, after the second install, match only the second set's cells.
/// A leaked stale entry from the first install would make the first
/// set's cell wake the process too after the second suspend, which this
/// test catches.
#[test]
fn sc048_dynamic_wait_set_built_fresh_at_each_suspend_reflects_that_calls_own_terms() {
let cell_first = StateCellId(230);
let cell_second = StateCellId(231);
let mut table = SensitivityTable::new();
// First suspend: waits on cell_first.
table.install_dynamic(
&EventWaitSet {
terms: vec![EventTerm::Edge {
cell: cell_first,
edge: EdgeKind::Posedge,
iff: None,
}],
..Default::default()
},
PROC_MAIN,
);
// Resume (per SC-047/SC-048's own "removed the instant the owning
// process resumes"): the table must be told, exactly as
// `dispatch_ready_set` does in production.
table.remove_dynamic(PROC_MAIN);
// Second suspend, same process, a DIFFERENT-shaped wait set.
table.install_dynamic(
&EventWaitSet {
terms: vec![EventTerm::Edge {
cell: cell_second,
edge: EdgeKind::Posedge,
iff: None,
}],
..Default::default()
},
PROC_MAIN,
);
assert!(
table
.matches(cell_first, EdgeKind::Posedge)
.next()
.is_none(),
"the first suspend's wait set must leave no residue after the second install"
);
assert_eq!(
table
.matches(cell_second, EdgeKind::Posedge)
.map(|(p, _, _, _)| p)
.collect::<Vec<_>>(),
vec![PROC_MAIN],
"only the second, current wait set's own cell must match"
);
}
/// SC-068's own literal acceptance at the sensitivity-table level
/// (`sched::control`'s `engine_never_calls_resume_when_iff_is_false_
/// but_does_on_the_next_true_edge` is this same acceptance proven
/// against the production `Engine` dispatch loop): `matches` surfaces
/// an installed `iff` predicate as the 4th tuple element but does not
/// itself evaluate it (documented on `matches`'s own doc comment); a
/// caller that DOES evaluate it before deciding "the process should
/// wake" -- inlined here as `matches_with_iff`, mirroring
/// `EngineNotifySink::notify_change`'s real filter -- must report no
/// match at all while the predicate reads false, and a match once it
/// reads true. `PredicateFn` is settled (`docs/CONTRACTS.md` D8) as a
/// bare `extern "C" fn(SimHandle) -> bool` with no `StateCellId`
/// parameter of its own (a real compiled guard reads whatever cell it
/// needs through the handle) -- this mock instead reads a thread-local
/// flag the test flips directly.
#[test]
fn sc068_iff_false_produces_no_match_iff_true_does() {
use vj_abi::SimHandle;
thread_local! {
static EN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
extern "C" fn iff_reads_en(_state: SimHandle) -> bool {
EN.with(|c| c.get())
}
fn matches_with_iff(
table: &SensitivityTable,
cell: StateCellId,
edge: EdgeKind,
handle: SimHandle,
) -> Vec<ProcessId> {
table
.matches(cell, edge)
.filter(|(_, _, _, iff)| match iff {
Some(pred) => (pred.0)(handle),
None => true,
})
.map(|(p, _, _, _)| p)
.collect()
}
let clk = StateCellId(240);
let wait = EventWaitSet {
terms: vec![EventTerm::Edge {
cell: clk,
edge: EdgeKind::Posedge,
iff: Some(PredicateFn(iff_reads_en)),
}],
..Default::default()
};
let mut table = SensitivityTable::new();
table.install_dynamic(&wait, PROC_MAIN);
let handle = SimHandle(std::ptr::null_mut());
EN.with(|c| c.set(false));
assert!(
matches_with_iff(&table, clk, EdgeKind::Posedge, handle).is_empty(),
"iff=false must produce no match at all, not merely a match resume() ignores"
);
EN.with(|c| c.set(true));
assert_eq!(
matches_with_iff(&table, clk, EdgeKind::Posedge, handle),
vec![PROC_MAIN],
"iff=true must produce the match"
);
}
}