veryl-analyzer 0.22.0

A modern hardware description language
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
use super::*;

fn assert_comb_loop(case: &str, code: &str, expected: bool) {
    let errors = analyze(code);
    let actual = errors
        .iter()
        .any(|error| matches!(error, AnalyzerError::CombinationalLoop { .. }));
    assert_eq!(actual, expected, "{case}: {errors:?}");
}

#[test]
fn comb_loop_cast_width_boundary_preserves_signed_extension() {
    for (source_type, expression, source_bit, result_bit, expected) in [
        ("i8", "value as 4", 3, 7, true),
        ("i8", "value as 4", 2, 7, false),
        ("i8", "value as 4", 7, 7, false),
        ("i8", "value as 4", 3, 3, true),
        ("u8", "value as 4", 3, 7, false),
        ("i16", "value as i8", 7, 15, true),
        ("i16", "value as i8", 15, 15, false),
        ("u16", "value as i8", 7, 15, true),
        ("i16", "value as u8", 7, 15, false),
        ("i8", "(value as 4) | 8'b0", 3, 7, false),
        ("i8", "(value as 4) | 8'sh00", 3, 7, true),
        ("i8", "~(value as 4)", 3, 7, true),
        ("i8", "(value as 4) << 1", 3, 7, true),
        ("i8", "(value as 4) >> 1", 3, 15, false),
        ("i8", "(value as 4) >>> 1", 3, 15, true),
    ] {
        let code = format!(
            r#"
            module Top(o: output bit) {{
                var feedback: bit;
                var value: {source_type};
                var result: u16;
                assign value = (feedback as {source_type}) << {source_bit};
                assign result = {expression};
                assign feedback = result[{result_bit}];
                assign o = feedback;
            }}
            "#
        );
        let errors = analyze(&code);
        assert!(
            errors
                .iter()
                .all(|error| matches!(error, AnalyzerError::CombinationalLoop { .. })),
            "{code}\n{errors:#?}"
        );
        assert_eq!(!errors.is_empty(), expected, "{code}\n{errors:#?}");
        assert!(comb_loop_analysis_is_complete(&code), "{code}");
    }
}

#[test]
fn comb_loop_function_copyin_preserves_formal_width_boundary() {
    for signed in [false, true] {
        let prefix = if signed { "i" } else { "u" };
        for (source_bit, result_bit) in [(12, 12), (8, 8), (4, 4), (7, 7), (7, 15), (4, 15)] {
            for shift in [0, 4] {
                for nested in [false, true] {
                    let actual = if shift == 0 {
                        "value".to_string()
                    } else {
                        format!("value >> {shift}")
                    };
                    let callee = if nested { "wrap" } else { "widen" };
                    let bit = source_bit + shift;
                    let code = format!(
                        r#"
                        module Top(o: output bit) {{
                            var feedback: bit;
                            var value: {prefix}32;
                            var result: {prefix}16;
                            function widen(v: input {prefix}8) -> {prefix}16 {{ return v; }}
                            function wrap(v: input {prefix}32) -> {prefix}16 {{ return widen(v); }}
                            assign value = (feedback as {prefix}32) << {bit};
                            assign result = {callee}({actual});
                            assign feedback = result[{result_bit}];
                            assign o = feedback;
                        }}
                        "#
                    );
                    let expected = source_bit < 8
                        && (source_bit == result_bit
                            || (signed && source_bit == 7 && result_bit >= 8));
                    let errors = analyze(&code);
                    assert!(
                        errors
                            .iter()
                            .all(|error| matches!(error, AnalyzerError::CombinationalLoop { .. })),
                        "{code}\n{errors:#?}"
                    );
                    assert_eq!(!errors.is_empty(), expected, "{code}\n{errors:#?}");
                    assert!(comb_loop_analysis_is_complete(&code), "{code}");
                }
            }
        }
    }
}

#[test]
fn comb_loop_dynamic_selector_arithmetic_preserves_wrapping_and_narrowing() {
    for (index_type, destination, source, dst_size, src_size, dst, src) in [
        ("bit<2>", "index as 1", "index", 2, 4, 0, 2),
        ("bit<127>", "index as 1", "index", 2, 4, 0, 2),
        ("bit<2>", "index", "index as 1", 4, 2, 2, 0),
        ("bit", "index + 1'b1", "index", 2, 2, 0, 1),
        ("bit<2>", "index - 2'b01", "index", 4, 4, 3, 0),
        ("bit<2>", "index * 2'b10", "index * 4'b0010", 4, 8, 0, 4),
        ("bit<2>", "-index", "4'b0 - index", 4, 16, 3, 15),
    ] {
        for feedback_bit in [0, 1] {
            let initializers = (0..src_size)
                .map(|element| {
                    if element == src {
                        format!("assign b[{element}] = {{1'b0, a[{dst}][{feedback_bit}]}};")
                    } else {
                        format!("assign b[{element}] = 0;")
                    }
                })
                .collect::<Vec<_>>()
                .join("\n");
            let code = format!(
                r#"
                module Top(index: input {index_type}, o: output logic) {{
                    var a: logic<2>[{dst_size}];
                    var b: logic<2>[{src_size}];
                    always_comb {{
                        a = '{{default: 0}};
                        a[{destination}] = b[{source}];
                    }}
                    {initializers}
                    assign o = a[{dst}][0];
                }}
                "#
            );
            let errors = analyze(&code);
            assert!(
                errors
                    .iter()
                    .all(|error| matches!(error, AnalyzerError::CombinationalLoop { .. })),
                "{code}\n{errors:#?}"
            );
            assert_eq!(!errors.is_empty(), feedback_bit == 0, "{code}\n{errors:#?}");
            assert!(comb_loop_analysis_is_complete(&code), "{code}");
        }
    }
}

#[test]
fn comb_loop_dynamic_selector_mutation_during_rhs_keeps_feedback() {
    for expression in ["b[index] | clear_index()", "b[index] | clear_indirectly()"] {
        for in_function in [false, true] {
            for feedback_bit in [0, 1] {
                let body = format!("index = sel; a = '{{default: 0}}; a[index] = {expression};");
                let process = if in_function {
                    format!("function update() {{ {body} }} always_comb {{ update(); }}")
                } else {
                    format!("always_comb {{ {body} }}")
                };
                let code = format!(
                    r#"
                    module Top(sel: input logic, o: output logic) {{
                        var index: logic;
                        var a: logic<2>[2];
                        var b: logic<2>[2];
                        function clear_index() -> logic<2> {{
                            index = 0;
                            return 0;
                        }}
                        function clear_indirectly() -> logic<2> {{
                            return clear_index();
                        }}
                        {process}
                        assign b[0] = 0;
                        assign b[1] = {{1'b0, a[0][{feedback_bit}]}};
                        assign o = a[0][0];
                    }}
                    "#
                );
                let errors = analyze(&code);
                assert!(
                    errors
                        .iter()
                        .all(|error| matches!(error, AnalyzerError::CombinationalLoop { .. })),
                    "{code}\n{errors:#?}"
                );
                assert_eq!(!errors.is_empty(), feedback_bit == 0, "{code}\n{errors:#?}");
                assert!(comb_loop_analysis_is_complete(&code), "{code}");
            }
        }
    }
}

#[test]
fn comb_loop_dynamic_selector_bound_equality_respects_expression_widths() {
    for (index_type, start, end, expected) in [
        ("bit<2>", "index as 1", "index", true),
        ("bit", "(index + 1'b1) as 1", "index + 2'b01", true),
        ("bit", "index + 1'b1", "index + 2'b01", false),
        ("bit<2>", "index as 4", "index", false),
        ("bit<2>", "index + 1", "1 + index", false),
    ] {
        let code = format!(
            r#"
            module Top(index: input {index_type}, o: output logic) {{
                var feedback: logic;
                assign feedback = o;
                always_comb {{
                    o = 0;
                    for _iteration in ({start})..({end}) {{
                        o = feedback;
                    }}
                }}
            }}
            "#
        );
        let errors = analyze(&code);
        assert!(
            errors
                .iter()
                .all(|error| matches!(error, AnalyzerError::CombinationalLoop { .. })),
            "{code}\n{errors:#?}"
        );
        assert_eq!(!errors.is_empty(), expected, "{code}\n{errors:#?}");
        assert!(comb_loop_analysis_is_complete(&code), "{code}");
    }
}

#[test]
fn comb_loop_dynamic_selector_stable_values_keep_safe_offsets() {
    for (destination, source) in [
        ("index", "b[index]"),
        ("index as 2", "b[index]"),
        ("index", "b[index as 2]"),
        ("index + 1", "b[index]"),
        ("index", "b[index] | passthrough(sel)"),
    ] {
        let code = format!(
            r#"
            module Top(sel: input logic, o: output logic) {{
                var index: logic;
                var a: logic<2>[3];
                var b: logic<2>[2];
                function passthrough(value: input logic) -> logic<2> {{
                    return value as 2;
                }}
                always_comb {{
                    index = sel;
                    a = '{{default: 0}};
                    a[{destination}] = {source};
                }}
                assign b[0] = 0;
                assign b[1] = a[0];
                assign o = a[0][0];
            }}
            "#
        );
        assert!(analyze(&code).is_empty(), "{code}");
        assert!(comb_loop_analysis_is_complete(&code), "{code}");
    }

    let code = r#"
        module Top(i: input bit, j: input bit, o: output logic) {
            var a: logic[2, 2];
            var b: logic[2, 2];
            always_comb {
                a = '{default: 0};
                a[i][j] = b[i][j];
            }
            assign b[0] = '{default: 0};
            assign b[1][0] = 0;
            assign b[1][1] = a[0][0];
            assign o = a[0][0];
        }
    "#;
    assert!(analyze(code).is_empty());
    assert!(comb_loop_analysis_is_complete(code));
}

#[test]
fn comb_loop_false_negative_constant_dead_logical_rhs_overwrites_feedback() {
    assert_comb_loop(
        "a function in a constant-dead logical RHS cannot overwrite feedback",
        r#"
        module Top (
            o: output logic,
        ) {
            var a    : logic;
            var b    : logic;
            var dummy: logic;
            function clear_a () -> logic {
                a = 1'b0;
                return 1'b0;
            }
            always_comb {
                a = b;
                dummy = 1'b0 && clear_a();
                b = a;
                o = a | b | dummy;
            }
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_false_positive_constant_dead_logical_rhs_creates_feedback() {
    assert_comb_loop(
        "a function in a constant-dead logical RHS cannot create feedback",
        r#"
        module Top (
            o: output logic,
        ) {
            var a    : logic;
            var b    : logic;
            var dummy: logic;
            function write_a (value: input logic) -> logic {
                a = value;
                return 1'b0;
            }
            always_comb {
                a = 1'b0;
                dummy = 1'b0 && write_a(b);
                b = a;
                o = a | b | dummy;
            }
        }
        "#,
        false,
    );
}

#[test]
fn array_literal_default_does_not_contaminate_an_explicit_element() {
    assert_comb_loop(
        "an array literal default does not contaminate its explicit element",
        r#"
        module Top (
            o: output logic,
        ) {
            var source: logic [4];
            var built : logic [4];
            assign built = '{source[0], default: 1'b0};
            assign source[0] = built[3];
            assign source[1] = 0;
            assign source[2] = 0;
            assign source[3] = 0;
            assign o = built[0];
        }
        "#,
        false,
    );
}

#[test]
fn array_literal_explicit_element_retains_feedback() {
    assert_comb_loop(
        "an array literal retains its explicit element",
        r#"
        module Top (
            o: output logic,
        ) {
            var source: logic [4];
            var built : logic [4];
            assign built = '{source[0], default: 1'b0};
            assign source[0] = built[0];
            assign source[1] = 0;
            assign source[2] = 0;
            assign source[3] = 0;
            assign o = built[3];
        }
        "#,
        true,
    );
}

#[test]
fn multidimensional_array_literal_keeps_flattened_elements_disjoint() {
    assert_comb_loop(
        "a nested array literal keeps distinct flattened elements disjoint",
        r#"
        module Top (
            o: output logic,
        ) {
            var source: logic [2, 2];
            var built : logic [2, 2];
            assign built = '{'{source[0][0], 1'b0}, '{1'b0, 1'b0}};
            assign source[0][0] = built[1][1];
            assign source[0][1] = 0;
            assign source[1] = '{default: 0};
            assign o = built[0][0];
        }
        "#,
        false,
    );
}

#[test]
fn multidimensional_array_literal_retains_matching_element_feedback() {
    assert_comb_loop(
        "a nested array literal retains matching flattened element feedback",
        r#"
        module Top (
            o: output logic,
        ) {
            var source: logic [2, 2];
            var built : logic [2, 2];
            assign built = '{'{source[0][0], 1'b0}, '{1'b0, 1'b0}};
            assign source[0][0] = built[0][0];
            assign source[0][1] = 0;
            assign source[1] = '{default: 0};
            assign o = built[1][1];
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_false_positive_function_array_return_widens_elements() {
    assert_comb_loop(
        "selecting one unpacked function result element does not read its siblings",
        r#"
        module Top (
            o: output logic,
        ) {
            type Pair = logic [2];
            function identity (x: input Pair) -> Pair {
                return x;
            }
            var source  : logic [2];
            var returned: logic [2];
            assign returned = identity(source);
            assign source[0] = returned[1];
            assign source[1] = 0;
            assign o = returned[0];
        }
        "#,
        false,
    );
}

#[test]
fn function_array_return_retains_matching_element_feedback() {
    assert_comb_loop(
        "selecting an unpacked function result element retains its matching source",
        r#"
        module Top (
            o: output logic,
        ) {
            type Pair = logic [2];
            function identity (x: input Pair) -> Pair {
                return x;
            }
            var source  : logic [2];
            var returned: logic [2];
            assign returned = identity(source);
            assign source[0] = returned[0];
            assign source[1] = 0;
            assign o = returned[1];
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_false_positive_function_array_output_widens_elements() {
    assert_comb_loop(
        "an unpacked function output preserves element identity",
        r#"
        module Top (
            o: output logic,
        ) {
            type Pair = logic [2];
            function copy (
                x: input  Pair,
                y: output Pair,
            ) {
                y = x;
            }
            var source  : Pair;
            var returned: Pair;
            always_comb {
                copy(source, returned);
            }
            assign source[0] = returned[1];
            assign source[1] = 0;
            assign o = returned[0];
        }
        "#,
        false,
    );
}

#[test]
fn function_array_output_retains_matching_element_feedback() {
    assert_comb_loop(
        "an unpacked function output retains matching element feedback",
        r#"
        module Top (
            o: output logic,
        ) {
            type Pair = logic [2];
            function copy (
                x: input  Pair,
                y: output Pair,
            ) {
                y = x;
            }
            var source  : Pair;
            var returned: Pair;
            always_comb {
                copy(source, returned);
            }
            assign source[0] = returned[0];
            assign source[1] = 0;
            assign o = returned[1];
        }
        "#,
        true,
    );
}

#[test]
fn overlapping_union_members_retain_feedback() {
    assert_comb_loop(
        "overlapping packed union members denote the same storage",
        r#"
        module Top (
            o: output logic,
        ) {
            union Overlay {
                bits: logic<2>,
                low : logic,
            }
            var value: Overlay;
            assign value.bits[0] = value.low;
            assign value.bits[1] = 0;
            assign o = value.low;
        }
        "#,
        true,
    );
}

#[test]
fn seeded_compound_assignment_is_feed_forward() {
    assert_comb_loop(
        "a compound assignment reads the immediately preceding definition",
        r#"
        module Top (
            i: input  logic,
            o: output logic,
        ) {
            var value: logic;
            always_comb {
                value = 0;
                value |= i;
                o = value;
            }
        }
        "#,
        false,
    );
}

#[test]
fn unseeded_compound_assignment_retains_self_feedback() {
    assert_comb_loop(
        "a compound assignment explicitly reads its old destination",
        r#"
        module Top (
            i: input  logic,
            o: output logic,
        ) {
            always_comb {
                o |= i;
            }
        }
        "#,
        true,
    );
}

#[test]
fn switch_statement_arms_are_path_exclusive() {
    assert_comb_loop(
        "opposing dependencies in switch arms cannot execute together",
        r#"
        module Top (
            sel: input  logic,
            o  : output logic,
        ) {
            var a: logic;
            var b: logic;
            always_comb {
                switch {
                    sel    : a = b;
                    !sel   : b = a;
                    default: {
                        a = 0;
                        b = 0;
                    }
                }
                o = a | b;
            }
        }
        "#,
        false,
    );
}

#[test]
fn comb_loop_false_positive_nested_function_array_identity_widens_elements() {
    assert_comb_loop(
        "nested unpacked-array identity calls preserve element identity",
        r#"
        module Top (
            o: output logic,
        ) {
            type Pair = logic [2];
            function identity (x: input Pair) -> Pair {
                return x;
            }
            function nested (x: input Pair) -> Pair {
                return identity(identity(x));
            }
            var source  : Pair;
            var returned: Pair;
            assign returned = nested(source);
            assign source[0] = returned[1];
            assign source[1] = 0;
            assign o = returned[0];
        }
        "#,
        false,
    );
}

#[test]
fn nested_function_array_identity_retains_matching_feedback() {
    assert_comb_loop(
        "nested unpacked-array identity calls retain matching-element feedback",
        r#"
        module Top (
            o: output logic,
        ) {
            type Pair = logic [2];
            function identity (x: input Pair) -> Pair {
                return x;
            }
            function nested (x: input Pair) -> Pair {
                return identity(identity(x));
            }
            var source  : Pair;
            var returned: Pair;
            assign returned = nested(source);
            assign source[0] = returned[0];
            assign source[1] = 0;
            assign o = returned[1];
        }
        "#,
        true,
    );
}

#[test]
fn function_array_permutation_keeps_distinct_elements_disjoint() {
    assert_comb_loop(
        "an unpacked-array function permutation preserves the source element mapping",
        r#"
        module Top (
            o: output logic,
        ) {
            type Pair = logic [2];
            function swap (x: input Pair) -> Pair {
                return '{x[1], x[0]};
            }
            var source  : Pair;
            var returned: Pair;
            assign returned = swap(source);
            assign source[0] = returned[0];
            assign source[1] = 0;
            assign o = returned[1];
        }
        "#,
        false,
    );
}

#[test]
fn function_array_permutation_retains_mapped_feedback() {
    assert_comb_loop(
        "an unpacked-array function permutation retains feedback through the mapped element",
        r#"
        module Top (
            o: output logic,
        ) {
            type Pair = logic [2];
            function swap (x: input Pair) -> Pair {
                return '{x[1], x[0]};
            }
            var source  : Pair;
            var returned: Pair;
            assign returned = swap(source);
            assign source[0] = returned[1];
            assign source[1] = 0;
            assign o = returned[0];
        }
        "#,
        true,
    );
}

#[test]
fn runtime_loop_forward_array_chain_is_not_feedback() {
    assert_comb_loop(
        "each runtime-loop iteration copies a lower element into a higher element",
        r#"
        module Top (
            n: input  logic<2>,
            i: input  logic,
            o: output logic,
        ) {
            var value: logic [4];
            always_comb {
                value = '{default: 0};
                value[0] = i;
                for index in 0..n {
                    value[index + 1] = value[index];
                }
                o = value[3];
            }
        }
        "#,
        false,
    );
}

#[test]
fn comb_loop_false_negative_runtime_loop_requires_multiple_iterations() {
    let code = r#"
        module Top (
            n: input  logic<2>,
            o: output logic,
        ) {
            var value   : logic [4];
            var feedback: logic;
            assign feedback = value[3];
            always_comb {
                value = '{default: 0};
                value[0] = feedback;
                for index in 0..n {
                    value[index + 1] = value[index];
                }
                o = feedback;
            }
        }
        "#;
    assert!(comb_loop_analysis_is_complete(code));
    assert_comb_loop(
        "runtime-loop iterations can carry a dependency from element zero to element three",
        code,
        true,
    );
}

#[test]
fn comb_loop_runtime_loop_propagates_through_an_unsplit_middle_partition() {
    assert_comb_loop(
        "a runtime loop propagates through every iteration inside a sparse middle partition",
        r#"
        module Top (
            n: input  logic<3>,
            o: output logic,
        ) {
            var value   : logic [5];
            var feedback: logic;
            assign feedback = value[4];
            always_comb {
                value = '{default: 0};
                value[0] = feedback;
                for index in 0..n {
                    value[index + 1] = value[index];
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_runtime_loop_propagates_between_unsplit_partitions() {
    assert_comb_loop(
        "runtime-loop iterations compose dependencies between sparse middle partitions",
        r#"
        module Top (
            n: input  logic<3>,
            o: output logic,
        ) {
            var a       : logic [5];
            var b       : logic [5];
            var feedback: logic;
            assign feedback = a[4];
            always_comb {
                a = '{default: 0};
                b = '{default: 0};
                a[0] = feedback;
                for index in 0..n {
                    a[index + 1] = b[index];
                    b[index + 1] = a[index];
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_runtime_loop_respects_a_dynamic_start_lower_bound() {
    assert_comb_loop(
        "runtime-loop splitting cannot execute indices below a dynamic start expression",
        r#"
        module Top (
            n: input  logic<2>,
            o: output logic,
        ) {
            var value   : logic [5];
            var feedback: logic;
            assign feedback = value[4];
            always_comb {
                value = '{default: 0};
                value[1] = feedback;
                for index in (n + 1)..4 {
                    value[index + 1] = value[index];
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn runtime_loop_with_identical_exclusive_bounds_is_empty() {
    assert_comb_loop(
        "an exclusive runtime range with identical bounds has no body path",
        r#"
        module Top (
            n: input  logic<2>,
            o: output logic,
        ) {
            var value   : logic [3];
            var feedback: logic;
            assign feedback = value[2];
            always_comb {
                value = '{default: 0};
                value[0] = feedback;
                for index in n..n {
                    value[index + 1] = value[index];
                }
                o = feedback;
            }
        }
        "#,
        false,
    );
}

#[test]
fn runtime_loop_with_two_dynamic_bounds_retains_a_feasible_feedback_path() {
    assert_comb_loop(
        "dynamic start and end cuts retain a feasible ordered iteration sequence",
        r#"
        module Top (
            start: input  logic<3>,
            stop : input  logic<3>,
            o    : output logic,
        ) {
            var value   : logic [5];
            var feedback: logic;
            assign feedback = value[4];
            always_comb {
                value = '{default: 0};
                value[1] = feedback;
                for index in start..stop {
                    value[index + 1] = value[index];
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_runtime_reverse_loop_requires_multiple_iterations() {
    assert_comb_loop(
        "a descending runtime loop carries a dependency from the high element to the low element",
        r#"
        module Top (
            n: input  logic<2>,
            o: output logic,
        ) {
            var value   : logic [4];
            var feedback: logic;
            assign feedback = value[0];
            always_comb {
                value = '{default: 0};
                value[3] = feedback;
                for index in rev 0..n {
                    value[index] = value[index + 1];
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_multidimensional_runtime_loop_uses_flattened_stride() {
    assert_comb_loop(
        "a runtime loop carries dependencies between rows of a multidimensional array",
        r#"
        module Top (
            n: input  logic<2>,
            o: output logic,
        ) {
            var value   : logic [4, 2];
            var feedback: logic;
            assign feedback = value[3][0];
            always_comb {
                value = '{default: 0};
                value[0][0] = feedback;
                for index in 0..n {
                    value[index + 1][0] = value[index][0];
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_runtime_loop_carries_dependencies_across_body_statements() {
    assert_comb_loop(
        "runtime-loop iterations compose dependencies across ordered body statements",
        r#"
        module Top (
            n: input  logic<2>,
            o: output logic,
        ) {
            var a       : logic [3];
            var b       : logic [3];
            var feedback: logic;
            assign feedback = a[2];
            always_comb {
                a = '{default: 0};
                b = '{default: 0};
                a[0] = feedback;
                for index in 0..n {
                    a[index + 1] = b[index];
                    b[index + 1] = a[index];
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_runtime_loop_with_modulo_index_may_wrap_to_its_seed() {
    assert_comb_loop(
        "a runtime loop with a modulo index may carry feedback around the array",
        r#"
        module Top (
            n: input  logic<3>,
            o: output logic,
        ) {
            var value   : logic [4];
            var feedback: logic;
            assign feedback = value[0];
            always_comb {
                value = '{default: 0};
                value[1] = feedback;
                for index in 1..n {
                    value[(index + 1) % 4] = value[index % 4];
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_runtime_loop_does_not_sample_modulo_access_at_affine_boundaries_only() {
    assert_comb_loop(
        "an unrelated affine access cannot hide intermediate modulo iterations",
        r#"
        module Top (
            n: input  logic<4>,
            o: output logic,
        ) {
            var value   : logic [4];
            var scratch : logic [8];
            var feedback: logic;
            assign feedback = value[0];
            always_comb {
                value = '{default: 0};
                scratch = '{default: 0};
                value[1] = feedback;
                for index in 1..n {
                    value[(index + 1) % 4] = value[index % 4];
                    scratch[index] = 1'b1;
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_runtime_iterator_and_other_dynamic_index_share_an_lsp() {
    assert_comb_loop(
        "the loop iterator and another dynamic index may address the same LSP region",
        r#"
        module Top (
            n: input  logic<2>,
            j: input  logic<2>,
            o: output logic,
        ) {
            var value   : logic [4];
            var feedback: logic;
            assign feedback = value[2];
            always_comb {
                value = '{default: 0};
                value[0] = feedback;
                for i in 0..n {
                    value[j] = value[i];
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_dynamic_non_additive_step_retains_possible_feedback() {
    // This is not an intentional false positive: when (n | 1) is below ten,
    // the loop executes and assigns b from a, so the feedback is realizable.
    let code = r#"
        module Top (
            n: input  logic<4>,
            o: output logic,
        ) {
            var a: logic;
            var b: logic;
            assign a = b;
            always_comb {
                b = 0;
                for _index in (n | 1)..10 step *= 2 {
                    b = a;
                }
                o = b;
            }
        }
    "#;
    assert!(comb_loop_analysis_is_complete(code));
    assert_comb_loop(
        "a non-additive runtime step retains its realizable body feedback",
        code,
        true,
    );
}

#[test]
fn comb_loop_runtime_iterator_conditions_retain_reachable_iterations() {
    assert_comb_loop(
        "runtime iterator conditions retain a feedback path across iterations",
        r#"
        module Top (
            n: input  logic<3>,
            o: output logic,
        ) {
            var value   : logic [3];
            var feedback: logic;
            assign feedback = value[2];
            always_comb {
                value = '{default: 0};
                value[0] = feedback;
                for index in 0..n {
                    if index == 0 {
                        value[1] = value[0];
                    }
                    if index == 1 {
                        value[2] = value[1];
                    }
                }
                o = feedback;
            }
        }
        "#,
        true,
    );
}

#[test]
fn constant_dead_function_in_destination_index_does_not_create_feedback() {
    assert_comb_loop(
        "a function in a constant-dead destination index operand is not evaluated",
        r#"
        module Top (o: output logic) {
            var a: logic;
            var b: logic;
            var value: logic [2];
            function write_a (x: input logic) -> logic {
                a = x;
                return 0;
            }
            always_comb {
                a = 0;
                value[1'b0 && write_a(b)] = 0;
                b = a;
                o = b | value[0];
            }
        }
        "#,
        false,
    );
}

#[test]
fn constant_dead_function_in_source_index_does_not_kill_feedback() {
    assert_comb_loop(
        "a function in a constant-dead source index operand cannot overwrite feedback",
        r#"
        module Top (o: output logic) {
            var a: logic;
            var b: logic;
            var dummy: logic;
            var value: logic [2];
            function clear_a () -> logic {
                a = 0;
                return 0;
            }
            always_comb {
                a = b;
                value = '{default: 0};
                dummy = value[1'b0 && clear_a()];
                b = a;
                o = b | dummy;
            }
        }
        "#,
        true,
    );
}

#[test]
fn zero_offset_cycle_is_not_hidden_by_parallel_shifted_paths() {
    assert_comb_loop(
        "parallel shifted dependencies cannot hide the same-bit cycle",
        r#"
        module Top (o: output logic<3>) {
            var a: logic<3>;
            var b: logic<3>;
            var c: logic<3>;
            var d: logic<3>;
            assign a = b | (b << 1) | (b << 2);
            assign d = a | (a << 1) | (a << 2);
            assign c = d | (d << 1) | (d << 2);
            assign b = c | (c << 1) | (c << 2);
            assign o = a;
        }
        "#,
        true,
    );
}

#[test]
fn comb_loop_procedural_assignments_clip_before_reduction() {
    // A whole-value read must see the stored intermediate, including bits
    // discarded by a shift or a narrower assignment. Exercise both discarded
    // and surviving feedback bits, also through a function summary.
    for (width, expression, feedback, expected_loop) in [
        (4, "a << 1", "{z, 3'b0}", false),
        (4, "a << 1", "{3'b0, z}", true),
        (4, "a >> 1", "{3'b0, z}", false),
        (4, "a >> 1", "{z, 3'b0}", true),
        (2, "a", "{z, 3'b0}", false),
        (2, "a", "{3'b0, z}", true),
    ] {
        for through_function in [false, true] {
            let procedure = if through_function {
                format!(
                    "function reduce(a: input logic<4>) -> logic {{
                        var t: logic<{width}>;
                        t = {expression};
                        return |t;
                    }}
                    assign z = reduce(a);"
                )
            } else {
                format!(
                    "var t: logic<{width}>;
                    always_comb {{ t = {expression}; z = |t; }}"
                )
            };
            let code = format!(
                "module Top (o: output logic) {{
                    var a: logic<4>;
                    var z: logic;
                    {procedure}
                    assign a = {feedback};
                    assign o = z;
                }}"
            );
            let errors = analyze(&code);
            assert!(
                errors
                    .iter()
                    .all(|error| matches!(error, AnalyzerError::CombinationalLoop { .. })),
                "{code}\n{errors:#?}"
            );
            assert_eq!(!errors.is_empty(), expected_loop, "{code}\n{errors:#?}");
            assert!(comb_loop_analysis_is_complete(&code), "{code}");
        }
    }
}

#[test]
fn comb_loop_positional_ring_keeps_budget_for_shifted_edges() {
    for count in [100, 500, 1_000] {
        let mut code = "module Top (o: output logic<2>) {\n".to_string();
        for index in 0..count {
            code.push_str(&format!("var v{index}: logic<2>;\n"));
        }
        code.push_str(&format!(
            "assign v0 = v{} >> 1;\nassign v1 = v0 << 1;\n",
            count - 1
        ));
        for index in 2..count {
            code.push_str(&format!("assign v{index} = v{};\n", index - 1));
        }
        code.push_str("assign o = v0;\n}");

        // The identity edges alone form a DAG, but v0[0] feeds v1[1] and
        // returns through the right shift after traversing the entire ring.
        crate::comb_loop_detect::reset_cycle_search_work();
        assert_comb_loop(
            "a positional ring retains its shifted feedback",
            &code,
            true,
        );
        let work = crate::comb_loop_detect::cycle_search_work();
        assert!(
            work < count * 100,
            "identity-only paths must not consume quadratic work: count={count}, work={work}"
        );
        assert!(comb_loop_analysis_is_complete(&code));
    }
}

#[test]
fn comb_loop_independent_diamonds_merge_without_enumerating_branch_choices() {
    const COUNT: usize = 32;
    let transfers = (0..COUNT)
        .map(|i| format!("assign v[{}] = if flags[{i}] ? v[{i}] : ~v[{i}];", i + 1))
        .collect::<Vec<_>>()
        .join("\n");
    let code = format!(
        r#"
        module Top (gate: input logic, flags: input logic<{COUNT}>, o: output logic) {{
            var a: logic;
            var b: logic;
            var v: logic[{}];
            always_comb {{
                if gate {{ a = b; o = 0; }} else {{ a = 0; o = v[{COUNT}]; }}
            }}
            assign v[0] = a;
            {transfers}
            assign b = o;
        }}
    "#,
        COUNT + 1
    );
    crate::comb_loop_detect::reset_cycle_search_work();
    assert!(analyze(&code).is_empty());
    assert!(
        crate::comb_loop_detect::cycle_search_work() < 750_000,
        "independent guards must meet before traversing the shared suffix: {}",
        crate::comb_loop_detect::cycle_search_work()
    );
    assert!(
        comb_loop_analysis_is_complete(&code),
        "a budget cutoff is not a proof of absence"
    );
}

#[test]
fn comb_loop_many_opposing_shifts_find_a_witness_before_exhausting_search() {
    for count in [32, 36, 64] {
        let terms = (1..=count)
            .flat_map(|n| [format!("(o << {n})"), format!("(o >> {n})")])
            .collect::<Vec<_>>()
            .join(" | ");
        let code = format!("module Top (o: output logic<128>) {{ assign o = {terms}; }}");
        crate::comb_loop_detect::reset_cycle_search_work();
        assert_comb_loop(
            "opposing shifts already contain a feasible cycle",
            &code,
            true,
        );
        assert!(
            crate::comb_loop_detect::cycle_search_work() < 100_000,
            "a cheap witness must not pay for unvisited triples: {}",
            crate::comb_loop_detect::cycle_search_work()
        );
        assert!(comb_loop_analysis_is_complete(&code));
    }
}

#[test]
fn comb_loop_many_exclusive_opposing_shifts_remain_acyclic_and_complete() {
    const COUNT: usize = 64;
    let shifts = |op| {
        (1..=COUNT)
            .map(|n| format!("(o {op} {n})"))
            .collect::<Vec<_>>()
            .join(" | ")
    };
    let code = format!(
        r#"
        module Top (select: input logic, o: output logic<128>) {{
            always_comb {{
                if select {{ o = {}; }} else {{ o = {}; }}
            }}
        }}
        "#,
        shifts("<<"),
        shifts(">>"),
    );
    assert_comb_loop(
        "exclusive shifts cannot form an opposing pair",
        &code,
        false,
    );
    assert!(comb_loop_analysis_is_complete(&code));
}