code2graph 0.0.0-beta.17

Purpose-neutral code-graph extraction: source files → symbols, references, and cross-file edges. Tree-sitter based, no storage opinion.
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
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
// SPDX-License-Identifier: Apache-2.0

//! Python extractor — one tree-sitter pass yielding definitions and references.
//!
//! Definitions: top-level `def` / `async def` (incl. decorated), `class` (incl.
//! decorated), and module-level ALL_CAPS constants. Qualified identity follows
//! the dotted module path derived from the file path (`src/auth/jwt.py` →
//! namespaces `auth`,`jwt`; `__init__.py` collapses to its package).
//! References: callee identifiers of `call` nodes (`foo(...)`, `obj.method(...)`).
//!
//! Emits neutral [`FileFacts`] — no storage entries, no source bodies.

use tree_sitter::{Node, Parser};

use crate::error::{CodegraphError, Result};
use crate::graph::types::{
    Binding, BindingKind, ByteSpan, EntryPoint, FileFacts, RefRole, Reference, Scope, ScopeId,
    ScopeKind, Symbol, SymbolKind, TypeRefContext, Visibility,
};
use crate::lang::Language;
use crate::symbol::Descriptor;

#[cfg(feature = "sql")]
use super::emit_embedded_sql_refs;
use super::{
    BindingRules, ExtractCtx, Extractor, MIN_REF_LEN, attach_reference_scopes,
    collect_call_references, definition_bindings, field_text, import_bindings, make_symbol,
    mark_receiver_qualifier_calls, mark_self_receiver_calls, member_descriptors, node_span,
    node_text, one_line_signature, push_ref, push_scope, push_type_ref, push_typed_binding,
};

/// Tree-sitter query capturing call-callee identifiers.
const CALL_QUERY: &str = r#"
(call
  function: [
    (identifier) @callee
    (attribute attribute: (identifier) @callee)
  ]
)
"#;

/// Method calls whose receiver is written as the conventional `self` parameter
/// (`self.foo()`).
///
/// Python has no `self` keyword — `self` is a plain `identifier` fixed only by
/// the near-universal convention (PEP 8) that a method's first parameter is
/// named `self`. It is therefore structurally indistinguishable from any other
/// object receiver, so this query captures `@receiver` and
/// [`mark_self_receiver_calls`] applies a text gate comparing it against the
/// literal `"self"`. The resolver still fails closed unless the enclosing symbol
/// is itself a type member, so a stray local named `self` outside a method never
/// yields a false edge.
const SELF_CALL_QUERY: &str = r#"
(call
  function: (attribute object: (identifier) @receiver attribute: (identifier) @callee))
"#;

/// Member calls whose receiver is a bare local/parameter identifier
/// (`x.foo()`), captured as `@receiver` so [`mark_receiver_qualifier_calls`]
/// can set the call's `qualifier` for [`crate::resolve::LocalTypedCallResolver`].
///
/// Only a bare `(identifier)` object is matched — chained (`a.b.foo()`) and
/// call (`a().foo()`) receivers are deliberately excluded, since their type is
/// not a scope-resolvable binding. Structurally this also matches `self.foo()`;
/// [`mark_self_receiver_calls`] runs AFTER and clears the qualifier it set for
/// the `self` receiver, so self-calls uniformly carry `qualifier = None`.
const RECEIVER_CALL_QUERY: &str = r#"
(call
  function: (attribute object: (identifier) @receiver attribute: (identifier) @callee))
"#;

/// Extracts Python symbols and references.
pub struct PythonExtractor;

impl Extractor for PythonExtractor {
    fn lang(&self) -> Language {
        Language::Python
    }

    fn extract_facts(&self, source: &str, file: &str) -> Result<FileFacts> {
        self.extract_impl(source, file, None)
    }

    fn extract_facts_with_bindings(
        &self,
        source: &str,
        file: &str,
        rules: &BindingRules,
    ) -> Result<FileFacts> {
        self.extract_impl(source, file, Some(rules))
    }
}

impl PythonExtractor {
    fn extract_impl(
        &self,
        source: &str,
        file: &str,
        rules: Option<&BindingRules>,
    ) -> Result<FileFacts> {
        let ts_language = crate::grammar::python();
        let mut parser = Parser::new();
        parser
            .set_language(&ts_language)
            .map_err(|_| CodegraphError::Parse {
                path: file.to_owned(),
            })?;
        let tree = parser
            .parse(source, None)
            .ok_or_else(|| CodegraphError::Parse {
                path: file.to_owned(),
            })?;

        let root = tree.root_node();
        let bytes = source.as_bytes();
        let namespaces = python_namespaces(file);

        let ctx = ExtractCtx {
            bytes,
            file,
            lang: Language::Python,
        };
        let defs = collect_symbols(&root, &ctx, &namespaces);
        let def_bindings = definition_bindings(&defs);
        let mut symbols = defs;
        // Class methods are gathered separately and appended AFTER `def_bindings`
        // is computed from the method-free `defs`. Python's LEGB rule means class
        // body names are not visible in module scope, so method symbols must never
        // flow through `definition_bindings` (which hard-codes `scope: 0`).
        symbols.extend(collect_class_method_symbols(&root, &ctx, &namespaces));
        let mut mod_sym = super::module_symbol(Language::Python, &namespaces, file, source.len());
        let module_id = mod_sym.id.to_scip_string();
        // Idiomatic Python entry point: a module-level `if __name__ == "__main__"`
        // guard marks the whole module as a `Main` entry point.
        if module_is_main_entry(&root, bytes) {
            mod_sym.entry_points.push(EntryPoint::Main);
        }
        symbols.push(mod_sym);
        let mut references = collect_call_references(
            &root,
            &ts_language,
            CALL_QUERY,
            Language::Python,
            bytes,
            file,
        )?;
        // General receiver capture MUST run BEFORE the self-mark: it also matches
        // `self.foo()` (setting qualifier = "self"), and the self-mark that runs
        // next clears that qualifier for the `self` receiver.
        mark_receiver_qualifier_calls(
            &root,
            &ts_language,
            RECEIVER_CALL_QUERY,
            Language::Python,
            bytes,
            &mut references,
        )?;
        mark_self_receiver_calls(
            &root,
            &ts_language,
            SELF_CALL_QUERY,
            Language::Python,
            bytes,
            &mut references,
            Some("self"),
        )?;
        collect_inheritance(&root, bytes, file, &mut references);
        collect_imports(&root, bytes, file, &mut references, &module_id);
        collect_type_references(&root, bytes, file, &mut references);
        collect_read_references(&root, bytes, file, &mut references);
        collect_write_references(&root, bytes, file, &mut references);
        #[cfg(feature = "sql")]
        if let Some(rules) = rules {
            collect_query_bindings(&root, bytes, file, rules, &mut references);
        }
        #[cfg(not(feature = "sql"))]
        let _ = rules;

        let scopes = collect_scopes(&root, source.len());
        attach_reference_scopes(&mut references, &scopes);
        let mut bindings = collect_bindings(&root, bytes, &scopes);
        bindings.extend(def_bindings);
        bindings.extend(import_bindings(&references, &scopes));

        Ok(FileFacts {
            file: file.to_owned(),
            lang: Language::Python.as_str().to_owned(),
            symbols,
            references,
            scopes,
            bindings,
            ffi_exports: Vec::new(),
        })
    }
}

/// Derive the dotted Python module path (namespace descriptors) from a file path.
fn python_namespaces(file: &str) -> Vec<String> {
    let p = file.strip_prefix("src/").unwrap_or(file);
    let mut parts: Vec<String> = p
        .split('/')
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
        .collect();
    if let Some(last) = parts.pop() {
        let stem = last
            .strip_suffix(".pyi")
            .or_else(|| last.strip_suffix(".py"))
            .unwrap_or(&last);
        if stem != "__init__" {
            parts.push(stem.to_owned());
        }
    }
    parts
}

/// Terminal identifier names that indicate an HTTP-route decorator call.
///
/// Detection rule (honest boundary): a decorator is an HTTP-route marker when it
/// is a CALL node whose `function:` field's terminal identifier is in this set
/// (case-sensitive). Bare non-call decorators (`@staticmethod`, `@dataclass`) and
/// call decorators whose terminal name is NOT here (`@cache.memoize()`) produce no
/// marker.  This is a syntactic, build-free heuristic — it covers Flask-style
/// `@app.route`, FastAPI `@router.get`, Starlette/Tornado route variants and
/// WebSocket handlers, but cannot detect dynamically constructed route registrations
/// or reflection-based frameworks.
const PY_ROUTE_VERBS: &[&str] = &[
    "get",
    "post",
    "put",
    "delete",
    "patch",
    "head",
    "options",
    "trace",
    "route",
    "websocket",
    "ws",
];

/// Compute entry-point markers for a function symbol.
///
/// `fn_name` is the bare function name (for `Main` detection).
/// `outer_node` is the span node — if it is a `decorated_definition`, its
/// `decorator` children are inspected for HTTP-route call decorators.
///
/// Node-kind path for a route decorator:
/// ```text
/// decorated_definition
///   decorator           ("@" + callee text)
///     call
///       function: attribute  ("app.get") or identifier ("get")
///       arguments: argument_list
/// ```
/// The `function:` field of the `call` is the callee; for an `attribute` node the
/// `attribute:` field gives the terminal identifier, for an `identifier` node the
/// text itself is the terminal.  The `attribute` node's full text (e.g. `app.get`)
/// is used as the `HttpRoute` marker string so the consumer can identify both the
/// framework object and the HTTP method without reparsing.
fn entry_points_for(fn_name: &str, outer_node: &Node, bytes: &[u8]) -> Vec<EntryPoint> {
    let mut markers: Vec<EntryPoint> = Vec::new();

    // (a) Name-based entry point: a function literally named `main`.
    if fn_name == "main" {
        markers.push(EntryPoint::Main);
    }

    // (b) HTTP-route decorator detection — only applies to `decorated_definition`.
    if outer_node.kind() != "decorated_definition" {
        return markers;
    }

    for child in outer_node.children(&mut outer_node.walk()) {
        if child.kind() != "decorator" {
            continue;
        }
        // A decorator node's children: "@" (anonymous) then the callee expression.
        // Route detection only fires when the callee is a CALL (not a bare name).
        let Some(call_node) = child
            .children(&mut child.walk())
            .find(|c| c.kind() == "call")
        else {
            continue;
        };

        // The `function:` field of the call is the callee expression.
        let Some(func_node) = call_node.child_by_field_name("function") else {
            continue;
        };

        // Determine the terminal identifier and the full callee text.
        let (terminal, callee_text) = match func_node.kind() {
            "attribute" => {
                // `app.get` / `router.post` — terminal is the `attribute:` field.
                let terminal = func_node
                    .child_by_field_name("attribute")
                    .map(|n| node_text(&n, bytes))
                    .unwrap_or("");
                let callee = node_text(&func_node, bytes);
                (terminal, callee)
            }
            "identifier" => {
                // bare `get(...)` / `route(...)` — terminal is the whole identifier.
                let text = node_text(&func_node, bytes);
                (text, text)
            }
            _ => continue,
        };

        if PY_ROUTE_VERBS.contains(&terminal) {
            markers.push(EntryPoint::HttpRoute(callee_text.to_owned()));
        }
    }

    markers
}

/// Returns `true` iff a DIRECT child of the `module` root is an `if_statement`
/// whose `condition:` is a `comparison_operator` representing the idiomatic
/// `__name__ == "__main__"` guard (in either operand order).
///
/// Node-kind path:
/// ```text
/// module
///   if_statement
///     condition: comparison_operator
///       identifier ("__name__")  "=="  string ("__main__")
/// ```
/// Detection is strict: the operator must be `==` (an anonymous `==` token child
/// of the `comparison_operator`), one operand must be the bare identifier
/// `__name__`, and the other a string whose content is `__main__`. `!=`/`is`/
/// other comparisons are rejected.
fn module_is_main_entry(root: &tree_sitter::Node, bytes: &[u8]) -> bool {
    root.children(&mut root.walk())
        .filter(|n| n.kind() == "if_statement")
        .filter_map(|n| n.child_by_field_name("condition"))
        .filter(|cond| cond.kind() == "comparison_operator")
        .any(|cond| is_name_eq_main(&cond, bytes))
}

/// Returns `true` when `cond` (a `comparison_operator`) is exactly
/// `__name__ == "__main__"` (either operand order).
fn is_name_eq_main(cond: &Node, bytes: &[u8]) -> bool {
    // The operator must be `==`: exactly one child is the anonymous `==` token,
    // and there must be no other comparison operator token (reject chained/`!=`).
    let eq_tokens = cond
        .children(&mut cond.walk())
        .filter(|c| !c.is_named() && c.kind() == "==")
        .count();
    if eq_tokens != 1 {
        return false;
    }

    let operands: Vec<Node> = cond.named_children(&mut cond.walk()).collect();
    if operands.len() != 2 {
        return false;
    }

    let (a, b) = (operands[0], operands[1]);
    is_dunder_name_pair(&a, &b, bytes) || is_dunder_name_pair(&b, &a, bytes)
}

/// `true` when `name_node` is the identifier `__name__` and `str_node` is a
/// string whose content is `__main__`.
fn is_dunder_name_pair(name_node: &Node, str_node: &Node, bytes: &[u8]) -> bool {
    name_node.kind() == "identifier"
        && node_text(name_node, bytes) == "__name__"
        && str_node.kind() == "string"
        && string_content(str_node, bytes) == "__main__"
}

/// Read the textual content of a `string` node, quote-style agnostic.
///
/// Prefers the `string_content` child (the grammar's named content node); falls
/// back to stripping a single layer of surrounding quotes when absent (e.g. an
/// empty string with no `string_content` child).
fn string_content<'a>(string_node: &Node, bytes: &'a [u8]) -> &'a str {
    if let Some(content) = string_node
        .children(&mut string_node.walk())
        .find(|c| c.kind() == "string_content")
    {
        return node_text(&content, bytes);
    }
    node_text(string_node, bytes)
        .trim_matches('"')
        .trim_matches('\'')
}

fn collect_symbols(root: &Node, ctx: &ExtractCtx, namespaces: &[String]) -> Vec<Symbol> {
    let mut out = Vec::new();
    collect_symbols_in(root, ctx, namespaces, &mut out);
    out
}

/// Is `kind` a module-level control-flow container whose body holds statements
/// that are still *module scope*? Real code guards module globals behind
/// `if`/`try`/`with`/`for`/`while` (e.g. platform-conditional constants), so we
/// descend through these — and the `block` suite they wrap — to reach the
/// conditionally-defined names. A `function_definition`/`class_definition` is
/// **not** in this set: its body is locals/members, not module scope, and
/// `collect_symbols_in` deliberately never recurses into it.
fn is_module_scope_container(kind: &str) -> bool {
    matches!(
        kind,
        "if_statement"
            | "elif_clause"
            | "else_clause"
            | "try_statement"
            | "except_clause"
            | "except_group_clause"
            | "finally_clause"
            | "with_statement"
            | "for_statement"
            | "while_statement"
            | "block"
    )
}

/// Apply the module-scope definition dispatch to every child of `node`, pushing
/// a `Symbol` for each `function_definition`/`class_definition`/
/// `decorated_definition`/`expression_statement`/`assignment`, and recursing
/// through control-flow containers (see [`is_module_scope_container`]) so names
/// guarded by module-level `if`/`try`/etc. are still emitted at module scope.
///
/// The recursion stops at function/class definitions: their symbol is emitted
/// but their body is never descended into, so locals never leak as globals.
/// Namespaces pass through unchanged — a constant under `if WIN:` is `module/X`,
/// exactly as a top-level one.
fn collect_symbols_in(node: &Node, ctx: &ExtractCtx, namespaces: &[String], out: &mut Vec<Symbol>) {
    for child in node.children(&mut node.walk()) {
        // (span node, signature node, name, kind, leaf descriptor)
        let parsed = match child.kind() {
            "function_definition" => def_of(&child, &child, ctx.bytes, true),
            "class_definition" => def_of(&child, &child, ctx.bytes, false),
            "decorated_definition" => {
                let Some(inner) = child
                    .children(&mut child.walk())
                    .find(|c| matches!(c.kind(), "function_definition" | "class_definition"))
                else {
                    continue;
                };
                let is_fn = inner.kind() == "function_definition";
                // span includes decorators (outer node); signature is the def line.
                def_of(&child, &inner, ctx.bytes, is_fn)
            }
            "expression_statement" | "assignment" => const_of(&child, ctx.bytes),
            // Descend into module-level control flow (and its `block` suites)
            // to reach conditionally-defined module globals. Visited once each.
            k if is_module_scope_container(k) => {
                collect_symbols_in(&child, ctx, namespaces, out);
                continue;
            }
            _ => None,
        };
        let Some((span_node, sig_node, name, kind, leaf)) = parsed else {
            continue;
        };

        let mut descriptors: Vec<Descriptor> = namespaces
            .iter()
            .cloned()
            .map(Descriptor::Namespace)
            .collect();
        descriptors.push(leaf);

        let signature = one_line_signature(node_text(&sig_node, ctx.bytes), &[':']);
        let visibility = python_visibility(&name);
        let mut sym = make_symbol(
            ctx,
            &span_node,
            name,
            kind,
            visibility,
            descriptors,
            signature,
        );
        // Populate entry-point markers for function definitions only.
        // Classes and constants never carry route/main markers.
        if sym.kind == SymbolKind::Function {
            sym.entry_points = entry_points_for(&sym.name, &span_node, ctx.bytes);
        }
        out.push(sym);
    }
}

/// Find the first DIRECT child of `node` whose kind is `kind`.
fn find_child_kind<'a>(node: &Node<'a>, kind: &str) -> Option<Node<'a>> {
    node.children(&mut node.walk()).find(|c| c.kind() == kind)
}

/// Collect [`SymbolKind::Method`] symbols for every top-level class's DIRECT
/// method members (`class_definition` / `decorated_definition` wrapping a
/// `class_definition`, found among `root`'s direct children — same scope as
/// `collect_symbols`). Nested classes are deliberately not descended into.
///
/// Kept as a separate pass so these symbols never flow through
/// `definition_bindings`: see the call site in `extract_impl` for why.
fn collect_class_method_symbols(
    root: &Node,
    ctx: &ExtractCtx,
    namespaces: &[String],
) -> Vec<Symbol> {
    let mut out = Vec::new();
    for child in root.children(&mut root.walk()) {
        let class_node = match child.kind() {
            "class_definition" => child,
            "decorated_definition" => {
                let Some(inner) = find_child_kind(&child, "class_definition") else {
                    continue;
                };
                inner
            }
            _ => continue,
        };
        let Some(class_name) = class_node
            .children(&mut class_node.walk())
            .find(|c| c.kind() == "identifier")
            .map(|c| node_text(&c, ctx.bytes).to_owned())
        else {
            continue;
        };
        collect_class_methods(&class_node, ctx, namespaces, &class_name, &mut out);
    }
    out
}

/// Emit a `Type(class_name).Method(method_name)` symbol for each DIRECT
/// `function_definition` (bare or decorated, incl. `async def`) in a class
/// body block. One level only: nested `def`s inside a method body are local
/// functions, not methods, and are not descended into.
fn collect_class_methods(
    class_node: &Node,
    ctx: &ExtractCtx,
    namespaces: &[String],
    class_name: &str,
    out: &mut Vec<Symbol>,
) {
    let Some(body) = class_node.child_by_field_name("body") else {
        return;
    };
    for member in body.children(&mut body.walk()) {
        let (span_node, sig_node) = match member.kind() {
            "function_definition" => (member, member),
            "decorated_definition" => {
                let Some(inner) = find_child_kind(&member, "function_definition") else {
                    continue;
                };
                (member, inner)
            }
            _ => continue,
        };
        let Some(name) = sig_node
            .children(&mut sig_node.walk())
            .find(|c| c.kind() == "identifier")
            .map(|c| node_text(&c, ctx.bytes).to_owned())
        else {
            continue;
        };
        // Same sentinel skip as `def_of`: drop pure-underscore names, keep real
        // dunders like `__init__`.
        if name.chars().all(|c| c == '_') {
            continue;
        }

        let descriptors = member_descriptors(
            namespaces,
            class_name,
            Descriptor::Method {
                name: name.clone(),
                disambiguator: crate::symbol::MethodDisambiguator::empty(),
            },
        );

        let signature = one_line_signature(node_text(&sig_node, ctx.bytes), &[':']);
        let visibility = python_visibility(&name);
        let sym = make_symbol(
            ctx,
            &span_node,
            name,
            SymbolKind::Method,
            visibility,
            descriptors,
            signature,
        );
        out.push(sym);
    }
}

/// Map a Python identifier to its [`Visibility`].
///
/// Unlike pure lint convention, Python's underscore prefixes carry language-level
/// meaning: a leading double underscore (without a trailing dunder) triggers
/// compiler name mangling (`__x` inside a class becomes `_Class__x`), and a leading
/// single underscore is excluded from `from module import *`. code2graph records
/// these as real visibility rather than `Unknown`. (This is distinct from Dart's
/// purely-conventional `_` prefix, which the extractor deliberately leaves `Unknown`.)
///
/// - `__dunder__` (>= 2 leading AND >= 2 trailing underscores) -> `Public` (magic/special methods).
/// - `__name` (>= 2 leading, <= 1 trailing) -> `Private` (name-mangled; scope-local).
/// - `_name` (exactly 1 leading underscore) -> `Internal` (module-private / conventionally protected).
/// - everything else, including trailing-underscore-only names like `type_` -> `Public`.
fn python_visibility(name: &str) -> Visibility {
    let lead = name.len() - name.trim_start_matches('_').len();
    let trail = name.len() - name.trim_end_matches('_').len();
    if lead >= 2 && trail >= 2 {
        Visibility::Public
    } else if lead >= 2 {
        Visibility::Private
    } else if lead == 1 {
        Visibility::Internal
    } else {
        Visibility::Public
    }
}

/// Build a function/class definition tuple from a def node.
fn def_of<'a>(
    span_node: &Node<'a>,
    sig_node: &Node<'a>,
    bytes: &[u8],
    is_fn: bool,
) -> Option<(Node<'a>, Node<'a>, String, SymbolKind, Descriptor)> {
    let name = sig_node
        .children(&mut sig_node.walk())
        .find(|c| c.kind() == "identifier")
        .map(|c| node_text(&c, bytes).to_owned())?;
    // Drop dunder/sentinel names like `__` but keep real dunder methods? Top-level
    // only here; skip names that are entirely underscores.
    if name.chars().all(|c| c == '_') {
        return None;
    }
    let (kind, leaf) = if is_fn {
        (
            SymbolKind::Function,
            Descriptor::Method {
                name: name.clone(),
                disambiguator: crate::symbol::MethodDisambiguator::empty(),
            },
        )
    } else {
        (SymbolKind::Class, Descriptor::Type(name.clone()))
    };
    Some((*span_node, *sig_node, name, kind, leaf))
}

/// Build a constant definition tuple from a module-level assignment.
///
/// Emits one `Const` symbol per module-level `X = …` / `X: T = …` / `X: T` whose
/// target is a simple identifier (Python has no const/static distinction — every
/// module global is the same construct, including `TypeVar`s). Tuple, attribute,
/// and subscript targets are skipped (no single addressable name), as are
/// pure-underscore throwaways. Module scope is guaranteed by the caller, which
/// only visits the module root's direct children.
fn const_of<'a>(
    node: &Node<'a>,
    bytes: &[u8],
) -> Option<(Node<'a>, Node<'a>, String, SymbolKind, Descriptor)> {
    let assign = if node.kind() == "assignment" {
        *node
    } else {
        node.children(&mut node.walk())
            .find(|c| c.kind() == "assignment")?
    };
    // The `left:` field is the assignment target: an `identifier` for a simple
    // binding, or a `pattern_list`/attribute/subscript we deliberately skip.
    let lhs = assign.child_by_field_name("left")?;
    if lhs.kind() != "identifier" {
        return None;
    }
    let name = node_text(&lhs, bytes).to_owned();
    if name.is_empty() || name.chars().all(|c| c == '_') {
        return None;
    }
    Some((
        *node,
        *node,
        name.clone(),
        SymbolKind::Const,
        Descriptor::Term(name),
    ))
}

/// Recursively walk `node` collecting `Import` references for every
/// `import_statement` and `import_from_statement` in the tree (covers top-level
/// and function-local imports; both attribute correctly via span-containment in
/// the resolver).
///
/// Rules:
/// - `import_from_statement`'s `module_name` field is the from-path (e.g.
///   `pkg.models` in `from pkg.models import Config`).
/// - `import_statement`'s imported names ARE the from-path (e.g. `import os` →
///   `from_path = "os"`; `import foo.bar` → `from_path = "foo.bar"`).
/// - For a `dotted_name` child: emit the leaf segment (last `.`-separated part).
/// - For an `aliased_import` child: emit the leaf of its `name` field (the real
///   name), ignoring the `alias` field.
/// - `wildcard_import` children (`from x import *`) produce no reference.
fn collect_imports(
    node: &Node,
    bytes: &[u8],
    file: &str,
    out: &mut Vec<Reference>,
    module_id: &str,
) {
    match node.kind() {
        "import_from_statement" => {
            // Extract the from-path once from the `module_name` field.
            let module_name = node.child_by_field_name("module_name");
            let from_path = module_name.map_or("", |n| node_text(&n, bytes));
            // Every segment of the from-path is a module → emit a ModuleRef each,
            // positioned at that segment's own identifier node. Relative imports
            // (`from . import x`) have no `dotted_name` module_name → skip.
            if let Some(mn) = module_name {
                emit_module_path_refs(&mn, false, bytes, file, out);
            }
            for child in node.children_by_field_name("name", &mut node.walk()) {
                match child.kind() {
                    "dotted_name" => {
                        let text = node_text(&child, bytes);
                        let leaf = super::simple_type_name(text, ".");
                        super::push_import_ref(out, leaf, &child, file, module_id, from_path);
                    }
                    "aliased_import" => {
                        // Take the real `name` field (a `dotted_name`), ignore `alias`.
                        if let Some(name_node) = child.child_by_field_name("name") {
                            let text = node_text(&name_node, bytes);
                            let leaf = super::simple_type_name(text, ".");
                            super::push_import_ref(
                                out, leaf, &name_node, file, module_id, from_path,
                            );
                        }
                    }
                    // wildcard_import and anything else produce nothing.
                    _ => {}
                }
            }
            // Import statements cannot contain nested import statements.
            return;
        }
        "import_statement" => {
            // `import foo.bar` / `import foo.bar as baz` — the from-path is the
            // full dotted name of the thing being imported (before any alias).
            for child in node.children_by_field_name("name", &mut node.walk()) {
                match child.kind() {
                    "dotted_name" => {
                        let text = node_text(&child, bytes);
                        let leaf = super::simple_type_name(text, ".");
                        // Every segment EXCEPT the last is a module → ModuleRef each
                        // (the last segment stays the existing leaf Import below).
                        emit_module_path_refs(&child, true, bytes, file, out);
                        // from_path = the full dotted text (e.g. "foo.bar")
                        super::push_import_ref(out, leaf, &child, file, module_id, text);
                    }
                    "aliased_import" => {
                        // Take the real `name` field (a `dotted_name`), ignore `alias`.
                        if let Some(name_node) = child.child_by_field_name("name") {
                            let text = node_text(&name_node, bytes);
                            let leaf = super::simple_type_name(text, ".");
                            // from_path = full dotted path before the alias
                            super::push_import_ref(out, leaf, &name_node, file, module_id, text);
                        }
                    }
                    // wildcard_import and anything else produce nothing.
                    _ => {}
                }
            }
            // Import statements cannot contain nested import statements.
            return;
        }
        _ => {}
    }

    // Recurse into all children to cover nested/local imports.
    for child in node.children(&mut node.walk()) {
        collect_imports(&child, bytes, file, out, module_id);
    }
}

/// Emit a [`RefRole::ModuleRef`] reference for module-path segments of a
/// `dotted_name` node, each positioned at its own child `identifier` node.
///
/// `skip_last` controls which segments count as modules:
/// - `false` — every segment is a module (the `from <module> import …` case,
///   where the entire `module_name` path is modules).
/// - `true` — every segment EXCEPT the trailing leaf is a module (the
///   `import a.b.c` case, where the last segment is the imported leaf and stays
///   an `Import`).
///
/// Empty / non-identifier segments are skipped gracefully (`push_ref` also drops
/// empty names), so relative-import dot parts emit nothing.
fn emit_module_path_refs(
    dotted: &Node,
    skip_last: bool,
    bytes: &[u8],
    file: &str,
    out: &mut Vec<Reference>,
) {
    if skip_last {
        // Collect so we can drop the final identifier (the imported leaf).
        let idents: Vec<Node> = dotted
            .children(&mut dotted.walk())
            .filter(|c| c.kind() == "identifier")
            .collect();
        let module_count = idents.len().saturating_sub(1);
        for id in idents.iter().take(module_count) {
            push_ref(out, node_text(id, bytes), id, file, RefRole::ModuleRef);
        }
    } else {
        // Every identifier is a module segment; no need to allocate.
        for id in dotted
            .children(&mut dotted.walk())
            .filter(|c| c.kind() == "identifier")
        {
            push_ref(out, node_text(&id, bytes), &id, file, RefRole::ModuleRef);
        }
    }
}

/// Recursively walk `node` collecting `Inherit` references for every
/// `class_definition` in the tree (including nested classes).
///
/// For each class that has a `superclasses` field (an `argument_list`), we
/// iterate its named children and handle:
/// - `identifier` — simple base name (e.g. `Base`).
/// - `attribute`  — dotted base; we take the `attribute` field (leaf segment,
///   e.g. `mod.Base` → `Base`).
///
/// Everything else (`subscript` for `Generic[T]`, `call`, `keyword_argument`
/// for `metaclass=`) is skipped gracefully.
fn collect_inheritance(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    if node.kind() == "class_definition" {
        if let Some(superclasses) = node.child_by_field_name("superclasses") {
            for child in superclasses.children(&mut superclasses.walk()) {
                if !child.is_named() {
                    continue;
                }
                match child.kind() {
                    "identifier" => {
                        super::push_ref(
                            out,
                            node_text(&child, bytes),
                            &child,
                            file,
                            RefRole::IsImplementation,
                        );
                    }
                    "attribute" => {
                        if let Some(name) = field_text(&child, "attribute", bytes) {
                            super::push_ref(out, &name, &child, file, RefRole::IsImplementation);
                        }
                    }
                    _ => {} // subscript (Generic[T]), call, keyword_argument, etc.
                }
            }
        }
    }

    // Recurse into all children so nested class definitions are covered.
    for child in node.children(&mut node.walk()) {
        collect_inheritance(&child, bytes, file, out);
    }
}

// ── Edge richness: TypeRef / Read / Write ────────────────────────────────────

/// Emit a [`RefRole::TypeRef`] reference by inspecting a `type:` field value.
///
/// In tree-sitter-python the `type:` field holds one of:
/// - `identifier`  — bare name like `int`, `Config`.
/// - `generic_type` — `List[int]`, `Dict[str, int]`: first named child is the
///   `identifier` (outer type name); child `type_parameter` node holds the
///   subscript args, each a `type` expression.
/// - `union_type`  — `int | str`: two `type` children; recurse each with `ctx`.
/// - `member_type` — `pkg.Sub`: the leaf `identifier` child (the last one) is
///   the referenced name; we skip the qualifier.
/// - Any other expression node (e.g. a string literal `"Foo"` for forward refs)
///   is silently skipped.
fn emit_type_node(
    node: &Node,
    bytes: &[u8],
    file: &str,
    ctx: TypeRefContext,
    out: &mut Vec<Reference>,
) {
    match node.kind() {
        // Transparent `type` wrapper (the named rule in tree-sitter-python that
        // wraps a `type:` field value): unwrap and recurse into the single child.
        "type" => {
            for child in node.named_children(&mut node.walk()) {
                emit_type_node(&child, bytes, file, ctx, out);
            }
        }
        "identifier" => {
            let name = node_text(node, bytes);
            push_type_ref(out, name, node, file, ctx);
        }
        "generic_type" => {
            // First named child is the base identifier.
            if let Some(head) = node.named_children(&mut node.walk()).next() {
                if head.kind() == "identifier" {
                    push_type_ref(out, node_text(&head, bytes), &head, file, ctx);
                }
            }
            // Second named child is `type_parameter` (`[...]`); its named
            // children are `type` expressions → recurse as GenericArg.
            if let Some(tp) = node
                .named_children(&mut node.walk())
                .find(|c| c.kind() == "type_parameter")
            {
                for child in tp.named_children(&mut tp.walk()) {
                    emit_type_node(&child, bytes, file, TypeRefContext::GenericArg, out);
                }
            }
        }
        "union_type" => {
            // Both sides are `type` expressions; recurse with the same context.
            for child in node.named_children(&mut node.walk()) {
                emit_type_node(&child, bytes, file, ctx, out);
            }
        }
        "member_type" => {
            // `pkg.Sub`: the last `identifier` child is the leaf name.
            // (grammar: type "." identifier — the identifier is the second child)
            if let Some(id) = node
                .named_children(&mut node.walk())
                .filter(|c| c.kind() == "identifier")
                .last()
            {
                push_type_ref(out, node_text(&id, bytes), &id, file, ctx);
            }
        }
        // Any other expression (string forward ref, etc.) — skip silently.
        _ => {}
    }
}

/// Recursively walk `node` and emit [`RefRole::TypeRef`] references for every
/// type-annotation position in Python source.
///
/// Covered positions:
/// - `typed_parameter` / `typed_default_parameter` — `type:` field → `ParameterType`
/// - `function_definition` — `return_type:` field → `ReturnType`
/// - `assignment` with a `type:` field (annotated assignment / class body field)
///   → `Field`
fn collect_type_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    match node.kind() {
        "typed_parameter" | "typed_default_parameter" => {
            if let Some(typ) = node.child_by_field_name("type") {
                emit_type_node(&typ, bytes, file, TypeRefContext::ParameterType, out);
            }
        }
        "function_definition" => {
            if let Some(ret) = node.child_by_field_name("return_type") {
                emit_type_node(&ret, bytes, file, TypeRefContext::ReturnType, out);
            }
            // Recurse into the function body to catch nested defs.
            for child in node.children(&mut node.walk()) {
                collect_type_references(&child, bytes, file, out);
            }
            return; // avoid double-recurse at the bottom
        }
        "assignment" => {
            if let Some(typ) = node.child_by_field_name("type") {
                emit_type_node(&typ, bytes, file, TypeRefContext::Field, out);
            }
        }
        _ => {}
    }

    for child in node.children(&mut node.walk()) {
        collect_type_references(&child, bytes, file, out);
    }
}

/// Returns `true` when `node` (an `identifier`) is in a non-read position —
/// already captured by another collector — and must NOT also be emitted as a
/// [`RefRole::Read`] reference.
///
/// Skipped positions:
/// - Call callee: `call` node's `function:` field.
/// - Declaration name: `function_definition` / `class_definition` `name:` field.
/// - Parameter name: bare `identifier` directly in `parameters`; or the
///   `identifier` inside `typed_parameter`, `default_parameter`,
///   `typed_default_parameter`, `list_splat_pattern`, `dictionary_splat_pattern`.
/// - Import binding: inside `import_statement` or `import_from_statement` or
///   `dotted_name` or `aliased_import`.
/// - Assignment LHS: `assignment` `left:` field (handled by writes).
/// - Attribute name: `attribute` node's `attribute:` field.
/// - Inside a `type` position: already a TypeRef; skip to avoid duplication.
fn is_non_read_position(node: &Node) -> bool {
    let parent = match node.parent() {
        Some(p) => p,
        None => return true,
    };
    match parent.kind() {
        // Call callee — `function:` field of a `call` node.
        "call" => parent.child_by_field_name("function").as_ref() == Some(node),
        // Declaration names.
        "function_definition" | "class_definition" => {
            parent.child_by_field_name("name").as_ref() == Some(node)
        }
        // Parameter: bare identifier directly inside `parameters`.
        "parameters" => true,
        // Typed / default parameter forms: the bound name identifier.
        "typed_parameter" | "list_splat_pattern" | "dictionary_splat_pattern" => {
            // The name is the first named child (an identifier); not the type.
            // We skip ALL identifier children of typed_parameter that are not
            // in the `type:` field — those are the param names.
            parent.child_by_field_name("type").as_ref() != Some(node) && node.kind() == "identifier"
        }
        "default_parameter" => parent.child_by_field_name("name").as_ref() == Some(node),
        "typed_default_parameter" => parent.child_by_field_name("name").as_ref() == Some(node),
        // Import contexts — already Import refs.
        "import_statement" | "import_from_statement" | "dotted_name" | "aliased_import" => true,
        // Assignment LHS — handled by collect_write_references.
        "assignment" => parent.child_by_field_name("left").as_ref() == Some(node),
        // Attribute name (`obj.attr` — skip the `attr` identifier only).
        "attribute" => parent.child_by_field_name("attribute").as_ref() == Some(node),
        // Inside a `type` node (type annotation position) — already a TypeRef.
        "type" => true,
        // `generic_type`'s first identifier is the type name — already TypeRef.
        "generic_type" => true,
        // `union_type`, `member_type` — inside type position.
        "union_type" | "member_type" => true,
        _ => false,
    }
}

/// Recursively walk `node` and emit [`RefRole::Read`] references for bare
/// `identifier` nodes used in value/expression positions. Applies [`MIN_REF_LEN`].
///
/// Skips positions handled by other collectors (call callees, declaration names,
/// parameter names, import bindings, assignment LHS, attribute property names,
/// type-annotation positions).
fn collect_read_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    if node.kind() == "identifier" {
        let name = node_text(node, bytes);
        if name.len() >= MIN_REF_LEN && !is_non_read_position(node) {
            push_ref(out, name, node, file, RefRole::Read);
        }
        // identifiers have no meaningful children; return early.
        return;
    }
    for child in node.children(&mut node.walk()) {
        collect_read_references(&child, bytes, file, out);
    }
}

/// Recursively walk `node` and emit [`RefRole::Write`] references for the
/// bare-identifier LHS of `assignment` nodes (e.g. `x = 5`, `base = helper()`).
///
/// Attribute/subscript LHS (`obj.attr = …`, `arr[i] = …`) are not covered in
/// v1. Applies [`MIN_REF_LEN`].
fn collect_write_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    if node.kind() == "assignment" {
        if let Some(lhs) = node.child_by_field_name("left") {
            if lhs.kind() == "identifier" {
                let name = node_text(&lhs, bytes);
                if name.len() >= MIN_REF_LEN {
                    push_ref(out, name, &lhs, file, RefRole::Write);
                }
            }
        }
    }
    for child in node.children(&mut node.walk()) {
        collect_write_references(&child, bytes, file, out);
    }
}

// ── Query-binding scan (cross-artifact code→SQL edges) ───────────────────────

/// Recursively walk `node` looking for call sites matching one of `rules`'s
/// Python constructs (e.g. `cursor.execute`, `text`), and emit a
/// [`RefRole::TypeRef`] reference (`cross_artifact: true`) for every SQL entity
/// (table/view) named in the embedded SQL argument.
///
/// The Python matching convention is the callee's FINAL name segment (not a
/// dotted path): `cursor.execute(...)` matches on `"execute"`, a bare
/// `text(...)` matches on `"text"`. Never fails extraction: a call that
/// doesn't match the expected shape (no matching rule, non-string argument,
/// malformed SQL, …) is simply skipped.
#[cfg(feature = "sql")]
fn collect_query_bindings(
    node: &Node,
    bytes: &[u8],
    file: &str,
    rules: &BindingRules,
    out: &mut Vec<Reference>,
) {
    if node.kind() == "call" {
        if let Some(func) = node.child_by_field_name("function") {
            let attr_name;
            let callee_name: Option<&str> = match func.kind() {
                "identifier" => Some(node_text(&func, bytes)),
                "attribute" => {
                    attr_name = field_text(&func, "attribute", bytes);
                    attr_name.as_deref()
                }
                _ => None,
            };
            if let Some(callee_name) = callee_name {
                for rule in rules.for_language(Language::Python) {
                    if rule.construct != callee_name {
                        continue;
                    }
                    let Some(arguments) = node.child_by_field_name("arguments") else {
                        continue;
                    };
                    let Some(arg) = arguments
                        .named_children(&mut arguments.walk())
                        .nth(rule.sql_arg)
                    else {
                        continue;
                    };
                    emit_embedded_sql_refs(&arg, "string_content", bytes, file, out);
                }
            }
        }
    }

    for child in node.children(&mut node.walk()) {
        collect_query_bindings(&child, bytes, file, rules, out);
    }
}

// ── Scope tree (Tier-B) ──────────────────────────────────────────────────────

/// Build the lexical scope tree for one Python file.
///
/// `scopes[0]` is always the file-root `Module` scope spanning `[0, source_len)`.
/// Python is **function-scoped, not block-scoped**: only `def`/`async def` open
/// a scope; `if`/`for`/`while`/`with` do not. A `class` body is deliberately
/// **not** a scope either — under Python's LEGB rule a method's name lookup skips
/// the enclosing class, so nested defs take the class's enclosing scope as their
/// parent.
///
/// Known v1 boundaries (documented, not yet handled): comprehension and lambda
/// scopes, and the `global`/`nonlocal` rebinding statements.
fn collect_scopes(root: &Node, source_len: usize) -> Vec<Scope> {
    let mut scopes = Vec::new();
    push_scope(
        &mut scopes,
        None,
        ByteSpan {
            start: 0,
            end: source_len,
        },
        ScopeKind::Module,
    );
    for child in root.children(&mut root.walk()) {
        scope_dfs(&child, 0, &mut scopes);
    }
    scopes
}

/// DFS opening a `Function` scope for each `def`, recursing all other nodes with
/// the same parent (so `class` bodies and block statements add no scope).
fn scope_dfs(node: &Node, parent_id: ScopeId, scopes: &mut Vec<Scope>) {
    if node.kind() == "function_definition" {
        let fn_id = push_scope(
            scopes,
            Some(parent_id),
            node_span(node),
            ScopeKind::Function,
        );
        if let Some(body) = node.child_by_field_name("body") {
            for child in body.children(&mut body.walk()) {
                scope_dfs(&child, fn_id, scopes);
            }
        }
    } else {
        for child in node.children(&mut node.walk()) {
            scope_dfs(&child, parent_id, scopes);
        }
    }
}

// ── Bindings (Tier-B) ────────────────────────────────────────────────────────

/// Collect parameter and local-variable [`Binding`]s for one file.
///
/// Covers function parameters and simple `name = …` assignments (each emitted as
/// `BindingKind::Local`/`Param` with `target = BindingTarget::Local`). Tuple/
/// attribute/subscript assignment targets and the walrus operator are deferred.
fn collect_bindings(root: &Node, bytes: &[u8], scopes: &[Scope]) -> Vec<Binding> {
    let mut out = Vec::new();
    collect_bindings_dfs(root, bytes, scopes, &mut out);
    out
}

fn collect_bindings_dfs(node: &Node, bytes: &[u8], scopes: &[Scope], out: &mut Vec<Binding>) {
    match node.kind() {
        "function_definition" => {
            if let Some(params) = node.child_by_field_name("parameters") {
                collect_params(&params, bytes, scopes, out);
            }
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
        "assignment" => {
            // Only a bare `name = …` target binds a local in this unit.
            if let Some(left) = node.child_by_field_name("left") {
                if left.kind() == "identifier" {
                    let intro = left.start_byte();
                    let name = node_text(&left, bytes).to_owned();
                    // An explicit annotation `name: Foo` / `name: Foo = …` (the
                    // `type:` field) records the declared type. A plain
                    // `name = Foo()` leaves it `None`: Python is dynamic and PEP8
                    // capitalization is too weak a signal to infer a constructor
                    // type, so we fail closed rather than guess.
                    let type_name = node
                        .child_by_field_name("type")
                        .map(|t| super::simple_type_name(node_text(&t, bytes), ".").to_owned());
                    push_typed_binding(out, name, intro, BindingKind::Local, scopes, type_name);
                }
            }
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
        _ => {
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
    }
}

/// Emit a [`BindingKind::Param`] for each parameter in a `parameters` node,
/// unwrapping the typed / default / splat parameter forms to the bound name.
fn collect_params(params: &Node, bytes: &[u8], scopes: &[Scope], out: &mut Vec<Binding>) {
    for child in params.named_children(&mut params.walk()) {
        let ident = match child.kind() {
            "identifier" => Some(child),
            "default_parameter" | "typed_default_parameter" => child.child_by_field_name("name"),
            "typed_parameter" | "list_splat_pattern" | "dictionary_splat_pattern" => child
                .named_children(&mut child.walk())
                .find(|c| c.kind() == "identifier"),
            _ => None,
        };
        if let Some(id) = ident {
            if id.kind() == "identifier" {
                let intro = id.start_byte();
                let name = node_text(&id, bytes).to_owned();
                // Parameter type hints (`def f(x: Foo)`) live on the `type:`
                // field of `typed_parameter` / `typed_default_parameter`.
                // Untyped forms (bare identifier, `default_parameter`, splats)
                // have no `type:` field → `None`.
                let type_name = child
                    .child_by_field_name("type")
                    .map(|t| super::simple_type_name(node_text(&t, bytes), ".").to_owned());
                push_typed_binding(out, name, intro, BindingKind::Param, scopes, type_name);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn self_receiver_call_marks_self_receiver() {
        let src =
            "class C:\n    def foo(self):\n        pass\n    def run(self):\n        self.foo()\n";
        let facts = PythonExtractor.extract(src, "src/c.py").unwrap();
        let foo_call = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Call && r.name == "foo")
            .expect("expected a Call reference for 'foo'");
        assert!(
            foo_call.self_receiver,
            "self.foo() should mark self_receiver = true"
        );
        assert_eq!(
            foo_call.qualifier, None,
            "self-call qualifier must stay None"
        );
    }

    #[test]
    fn non_self_receiver_call_does_not_mark_self_receiver() {
        let src = "class C:\n    def foo(self):\n        pass\n    def run(self, obj):\n        obj.foo()\n";
        let facts = PythonExtractor.extract(src, "src/c.py").unwrap();
        let foo_calls: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Call && r.name == "foo")
            .collect();
        assert!(
            foo_calls.iter().any(|r| !r.self_receiver),
            "obj.foo() must NOT mark self_receiver, got {foo_calls:?}"
        );
    }

    #[test]
    fn local_receiver_call_sets_qualifier() {
        // `obj.foo()` where `obj` is a plain identifier → the callee Call ref
        // carries `qualifier = Some("obj")` for the local-typed-call resolver.
        let src = "def run(obj):\n    obj.foo()\n";
        let facts = PythonExtractor.extract(src, "src/c.py").unwrap();
        let foo_call = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Call && r.name == "foo")
            .expect("expected a Call reference for 'foo'");
        assert_eq!(
            foo_call.qualifier.as_deref(),
            Some("obj"),
            "expected qualifier 'obj' on the foo call ref"
        );
        assert!(
            !foo_call.self_receiver,
            "obj.foo() must not be marked self_receiver"
        );
    }

    #[test]
    fn param_type_hint_sets_binding_type_name() {
        // `def f(r: Repo)` → the param binding `r` records type_name Some("Repo").
        let src = "def f(r: Repo):\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/c.py").unwrap();
        let r_binding = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Param && b.name == "r")
            .expect("expected a Param binding for 'r'");
        assert_eq!(r_binding.type_name.as_deref(), Some("Repo"));
    }

    #[test]
    fn annotated_local_sets_binding_type_name() {
        // `x: Foo = make()` → the local binding `x` records type_name Some("Foo").
        let src = "def f():\n    x: Foo = make()\n    return x\n";
        let facts = PythonExtractor.extract(src, "src/c.py").unwrap();
        let x_binding = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Local && b.name == "x")
            .expect("expected a Local binding for 'x'");
        assert_eq!(x_binding.type_name.as_deref(), Some("Foo"));
    }

    #[test]
    fn bare_constructor_local_leaves_type_name_none() {
        // `x = Foo()` — no annotation. Python is dynamic; we fail closed rather
        // than infer a type from PEP8 capitalization.
        let src = "def f():\n    xyz = Foo()\n    return xyz\n";
        let facts = PythonExtractor.extract(src, "src/c.py").unwrap();
        let x_binding = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Local && b.name == "xyz")
            .expect("expected a Local binding for 'xyz'");
        assert_eq!(x_binding.type_name, None);
    }

    #[test]
    fn extracts_defs_with_dotted_module() {
        let src = "\
def validate_token(tok):
    return helper()

class Config:
    pass

async def fetch_data():
    pass

MAX_RETRIES = 3
";
        let facts = PythonExtractor.extract(src, "src/auth/jwt.py").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let vt = by_name("validate_token").unwrap();
        assert_eq!(
            vt.id.to_scip_string(),
            "codegraph . . . auth/jwt/validate_token()."
        );
        assert_eq!(vt.kind, SymbolKind::Function);

        assert_eq!(by_name("Config").unwrap().kind, SymbolKind::Class);
        assert!(by_name("fetch_data").is_some());
        assert_eq!(by_name("MAX_RETRIES").unwrap().kind, SymbolKind::Const);
    }

    /// Every module-level binding — a `TypeVar`, a lowercase/underscore global, an
    /// annotated one — becomes a `Const` symbol; tuple targets and function-local
    /// bindings do not.
    #[test]
    fn extracts_module_level_bindings_as_consts() {
        let src = "\
V = TypeVar('V')
_default_stream = make_stream()
timeout: int = 30

def run():
    local = 1
    return local

a, b = pair()
";
        let facts = PythonExtractor.extract(src, "src/click/util.py").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let v = by_name("V").expect("TypeVar binding");
        assert_eq!(v.kind, SymbolKind::Const);
        assert_eq!(v.id.to_scip_string(), "codegraph . . . click/util/V.");
        assert_eq!(by_name("_default_stream").unwrap().kind, SymbolKind::Const);
        assert_eq!(by_name("timeout").unwrap().kind, SymbolKind::Const);

        // A function-local binding is not a module symbol.
        assert!(by_name("local").is_none());
        // Tuple-unpacking targets have no single addressable name — skipped,
        // and the right-hand side (`pair`) is never mistaken for the target.
        assert!(by_name("a").is_none());
        assert!(by_name("b").is_none());
        assert!(by_name("pair").is_none());
    }

    /// Constants guarded by a module-level `if`/`else` are still module scope —
    /// both branches emit their bindings (distinct occurrences; the resolver
    /// dedups by identity), with plain `module/NAME` descriptors, no `if` segment.
    #[test]
    fn extracts_conditional_module_bindings_as_consts() {
        let src = "if WIN:\n    BEFORE_BAR = \"a\"\nelse:\n    BEFORE_BAR = \"b\"\n    AFTER_BAR = \"c\"\n";
        let facts = PythonExtractor.extract(src, "src/click/util.py").unwrap();

        assert!(
            facts
                .symbols
                .iter()
                .any(|s| s.name == "BEFORE_BAR" && s.kind == SymbolKind::Const),
            "BEFORE_BAR (under if/else) should be a Const module symbol"
        );
        let after = facts
            .symbols
            .iter()
            .find(|s| s.name == "AFTER_BAR")
            .expect("AFTER_BAR (under else) should be emitted");
        assert_eq!(after.kind, SymbolKind::Const);
        assert_eq!(
            after.id.to_scip_string(),
            "codegraph . . . click/util/AFTER_BAR."
        );
    }

    /// A function conditionally defined under `try`/`except` (the classic
    /// optional-import fallback) is emitted as a module-scope Function.
    #[test]
    fn extracts_conditional_module_function() {
        let src = "try:\n    def helper(): pass\nexcept ImportError:\n    def helper(): pass\n";
        let facts = PythonExtractor.extract(src, "src/click/util.py").unwrap();
        assert!(
            facts
                .symbols
                .iter()
                .any(|s| s.name == "helper" && s.kind == SymbolKind::Function),
            "helper (under try/except) should be a module-scope Function"
        );
    }

    /// The recursion descends only through control-flow containers, never into
    /// function/class bodies: a nested `def` or local binding must NOT surface
    /// as a module symbol, though the enclosing `def` itself does.
    #[test]
    fn recursion_does_not_enter_function_bodies() {
        let src = "def outer():\n    inner_const = 1\n    def nested(): pass\n";
        let facts = PythonExtractor.extract(src, "src/click/util.py").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        assert!(by_name("outer").is_some(), "outer is a module function");
        assert!(
            by_name("inner_const").is_none(),
            "function-local binding must not leak as a module Const"
        );
        assert!(
            by_name("nested").is_none(),
            "nested def must not leak as a module Function"
        );
    }

    #[test]
    fn init_collapses_to_package() {
        let facts = PythonExtractor
            .extract("def helper(): pass", "src/auth/__init__.py")
            .unwrap();
        assert_eq!(
            facts.symbols[0].id.to_scip_string(),
            "codegraph . . . auth/helper()."
        );
    }

    #[test]
    fn emits_function_scope_and_bindings() {
        let src = "def run(arg):\n    local = 1\n    helper(arg)\n";
        let facts = PythonExtractor.extract(src, "src/main.py").unwrap();
        // Module root scope + one function scope.
        assert_eq!(facts.scopes.len(), 2, "expected module + function scope");
        assert_eq!(facts.scopes[0].kind, ScopeKind::Module);
        assert_eq!(facts.scopes[1].kind, ScopeKind::Function);

        let has = |name: &str, kind: BindingKind| {
            facts
                .bindings
                .iter()
                .any(|b| b.name == name && b.kind == kind)
        };
        assert!(has("arg", BindingKind::Param), "param binding missing");
        assert!(has("local", BindingKind::Local), "local binding missing");
        assert!(has("run", BindingKind::Definition), "def binding missing");
    }

    #[test]
    fn class_body_opens_no_scope_legb() {
        // Python's LEGB skips the class scope for nested defs, so a class body
        // adds no scope: the method's enclosing scope is the module.
        let src = "class Foo:\n    def method(self):\n        pass\n";
        let facts = PythonExtractor.extract(src, "src/m.py").unwrap();
        let fn_scopes: Vec<_> = facts
            .scopes
            .iter()
            .filter(|s| s.kind == ScopeKind::Function)
            .collect();
        assert_eq!(fn_scopes.len(), 1, "only the method opens a scope");
        assert!(
            !facts.scopes.iter().any(|s| s.kind == ScopeKind::Type),
            "class body must not open a Type scope in Python"
        );
        assert_eq!(
            fn_scopes[0].parent,
            Some(0),
            "method's enclosing scope is the module (class skipped)"
        );
    }

    #[test]
    fn class_methods_emit_method_symbols() {
        let src = "class Base:\n    def hello(self):\n        pass\n";
        let facts = PythonExtractor.extract(src, "src/m.py").unwrap();
        let hello = facts
            .symbols
            .iter()
            .find(|s| s.name == "hello")
            .expect("expected a 'hello' symbol");
        assert_eq!(hello.kind, SymbolKind::Method);
        assert!(
            hello.id.to_scip_string().ends_with("Base#hello()."),
            "unexpected scip string: {}",
            hello.id.to_scip_string()
        );
        assert!(
            facts
                .symbols
                .iter()
                .any(|s| s.name == "Base" && s.kind == SymbolKind::Class),
            "expected Base Class symbol to still be present"
        );
    }

    #[test]
    fn dunder_init_is_emitted_as_method() {
        let src = "class Base:\n    def __init__(self):\n        pass\n";
        let facts = PythonExtractor.extract(src, "src/m.py").unwrap();
        let init =
            facts.symbols.iter().find(|s| s.name == "__init__").expect(
                "expected '__init__' to be emitted (only pure-underscore names are skipped)",
            );
        assert_eq!(init.kind, SymbolKind::Method);
    }

    #[test]
    fn module_level_visibility_follows_pep8_underscore_convention() {
        let src = "\
def public_fn(): pass
def _internal_fn(): pass
def __mangled_fn(): pass
class _Internal: pass
_INTERNAL_CONST = 1
PUBLIC_CONST = 2
";
        let facts = PythonExtractor.extract(src, "src/m.py").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();
        assert_eq!(by_name("public_fn").unwrap().visibility, Visibility::Public);
        assert_eq!(
            by_name("_internal_fn").unwrap().visibility,
            Visibility::Internal
        );
        assert_eq!(
            by_name("__mangled_fn").unwrap().visibility,
            Visibility::Private
        );
        assert_eq!(
            by_name("_Internal").unwrap().visibility,
            Visibility::Internal
        );
        assert_eq!(
            by_name("_INTERNAL_CONST").unwrap().visibility,
            Visibility::Internal
        );
        assert_eq!(
            by_name("PUBLIC_CONST").unwrap().visibility,
            Visibility::Public
        );
    }

    #[test]
    fn class_method_visibility_follows_pep8_underscore_convention() {
        let src = "\
class Base:
    def __init__(self):
        pass

    def _protected(self):
        pass

    def __private(self):
        pass

    def run(self):
        pass
";
        let facts = PythonExtractor.extract(src, "src/m.py").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();
        assert_eq!(by_name("__init__").unwrap().visibility, Visibility::Public);
        assert_eq!(
            by_name("_protected").unwrap().visibility,
            Visibility::Internal
        );
        assert_eq!(
            by_name("__private").unwrap().visibility,
            Visibility::Private
        );
        assert_eq!(by_name("run").unwrap().visibility, Visibility::Public);
    }

    #[test]
    fn decorated_and_async_methods_are_emitted() {
        let src = "\
class Base:
    @staticmethod
    def s():
        pass

    @classmethod
    def c(cls):
        pass

    async def a(self):
        pass
";
        let facts = PythonExtractor.extract(src, "src/m.py").unwrap();
        for name in ["s", "c", "a"] {
            let sym = facts
                .symbols
                .iter()
                .find(|s| s.name == name)
                .unwrap_or_else(|| panic!("expected method '{name}' to be emitted"));
            assert_eq!(sym.kind, SymbolKind::Method, "method '{name}' wrong kind");
        }
    }

    #[test]
    fn nested_def_inside_method_is_not_a_symbol() {
        let src = "\
class Base:
    def outer(self):
        def inner():
            pass
        return inner
";
        let facts = PythonExtractor.extract(src, "src/m.py").unwrap();
        assert!(
            !facts.symbols.iter().any(|s| s.name == "inner"),
            "nested `def inner` must not be emitted as a symbol"
        );
        assert!(facts.symbols.iter().any(|s| s.name == "outer"));
    }

    #[test]
    fn class_methods_do_not_leak_module_scope_bindings() {
        // Guards the risk that method symbols flow through `definition_bindings`
        // (which hard-codes `scope: 0`), which would wrongly make `hello()`
        // resolvable as a bare module-scope call anywhere in the file.
        let src = "class Base:\n    def hello(self):\n        pass\n";
        let facts = PythonExtractor.extract(src, "src/m.py").unwrap();
        assert!(
            !facts
                .bindings
                .iter()
                .any(|b| b.name == "hello" && b.kind == BindingKind::Definition && b.scope == 0),
            "method 'hello' must not have a module-scope Definition binding"
        );
    }

    #[test]
    fn extracts_call_references() {
        let facts = PythonExtractor
            .extract(
                "def main():\n    validate_token('t')\n    helper()\n",
                "src/main.py",
            )
            .unwrap();
        let names: Vec<&str> = facts.references.iter().map(|r| r.name.as_str()).collect();
        assert!(names.contains(&"validate_token"));
        assert!(names.contains(&"helper"));
    }

    #[test]
    fn extracts_single_base_class_inherit_reference() {
        let src = "class Sub(Base):\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/mod.py").unwrap();
        let inherit_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::IsImplementation)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            inherit_names,
            vec!["Base"],
            "expected ['Base'] in {inherit_names:?}"
        );
    }

    #[test]
    fn extracts_multiple_base_classes_inherit_references() {
        let src = "class Multi(A, B):\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/mod.py").unwrap();
        let inherit_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::IsImplementation)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            inherit_names.contains(&"A"),
            "expected 'A' in {inherit_names:?}"
        );
        assert!(
            inherit_names.contains(&"B"),
            "expected 'B' in {inherit_names:?}"
        );
    }

    #[test]
    fn extracts_dotted_base_class_leaf_segment() {
        let src = "class Dotted(mod.Base):\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/mod.py").unwrap();
        let inherit_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::IsImplementation)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            inherit_names,
            vec!["Base"],
            "expected ['Base'] in {inherit_names:?}"
        );
    }

    // --- import extraction tests ---

    #[test]
    fn import_from_statement_emits_leaf_name() {
        let src = "from pkg.models import Config\n";
        let facts = PythonExtractor.extract(src, "src/app.py").unwrap();
        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            import_names,
            vec!["Config"],
            "expected ['Config'] in {import_names:?}"
        );
    }

    #[test]
    fn import_statement_emits_module_leaf() {
        // `import os` → leaf "os"; `import foo.bar` → leaf "bar"
        let src = "import os\nimport foo.bar\n";
        let facts = PythonExtractor.extract(src, "src/mod.py").unwrap();
        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            import_names.contains(&"os"),
            "expected 'os' in {import_names:?}"
        );
        assert!(
            import_names.contains(&"bar"),
            "expected 'bar' in {import_names:?}"
        );
    }

    #[test]
    fn import_from_statement_multiple_names() {
        let src = "from x import A, B\n";
        let facts = PythonExtractor.extract(src, "src/mod.py").unwrap();
        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            import_names.contains(&"A"),
            "expected 'A' in {import_names:?}"
        );
        assert!(
            import_names.contains(&"B"),
            "expected 'B' in {import_names:?}"
        );
    }

    #[test]
    fn import_alias_emits_real_name_not_alias() {
        // `from pkg import Thing as T` → ref "Thing", not "T"
        let src = "from pkg import Thing as T\n";
        let facts = PythonExtractor.extract(src, "src/mod.py").unwrap();
        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            import_names.contains(&"Thing"),
            "expected 'Thing' in {import_names:?}"
        );
        assert!(
            !import_names.contains(&"T"),
            "alias 'T' must NOT appear in {import_names:?}"
        );
    }

    #[test]
    fn wildcard_import_emits_nothing() {
        let src = "from x import *\n";
        let facts = PythonExtractor.extract(src, "src/mod.py").unwrap();
        let import_refs: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            import_refs.is_empty(),
            "expected no Import refs for wildcard, got {import_refs:?}"
        );
    }

    #[test]
    fn import_refs_carry_source_module() {
        // The import refs for `from pkg.models import Config` should all have
        // `source_module == Some(<module scip id of src/app.py>)`.
        let src = "from pkg.models import Config\n";
        let file = "src/app.py";
        let facts = PythonExtractor.extract(src, file).unwrap();

        // Compute expected module id the same way the extractor does.
        let namespaces = python_namespaces(file);
        let expected_module_id =
            crate::extract::module_symbol(Language::Python, &namespaces, file, src.len())
                .id
                .to_scip_string();

        let import_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .collect();
        assert!(!import_refs.is_empty(), "expected at least one Import ref");
        for r in &import_refs {
            assert_eq!(
                r.source_module,
                Some(expected_module_id.clone()),
                "Import ref '{}' should carry source_module = {:?}",
                r.name,
                expected_module_id
            );
        }
    }

    #[test]
    fn call_refs_have_no_source_module() {
        let src = "def main():\n    helper()\n";
        let facts = PythonExtractor.extract(src, "src/main.py").unwrap();
        let call_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Call)
            .collect();
        assert!(!call_refs.is_empty(), "expected at least one Call ref");
        for r in &call_refs {
            assert_eq!(
                r.source_module, None,
                "Call ref '{}' must have source_module = None",
                r.name
            );
        }
    }

    // ── Edge richness: TypeRef / Read / Write ────────────────────────────────

    #[test]
    fn py_param_type_ref_emitted() {
        // `def f(c: Config): pass` → TypeRef "Config" with ParameterType ctx.
        let src = "def f(c: Config): pass\n";
        let facts = PythonExtractor.extract(src, "src/main.py").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::TypeRef && r.name == "Config")
            .expect("expected TypeRef ref for 'Config'");
        assert_eq!(
            r.type_ref_ctx,
            Some(TypeRefContext::ParameterType),
            "expected ParameterType ctx, got {:?}",
            r.type_ref_ctx
        );
    }

    #[test]
    fn py_return_type_ref_emitted() {
        // `def f() -> Config: pass` → TypeRef "Config" with ReturnType ctx.
        let src = "def f() -> Config: pass\n";
        let facts = PythonExtractor.extract(src, "src/main.py").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::TypeRef && r.name == "Config")
            .expect("expected TypeRef ref for 'Config'");
        assert_eq!(
            r.type_ref_ctx,
            Some(TypeRefContext::ReturnType),
            "expected ReturnType ctx, got {:?}",
            r.type_ref_ctx
        );
    }

    #[test]
    fn py_annotated_field_type_ref_emitted() {
        // `class C:\n    name: Config` → TypeRef "Config" with Field ctx.
        let src = "class C:\n    name: Config\n";
        let facts = PythonExtractor.extract(src, "src/main.py").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::TypeRef && r.name == "Config")
            .expect("expected TypeRef ref for 'Config'");
        assert_eq!(
            r.type_ref_ctx,
            Some(TypeRefContext::Field),
            "expected Field ctx, got {:?}",
            r.type_ref_ctx
        );
    }

    #[test]
    fn py_read_ref_emitted_for_use_not_declaration() {
        // `def f():\n    base = 1\n    return base`
        // → Read ref for `base` in `return base`; the LHS `base` is a Write, not a Read.
        let src = "def f():\n    base = 1\n    return base\n";
        let facts = PythonExtractor.extract(src, "src/main.py").unwrap();
        let read_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read && r.name == "base")
            .collect();
        assert!(
            !read_refs.is_empty(),
            "expected at least one Read ref for 'base', got none"
        );
        // `return base` starts after the assignment line (byte > 20).
        let use_ref = read_refs
            .iter()
            .find(|r| r.occ.byte > 20)
            .expect("expected Read ref for 'base' in the return statement (byte > 20)");
        assert!(
            use_ref.occ.byte > 20,
            "Read ref should be at the use site, not the declaration"
        );
    }

    #[test]
    fn py_write_ref_emitted_for_assignment() {
        // `def f():\n    xxx = 5` → Write ref for `xxx`.
        let src = "def f():\n    xxx = 5\n";
        let facts = PythonExtractor.extract(src, "src/main.py").unwrap();
        let write_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Write && r.name == "xxx")
            .collect();
        assert!(
            !write_refs.is_empty(),
            "expected at least one Write ref for 'xxx', got none — all refs: {:?}",
            facts
                .references
                .iter()
                .map(|r| (&r.name, r.role))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn py_call_not_also_read() {
        // `helper()` → a Call ref for "helper", but NOT also a Read ref.
        let src = "def run():\n    helper()\n";
        let facts = PythonExtractor.extract(src, "src/main.py").unwrap();
        let call_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Call && r.name == "helper")
            .collect();
        assert!(!call_refs.is_empty(), "expected a Call ref for 'helper'");
        let read_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read && r.name == "helper")
            .collect();
        assert!(
            read_refs.is_empty(),
            "helper() must NOT produce a Read ref; got: {read_refs:?}"
        );
    }

    #[test]
    fn py_attribute_not_a_read_of_property() {
        // `obj.foo` → no Read ref named "foo" (only `obj` can be a Read).
        let src = "def run():\n    return obj.foo\n";
        let facts = PythonExtractor.extract(src, "src/main.py").unwrap();
        let foo_reads: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read && r.name == "foo")
            .collect();
        assert!(
            foo_reads.is_empty(),
            "attribute 'foo' must NOT be a Read ref; got: {foo_reads:?}"
        );
    }

    // --- module-path ModuleRef tests ---

    fn module_ref_names(facts: &FileFacts) -> Vec<String> {
        let mut names: Vec<String> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::ModuleRef)
            .map(|r| r.name.clone())
            .collect();
        names.sort();
        names
    }

    #[test]
    fn from_import_emits_module_refs_for_path_segments() {
        let src = "from a.b import c\n";
        let facts = PythonExtractor.extract(src, "src/app.py").unwrap();
        assert_eq!(
            module_ref_names(&facts),
            vec!["a".to_owned(), "b".to_owned()],
        );
        assert!(
            facts
                .references
                .iter()
                .any(|r| r.role == RefRole::Import && r.name == "c"),
            "expected Import ref 'c'"
        );
    }

    #[test]
    fn from_single_module_import() {
        let src = "from a import c\n";
        let facts = PythonExtractor.extract(src, "src/app.py").unwrap();
        assert_eq!(module_ref_names(&facts), vec!["a".to_owned()]);
        assert!(
            facts
                .references
                .iter()
                .any(|r| r.role == RefRole::Import && r.name == "c"),
            "expected Import ref 'c'"
        );
    }

    #[test]
    fn import_dotted_emits_module_refs_except_leaf() {
        let src = "import a.b.c\n";
        let facts = PythonExtractor.extract(src, "src/app.py").unwrap();
        assert_eq!(
            module_ref_names(&facts),
            vec!["a".to_owned(), "b".to_owned()],
        );
        assert!(
            facts
                .references
                .iter()
                .any(|r| r.role == RefRole::Import && r.name == "c"),
            "expected Import ref 'c' (the leaf segment) to still be present"
        );
    }

    #[test]
    fn relative_import_no_crash() {
        let src = "from . import x\n";
        let facts = PythonExtractor.extract(src, "src/app.py").unwrap();
        // The lone dot has no module identifier → no ModuleRef at all.
        let module_refs = module_ref_names(&facts);
        assert!(
            module_refs.is_empty(),
            "relative `from . import x` must emit no ModuleRef, got {:?}",
            module_refs
        );
        // And no empty-named ref leaked through anywhere.
        assert!(
            facts.references.iter().all(|r| !r.name.is_empty()),
            "no reference should have an empty name"
        );
    }

    // --- from_path tests ---

    #[test]
    fn import_from_statement_carries_from_path() {
        // `from pkg.models import Config` → from_path == "pkg.models"
        let src = "from pkg.models import Config\n";
        let facts = PythonExtractor.extract(src, "src/app.py").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Import && r.name == "Config")
            .expect("expected Import ref for 'Config'");
        assert_eq!(
            r.from_path,
            Some("pkg.models".to_owned()),
            "from_path should be 'pkg.models', got {:?}",
            r.from_path
        );
    }

    #[test]
    fn plain_import_statement_carries_from_path() {
        // `import os` → from_path == "os"; `import foo.bar` → from_path == "foo.bar"
        let src = "import os\nimport foo.bar\n";
        let facts = PythonExtractor.extract(src, "src/mod.py").unwrap();

        let os_ref = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Import && r.name == "os")
            .expect("expected Import ref for 'os'");
        assert_eq!(
            os_ref.from_path,
            Some("os".to_owned()),
            "from_path for 'import os' should be 'os', got {:?}",
            os_ref.from_path
        );

        let bar_ref = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Import && r.name == "bar")
            .expect("expected Import ref for 'bar'");
        assert_eq!(
            bar_ref.from_path,
            Some("foo.bar".to_owned()),
            "from_path for 'import foo.bar' should be 'foo.bar', got {:?}",
            bar_ref.from_path
        );
    }

    // ── Entry-point detection ────────────────────────────────────────────────

    /// Helper: find a symbol by bare name and return a clone.
    fn sym_by_name(facts: &FileFacts, name: &str) -> Symbol {
        facts
            .symbols
            .iter()
            .find(|s| s.name == name)
            .unwrap_or_else(|| {
                panic!("symbol '{name}' not found; symbols: {:?}", {
                    let names: Vec<&str> = facts.symbols.iter().map(|s| s.name.as_str()).collect();
                    names
                })
            })
            .clone()
    }

    /// Helper: render entry_points as a compact string for assertion messages.
    fn ep_str(eps: &[EntryPoint]) -> String {
        eps.iter()
            .map(|ep| match ep {
                EntryPoint::Main => "Main".to_owned(),
                EntryPoint::HttpRoute(m) => format!("HttpRoute({m})"),
            })
            .collect::<Vec<_>>()
            .join(", ")
    }

    #[test]
    fn entry_point_app_get_route() {
        // @app.get("/users") → HttpRoute("app.get")
        let src = "@app.get(\"/users\")\ndef list_users():\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/routes.py").unwrap();
        let sym = sym_by_name(&facts, "list_users");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point, got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::HttpRoute(m) if m == "app.get"),
            "expected HttpRoute(\"app.get\"), got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn entry_point_app_route_with_methods_arg() {
        // @app.route("/x", methods=["POST"]) → HttpRoute("app.route")
        let src = "@app.route(\"/x\", methods=[\"POST\"])\ndef handler():\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/routes.py").unwrap();
        let sym = sym_by_name(&facts, "handler");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point, got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::HttpRoute(m) if m == "app.route"),
            "expected HttpRoute(\"app.route\"), got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn entry_point_non_route_decorator_ignored() {
        // A top-level call-form decorator whose terminal name is NOT a route verb
        // (`lru_cache` ∉ PY_ROUTE_VERBS) must produce no entry point. (Bare
        // non-call decorators like `@staticmethod` only appear on class methods,
        // which `collect_symbols` doesn't descend into.)
        let src =
            "import functools\n@functools.lru_cache(maxsize=128)\ndef compute(x):\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/util.py").unwrap();
        let sym2 = sym_by_name(&facts, "compute");
        assert!(
            sym2.entry_points.is_empty(),
            "non-route call decorator must not produce entry points; got [{}]",
            ep_str(&sym2.entry_points)
        );
    }

    #[test]
    fn entry_point_main_function() {
        // def main(): pass → EntryPoint::Main
        let src = "def main():\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/main.py").unwrap();
        let sym = sym_by_name(&facts, "main");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point, got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::Main),
            "expected Main, got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn entry_point_plain_function_empty() {
        // An undecorated, non-main function → empty entry_points.
        let src = "def process(data):\n    return data\n";
        let facts = PythonExtractor.extract(src, "src/util.py").unwrap();
        let sym = sym_by_name(&facts, "process");
        assert!(
            sym.entry_points.is_empty(),
            "plain function must have no entry points; got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn entry_point_fastapi_router_post() {
        // @router.post("/items") → HttpRoute("router.post")
        let src = "@router.post(\"/items\")\ndef create_item():\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/items.py").unwrap();
        let sym = sym_by_name(&facts, "create_item");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point, got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::HttpRoute(m) if m == "router.post"),
            "expected HttpRoute(\"router.post\"), got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn entry_point_websocket_route() {
        // @bp.websocket("/ws") → HttpRoute("bp.websocket")
        let src = "@bp.websocket(\"/ws\")\ndef ws_handler():\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/ws.py").unwrap();
        let sym = sym_by_name(&facts, "ws_handler");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point, got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::HttpRoute(m) if m == "bp.websocket"),
            "expected HttpRoute(\"bp.websocket\"), got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn entry_point_main_guard_marks_module() {
        // A module-level `if __name__ == "__main__":` guard marks the MODULE
        // symbol (kind Module) as a `Main` entry point.
        let src = "if __name__ == \"__main__\":\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/app.py").unwrap();
        let module = facts
            .symbols
            .iter()
            .find(|s| s.kind == SymbolKind::Module)
            .expect("expected a Module symbol");
        assert!(
            module
                .entry_points
                .iter()
                .any(|ep| matches!(ep, EntryPoint::Main)),
            "module guard must mark the module Main; got [{}]",
            ep_str(&module.entry_points)
        );
    }

    #[test]
    fn entry_point_non_main_guard_ignored() {
        // `if __name__ == "__other__":` is NOT the main guard → no entry point.
        let src = "if __name__ == \"__other__\":\n    pass\n";
        let facts = PythonExtractor.extract(src, "src/app.py").unwrap();
        let module = facts
            .symbols
            .iter()
            .find(|s| s.kind == SymbolKind::Module)
            .expect("expected a Module symbol");
        assert!(
            module.entry_points.is_empty(),
            "non-main guard must not mark the module; got [{}]",
            ep_str(&module.entry_points)
        );
    }

    // ── Query-binding cross-artifact refs (code→SQL) ─────────────────────────

    #[cfg(feature = "sql")]
    #[test]
    fn method_call_query_binding_emits_cross_artifact_typeref() {
        let src = "cursor.execute(\"SELECT id FROM users\")\n";
        let facts = PythonExtractor
            .extract_with_bindings(src, "src/app.py", &BindingRules::with_defaults())
            .unwrap();

        let found = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::TypeRef && r.name == "users" && r.cross_artifact);
        let r = found.expect("expected a cross-artifact TypeRef reference named 'users'");

        let select_byte = src.find("SELECT").expect("fixture contains SELECT");
        assert!(
            r.occ.byte >= select_byte,
            "reference byte {} should point at/after 'SELECT' at {}",
            r.occ.byte,
            select_byte
        );
    }

    #[cfg(feature = "sql")]
    #[test]
    fn plain_function_query_binding_emits_cross_artifact_typeref() {
        let src = "text(\"SELECT id FROM orders\")\n";
        let facts = PythonExtractor
            .extract_with_bindings(src, "src/app.py", &BindingRules::with_defaults())
            .unwrap();

        let found = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::TypeRef && r.name == "orders" && r.cross_artifact);
        found.expect("expected a cross-artifact TypeRef reference named 'orders'");
    }

    #[cfg(feature = "sql")]
    #[test]
    fn empty_binding_rules_yield_no_cross_artifact_reference() {
        let src = "cursor.execute(\"SELECT id FROM users\")\n";
        let file = "src/app.py";

        let with_empty_rules = PythonExtractor
            .extract_with_bindings(src, file, &BindingRules::empty())
            .unwrap();
        assert!(
            !with_empty_rules.references.iter().any(|r| r.cross_artifact),
            "an empty binding-rule registry must yield no cross-artifact references"
        );

        let plain = PythonExtractor.extract(src, file).unwrap();
        assert!(
            !plain.references.iter().any(|r| r.cross_artifact),
            "the plain extract() path must yield no cross-artifact references"
        );
    }
}