dimpact 0.5.3

impact analysis from diff
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
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
use serde::{Deserialize, Serialize};

/// Kind of dependency edge in data/control flow graph.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum DependencyKind {
    /// Data dependence (definition → use).
    Data,
    /// Control dependence (predicate → statement).
    Control,
}

/// Node in the data flow graph, representing a definition or use.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DfgNode {
    /// Unique identifier for the node.
    pub id: String,
    /// Symbol or variable name.
    pub name: String,
    /// File path where this node is located.
    pub file: String,
    /// Line number of the node (1-based).
    pub line: u32,
}

/// Edge in the data/control flow graph.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DfgEdge {
    /// Source node ID.
    pub from: String,
    /// Target node ID.
    pub to: String,
    /// Type of dependency.
    pub kind: DependencyKind,
}

/// Representation of a Data Flow Graph.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DataFlowGraph {
    /// All definition/use nodes.
    pub nodes: Vec<DfgNode>,
    /// All dependency edges.
    pub edges: Vec<DfgEdge>,
}

/// Trait for constructing a Data Flow Graph from source code.
pub trait DfgBuilder {
    /// Build a DFG for the given file path and its source content.
    fn build(path: &str, source: &str) -> DataFlowGraph;
}

/// Default Rust DFG builder (stub implementation).
pub struct RustDfgBuilder;

fn parse_ruby_param_name(raw: &str) -> Option<String> {
    let candidate = raw
        .trim()
        .split('=')
        .next()
        .unwrap_or("")
        .trim()
        .trim_start_matches(['*', '&'])
        .split(':')
        .next()
        .unwrap_or("")
        .trim();

    let mut chars = candidate.chars();
    let first = chars.next()?;
    if !(first.is_ascii_alphabetic() || first == '_') {
        return None;
    }
    if !chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_') {
        return None;
    }
    Some(candidate.to_string())
}

fn strip_ruby_inline_comment(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    let mut in_single = false;
    let mut in_double = false;
    let mut escaped = false;

    for ch in raw.chars() {
        if escaped {
            out.push(ch);
            escaped = false;
            continue;
        }
        if (in_single || in_double) && ch == '\\' {
            out.push(ch);
            escaped = true;
            continue;
        }
        if !in_double && ch == '\'' {
            in_single = !in_single;
            out.push(ch);
            continue;
        }
        if !in_single && ch == '"' {
            in_double = !in_double;
            out.push(ch);
            continue;
        }
        if !in_single && !in_double && ch == '#' {
            break;
        }
        out.push(ch);
    }

    out.trim().to_string()
}

impl DfgBuilder for RustDfgBuilder {
    fn build(path: &str, source: &str) -> DataFlowGraph {
        use std::collections::{HashMap, HashSet};
        // Initialize DFG containers
        let mut nodes: Vec<DfgNode> = Vec::new();
        let mut edges: Vec<DfgEdge> = Vec::new();
        // SSA-like ordered definition records: variable -> [(line, def_id)]
        let mut def_records_by_name: HashMap<String, Vec<(u32, String)>> = HashMap::new();
        let mut param_def_records_by_name: HashMap<String, Vec<(u32, String)>> = HashMap::new();
        // Map variable name -> set of line numbers where it's defined
        let mut def_lines_by_name: HashMap<String, HashSet<u32>> = HashMap::new();
        let mut seen_node_ids: HashSet<String> = HashSet::new();
        let line_offsets = crate::languages::util::line_offsets(source);
        let mut ignored_use_byte_ranges: Vec<(usize, usize)> = Vec::new();
        // Interprocedural analysis: parameters and assignments via AST
        {
            // Parse Rust AST to extract definitions
            let mut parser = tree_sitter::Parser::new();
            let lang: tree_sitter::Language = tree_sitter_rust::LANGUAGE.into();
            parser.set_language(&lang).expect("set language");
            if let Some(tree) = parser.parse(source, None) {
                let mut cursor = tree.root_node().walk();
                let mut stack = vec![tree.root_node()];
                while let Some(node) = stack.pop() {
                    // Traverse children
                    for child in node.named_children(&mut cursor) {
                        stack.push(child);
                    }
                    // Function parameters: treat as definitions
                    if node.kind() == "function_item" {
                        if let Some(body) = node.child_by_field_name("body") {
                            ignored_use_byte_ranges.push((node.start_byte(), body.start_byte()));
                        }
                        if let Some(params_node) = node.child_by_field_name("parameters") {
                            for param in params_node.named_children(&mut cursor) {
                                if param.kind() == "parameter"
                                    && let Some(pat) = param.child_by_field_name("pattern")
                                {
                                    let name = pat.utf8_text(source.as_bytes()).unwrap_or("");
                                    if !name.is_empty() {
                                        let sl = crate::languages::util::byte_to_line(
                                            &line_offsets,
                                            pat.start_byte(),
                                        );
                                        let node_id = format!("{}:def:{}:{}", path, name, sl);
                                        if seen_node_ids.insert(node_id.clone()) {
                                            nodes.push(DfgNode {
                                                id: node_id.clone(),
                                                name: name.to_string(),
                                                file: path.to_string(),
                                                line: sl,
                                            });
                                            def_records_by_name
                                                .entry(name.to_string())
                                                .or_default()
                                                .push((sl, node_id.clone()));
                                            param_def_records_by_name
                                                .entry(name.to_string())
                                                .or_default()
                                                .push((sl, node_id.clone()));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // Assignment expressions: x = ... as definitions
                    if node.kind() == "assignment_expression"
                        && let Some(lhs) = node.child_by_field_name("left")
                        && lhs.kind() == "identifier"
                    {
                        let name = lhs.utf8_text(source.as_bytes()).unwrap_or("");
                        if !name.is_empty() {
                            let sl = crate::languages::util::byte_to_line(
                                &line_offsets,
                                lhs.start_byte(),
                            );
                            let node_id = format!("{}:def:{}:{}", path, name, sl);
                            if seen_node_ids.insert(node_id.clone()) {
                                nodes.push(DfgNode {
                                    id: node_id.clone(),
                                    name: name.to_string(),
                                    file: path.to_string(),
                                    line: sl,
                                });
                                def_records_by_name
                                    .entry(name.to_string())
                                    .or_default()
                                    .push((sl, node_id.clone()));
                            }
                            def_lines_by_name
                                .entry(name.to_string())
                                .or_default()
                                .insert(sl);
                        }
                    }
                }
            }
        }
        // Definitions (let) and uses of defined vars
        // Reserved keywords to skip as uses
        let reserved = [
            "let", "mut", "fn", "pub", "self", "super", "crate", "if", "else", "match", "for",
            "while", "loop", "return", "use", "struct", "enum", "trait", "impl", "mod", "as", "in",
            "true", "false",
        ];
        // First pass: collect let-definitions (including `let mut x = ...`).
        let re_let_def =
            regex::Regex::new(r"^\s*let(?:\s+mut)?\s+([A-Za-z_][A-Za-z0-9_]*)\b").unwrap();
        for (idx, line) in source.lines().enumerate() {
            let line_no = (idx + 1) as u32;
            let Some(cap) = re_let_def.captures(line) else {
                continue;
            };
            let Some(name) = cap.get(1).map(|m| m.as_str()) else {
                continue;
            };
            let node_id = format!("{}:def:{}:{}", path, name, line_no);
            if seen_node_ids.insert(node_id.clone()) {
                nodes.push(DfgNode {
                    id: node_id.clone(),
                    name: name.to_string(),
                    file: path.to_string(),
                    line: line_no,
                });
                def_records_by_name
                    .entry(name.to_string())
                    .or_default()
                    .push((line_no, node_id.clone()));
            }
            // Track definition line
            def_lines_by_name
                .entry(name.to_string())
                .or_default()
                .insert(line_no);
        }
        for records in def_records_by_name.values_mut() {
            records.sort_by_key(|(line, _)| *line);
        }
        let control_ranges = collect_control_ranges_rust(source);

        // Lightweight alias propagation: a = b; / let a = b;
        // Add conservative data edge def(b) -> def(a) at assignment lines.
        let re_alias_let = regex::Regex::new(
            r"^\s*let(?:\s+mut)?\s+([A-Za-z_][A-Za-z0-9_]*)(?:\s*:[^=]+)?\s*=\s*([A-Za-z_][A-Za-z0-9_]*)\b",
        )
        .unwrap();
        let re_alias_assign =
            regex::Regex::new(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*([A-Za-z_][A-Za-z0-9_]*)\b")
                .unwrap();
        for (idx, line) in source.lines().enumerate() {
            let line_no = (idx + 1) as u32;
            let pair = if let Some(cap) = re_alias_let.captures(line) {
                Some((
                    cap.get(1).unwrap().as_str().to_string(),
                    cap.get(2).unwrap().as_str().to_string(),
                ))
            } else {
                re_alias_assign.captures(line).map(|cap| {
                    (
                        cap.get(1).unwrap().as_str().to_string(),
                        cap.get(2).unwrap().as_str().to_string(),
                    )
                })
            };
            let Some((lhs, rhs)) = pair else {
                continue;
            };
            if lhs == rhs {
                continue;
            }
            let Some(lhs_def_id) = def_records_by_name.get(&lhs).and_then(|recs| {
                recs.iter()
                    .rev()
                    .find(|(ln, _)| *ln == line_no)
                    .map(|(_, id)| id.clone())
            }) else {
                continue;
            };
            let rhs_defs =
                reaching_def_ids_ssa_like(&rhs, line_no, &def_records_by_name, &control_ranges);
            for rhs_def_id in rhs_defs {
                edges.push(DfgEdge {
                    from: rhs_def_id,
                    to: lhs_def_id.clone(),
                    kind: DependencyKind::Data,
                });
            }
        }

        // Second pass: collect uses and link to reaching defs (SSA-like)
        let token_re = regex::Regex::new(r"[A-Za-z_][A-Za-z0-9_]*").unwrap();
        for m in token_re.find_iter(source) {
            let token = m.as_str();
            if reserved.contains(&token) {
                continue;
            }
            if ignored_use_byte_ranges
                .iter()
                .any(|(start, end)| m.start() >= *start && m.start() < *end)
            {
                continue;
            }
            let line_no = crate::languages::util::byte_to_line(&line_offsets, m.start());
            // Skip uses on same line as definition
            if def_lines_by_name
                .get(token)
                .is_some_and(|lines| lines.contains(&line_no))
            {
                continue;
            }
            let reaching = reaching_def_ids_ssa_like_with_same_line_params(
                token,
                line_no,
                &def_records_by_name,
                &param_def_records_by_name,
                &control_ranges,
            );
            if !reaching.is_empty() {
                let node_id = format!("{}:use:{}:{}", path, token, line_no);
                if seen_node_ids.insert(node_id.clone()) {
                    nodes.push(DfgNode {
                        id: node_id.clone(),
                        name: token.to_string(),
                        file: path.to_string(),
                        line: line_no,
                    });
                }
                for def_id in reaching {
                    edges.push(DfgEdge {
                        from: def_id,
                        to: node_id.clone(),
                        kind: DependencyKind::Data,
                    });
                }
            }
        }
        // Add control dependency nodes/edges from precomputed control ranges.
        let data_node_count = nodes.len();
        for (start_ln, end_ln) in &control_ranges {
            let ctrl_id = format!("{}:ctrl:{}:{}", path, start_ln, end_ln);
            if seen_node_ids.insert(ctrl_id.clone()) {
                nodes.push(DfgNode {
                    id: ctrl_id.clone(),
                    name: "control".to_string(),
                    file: path.to_string(),
                    line: *start_ln,
                });
            }
            for nd in &nodes[..data_node_count] {
                if nd.line >= *start_ln && nd.line <= *end_ln {
                    edges.push(DfgEdge {
                        from: ctrl_id.clone(),
                        to: nd.id.clone(),
                        kind: DependencyKind::Control,
                    });
                }
            }
        }
        DataFlowGraph { nodes, edges }
    }
}

/// Ruby Data Flow Graph builder: supports params, assignments, return, and control dependencies.
pub struct RubyDfgBuilder;

impl DfgBuilder for RubyDfgBuilder {
    fn build(path: &str, source: &str) -> DataFlowGraph {
        use regex::Regex;
        use std::collections::{HashMap, HashSet};
        // Initialize DFG containers
        let mut nodes: Vec<DfgNode> = Vec::new();
        let mut edges: Vec<DfgEdge> = Vec::new();
        let mut def_records_by_name: HashMap<String, Vec<(u32, String)>> = HashMap::new();
        let mut def_lines_by_name: HashMap<String, HashSet<u32>> = HashMap::new();
        let mut seen_node_ids: HashSet<String> = HashSet::new();
        let reserved = [
            "if", "else", "elsif", "end", "return", "def", "class", "module",
        ];

        // Parse parameters via regex
        let fn_re =
            Regex::new(r"^\s*def\s+[^\s(]+\s*(?:\(([^)]*)\)|\s+([*&A-Za-z_][^#\n;]*))?$").unwrap();
        for (idx, line) in source.lines().enumerate() {
            let line_no = (idx + 1) as u32;
            if let Some(cap) = fn_re.captures(line) {
                let params = cap
                    .get(1)
                    .or_else(|| cap.get(2))
                    .map(|m| strip_ruby_inline_comment(m.as_str()))
                    .unwrap_or_default();
                for p in params.split(',') {
                    let Some(name) = parse_ruby_param_name(p) else {
                        continue;
                    };
                    if !name.is_empty() {
                        let node_id = format!("{}:def:{}:{}", path, name, line_no);
                        if seen_node_ids.insert(node_id.clone()) {
                            nodes.push(DfgNode {
                                id: node_id.clone(),
                                name: name.clone(),
                                file: path.to_string(),
                                line: line_no,
                            });
                            def_records_by_name
                                .entry(name.clone())
                                .or_default()
                                .push((line_no, node_id));
                        }
                        def_lines_by_name.entry(name).or_default().insert(line_no);
                    }
                }
            }
        }

        for records in def_records_by_name.values_mut() {
            records.sort_by_key(|(line, _)| *line);
        }
        let control_ranges = collect_control_ranges_ruby(source);

        // Capture assignments and their RHS uses, then define LHS (SSA-like ordering).
        let assign_re =
            Regex::new(r"^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*([a-zA-Z_][a-zA-Z0-9_]*)").unwrap();
        for (idx, line) in source.lines().enumerate() {
            let line_no = (idx + 1) as u32;
            if let Some(cap) = assign_re.captures(line) {
                let lhs = cap.get(1).unwrap().as_str();
                let rhs = cap.get(2).unwrap().as_str();

                let reaching_rhs =
                    reaching_def_ids_ssa_like(rhs, line_no, &def_records_by_name, &control_ranges);
                if !reaching_rhs.is_empty() {
                    let use_id = format!("{}:use:{}:{}", path, rhs, line_no);
                    if seen_node_ids.insert(use_id.clone()) {
                        nodes.push(DfgNode {
                            id: use_id.clone(),
                            name: rhs.to_string(),
                            file: path.to_string(),
                            line: line_no,
                        });
                    }
                    for def_id in &reaching_rhs {
                        edges.push(DfgEdge {
                            from: def_id.clone(),
                            to: use_id.clone(),
                            kind: DependencyKind::Data,
                        });
                    }
                }

                // LHS definition
                let def_id = format!("{}:def:{}:{}", path, lhs, line_no);
                if seen_node_ids.insert(def_id.clone()) {
                    nodes.push(DfgNode {
                        id: def_id.clone(),
                        name: lhs.to_string(),
                        file: path.to_string(),
                        line: line_no,
                    });
                    def_records_by_name
                        .entry(lhs.to_string())
                        .or_default()
                        .push((line_no, def_id.clone()));
                }
                def_lines_by_name
                    .entry(lhs.to_string())
                    .or_default()
                    .insert(line_no);

                // Lightweight alias propagation: a = b => def(b) -> def(a)
                if lhs != rhs {
                    for rhs_def_id in &reaching_rhs {
                        edges.push(DfgEdge {
                            from: rhs_def_id.clone(),
                            to: def_id.clone(),
                            kind: DependencyKind::Data,
                        });
                    }
                }
            }
        }

        for records in def_records_by_name.values_mut() {
            records.sort_by_key(|(line, _)| *line);
        }

        // Capture return uses
        let return_re = Regex::new(r"return\s+([a-zA-Z_][a-zA-Z0-9_]*)").unwrap();
        for (idx, line) in source.lines().enumerate() {
            let line_no = (idx + 1) as u32;
            if let Some(cap) = return_re.captures(line) {
                let name = cap.get(1).unwrap().as_str();
                if def_lines_by_name
                    .get(name)
                    .is_some_and(|s| s.contains(&line_no))
                {
                    continue;
                }
                let node_id = format!("{}:use:{}:{}", path, name, line_no);
                if seen_node_ids.insert(node_id.clone()) {
                    nodes.push(DfgNode {
                        id: node_id.clone(),
                        name: name.to_string(),
                        file: path.to_string(),
                        line: line_no,
                    });
                }
                let reaching =
                    reaching_def_ids_ssa_like(name, line_no, &def_records_by_name, &control_ranges);
                for def_id in reaching {
                    edges.push(DfgEdge {
                        from: def_id,
                        to: node_id.clone(),
                        kind: DependencyKind::Data,
                    });
                }
            }
        }

        // Capture general uses beyond return (assignments, method calls, etc.)
        for (idx, line) in source.lines().enumerate() {
            let line_no = (idx + 1) as u32;
            for token in line.split(|c: char| !c.is_alphanumeric() && c != '_') {
                if token.is_empty() || reserved.contains(&token) {
                    continue;
                }
                // Skip if defined on this line
                if def_lines_by_name
                    .get(token)
                    .is_some_and(|s| s.contains(&line_no))
                {
                    continue;
                }
                let reaching = reaching_def_ids_ssa_like(
                    token,
                    line_no,
                    &def_records_by_name,
                    &control_ranges,
                );
                if reaching.is_empty() {
                    continue;
                }
                let use_id = format!("{}:use:{}:{}", path, token, line_no);
                if seen_node_ids.insert(use_id.clone()) {
                    nodes.push(DfgNode {
                        id: use_id.clone(),
                        name: token.to_string(),
                        file: path.to_string(),
                        line: line_no,
                    });
                }
                for def_id in reaching {
                    edges.push(DfgEdge {
                        from: def_id,
                        to: use_id.clone(),
                        kind: DependencyKind::Data,
                    });
                }
            }
        }

        // Add control dependency nodes/edges from precomputed control ranges.
        let data_count = nodes.len();
        for (start_ln, end_ln) in &control_ranges {
            let ctrl_id = format!("{}:ctrl:{}:{}", path, start_ln, end_ln);
            if seen_node_ids.insert(ctrl_id.clone()) {
                nodes.push(DfgNode {
                    id: ctrl_id.clone(),
                    name: "control".to_string(),
                    file: path.to_string(),
                    line: *start_ln,
                });
            }
            for nd in &nodes[..data_count] {
                if nd.line >= *start_ln && nd.line <= *end_ln {
                    edges.push(DfgEdge {
                        from: ctrl_id.clone(),
                        to: nd.id.clone(),
                        kind: DependencyKind::Control,
                    });
                }
            }
        }

        DataFlowGraph { nodes, edges }
    }
}
// Insert at PdgBuilder
use crate::ir::reference::Reference;

/// Per-input impact slice inside a function summary.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FunctionInputImpact {
    pub input_node_id: String,
    pub impacted_node_ids: Vec<String>,
}

/// Minimal function summary (input -> impact) derived from PDG data edges.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FunctionSummary {
    pub function_id: String,
    pub file: String,
    pub start_line: u32,
    pub end_line: u32,
    pub inputs: Vec<String>,
    pub flows: Vec<FunctionInputImpact>,
}

/// Builder for Program Dependence Graphs by merging DFG and call graph.
pub struct PdgBuilder;

fn push_unique_edge(
    pdg: &mut DataFlowGraph,
    seen_edges: &mut std::collections::HashSet<(String, String, DependencyKind)>,
    from: String,
    to: String,
    kind: DependencyKind,
) {
    if seen_edges.insert((from.clone(), to.clone(), kind.clone())) {
        pdg.edges.push(DfgEdge { from, to, kind });
    }
}

fn collect_nested_call_refs<'a>(
    outer_callee_id: &str,
    impacted_node_ids: &[String],
    refs: &'a [Reference],
    node_loc_by_id: &std::collections::HashMap<String, (String, u32)>,
) -> Vec<&'a Reference> {
    let impacted_locs: std::collections::HashSet<(String, u32)> = impacted_node_ids
        .iter()
        .filter_map(|id| node_loc_by_id.get(id).cloned())
        .collect();
    if impacted_locs.is_empty() {
        return Vec::new();
    }

    refs.iter()
        .filter(|nested| {
            nested.kind == crate::ir::reference::RefKind::Call
                && nested.provenance == crate::ir::reference::EdgeProvenance::CallGraph
                && nested.from.0 == outer_callee_id
                && impacted_locs.contains(&(nested.file.clone(), nested.line))
        })
        .collect()
}

fn has_nested_completion_candidate(
    outer_callee_id: &str,
    impacted_node_ids: &[String],
    refs: &[Reference],
    node_loc_by_id: &std::collections::HashMap<String, (String, u32)>,
) -> bool {
    !collect_nested_call_refs(outer_callee_id, impacted_node_ids, refs, node_loc_by_id).is_empty()
}

#[allow(clippy::too_many_arguments)]
fn push_nested_completion_bridges(
    pdg: &mut DataFlowGraph,
    seen_edges: &mut std::collections::HashSet<(String, String, DependencyKind)>,
    outer_callee_id: &str,
    impacted_node_ids: &[String],
    callsite_defs: &[String],
    refs: &[Reference],
    summary_by_fn: &std::collections::HashMap<String, FunctionSummary>,
    node_loc_by_id: &std::collections::HashMap<String, (String, u32)>,
    uses_by_loc: &std::collections::HashMap<(String, u32), Vec<String>>,
    remaining_hops: usize,
) -> bool {
    if callsite_defs.is_empty() || remaining_hops == 0 {
        return false;
    }

    let impacted_set: std::collections::HashSet<&str> =
        impacted_node_ids.iter().map(String::as_str).collect();
    let mut propagated_any = false;

    for nested_ref in
        collect_nested_call_refs(outer_callee_id, impacted_node_ids, refs, node_loc_by_id)
    {
        let Some(nested_summary) = summary_by_fn.get(&nested_ref.to.0) else {
            continue;
        };

        let nested_callsite_uses = collect_callsite_uses(
            uses_by_loc,
            nested_ref.file.as_str(),
            nested_ref.line,
            nested_summary.inputs.len(),
        );

        let mut relevant_bindings: Vec<(String, String)> = if nested_callsite_uses.len()
            == nested_summary.inputs.len()
            && !nested_callsite_uses.is_empty()
        {
            nested_summary
                .inputs
                .iter()
                .zip(nested_callsite_uses.iter())
                .filter(|(_, use_id)| impacted_set.contains(use_id.as_str()))
                .map(|(input, use_id)| (use_id.clone(), input.clone()))
                .collect()
        } else {
            Vec::new()
        };

        if relevant_bindings.is_empty() && nested_summary.inputs.len() == 1 {
            let binding_sources: Vec<String> = if nested_callsite_uses.len() == 1 {
                vec![nested_callsite_uses[0].clone()]
            } else {
                impacted_node_ids
                    .iter()
                    .filter(|impacted| {
                        node_loc_by_id
                            .get(impacted.as_str())
                            .is_some_and(|(file, line)| {
                                *file == nested_ref.file && *line == nested_ref.line
                            })
                    })
                    .cloned()
                    .collect()
            };
            let nested_input = nested_summary.inputs[0].clone();
            relevant_bindings = binding_sources
                .into_iter()
                .map(|binding_source| (binding_source, nested_input.clone()))
                .collect();
        }

        for (binding_source, nested_input) in relevant_bindings {
            push_unique_edge(
                pdg,
                seen_edges,
                binding_source,
                nested_input.clone(),
                DependencyKind::Data,
            );
            for nested_flow in nested_summary.flows.iter().filter(|flow| {
                flow.input_node_id == nested_input && !flow.impacted_node_ids.is_empty()
            }) {
                propagated_any = true;
                for nested_impacted in &nested_flow.impacted_node_ids {
                    for d in callsite_defs {
                        push_unique_edge(
                            pdg,
                            seen_edges,
                            nested_impacted.clone(),
                            d.clone(),
                            DependencyKind::Data,
                        );
                    }
                }
                propagated_any |= push_nested_completion_bridges(
                    pdg,
                    seen_edges,
                    nested_ref.to.0.as_str(),
                    &nested_flow.impacted_node_ids,
                    callsite_defs,
                    refs,
                    summary_by_fn,
                    node_loc_by_id,
                    uses_by_loc,
                    remaining_hops.saturating_sub(1),
                );
            }
        }
    }

    propagated_any
}

fn collect_callsite_nodes(
    nodes_by_loc: &std::collections::HashMap<(String, u32), Vec<String>>,
    file: &str,
    line: u32,
    expected_len: usize,
    preferred_offsets: &[i32],
) -> Vec<String> {
    let mut collected = Vec::new();
    for offset in preferred_offsets {
        let candidate_line = if *offset < 0 {
            let delta = offset.unsigned_abs();
            if delta > line {
                continue;
            }
            line - delta
        } else {
            line.saturating_add(*offset as u32)
        };
        let key = (file.to_string(), candidate_line);
        let Some(node_ids) = nodes_by_loc.get(&key) else {
            continue;
        };
        collected.extend(node_ids.iter().cloned());
        if expected_len > 0 && collected.len() >= expected_len {
            break;
        }
    }
    collected
}

fn collect_exact_callsite_uses(
    uses_by_loc: &std::collections::HashMap<(String, u32), Vec<String>>,
    file: &str,
    line: u32,
    expected_len: usize,
) -> Vec<String> {
    collect_callsite_nodes(uses_by_loc, file, line, expected_len, &[0])
}

fn collect_callsite_uses(
    uses_by_loc: &std::collections::HashMap<(String, u32), Vec<String>>,
    file: &str,
    line: u32,
    expected_len: usize,
) -> Vec<String> {
    let exact = collect_exact_callsite_uses(uses_by_loc, file, line, expected_len);
    if expected_len == 0 || exact.len() >= expected_len {
        return exact;
    }
    collect_callsite_nodes(
        uses_by_loc,
        file,
        line,
        expected_len,
        &[0, 1, -1, 2, -2, 3, -3],
    )
}

fn collect_exact_callsite_defs(
    defs_by_loc: &std::collections::HashMap<(String, u32), Vec<String>>,
    file: &str,
    line: u32,
) -> Vec<String> {
    collect_callsite_nodes(defs_by_loc, file, line, 0, &[0])
}

fn collect_callsite_defs(
    defs_by_loc: &std::collections::HashMap<(String, u32), Vec<String>>,
    file: &str,
    line: u32,
) -> Vec<String> {
    let exact = collect_exact_callsite_defs(defs_by_loc, file, line);
    if !exact.is_empty() {
        return exact;
    }
    collect_callsite_nodes(defs_by_loc, file, line, 0, &[0, -1, 1, -2, 2])
}

fn filter_symbolic_propagation_refs<'a>(
    refs: &'a [Reference],
    defs_by_loc: &std::collections::HashMap<(String, u32), Vec<String>>,
    uses_by_loc: &std::collections::HashMap<(String, u32), Vec<String>>,
    summary_by_fn: &std::collections::HashMap<String, FunctionSummary>,
) -> Vec<&'a Reference> {
    let mut grouped: std::collections::BTreeMap<(String, String, String), Vec<&Reference>> =
        std::collections::BTreeMap::new();

    for reference in refs.iter().filter(|r| {
        r.kind == crate::ir::reference::RefKind::Call
            && r.provenance == crate::ir::reference::EdgeProvenance::CallGraph
    }) {
        grouped
            .entry((
                reference.from.0.clone(),
                reference.to.0.clone(),
                reference.file.clone(),
            ))
            .or_default()
            .push(reference);
    }

    let mut selected = Vec::new();
    for group in grouped.into_values() {
        let summary_input_count = group
            .first()
            .and_then(|reference| summary_by_fn.get(&reference.to.0))
            .map(|summary| summary.inputs.len())
            .unwrap_or_default()
            .max(1);

        let with_exact_defs_and_uses: Vec<&Reference> = group
            .iter()
            .copied()
            .filter(|reference| {
                let exact_defs = collect_exact_callsite_defs(
                    defs_by_loc,
                    reference.file.as_str(),
                    reference.line,
                );
                let exact_uses = collect_exact_callsite_uses(
                    uses_by_loc,
                    reference.file.as_str(),
                    reference.line,
                    summary_input_count,
                );
                !exact_defs.is_empty()
                    && !exact_uses.is_empty()
                    && exact_uses.len() >= summary_input_count
            })
            .collect();
        if !with_exact_defs_and_uses.is_empty() {
            selected.extend(with_exact_defs_and_uses);
            continue;
        }

        let with_exact_defs: Vec<&Reference> = group
            .iter()
            .copied()
            .filter(|reference| {
                !collect_exact_callsite_defs(defs_by_loc, reference.file.as_str(), reference.line)
                    .is_empty()
            })
            .collect();
        if !with_exact_defs.is_empty() {
            selected.extend(with_exact_defs);
            continue;
        }

        let with_exact_uses: Vec<&Reference> = group
            .iter()
            .copied()
            .filter(|reference| {
                let exact_uses = collect_exact_callsite_uses(
                    uses_by_loc,
                    reference.file.as_str(),
                    reference.line,
                    summary_input_count,
                );
                !exact_uses.is_empty() && exact_uses.len() >= summary_input_count
            })
            .collect();
        if !with_exact_uses.is_empty() {
            selected.extend(with_exact_uses);
            continue;
        }

        selected.extend(group);
    }

    selected
}

impl PdgBuilder {
    /// Build a PDG by combining the data/control flow graph and call references.
    pub fn build(dfg: &DataFlowGraph, refs: &[Reference]) -> DataFlowGraph {
        // Start with existing DFG
        let mut pdg = dfg.clone();
        // Add call edges as data dependencies
        for r in refs {
            pdg.edges.push(DfgEdge {
                from: r.from.0.clone(),
                to: r.to.0.clone(),
                kind: DependencyKind::Data,
            });
        }
        pdg
    }

    /// Augment PDG with symbolic propagation bridges.
    /// Heuristics:
    /// - Connect variable uses at call sites to callee symbols.
    /// - Connect callee symbols to variable definitions at call sites (returned value captured).
    /// - Connect function/method symbols to all variable def/use nodes within their range.
    pub fn augment_symbolic_propagation(
        pdg: &mut DataFlowGraph,
        refs: &[Reference],
        index: &crate::ir::reference::SymbolIndex,
    ) {
        use crate::ir::SymbolKind;
        // Index DFG nodes by (file,line)
        let mut uses_by_loc: std::collections::HashMap<(String, u32), Vec<String>> =
            std::collections::HashMap::new();
        let mut defs_by_loc: std::collections::HashMap<(String, u32), Vec<String>> =
            std::collections::HashMap::new();
        for n in &pdg.nodes {
            let key = (n.file.clone(), n.line);
            if n.id.contains(":use:") {
                uses_by_loc
                    .entry(key.clone())
                    .or_default()
                    .push(n.id.clone());
            }
            if n.id.contains(":def:") {
                defs_by_loc.entry(key).or_default().push(n.id.clone());
            }
        }

        let mut seen_edges: std::collections::HashSet<(String, String, DependencyKind)> = pdg
            .edges
            .iter()
            .map(|e| (e.from.clone(), e.to.clone(), e.kind.clone()))
            .collect();
        let node_loc_by_id: std::collections::HashMap<String, (String, u32)> = pdg
            .nodes
            .iter()
            .map(|node| (node.id.clone(), (node.file.clone(), node.line)))
            .collect();

        // Precompute minimal function summaries and map by callee symbol ID.
        let summaries = Self::build_function_summaries(pdg, index);
        let mut summary_by_fn: std::collections::HashMap<String, FunctionSummary> =
            std::collections::HashMap::new();
        for s in summaries {
            summary_by_fn.insert(s.function_id.clone(), s);
        }

        let symbolic_refs =
            filter_symbolic_propagation_refs(refs, &defs_by_loc, &uses_by_loc, &summary_by_fn);

        // 1) Call-site bridges + summary-connected inter-procedural bridges
        for r in symbolic_refs {
            let summary_input_count = summary_by_fn
                .get(&r.to.0)
                .map(|summary| summary.inputs.len())
                .unwrap_or_default();
            let callsite_uses = collect_callsite_uses(
                &uses_by_loc,
                r.file.as_str(),
                r.line,
                summary_input_count.max(1),
            );
            let callsite_defs = collect_callsite_defs(&defs_by_loc, r.file.as_str(), r.line);

            for u in &callsite_uses {
                push_unique_edge(
                    pdg,
                    &mut seen_edges,
                    u.clone(),
                    r.to.0.clone(),
                    DependencyKind::Data,
                );
            }
            for d in &callsite_defs {
                push_unique_edge(
                    pdg,
                    &mut seen_edges,
                    r.to.0.clone(),
                    d.clone(),
                    DependencyKind::Data,
                );
            }

            // Connect call-site propagation through callee summary (input -> impacted).
            if let Some(summary) = summary_by_fn.get(&r.to.0) {
                let active_flows: Vec<&FunctionInputImpact> = summary
                    .flows
                    .iter()
                    .filter(|flow| !flow.impacted_node_ids.is_empty())
                    .collect();
                if active_flows.is_empty() {
                    continue;
                }

                if callsite_uses.len() == summary.inputs.len() && !callsite_uses.is_empty() {
                    let use_by_input: std::collections::HashMap<&str, &String> = summary
                        .inputs
                        .iter()
                        .zip(callsite_uses.iter())
                        .map(|(input, use_id)| (input.as_str(), use_id))
                        .collect();

                    for flow in &active_flows {
                        let Some(mapped_use) = use_by_input.get(flow.input_node_id.as_str()) else {
                            continue;
                        };
                        push_unique_edge(
                            pdg,
                            &mut seen_edges,
                            (*mapped_use).clone(),
                            flow.input_node_id.clone(),
                            DependencyKind::Data,
                        );
                        let requires_nested_validation = has_nested_completion_candidate(
                            r.to.0.as_str(),
                            &flow.impacted_node_ids,
                            refs,
                            &node_loc_by_id,
                        );
                        let nested_completion_found = push_nested_completion_bridges(
                            pdg,
                            &mut seen_edges,
                            r.to.0.as_str(),
                            &flow.impacted_node_ids,
                            &callsite_defs,
                            refs,
                            &summary_by_fn,
                            &node_loc_by_id,
                            &uses_by_loc,
                            2,
                        );
                        let can_bridge_to_callsite_defs =
                            !requires_nested_validation || nested_completion_found;
                        if can_bridge_to_callsite_defs {
                            for impacted in &flow.impacted_node_ids {
                                for d in &callsite_defs {
                                    push_unique_edge(
                                        pdg,
                                        &mut seen_edges,
                                        impacted.clone(),
                                        d.clone(),
                                        DependencyKind::Data,
                                    );
                                }
                            }
                        }
                        if callsite_defs.len() == 1 && can_bridge_to_callsite_defs {
                            push_unique_edge(
                                pdg,
                                &mut seen_edges,
                                (*mapped_use).clone(),
                                callsite_defs[0].clone(),
                                DependencyKind::Data,
                            );
                        }
                    }
                } else if summary.inputs.len() == 1 && callsite_uses.len() == 1 {
                    let only_use = callsite_uses[0].clone();
                    for flow in &active_flows {
                        push_unique_edge(
                            pdg,
                            &mut seen_edges,
                            only_use.clone(),
                            flow.input_node_id.clone(),
                            DependencyKind::Data,
                        );
                        let requires_nested_validation = has_nested_completion_candidate(
                            r.to.0.as_str(),
                            &flow.impacted_node_ids,
                            refs,
                            &node_loc_by_id,
                        );
                        let nested_completion_found = push_nested_completion_bridges(
                            pdg,
                            &mut seen_edges,
                            r.to.0.as_str(),
                            &flow.impacted_node_ids,
                            &callsite_defs,
                            refs,
                            &summary_by_fn,
                            &node_loc_by_id,
                            &uses_by_loc,
                            2,
                        );
                        let can_bridge_to_callsite_defs =
                            !requires_nested_validation || nested_completion_found;
                        if can_bridge_to_callsite_defs {
                            for impacted in &flow.impacted_node_ids {
                                for d in &callsite_defs {
                                    push_unique_edge(
                                        pdg,
                                        &mut seen_edges,
                                        impacted.clone(),
                                        d.clone(),
                                        DependencyKind::Data,
                                    );
                                }
                            }
                            if callsite_defs.len() == 1 {
                                push_unique_edge(
                                    pdg,
                                    &mut seen_edges,
                                    only_use.clone(),
                                    callsite_defs[0].clone(),
                                    DependencyKind::Data,
                                );
                            }
                        }
                    }
                } else if summary.inputs.len() == 1
                    && callsite_uses.is_empty()
                    && callsite_defs.len() == 1
                {
                    for flow in &active_flows {
                        let requires_nested_validation = has_nested_completion_candidate(
                            r.to.0.as_str(),
                            &flow.impacted_node_ids,
                            refs,
                            &node_loc_by_id,
                        );
                        let nested_completion_found = push_nested_completion_bridges(
                            pdg,
                            &mut seen_edges,
                            r.to.0.as_str(),
                            &flow.impacted_node_ids,
                            &callsite_defs,
                            refs,
                            &summary_by_fn,
                            &node_loc_by_id,
                            &uses_by_loc,
                            2,
                        );
                        if !requires_nested_validation || nested_completion_found {
                            for impacted in &flow.impacted_node_ids {
                                push_unique_edge(
                                    pdg,
                                    &mut seen_edges,
                                    impacted.clone(),
                                    callsite_defs[0].clone(),
                                    DependencyKind::Data,
                                );
                            }
                        }
                    }
                }
            }
        }
        // 2) Intra-function bridges: symbol -> all DFG nodes within its span
        for s in &index.symbols {
            if !matches!(s.kind, SymbolKind::Function | SymbolKind::Method) {
                continue;
            }
            let in_span_node_ids: Vec<String> = pdg
                .nodes
                .iter()
                .filter(|n| {
                    n.file == s.file && n.line >= s.range.start_line && n.line <= s.range.end_line
                })
                .map(|n| n.id.clone())
                .collect();
            for node_id in in_span_node_ids {
                push_unique_edge(
                    pdg,
                    &mut seen_edges,
                    s.id.0.clone(),
                    node_id,
                    DependencyKind::Data,
                );
            }
        }
    }

    /// Build minimal function summaries (input -> impacted nodes) from PDG data edges.
    ///
    /// Input heuristic:
    /// - in-range def nodes with no incoming in-range data edges.
    ///
    /// Impact heuristic:
    /// - nodes reachable from each input via in-range data edges (excluding the input itself).
    pub fn build_function_summaries(
        pdg: &DataFlowGraph,
        index: &crate::ir::reference::SymbolIndex,
    ) -> Vec<FunctionSummary> {
        use crate::ir::SymbolKind;
        use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};

        let mut nodes_by_id: HashMap<&str, &DfgNode> = HashMap::new();
        for n in &pdg.nodes {
            nodes_by_id.insert(n.id.as_str(), n);
        }

        let mut out_adj: HashMap<&str, Vec<&str>> = HashMap::new();
        let mut in_adj: HashMap<&str, Vec<&str>> = HashMap::new();
        for e in &pdg.edges {
            if e.kind != DependencyKind::Data {
                continue;
            }
            if nodes_by_id.contains_key(e.from.as_str()) && nodes_by_id.contains_key(e.to.as_str())
            {
                out_adj
                    .entry(e.from.as_str())
                    .or_default()
                    .push(e.to.as_str());
                in_adj
                    .entry(e.to.as_str())
                    .or_default()
                    .push(e.from.as_str());
            }
        }

        let mut summaries = Vec::new();
        for s in &index.symbols {
            if !matches!(s.kind, SymbolKind::Function | SymbolKind::Method) {
                continue;
            }

            let in_range_ids: Vec<String> = pdg
                .nodes
                .iter()
                .filter(|n| {
                    n.file == s.file
                        && n.line >= s.range.start_line
                        && n.line <= s.range.end_line
                        && (n.id.contains(":def:") || n.id.contains(":use:"))
                })
                .map(|n| n.id.clone())
                .collect();
            if in_range_ids.is_empty() {
                continue;
            }
            let in_range_set: HashSet<&str> = in_range_ids.iter().map(|id| id.as_str()).collect();

            let mut param_like_inputs: Vec<String> = Vec::new();
            for id in &in_range_ids {
                if !id.contains(":def:") {
                    continue;
                }
                if nodes_by_id
                    .get(id.as_str())
                    .is_none_or(|n| n.line != s.range.start_line)
                {
                    continue;
                }
                if !param_like_inputs.iter().any(|seen| seen == id) {
                    param_like_inputs.push(id.clone());
                }
            }

            let inputs: Vec<String> = if !param_like_inputs.is_empty() {
                // Prefer parameter-like defs on function start line as summary inputs.
                param_like_inputs
            } else {
                // Fallback: entry defs with no incoming in-range data edges.
                let mut roots = Vec::new();
                for id in &in_range_ids {
                    if !id.contains(":def:") {
                        continue;
                    }
                    let is_root = in_adj
                        .get(id.as_str())
                        .map(|froms| froms.iter().all(|f| !in_range_set.contains(*f)))
                        .unwrap_or(true);
                    if is_root && !roots.iter().any(|seen| seen == id) {
                        roots.push(id.clone());
                    }
                }
                roots
            };
            if inputs.is_empty() {
                continue;
            }

            let mut flows = Vec::new();
            for input in &inputs {
                let mut q: VecDeque<&str> = VecDeque::new();
                let mut seen: HashSet<&str> = HashSet::new();
                q.push_back(input.as_str());
                seen.insert(input.as_str());

                let mut impacted: BTreeSet<String> = BTreeSet::new();
                while let Some(cur) = q.pop_front() {
                    for next in out_adj.get(cur).cloned().unwrap_or_default() {
                        if !in_range_set.contains(next) || seen.contains(next) {
                            continue;
                        }
                        seen.insert(next);
                        q.push_back(next);
                        if next != input.as_str() {
                            impacted.insert(next.to_string());
                        }
                    }
                }

                flows.push(FunctionInputImpact {
                    input_node_id: input.clone(),
                    impacted_node_ids: impacted.into_iter().collect(),
                });
            }

            summaries.push(FunctionSummary {
                function_id: s.id.0.clone(),
                file: s.file.clone(),
                start_line: s.range.start_line,
                end_line: s.range.end_line,
                inputs,
                flows,
            });
        }

        summaries
    }
}

fn collect_control_ranges_rust(source: &str) -> Vec<(u32, u32)> {
    let spec = crate::ts_core::load_rust_spec();
    let compiled = match crate::ts_core::compile_queries_rust(&spec) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };
    let Some(ctrl_q) = &compiled.control else {
        return Vec::new();
    };

    let runner = crate::ts_core::QueryRunner::new_rust();
    let offs = crate::languages::util::line_offsets(source);
    let mut out = Vec::new();
    for caps in runner.run_captures(source, ctrl_q) {
        if let Some(c0) = caps.first() {
            let start_ln = crate::languages::util::byte_to_line(&offs, c0.start);
            let end_ln = crate::languages::util::byte_to_line(&offs, c0.end.saturating_sub(1));
            out.push((start_ln, end_ln));
        }
    }
    out.sort_unstable();
    out.dedup();
    out
}

fn collect_control_ranges_ruby(source: &str) -> Vec<(u32, u32)> {
    let spec = crate::ts_core::load_ruby_spec();
    let compiled = match crate::ts_core::compile_queries_ruby(&spec) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };
    let Some(ctrl_q) = &compiled.control else {
        return Vec::new();
    };

    let runner = crate::ts_core::QueryRunner::new_ruby();
    let offs = crate::languages::util::line_offsets(source);
    let mut out = Vec::new();
    for caps in runner.run_captures(source, ctrl_q) {
        if let Some(c0) = caps.first() {
            let start_ln = crate::languages::util::byte_to_line(&offs, c0.start);
            let end_ln = crate::languages::util::byte_to_line(&offs, c0.end.saturating_sub(1));
            out.push((start_ln, end_ln));
        }
    }

    // Text fallback for if/elsif/else...end ranges to stabilize branch merges.
    let mut if_stack: Vec<u32> = Vec::new();
    for (idx, raw) in source.lines().enumerate() {
        let line_no = (idx + 1) as u32;
        let t = raw.trim_start();
        if t.starts_with("if ") || t == "if" || t.starts_with("unless ") || t == "unless" {
            if_stack.push(line_no);
            continue;
        }
        if t.starts_with("end")
            && let Some(start_ln) = if_stack.pop()
        {
            out.push((start_ln, line_no));
        }
    }

    out.sort_unstable();
    out.dedup();
    out
}

fn reaching_def_ids_ssa_like(
    name: &str,
    use_line: u32,
    def_records_by_name: &std::collections::HashMap<String, Vec<(u32, String)>>,
    control_ranges: &[(u32, u32)],
) -> Vec<String> {
    let Some(records) = def_records_by_name.get(name) else {
        return Vec::new();
    };

    let mut prior: Vec<(u32, String)> = records
        .iter()
        .filter(|(line, _)| *line < use_line)
        .cloned()
        .collect();
    if prior.is_empty() {
        return Vec::new();
    }
    prior.sort_by_key(|(line, _)| *line);

    let latest_line = prior.last().map(|(line, _)| *line).unwrap_or(0);
    let mut selected: std::collections::BTreeSet<String> = prior
        .iter()
        .filter(|(line, _)| *line == latest_line)
        .map(|(_, id)| id.clone())
        .collect();

    // SSA-like + branch stabilization:
    // if the latest reaching def is inside a completed control range before this use,
    // include all defs of the symbol from that control range (branch-merge approximation).
    // Additionally, when only one def is found in that range, include the last pre-range def
    // to model partial assignment paths (e.g. `if cond { x = ... }` without `else`).
    for (start, end) in control_ranges {
        if *end >= use_line || latest_line < *start || latest_line > *end {
            continue;
        }

        let mut in_range_defs: Vec<&String> = Vec::new();
        for (line, id) in &prior {
            if *line >= *start && *line <= *end {
                selected.insert(id.clone());
                in_range_defs.push(id);
            }
        }

        if in_range_defs.len() <= 1
            && let Some((_, pre_id)) = prior.iter().rev().find(|(line, _)| *line < *start)
        {
            selected.insert(pre_id.clone());
        }
    }

    selected.into_iter().collect()
}

fn reaching_def_ids_ssa_like_with_same_line_params(
    name: &str,
    use_line: u32,
    def_records_by_name: &std::collections::HashMap<String, Vec<(u32, String)>>,
    param_def_records_by_name: &std::collections::HashMap<String, Vec<(u32, String)>>,
    control_ranges: &[(u32, u32)],
) -> Vec<String> {
    let reaching = reaching_def_ids_ssa_like(name, use_line, def_records_by_name, control_ranges);
    if !reaching.is_empty() {
        return reaching;
    }

    let Some(param_records) = param_def_records_by_name.get(name) else {
        return Vec::new();
    };

    let mut same_line_params: Vec<String> = param_records
        .iter()
        .filter(|(line, _)| *line == use_line)
        .map(|(_, id)| id.clone())
        .collect();
    same_line_params.sort();
    same_line_params.dedup();
    same_line_params
}

#[cfg(test)]
mod pdg_tests {
    use super::*;
    use crate::ir::SymbolId;
    use crate::ir::reference::Reference;

    #[test]
    fn build_empty_pdg() {
        let dfg = DataFlowGraph {
            nodes: Vec::new(),
            edges: Vec::new(),
        };
        let refs: Vec<Reference> = Vec::new();
        let pdg = PdgBuilder::build(&dfg, &refs);
        assert!(pdg.nodes.is_empty());
        assert!(pdg.edges.is_empty());
    }

    #[test]
    fn build_pdg_with_refs() {
        // Prepare a dummy reference
        let from_id = SymbolId::new("rust", "f.rs", &crate::ir::SymbolKind::Function, "foo", 1);
        let to_id = SymbolId::new("rust", "f.rs", &crate::ir::SymbolKind::Function, "bar", 5);
        let r = Reference {
            from: from_id.clone(),
            to: to_id.clone(),
            kind: crate::ir::reference::RefKind::Call,
            file: "f.rs".to_string(),
            line: 10,
            certainty: crate::ir::reference::EdgeCertainty::Confirmed,
            provenance: crate::ir::reference::EdgeProvenance::CallGraph,
        };
        let dfg = DataFlowGraph {
            nodes: Vec::new(),
            edges: Vec::new(),
        };
        let pdg = PdgBuilder::build(&dfg, &[r]);
        assert_eq!(pdg.edges.len(), 1);
        let e = &pdg.edges[0];
        assert_eq!(&e.from, &from_id.0);
        assert_eq!(&e.to, &to_id.0);
        assert_eq!(e.kind, DependencyKind::Data);
    }

    #[test]
    fn pdg_includes_control_and_call_edges() {
        // Prepare a simple DFG with one let and one use, plus a call ref
        let mut dfg = DataFlowGraph {
            nodes: Vec::new(),
            edges: Vec::new(),
        };
        // Add a control node
        dfg.nodes.push(DfgNode {
            id: "f.rs:ctrl:2:4".to_string(),
            name: "control".to_string(),
            file: "f.rs".to_string(),
            line: 2,
        });
        // Add a def/use node
        dfg.nodes.push(DfgNode {
            id: "f.rs:def: x:2".to_string(),
            name: "x".to_string(),
            file: "f.rs".to_string(),
            line: 2,
        });
        // No edges in DFG
        let ref_sym = Reference {
            from: crate::ir::SymbolId("rust:f.rs:fn:foo:1".to_string()),
            to: crate::ir::SymbolId("rust:f.rs:fn:bar:1".to_string()),
            kind: crate::ir::reference::RefKind::Call,
            file: "f.rs".to_string(),
            line: 10,
            certainty: crate::ir::reference::EdgeCertainty::Confirmed,
            provenance: crate::ir::reference::EdgeProvenance::CallGraph,
        };
        let pdg = PdgBuilder::build(&dfg, std::slice::from_ref(&ref_sym));
        // Check call edge added
        assert!(pdg.edges.iter().any(|e| e.from == ref_sym.from.0
            && e.to == ref_sym.to.0
            && e.kind == DependencyKind::Data));
        // Check control edge remains
        // Control edges were not in DFG; here we only check call edges merge
        // The control node should still be present
        assert!(pdg.nodes.iter().any(|n| n.id == "f.rs:ctrl:2:4"));
    }

    #[test]
    fn propagation_connects_summary_interprocedurally() {
        use crate::ir::{Symbol, SymbolKind, TextRange};

        let mut pdg = DataFlowGraph {
            nodes: vec![
                DfgNode {
                    id: "f.rs:use:x:10".to_string(),
                    name: "x".to_string(),
                    file: "f.rs".to_string(),
                    line: 10,
                },
                DfgNode {
                    id: "f.rs:def:y:10".to_string(),
                    name: "y".to_string(),
                    file: "f.rs".to_string(),
                    line: 10,
                },
                DfgNode {
                    id: "f.rs:def:a:1".to_string(),
                    name: "a".to_string(),
                    file: "f.rs".to_string(),
                    line: 1,
                },
                DfgNode {
                    id: "f.rs:use:a:2".to_string(),
                    name: "a".to_string(),
                    file: "f.rs".to_string(),
                    line: 2,
                },
            ],
            edges: vec![DfgEdge {
                from: "f.rs:def:a:1".to_string(),
                to: "f.rs:use:a:2".to_string(),
                kind: DependencyKind::Data,
            }],
        };

        let refs = vec![Reference {
            from: SymbolId("rust:f.rs:fn:caller:9".to_string()),
            to: SymbolId("rust:f.rs:fn:callee:1".to_string()),
            kind: crate::ir::reference::RefKind::Call,
            file: "f.rs".to_string(),
            line: 10,
            certainty: crate::ir::reference::EdgeCertainty::Confirmed,
            provenance: crate::ir::reference::EdgeProvenance::CallGraph,
        }];
        let index = crate::ir::reference::SymbolIndex::build(vec![Symbol {
            id: SymbolId("rust:f.rs:fn:callee:1".to_string()),
            name: "callee".to_string(),
            kind: SymbolKind::Function,
            file: "f.rs".to_string(),
            range: TextRange {
                start_line: 1,
                end_line: 3,
            },
            language: "rust".to_string(),
        }]);

        PdgBuilder::augment_symbolic_propagation(&mut pdg, &refs, &index);

        assert!(pdg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data && e.from == "f.rs:use:x:10" && e.to == "f.rs:def:a:1"
        }));
        assert!(pdg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data && e.from == "f.rs:use:a:2" && e.to == "f.rs:def:y:10"
        }));
        assert!(pdg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data && e.from == "f.rs:use:x:10" && e.to == "f.rs:def:y:10"
        }));
    }

    #[test]
    fn propagation_summary_bridge_maps_later_arg_without_leaking_earlier_arg() {
        use crate::ir::{Symbol, SymbolKind, TextRange};

        let mut pdg = DataFlowGraph {
            nodes: vec![
                DfgNode {
                    id: "f.rs:use:x:10".to_string(),
                    name: "x".to_string(),
                    file: "f.rs".to_string(),
                    line: 10,
                },
                DfgNode {
                    id: "f.rs:use:y:10".to_string(),
                    name: "y".to_string(),
                    file: "f.rs".to_string(),
                    line: 10,
                },
                DfgNode {
                    id: "f.rs:def:out:10".to_string(),
                    name: "out".to_string(),
                    file: "f.rs".to_string(),
                    line: 10,
                },
                DfgNode {
                    id: "f.rs:def:a:1".to_string(),
                    name: "a".to_string(),
                    file: "f.rs".to_string(),
                    line: 1,
                },
                DfgNode {
                    id: "f.rs:def:b:1".to_string(),
                    name: "b".to_string(),
                    file: "f.rs".to_string(),
                    line: 1,
                },
                DfgNode {
                    id: "f.rs:use:b:2".to_string(),
                    name: "b".to_string(),
                    file: "f.rs".to_string(),
                    line: 2,
                },
            ],
            edges: vec![DfgEdge {
                from: "f.rs:def:b:1".to_string(),
                to: "f.rs:use:b:2".to_string(),
                kind: DependencyKind::Data,
            }],
        };

        let refs = vec![Reference {
            from: SymbolId("rust:f.rs:fn:caller:9".to_string()),
            to: SymbolId("rust:f.rs:fn:callee:1".to_string()),
            kind: crate::ir::reference::RefKind::Call,
            file: "f.rs".to_string(),
            line: 10,
            certainty: crate::ir::reference::EdgeCertainty::Confirmed,
            provenance: crate::ir::reference::EdgeProvenance::CallGraph,
        }];
        let index = crate::ir::reference::SymbolIndex::build(vec![Symbol {
            id: SymbolId("rust:f.rs:fn:callee:1".to_string()),
            name: "callee".to_string(),
            kind: SymbolKind::Function,
            file: "f.rs".to_string(),
            range: TextRange {
                start_line: 1,
                end_line: 2,
            },
            language: "rust".to_string(),
        }]);

        PdgBuilder::augment_symbolic_propagation(&mut pdg, &refs, &index);

        assert!(pdg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data && e.from == "f.rs:use:y:10" && e.to == "f.rs:def:b:1"
        }));
        assert!(pdg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data && e.from == "f.rs:use:y:10" && e.to == "f.rs:def:out:10"
        }));
        assert!(!pdg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data && e.from == "f.rs:use:x:10" && e.to == "f.rs:def:b:1"
        }));
        assert!(!pdg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data && e.from == "f.rs:use:x:10" && e.to == "f.rs:def:out:10"
        }));
    }

    #[test]
    fn function_summary_minimal_input_to_impact() {
        use crate::ir::{Symbol, SymbolKind, TextRange};

        let dfg = RustDfgBuilder::build(
            "f.rs",
            "fn foo(a: i32) -> i32 {\n    let b = a;\n    return b;\n}\n",
        );
        let pdg = PdgBuilder::build(&dfg, &[]);

        let foo = Symbol {
            id: SymbolId::new("rust", "f.rs", &SymbolKind::Function, "foo", 1),
            name: "foo".to_string(),
            kind: SymbolKind::Function,
            file: "f.rs".to_string(),
            range: TextRange {
                start_line: 1,
                end_line: 4,
            },
            language: "rust".to_string(),
        };
        let index = crate::ir::reference::SymbolIndex::build(vec![foo]);

        let summaries = PdgBuilder::build_function_summaries(&pdg, &index);
        assert_eq!(summaries.len(), 1);
        let s = &summaries[0];
        assert_eq!(s.function_id, "rust:f.rs:fn:foo:1");
        assert!(s.inputs.iter().any(|id| id.ends_with(":def:a:1")));

        let flow = s
            .flows
            .iter()
            .find(|f| f.input_node_id.ends_with(":def:a:1"))
            .expect("flow for input a");
        assert!(
            flow.impacted_node_ids
                .iter()
                .any(|id| id.ends_with(":def:b:2"))
        );
        assert!(
            flow.impacted_node_ids
                .iter()
                .any(|id| id.ends_with(":use:b:3"))
        );
    }

    #[test]
    fn function_summary_tracks_same_line_parameter_use_in_single_line_function() {
        use crate::ir::{Symbol, SymbolKind, TextRange};

        let dfg = RustDfgBuilder::build("f.rs", "fn foo(a: i32) -> i32 { a + 1 }\n");
        assert!(
            dfg.nodes.iter().any(|n| n.id == "f.rs:use:a:1"),
            "single-line parameter use should be tracked"
        );
        assert!(
            dfg.edges.iter().any(|e| {
                e.kind == DependencyKind::Data && e.from == "f.rs:def:a:1" && e.to == "f.rs:use:a:1"
            }),
            "single-line parameter use should connect back to its parameter def"
        );

        let foo = Symbol {
            id: SymbolId::new("rust", "f.rs", &SymbolKind::Function, "foo", 1),
            name: "foo".to_string(),
            kind: SymbolKind::Function,
            file: "f.rs".to_string(),
            range: TextRange {
                start_line: 1,
                end_line: 1,
            },
            language: "rust".to_string(),
        };
        let index = crate::ir::reference::SymbolIndex::build(vec![foo]);
        let pdg = PdgBuilder::build(&dfg, &[]);
        let summaries = PdgBuilder::build_function_summaries(&pdg, &index);
        let s = summaries.first().expect("summary for foo");
        assert!(s.inputs.iter().any(|id| id.ends_with(":def:a:1")));
        let flow = s
            .flows
            .iter()
            .find(|f| f.input_node_id.ends_with(":def:a:1"))
            .expect("flow for param a");
        assert!(
            flow.impacted_node_ids
                .iter()
                .any(|id| id.ends_with(":use:a:1")),
            "single-line return expression should remain visible in summary impact"
        );
    }

    #[test]
    fn function_summary_prefers_parameter_inputs_over_local_roots() {
        use crate::ir::{Symbol, SymbolKind, TextRange};

        let dfg = RustDfgBuilder::build(
            "f.rs",
            "fn foo(a: i32) -> i32 {\n    let seed = 1;\n    let b = a + seed;\n    return b;\n}\n",
        );
        let pdg = PdgBuilder::build(&dfg, &[]);

        let foo = Symbol {
            id: SymbolId::new("rust", "f.rs", &SymbolKind::Function, "foo", 1),
            name: "foo".to_string(),
            kind: SymbolKind::Function,
            file: "f.rs".to_string(),
            range: TextRange {
                start_line: 1,
                end_line: 5,
            },
            language: "rust".to_string(),
        };
        let index = crate::ir::reference::SymbolIndex::build(vec![foo]);

        let summaries = PdgBuilder::build_function_summaries(&pdg, &index);
        let s = summaries.first().expect("summary for foo");

        assert!(s.inputs.iter().any(|id| id.ends_with(":def:a:1")));
        assert!(
            !s.inputs.iter().any(|id| id.ends_with(":def:seed:2")),
            "parameter-style input selection should suppress local root defs"
        );
    }

    #[test]
    fn function_summary_falls_back_to_root_defs_without_params() {
        use crate::ir::{Symbol, SymbolKind, TextRange};

        let dfg = RustDfgBuilder::build(
            "f.rs",
            "fn bar() -> i32 {\n    let seed = 1;\n    let out = seed;\n    return out;\n}\n",
        );
        let pdg = PdgBuilder::build(&dfg, &[]);

        let bar = Symbol {
            id: SymbolId::new("rust", "f.rs", &SymbolKind::Function, "bar", 1),
            name: "bar".to_string(),
            kind: SymbolKind::Function,
            file: "f.rs".to_string(),
            range: TextRange {
                start_line: 1,
                end_line: 5,
            },
            language: "rust".to_string(),
        };
        let index = crate::ir::reference::SymbolIndex::build(vec![bar]);

        let summaries = PdgBuilder::build_function_summaries(&pdg, &index);
        let s = summaries.first().expect("summary for bar");

        assert!(
            s.inputs.iter().any(|id| id.ends_with(":def:seed:2")),
            "fallback root-def input should remain for parameterless function"
        );
    }
}

// Unit tests for DFG
#[cfg(test)]
mod tests {
    use super::*;
    use crate::dfg::RubyDfgBuilder;

    #[test]
    fn build_empty_graph() {
        let dfg = RustDfgBuilder::build("foo.rs", "");
        assert!(dfg.nodes.is_empty(), "expected no nodes in empty source");
        assert!(dfg.edges.is_empty(), "expected no edges in empty source");
    }

    #[test]
    fn build_assignment_definitions() {
        let src = r#"
        let x = 1;
        x = 42;
        let y = x;
        "#;
        let dfg = RustDfgBuilder::build("f.rs", src);
        // Expect multiple definitions of x (initial let and assignment)
        let defs: Vec<_> = dfg
            .nodes
            .iter()
            .filter(|n| n.name == "x" && n.id.contains(":def:"))
            .collect();
        assert!(
            defs.len() >= 2,
            "expected >=2 definitions of x, got {}",
            defs.len()
        );
        // SSA-like expectation: use at line 4 should connect to latest reaching def (line 3)
        let use_id = "f.rs:use:x:4";
        let incoming: Vec<_> = dfg
            .edges
            .iter()
            .filter(|e| e.kind == DependencyKind::Data && e.to == use_id)
            .map(|e| e.from.clone())
            .collect();
        assert_eq!(incoming.len(), 1, "expected one reaching def for x@line4");
        assert!(
            incoming[0].ends_with(":def:x:3"),
            "expected latest def at line 3, got {}",
            incoming[0]
        );

        // Alias propagation: let y = x should add def(x@3) -> def(y@4)
        assert!(dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from.ends_with(":def:x:3")
                && e.to.ends_with(":def:y:4")
        }));
    }

    #[test]
    fn rust_alias_chain_and_reassignment_prefers_latest_def() {
        let src = "let mut a = seed;\nlet b = a;\na = other;\nlet c = a;\nlet d = b;\n";
        let dfg = RustDfgBuilder::build("f.rs", src);

        // `let mut a` should define `a` (not a bogus `mut` symbol).
        assert!(dfg.nodes.iter().any(|n| n.id.ends_with(":def:a:1")));
        assert!(!dfg.nodes.iter().any(|n| n.name == "mut"));

        // Assignment chain: a -> b -> d.
        assert!(dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from.ends_with(":def:a:1")
                && e.to.ends_with(":def:b:2")
        }));
        assert!(dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from.ends_with(":def:b:2")
                && e.to.ends_with(":def:d:5")
        }));

        // Reassignment: `c = a` should use latest def of a (line 3), not initial line 1.
        assert!(dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from.ends_with(":def:a:3")
                && e.to.ends_with(":def:c:4")
        }));
        assert!(!dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from.ends_with(":def:a:1")
                && e.to.ends_with(":def:c:4")
        }));
    }

    #[test]
    fn build_return_dependency() {
        let src = r#"
        fn foo() {
            let a = compute();
            return a;
        }
        "#;
        let dfg = RustDfgBuilder::build("f.rs", src);
        // Expect definition for a and use of a in return
        let def_ids: Vec<&String> = dfg
            .nodes
            .iter()
            .filter(|n| n.name == "a" && n.id.contains(":def:"))
            .map(|n| &n.id)
            .collect();
        assert_eq!(
            def_ids.len(),
            1,
            "expected one definition of a, got {}",
            def_ids.len()
        );
        let use_ids: Vec<&String> = dfg
            .nodes
            .iter()
            .filter(|n| n.name == "a" && n.id.contains(":use:"))
            .map(|n| &n.id)
            .collect();
        assert_eq!(
            use_ids.len(),
            1,
            "expected one use of a, got {}",
            use_ids.len()
        );
        // Edge from def a to use a
        let edge_exists = dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data && e.from == *def_ids[0] && e.to == *use_ids[0]
        });
        assert!(
            edge_exists,
            "expected data edge from '{}' to '{}'",
            def_ids[0], use_ids[0]
        );
    }

    #[test]
    fn build_control_dependencies() {
        let src = r#"
        let x = 1;
        if x > 0 {
            let y = x;
            let z = y;
        }
        "#;
        let dfg = RustDfgBuilder::build("f.rs", src);
        // Expect at least one control node and control edges
        let ctrl_nodes: Vec<_> = dfg
            .nodes
            .iter()
            .filter(|n| n.id.contains(":ctrl:"))
            .collect();
        assert!(!ctrl_nodes.is_empty(), "expected control nodes");
        let ctrl_edges: Vec<_> = dfg
            .edges
            .iter()
            .filter(|e| e.kind == DependencyKind::Control)
            .collect();
        assert!(!ctrl_edges.is_empty(), "expected control edges");
        // All control edges should originate from control nodes
        for edge in ctrl_edges {
            assert!(
                edge.from.contains(":ctrl:"),
                "control edge should originate from control node"
            );
        }
    }

    #[test]
    fn rust_reaching_defs_branch_join_includes_both_branch_defs() {
        let src = "let x = 0;\nif cond {\n    x = 1;\n} else {\n    x = 2;\n}\nlet y = x;\n";
        let dfg = RustDfgBuilder::build("f.rs", src);

        let use_id = "f.rs:use:x:7";
        let incoming: std::collections::BTreeSet<_> = dfg
            .edges
            .iter()
            .filter(|e| e.kind == DependencyKind::Data && e.to == use_id)
            .map(|e| e.from.clone())
            .collect();

        assert!(
            incoming.iter().any(|id| id.ends_with(":def:x:3")),
            "expected then-branch def to reach join"
        );
        assert!(
            incoming.iter().any(|id| id.ends_with(":def:x:5")),
            "expected else-branch def to reach join"
        );
        assert!(
            !incoming.iter().any(|id| id.ends_with(":def:x:1")),
            "initial def should be shadowed by branch defs"
        );
    }

    #[test]
    fn rust_reaching_defs_partial_branch_keeps_pre_branch_def() {
        let src = "let x = 0;\nif cond {\n    x = 1;\n}\nlet y = x;\n";
        let dfg = RustDfgBuilder::build("f.rs", src);

        let use_id = "f.rs:use:x:5";
        let incoming: std::collections::BTreeSet<_> = dfg
            .edges
            .iter()
            .filter(|e| e.kind == DependencyKind::Data && e.to == use_id)
            .map(|e| e.from.clone())
            .collect();

        assert!(
            incoming.iter().any(|id| id.ends_with(":def:x:3")),
            "branch def should reach join"
        );
        assert!(
            incoming.iter().any(|id| id.ends_with(":def:x:1")),
            "pre-branch def should remain for non-taken path"
        );
    }

    #[test]
    fn ruby_alias_assignment_adds_def_to_def_edge() {
        let src = "a = seed\nb = a\nreturn b\n";
        let dfg = RubyDfgBuilder::build("test.rb", src);

        assert!(dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from.ends_with(":def:a:1")
                && e.to.ends_with(":def:b:2")
        }));
    }

    #[test]
    fn ruby_alias_reassignment_prefers_latest_def() {
        let src = "a = seed\nb = a\na = other\nc = a\n";
        let dfg = RubyDfgBuilder::build("test.rb", src);

        assert!(dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from.ends_with(":def:a:1")
                && e.to.ends_with(":def:b:2")
        }));
        assert!(dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from.ends_with(":def:a:3")
                && e.to.ends_with(":def:c:4")
        }));
        assert!(!dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from.ends_with(":def:a:1")
                && e.to.ends_with(":def:c:4")
        }));
    }

    #[test]
    fn ruby_reaching_defs_partial_branch_keeps_pre_branch_def() {
        let src = "a = seed\nif cond\n  a = other\nend\nb = a\n";
        let dfg = RubyDfgBuilder::build("test.rb", src);

        let use_id = "test.rb:use:a:5";
        let incoming: std::collections::BTreeSet<_> = dfg
            .edges
            .iter()
            .filter(|e| e.kind == DependencyKind::Data && e.to == use_id)
            .map(|e| e.from.clone())
            .collect();

        assert!(
            incoming.iter().any(|id| id.ends_with(":def:a:3")),
            "branch def should reach join"
        );
        assert!(
            incoming.iter().any(|id| id.ends_with(":def:a:1")),
            "pre-branch def should remain for non-taken path"
        );
    }

    #[test]
    fn ruby_no_paren_method_params_feed_alias_and_return_flow() {
        let src = r#"def bounce value, fallback: nil
  alias_value = value
  return alias_value
end
"#;
        let dfg = RubyDfgBuilder::build("test.rb", src);

        assert!(dfg.nodes.iter().any(|n| n.id == "test.rb:def:value:1"));
        assert!(dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from == "test.rb:def:value:1"
                && e.to == "test.rb:def:alias_value:2"
        }));
        assert!(dfg.edges.iter().any(|e| {
            e.kind == DependencyKind::Data
                && e.from == "test.rb:def:alias_value:2"
                && e.to == "test.rb:use:alias_value:3"
        }));
    }

    #[test]
    fn build_ruby_dfg_simple() {
        let src = r#"
        def foo(a)
            b = a
            if b > 0
                c = b
            end
            return c
        end
        "#;
        let path = "test.rb";
        let dfg = RubyDfgBuilder::build(path, src);
        // Parameter 'a'
        assert!(
            dfg.nodes
                .iter()
                .any(|n| n.name == "a" && n.id.starts_with("test.rb:def:a:")),
            "expected definition node for 'a'"
        );
        // Definition 'b' and 'c'
        assert!(
            dfg.nodes.iter().any(|n| n.id.contains(":def:b:")),
            "expected def node for 'b'"
        );
        assert!(
            dfg.nodes.iter().any(|n| n.id.contains(":def:c:")),
            "expected def node for 'c'"
        );
        // Data dependencies for uses
        assert!(
            dfg.edges
                .iter()
                .any(|e| e.from.contains(":def:a:") && e.to.contains(":use:a:")),
            "expected data edge from def:a to use:a"
        );
        assert!(
            dfg.edges
                .iter()
                .any(|e| e.from.contains(":def:b:") && e.to.contains(":use:b:")),
            "expected data edge from def:b to use:b"
        );
        // Control dependency for if block
        assert!(
            dfg.nodes.iter().any(|n| n.id.contains(":ctrl:")),
            "expected control node"
        );
        assert!(
            dfg.edges.iter().any(|e| e.kind == DependencyKind::Control),
            "expected control edges"
        );
    }
}