vj-sim 0.3.0

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

use std::collections::HashSet;

use super::bins::BinValues;
use super::coverpoint::{CovEvent, Coverage, Coverpoint};
use super::cross::Cross;
use super::decl::{
    ArrayKind, BinDecl, BinKind, Bound, CoverpointDecl, CrossBinDecl, CrossDecl, Matches,
    RangeItem, SelectExpr,
};
use super::options::{Options, TypeOptions};
use super::value::{CovError, Eval, Expr, KernelId, NoKernels, TypeInfo, Val};

fn r(lo: i128, hi: i128) -> RangeItem {
    RangeItem::Range(Bound::Expr(Expr::int(lo)), Bound::Expr(Expr::int(hi)))
}

fn s(v: i128) -> RangeItem {
    RangeItem::Single(Expr::int(v))
}

fn rr(lo: f64, hi: f64) -> RangeItem {
    RangeItem::Range(Bound::Expr(Expr::real(lo)), Bound::Expr(Expr::real(hi)))
}

fn bin(name: &str, items: Vec<RangeItem>) -> BinDecl {
    BinDecl::ranges(name, items)
}

fn open(name: &str, items: Vec<RangeItem>) -> BinDecl {
    BinDecl::ranges(name, items).array(ArrayKind::Open)
}

fn cp_decl(name: &str, ty: TypeInfo, bins: Vec<BinDecl>) -> CoverpointDecl {
    let mut d = CoverpointDecl::new(name, ty, Expr::Kernel(0));
    d.bins = bins;
    d
}

fn make_cp(d: &CoverpointDecl, ev: &mut dyn Eval, ctor: &[Val]) -> Coverpoint {
    Coverpoint::new(d, &Options::default(), &TypeOptions::default(), ev, ctor)
        .expect("coverpoint builds")
        .0
}

fn cp(name: &str, ty: TypeInfo, bins: Vec<BinDecl>) -> Coverpoint {
    make_cp(&cp_decl(name, ty, bins), &mut NoKernels, &[])
}

fn try_cross(
    d: &CrossDecl,
    cps: &[Coverpoint],
    ev: &mut dyn Eval,
    ctor: &[Val],
) -> Result<(Cross, Vec<String>), CovError> {
    let refs: Vec<&Coverpoint> = cps.iter().collect();
    Cross::new(
        d,
        &refs,
        &Options::default(),
        &TypeOptions::default(),
        ev,
        ctor,
    )
}

fn cross(d: &CrossDecl, cps: &[Coverpoint]) -> Cross {
    try_cross(d, cps, &mut NoKernels, &[])
        .expect("cross builds")
        .0
}

/// Samples every coverpoint with its value, then the cross.
fn feed_ev(
    cps: &mut [Coverpoint],
    x: &mut Cross,
    vals: &[i128],
    ev: &mut dyn Eval,
) -> Vec<CovEvent> {
    for (c, v) in cps.iter_mut().zip(vals) {
        c.sample_value(&Val::Int(*v), ev, &[]).unwrap();
    }
    let refs: Vec<&Coverpoint> = cps.iter().collect();
    x.sample(&refs, ev, &[]).unwrap()
}

fn feed(cps: &mut [Coverpoint], x: &mut Cross, vals: &[i128]) -> Vec<CovEvent> {
    feed_ev(cps, x, vals, &mut NoKernels)
}

fn binsof(cp: &str) -> SelectExpr {
    SelectExpr::Binsof {
        cp: cp.to_string(),
        bin: None,
        intersect: None,
    }
}

fn binsof_bin(cp: &str, bin: &str) -> SelectExpr {
    SelectExpr::Binsof {
        cp: cp.to_string(),
        bin: Some(bin.to_string()),
        intersect: None,
    }
}

fn binsof_in(cp: &str, ranges: Vec<RangeItem>) -> SelectExpr {
    SelectExpr::Binsof {
        cp: cp.to_string(),
        bin: None,
        intersect: Some(ranges),
    }
}

fn not(e: SelectExpr) -> SelectExpr {
    SelectExpr::Not(Box::new(e))
}

fn and(a: SelectExpr, b: SelectExpr) -> SelectExpr {
    SelectExpr::And(Box::new(a), Box::new(b))
}

fn or(a: SelectExpr, b: SelectExpr) -> SelectExpr {
    SelectExpr::Or(Box::new(a), Box::new(b))
}

fn with(sel: SelectExpr, kernel: KernelId, matches: Matches) -> SelectExpr {
    SelectExpr::With {
        sel: Box::new(sel),
        expr: Expr::Kernel(kernel),
        matches,
    }
}

fn normal(name: &str, select: SelectExpr) -> CrossBinDecl {
    CrossBinDecl::new(name, BinKind::Normal, select)
}

fn tuples(x: &Cross, bin: &str) -> Vec<String> {
    x.tuples_of(bin).unwrap_or_else(|| panic!("no bin {bin}"))
}

fn auto_names(x: &Cross) -> Vec<String> {
    x.auto_bins().into_iter().map(|(n, _)| n).collect()
}

/// An evaluator running a closure over kernel ids.
struct Fn1<F: FnMut(KernelId, &[Val]) -> Val>(F);

impl<F: FnMut(KernelId, &[Val]) -> Val> Eval for Fn1<F> {
    fn eval(&mut self, id: KernelId, args: &[Val]) -> Result<Val, CovError> {
        Ok((self.0)(id, args))
    }
}

fn int_of(v: &Val) -> i128 {
    match v {
        Val::Int(i) => *i,
        o => panic!("not an int: {o:?}"),
    }
}

fn b2i(b: bool) -> Val {
    Val::Int(b as i128)
}

// ---------------------------------------------------------------- 19.6

#[test]
fn cross_is_the_cartesian_product_of_all_bins() {
    // 19.6: `aXb : cross a, b` of two 4-bit variables: 16 auto bins each, so
    // 256 cross products, each a bin of aXb.
    let ty = TypeInfo::unsigned(4);
    let cps = [cp("a", ty, vec![]), cp("b", ty, vec![])];
    let x = cross(&CrossDecl::new("aXb", &["a", "b"]), &cps);
    assert_eq!(x.space(), 256);
    assert_eq!(
        x.coverage(),
        Coverage {
            covered: 0,
            total: 256
        }
    );
    let names = auto_names(&x);
    assert_eq!(names.len(), 256);
    assert_eq!(names[0], "<auto[0],auto[0]>");
    assert_eq!(names[1], "<auto[0],auto[1]>");
    assert_eq!(names[255], "<auto[15],auto[15]>");
}

#[test]
fn cross_of_variable_and_explicit_coverpoint_makes_160_bins() {
    // 19.6 cov3: b_var gives auto[0]..auto[15], A gives yy[0]..yy[9]:
    // 16 x 10 = 160 cross products in the order <auto[0],yy[0]>,
    // <auto[0],yy[1]>, ... <auto[15],yy[9]>.
    let cps = [
        cp("b_var", TypeInfo::unsigned(4), vec![]),
        cp("A", TypeInfo::unsigned(32), vec![open("yy", vec![r(0, 9)])]),
    ];
    let x = cross(&CrossDecl::new("CC", &["b_var", "A"]), &cps);
    let names = auto_names(&x);
    assert_eq!(names.len(), 160);
    assert_eq!(names[0], "<auto[0],yy[0]>");
    assert_eq!(names[1], "<auto[0],yy[1]>");
    assert_eq!(names[10], "<auto[1],yy[0]>");
    assert_eq!(names[159], "<auto[15],yy[9]>");
}

#[test]
fn default_ignore_and_illegal_bins_make_no_cross_products() {
    // 19.6: "No cross coverage bins shall be created for coverpoint bins that
    // are specified as default, ignored, or illegal bins."
    let ty = TypeInfo::unsigned(4);
    let cps = [
        cp(
            "a",
            ty,
            vec![
                bin("lo", vec![r(0, 3)]),
                bin("ign", vec![r(4, 5)]).kind(BinKind::Ignore),
                bin("ill", vec![r(6, 7)]).kind(BinKind::Illegal),
                BinDecl::default_bin("rest"),
            ],
        ),
        cp(
            "b",
            ty,
            vec![bin("one", vec![s(1)]), bin("two", vec![s(2)])],
        ),
    ];
    let x = cross(&CrossDecl::new("c", &["a", "b"]), &cps);
    assert_eq!(auto_names(&x), ["<lo,one>", "<lo,two>"]);
}

#[test]
fn sampling_counts_the_tuple_of_the_matching_bins() {
    let ty = TypeInfo::unsigned(4);
    let mut cps = [
        cp(
            "a",
            ty,
            vec![bin("lo", vec![r(0, 7)]), bin("hi", vec![r(8, 15)])],
        ),
        cp(
            "b",
            ty,
            vec![bin("lo", vec![r(0, 7)]), bin("hi", vec![r(8, 15)])],
        ),
    ];
    let mut x = cross(&CrossDecl::new("c", &["a", "b"]), &cps);
    feed(&mut cps, &mut x, &[1, 9]);
    feed(&mut cps, &mut x, &[2, 12]);
    feed(&mut cps, &mut x, &[9, 9]);
    assert_eq!(x.hits("<lo,hi>"), Some(2));
    assert_eq!(x.hits("<hi,hi>"), Some(1));
    assert_eq!(x.hits("<lo,lo>"), Some(0));
    assert_eq!(x.hits("<nope>"), None);
    assert_eq!(
        x.coverage(),
        Coverage {
            covered: 2,
            total: 4
        }
    );
    assert_eq!(x.samples, 3);
}

// ---------------------------------------------------------------- 19.6.1

fn ct_cps() -> [Coverpoint; 2] {
    let ty = TypeInfo::signed(32);
    [
        cp("i", ty, vec![open("i", vec![r(0, 1)])]),
        cp("j", ty, vec![open("j", vec![r(0, 1)])]),
    ]
}

#[test]
fn ct_example_x1_has_four_auto_bins() {
    // 19.6.1: x1 has <i[0],j[0]>, <i[1],j[0]>, <i[0],j[1]>, <i[1],j[1]>
    // (listed there in a different order than ours; the set is what counts).
    let cps = ct_cps();
    let x = cross(&CrossDecl::new("x1", &["i", "j"]), &cps);
    let mut names = auto_names(&x);
    names.sort();
    assert_eq!(
        names,
        ["<i[0],j[0]>", "<i[0],j[1]>", "<i[1],j[0]>", "<i[1],j[1]>"]
    );
}

#[test]
fn ct_example_x2_keeps_auto_bins_outside_the_user_bin() {
    // 19.6.1: x2 has i_zero (for <i[0],j[0]> and <i[0],j[1]>) plus the
    // retained automatic bins <i[1],j[0]> and <i[1],j[1]>.
    let mut cps = ct_cps();
    let d = CrossDecl::new("x2", &["i", "j"]).bin(normal("i_zero", binsof_in("i", vec![s(0)])));
    let mut x = cross(&d, &cps);
    assert_eq!(tuples(&x, "i_zero"), ["<i[0],j[0]>", "<i[0],j[1]>"]);
    assert_eq!(auto_names(&x), ["<i[1],j[0]>", "<i[1],j[1]>"]);
    assert_eq!(x.coverage().total, 3);
    feed(&mut cps, &mut x, &[0, 1]);
    feed(&mut cps, &mut x, &[1, 1]);
    assert_eq!(x.hits("i_zero"), Some(1));
    assert_eq!(x.hits("<i[1],j[1]>"), Some(1));
    assert_eq!(x.hits("<i[0],j[1]>"), None);
    assert_eq!(
        x.coverage(),
        Coverage {
            covered: 2,
            total: 3
        }
    );
}

#[test]
fn cross_retain_auto_bins_zero_drops_the_automatic_bins() {
    // 19.7 / 19.6.1: cross_retain_auto_bins = 0 leaves only the user bins.
    let cps = ct_cps();
    let mut d = CrossDecl::new("x2", &["i", "j"]).bin(normal("i_zero", binsof_in("i", vec![s(0)])));
    d.options
        .push(("cross_retain_auto_bins".to_string(), Expr::int(0)));
    let x = cross(&d, &cps);
    assert!(auto_names(&x).is_empty());
    assert_eq!(x.coverage().total, 1);
}

fn abcd_cps() -> [Coverpoint; 2] {
    let ty = TypeInfo::unsigned(8);
    [
        cp(
            "a",
            ty,
            vec![
                bin("a1", vec![r(0, 63)]),
                bin("a2", vec![r(64, 127)]),
                bin("a3", vec![r(128, 191)]),
                bin("a4", vec![r(192, 255)]),
            ],
        ),
        cp(
            "b",
            ty,
            vec![
                bin("b1", vec![s(0)]),
                bin("b2", vec![r(1, 84)]),
                bin("b3", vec![r(85, 169)]),
                bin("b4", vec![r(170, 255)]),
            ],
        ),
    ]
}

fn c_decl() -> CrossDecl {
    CrossDecl::new("c", &["a", "b"])
        .bin(normal("c1", not(binsof_in("a", vec![r(100, 200)]))))
        .bin(normal(
            "c2",
            or(binsof_bin("a", "a2"), binsof_bin("b", "b2")),
        ))
        .bin(normal(
            "c3",
            and(binsof_bin("a", "a1"), binsof_bin("b", "b4")),
        ))
}

#[test]
fn lrm_19_6_1_1_select_expressions() {
    // 19.6.1.1: c1 = 4 products <a1,b1..b4>; c2 = 7 products; c3 = 1 product
    // <a1,b4>; 6 automatic bins are retained.
    let cps = abcd_cps();
    let x = cross(&c_decl(), &cps);
    assert_eq!(
        tuples(&x, "c1"),
        ["<a1,b1>", "<a1,b2>", "<a1,b3>", "<a1,b4>"]
    );
    assert_eq!(
        tuples(&x, "c2"),
        [
            "<a1,b2>", "<a2,b1>", "<a2,b2>", "<a2,b3>", "<a2,b4>", "<a3,b2>", "<a4,b2>"
        ]
    );
    assert_eq!(tuples(&x, "c3"), ["<a1,b4>"]);
    assert_eq!(
        auto_names(&x),
        [
            "<a3,b1>", "<a3,b3>", "<a3,b4>", "<a4,b1>", "<a4,b3>", "<a4,b4>"
        ]
    );
    assert_eq!(x.coverage().total, 9);
}

#[test]
fn lrm_19_6_1_1_sampling_counts_each_bin_once_per_sample() {
    let mut cps = abcd_cps();
    let mut x = cross(&c_decl(), &cps);
    // <a2,b2> is in c2 only
    feed(&mut cps, &mut x, &[70, 80]);
    // <a1,b4> is in both c1 and c3
    feed(&mut cps, &mut x, &[10, 200]);
    // <a3,b1> is a retained automatic bin
    feed(&mut cps, &mut x, &[130, 0]);
    assert_eq!(x.hits("c1"), Some(1));
    assert_eq!(x.hits("c2"), Some(1));
    assert_eq!(x.hits("c3"), Some(1));
    assert_eq!(x.hits("<a3,b1>"), Some(1));
    assert_eq!(
        x.coverage(),
        Coverage {
            covered: 4,
            total: 9
        }
    );
}

#[test]
fn a_bin_with_several_matching_products_counts_once_per_sample() {
    // 19.6.1: "The count of the bin is incremented every time any of the cross
    // products match": two overlapping bins of `a` both take 5, giving two
    // matching products in one user bin, which counts once.
    let ty = TypeInfo::unsigned(4);
    let mut cps = [
        cp(
            "a",
            ty,
            vec![bin("a1", vec![s(5)]), bin("a2", vec![r(5, 6)])],
        ),
        cp("b", ty, vec![bin("b1", vec![s(0)])]),
    ];
    let d = CrossDecl::new("c", &["a", "b"]).bin(normal("all", binsof("a")));
    let mut x = cross(&d, &cps);
    feed(&mut cps, &mut x, &[5, 0]);
    assert_eq!(x.hits("all"), Some(1));
    feed(&mut cps, &mut x, &[6, 0]);
    assert_eq!(x.hits("all"), Some(2));
}

#[test]
fn binsof_names_an_array_by_its_base_name() {
    // 19.6.1: `binsof(b.two)` selects every bin of the array two[].
    let ty = TypeInfo::unsigned(4);
    let cps = [
        cp("a", ty, vec![bin("only", vec![s(0)])]),
        cp(
            "b",
            ty,
            vec![open("two", vec![r(0, 2)]), bin("other", vec![s(9)])],
        ),
    ];
    let d = CrossDecl::new("c", &["a", "b"])
        .bin(normal("arr", binsof_bin("b", "two")))
        .bin(normal("one", binsof_bin("b", "two[1]")));
    let x = cross(&d, &cps);
    assert_eq!(
        tuples(&x, "arr"),
        ["<only,two[0]>", "<only,two[1]>", "<only,two[2]>"]
    );
    assert_eq!(tuples(&x, "one"), ["<only,two[1]>"]);
}

#[test]
fn binsof_with_intersect_keeps_bins_that_share_a_value() {
    // 19.6.1: bins whose values intersect {5,[1:3]} (ranges and singles).
    let ty = TypeInfo::unsigned(3);
    let cps = [
        cp("a", ty, vec![open("a", vec![r(0, 7)])]),
        cp("b", ty, vec![bin("b", vec![r(0, 1)])]),
    ];
    let d = CrossDecl::new("c", &["a", "b"])
        .bin(normal("hit", binsof_in("a", vec![s(5), r(1, 3)])))
        .bin(normal("miss", not(binsof_in("a", vec![s(5), r(1, 3)]))));
    let x = cross(&d, &cps);
    assert_eq!(
        tuples(&x, "hit"),
        ["<a[1],b>", "<a[2],b>", "<a[3],b>", "<a[5],b>"]
    );
    assert_eq!(
        tuples(&x, "miss"),
        ["<a[0],b>", "<a[4],b>", "<a[6],b>", "<a[7],b>"]
    );
}

#[test]
fn intersect_on_a_wide_bin_overlaps_by_range() {
    // a bin intersects when any of its values is in the list
    let cps = abcd_cps();
    let d = CrossDecl::new("c", &["a", "b"]).bin(normal("w", binsof_in("a", vec![s(64)])));
    let x = cross(&d, &cps);
    assert_eq!(tuples(&x, "w").len(), 4);
    assert!(tuples(&x, "w").iter().all(|t| t.starts_with("<a2,")));
}

#[test]
fn binsof_on_a_transition_bin_uses_the_last_value() {
    // 19.6.1.1: "When select expressions are specified on transition bins, the
    // binsof operator uses the last value of the transition."
    let ty = TypeInfo::unsigned(4);
    let cps = [
        cp(
            "t",
            ty,
            vec![BinDecl::trans(
                "up",
                vec![vec![
                    super::decl::TransItem::new(vec![s(1)]),
                    super::decl::TransItem::new(vec![s(2)]),
                ]],
            )],
        ),
        cp("b", ty, vec![bin("b", vec![s(0)])]),
    ];
    let d = CrossDecl::new("c", &["t", "b"])
        .bin(normal("last", binsof_in("t", vec![s(2)])))
        .bin(normal("first", binsof_in("t", vec![s(1)])));
    let x = cross(&d, &cps);
    assert_eq!(tuples(&x, "last"), ["<up,b>"]);
    assert!(tuples(&x, "first").is_empty());
    // a bin with no tuples is empty, excluded from coverage
    assert!(x.bins().iter().find(|b| b.name == "first").unwrap().empty);
    assert_eq!(x.coverage().total, 1);
}

#[test]
fn a_transition_bin_forms_a_tuple_when_the_sequence_completes() {
    let ty = TypeInfo::unsigned(4);
    let mut cps = [
        cp(
            "t",
            ty,
            vec![BinDecl::trans(
                "up",
                vec![vec![
                    super::decl::TransItem::new(vec![s(1)]),
                    super::decl::TransItem::new(vec![s(2)]),
                ]],
            )],
        ),
        cp("b", ty, vec![bin("b", vec![s(0)])]),
    ];
    let mut x = cross(&CrossDecl::new("c", &["t", "b"]), &cps);
    feed(&mut cps, &mut x, &[1, 0]);
    assert_eq!(x.hits("<up,b>"), Some(0));
    feed(&mut cps, &mut x, &[2, 0]);
    assert_eq!(x.hits("<up,b>"), Some(1));
}

// ---------------------------------------------------------------- 19.6.1.2

fn apple_cps() -> [Coverpoint; 2] {
    let ty = TypeInfo::unsigned(8);
    let mut ev = Fn1(|id, args: &[Val]| match id {
        1 => b2i(int_of(&args[0]) % 2 == 0),
        2 => b2i(int_of(&args[0]) % 3 == 0),
        other => panic!("kernel {other}"),
    });
    let a = cp(
        "a",
        ty,
        vec![open("low", vec![r(0, 127)]), bin("high", vec![r(128, 255)])],
    );
    let b = make_cp(
        &cp_decl(
            "b",
            ty,
            vec![
                open("two", vec![r(0, 255)]).with(Expr::Kernel(1)),
                open("three", vec![r(0, 255)]).with(Expr::Kernel(2)),
            ],
        ),
        &mut ev,
        &[],
    );
    [a, b]
}

/// The cross-level kernels of the 19.6.1.2 example: args are `a, b`.
fn apple_ev() -> Fn1<impl FnMut(KernelId, &[Val]) -> Val> {
    Fn1(|id, args: &[Val]| {
        let (a, b) = (int_of(&args[0]), int_of(&args[1]));
        match id {
            10 => b2i(a + b < 257),
            11 => b2i(a == b),
            12 => b2i(b > 12),
            13 => b2i(a & b & 0xFF != 0),
            other => panic!("kernel {other}"),
        }
    })
}

#[test]
fn lrm_19_6_1_2_apple_selects_three_bin_tuples() {
    // 19.6.1.2: `bins apple = X with (a+b < 257) matches 127` consists of
    // <high,two[0]>, <high,two[2]> and <high,three[0]>.
    let cps = apple_cps();
    let d = CrossDecl::new("X", &["a", "b"]).bin(normal(
        "apple",
        with(SelectExpr::All, 10, Matches::Count(Expr::int(127))),
    ));
    let (x, _) = try_cross(&d, &cps, &mut apple_ev(), &[]).unwrap();
    assert_eq!(
        tuples(&x, "apple"),
        ["<high,two[0]>", "<high,two[2]>", "<high,three[0]>"]
    );
}

#[test]
fn lrm_19_6_1_2_cherry_selects_where_a_equals_b() {
    // 19.6.1.2: cherry = (binsof(b) intersect {[0:50]} && binsof(a.low)
    // intersect {[0:50]}) with (a==b): low[k] with a two[k] (k even, 26 of
    // them in 0..50) or a three[k] (k a multiple of 3, 17 in 0..48).
    let cps = apple_cps();
    let sel = with(
        and(
            binsof_in("b", vec![r(0, 50)]),
            SelectExpr::Binsof {
                cp: "a".to_string(),
                bin: Some("low".to_string()),
                intersect: Some(vec![r(0, 50)]),
            },
        ),
        11,
        Matches::one(),
    );
    let d = CrossDecl::new("X", &["a", "b"]).bin(normal("cherry", sel));
    let (x, _) = try_cross(&d, &cps, &mut apple_ev(), &[]).unwrap();
    let t = tuples(&x, "cherry");
    assert_eq!(t.len(), 26 + 17);
    assert!(t.contains(&"<low[0],two[0]>".to_string()));
    assert!(t.contains(&"<low[0],three[0]>".to_string()));
    assert!(t.contains(&"<low[48],two[48]>".to_string()));
    assert!(t.contains(&"<low[48],three[48]>".to_string()));
    assert!(t.contains(&"<low[50],two[50]>".to_string()));
    assert!(!t.contains(&"<low[50],three[50]>".to_string()));
    assert!(!t.contains(&"<low[1],two[0]>".to_string()));
}

#[test]
fn lrm_19_6_1_2_plum_unites_two_with_selections() {
    // 19.6.1.2: plum = binsof(b.two) with (b > 12) || binsof(a.low) with
    // (a & b & mask), with mask = 8'hFF. The expected set is recomputed here
    // by brute force over the value tuples.
    let cps = apple_cps();
    let sel = or(
        with(binsof_bin("b", "two"), 12, Matches::one()),
        with(binsof_bin("a", "low"), 13, Matches::one()),
    );
    let d = CrossDecl::new("X", &["a", "b"]).bin(normal("plum", sel));
    let (x, _) = try_cross(&d, &cps, &mut apple_ev(), &[]).unwrap();
    let mut a_bins: Vec<(String, i128)> = (0..128).map(|k| (format!("low[{k}]"), k)).collect();
    a_bins.push(("high".to_string(), 128));
    let mut b_bins: Vec<(String, i128)> = Vec::new();
    for v in (0..256).step_by(2) {
        b_bins.push((format!("two[{v}]"), v));
    }
    for v in (0..256).step_by(3) {
        b_bins.push((format!("three[{v}]"), v));
    }
    let mut want: HashSet<String> = HashSet::new();
    for (an, ak) in &a_bins {
        for (bn, bv) in &b_bins {
            let first = bn.starts_with("two") && *bv > 12;
            let second = an.starts_with("low") && (ak & bv & 0xFF) != 0;
            if first || second {
                want.insert(format!("<{an},{bn}>"));
            }
        }
    }
    let got: HashSet<String> = tuples(&x, "plum").into_iter().collect();
    assert_eq!(got.len(), want.len());
    assert_eq!(got, want);
    // spot checks that do not rely on the brute-force code
    assert!(got.contains("<high,two[14]>"));
    assert!(!got.contains("<high,two[12]>"));
    assert!(got.contains("<low[1],three[3]>"));
    assert!(got.contains("<low[2],three[3]>"));
    assert!(!got.contains("<low[4],three[3]>"));
}

#[test]
fn with_dollar_requires_every_value_tuple_to_satisfy() {
    // 19.6.1.2: `matches $` needs all value tuples. Bin tuples <lo,hi> hold
    // (a,b) in {0..3} x {4..7}; a<b holds for all of them.
    let ty = TypeInfo::unsigned(4);
    let cps = [
        cp(
            "a",
            ty,
            vec![bin("lo", vec![r(0, 3)]), bin("mid", vec![r(2, 5)])],
        ),
        cp("b", ty, vec![bin("hi", vec![r(4, 7)])]),
    ];
    let mut ev = Fn1(|_, args: &[Val]| b2i(int_of(&args[0]) < int_of(&args[1])));
    let all =
        CrossDecl::new("c", &["a", "b"]).bin(normal("all", with(SelectExpr::All, 1, Matches::All)));
    let (x, _) = try_cross(&all, &cps, &mut ev, &[]).unwrap();
    // <mid,hi> has (5,4), which fails a<b
    assert_eq!(tuples(&x, "all"), ["<lo,hi>"]);
    let any = CrossDecl::new("c", &["a", "b"])
        .bin(normal("any", with(SelectExpr::All, 1, Matches::one())));
    let (x, _) = try_cross(&any, &cps, &mut ev, &[]).unwrap();
    assert_eq!(tuples(&x, "any"), ["<lo,hi>", "<mid,hi>"]);
}

#[test]
fn with_kernel_receives_constructor_arguments_first() {
    // value.rs convention: constructor arguments, then one value per item.
    let ty = TypeInfo::unsigned(4);
    let cps = [
        cp("a", ty, vec![open("a", vec![r(0, 3)])]),
        cp("b", ty, vec![open("b", vec![r(0, 3)])]),
    ];
    let mut ev = Fn1(|_, args: &[Val]| {
        assert_eq!(args.len(), 3);
        b2i(int_of(&args[1]) + int_of(&args[2]) == int_of(&args[0]))
    });
    let d = CrossDecl::new("c", &["a", "b"])
        .bin(normal("sum", with(SelectExpr::All, 1, Matches::one())));
    let (x, _) = try_cross(&d, &cps, &mut ev, &[Val::Int(3)]).unwrap();
    assert_eq!(
        tuples(&x, "sum"),
        ["<a[0],b[3]>", "<a[1],b[2]>", "<a[2],b[1]>", "<a[3],b[0]>"]
    );
}

#[test]
fn matches_must_be_positive() {
    let cps = abcd_cps();
    let d = CrossDecl::new("c", &["a", "b"]).bin(normal(
        "z",
        with(SelectExpr::All, 1, Matches::Count(Expr::int(0))),
    ));
    let mut ev = Fn1(|_, _: &[Val]| b2i(true));
    assert!(matches!(
        try_cross(&d, &cps, &mut ev, &[]),
        Err(CovError::CrossSelect { .. })
    ));
}

#[test]
fn with_over_a_huge_space_is_a_named_error_not_a_hang() {
    let ty = TypeInfo::unsigned(32);
    let cps = [cp("a", ty, vec![]), cp("b", ty, vec![])];
    let d =
        CrossDecl::new("c", &["a", "b"]).bin(normal("w", with(SelectExpr::All, 1, Matches::All)));
    let mut ev = Fn1(|_, _: &[Val]| b2i(true));
    assert!(matches!(
        try_cross(&d, &cps, &mut ev, &[]),
        Err(CovError::TooManyValues { .. })
    ));
}

// ---------------------------------------------------------------- 19.6.1.4

fn set_expr(pairs: &[(i128, i128)]) -> Expr {
    Expr::Const(Val::List(
        pairs
            .iter()
            .map(|&(x, y)| Val::List(vec![Val::Int(x), Val::Int(y)]))
            .collect(),
    ))
}

fn set_sel(pairs: &[(i128, i128)], matches: Matches) -> SelectExpr {
    SelectExpr::Set {
        expr: set_expr(pairs),
        matches,
    }
}

#[test]
fn lrm_19_6_1_4_array_literal_defines_the_bin_tuples() {
    // 19.6.1.4: `bins one = '{ '{1,2}, '{3,4}, '{5,6} }` is
    // <a.x[1],b.y[2]>, <a.x[3],b.y[4]>, <a.x[5],b.y[6]>.
    let cps = [
        cp("a", TypeInfo::signed(32), vec![open("x", vec![r(0, 10)])]),
        cp("b", TypeInfo::unsigned(8), vec![open("y", vec![r(0, 20)])]),
    ];
    let d = CrossDecl::new("aXb", &["a", "b"]).bin(normal(
        "one",
        set_sel(&[(1, 2), (3, 4), (5, 6)], Matches::one()),
    ));
    let x = cross(&d, &cps);
    assert_eq!(
        tuples(&x, "one"),
        ["<x[1],y[2]>", "<x[3],y[4]>", "<x[5],y[6]>"]
    );
}

#[test]
fn lrm_19_6_1_4_function_built_queues_for_wide_coverpoints() {
    // 19.6.1.4 mod_m: cg(3) with 32-bit coverpoints a and b (64 auto bins
    // each): one = <0,0>,<1,1>,<2,2>; two = <0,0>,<2,2>,<4,4>. All of those
    // values fall into <auto[0],auto[0]>, so each is one bin tuple, selected
    // by the default policy (one value tuple) and by `matches 3` / `matches 2`
    // but not by a larger count.
    let ty = TypeInfo::unsigned(32);
    let cps = [cp("a", ty, vec![]), cp("b", ty, vec![])];
    let first = "<auto[0:67108863],auto[0:67108863]>";
    let one = &[(0, 0), (1, 1), (2, 2)];
    let two = &[(0, 0), (2, 2), (4, 4)];
    let d = CrossDecl::new("aXb", &["a", "b"])
        .bin(normal("one", set_sel(one, Matches::one())))
        .bin(normal("two", set_sel(two, Matches::one())))
        .bin(normal("one3", set_sel(one, Matches::Count(Expr::int(3)))))
        .bin(normal("one4", set_sel(one, Matches::Count(Expr::int(4)))))
        .bin(normal("oneall", set_sel(one, Matches::All)));
    let x = cross(&d, &cps);
    assert_eq!(tuples(&x, "one"), [first]);
    assert_eq!(tuples(&x, "two"), [first]);
    assert_eq!(tuples(&x, "one3"), [first]);
    assert!(tuples(&x, "one4").is_empty());
    // `$`: all 2^26 x 2^26 value tuples would have to be listed
    assert!(tuples(&x, "oneall").is_empty());
}

#[test]
fn set_expression_tuples_are_deduplicated_and_unknown_ones_skipped() {
    let ty = TypeInfo::unsigned(32);
    let cps = [cp("a", ty, vec![]), cp("b", ty, vec![])];
    let list = Expr::Const(Val::List(vec![
        Val::List(vec![Val::Int(1), Val::Int(1)]),
        Val::List(vec![Val::Int(1), Val::Int(1)]),
        Val::List(vec![Val::Unknown, Val::Int(2)]),
    ]));
    let d = CrossDecl::new("c", &["a", "b"]).bin(normal(
        "dup",
        SelectExpr::Set {
            expr: list,
            matches: Matches::Count(Expr::int(2)),
        },
    ));
    let x = cross(&d, &cps);
    // one distinct tuple: below the required two
    assert!(tuples(&x, "dup").is_empty());
}

#[test]
fn set_expression_values_outside_every_bin_select_nothing() {
    let ty = TypeInfo::unsigned(8);
    let cps = [
        cp("a", ty, vec![bin("a", vec![r(0, 3)])]),
        cp("b", ty, vec![bin("b", vec![r(0, 3)])]),
    ];
    let d = CrossDecl::new("c", &["a", "b"])
        .bin(normal("out", set_sel(&[(1, 9), (9, 1)], Matches::one())));
    let x = cross(&d, &cps);
    assert!(tuples(&x, "out").is_empty());
}

#[test]
fn set_expression_must_be_a_list_of_tuples_of_the_right_width() {
    let ty = TypeInfo::unsigned(8);
    let cps = [
        cp("a", ty, vec![bin("a", vec![r(0, 3)])]),
        cp("b", ty, vec![bin("b", vec![r(0, 3)])]),
    ];
    let wrong = CrossDecl::new("c", &["a", "b"]).bin(normal(
        "bad",
        SelectExpr::Set {
            expr: Expr::Const(Val::List(vec![Val::List(vec![Val::Int(1)])])),
            matches: Matches::one(),
        },
    ));
    assert!(matches!(
        try_cross(&wrong, &cps, &mut NoKernels, &[]),
        Err(CovError::CrossSelect { .. })
    ));
    let scalar = CrossDecl::new("c", &["a", "b"]).bin(normal(
        "bad",
        SelectExpr::Set {
            expr: Expr::int(3),
            matches: Matches::one(),
        },
    ));
    assert!(matches!(
        try_cross(&scalar, &cps, &mut NoKernels, &[]),
        Err(CovError::CrossSelect { .. })
    ));
}

// ---------------------------------------------------------------- 19.6.2

#[test]
fn ignore_bins_exclude_products_from_everything() {
    // 19.6.2: `ignore_bins ignore = binsof(a) intersect { 5, [1:3] }` removes
    // those products from coverage, even from other bins of the cross.
    let ty = TypeInfo::unsigned(3);
    let mut cps = [
        cp("a", ty, vec![open("a", vec![r(0, 7)])]),
        cp("b", ty, vec![bin("b", vec![r(0, 1)])]),
    ];
    let d = CrossDecl::new("yy", &["a", "b"])
        .bin(CrossBinDecl::new(
            "ignore",
            BinKind::Ignore,
            binsof_in("a", vec![s(5), r(1, 3)]),
        ))
        .bin(normal("hi", binsof_in("a", vec![r(4, 7)])));
    let mut x = cross(&d, &cps);
    // <a[5],b> is ignored, so "hi" holds the other three
    assert_eq!(tuples(&x, "hi"), ["<a[4],b>", "<a[6],b>", "<a[7],b>"]);
    assert_eq!(auto_names(&x), ["<a[0],b>"]);
    assert_eq!(x.coverage().total, 2);
    feed(&mut cps, &mut x, &[5, 0]);
    feed(&mut cps, &mut x, &[2, 0]);
    assert_eq!(x.hits("hi"), Some(0));
    assert_eq!(x.coverage().covered, 0);
    feed(&mut cps, &mut x, &[6, 1]);
    assert_eq!(x.hits("hi"), Some(1));
}

#[test]
fn a_user_bin_left_with_no_products_is_excluded_from_coverage() {
    // 19.6.2: its products were all ignored, so the bin is empty (19.11).
    let ty = TypeInfo::unsigned(3);
    let cps = [
        cp("a", ty, vec![open("a", vec![r(0, 1)])]),
        cp("b", ty, vec![bin("b", vec![r(0, 1)])]),
    ];
    let d = CrossDecl::new("c", &["a", "b"])
        .bin(CrossBinDecl::new(
            "ign",
            BinKind::Ignore,
            binsof_bin("a", "a[0]"),
        ))
        .bin(normal("gone", binsof_bin("a", "a[0]")))
        .bin(normal("kept", binsof_bin("a", "a[1]")));
    let x = cross(&d, &cps);
    let gone = x.bins().iter().find(|b| b.name == "gone").unwrap();
    assert!(gone.empty);
    assert_eq!(gone.tuple_count(), 0);
    assert_eq!(x.coverage().total, 1);
}

// ---------------------------------------------------------------- 19.6.3

fn illegal_fixture() -> ([Coverpoint; 2], CrossDecl) {
    let ty = TypeInfo::unsigned(4);
    let cps = [
        cp("x", ty, vec![open("x", vec![r(0, 3)])]),
        cp("y", ty, vec![open("y", vec![r(0, 3)])]),
    ];
    let d = CrossDecl::new("zz", &["x", "y"]).bin(CrossBinDecl::new(
        "illegal",
        BinKind::Illegal,
        binsof_in("y", vec![s(2)]),
    ));
    (cps, d)
}

#[test]
fn illegal_cross_product_is_a_runtime_error_and_not_covered() {
    // 19.6.3: "All cross products that satisfy the select expression are
    // excluded from coverage, and a run-time error is issued."
    let (mut cps, d) = illegal_fixture();
    let mut x = cross(&d, &cps);
    assert_eq!(x.coverage().total, 12);
    let ev = feed(&mut cps, &mut x, &[1, 2]);
    assert_eq!(
        ev,
        [CovEvent::IllegalBin {
            coverpoint: "zz".to_string(),
            bin: "illegal".to_string(),
            value: "<x[1],y[2]>".to_string(),
        }]
    );
    assert_eq!(x.hits("illegal"), Some(1));
    assert_eq!(x.coverage().covered, 0);
    assert!(feed(&mut cps, &mut x, &[1, 1]).is_empty());
}

#[test]
fn illegal_takes_precedence_over_ignore_and_user_bins() {
    // 19.6.3: illegal products error "even if they are also explicitly
    // ignored (using an ignore_bins) or included in another cross bin".
    let (mut cps, d) = illegal_fixture();
    let d = d
        .bin(CrossBinDecl::new(
            "ign",
            BinKind::Ignore,
            binsof_in("y", vec![r(2, 3)]),
        ))
        .bin(normal("usr", binsof_in("y", vec![r(1, 2)])));
    let mut x = cross(&d, &cps);
    let ev = feed(&mut cps, &mut x, &[0, 2]);
    assert_eq!(ev.len(), 1);
    assert_eq!(x.hits("usr"), Some(0));
    // y = 3 is only ignored: no event, no count
    assert!(feed(&mut cps, &mut x, &[0, 3]).is_empty());
    assert_eq!(x.hits("usr"), Some(0));
    // y = 1 is in usr
    feed(&mut cps, &mut x, &[0, 1]);
    assert_eq!(x.hits("usr"), Some(1));
}

#[test]
fn illegal_bin_value_comes_from_a_constructor_argument() {
    // 19.6.3 covergroup zz(int bad): `binsof(y) intersect {bad}`.
    let ty = TypeInfo::unsigned(4);
    let mut cps = [
        cp("x", ty, vec![open("x", vec![r(0, 3)])]),
        cp("y", ty, vec![open("y", vec![r(0, 3)])]),
    ];
    let d = CrossDecl::new("zz", &["x", "y"]).bin(CrossBinDecl::new(
        "illegal",
        BinKind::Illegal,
        binsof_in("y", vec![RangeItem::Single(Expr::Kernel(5))]),
    ));
    let mut ev = Fn1(|id, args: &[Val]| {
        assert_eq!(id, 5);
        args[0].clone()
    });
    let (mut x, _) = try_cross(&d, &cps, &mut ev, &[Val::Int(3)]).unwrap();
    assert!(feed(&mut cps, &mut x, &[0, 2]).is_empty());
    assert_eq!(feed(&mut cps, &mut x, &[0, 3]).len(), 1);
}

// ---------------------------------------------------------------- guards

#[test]
fn cross_iff_false_ignores_the_sample() {
    // 19.6: "If at any sample point, the condition evaluates to false, the
    // cross coverage is ignored."
    let ty = TypeInfo::unsigned(2);
    let mut cps = [cp("a", ty, vec![]), cp("b", ty, vec![])];
    let mut d = CrossDecl::new("c", &["a", "b"]);
    d.iff = Some(Expr::Kernel(7));
    let mut en = true;
    let mut ev = Fn1(|_, _: &[Val]| b2i(en));
    let mut x = try_cross(&d, &cps, &mut ev, &[]).unwrap().0;
    feed_ev(&mut cps, &mut x, &[1, 1], &mut ev);
    assert_eq!(x.hits("<auto[1],auto[1]>"), Some(1));
    en = false;
    let mut ev = Fn1(|_, _: &[Val]| b2i(en));
    feed_ev(&mut cps, &mut x, &[1, 1], &mut ev);
    assert_eq!(x.hits("<auto[1],auto[1]>"), Some(1));
    assert_eq!(x.samples, 1);
}

#[test]
fn cross_bin_iff_guards_only_that_bin() {
    // 19.6: the iff at the end of a cross bin is a per-bin guard.
    let ty = TypeInfo::unsigned(2);
    let mut cps = [
        cp("a", ty, vec![open("a", vec![r(0, 1)])]),
        cp("b", ty, vec![bin("b", vec![r(0, 3)])]),
    ];
    let d = CrossDecl::new("c", &["a", "b"])
        .bin(normal("guarded", binsof("a")).iff(Expr::Kernel(3)))
        .bin(normal("free", binsof("a")));
    let mut on = false;
    let mut ev = Fn1(|_, _: &[Val]| b2i(on));
    let mut x = try_cross(&d, &cps, &mut ev, &[]).unwrap().0;
    feed_ev(&mut cps, &mut x, &[0, 0], &mut ev);
    on = true;
    let mut ev = Fn1(|_, _: &[Val]| b2i(on));
    feed_ev(&mut cps, &mut x, &[0, 0], &mut ev);
    assert_eq!(x.hits("guarded"), Some(1));
    assert_eq!(x.hits("free"), Some(2));
}

#[test]
fn a_coverpoint_without_a_usable_value_forms_no_tuple() {
    // 19.6: a cross counts bin tuples; a coverpoint whose iff is false, whose
    // value is x/z, whose value is ignored, illegal or only in `default`, has
    // no bin to contribute.
    let ty = TypeInfo::unsigned(4);
    let mut a_decl = cp_decl(
        "a",
        ty,
        vec![
            bin("lo", vec![r(0, 3)]),
            bin("ign", vec![s(4)]).kind(BinKind::Ignore),
            bin("ill", vec![s(5)]).kind(BinKind::Illegal),
            BinDecl::default_bin("rest"),
        ],
    );
    a_decl.iff = Some(Expr::Kernel(9));
    let mut en = true;
    let mut ev = Fn1(|id, args: &[Val]| match id {
        9 => b2i(en),
        0 => args[0].clone(),
        _ => panic!(),
    });
    let a = make_cp(&a_decl, &mut ev, &[]);
    let b = cp("b", ty, vec![bin("one", vec![r(0, 15)])]);
    let mut cps = [a, b];
    let mut x = cross(&CrossDecl::new("c", &["a", "b"]), &cps);
    for v in [4, 5, 9] {
        let _ = feed(&mut cps, &mut x, &[v, 1]);
    }
    cps[0]
        .sample_value(&Val::Unknown, &mut NoKernels, &[])
        .unwrap();
    cps[1]
        .sample_value(&Val::Int(1), &mut NoKernels, &[])
        .unwrap();
    let refs: Vec<&Coverpoint> = cps.iter().collect();
    x.sample(&refs, &mut NoKernels, &[]).unwrap();
    assert_eq!(x.hits("<lo,one>"), Some(0));
    assert_eq!(x.samples, 0);
    // iff false at the coverpoint
    en = false;
    let mut ev = Fn1(|id, args: &[Val]| match id {
        9 => b2i(en),
        0 => args[0].clone(),
        _ => panic!(),
    });
    cps[0].sample(&mut ev, &[]).unwrap();
    let refs: Vec<&Coverpoint> = cps.iter().collect();
    x.sample(&refs, &mut NoKernels, &[]).unwrap();
    assert_eq!(x.samples, 0);
    // and a usable value counts
    feed(&mut cps, &mut x, &[2, 1]);
    assert_eq!(x.hits("<lo,one>"), Some(1));
}

#[test]
fn at_least_applies_to_cross_bins() {
    // 19.7: option.at_least on the cross: a bin is covered at that many hits.
    let ty = TypeInfo::unsigned(2);
    let mut cps = [
        cp("a", ty, vec![bin("a", vec![r(0, 3)])]),
        cp("b", ty, vec![bin("b", vec![r(0, 3)])]),
    ];
    let mut d = CrossDecl::new("c", &["a", "b"]).bin(normal("u", binsof("a")));
    d.options.push(("at_least".to_string(), Expr::int(2)));
    let mut x = cross(&d, &cps);
    assert_eq!(
        x.coverage(),
        Coverage {
            covered: 0,
            total: 1
        }
    );
    feed(&mut cps, &mut x, &[1, 1]);
    assert_eq!(x.coverage().covered, 0);
    feed(&mut cps, &mut x, &[2, 2]);
    assert_eq!(
        x.coverage(),
        Coverage {
            covered: 1,
            total: 1
        }
    );
}

#[test]
fn at_least_applies_to_automatic_cross_bins() {
    let ty = TypeInfo::unsigned(1);
    let mut cps = [cp("a", ty, vec![]), cp("b", ty, vec![])];
    let mut d = CrossDecl::new("c", &["a", "b"]);
    d.options.push(("at_least".to_string(), Expr::int(2)));
    let mut x = cross(&d, &cps);
    feed(&mut cps, &mut x, &[0, 0]);
    assert_eq!(
        x.coverage(),
        Coverage {
            covered: 0,
            total: 4
        }
    );
    feed(&mut cps, &mut x, &[0, 0]);
    assert_eq!(
        x.coverage(),
        Coverage {
            covered: 1,
            total: 4
        }
    );
}

#[test]
fn cross_inherits_at_least_from_the_covergroup() {
    // 19.7: at_least assigned at covergroup level is the default below it.
    let ty = TypeInfo::unsigned(1);
    let mut cps = [cp("a", ty, vec![]), cp("b", ty, vec![])];
    let cg = Options {
        at_least: 3,
        ..Options::default()
    };
    let refs: Vec<&Coverpoint> = cps.iter().collect();
    let mut x = Cross::new(
        &CrossDecl::new("c", &["a", "b"]),
        &refs,
        &cg,
        &TypeOptions::default(),
        &mut NoKernels,
        &[],
    )
    .unwrap()
    .0;
    assert_eq!(x.options.at_least, 3);
    for _ in 0..2 {
        feed(&mut cps, &mut x, &[1, 1]);
    }
    assert_eq!(x.coverage().covered, 0);
    feed(&mut cps, &mut x, &[1, 1]);
    assert_eq!(x.coverage().covered, 1);
}

#[test]
fn reset_zeroes_every_bin() {
    let ct = ct_cps();
    let mut cps = ct;
    let d = CrossDecl::new("x2", &["i", "j"]).bin(normal("i_zero", binsof_in("i", vec![s(0)])));
    let mut x = cross(&d, &cps);
    feed(&mut cps, &mut x, &[0, 0]);
    feed(&mut cps, &mut x, &[1, 0]);
    assert_eq!(x.coverage().covered, 2);
    x.reset();
    assert_eq!(x.coverage().covered, 0);
    assert_eq!(x.samples, 0);
}

// ---------------------------------------------------------------- real, wildcard

#[test]
fn cross_of_real_coverpoints_selects_by_interval_overlap() {
    // 19.6: a cross may include coverpoints of real expressions.
    let real = TypeInfo::real();
    let mut cps = [
        cp(
            "r",
            real,
            vec![bin("lo", vec![rr(0.0, 1.0)]), bin("hi", vec![rr(2.0, 3.0)])],
        ),
        cp("n", TypeInfo::unsigned(2), vec![bin("n", vec![r(0, 3)])]),
    ];
    let d = CrossDecl::new("c", &["r", "n"])
        .bin(normal("near", binsof_in("r", vec![rr(0.5, 0.6)])))
        .bin(normal(
            "single",
            binsof_in("r", vec![RangeItem::Single(Expr::real(3.0))]),
        ));
    let mut x = cross(&d, &cps);
    assert_eq!(tuples(&x, "near"), ["<lo,n>"]);
    assert_eq!(tuples(&x, "single"), ["<hi,n>"]);
    cps[0]
        .sample_value(&Val::Real(2.5), &mut NoKernels, &[])
        .unwrap();
    cps[1]
        .sample_value(&Val::Int(1), &mut NoKernels, &[])
        .unwrap();
    let refs: Vec<&Coverpoint> = cps.iter().collect();
    x.sample(&refs, &mut NoKernels, &[]).unwrap();
    assert_eq!(x.hits("single"), Some(1));
    assert_eq!(x.hits("near"), Some(0));
}

#[test]
fn with_over_a_real_coverpoint_is_a_named_error() {
    let real = TypeInfo::real();
    let cps = [
        cp("r", real, vec![bin("lo", vec![rr(0.0, 1.0)])]),
        cp("n", TypeInfo::unsigned(2), vec![bin("n", vec![r(0, 3)])]),
    ];
    let d =
        CrossDecl::new("c", &["r", "n"]).bin(normal("w", with(SelectExpr::All, 1, Matches::one())));
    let mut ev = Fn1(|_, _: &[Val]| b2i(true));
    assert!(matches!(
        try_cross(&d, &cps, &mut ev, &[]),
        Err(CovError::Unsupported(_))
    ));
}

#[test]
fn wildcard_bins_intersect_through_their_expanded_values() {
    // a wildcard bin `2'b1?` holds {2,3}
    let ty = TypeInfo::unsigned(2);
    let cps = [
        cp(
            "w",
            ty,
            vec![
                BinDecl::ranges(
                    "hi",
                    vec![RangeItem::Single(Expr::Const(Val::Pat {
                        bits: 0b10,
                        care: 0b10,
                    }))],
                )
                .wildcard(),
                bin("lo", vec![r(0, 1)]),
            ],
        ),
        cp("n", ty, vec![bin("n", vec![r(0, 3)])]),
    ];
    let d = CrossDecl::new("c", &["w", "n"]).bin(normal("three", binsof_in("w", vec![s(3)])));
    let x = cross(&d, &cps);
    assert_eq!(tuples(&x, "three"), ["<hi,n>"]);
}

#[test]
fn bin_values_of_default_bins_are_rejected() {
    let ty = TypeInfo::unsigned(2);
    let c = cp("a", ty, vec![BinDecl::default_bin("d")]);
    assert!(matches!(
        c.bins[0].values(&ty),
        Err(CovError::Unsupported(_))
    ));
    let c = cp("a", ty, vec![bin("x", vec![s(1)])]);
    assert!(matches!(c.bins[0].values(&ty), Ok(BinValues::Ints(_))));
}

// ---------------------------------------------------------------- errors

#[test]
fn malformed_crosses_are_named_errors() {
    let ty = TypeInfo::unsigned(2);
    let cps = [cp("a", ty, vec![]), cp("b", ty, vec![])];
    let mk = |d: CrossDecl| try_cross(&d, &cps, &mut NoKernels, &[]);
    // fewer than two items (Syntax 19-4)
    assert!(matches!(
        mk(CrossDecl::new("c", &["a"])),
        Err(CovError::CrossSelect { .. })
    ));
    // the coverpoints given are not the crossed ones
    assert!(matches!(
        mk(CrossDecl::new("c", &["a", "z"])),
        Err(CovError::CrossSelect { .. })
    ));
    // binsof of a coverpoint that is not crossed
    let d = CrossDecl::new("c", &["a", "b"]).bin(normal("x", binsof("z")));
    assert!(matches!(mk(d), Err(CovError::CrossSelect { .. })));
    // binsof of a bin the coverpoint does not have
    let d = CrossDecl::new("c", &["a", "b"]).bin(normal("x", binsof_bin("a", "nope")));
    assert!(matches!(mk(d), Err(CovError::CrossSelect { .. })));
}

#[test]
fn a_cross_space_over_the_limit_is_a_named_error() {
    let ty = TypeInfo::unsigned(12);
    let cps = [
        cp("a", ty, vec![open("a", vec![r(0, 4095)])]),
        cp("b", ty, vec![open("b", vec![r(0, 4095)])]),
    ];
    assert!(matches!(
        try_cross(&CrossDecl::new("c", &["a", "b"]), &cps, &mut NoKernels, &[]),
        Err(CovError::TooManyValues { .. })
    ));
}

#[test]
fn three_way_cross_numbers_tuples_first_item_most_significant() {
    let ty = TypeInfo::unsigned(1);
    let mut cps = [
        cp("a", ty, vec![]),
        cp("b", ty, vec![]),
        cp("c", ty, vec![]),
    ];
    let mut x = cross(&CrossDecl::new("x", &["a", "b", "c"]), &cps);
    assert_eq!(x.space(), 8);
    let names = auto_names(&x);
    assert_eq!(names[0], "<auto[0],auto[0],auto[0]>");
    assert_eq!(names[1], "<auto[0],auto[0],auto[1]>");
    assert_eq!(names[2], "<auto[0],auto[1],auto[0]>");
    assert_eq!(names[7], "<auto[1],auto[1],auto[1]>");
    feed(&mut cps, &mut x, &[1, 0, 1]);
    assert_eq!(x.hits("<auto[1],auto[0],auto[1]>"), Some(1));
    assert_eq!(
        x.coverage(),
        Coverage {
            covered: 1,
            total: 8
        }
    );
}