zhc_ir 0.7.0

Graph-based intermediate representation framework with dialect support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
use crate::testlang::{TestInstructionSet, TestLang};
use crate::{DialectInstructionSet, IR};
use zhc_utils::{assert_display_is, iter::CollectInVec, svec};

/// Tests basic IR construction with complex operation graph and validates
/// all operation properties, value relationships, and depth calculations
#[test]
fn test_construction() {
    let mut store: IR<TestLang> = IR::empty();

    let (lhs_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (rhs_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (join_id, v2) = store.add_op(TestInstructionSet::Add, svec![v0[0], v1[0]]);
    let (split_id, v3) = store.add_op(TestInstructionSet::DivRem, svec![v2[0], v0[0]]);
    let (ulhs_id, v4) = store.add_op(TestInstructionSet::Inc, svec![v3[0]]);
    let (urhs_id, v5) = store.add_op(TestInstructionSet::Inc, svec![v3[1]]);
    let (final_add_id, v6) = store.add_op(TestInstructionSet::Add, svec![v4[0], v5[0]]);
    let (effect_id, _) = store.add_op(TestInstructionSet::Return, svec![v3[0]]);

    let lhs = store.get_op(lhs_id);
    let p0 = store.get_val(v0[0]);
    let rhs = store.get_op(rhs_id);
    let p1 = store.get_val(v1[0]);
    let join = store.get_op(join_id);
    let p2 = store.get_val(v2[0]);
    let split = store.get_op(split_id);
    let p3 = store.get_val(v3[0]);
    let p4 = store.get_val(v3[1]);
    let ulhs = store.get_op(ulhs_id);
    let p5 = store.get_val(v4[0]);
    let urhs = store.get_op(urhs_id);
    let p6 = store.get_val(v5[0]);
    let final_add = store.get_op(final_add_id);
    let p7 = store.get_val(v6[0]);
    let effect = store.get_op(effect_id);

    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = int_input<pos: 1>();
            %2 = add(%0, %1);
            %3, %4 = div_rem(%2, %0);
            %5 = inc(%3);
            %6 = inc(%4);
            %7 = add(%5, %6);
            return(%3);
        "#
    );

    assert_eq!(store.n_ops(), 8);
    assert_eq!(store.n_vals(), 8);
    assert!(lhs.is_active());
    assert_eq!(lhs.get_depth(), 1);
    assert_eq!(lhs.get_args_iter().covec(), []);
    assert_eq!(lhs.get_returns_iter().covec(), [p0.clone()]);

    assert!(rhs.is_active());
    assert_eq!(rhs.get_depth(), 1);
    assert_eq!(rhs.get_args_iter().covec(), []);
    assert_eq!(rhs.get_returns_iter().covec(), [p1.clone()]);

    assert!(p0.is_active());
    assert_eq!(p0.get_origin().opref, lhs);
    assert_eq!(p0.get_users_iter().covec(), [join.clone(), split.clone()]);

    assert!(p1.is_active());
    assert_eq!(p1.get_origin().opref, rhs);
    assert_eq!(p1.get_users_iter().covec(), [join.clone()]);

    assert!(join.is_active());
    assert_eq!(join.get_depth(), 2);
    assert_eq!(join.get_args_iter().covec(), [p0.clone(), p1.clone()]);
    assert_eq!(join.get_returns_iter().covec(), [p2.clone()]);

    assert!(p2.is_active());
    assert_eq!(p2.get_origin().opref, join);
    assert_eq!(p2.get_users_iter().covec(), [split.clone()]);

    assert!(split.is_active());
    assert_eq!(split.get_depth(), 3);
    assert_eq!(split.get_args_iter().covec(), [p2.clone(), p0.clone()]);
    assert_eq!(split.get_returns_iter().covec(), [p3.clone(), p4.clone()]);

    assert!(p3.is_active());
    assert_eq!(p3.get_origin().opref, split);
    assert_eq!(p3.get_users_iter().covec(), [ulhs.clone(), effect.clone()]);

    assert!(p4.is_active());
    assert_eq!(p4.get_origin().opref, split);
    assert_eq!(p4.get_users_iter().covec(), [urhs.clone()]);

    assert!(ulhs.is_active());
    assert_eq!(ulhs.get_depth(), 4);
    assert_eq!(ulhs.get_args_iter().covec(), [p3.clone()]);
    assert_eq!(ulhs.get_returns_iter().covec(), [p5.clone()]);

    assert!(p5.is_active());
    assert_eq!(p5.get_origin().opref, ulhs);
    assert_eq!(p5.get_users_iter().covec(), [final_add.clone()]);

    assert!(urhs.is_active());
    assert_eq!(urhs.get_depth(), 4);
    assert_eq!(urhs.get_args_iter().covec(), [p4.clone()]);
    assert_eq!(urhs.get_returns_iter().covec(), [p6.clone()]);

    assert!(p6.is_active());
    assert_eq!(p6.get_origin().opref, urhs);
    assert_eq!(p6.get_users_iter().covec(), [final_add.clone()]);

    assert!(final_add.is_active());
    assert_eq!(final_add.get_depth(), 5);
    assert_eq!(final_add.get_args_iter().covec(), [p5.clone(), p6.clone()]);
    assert_eq!(final_add.get_returns_iter().covec(), [p7.clone()]);

    assert!(p7.is_active());
    assert_eq!(p7.get_origin().opref, final_add);
    assert_eq!(p7.get_users_iter().covec(), []);

    assert!(effect.is_active());
    assert_eq!(effect.get_depth(), 4);
    assert_eq!(effect.get_args_iter().covec(), [p3.clone()]);
    assert_eq!(effect.get_returns_iter().covec(), []);
}

/// Tests that an operation reaches itself (reflexive property)
#[test]
fn test_reaches_self() {
    let mut store: IR<TestLang> = IR::empty();
    let (lhs_id, _) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let lhs = store.get_op(lhs_id);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
        "#
    );
    assert!(lhs.reaches(&lhs));
}

/// Tests basic reachability between two operations in a dependency chain
#[test]
fn test_reaches_base() {
    let mut store: IR<TestLang> = IR::empty();
    let (lhs_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (ulhs_id, _) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    let lhs = store.get_op(lhs_id);
    let ulhs = store.get_op(ulhs_id);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = inc(%0);
        "#
    );
    assert!(lhs.reaches(&ulhs));
}

/// Tests reachability through a longer chain of operations
#[test]
fn test_reaches_chain() {
    let mut store: IR<TestLang> = IR::empty();
    let (lhs_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, v1) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    let (_, v2) = store.add_op(TestInstructionSet::Inc, svec![v1[0]]);
    let (_, v3) = store.add_op(TestInstructionSet::Inc, svec![v2[0]]);
    let (_, v4) = store.add_op(TestInstructionSet::Inc, svec![v3[0]]);
    let (ulhs_id, _) = store.add_op(TestInstructionSet::Inc, svec![v4[0]]);
    let lhs = store.get_op(lhs_id);
    let ulhs = store.get_op(ulhs_id);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = inc(%0);
            %2 = inc(%1);
            %3 = inc(%2);
            %4 = inc(%3);
            %5 = inc(%4);
        "#
    );
    assert!(lhs.reaches(&ulhs));
}

/// Tests that independent operations don't reach each other
#[test]
fn test_reaches_happy_path() {
    let mut store: IR<TestLang> = IR::empty();
    let (lhs_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (rhs_id, _) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let _ = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    let lhs = store.get_op(lhs_id);
    let rhs = store.get_op(rhs_id);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = int_input<pos: 1>();
            %2 = inc(%0);
        "#
    );
    assert!(!lhs.reaches(&rhs));
}

/// Tests get_reaching_iter returns all operations that can reach the current operation
#[test]
fn test_get_reaching_iter_simple() {
    let mut store: IR<TestLang> = IR::empty();
    let (inp1_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inp2_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (add_id, v2) = store.add_op(TestInstructionSet::Add, svec![v0[0], v1[0]]);
    let (inc_id, _) = store.add_op(TestInstructionSet::Inc, svec![v2[0]]);

    let inc_op = store.get_op(inc_id);
    let reaching_ops: Vec<_> = inc_op.get_reaching_iter().map(|op| op.get_id()).collect();

    // inc operation should reach all its predecessors: add, inp1, inp2
    assert_eq!(reaching_ops.len(), 3);
    assert!(reaching_ops.contains(&inp1_id));
    assert!(reaching_ops.contains(&inp2_id));
    assert!(reaching_ops.contains(&add_id));
}

/// Tests get_reaching_iter with complex dependency graph
#[test]
fn test_get_reaching_iter_complex() {
    let mut store: IR<TestLang> = IR::empty();
    let (inp_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inc1_id, v1) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    let (inc2_id, v2) = store.add_op(TestInstructionSet::Inc, svec![v1[0]]);
    let (inc3_id, v3) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]); // Alternative branch
    let (add_id, _) = store.add_op(TestInstructionSet::Add, svec![v2[0], v3[0]]);

    let add_op = store.get_op(add_id);
    let reaching_ops: Vec<_> = add_op.get_reaching_iter().map(|op| op.get_id()).collect();

    // add should reach inp, inc1, inc2, inc3
    assert_eq!(reaching_ops.len(), 4);
    assert!(reaching_ops.contains(&inp_id));
    assert!(reaching_ops.contains(&inc1_id));
    assert!(reaching_ops.contains(&inc2_id));
    assert!(reaching_ops.contains(&inc3_id));
}

/// Tests get_reaching_iter with diamond pattern
#[test]
fn test_get_reaching_iter_diamond() {
    let mut store: IR<TestLang> = IR::empty();
    let (a_id, a_vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]); // A
    let (b_id, b_vals) = store.add_op(TestInstructionSet::Inc, svec![a_vals[0]]); // B depends on A
    let (c_id, c_vals) = store.add_op(TestInstructionSet::Inc, svec![a_vals[0]]); // C depends on A
    let (d_id, _) = store.add_op(TestInstructionSet::Add, svec![b_vals[0], c_vals[0]]); // D depends on B,C

    let d_op = store.get_op(d_id);
    let reaching_ops: Vec<_> = d_op.get_reaching_iter().map(|op| op.get_id()).collect();

    // D should reach A, B, C but not include itself
    assert_eq!(reaching_ops.len(), 3);
    assert!(reaching_ops.contains(&a_id));
    assert!(reaching_ops.contains(&b_id));
    assert!(reaching_ops.contains(&c_id));
    assert!(!reaching_ops.contains(&d_id));
}

/// Tests get_reaching_iter on input operation (no predecessors)
#[test]
fn test_get_reaching_iter_input() {
    let mut store: IR<TestLang> = IR::empty();
    let (inp_id, _) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);

    let inp_op = store.get_op(inp_id);
    let reaching_ops: Vec<_> = inp_op.get_reaching_iter().map(|op| op.get_id()).collect();

    // Input operation has no predecessors
    assert_eq!(reaching_ops.len(), 0);
}

/// Tests get_reaching_iter with two completely disconnected subgraphs
#[test]
fn test_get_reaching_iter_disconnected_subgraphs() {
    let mut store: IR<TestLang> = IR::empty();

    // Subgraph 1: inp1 → inc1 → inc2
    let (inp1_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inc1_id, v1) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    let (inc2_id, _v2) = store.add_op(TestInstructionSet::Inc, svec![v1[0]]);

    // Subgraph 2: inp2 → inc3 → inc4
    let (inp2_id, v3) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (inc3_id, v4) = store.add_op(TestInstructionSet::Inc, svec![v3[0]]);
    let (inc4_id, _v5) = store.add_op(TestInstructionSet::Inc, svec![v4[0]]);

    // Test that subgraph 1 operations only reach within their own subgraph
    let inc2_op = store.get_op(inc2_id);
    let inc2_reaching: Vec<_> = inc2_op.get_reaching_iter().map(|op| op.get_id()).collect();

    assert_eq!(inc2_reaching.len(), 2); // Should only reach inp1 and inc1
    assert!(inc2_reaching.contains(&inp1_id));
    assert!(inc2_reaching.contains(&inc1_id));
    assert!(!inc2_reaching.contains(&inp2_id));
    assert!(!inc2_reaching.contains(&inc3_id));
    assert!(!inc2_reaching.contains(&inc4_id));

    // Test that subgraph 2 operations only reach within their own subgraph
    let inc4_op = store.get_op(inc4_id);
    let inc4_reaching: Vec<_> = inc4_op.get_reaching_iter().map(|op| op.get_id()).collect();

    assert_eq!(inc4_reaching.len(), 2); // Should only reach inp2 and inc3
    assert!(inc4_reaching.contains(&inp2_id));
    assert!(inc4_reaching.contains(&inc3_id));
    assert!(!inc4_reaching.contains(&inp1_id));
    assert!(!inc4_reaching.contains(&inc1_id));
    assert!(!inc4_reaching.contains(&inc2_id));

    // Test that operations from different subgraphs don't reach each other
    assert!(!inc2_op.reaches(&inc4_op));
    assert!(!inc4_op.reaches(&inc2_op));
    assert!(!store.get_op(inc1_id).reaches(&store.get_op(inc3_id)));
    assert!(!store.get_op(inc3_id).reaches(&store.get_op(inc1_id)));
}

/// Tests get_reached_iter returns all operations that can be reached from the current operation
#[test]
fn test_get_reached_iter_simple() {
    let mut store: IR<TestLang> = IR::empty();
    let (inp1_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inp2_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (add_id, v2) = store.add_op(TestInstructionSet::Add, svec![v0[0], v1[0]]);
    let (inc_id, _) = store.add_op(TestInstructionSet::Inc, svec![v2[0]]);

    let add_op = store.get_op(add_id);
    let reached_ops: Vec<_> = add_op.get_reached_iter().map(|op| op.get_id()).collect();

    // add operation should reach its successors: inc
    assert_eq!(reached_ops.len(), 1);
    assert!(reached_ops.contains(&inc_id));
    assert!(!reached_ops.contains(&inp1_id));
    assert!(!reached_ops.contains(&inp2_id));
    assert!(!reached_ops.contains(&add_id));
}

/// Tests get_reached_iter with complex dependency graph
#[test]
fn test_get_reached_iter_complex() {
    let mut store: IR<TestLang> = IR::empty();
    let (inp_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inc1_id, v1) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    let (inc2_id, v2) = store.add_op(TestInstructionSet::Inc, svec![v1[0]]);
    let (inc3_id, v3) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]); // Alternative branch
    let (add_id, _) = store.add_op(TestInstructionSet::Add, svec![v2[0], v3[0]]);

    let inp_op = store.get_op(inp_id);
    let reached_ops: Vec<_> = inp_op.get_reached_iter().map(|op| op.get_id()).collect();

    // inp should reach inc1, inc2, inc3, add
    assert_eq!(reached_ops.len(), 4);
    assert!(reached_ops.contains(&inc1_id));
    assert!(reached_ops.contains(&inc2_id));
    assert!(reached_ops.contains(&inc3_id));
    assert!(reached_ops.contains(&add_id));
}

/// Tests get_reached_iter with diamond pattern
#[test]
fn test_get_reached_iter_diamond() {
    let mut store: IR<TestLang> = IR::empty();
    let (a_id, a_vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]); // A
    let (b_id, b_vals) = store.add_op(TestInstructionSet::Inc, svec![a_vals[0]]); // B depends on A
    let (c_id, c_vals) = store.add_op(TestInstructionSet::Inc, svec![a_vals[0]]); // C depends on A
    let (d_id, _) = store.add_op(TestInstructionSet::Add, svec![b_vals[0], c_vals[0]]); // D depends on B,C

    let a_op = store.get_op(a_id);
    let reached_ops: Vec<_> = a_op.get_reached_iter().map(|op| op.get_id()).collect();

    // A should reach B, C, D but not include itself
    assert_eq!(reached_ops.len(), 3);
    assert!(reached_ops.contains(&b_id));
    assert!(reached_ops.contains(&c_id));
    assert!(reached_ops.contains(&d_id));
    assert!(!reached_ops.contains(&a_id));
}

/// Tests get_reached_iter on operation with no successors (effect)
#[test]
fn test_get_reached_iter_effect() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (ret_id, _) = store.add_op(TestInstructionSet::Return, vals);

    let ret_op = store.get_op(ret_id);
    let reached_ops: Vec<_> = ret_op.get_reached_iter().map(|op| op.get_id()).collect();

    // Return operation has no successors
    assert_eq!(reached_ops.len(), 0);
}

/// Tests get_reached_iter with two completely disconnected subgraphs
#[test]
fn test_get_reached_iter_disconnected_subgraphs() {
    let mut store: IR<TestLang> = IR::empty();

    // Subgraph 1: inp1 → inc1 → inc2
    let (inp1_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inc1_id, v1) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    let (inc2_id, _v2) = store.add_op(TestInstructionSet::Inc, svec![v1[0]]);

    // Subgraph 2: inp2 → inc3 → inc4
    let (inp2_id, v3) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (inc3_id, v4) = store.add_op(TestInstructionSet::Inc, svec![v3[0]]);
    let (inc4_id, _v5) = store.add_op(TestInstructionSet::Inc, svec![v4[0]]);

    // Test that subgraph 1 operations only reach within their own subgraph
    let inp1_op = store.get_op(inp1_id);
    let inp1_reached: Vec<_> = inp1_op.get_reached_iter().map(|op| op.get_id()).collect();

    assert_eq!(inp1_reached.len(), 2); // Should only reach inc1 and inc2
    assert!(inp1_reached.contains(&inc1_id));
    assert!(inp1_reached.contains(&inc2_id));
    assert!(!inp1_reached.contains(&inp2_id));
    assert!(!inp1_reached.contains(&inc3_id));
    assert!(!inp1_reached.contains(&inc4_id));

    // Test that subgraph 2 operations only reach within their own subgraph
    let inp2_op = store.get_op(inp2_id);
    let inp2_reached: Vec<_> = inp2_op.get_reached_iter().map(|op| op.get_id()).collect();

    assert_eq!(inp2_reached.len(), 2); // Should only reach inc3 and inc4
    assert!(inp2_reached.contains(&inc3_id));
    assert!(inp2_reached.contains(&inc4_id));
    assert!(!inp2_reached.contains(&inp1_id));
    assert!(!inp2_reached.contains(&inc1_id));
    assert!(!inp2_reached.contains(&inc2_id));

    // Test that operations from different subgraphs don't reach each other
    assert!(!inp1_op.reaches(&store.get_op(inc3_id)));
    assert!(!inp2_op.reaches(&store.get_op(inc1_id)));
    assert!(!store.get_op(inc1_id).reaches(&store.get_op(inc3_id)));
    assert!(!store.get_op(inc3_id).reaches(&store.get_op(inc1_id)));
}

/// Tests get_reached_iter with branching pattern (one-to-many)
#[test]
fn test_get_reached_iter_branching() {
    let mut store: IR<TestLang> = IR::empty();
    let (inp_id, vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (ret1_id, _) = store.add_op(TestInstructionSet::Return, vals.clone());
    let (inc_id, inc_vals) = store.add_op(TestInstructionSet::Inc, vals);
    let (ret2_id, _) = store.add_op(TestInstructionSet::Return, inc_vals);

    let inp_op = store.get_op(inp_id);
    let reached_ops: Vec<_> = inp_op.get_reached_iter().map(|op| op.get_id()).collect();

    // inp should reach all three operations that use its output
    assert_eq!(reached_ops.len(), 3);
    assert!(reached_ops.contains(&ret1_id));
    assert!(reached_ops.contains(&inc_id));
    assert!(reached_ops.contains(&ret2_id));
}

/// Tests get_reached_iter with convergent pattern (many-to-one)
#[test]
fn test_get_reached_iter_convergent() {
    let mut store: IR<TestLang> = IR::empty();
    let (inp1_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inp2_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (add_id, _) = store.add_op(TestInstructionSet::Add, svec![v0[0], v1[0]]);

    // Both inputs should reach the same add operation
    let inp1_op = store.get_op(inp1_id);
    let inp1_reached: Vec<_> = inp1_op.get_reached_iter().map(|op| op.get_id()).collect();

    let inp2_op = store.get_op(inp2_id);
    let inp2_reached: Vec<_> = inp2_op.get_reached_iter().map(|op| op.get_id()).collect();

    // Both should reach the add operation
    assert_eq!(inp1_reached.len(), 1);
    assert_eq!(inp2_reached.len(), 1);
    assert!(inp1_reached.contains(&add_id));
    assert!(inp2_reached.contains(&add_id));
}

/// Tests that attempting to delete an operation still in use panics
#[test]
#[should_panic]
fn test_delete_op_in_use() {
    let mut store: IR<TestLang> = IR::empty();
    let (lhs_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, v1) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let _ = store.add_op(TestInstructionSet::Add, svec![v0[0], v1[0]]);
    store.delete_op(lhs_id);
}

/// Tests successful deletion of operations and verification of inactive state
#[test]
fn test_delete_op() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (rhs_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (join_id, v2) = store.add_op(TestInstructionSet::Add, svec![v0[0], v1[0]]);
    store.delete_op(join_id);
    store.delete_op(rhs_id);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
        "#
    );
    assert!(store.raw_get_val(v2[0]).is_inactive());
    assert!(store.raw_get_val(v1[0]).is_inactive());
    assert!(store.raw_get_op(join_id).is_inactive());
    assert!(store.raw_get_op(rhs_id).is_inactive());
}

/// Tests that replacing a value with one that would create a cycle panics
#[test]
#[should_panic(expected = "Tried to replace a value with one it reaches.")]
fn test_replace_val_use_wrong() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, v1) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = inc(%0);
        "#
    );
    store.replace_val_use(v0[0], v1[0]);
}

/// Tests that replacing a value with one that would create a cycle panics (longer chain)
#[test]
#[should_panic(expected = "Tried to replace a value with one it reaches.")]
fn test_replace_val_use_wrong_longer() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, v1) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = inc(%0);
        "#
    );
    store.replace_val_use(v0[0], v1[0]);
}

/// Tests successful value use replacement and user list updates
#[test]
fn test_replace_val_use() {
    let mut store: IR<TestLang> = IR::empty();
    let (_inp1_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_inp2_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (inc_id, _v2) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = int_input<pos: 1>();
            %2 = inc(%0);
        "#
    );
    store.replace_val_use(v0[0], v1[0]);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = int_input<pos: 1>();
            %2 = inc(%1);
        "#
    );
    let inc = store.get_op(inc_id);
    let v0 = store.get_val(v0[0]);
    let v1 = store.get_val(v1[0]);
    assert_eq!(v0.get_users_iter().covec(), []);
    assert_eq!(v1.get_users_iter().covec(), [inc.clone()]);
}

/// Tests that value replacement makes operation depth shallower when appropriate
#[test]
fn test_replace_val_use_make_shallower() {
    let mut store: IR<TestLang> = IR::empty();
    let (_inp1_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_inp2_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (_, v2) = store.add_op(TestInstructionSet::Inc, svec![v1[0]]);
    let (_, v3) = store.add_op(TestInstructionSet::Inc, svec![v2[0]]);
    let (_, v4) = store.add_op(TestInstructionSet::Inc, svec![v3[0]]);
    let (last_id, _v5) = store.add_op(TestInstructionSet::Inc, svec![v4[0]]);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = int_input<pos: 1>();
            %2 = inc(%1);
            %3 = inc(%2);
            %4 = inc(%3);
            %5 = inc(%4);
        "#
    );
    let last = store.get_op(last_id);
    assert_eq!(last.get_depth(), 5);
    store.replace_val_use(v4[0], v0[0]);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = int_input<pos: 1>();
            %2 = inc(%1);
            %3 = inc(%2);
            %4 = inc(%3);
            %5 = inc(%0);
        "#
    );
    let last = store.get_op(last_id);
    assert_eq!(last.get_depth(), 2);
}

/// Tests that value replacement makes operation depth deeper when appropriate
#[test]
fn test_replace_val_use_make_deeper() {
    let mut store: IR<TestLang> = IR::empty();
    let (_inp1_id, v0) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_inp2_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (_, v2) = store.add_op(TestInstructionSet::Inc, svec![v1[0]]);
    let (_, v3) = store.add_op(TestInstructionSet::Inc, svec![v2[0]]);
    let (_, v4) = store.add_op(TestInstructionSet::Inc, svec![v0[0]]);
    let (last_id, _v5) = store.add_op(TestInstructionSet::Inc, svec![v4[0]]);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = int_input<pos: 1>();
            %2 = inc(%1);
            %3 = inc(%2);
            %4 = inc(%0);
            %5 = inc(%4);
        "#
    );
    let last = store.get_op(last_id);
    assert_eq!(last.get_depth(), 3);
    store.replace_val_use(v0[0], v3[0]);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = int_input<pos: 1>();
            %2 = inc(%1);
            %3 = inc(%2);
            %4 = inc(%3);
            %5 = inc(%4);
        "#
    );
    let last = store.get_op(last_id);
    assert_eq!(last.get_depth(), 5);
}

/// Tests that add_op panics when argument types don't match operation signature
#[test]
#[should_panic(expected = "add_op failed: Signature error: received [Bool] instead of [Int]")]
fn test_add_op_type_mismatch() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, bool_val) = store.add_op(TestInstructionSet::BoolConstant { val: true }, svec![]);
    // Try to use bool value where int is expected
    store.add_op(TestInstructionSet::Inc, svec![bool_val[0]]);
}

/// Tests that add_op return error when wrong number of arguments provided
#[test]
#[should_panic(expected = "add_op failed: Signature error: received [Int] instead of [Int, Int]")]
fn test_add_op_wrong_arg_count() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, int_vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    // Add operation expects 2 args, providing only 1
    store.add_op(TestInstructionSet::Add, svec![int_vals[0]]);
}

/// Tests that using inactive ValId in add_op panics
#[test]
#[should_panic(expected = "add_op failed: Inactive value: %0")]
fn test_add_op_with_deleted_value() {
    let mut store: IR<TestLang> = IR::empty();
    let (op_id, vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    store.delete_op(op_id);
    // Try to use deleted value
    store.add_op(TestInstructionSet::Inc, svec![vals[0]]);
}

/// Tests that accessing deleted operation via public API panics
#[test]
#[should_panic(expected = "Tried to get a dead op")]
fn test_get_deleted_op() {
    let mut store: IR<TestLang> = IR::empty();
    let (op_id, _) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    store.delete_op(op_id);
    store.get_op(op_id);
}

/// Tests that accessing deleted value via public API panics
#[test]
#[should_panic(expected = "Tried to get a dead val")]
fn test_get_deleted_val() {
    let mut store: IR<TestLang> = IR::empty();
    let (op_id, vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    store.delete_op(op_id);
    store.get_val(vals[0]);
}

/// Tests that double deletion is captured
#[test]
#[should_panic(expected = "Tried to delete an already inactive operation")]
fn test_double_deletion() {
    let mut store: IR<TestLang> = IR::empty();
    let (op_id, _) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    store.delete_op(op_id);
    store.delete_op(op_id); // Should panic on second deletion
}

/// Tests self-value replacement (should be no-op)
#[test]
fn test_replace_val_use_self() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inc_id, _) = store.add_op(TestInstructionSet::Inc, svec![vals[0]]);

    let inc_before = format!("{:?}", store.get_op(inc_id));
    store.replace_val_use(vals[0], vals[0]); // Should be no-op
    let inc_after = format!("{:?}", store.get_op(inc_id));

    assert_eq!(inc_before, inc_after);
    assert_display_is!(
        store.format(),
        r#"
            %0 = int_input<pos: 0>();
            %1 = inc(%0);
        "#
    );
}

/// Tests using same value multiple times in single operation
#[test]
fn test_same_value_multiple_args() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (add_id, _) = store.add_op(TestInstructionSet::Add, svec![vals[0], vals[0]]);

    let val = store.get_val(vals[0]);
    let add_op = store.get_op(add_id);

    // Value should appear in users list only once, but op uses it twice
    assert_eq!(val.get_users_iter().count(), 1);
    assert_eq!(
        add_op
            .get_args_iter()
            .filter(|v| v.get_id() == vals[0])
            .count(),
        2
    );
}

/// Tests diamond dependency pattern (A→B, A→C, B→D, C→D)
#[test]
fn test_diamond_dependencies() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, a_vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]); // A
    let (_b_id, b_vals) = store.add_op(TestInstructionSet::Inc, svec![a_vals[0]]); // B depends on A
    let (_c_id, c_vals) = store.add_op(TestInstructionSet::Inc, svec![a_vals[0]]); // C depends on A
    let (d_id, _) = store.add_op(TestInstructionSet::Add, svec![b_vals[0], c_vals[0]]); // D depends on B,C

    let a_val = store.get_val(a_vals[0]);
    let d_op = store.get_op(d_id);

    // A should have 2 users (B and C)
    assert_eq!(a_val.get_users_iter().count(), 2);
    // D should be at depth 3 (A:1 → B,C:2 → D:3)
    assert_eq!(d_op.get_depth(), 3);
}

/// Tests multiple independent subgraphs in same IR
#[test]
fn test_independent_subgraphs() {
    let mut store: IR<TestLang> = IR::empty();

    // Subgraph 1: input1 → inc1
    let (_, vals1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inc1_id, _) = store.add_op(TestInstructionSet::Inc, svec![vals1[0]]);

    // Subgraph 2: input2 → inc2
    let (_, vals2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (inc2_id, _) = store.add_op(TestInstructionSet::Inc, svec![vals2[0]]);

    let inc1 = store.get_op(inc1_id);
    let inc2 = store.get_op(inc2_id);

    // Neither should reach the other
    assert!(!inc1.reaches(&inc2));
    assert!(!inc2.reaches(&inc1));
}

/// Tests operations with multi-return where returns have different user patterns
#[test]
fn test_multi_return_different_users() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, inp1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, inp2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (_, div_vals) = store.add_op(TestInstructionSet::DivRem, svec![inp1[0], inp2[0]]);

    // Use first return in one op, second return in another
    let (_, _) = store.add_op(TestInstructionSet::Inc, svec![div_vals[0]]); // Use quotient
    let (_, _) = store.add_op(TestInstructionSet::Inc, svec![div_vals[1]]); // Use remainder

    let quot = store.get_val(div_vals[0]);
    let rem = store.get_val(div_vals[1]);

    assert_eq!(quot.get_users_iter().count(), 1);
    assert_eq!(rem.get_users_iter().count(), 1);
    assert_ne!(
        quot.get_users_iter().next().unwrap().get_id(),
        rem.get_users_iter().next().unwrap().get_id()
    );
}

/// Tests iteration behavior over IR with deleted elements
#[test]
fn test_iteration_with_deleted_elements() {
    let mut store: IR<TestLang> = IR::empty();
    let (op1_id, _) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2_id, _) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (op3_id, _) = store.add_op(TestInstructionSet::IntInput { pos: 2 }, svec![]);

    store.delete_op(op2_id); // Delete middle operation

    let active_ops = store.walk_ops_linear().map(|op| op.get_id()).covec();

    // Should only see active operations
    assert_eq!(active_ops.len(), 2);
    assert!(active_ops.contains(&op1_id));
    assert!(!active_ops.contains(&op2_id));
    assert!(active_ops.contains(&op3_id));

    // Raw iterator should see all operations
    let all_ops = store.raw_walk_ops_linear().map(|op| op.get_id()).covec();
    assert_eq!(all_ops.len(), 3);
}

/// Tests that user lists remain consistent after deletions
#[test]
fn test_user_consistency_after_deletion() {
    let mut store: IR<TestLang> = IR::empty();
    let (_inp_id, vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inc1_id, _) = store.add_op(TestInstructionSet::Inc, svec![vals[0]]);
    let (_inc2_id, _) = store.add_op(TestInstructionSet::Inc, svec![vals[0]]);

    // Value should have 2 users
    assert_eq!(store.get_val(vals[0]).get_users_iter().count(), 2);

    store.delete_op(inc1_id);

    // Value should still have 1 user, but the deleted op shouldn't appear in iteration
    let remaining_users: Vec<_> = store
        .get_val(vals[0])
        .raw_get_uses_iter()
        .map(|op| op.opref.get_id())
        .collect();
    assert_eq!(remaining_users.len(), 2); // Raw users list still contains deleted op

    // But active users should only show the remaining one
    let active_users: Vec<_> = store
        .get_val(vals[0])
        .get_users_iter()
        // .filter(|op| op.is_active())
        .collect();
    assert_eq!(active_users.len(), 1);
}

/// Tests replacement cascade affecting multiple dependency levels
#[test]
fn test_replacement_cascade_multiple_levels() {
    let mut store: IR<TestLang> = IR::empty();

    // Create: inp1 → inc1 → inc2 → inc3
    //         inp2 (unused initially)
    let (_, inp1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, inp2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (inc1_id, inc1_vals) = store.add_op(TestInstructionSet::Inc, svec![inp1[0]]);
    let (inc2_id, inc2_vals) = store.add_op(TestInstructionSet::Inc, svec![inc1_vals[0]]);
    let (inc3_id, _) = store.add_op(TestInstructionSet::Inc, svec![inc2_vals[0]]);

    let depths_before = [
        store.get_op(inc1_id).get_depth(),
        store.get_op(inc2_id).get_depth(),
        store.get_op(inc3_id).get_depth(),
    ];

    // Replace inc1's input with inp2, should cascade depth updates
    store.replace_val_use(inp1[0], inp2[0]);

    let depths_after = [
        store.get_op(inc1_id).get_depth(),
        store.get_op(inc2_id).get_depth(),
        store.get_op(inc3_id).get_depth(),
    ];

    // Depths should remain the same since both inputs are at depth 1
    assert_eq!(depths_before, depths_after);
}

/// Tests replacement creating deeper dependency chain
#[test]
fn test_replacement_deeper_chain() {
    let mut store: IR<TestLang> = IR::empty();

    // Create: inp1, inp2 → inc1, inp2 → inc2
    let (_, inp1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, inp2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (_, inc1_vals) = store.add_op(TestInstructionSet::Inc, svec![inp2[0]]);
    let (inc2_id, _) = store.add_op(TestInstructionSet::Inc, svec![inp1[0]]); // Initially uses inp1

    assert_eq!(store.get_op(inc2_id).get_depth(), 2);

    // Replace inp1 with inc1's output, making inc2 deeper
    store.replace_val_use(inp1[0], inc1_vals[0]);

    assert_eq!(store.get_op(inc2_id).get_depth(), 3); // Now inp2→inc1→inc2
}

/// Tests has_opid/has_valid behavior with deleted elements
#[test]
fn test_has_id_with_deleted_elements() {
    let mut store: IR<TestLang> = IR::empty();
    let (op_id, vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);

    assert!(store.has_opid(op_id));
    assert!(store.has_valid(vals[0]));

    store.delete_op(op_id);

    // Public API should return false for deleted elements
    assert!(!store.has_opid(op_id));
    assert!(!store.has_valid(vals[0]));

    // Raw API should still return true
    assert!(store.raw_has_opid(op_id));
    assert!(store.raw_has_valid(vals[0]));
}

/// Tests operations on empty IR
#[test]
fn test_empty_ir_operations() {
    let store: IR<TestLang> = IR::empty();

    assert_eq!(store.n_ops(), 0);
    assert_eq!(store.n_vals(), 0);
    assert_eq!(store.walk_ops_linear().count(), 0);

    // Check that topological order works on empty IR
    let topo_ops: Vec<_> = store.raw_walk_ops_topo().collect();
    assert_eq!(topo_ops.len(), 0);
}

/// Tests topological ordering with deleted operations
#[test]
fn test_topological_order_with_deletions() {
    let mut store: IR<TestLang> = IR::empty();
    let (op1_id, vals1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2_id, vals2) = store.add_op(TestInstructionSet::Inc, svec![vals1[0]]);
    let (op3_id, _vals3) = store.add_op(TestInstructionSet::Inc, svec![vals2[0]]);
    let (op4_id, _) = store.add_op(TestInstructionSet::Inc, svec![vals1[0]]); // Independent branch

    // Delete operations in reverse dependency order (leaf first)
    store.delete_op(op3_id); // Delete op3 first since it depends on op2
    store.delete_op(op2_id); // Now safe to delete op2

    // Topological order should include deleted operations in raw iterator
    let all_topo: Vec<_> = store.raw_topological_opwalker().collect();
    assert_eq!(all_topo.len(), 4);
    assert!(all_topo.contains(&op1_id));
    assert!(all_topo.contains(&op2_id));
    assert!(all_topo.contains(&op3_id));
    assert!(all_topo.contains(&op4_id));

    // Order should still be maintained: op1, then op2/op4 (same depth), then op3
    let op1_pos = all_topo.iter().position(|&id| id == op1_id).unwrap();
    let op2_pos = all_topo.iter().position(|&id| id == op2_id).unwrap();
    let op3_pos = all_topo.iter().position(|&id| id == op3_id).unwrap();
    let op4_pos = all_topo.iter().position(|&id| id == op4_id).unwrap();

    assert!(op1_pos < op2_pos);
    assert!(op1_pos < op4_pos);
    assert!(op2_pos < op3_pos);
}

/// Tests replacement with type validation
#[test]
#[should_panic(expected = "Tried to replace a value with one of different type")]
fn test_replace_val_different_types() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, int_vals) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, bool_vals) = store.add_op(TestInstructionSet::BoolConstant { val: true }, svec![]);

    // Try to replace int value with bool value
    store.replace_val_use(int_vals[0], bool_vals[0]);
}

/// Tests operations that become unreachable after replacement but aren't deleted
#[test]
fn test_unreachable_after_replacement() {
    let mut store: IR<TestLang> = IR::empty();
    let (_, inp1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, inp2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (inc1_id, inc1_vals) = store.add_op(TestInstructionSet::Inc, svec![inp1[0]]);
    let (_ret_id, _) = store.add_op(TestInstructionSet::Return, svec![inc1_vals[0]]);

    // Replace return's input with inp2, making inc1 unreachable
    store.replace_val_use(inc1_vals[0], inp2[0]);

    // inc1 should still exist and be active, but have no users
    assert!(store.has_opid(inc1_id));
    assert_eq!(store.get_val(inc1_vals[0]).get_users_iter().count(), 0);

    // Should be able to delete it now
    store.delete_op(inc1_id);
    assert!(!store.has_opid(inc1_id));
}

#[test]
fn test_is_effect() {
    let mut ir = IR::<TestLang>::empty();
    let (_, inp1) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, inp2) = ir.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (add_op, add) = ir.add_op(TestInstructionSet::Add, svec![inp1[0], inp2[0]]);
    let (ret_op, _) = ir.add_op(TestInstructionSet::Return, svec![add[0]]);

    assert!(ir.get_op(ret_op).is_effect());
    assert!(!ir.get_op(add_op).is_effect());
}

#[test]
fn test_signature_consistency() {
    let mut ir = IR::<TestLang>::empty();
    let (_, inp1) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_, inp2) = ir.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (add_op, _) = ir.add_op(TestInstructionSet::Add, svec![inp1[0], inp2[0]]);
    let op_ref = ir.get_op(add_op);

    // Verify cached signature matches operation signature
    assert_eq!(op_ref.signature, &op_ref.operation.get_signature());
}

#[test]
fn test_batch_delete_empty() {
    let mut ir = IR::<TestLang>::empty();
    let (op1, _) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);

    // Empty batch should be no-op
    ir.batch_delete_op(std::iter::empty());

    assert!(ir.has_opid(op1));
    assert_eq!(ir.n_ops(), 1);
}

#[test]
fn test_batch_delete_single() {
    let mut ir = IR::<TestLang>::empty();
    let (op1, vals1) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2, _) = ir.add_op(TestInstructionSet::Return, vals1);

    ir.batch_delete_op(std::iter::once(op2));

    assert!(ir.has_opid(op1));
    assert!(!ir.has_opid(op2));
    assert_eq!(ir.n_ops(), 1);
}

#[test]
fn test_batch_delete_dependency_chain() {
    let mut ir = IR::<TestLang>::empty();
    let (op1, vals1) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2, vals2) = ir.add_op(TestInstructionSet::Inc, vals1);
    let (op3, vals3) = ir.add_op(TestInstructionSet::Inc, vals2);
    let (op4, _) = ir.add_op(TestInstructionSet::Return, vals3);

    // Delete the entire chain
    ir.batch_delete_op([op2, op3, op4].into_iter());

    assert!(ir.has_opid(op1));
    assert!(!ir.has_opid(op2));
    assert!(!ir.has_opid(op3));
    assert!(!ir.has_opid(op4));
    assert_eq!(ir.n_ops(), 1);
}

#[test]
fn test_batch_delete_order_independence() {
    let mut ir = IR::<TestLang>::empty();
    let (op1, vals1) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2, vals2) = ir.add_op(TestInstructionSet::Inc, vals1);
    let (op3, _) = ir.add_op(TestInstructionSet::Return, vals2);

    // Delete in reverse dependency order - should still work
    ir.batch_delete_op([op2, op3].into_iter());

    assert!(ir.has_opid(op1));
    assert!(!ir.has_opid(op2));
    assert!(!ir.has_opid(op3));
    assert_eq!(ir.n_ops(), 1);
}

#[test]
fn test_batch_delete_diamond_pattern() {
    let mut ir = IR::<TestLang>::empty();
    let (op1, vals1) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2, vals2) = ir.add_op(TestInstructionSet::Inc, vals1.clone());
    let (op3, vals3) = ir.add_op(TestInstructionSet::Inc, vals1);
    let (op4, _) = ir.add_op(TestInstructionSet::Add, svec![vals2[0], vals3[0]]);

    // Delete the diamond (op2, op3, op4) but leave op1
    ir.batch_delete_op([op2, op3, op4].into_iter());

    assert!(ir.has_opid(op1));
    assert!(!ir.has_opid(op2));
    assert!(!ir.has_opid(op3));
    assert!(!ir.has_opid(op4));
    assert_eq!(ir.n_ops(), 1);
}

#[test]
fn test_batch_delete_independent_operations() {
    let mut ir = IR::<TestLang>::empty();
    let (op1, vals1) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2, vals2) = ir.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (op3, _) = ir.add_op(TestInstructionSet::Return, vals1);
    let (op4, _) = ir.add_op(TestInstructionSet::Return, vals2);

    // Delete two independent subgraphs
    ir.batch_delete_op([op3, op4].into_iter());

    assert!(ir.has_opid(op1));
    assert!(ir.has_opid(op2));
    assert!(!ir.has_opid(op3));
    assert!(!ir.has_opid(op4));
    assert_eq!(ir.n_ops(), 2);
}

#[test]
#[should_panic(expected = "Tried to delete an operation whose return values are still in use")]
fn test_batch_delete_with_external_users() {
    let mut ir = IR::<TestLang>::empty();
    let (_op1, vals1) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2, vals2) = ir.add_op(TestInstructionSet::Inc, vals1);
    let (op3, _) = ir.add_op(TestInstructionSet::Return, vals2.clone());
    let (_op4, _) = ir.add_op(TestInstructionSet::Return, vals2); // op4 also uses vals?2

    // Try to delete op2 and op3, but op4 still uses vals2 from op2
    ir.batch_delete_op([op2, op3].into_iter());
}

#[test]
fn test_batch_delete_partial_dependency_closure() {
    let mut ir = IR::<TestLang>::empty();
    let (op1, vals1) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2, vals2) = ir.add_op(TestInstructionSet::Inc, vals1);
    let (op3, vals3) = ir.add_op(TestInstructionSet::Inc, vals2.clone());
    let (op4, _) = ir.add_op(TestInstructionSet::Return, vals3);
    let (op5, _) = ir.add_op(TestInstructionSet::Return, vals2); // Also uses vals2

    // Can delete op3 and op4 (leaves op2 and op5 intact)
    ir.batch_delete_op([op3, op4].into_iter());

    assert!(ir.has_opid(op1));
    assert!(ir.has_opid(op2));
    assert!(!ir.has_opid(op3));
    assert!(!ir.has_opid(op4));
    assert!(ir.has_opid(op5));
    assert_eq!(ir.n_ops(), 3);
}

#[test]
#[should_panic(expected = "Tried to get a dead op")]
fn test_batch_delete_already_deleted() {
    let mut ir = IR::<TestLang>::empty();
    let (_, vals1) = ir.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2, _) = ir.add_op(TestInstructionSet::Return, vals1);

    ir.delete_op(op2); // Delete normally first

    // Try to batch delete already deleted operation
    ir.batch_delete_op(std::iter::once(op2));
}

/// Tests that ValOrigin correctly tracks the position of values within multi-return operations.
///
/// This verifies that when an operation returns multiple values, each value knows not just
/// which operation produced it, but also which return position it came from.
#[test]
fn test_val_origin_position_tracking() {
    let mut store: IR<TestLang> = IR::empty();

    // Create an operation with multiple return values
    let (_input_id, v_input) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (divrem_id, v_divrem) =
        store.add_op(TestInstructionSet::DivRem, svec![v_input[0], v_input[0]]);

    // Test that each return value has the correct position in its origin
    let quotient = store.get_val(v_divrem[0]);
    let remainder = store.get_val(v_divrem[1]);

    // Verify the origin operation is correct
    assert_eq!(quotient.get_origin().opref.get_id(), divrem_id);
    assert_eq!(remainder.get_origin().opref.get_id(), divrem_id);

    // Verify the positions are correct - quotient should be position 0, remainder position 1
    assert_eq!(quotient.get_origin().position, 0);
    assert_eq!(remainder.get_origin().position, 1);
}

/// Tests that ValUse correctly tracks the argument position where values are consumed.
///
/// This verifies that when a value is used as an argument to an operation, the value
/// knows not just which operation uses it, but also at which argument position.
#[test]
fn test_val_use_position_tracking() {
    let mut store: IR<TestLang> = IR::empty();

    // Create values to be used as arguments
    let (_input1_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_input2_id, v2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);

    // Create an operation that uses both values as arguments
    let (add_id, _v_add) = store.add_op(TestInstructionSet::Add, svec![v1[0], v2[0]]);

    // Test that values track their usage positions correctly
    let val1 = store.get_val(v1[0]);
    let val2 = store.get_val(v2[0]);

    // Each value should have exactly one user (the add operation)
    assert_eq!(val1.users.len(), 1);
    assert_eq!(val2.users.len(), 1);

    // Check the user operation ID is correct
    assert_eq!(val1.users[0].opid, add_id);
    assert_eq!(val2.users[0].opid, add_id);

    // Check the positions - v1[0] should be at position 0, v2[0] at position 1
    assert_eq!(val1.users[0].position, 0);
    assert_eq!(val2.users[0].position, 1);
}

/// Tests position tracking when the same value is used multiple times in different positions.
///
/// This verifies that when a value is used as arguments in multiple operations and positions,
/// each usage is tracked with the correct operation ID and argument position.
#[test]
fn test_position_tracking_with_multiple_uses() {
    let mut store: IR<TestLang> = IR::empty();

    // Create a value that will be used multiple times
    let (_input_id, v_input) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);

    // Use the same value in different positions of different operations
    let (add1_id, _v_add1) = store.add_op(TestInstructionSet::Add, svec![v_input[0], v_input[0]]);
    let (divrem_id, _v_divrem) =
        store.add_op(TestInstructionSet::DivRem, svec![v_input[0], v_input[0]]);

    let input_val = store.get_val(v_input[0]);

    // The input value should be used 4 times total (twice in each operation)
    assert_eq!(input_val.users.len(), 4);

    // Collect the usage information for verification
    let mut uses = input_val.users.iter().collect::<Vec<_>>();
    uses.sort_by_key(|u| (u.opid, u.position));

    // Verify the usage positions are tracked correctly
    let add1_uses: Vec<_> = uses.iter().filter(|u| u.opid == add1_id).collect();
    let divrem_uses: Vec<_> = uses.iter().filter(|u| u.opid == divrem_id).collect();

    assert_eq!(add1_uses.len(), 2);
    assert_eq!(divrem_uses.len(), 2);

    // Each operation should use the value at both position 0 and 1
    assert!(add1_uses.iter().any(|u| u.position == 0));
    assert!(add1_uses.iter().any(|u| u.position == 1));
    assert!(divrem_uses.iter().any(|u| u.position == 0));
    assert!(divrem_uses.iter().any(|u| u.position == 1));
}

/// Tests comprehensive position tracking with operations that have multiple returns and uses.
///
/// This combines multi-return operations with multi-argument operations to verify that
/// both origin positions (which return value) and use positions (which argument) are
/// correctly tracked throughout the dataflow graph.
#[test]
fn test_position_tracking_with_multi_return_multi_use() {
    let mut store: IR<TestLang> = IR::empty();

    // Create initial values
    let (_input1_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_input2_id, v2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);

    // Create an operation with multiple returns
    let (divrem_id, v_divrem) = store.add_op(TestInstructionSet::DivRem, svec![v1[0], v2[0]]);

    // Use both return values in different positions of a new operation
    let (add_id, _v_add) = store.add_op(TestInstructionSet::Add, svec![v_divrem[0], v_divrem[1]]);

    // Test origin position tracking for the multi-return operation
    let quotient = store.get_val(v_divrem[0]);
    let remainder = store.get_val(v_divrem[1]);

    assert_eq!(quotient.get_origin().opref.get_id(), divrem_id);
    assert_eq!(quotient.get_origin().position, 0);
    assert_eq!(remainder.get_origin().opref.get_id(), divrem_id);
    assert_eq!(remainder.get_origin().position, 1);

    // Test use position tracking for values used by the add operation
    assert_eq!(quotient.users.len(), 1);
    assert_eq!(remainder.users.len(), 1);

    assert_eq!(quotient.users[0].opid, add_id);
    assert_eq!(quotient.users[0].position, 0);
    assert_eq!(remainder.users[0].opid, add_id);
    assert_eq!(remainder.users[0].position, 1);
}

/// Tests that position information remains consistent after value replacement operations.
///
/// This verifies that when replace_val_use is called, the position tracking is updated
/// correctly - the new value should be tracked at the same argument position where the
/// old value was used.
#[test]
fn test_position_consistency_after_replacement() {
    let mut store: IR<TestLang> = IR::empty();

    // Create values
    let (_input1_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_input2_id, v2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (_input3_id, v3) = store.add_op(TestInstructionSet::IntInput { pos: 2 }, svec![]);

    // Create an operation using the first value
    let (add_id, _v_add) = store.add_op(TestInstructionSet::Add, svec![v1[0], v2[0]]);

    // Replace the first argument with a different value
    store.replace_val_use(v1[0], v3[0]);

    // Verify position tracking is maintained after replacement
    let val3 = store.get_val(v3[0]);
    let val1 = store.get_val(v1[0]);

    // val3 should now be used at position 0 of the add operation
    assert!(
        val3.users
            .iter()
            .any(|u| u.opid == add_id && u.position == 0)
    );

    // val1 should no longer be used by the add operation
    assert!(!val1.users.iter().any(|u| u.opid == add_id));
}

/// Tests position tracking with single-argument operations.
///
/// This verifies that position tracking works correctly for operations that take
/// only one argument, ensuring the position is tracked as 0.
#[test]
fn test_position_tracking_single_argument_operation() {
    let mut store: IR<TestLang> = IR::empty();

    // Create a value and use it in a single-argument operation
    let (_input_id, v_input) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (inc_id, _v_inc) = store.add_op(TestInstructionSet::Inc, svec![v_input[0]]);

    // Verify position tracking for single-argument operation
    let input_val = store.get_val(v_input[0]);

    assert_eq!(input_val.users.len(), 1);
    assert_eq!(input_val.users[0].opid, inc_id);
    assert_eq!(input_val.users[0].position, 0);
}

/// Tests position tracking with single-return operations.
///
/// This verifies that position tracking works correctly for operations that return
/// only one value, ensuring the return position is tracked as 0.
#[test]
fn test_position_tracking_single_return_operation() {
    let mut store: IR<TestLang> = IR::empty();

    // Create operations with single return values
    let (_input_id, v_input) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (add_id, v_add) = store.add_op(TestInstructionSet::Add, svec![v_input[0], v_input[0]]);

    // Verify position tracking for single-return operation
    let result_val = store.get_val(v_add[0]);

    assert_eq!(result_val.get_origin().opref.get_id(), add_id);
    assert_eq!(result_val.get_origin().position, 0);
}

/// Tests position tracking with zero-argument operations.
///
/// This verifies that operations with no arguments (like input operations) still
/// have their return values properly tracked with position 0.
#[test]
fn test_position_tracking_zero_argument_operation() {
    let mut store: IR<TestLang> = IR::empty();

    // Create an operation with no arguments (like IntInput)
    let (input_id, v_input) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);

    // Verify the value's origin tracking
    let input_val = store.get_val(v_input[0]);

    assert_eq!(input_val.get_origin().opref.get_id(), input_id);
    assert_eq!(input_val.get_origin().position, 0);
    assert_eq!(input_val.users.len(), 0); // No users initially
}

/// Tests that position tracking is properly maintained after operation deletion.
///
/// This verifies that when operations are deleted, the position tracking information
/// behaves correctly - raw users lists retain deleted operations, but filtered
/// iteration excludes inactive operations.
#[test]
fn test_position_tracking_after_deletion() {
    let mut store: IR<TestLang> = IR::empty();

    // Create a chain of operations
    let (_input1_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_input2_id, v2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (_add1_id, v_add1) = store.add_op(TestInstructionSet::Add, svec![v1[0], v2[0]]);
    let (add2_id, _v_add2) = store.add_op(TestInstructionSet::Add, svec![v_add1[0], v1[0]]);

    // Verify initial position tracking
    let intermediate_val = store.get_val(v_add1[0]);
    assert_eq!(intermediate_val.users.len(), 1);
    assert_eq!(intermediate_val.users[0].opid, add2_id);
    assert_eq!(intermediate_val.users[0].position, 0);

    // Delete the second add operation
    store.delete_op(add2_id);

    // Verify the intermediate value still has the deleted operation in raw users list
    let intermediate_val_after = store.get_val(v_add1[0]);
    assert_eq!(intermediate_val_after.users.len(), 1); // Raw list still contains deleted op

    // But filtered iteration should show no active users
    let active_users: Vec<_> = intermediate_val_after.get_users_iter().collect();
    assert_eq!(active_users.len(), 0);
}

/// Tests basic equality and functionality of ValOrigin and ValUse types.
///
/// This verifies that the ValOrigin and ValUse structs have proper equality
/// semantics and can be constructed and compared correctly.
#[test]
fn test_val_origin_and_val_use_equality() {
    use crate::{ValOrigin, ValUse};

    let mut store: IR<TestLang> = IR::empty();

    // Create some operations to get valid OpIds
    let (op1_id, _v1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (op2_id, _v2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);

    // Test ValOrigin equality
    let origin1 = ValOrigin {
        opid: op1_id,
        position: 0,
    };
    let origin2 = ValOrigin {
        opid: op1_id,
        position: 0,
    };
    let origin3 = ValOrigin {
        opid: op1_id,
        position: 1,
    };
    let origin4 = ValOrigin {
        opid: op2_id,
        position: 0,
    };

    assert_eq!(origin1, origin2);
    assert_ne!(origin1, origin3);
    assert_ne!(origin1, origin4);

    // Test ValUse equality
    let use1 = ValUse {
        opid: op1_id,
        position: 0,
    };
    let use2 = ValUse {
        opid: op1_id,
        position: 0,
    };
    let use3 = ValUse {
        opid: op1_id,
        position: 1,
    };
    let use4 = ValUse {
        opid: op2_id,
        position: 0,
    };

    assert_eq!(use1, use2);
    assert_ne!(use1, use3);
    assert_ne!(use1, use4);

    // Test cloning
    let origin_clone = origin1.clone();
    let use_clone = use1.clone();

    assert_eq!(origin1, origin_clone);
    assert_eq!(use1, use_clone);
}

/// Tests that ValOrigin and ValUse maintain their Debug trait implementation.
///
/// This ensures that these types can be printed for debugging purposes
/// and that their debug output contains the expected information.
#[test]
fn test_val_origin_and_val_use_debug() {
    use crate::{ValOrigin, ValUse};

    let mut store: IR<TestLang> = IR::empty();
    let (op_id, _v) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);

    let origin = ValOrigin {
        opid: op_id,
        position: 2,
    };
    let use_val = ValUse {
        opid: op_id,
        position: 3,
    };

    let origin_debug = format!("{:?}", origin);
    let use_debug = format!("{:?}", use_val);

    // Verify that debug output contains the expected fields
    assert!(origin_debug.contains("ValOrigin"));
    assert!(origin_debug.contains("opid"));
    assert!(origin_debug.contains("position"));
    assert!(origin_debug.contains("2"));

    assert!(use_debug.contains("ValUse"));
    assert!(use_debug.contains("opid"));
    assert!(use_debug.contains("position"));
    assert!(use_debug.contains("3"));
}

/// Tests integration of position tracking with IR iterator methods.
///
/// This verifies that the position tracking works correctly when accessed through
/// the standard IR iteration methods like get_args_iter() and get_users_iter().
#[test]
fn test_position_tracking_with_iterators() {
    let mut store: IR<TestLang> = IR::empty();

    // Build a more complex graph to test iterator integration
    let (_input1_id, v1) = store.add_op(TestInstructionSet::IntInput { pos: 0 }, svec![]);
    let (_input2_id, v2) = store.add_op(TestInstructionSet::IntInput { pos: 1 }, svec![]);
    let (divrem_id, v_divrem) = store.add_op(TestInstructionSet::DivRem, svec![v1[0], v2[0]]);
    let (add_id, _v_add) = store.add_op(TestInstructionSet::Add, svec![v_divrem[0], v_divrem[1]]);

    // Test that get_args_iter provides values with correct position tracking
    let add_op = store.get_op(add_id);
    let args: Vec<_> = add_op.get_args_iter().collect();

    assert_eq!(args.len(), 2);

    // First argument should be the quotient (position 0 from divrem)
    assert_eq!(args[0].get_origin().opref.get_id(), divrem_id);
    assert_eq!(args[0].get_origin().position, 0);

    // Second argument should be the remainder (position 1 from divrem)
    assert_eq!(args[1].get_origin().opref.get_id(), divrem_id);
    assert_eq!(args[1].get_origin().position, 1);

    // Test that get_returns_iter provides values with correct position tracking
    let divrem_op = store.get_op(divrem_id);
    let returns: Vec<_> = divrem_op.get_returns_iter().collect();

    assert_eq!(returns.len(), 2);
    assert_eq!(returns[0].get_origin().position, 0);
    assert_eq!(returns[1].get_origin().position, 1);

    // Test that get_users_iter reflects correct position usage
    let quotient_users: Vec<_> = returns[0].get_users_iter().collect();
    let remainder_users: Vec<_> = returns[1].get_users_iter().collect();

    assert_eq!(quotient_users.len(), 1);
    assert_eq!(remainder_users.len(), 1);
    assert_eq!(quotient_users[0].get_id(), add_id);
    assert_eq!(remainder_users[0].get_id(), add_id);

    // Test get_uses_iter to verify position information
    let quotient_uses: Vec<_> = returns[0].get_uses_iter().collect();
    let remainder_uses: Vec<_> = returns[1].get_uses_iter().collect();

    assert_eq!(quotient_uses.len(), 1);
    assert_eq!(remainder_uses.len(), 1);

    // Verify position tracking in the use references
    assert_eq!(quotient_uses[0].opref.get_id(), add_id);
    assert_eq!(quotient_uses[0].position, 0);

    assert_eq!(remainder_uses[0].opref.get_id(), add_id);
    assert_eq!(remainder_uses[0].position, 1);

    // Verify the actual position tracking in the users lists
    assert_eq!(returns[0].users.len(), 1);
    assert_eq!(returns[0].users[0].opid, add_id);
    assert_eq!(returns[0].users[0].position, 0);

    assert_eq!(returns[1].users.len(), 1);
    assert_eq!(returns[1].users[0].opid, add_id);
    assert_eq!(returns[1].users[0].position, 1);
}