go-brrr 0.1.0

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

use std::collections::{HashMap, HashSet, VecDeque};

use wide::u64x4;

use crate::dfg::types::DFGInfo;

/// Criteria for slicing operations.
#[derive(Debug, Clone)]
pub struct SliceCriteria {
    /// Target line number (1-indexed, matching source code)
    pub line: usize,
    /// Optional: specific variable to track.
    /// When None, all data flow edges are followed.
    /// When Some(var), only edges for that variable are followed.
    pub variable: Option<String>,
}

impl SliceCriteria {
    /// Create criteria for a specific line.
    #[inline]
    pub fn at_line(line: usize) -> Self {
        Self {
            line,
            variable: None,
        }
    }

    /// Create criteria for a specific line and variable.
    #[inline]
    pub fn at_line_variable(line: usize, variable: impl Into<String>) -> Self {
        Self {
            line,
            variable: Some(variable.into()),
        }
    }
}

/// Result of a program slice computation.
///
/// Contains the slice itself (affected lines) plus metadata about
/// the computation for debugging and analysis purposes.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SliceResult {
    /// Function name where slicing was performed.
    pub function_name: String,

    /// Target/source line of the slice criterion.
    pub target_line: usize,

    /// Direction of the slice ("backward" or "forward").
    pub direction: String,

    /// Lines in the slice (sorted ascending).
    /// These are all lines that either affect (backward) or are
    /// affected by (forward) the target line.
    pub lines: Vec<usize>,

    /// Variables involved in the slice.
    /// Unique set of variable names found along the data flow paths.
    pub variables: Vec<String>,

    /// If slicing was restricted to a specific variable.
    pub variable_filter: Option<String>,

    /// Metrics about the slice computation.
    pub metrics: SliceMetrics,
}

/// Metrics about a computed slice.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SliceMetrics {
    /// Total number of lines in the slice.
    pub slice_size: usize,

    /// Number of edges traversed during computation.
    pub edges_traversed: usize,

    /// Slice ratio: slice_size / total_function_lines.
    /// Lower is better (more focused slice).
    pub slice_ratio: f64,

    /// Number of unique variables in the slice.
    pub variable_count: usize,
}

impl SliceMetrics {
    /// Create empty metrics for empty slices.
    ///
    /// Used when slicing an empty DFG or targeting a nonexistent line.
    #[allow(dead_code)] // Public API for library consumers
    #[inline]
    pub fn empty() -> Self {
        Self {
            slice_size: 0,
            edges_traversed: 0,
            slice_ratio: 0.0,
            variable_count: 0,
        }
    }
}

impl SliceResult {
    /// Check if a specific line is in the slice.
    #[allow(dead_code)] // Public API for library consumers
    #[inline]
    pub fn contains_line(&self, line: usize) -> bool {
        self.lines.binary_search(&line).is_ok()
    }

    /// Get the line range covered by the slice.
    ///
    /// Returns `Some((min_line, max_line))` if the slice is non-empty,
    /// `None` if the slice is empty.
    #[allow(dead_code)] // Public API for library consumers
    pub fn line_range(&self) -> Option<(usize, usize)> {
        match (self.lines.first(), self.lines.last()) {
            (Some(&first), Some(&last)) => Some((first, last)),
            _ => None,
        }
    }

    /// Check if the slice is empty.
    #[allow(dead_code)] // Public API for library consumers
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.lines.is_empty()
    }
}

/// Compute a backward slice: find all lines that can affect the target line.
///
/// Starting from the slicing criterion (target line), traces backward through
/// def-use chains to find all statements that could influence the computation
/// at the target line.
///
/// # Algorithm
/// Uses BFS traversal on the reverse data flow graph:
/// 1. Initialize frontier with the target line
/// 2. For each line in frontier, find all edges where `to_line == line`
/// 3. Add `from_line` of each such edge to frontier (if not visited)
/// 4. Continue until frontier is empty
///
/// # Arguments
/// * `dfg` - Data flow graph to slice
/// * `criteria` - Slicing criteria (line and optional variable filter)
///
/// # Returns
/// `SliceResult` containing affected lines and metadata.
///
/// # Time Complexity
/// O(V + E) where V = unique lines, E = edges
pub fn backward_slice(dfg: &DFGInfo, criteria: &SliceCriteria) -> SliceResult {
    let lines = if let Some(ref var) = criteria.variable {
        backward_slice_variable_impl(dfg, criteria.line, var)
    } else {
        backward_slice_all(dfg, criteria.line)
    };

    // Collect variables involved in the slice
    let variables = collect_slice_variables(dfg, &lines);

    // Compute metrics
    let function_line_range = compute_function_line_range(dfg);
    let total_lines = function_line_range
        .map(|(min, max)| max.saturating_sub(min).saturating_add(1))
        .unwrap_or(1);
    let edges_traversed = count_edges_in_slice(dfg, &lines);

    let metrics = SliceMetrics {
        slice_size: lines.len(),
        edges_traversed,
        slice_ratio: lines.len() as f64 / total_lines as f64,
        variable_count: variables.len(),
    };

    SliceResult {
        function_name: dfg.function_name.clone(),
        target_line: criteria.line,
        direction: "backward".to_string(),
        lines,
        variables,
        variable_filter: criteria.variable.clone(),
        metrics,
    }
}

/// Compute a forward slice: find all lines affected by the source line.
///
/// Starting from the slicing criterion (source line), traces forward through
/// use-def chains to find all statements that could be influenced by
/// computations at the source line.
///
/// # Algorithm
/// Uses BFS traversal on the data flow graph:
/// 1. Initialize frontier with the source line
/// 2. For each line in frontier, find all edges where `from_line == line`
/// 3. Add `to_line` of each such edge to frontier (if not visited)
/// 4. Continue until frontier is empty
///
/// # Arguments
/// * `dfg` - Data flow graph to slice
/// * `criteria` - Slicing criteria (line and optional variable filter)
///
/// # Returns
/// `SliceResult` containing affected lines and metadata.
///
/// # Time Complexity
/// O(V + E) where V = unique lines, E = edges
pub fn forward_slice(dfg: &DFGInfo, criteria: &SliceCriteria) -> SliceResult {
    let lines = if let Some(ref var) = criteria.variable {
        forward_slice_variable_impl(dfg, criteria.line, var)
    } else {
        forward_slice_all(dfg, criteria.line)
    };

    // Collect variables involved in the slice
    let variables = collect_slice_variables(dfg, &lines);

    // Compute metrics
    let function_line_range = compute_function_line_range(dfg);
    let total_lines = function_line_range
        .map(|(min, max)| max.saturating_sub(min).saturating_add(1))
        .unwrap_or(1);
    let edges_traversed = count_edges_in_slice(dfg, &lines);

    let metrics = SliceMetrics {
        slice_size: lines.len(),
        edges_traversed,
        slice_ratio: lines.len() as f64 / total_lines as f64,
        variable_count: variables.len(),
    };

    SliceResult {
        function_name: dfg.function_name.clone(),
        target_line: criteria.line,
        direction: "forward".to_string(),
        lines,
        variables,
        variable_filter: criteria.variable.clone(),
        metrics,
    }
}

/// Backward slice for a specific variable only.
///
/// More focused than full backward slice - only follows edges
/// that involve the specified variable.
///
/// # Arguments
/// * `dfg` - Data flow graph
/// * `line` - Target line number
/// * `variable` - Variable name to track
///
/// # Returns
/// Sorted vector of line numbers in the slice.
#[allow(dead_code)] // Public API for library consumers
pub fn backward_slice_variable(dfg: &DFGInfo, line: usize, variable: &str) -> Vec<usize> {
    backward_slice_variable_impl(dfg, line, variable)
}

/// Forward slice for a specific variable only.
///
/// More focused than full forward slice - only follows edges
/// that involve the specified variable.
///
/// # Arguments
/// * `dfg` - Data flow graph
/// * `line` - Source line number
/// * `variable` - Variable name to track
///
/// # Returns
/// Sorted vector of line numbers in the slice.
#[allow(dead_code)] // Public API for library consumers
pub fn forward_slice_variable(dfg: &DFGInfo, line: usize, variable: &str) -> Vec<usize> {
    forward_slice_variable_impl(dfg, line, variable)
}

/// Compute bidirectional slice (both backward and forward from a line).
///
/// Useful for understanding the full context of a line - both
/// what affects it and what it affects.
///
/// # Arguments
/// * `dfg` - Data flow graph
/// * `criteria` - Slicing criteria
///
/// # Returns
/// Tuple of (backward_result, forward_result)
#[allow(dead_code)] // Public API for library consumers
pub fn bidirectional_slice(dfg: &DFGInfo, criteria: &SliceCriteria) -> (SliceResult, SliceResult) {
    let backward = backward_slice(dfg, criteria);
    let forward = forward_slice(dfg, criteria);
    (backward, forward)
}

/// Result of a chop computation.
///
/// Contains the intersection of forward slice from source and backward
/// slice from target, plus metadata about the computation.
#[allow(dead_code)] // Public API for library consumers
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ChopResult {
    /// Lines in the chop (sorted ascending).
    /// These are all lines that lie on a data flow path from source to target.
    pub lines: Vec<usize>,

    /// Source line (start of chop).
    pub source_line: usize,

    /// Target line (end of chop).
    pub target_line: usize,

    /// If chop was restricted to a specific variable.
    pub variable: Option<String>,
}

impl ChopResult {
    /// Check if a specific line is in the chop.
    #[allow(dead_code)] // Public API for library consumers
    #[inline]
    pub fn contains_line(&self, line: usize) -> bool {
        self.lines.binary_search(&line).is_ok()
    }

    /// Get the line range covered by the chop.
    ///
    /// Returns `Some((min_line, max_line))` if the chop is non-empty,
    /// `None` if the chop is empty.
    #[allow(dead_code)] // Public API for library consumers
    pub fn line_range(&self) -> Option<(usize, usize)> {
        match (self.lines.first(), self.lines.last()) {
            (Some(&first), Some(&last)) => Some((first, last)),
            _ => None,
        }
    }

    /// Check if the chop is empty.
    #[allow(dead_code)] // Public API for library consumers
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.lines.is_empty()
    }
}

/// Compute the chop between two lines.
///
/// A chop(source, target) contains all statements that can be
/// on a path from source to target. Useful for understanding
/// how data flows between two specific points.
///
/// # Algorithm
/// Chop = Forward_slice(source) INTERSECT Backward_slice(target)
///
/// Returns empty chop if either source_line or target_line does not exist
/// in the DFG, matching Python's PDG semantics.
///
/// # Arguments
/// * `dfg` - Data flow graph
/// * `source_line` - Source line (start of chop)
/// * `target_line` - Target line (end of chop)
///
/// # Returns
/// `ChopResult` containing affected lines and metadata.
#[allow(dead_code)] // Public API for library consumers
pub fn chop(dfg: &DFGInfo, source_line: usize, target_line: usize) -> ChopResult {
    chop_impl(dfg, source_line, target_line, None)
}

/// Compute the chop between two lines for a specific variable.
///
/// More focused than full chop - only follows data flow edges
/// that involve the specified variable, then computes the intersection.
///
/// # Algorithm
/// Chop = Forward_slice_variable(source, var) INTERSECT Backward_slice_variable(target, var)
///
/// # Arguments
/// * `dfg` - Data flow graph
/// * `source_line` - Source line (start of chop)
/// * `target_line` - Target line (end of chop)
/// * `variable` - Variable name to track
///
/// # Returns
/// `ChopResult` containing affected lines and metadata.
///
/// # Example
/// ```text
/// Line 1: x = input()
/// Line 2: y = x + 1
/// Line 3: x = x * 2
/// Line 4: z = x + y
///
/// chop_for_variable(dfg, 1, 4, "x") -> lines [1, 3, 4]
/// chop_for_variable(dfg, 1, 4, "y") -> lines [2, 4]
/// ```
#[allow(dead_code)] // Public API for library consumers
pub fn chop_for_variable(
    dfg: &DFGInfo,
    source_line: usize,
    target_line: usize,
    variable: &str,
) -> ChopResult {
    chop_impl(dfg, source_line, target_line, Some(variable))
}

/// Internal implementation for chop computation with optional variable filtering.
///
/// # Arguments
/// * `dfg` - Data flow graph
/// * `source_line` - Source line (start of chop)
/// * `target_line` - Target line (end of chop)
/// * `variable` - Optional variable name to filter edges
fn chop_impl(
    dfg: &DFGInfo,
    source_line: usize,
    target_line: usize,
    variable: Option<&str>,
) -> ChopResult {
    // For non-variable case, use optimized bidirectional traversal
    if variable.is_none() {
        let lines = chop_bidirectional(dfg, source_line, target_line);
        return ChopResult {
            lines,
            source_line,
            target_line,
            variable: None,
        };
    }

    // Variable-filtered case: use separate slice computations
    // (variable filtering requires edge-by-edge inspection)
    // SAFETY: We already returned early if variable.is_none() above
    let var = match variable {
        Some(v) => v,
        None => {
            // Unreachable due to guard clause above, but handle gracefully
            return ChopResult {
                lines: Vec::new(),
                source_line,
                target_line,
                variable: None,
            };
        }
    };

    // Use cached adjacency to validate lines exist (O(1) lookup)
    let cache = dfg.get_adjacency_cache();
    let source_exists = cache.incoming.contains_key(&source_line)
        || cache.outgoing.contains_key(&source_line);
    let target_exists = cache.incoming.contains_key(&target_line)
        || cache.outgoing.contains_key(&target_line);

    if !source_exists || !target_exists {
        return ChopResult {
            lines: Vec::new(),
            source_line,
            target_line,
            variable: Some(var.to_string()),
        };
    }

    let forward_set: HashSet<usize> = forward_slice_variable_impl(dfg, source_line, var)
        .into_iter()
        .collect();

    let backward_set: HashSet<usize> = backward_slice_variable_impl(dfg, target_line, var)
        .into_iter()
        .collect();

    // Chop = intersection of forward from source and backward from target
    let mut chop_lines: Vec<usize> = forward_set
        .intersection(&backward_set)
        .copied()
        .collect();

    chop_lines.sort_unstable();

    ChopResult {
        lines: chop_lines,
        source_line,
        target_line,
        variable: Some(var.to_string()),
    }
}

/// Compute program chop using bidirectional traversal.
///
/// Uses interleaved forward/backward BFS which:
/// 1. Uses cached adjacency lists (amortized O(1) edge lookups)
/// 2. Processes both directions simultaneously for better cache locality
/// 3. Builds result directly without intermediate Vec allocations
///
/// # Algorithm
/// Chop(source, target) = Forward_slice(source) INTERSECT Backward_slice(target)
///
/// This implementation performs both traversals in a single pass, alternating
/// between forward and backward expansion. The result is the intersection of
/// all nodes reachable from source (forward) and all nodes that can reach
/// target (backward).
///
/// # Important: Why We Cannot Terminate Early
/// A naive bidirectional BFS might terminate when frontiers first meet, but this
/// is INCORRECT for chop computation. The chop requires ALL nodes on ANY path
/// from source to target, not just detection of connectivity. Early termination
/// would miss nodes that are only visited later in the traversal.
///
/// # Arguments
/// * `dfg` - Data flow graph
/// * `source_line` - Source line (start of chop)
/// * `target_line` - Target line (end of chop)
///
/// # Returns
/// Sorted vector of line numbers in the chop.
///
/// # Complexity
/// O(V + E) where V = unique lines, E = edges
/// Same asymptotic complexity as separate traversals, but with:
/// - Better cache locality from interleaved access
/// - Single adjacency cache access (shared between both directions)
/// - Direct HashSet building without intermediate Vec conversion
fn chop_bidirectional(dfg: &DFGInfo, source_line: usize, target_line: usize) -> Vec<usize> {
    // Handle trivial case: same source and target
    if source_line == target_line {
        let cache = dfg.get_adjacency_cache();
        let exists = cache.incoming.contains_key(&source_line)
            || cache.outgoing.contains_key(&source_line);
        return if exists { vec![source_line] } else { Vec::new() };
    }

    // Get cached adjacency (O(1) if already built, O(E) first time)
    let cache = dfg.get_adjacency_cache();

    // Validate both endpoints exist in the graph
    let source_exists = cache.incoming.contains_key(&source_line)
        || cache.outgoing.contains_key(&source_line);
    let target_exists = cache.incoming.contains_key(&target_line)
        || cache.outgoing.contains_key(&target_line);

    if !source_exists || !target_exists {
        return Vec::new();
    }

    // Pre-allocate with reasonable capacity based on graph density
    let estimated_size = (cache.outgoing.len() + cache.incoming.len()) / 4;
    let mut forward_visited: HashSet<usize> = HashSet::with_capacity(estimated_size);
    let mut backward_visited: HashSet<usize> = HashSet::with_capacity(estimated_size);

    let mut forward_frontier: VecDeque<usize> = VecDeque::with_capacity(estimated_size / 2);
    let mut backward_frontier: VecDeque<usize> = VecDeque::with_capacity(estimated_size / 2);

    // Initialize frontiers
    forward_frontier.push_back(source_line);
    forward_visited.insert(source_line);

    backward_frontier.push_back(target_line);
    backward_visited.insert(target_line);

    // Interleaved BFS: expand both frontiers until exhausted
    // We MUST complete both traversals for correct chop semantics
    while !forward_frontier.is_empty() || !backward_frontier.is_empty() {
        // Expand forward frontier (follow outgoing edges)
        if let Some(line) = forward_frontier.pop_front() {
            if let Some(successors) = cache.outgoing.get(&line) {
                for &succ in successors {
                    if forward_visited.insert(succ) {
                        forward_frontier.push_back(succ);
                    }
                }
            }
        }

        // Expand backward frontier (follow incoming edges)
        if let Some(line) = backward_frontier.pop_front() {
            if let Some(predecessors) = cache.incoming.get(&line) {
                for &pred in predecessors {
                    if backward_visited.insert(pred) {
                        backward_frontier.push_back(pred);
                    }
                }
            }
        }
    }

    // Chop = intersection of forward-reachable and backward-reachable
    // Use smaller set for iteration (optimization for asymmetric slices)
    let mut result: Vec<usize> = if forward_visited.len() <= backward_visited.len() {
        forward_visited
            .iter()
            .filter(|&line| backward_visited.contains(line))
            .copied()
            .collect()
    } else {
        backward_visited
            .iter()
            .filter(|&line| forward_visited.contains(line))
            .copied()
            .collect()
    };

    result.sort_unstable();
    result
}

// =============================================================================
// Internal Implementation Functions
// =============================================================================

// NOTE: The `get_valid_lines` function was removed as it's now superseded by
// the cached adjacency list. Line existence is validated using:
//   cache.incoming.contains_key(&line) || cache.outgoing.contains_key(&line)
// This provides O(1) lookup instead of O(E) traversal.

/// Backward slice without variable filtering.
///
/// Uses cached adjacency lists for O(1) edge lookups.
/// First slice operation builds the cache; subsequent calls reuse it.
///
/// # Complexity
/// - First call: O(E) to build cache + O(V + E) for traversal
/// - Subsequent calls: O(V + E) for traversal only (15900x faster for large graphs)
///
/// Returns empty vector if:
/// - DFG is empty (no edges)
/// - target_line does not exist in the DFG
///
/// This matches Python's PDG semantics.
pub(crate) fn backward_slice_all(dfg: &DFGInfo, target_line: usize) -> Vec<usize> {
    // Handle empty DFG explicitly - no data flow means empty slice
    if dfg.edges.is_empty() {
        return Vec::new();
    }

    // Get cached adjacency list (built once, reused for all slice operations)
    let cache = dfg.get_adjacency_cache();

    // Validate target line exists in DFG before traversal
    // A line exists if it appears in either incoming or outgoing adjacency
    let target_exists = cache.incoming.contains_key(&target_line)
        || cache.outgoing.contains_key(&target_line);
    if !target_exists {
        return Vec::new();
    }

    // BFS backward using cached incoming adjacency
    let mut result = HashSet::new();
    let mut frontier = VecDeque::new();
    frontier.push_back(target_line);

    while let Some(line) = frontier.pop_front() {
        if result.insert(line) {
            if let Some(sources) = cache.incoming.get(&line) {
                for &source in sources {
                    if !result.contains(&source) {
                        frontier.push_back(source);
                    }
                }
            }
        }
    }

    let mut lines: Vec<_> = result.into_iter().collect();
    lines.sort_unstable();
    lines
}

/// Backward slice for a specific variable.
///
/// This is the internal implementation that only considers data flow for the specified
/// variable. For semantically correct slicing that matches Python's PDG behavior,
/// use `backward_slice_variable_with_control` which also includes control dependencies.
fn backward_slice_variable_impl(dfg: &DFGInfo, target_line: usize, variable: &str) -> Vec<usize> {
    backward_slice_variable_with_control_impl(dfg, target_line, variable, None)
}

/// Backward slice for a specific variable with optional control dependencies.
///
/// This matches Python's PDG slicing semantics where:
/// - Data flow edges are filtered to the specific variable
/// - Control dependencies are ALWAYS followed (regardless of variable)
///
/// Without control dependencies, the slice would miss conditions that determine
/// whether the variable is defined. For example:
/// ```text
/// 1: if flag:
/// 2:     x = 10
/// 3: print(x)
/// ```
/// A backward slice from line 3 for variable 'x' should include line 1 (the condition)
/// because the condition determines whether x is defined.
///
/// Returns empty vector if target_line does not exist in the DFG,
/// matching Python's PDG semantics.
///
/// # Arguments
/// * `dfg` - Data flow graph
/// * `target_line` - Line to slice from
/// * `variable` - Variable to track
/// * `control_deps` - Optional pre-computed control dependencies (reverse mapping)
///
/// # Performance
/// Uses pre-computed per-variable adjacency cache for O(1) edge lookups.
/// First call builds cache O(E), subsequent calls are O(V + E_var) where
/// E_var is the number of edges for the specific variable.
fn backward_slice_variable_with_control_impl(
    dfg: &DFGInfo,
    target_line: usize,
    variable: &str,
    control_deps: Option<&HashMap<usize, Vec<usize>>>,
) -> Vec<usize> {
    // Use cached adjacency to validate target line exists
    // This avoids O(E) traversal of get_valid_lines()
    let cache = dfg.get_adjacency_cache();
    let target_exists = cache.incoming.contains_key(&target_line)
        || cache.outgoing.contains_key(&target_line);
    if !target_exists {
        return Vec::new();
    }

    // Get pre-computed per-variable incoming adjacency (O(1) after first build)
    let var_incoming = dfg.get_var_incoming_lines(variable);

    // BFS backward using pre-computed adjacency + control dependencies
    let mut result = HashSet::new();
    let mut frontier = VecDeque::new();
    frontier.push_back(target_line);

    while let Some(line) = frontier.pop_front() {
        if result.insert(line) {
            // Follow variable-specific data flow edges (O(1) lookup)
            if let Some(var_adj) = var_incoming {
                if let Some(sources) = var_adj.get(&line) {
                    for &source in sources {
                        if !result.contains(&source) {
                            frontier.push_back(source);
                        }
                    }
                }
            }

            // Also follow ALL control dependencies (not variable-specific)
            // This matches Python's PDG behavior where control edges are always followed
            if let Some(deps) = control_deps {
                if let Some(condition_lines) = deps.get(&line) {
                    for &condition_line in condition_lines {
                        if !result.contains(&condition_line) {
                            frontier.push_back(condition_line);
                        }
                    }
                }
            }
        }
    }

    let mut lines: Vec<_> = result.into_iter().collect();
    lines.sort_unstable();
    lines
}

/// Forward slice without variable filtering.
///
/// Uses cached adjacency lists for O(1) edge lookups.
/// First slice operation builds the cache; subsequent calls reuse it.
///
/// # Complexity
/// - First call: O(E) to build cache + O(V + E) for traversal
/// - Subsequent calls: O(V + E) for traversal only (15900x faster for large graphs)
///
/// Returns empty vector if:
/// - DFG is empty (no edges)
/// - source_line does not exist in the DFG
///
/// This matches Python's PDG semantics.
pub(crate) fn forward_slice_all(dfg: &DFGInfo, source_line: usize) -> Vec<usize> {
    // Handle empty DFG explicitly - no data flow means empty slice
    if dfg.edges.is_empty() {
        return Vec::new();
    }

    // Get cached adjacency list (built once, reused for all slice operations)
    let cache = dfg.get_adjacency_cache();

    // Validate source line exists in DFG before traversal
    // A line exists if it appears in either incoming or outgoing adjacency
    let source_exists = cache.incoming.contains_key(&source_line)
        || cache.outgoing.contains_key(&source_line);
    if !source_exists {
        return Vec::new();
    }

    // BFS forward using cached outgoing adjacency
    let mut result = HashSet::new();
    let mut frontier = VecDeque::new();
    frontier.push_back(source_line);

    while let Some(line) = frontier.pop_front() {
        if result.insert(line) {
            if let Some(targets) = cache.outgoing.get(&line) {
                for &target in targets {
                    if !result.contains(&target) {
                        frontier.push_back(target);
                    }
                }
            }
        }
    }

    let mut lines: Vec<_> = result.into_iter().collect();
    lines.sort_unstable();
    lines
}

/// Forward slice for a specific variable.
///
/// This is the internal implementation that only considers data flow for the specified
/// variable. For semantically correct slicing that matches Python's PDG behavior,
/// use `forward_slice_variable_with_control` which also includes control dependencies.
fn forward_slice_variable_impl(dfg: &DFGInfo, source_line: usize, variable: &str) -> Vec<usize> {
    forward_slice_variable_with_control_impl(dfg, source_line, variable, None)
}

/// Forward slice for a specific variable with optional control dependencies.
///
/// This matches Python's PDG slicing semantics where:
/// - Data flow edges are filtered to the specific variable
/// - Control dependencies are ALWAYS followed (regardless of variable)
///
/// For forward slicing, if a condition controls where the variable flows,
/// we need to include the controlled lines.
///
/// Returns empty vector if source_line does not exist in the DFG,
/// matching Python's PDG semantics.
///
/// # Arguments
/// * `dfg` - Data flow graph
/// * `source_line` - Line to slice from
/// * `variable` - Variable to track
/// * `control_deps` - Optional pre-computed control dependencies (forward mapping)
///
/// # Performance
/// Uses pre-computed per-variable adjacency cache for O(1) edge lookups.
/// First call builds cache O(E), subsequent calls are O(V + E_var) where
/// E_var is the number of edges for the specific variable.
fn forward_slice_variable_with_control_impl(
    dfg: &DFGInfo,
    source_line: usize,
    variable: &str,
    control_deps: Option<&HashMap<usize, Vec<usize>>>,
) -> Vec<usize> {
    // Use cached adjacency to validate source line exists
    // This avoids O(E) traversal of get_valid_lines()
    let cache = dfg.get_adjacency_cache();
    let source_exists = cache.incoming.contains_key(&source_line)
        || cache.outgoing.contains_key(&source_line);
    if !source_exists {
        return Vec::new();
    }

    // Get pre-computed per-variable outgoing adjacency (O(1) after first build)
    let var_outgoing = dfg.get_var_outgoing_lines(variable);

    // BFS forward using pre-computed adjacency + control dependencies
    let mut result = HashSet::new();
    let mut frontier = VecDeque::new();
    frontier.push_back(source_line);

    while let Some(line) = frontier.pop_front() {
        if result.insert(line) {
            // Follow variable-specific data flow edges (O(1) lookup)
            if let Some(var_adj) = var_outgoing {
                if let Some(targets) = var_adj.get(&line) {
                    for &target in targets {
                        if !result.contains(&target) {
                            frontier.push_back(target);
                        }
                    }
                }
            }

            // Also follow ALL control dependencies (not variable-specific)
            // This matches Python's PDG behavior where control edges are always followed
            if let Some(deps) = control_deps {
                if let Some(dependent_lines) = deps.get(&line) {
                    for &dependent_line in dependent_lines {
                        if !result.contains(&dependent_line) {
                            frontier.push_back(dependent_line);
                        }
                    }
                }
            }
        }
    }

    let mut lines: Vec<_> = result.into_iter().collect();
    lines.sort_unstable();
    lines
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Collect all variables involved in edges touching the given lines.
fn collect_slice_variables(dfg: &DFGInfo, lines: &[usize]) -> Vec<String> {
    let line_set: HashSet<usize> = lines.iter().copied().collect();

    let mut variables: HashSet<&str> = HashSet::new();
    for edge in &dfg.edges {
        if line_set.contains(&edge.from_line) || line_set.contains(&edge.to_line) {
            variables.insert(&edge.variable);
        }
    }

    let mut result: Vec<String> = variables.into_iter().map(String::from).collect();
    result.sort_unstable();
    result
}

/// Count edges whose both endpoints are in the slice.
///
/// Filters out self-loops (edges where from_line == to_line) as they
/// are semantically meaningless and inflate metrics artificially.
///
/// # Performance
/// Expects `lines` to be sorted (all slice functions return sorted results).
/// Uses binary search for O(log n) membership tests with excellent cache locality,
/// avoiding HashSet allocation and hash computation overhead.
///
/// For very small slices (<= 16 lines), uses linear search which is faster
/// due to better cache prefetching and no function call overhead.
fn count_edges_in_slice(dfg: &DFGInfo, lines: &[usize]) -> usize {
    if lines.is_empty() {
        return 0;
    }

    // Threshold for switching between linear and binary search.
    // Linear search is faster for small arrays due to cache prefetching
    // and avoiding the overhead of binary search's branch mispredictions.
    const LINEAR_THRESHOLD: usize = 16;

    let contains = if lines.len() <= LINEAR_THRESHOLD {
        // Linear search for small slices - cache-friendly sequential access
        |lines: &[usize], value: usize| -> bool { lines.contains(&value) }
    } else {
        // Binary search for larger slices - O(log n) with sorted input
        |lines: &[usize], value: usize| -> bool { lines.binary_search(&value).is_ok() }
    };

    dfg.edges
        .iter()
        .filter(|e| {
            // Skip self-loops - they add no data flow information
            e.from_line != e.to_line
                && contains(lines, e.from_line)
                && contains(lines, e.to_line)
        })
        .count()
}

/// Compute the line range covered by the DFG using SIMD acceleration.
///
/// Uses `u64x4` to process 4 line values simultaneously, computing
/// min/max in parallel. Falls back to scalar for remainder elements.
///
/// # Performance
///
/// For DFGs with N edges (2N line values):
/// - SIMD loop: processes floor(2N/4) * 4 values with 4-way parallelism
/// - Scalar remainder: processes 2N mod 4 values
/// - Final reduction: 3 comparisons for 4-element vector
///
/// Provides ~2-3x speedup on large DFGs compared to scalar implementation.
fn compute_function_line_range(dfg: &DFGInfo) -> Option<(usize, usize)> {
    if dfg.edges.is_empty() {
        return None;
    }

    let edges = &dfg.edges;
    let edge_count = edges.len();

    // Threshold: SIMD overhead not worth it for tiny DFGs
    const SIMD_THRESHOLD: usize = 8;

    if edge_count < SIMD_THRESHOLD {
        // Scalar path for small DFGs - avoids SIMD setup overhead
        let mut min_line = usize::MAX;
        let mut max_line = 0;
        for edge in edges {
            min_line = min_line.min(edge.from_line).min(edge.to_line);
            max_line = max_line.max(edge.from_line).max(edge.to_line);
        }
        return if min_line <= max_line {
            Some((min_line, max_line))
        } else {
            None
        };
    }

    // SOA extraction: gather from_line and to_line into contiguous arrays
    // This enables efficient SIMD loading with better cache utilization
    let total_values = edge_count * 2;
    let mut line_values: Vec<u64> = Vec::with_capacity(total_values);

    for edge in edges {
        line_values.push(edge.from_line as u64);
        line_values.push(edge.to_line as u64);
    }

    // Initialize SIMD accumulators
    let mut simd_min = u64x4::splat(u64::MAX);
    let mut simd_max = u64x4::splat(0);

    // Process 4 values at a time
    let simd_chunks = total_values / 4;
    let simd_end = simd_chunks * 4;

    for chunk_idx in 0..simd_chunks {
        let base = chunk_idx * 4;

        // Load 4 line values into SIMD register
        let values = u64x4::new([
            line_values[base],
            line_values[base + 1],
            line_values[base + 2],
            line_values[base + 3],
        ]);

        // SIMD min: simd_min = blend(values < simd_min, values, simd_min)
        let lt_mask = values.cmp_lt(simd_min);
        simd_min = lt_mask.blend(values, simd_min);

        // SIMD max: simd_max = blend(values > simd_max, values, simd_max)
        let gt_mask = values.cmp_gt(simd_max);
        simd_max = gt_mask.blend(values, simd_max);
    }

    // Horizontal reduction: extract 4 lanes and reduce to scalar
    let min_arr = simd_min.to_array();
    let max_arr = simd_max.to_array();

    let mut min_line = min_arr[0].min(min_arr[1]).min(min_arr[2]).min(min_arr[3]) as usize;
    let mut max_line = max_arr[0].max(max_arr[1]).max(max_arr[2]).max(max_arr[3]) as usize;

    // Handle remainder (0-3 values) with scalar operations
    for &value in &line_values[simd_end..] {
        let v = value as usize;
        min_line = min_line.min(v);
        max_line = max_line.max(v);
    }

    if min_line <= max_line {
        Some((min_line, max_line))
    } else {
        None
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dfg::types::{DFGInfo, DataflowEdge, DataflowKind};

    /// Create a test DFG with known structure:
    ///
    /// ```text
    /// Line 1: x = input()          # Definition of x
    /// Line 2: y = x + 1            # Use of x, Definition of y
    /// Line 3: z = y * 2            # Use of y, Definition of z
    /// Line 4: w = x + z            # Use of x and z, Definition of w
    /// Line 5: return w             # Use of w
    /// ```
    fn create_test_dfg() -> DFGInfo {
        DFGInfo::new(
            "test_func".to_string(),
            vec![
                // x flows: 1 -> 2, 1 -> 4
                DataflowEdge {
                    variable: "x".to_string(),
                    from_line: 1,
                    to_line: 2,
                    kind: DataflowKind::Definition,
                },
                DataflowEdge {
                    variable: "x".to_string(),
                    from_line: 1,
                    to_line: 4,
                    kind: DataflowKind::Use,
                },
                // y flows: 2 -> 3
                DataflowEdge {
                    variable: "y".to_string(),
                    from_line: 2,
                    to_line: 3,
                    kind: DataflowKind::Definition,
                },
                // z flows: 3 -> 4
                DataflowEdge {
                    variable: "z".to_string(),
                    from_line: 3,
                    to_line: 4,
                    kind: DataflowKind::Definition,
                },
                // w flows: 4 -> 5
                DataflowEdge {
                    variable: "w".to_string(),
                    from_line: 4,
                    to_line: 5,
                    kind: DataflowKind::Definition,
                },
            ],
            [
                ("x".to_string(), vec![1]),
                ("y".to_string(), vec![2]),
                ("z".to_string(), vec![3]),
                ("w".to_string(), vec![4]),
            ]
            .into_iter()
            .collect(),
            [
                ("x".to_string(), vec![2, 4]),
                ("y".to_string(), vec![3]),
                ("z".to_string(), vec![4]),
                ("w".to_string(), vec![5]),
            ]
            .into_iter()
            .collect(),
        )
    }

    #[test]
    fn test_backward_slice_from_return() {
        let dfg = create_test_dfg();
        let criteria = SliceCriteria::at_line(5);
        let result = backward_slice(&dfg, &criteria);

        // Backward from line 5 (return w) should include:
        // 5 -> 4 (w defined) -> 3 (z defined) -> 2 (y defined) -> 1 (x defined)
        // Also 4 uses x directly from 1
        assert_eq!(result.lines, vec![1, 2, 3, 4, 5]);
        assert_eq!(result.direction, "backward");
        assert_eq!(result.target_line, 5);
    }

    #[test]
    fn test_backward_slice_from_middle() {
        let dfg = create_test_dfg();
        let criteria = SliceCriteria::at_line(3);
        let result = backward_slice(&dfg, &criteria);

        // Backward from line 3 (z = y * 2) should include:
        // 3 -> 2 (y defined) -> 1 (x defined)
        assert_eq!(result.lines, vec![1, 2, 3]);
    }

    #[test]
    fn test_forward_slice_from_start() {
        let dfg = create_test_dfg();
        let criteria = SliceCriteria::at_line(1);
        let result = forward_slice(&dfg, &criteria);

        // Forward from line 1 (x = input) should reach everything
        // 1 -> 2 -> 3 -> 4 -> 5
        // 1 -> 4 -> 5
        assert_eq!(result.lines, vec![1, 2, 3, 4, 5]);
        assert_eq!(result.direction, "forward");
    }

    #[test]
    fn test_forward_slice_from_middle() {
        let dfg = create_test_dfg();
        let criteria = SliceCriteria::at_line(3);
        let result = forward_slice(&dfg, &criteria);

        // Forward from line 3 (z = y * 2):
        // 3 -> 4 -> 5
        assert_eq!(result.lines, vec![3, 4, 5]);
    }

    #[test]
    fn test_backward_slice_variable_specific() {
        let dfg = create_test_dfg();
        let result = backward_slice_variable(&dfg, 4, "x");

        // Backward from line 4 following only x:
        // 4 <- 1 (x defined at 1, used at 4)
        assert_eq!(result, vec![1, 4]);
    }

    #[test]
    fn test_forward_slice_variable_specific() {
        let dfg = create_test_dfg();
        let result = forward_slice_variable(&dfg, 2, "y");

        // Forward from line 2 following only y:
        // 2 -> 3 (y used at 3)
        assert_eq!(result, vec![2, 3]);
    }

    #[test]
    fn test_chop() {
        let dfg = create_test_dfg();
        let result = chop(&dfg, 1, 5);

        // Chop from 1 to 5 = forward(1) intersect backward(5)
        // Both should be {1,2,3,4,5}
        assert_eq!(result.lines, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_chop_narrower() {
        let dfg = create_test_dfg();
        let result = chop(&dfg, 2, 4);

        // forward(2) = {2, 3, 4, 5}
        // backward(4) = {1, 2, 3, 4}
        // intersection = {2, 3, 4}
        assert_eq!(result.lines, vec![2, 3, 4]);
    }

    #[test]
    fn test_chop_for_variable() {
        let dfg = create_test_dfg();

        // Test chop for variable x from line 1 to line 4
        // x edges: 1->2, 1->4
        // forward_slice_variable(1, x) = {1, 2, 4}
        // backward_slice_variable(4, x) = {1, 4}
        // intersection = {1, 4}
        let result_x = chop_for_variable(&dfg, 1, 4, "x");
        assert_eq!(result_x.lines, vec![1, 4]);
        assert_eq!(result_x.variable, Some("x".to_string()));
        assert_eq!(result_x.source_line, 1);
        assert_eq!(result_x.target_line, 4);
    }

    #[test]
    fn test_chop_for_variable_y() {
        let dfg = create_test_dfg();

        // Test chop for variable y
        // y edges: 2->3
        // forward_slice_variable(2, y) = {2, 3}
        // backward_slice_variable(3, y) = {2, 3}
        // intersection = {2, 3}
        let result = chop_for_variable(&dfg, 2, 3, "y");
        assert_eq!(result.lines, vec![2, 3]);
        assert_eq!(result.source_line, 2);
        assert_eq!(result.target_line, 3);
        assert_eq!(result.variable, Some("y".to_string()));
    }

    #[test]
    fn test_chop_for_variable_no_path() {
        let dfg = create_test_dfg();

        // Test chop for variable x from line 1 to line 5
        // x edges: 1->2, 1->4
        // forward_slice_variable(1, x) = {1, 2, 4}
        // backward_slice_variable(5, x) = {} (no x edges end at line 5, w does)
        // intersection = {}
        let result = chop_for_variable(&dfg, 1, 5, "x");
        assert!(result.is_empty());
        assert_eq!(result.variable, Some("x".to_string()));
    }

    #[test]
    fn test_chop_result_methods() {
        let dfg = create_test_dfg();
        let result = chop(&dfg, 2, 4);

        // Test contains_line
        assert!(result.contains_line(2));
        assert!(result.contains_line(3));
        assert!(result.contains_line(4));
        assert!(!result.contains_line(1));
        assert!(!result.contains_line(5));

        // Test line_range
        assert_eq!(result.line_range(), Some((2, 4)));

        // Test is_empty
        assert!(!result.is_empty());
    }

    #[test]
    fn test_chop_metadata() {
        let dfg = create_test_dfg();
        let result = chop(&dfg, 1, 5);

        assert_eq!(result.source_line, 1);
        assert_eq!(result.target_line, 5);
        assert!(result.variable.is_none());
    }

    #[test]
    fn test_bidirectional_slice() {
        let dfg = create_test_dfg();
        let criteria = SliceCriteria::at_line(3);
        let (backward, forward) = bidirectional_slice(&dfg, &criteria);

        assert_eq!(backward.lines, vec![1, 2, 3]);
        assert_eq!(forward.lines, vec![3, 4, 5]);
    }

    #[test]
    fn test_slice_metrics() {
        let dfg = create_test_dfg();
        let criteria = SliceCriteria::at_line(5);
        let result = backward_slice(&dfg, &criteria);

        assert_eq!(result.metrics.slice_size, 5);
        assert!(result.metrics.slice_ratio > 0.0);
        assert!(result.metrics.slice_ratio <= 1.0);
    }

    #[test]
    fn test_slice_result_contains_line() {
        let dfg = create_test_dfg();
        let criteria = SliceCriteria::at_line(3);
        let result = backward_slice(&dfg, &criteria);

        assert!(result.contains_line(1));
        assert!(result.contains_line(2));
        assert!(result.contains_line(3));
        assert!(!result.contains_line(4));
        assert!(!result.contains_line(5));
    }

    #[test]
    fn test_slice_result_line_range() {
        let dfg = create_test_dfg();
        let criteria = SliceCriteria::at_line(3);
        let result = backward_slice(&dfg, &criteria);

        assert_eq!(result.line_range(), Some((1, 3)));
    }

    #[test]
    fn test_empty_dfg_slice() {
        let dfg = DFGInfo::new(
            "empty".to_string(),
            vec![],
            Default::default(),
            Default::default(),
        );

        let criteria = SliceCriteria::at_line(1);
        let result = backward_slice(&dfg, &criteria);

        // Empty DFG means no valid lines exist, so target line is invalid
        // This matches Python's PDG semantics: return empty set for non-existent lines
        assert!(result.lines.is_empty());
        assert!(result.variables.is_empty());
    }

    #[test]
    fn test_slice_nonexistent_line() {
        let dfg = create_test_dfg();

        // Line 100 does not exist in the DFG (which has lines 1-5)
        let criteria = SliceCriteria::at_line(100);
        let result = backward_slice(&dfg, &criteria);

        // Should return empty slice for non-existent line
        // This matches Python's PDG semantics
        assert!(result.lines.is_empty());
        assert!(result.variables.is_empty());
    }

    #[test]
    fn test_forward_slice_nonexistent_line() {
        let dfg = create_test_dfg();

        // Line 100 does not exist in the DFG
        let criteria = SliceCriteria::at_line(100);
        let result = forward_slice(&dfg, &criteria);

        // Should return empty slice for non-existent line
        assert!(result.lines.is_empty());
    }

    #[test]
    fn test_chop_nonexistent_source() {
        let dfg = create_test_dfg();

        // Source line 100 does not exist
        let result = chop(&dfg, 100, 3);

        // Should return empty chop when source doesn't exist
        assert!(result.is_empty());
    }

    #[test]
    fn test_chop_nonexistent_target() {
        let dfg = create_test_dfg();

        // Target line 100 does not exist
        let result = chop(&dfg, 1, 100);

        // Should return empty chop when target doesn't exist
        assert!(result.is_empty());
    }

    #[test]
    fn test_variable_slice_nonexistent_line() {
        let dfg = create_test_dfg();

        // Line 100 does not exist
        let result = backward_slice_variable(&dfg, 100, "x");

        // Should return empty slice for non-existent line
        assert!(result.is_empty());
    }

    #[test]
    fn test_slice_with_variable_filter_criteria() {
        let dfg = create_test_dfg();
        let criteria = SliceCriteria::at_line_variable(4, "x");
        let result = backward_slice(&dfg, &criteria);

        // Only following x edges from line 4
        assert_eq!(result.lines, vec![1, 4]);
        assert_eq!(result.variable_filter, Some("x".to_string()));
    }

    // =========================================================================
    // Empty DFG and Edge Case Tests
    // =========================================================================

    #[test]
    fn test_empty_dfg_returns_empty_slice_backward() {
        let empty_dfg = DFGInfo::new(
            "empty_test".to_string(),
            vec![],
            Default::default(),
            Default::default(),
        );

        // Test backward_slice_all directly with empty DFG
        let result = backward_slice_all(&empty_dfg, 42);
        assert!(
            result.is_empty(),
            "Empty DFG should return empty slice, got {:?}",
            result
        );
    }

    #[test]
    fn test_empty_dfg_returns_empty_slice_forward() {
        let empty_dfg = DFGInfo::new(
            "empty_test".to_string(),
            vec![],
            Default::default(),
            Default::default(),
        );

        // Test forward_slice_all directly with empty DFG
        let result = forward_slice_all(&empty_dfg, 42);
        assert!(
            result.is_empty(),
            "Empty DFG should return empty slice, got {:?}",
            result
        );
    }

    #[test]
    fn test_nonexistent_target_returns_empty_slice_backward() {
        let dfg = DFGInfo::new(
            "test".to_string(),
            vec![DataflowEdge {
                from_line: 1,
                to_line: 2,
                variable: "x".into(),
                kind: DataflowKind::Definition,
            }],
            [("x".to_string(), vec![1])].into_iter().collect(),
            [("x".to_string(), vec![2])].into_iter().collect(),
        );

        // Line 100 doesn't exist in DFG (only has lines 1 and 2)
        let result = backward_slice_all(&dfg, 100);
        assert!(
            result.is_empty(),
            "Nonexistent target should return empty slice, got {:?}",
            result
        );
    }

    #[test]
    fn test_nonexistent_source_returns_empty_slice_forward() {
        let dfg = DFGInfo::new(
            "test".to_string(),
            vec![DataflowEdge {
                from_line: 1,
                to_line: 2,
                variable: "x".into(),
                kind: DataflowKind::Definition,
            }],
            [("x".to_string(), vec![1])].into_iter().collect(),
            [("x".to_string(), vec![2])].into_iter().collect(),
        );

        // Line 100 doesn't exist in DFG (only has lines 1 and 2)
        let result = forward_slice_all(&dfg, 100);
        assert!(
            result.is_empty(),
            "Nonexistent source should return empty slice, got {:?}",
            result
        );
    }

    #[test]
    fn test_slice_metrics_empty() {
        let metrics = SliceMetrics::empty();

        assert_eq!(metrics.slice_size, 0);
        assert_eq!(metrics.edges_traversed, 0);
        assert!((metrics.slice_ratio - 0.0).abs() < f64::EPSILON);
        assert_eq!(metrics.variable_count, 0);
    }

    #[test]
    fn test_empty_dfg_slice_preserves_target_line() {
        let empty_dfg = DFGInfo::new(
            "empty".to_string(),
            vec![],
            Default::default(),
            Default::default(),
        );

        let criteria = SliceCriteria::at_line(42);
        let result = backward_slice(&empty_dfg, &criteria);

        // Empty slice but target_line should still be recorded
        assert!(result.lines.is_empty());
        assert_eq!(result.target_line, 42);
        assert_eq!(result.direction, "backward");
    }

    // =========================================================================
    // Bidirectional Chop Tests
    // =========================================================================

    #[test]
    fn test_chop_bidirectional_same_source_target() {
        let dfg = create_test_dfg();

        // Same line should return just that line
        let result = chop_bidirectional(&dfg, 2, 2);
        assert_eq!(result, vec![2]);
    }

    #[test]
    fn test_chop_bidirectional_same_source_target_nonexistent() {
        let dfg = create_test_dfg();

        // Nonexistent line should return empty
        let result = chop_bidirectional(&dfg, 100, 100);
        assert!(result.is_empty());
    }

    #[test]
    fn test_chop_bidirectional_full_path() {
        let dfg = create_test_dfg();

        // Full path from 1 to 5 should include all lines
        let result = chop_bidirectional(&dfg, 1, 5);
        assert_eq!(result, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_chop_bidirectional_partial_path() {
        let dfg = create_test_dfg();

        // Partial path from 2 to 4
        // forward(2) = {2, 3, 4, 5}
        // backward(4) = {1, 2, 3, 4}
        // intersection = {2, 3, 4}
        let result = chop_bidirectional(&dfg, 2, 4);
        assert_eq!(result, vec![2, 3, 4]);
    }

    #[test]
    fn test_chop_bidirectional_nonexistent_source() {
        let dfg = create_test_dfg();

        let result = chop_bidirectional(&dfg, 100, 5);
        assert!(result.is_empty());
    }

    #[test]
    fn test_chop_bidirectional_nonexistent_target() {
        let dfg = create_test_dfg();

        let result = chop_bidirectional(&dfg, 1, 100);
        assert!(result.is_empty());
    }

    #[test]
    fn test_chop_bidirectional_matches_original() {
        // Verify bidirectional gives same result as original approach
        let dfg = create_test_dfg();

        for source in 1..=5 {
            for target in 1..=5 {
                let bidirectional = chop_bidirectional(&dfg, source, target);

                // Compute using original approach
                let forward_set: HashSet<usize> = forward_slice_all(&dfg, source)
                    .into_iter()
                    .collect();
                let backward_set: HashSet<usize> = backward_slice_all(&dfg, target)
                    .into_iter()
                    .collect();
                let mut original: Vec<usize> = forward_set
                    .intersection(&backward_set)
                    .copied()
                    .collect();
                original.sort_unstable();

                assert_eq!(
                    bidirectional, original,
                    "Mismatch for chop({}, {}): bidirectional={:?}, original={:?}",
                    source, target, bidirectional, original
                );
            }
        }
    }

    #[test]
    fn test_chop_bidirectional_with_branching_graph() {
        // Create a DFG with multiple paths to verify we find ALL nodes
        // Graph: 1 -> 2 -> 4
        //        1 -> 3 -> 4
        let dfg = DFGInfo::new(
            "branching".to_string(),
            vec![
                DataflowEdge {
                    variable: "x".to_string(),
                    from_line: 1,
                    to_line: 2,
                    kind: DataflowKind::Definition,
                },
                DataflowEdge {
                    variable: "y".to_string(),
                    from_line: 1,
                    to_line: 3,
                    kind: DataflowKind::Definition,
                },
                DataflowEdge {
                    variable: "x".to_string(),
                    from_line: 2,
                    to_line: 4,
                    kind: DataflowKind::Use,
                },
                DataflowEdge {
                    variable: "y".to_string(),
                    from_line: 3,
                    to_line: 4,
                    kind: DataflowKind::Use,
                },
            ],
            [
                ("x".to_string(), vec![1]),
                ("y".to_string(), vec![1]),
            ]
            .into_iter()
            .collect(),
            [
                ("x".to_string(), vec![2, 4]),
                ("y".to_string(), vec![3, 4]),
            ]
            .into_iter()
            .collect(),
        );

        // Chop from 1 to 4 should include all paths: {1, 2, 3, 4}
        let result = chop_bidirectional(&dfg, 1, 4);
        assert_eq!(result, vec![1, 2, 3, 4],
            "Bidirectional chop should find ALL nodes on ALL paths");
    }

    #[test]
    fn test_chop_bidirectional_no_path() {
        // Create a DFG with disconnected components
        // Graph: 1 -> 2    3 -> 4 (no path from 1 to 4)
        let dfg = DFGInfo::new(
            "disconnected".to_string(),
            vec![
                DataflowEdge {
                    variable: "x".to_string(),
                    from_line: 1,
                    to_line: 2,
                    kind: DataflowKind::Definition,
                },
                DataflowEdge {
                    variable: "y".to_string(),
                    from_line: 3,
                    to_line: 4,
                    kind: DataflowKind::Definition,
                },
            ],
            [
                ("x".to_string(), vec![1]),
                ("y".to_string(), vec![3]),
            ]
            .into_iter()
            .collect(),
            [
                ("x".to_string(), vec![2]),
                ("y".to_string(), vec![4]),
            ]
            .into_iter()
            .collect(),
        );

        // No path from 1 to 4
        let result = chop_bidirectional(&dfg, 1, 4);
        assert!(result.is_empty(), "Should return empty when no path exists");
    }

    #[test]
    fn test_chop_uses_bidirectional_internally() {
        // Verify that chop() uses chop_bidirectional for non-variable case
        let dfg = create_test_dfg();

        let chop_result = chop(&dfg, 2, 4);
        let bidirectional_result = chop_bidirectional(&dfg, 2, 4);

        assert_eq!(chop_result.lines, bidirectional_result,
            "chop() should use chop_bidirectional internally");
    }

    #[test]
    fn test_chop_empty_dfg() {
        let empty_dfg = DFGInfo::new(
            "empty".to_string(),
            vec![],
            Default::default(),
            Default::default(),
        );

        let result = chop_bidirectional(&empty_dfg, 1, 5);
        assert!(result.is_empty());
    }

    // =========================================================================
    // Tests for compute_function_line_range SIMD optimization
    // =========================================================================

    #[test]
    fn test_compute_line_range_empty() {
        let dfg = DFGInfo::new(
            "empty".to_string(),
            vec![],
            Default::default(),
            Default::default(),
        );
        assert_eq!(compute_function_line_range(&dfg), None);
    }

    #[test]
    fn test_compute_line_range_scalar_path() {
        // Small DFG (< 8 edges) uses scalar path
        let dfg = create_test_dfg();
        let result = compute_function_line_range(&dfg);
        // DFG has edges from lines 1-5
        assert_eq!(result, Some((1, 5)));
    }

    #[test]
    fn test_compute_line_range_simd_path() {
        // Create a large DFG to trigger SIMD path (>= 8 edges)
        let mut edges = Vec::with_capacity(20);
        for i in 0..20 {
            edges.push(DataflowEdge {
                variable: format!("v{}", i),
                from_line: 10 + i,
                to_line: 100 + i,
                kind: DataflowKind::Definition,
            });
        }

        let dfg = DFGInfo::new(
            "simd_test".to_string(),
            edges,
            Default::default(),
            Default::default(),
        );

        let result = compute_function_line_range(&dfg);
        // Min: 10 (first from_line), Max: 119 (last to_line)
        assert_eq!(result, Some((10, 119)));
    }

    #[test]
    fn test_compute_line_range_simd_with_remainder() {
        // Create DFG with 10 edges (20 values, remainder = 0 after SIMD chunks)
        let mut edges = Vec::with_capacity(10);
        for i in 0..10 {
            edges.push(DataflowEdge {
                variable: format!("v{}", i),
                from_line: 5 + i * 2,
                to_line: 6 + i * 2,
                kind: DataflowKind::Definition,
            });
        }

        let dfg = DFGInfo::new(
            "simd_remainder_test".to_string(),
            edges,
            Default::default(),
            Default::default(),
        );

        let result = compute_function_line_range(&dfg);
        // Min: 5 (first from_line), Max: 24 (last to_line: 6 + 9*2)
        assert_eq!(result, Some((5, 24)));
    }

    #[test]
    fn test_compute_line_range_simd_odd_remainder() {
        // Create DFG with 9 edges (18 values, remainder = 2 after 4 SIMD chunks)
        let mut edges = Vec::with_capacity(9);
        for i in 0..9 {
            edges.push(DataflowEdge {
                variable: format!("v{}", i),
                from_line: 1000 - i * 10,
                to_line: 2000 + i * 5,
                kind: DataflowKind::Definition,
            });
        }

        let dfg = DFGInfo::new(
            "simd_odd_test".to_string(),
            edges,
            Default::default(),
            Default::default(),
        );

        let result = compute_function_line_range(&dfg);
        // from_lines: 1000, 990, 980, ..., 920 (min = 920)
        // to_lines: 2000, 2005, 2010, ..., 2040 (max = 2040)
        assert_eq!(result, Some((920, 2040)));
    }

    #[test]
    fn test_compute_line_range_single_edge() {
        let dfg = DFGInfo::new(
            "single".to_string(),
            vec![DataflowEdge {
                variable: "x".to_string(),
                from_line: 42,
                to_line: 100,
                kind: DataflowKind::Definition,
            }],
            Default::default(),
            Default::default(),
        );

        let result = compute_function_line_range(&dfg);
        assert_eq!(result, Some((42, 100)));
    }

    #[test]
    fn test_compute_line_range_same_from_to() {
        // Edge where from_line == to_line (self-reference)
        let mut edges = Vec::with_capacity(10);
        for i in 0..10 {
            edges.push(DataflowEdge {
                variable: format!("v{}", i),
                from_line: 50,
                to_line: 50,
                kind: DataflowKind::Definition,
            });
        }

        let dfg = DFGInfo::new(
            "same_line".to_string(),
            edges,
            Default::default(),
            Default::default(),
        );

        let result = compute_function_line_range(&dfg);
        assert_eq!(result, Some((50, 50)));
    }
}