bonsai-ninja-lang-csharp 0.2.1

C# language adapter.
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
//! C# language adapter.
mod parse_recovery;

use bonsai_common::{FileId, Span};
use bonsai_lang_api::{
    collect_assign_targets, collect_param_type_aliases, decl_index_with_handler, extract_imports_via,
    kit::{
        call_arg_from_node_with_handler, canonical_simple_type_name, collect_kinds,
        collect_receiver_field_writes, language_from_pack, node_text,
        package_module_segments_with_workspace_prefix, parse_with, span_of,
    },
    AdapterContext, AdapterError, ArgumentPassingMode, CallArg, CallKind, CallTargetExtraction, DeclIndex,
    DeclKind, FieldWrite, FlowEvent, GrammarHandler, ImportIndex, ImportScope, ImportSpec, LanguageAdapter,
    LanguageCapabilities, LanguageId, PatternBindingSite, TypeAliasBinding, TypeAliasVocabulary, Visibility,
    EMPTY_HANDLER,
};
use parse_recovery::csharp_parse_recovery_edits;
use tree_sitter::Node;

fn csharp_call_target<'tree>(node: Node<'tree>, src: &[u8]) -> Option<CallTargetExtraction<'tree>> {
    let target = match node.kind() {
        "invocation_expression" => node.child_by_field_name("function")?,
        "object_creation_expression" => node.child_by_field_name("type")?,
        _ => return None,
    };
    let full_text = node_text(&target, src).trim();
    (!full_text.is_empty()).then_some(CallTargetExtraction {
        node: target,
        full_text: full_text.to_string(),
    })
}

fn csharp_pattern_bindings(node: Node<'_>) -> Vec<PatternBindingSite<'_>> {
    let mut sites = Vec::new();
    if let Some(condition) = node.child_by_field_name("condition") {
        let mut stack = vec![condition];
        while let Some(current) = stack.pop() {
            if current.kind() == "is_pattern_expression" {
                if let (Some(source), Some(pattern)) = (
                    current.child_by_field_name("expression"),
                    current.child_by_field_name("pattern"),
                ) {
                    csharp_pattern_binding_names(pattern, current, source, &mut sites);
                }
                continue;
            }
            let mut cursor = current.walk();
            stack.extend(current.named_children(&mut cursor));
        }
    }
    if let (Some(source), Some(body)) = (
        node.child_by_field_name("value"),
        node.child_by_field_name("body"),
    ) {
        let mut stack = vec![body];
        while let Some(current) = stack.pop() {
            if current.kind() == "switch_section" {
                let mut cursor = current.walk();
                for child in current.named_children(&mut cursor) {
                    csharp_pattern_binding_names(child, current, source, &mut sites);
                }
                continue;
            }
            let mut cursor = current.walk();
            stack.extend(current.named_children(&mut cursor));
        }
    }
    sites
}

fn csharp_pattern_binding_names<'tree>(
    pattern: Node<'tree>,
    span_node: Node<'tree>,
    source: Node<'tree>,
    out: &mut Vec<PatternBindingSite<'tree>>,
) {
    if matches!(
        pattern.kind(),
        "declaration_pattern" | "var_pattern" | "recursive_pattern"
    ) {
        if let Some(name) = pattern.child_by_field_name("name") {
            out.push(PatternBindingSite {
                span_node,
                pattern: name,
                source,
            });
        }
    }
    if pattern.kind() == "parenthesized_variable_designation" {
        let mut cursor = pattern.walk();
        if cursor.goto_first_child() {
            loop {
                let child = cursor.node();
                if child.is_named() && cursor.field_name() == Some("name") {
                    out.push(PatternBindingSite {
                        span_node,
                        pattern: child,
                        source,
                    });
                }
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
        }
    }
    if !matches!(
        pattern.kind(),
        "pattern"
            | "declaration_pattern"
            | "var_pattern"
            | "recursive_pattern"
            | "parenthesized_pattern"
            | "and_pattern"
            | "or_pattern"
            | "negated_pattern"
            | "list_pattern"
            | "tuple_pattern"
            | "subpattern"
            | "positional_pattern_clause"
            | "property_pattern_clause"
            | "parenthesized_variable_designation"
    ) {
        return;
    }
    let mut cursor = pattern.walk();
    for child in pattern.named_children(&mut cursor) {
        if pattern
            .child_by_field_name("type")
            .is_some_and(|ty| ty.id() == child.id())
        {
            continue;
        }
        csharp_pattern_binding_names(child, span_node, source, out);
    }
}

const CSHARP_TYPE_ALIASES: TypeAliasVocabulary = TypeAliasVocabulary {
    fn_kinds: &[
        "method_declaration",
        "constructor_declaration",
        "local_function_statement",
    ],
    param_kinds: &["parameter"],
    name_field: "name",
    type_field: "type",
};

const CSHARP_DECL_KINDS: &[&str] = &[
    "method_declaration",
    "constructor_declaration",
    "destructor_declaration",
    "class_declaration",
    "struct_declaration",
    "interface_declaration",
    "record_declaration",
    "enum_declaration",
    "delegate_declaration",
    "property_declaration",
    "event_declaration",
    "field_declaration",
    "local_function_statement",
];

// C# default for type members is `private` and for top-level
// types it's `internal`, but applying that strictly when
// module_path is the file-stem fallback would block legitimate
// cross-file calls within the same project. Default to `Public`
// until real module_path coverage (namespace declarations) lands;
// tighten then.
const CSHARP_DEFAULT_VISIBILITY: Visibility = Visibility::Public;
use tree_sitter::{Language, Tree};

fn csharp_foreach_binding(node: Node<'_>) -> Option<(Node<'_>, Node<'_>)> {
    (node.kind() == "foreach_statement")
        .then(|| {
            Some((
                node.child_by_field_name("left")?,
                node.child_by_field_name("right")?,
            ))
        })
        .flatten()
}

pub const LANG_ID: LanguageId = LanguageId::new("csharp");
const PACK_NAME: &str = "csharp";
// `accessor_declaration` is C#'s property getter/setter body. Treating
// it as a function-declaration kind gives each accessor its own Decl
// with its own flow_events so taint that flows through `string X
// { get => …; set => _x = value; }` is observed end-to-end. Without
// this the property collapses into a Field decl and accessor body
// events disappear (audit task #131). `constructor_declaration` and
// `destructor_declaration` join the set so RAII / dtor flows surface.
const HANDLER: GrammarHandler = GrammarHandler {
    expression_value_kind_extractor: None,
    literal_value_kinds: &[
        "null_literal",
        "boolean_literal",
        "integer_literal",
        "real_literal",
        "true",
        "false",
    ],
    string_literal_kinds: &[
        "string_literal",
        "verbatim_string_literal",
        "raw_string_literal",
        "interpolated_string_expression",
        "character_literal",
    ],
    comment_kinds: &["comment"],
    doc_comment_prefixes: &["///", "/**"],
    decorator_kinds: &["attribute"],
    parameter_container_kinds: &["parameter_list"],
    parameter_kinds: &["parameter", "implicit_parameter"],
    parameter_modifier_kinds: &["attribute_list"],
    parameter_annotation_kinds: &["attribute"],
    implicit_parameter_kinds: &["implicit_parameter"],
    binding_identifier_kinds: &["identifier"],
    pattern_binding_extractor: Some(csharp_pattern_bindings),
    identifier_kinds: &["identifier"],
    aggregate_pattern_kinds: &["tuple_pattern"],
    positional_aggregate_kinds: &[
        "tuple_expression",
        "array_initializer",
        "array_creation_expression",
    ],
    aggregate_value_field_names: &["value", "expression"],
    spread_kinds: &["spread_element"],
    spread_value_field_names: &["expression"],
    aggregate_syntax_only_kinds: &["type"],
    transparent_call_wrapper_kinds: &[
        "member_access_expression",
        "parenthesized_expression",
        "await_expression",
        "as_expression",
        "non_null_expression",
    ],
    assignment_target_wrapper_kinds: &["variable_declarator", "variable_declaration"],
    binding_declaration_keyword_spellings: &["const"],
    fn_kinds: &[
        "method_declaration",
        "local_function_statement",
        "accessor_declaration",
        "constructor_declaration",
        "destructor_declaration",
    ],
    call_kinds: &["invocation_expression", "object_creation_expression"],
    constructor_call_kinds: &["object_creation_expression"],
    call_callee_field_names: &["function"],
    constructor_type_field_names: &["type"],
    call_target_extractor: Some(csharp_call_target),
    call_argument_field_names: &["arguments"],
    call_argument_container_kinds: &["argument_list"],
    argument_wrapper_kinds: &["argument"],
    argument_name_field_names: &["name"],
    argument_value_field_names: &["expression"],
    writeback_operand_field_names: &["expression"],
    transparent_expression_wrapper_kinds: &["expression"],
    lambda_body_field_names: &["body", "expression_body"],
    argument_passing_mode_extractor: Some(csharp_argument_passing_mode),
    constructor_names: bonsai_lang_api::NO_CONSTRUCTOR_METHOD_NAMES,
    runtime_type_guard_operators: &["is"],
    runtime_type_wrapper_kinds: &["parenthesized_expression"],
    value_free_expression_kinds: &["sizeof_expression", "typeof_expression"],
    value_free_call_names: &["nameof"],
    call_ref_kinds: &["invocation_expression", "object_creation_expression"],
    member_expression_kinds: &["member_access_expression", "property_access_expression"],
    subscript_expression_kinds: &["element_access_expression"],
    member_base_field_names: &["expression", "object"],
    member_name_field_names: &["name"],
    subscript_base_field_names: &["expression", "object"],
    subscript_index_field_names: &["argument", "index"],
    class_kinds: &[
        "class_declaration",
        "struct_declaration",
        "interface_declaration",
        "enum_declaration",
        "record_declaration",
    ],
    class_decl_kinds: &[
        ("class_declaration", DeclKind::Class),
        ("record_declaration", DeclKind::Class),
        ("struct_declaration", DeclKind::Struct),
        ("interface_declaration", DeclKind::Interface),
        ("enum_declaration", DeclKind::Enum),
    ],
    method_kinds: &["method_declaration", "accessor_declaration"],
    method_context_kinds: &[
        "class_declaration",
        "struct_declaration",
        "interface_declaration",
        "record_declaration",
    ],
    constructor_method_kinds: &["constructor_declaration"],
    if_kinds: &[
        "if_statement",
        "conditional_expression",
        "switch_statement",
        "switch_expression",
    ],
    branch_then_field_names: &["consequence", "body"],
    branch_else_field_names: &["alternative"],
    branch_condition_field_names: &["condition", "value"],
    loop_body_field_names: &["body"],
    loop_body_kinds: &["block", "expression_statement"],
    branch_arm_kinds: &["block", "expression_statement", "switch_section"],
    for_kinds: &["for_statement"],
    foreach_kinds: &["foreach_statement"],
    foreach_binding_extractor: Some(csharp_foreach_binding),
    while_kinds: &["while_statement"],
    do_kinds: &["do_statement"],
    assignment_kinds: &[
        "assignment_expression",
        "variable_declarator",
        "property_declaration",
        "variable_declaration",
        "local_declaration_statement",
    ],
    compound_assignment_operators: &[
        "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", "&=", "^=", "|=", "??=",
    ],
    type_only_declaration_kinds: &[
        "property_declaration",
        "variable_declaration",
        "local_declaration_statement",
    ],
    return_kinds: &["return_statement"],
    throw_kinds: &["throw_statement", "throw_expression"],
    lambda_kinds: &["lambda_expression"],
    try_kinds: &["try_statement"],
    catch_kinds: &["catch_clause"],
    finally_kinds: &["finally_clause"],
    break_kinds: &["break_statement"],
    continue_kinds: &["continue_statement"],
    control_label_field_names: &[],
    yield_kinds: &["yield_statement"],
    yield_value_field_names: &["expression"],
    await_kinds: &["await_expression"],
    using_kinds: &["using_statement"],
    using_body_field_names: &["body"],
    try_body_field_names: &["body"],
    implicit_receiver_names: &["this", "base"],
    ..EMPTY_HANDLER
};

fn csharp_argument_passing_mode(argument: Node<'_>, value: Node<'_>) -> ArgumentPassingMode {
    if [argument, value].into_iter().any(|node| {
        matches!(node.kind(), "argument" | "ref_expression") && {
            let mut cursor = node.walk();
            let has_writeback_marker = node
                .children(&mut cursor)
                .any(|child| matches!(child.kind(), "ref" | "out" | "in" | "ref_kind_keyword"));
            has_writeback_marker
        }
    }) {
        ArgumentPassingMode::WriteBack
    } else {
        ArgumentPassingMode::Value
    }
}

#[derive(Debug, Default, Copy, Clone)]
pub struct CSharpAdapter;

impl CSharpAdapter {
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl LanguageAdapter for CSharpAdapter {
    fn language_id(&self) -> LanguageId {
        LANG_ID
    }
    fn display_name(&self) -> &'static str {
        "C#"
    }
    fn file_extensions(&self) -> &'static [&'static str] {
        // `.csx` is C#'s script / interactive form — same grammar and
        // lookup semantics apply.
        &["cs", "csx"]
    }
    fn tree_sitter_language(&self) -> Result<Language, AdapterError> {
        language_from_pack(PACK_NAME)
    }
    fn parse_recovery_edits(
        &self,
        snapshot: &bonsai_lang_api::FileSnapshot,
        _vfs: &bonsai_lang_api::Vfs,
        tree: &bonsai_lang_api::SyntaxTree,
    ) -> Vec<bonsai_lang_api::ParseRecoveryEdit> {
        csharp_parse_recovery_edits(snapshot, tree)
    }
    fn capabilities(&self) -> LanguageCapabilities {
        // Exceptions: the adapter populates `Throw::thrown_type` from
        // `throw new IOException(...)` and `Try::catch_types` from
        // `catch (IOException e)`. Catch-all `catch { }` arms produce
        // an empty `catch_types` and the engine falls back to the
        // conservative seed-on-any-tainted-throw behavior.
        LanguageCapabilities {
            module_default_export_names: &[],
            universal_type_names: &["object", "Object", "dynamic"],
            module_path_syntax: bonsai_lang_api::ModulePathSyntax::none(),
            exceptions: bonsai_lang_api::CapabilityLevel::Exact,
            receiver_types: bonsai_lang_api::CapabilityLevel::Partial,
            constructor_method_names: bonsai_lang_api::NO_CONSTRUCTOR_METHOD_NAMES,
            super_receiver_tokens: &["base"],
            implicit_receiver_tokens: &["this"],
            ..LanguageCapabilities::partial_baseline()
        }
    }
    fn extract_declarations(&self, file: FileId, ctx: &AdapterContext<'_>) -> DeclIndex {
        let mut idx = decl_index_with_handler(PACK_NAME, file, ctx, &HANDLER);
        let mut class_member_names_by_symbol: std::collections::HashMap<
            bonsai_common::SymbolId,
            std::collections::HashSet<String>,
        > = std::collections::HashMap::new();
        if let Some((snapshot, tree)) = parse_with(PACK_NAME, file, ctx) {
            let src = snapshot.text.as_bytes();
            // Phase-6 return-type extraction: `T Method() {}` populates
            // `Decl.return_type` for `apply_assign_call_result_types`.
            bonsai_lang_api::populate_decl_return_types(&mut idx, &tree, src, &HANDLER);
            for decl in &mut idx.defs {
                populate_csharp_exception_types(&mut decl.flow_events, &tree, src);
            }
        }
        let pkg = parse_with(PACK_NAME, file, ctx).and_then(|(snapshot, tree)| {
            extract_csharp_namespace(tree.root_node(), snapshot.text.as_bytes())
        });
        if let Some(segments) = pkg {
            let segments = package_module_segments_with_workspace_prefix(file, ctx, segments, &[]);
            bonsai_lang_api::apply_module_path_semantic_identity(&mut idx, segments);
        } else {
            bonsai_lang_api::apply_file_stem_semantic_identity(&mut idx, ctx);
        }
        if let Some((snapshot, tree)) = parse_with(PACK_NAME, file, ctx) {
            let src = snapshot.text.as_bytes();
            let vis_map = collect_csharp_visibility(tree.root_node(), file, src);
            let alias_map = collect_param_type_aliases(&tree, file, src, &CSHARP_TYPE_ALIASES);
            // Locally-declared receiver types (casts / typed locals).
            let local_alias_map = collect_csharp_local_type_aliases(&tree, file, src);
            // Class-level field/property type bindings extend each
            // method's `type_aliases`. A field declared as `private
            // readonly AuthService _authService = new AuthService();`
            // must be visible inside the class's methods so receiver
            // calls like `_authService.RunAdminCommand(...)` resolve
            // through the workspace's `AuthService` decl. The
            // class-scoped collection mirrors Java's pattern in
            // `lang_java` and applies symmetrically to property
            // declarations (`public Foo Bar { get; set; }` carries
            // the same `Bar : Foo` binding).
            let class_field_aliases = collect_csharp_class_field_aliases(&tree, file, src);
            // Pre-compute the parent class span for each method-like
            // decl so the per-decl pass below can patch `type_aliases`
            // without re-borrowing `idx.defs` while it's already
            // mutably borrowed.
            let class_span_for_parent: std::collections::HashMap<bonsai_common::SymbolId, Span> = idx
                .defs
                .iter()
                .filter(|candidate| is_class_like(candidate.kind))
                .map(|candidate| (candidate.symbol, candidate.span))
                .collect();
            for (class_symbol, class_span) in &class_span_for_parent {
                let Some(field_aliases) = class_field_aliases
                    .iter()
                    .find_map(|(span, aliases)| (*span == *class_span).then_some(aliases))
                else {
                    continue;
                };
                let names = class_member_names_by_symbol.entry(*class_symbol).or_default();
                names.extend(
                    field_aliases
                        .iter()
                        .map(|alias| alias.name.trim())
                        .filter(|name| !name.is_empty())
                        .map(str::to_string),
                );
            }
            for decl in &mut idx.defs {
                if let Some(vis) = vis_map.get(&decl.span).copied() {
                    decl.visibility = vis;
                }
                let mut aliases = alias_map.get(&decl.span).cloned().unwrap_or_default();
                if let Some(locals) = local_alias_map.get(&decl.span) {
                    for alias in locals {
                        // Param annotations (added first) take precedence
                        // over a local of the same name.
                        if !aliases.iter().any(|existing| existing.name == alias.name) {
                            aliases.push(alias.clone());
                        }
                    }
                }
                if matches!(
                    decl.kind,
                    DeclKind::Function | DeclKind::Method | DeclKind::Constructor
                ) {
                    if let Some(class_span) = decl
                        .parent
                        .and_then(|parent_sym| class_span_for_parent.get(&parent_sym).copied())
                    {
                        if let Some(field_aliases) = class_field_aliases
                            .iter()
                            .find_map(|(span, list)| (*span == class_span).then_some(list))
                        {
                            for alias in field_aliases {
                                if !aliases.contains(alias) {
                                    aliases.push(alias.clone());
                                }
                            }
                        }
                    }
                }
                if !aliases.is_empty() {
                    decl.type_aliases = aliases;
                }
            }
            // Per-class `bases`: `class Echo : Base, IFoo` → ["Base", "IFoo"].
            // C# uses a single `base_list` for both class super and
            // interface impls — they're indistinguishable in syntax.
            let bases_by_span = collect_csharp_class_bases(&tree, file, src);
            for decl in &mut idx.defs {
                if !is_class_like(decl.kind) {
                    continue;
                }
                if let Some(bases) = bases_by_span
                    .iter()
                    .find_map(|(span, bases)| (*span == decl.span).then_some(bases))
                {
                    decl.bases = bases.clone();
                }
            }
        }
        for decl in &mut idx.defs {
            bonsai_lang_api::normalize_call_result_assignment_sources(&mut decl.flow_events);
        }
        // Synthesize implicit members of positional `record`
        // declarations (canonical constructor + component accessors) so
        // `new R(.., tainted, ..)` and `r.Comp` thread taint — C#
        // records have no grammar nodes for these. Shared with lang_java.
        if let Some((snapshot, tree)) = parse_with(PACK_NAME, file, ctx) {
            let src = snapshot.text.as_bytes();
            bonsai_lang_api::kit::synthesize_record_members(&mut idx, &tree, src, file);
            // Expression-bodied properties (`X => expr;`) have no
            // accessor node, so synthesize their getter before resolving
            // bare property reads below.
            synthesize_csharp_expression_bodied_properties(&mut idx, &tree, src, file);
            // C# constructor bodies are `block` kind — excluded from
            // the kit's `body_has_implicit_return` set — so the kit
            // emits no synthetic Return for them. Java's equivalent
            // (`constructor_body` kind) IS treated as an expression-
            // body, so each Java ctor gets a `Return{value_text=body}`
            // event whose identifier tokenization bridges param taint
            // to the return → caller's CallRet → caller's `repo`
            // allocation. Mirror that by synthesizing a ctor Return
            // whose value_text includes the body text + constructor_
            // initializer text (`: base(data)`) so params propagate
            // through the inheritance chain even when the body is
            // empty — `new AuditedRepository(envelope)` then taints
            // `repo` whole-object (Java-style), letting the existing
            // 1-level receiver-field bridge carry it.
            synthesize_csharp_constructor_implicit_returns(&mut idx, &tree, src, file);
        }
        // Resolve bare implicit-`this` property reads/writes. C# accesses a
        // zero-arg property/getter by its bare name (`var c = Cmd;` for
        // `string Cmd => Data.Cmd;`) and writes instance properties as
        // `Data = data;` inside constructors. Rewrite those implicit
        // receiver accesses so the IDG can stitch property returns and
        // constructor field writes onto object instances.
        qualify_csharp_implicit_member_accesses(&mut idx, &class_member_names_by_symbol);
        for decl in &mut idx.defs {
            enrich_csharp_receiver_field_writes(decl);
        }
        propagate_csharp_base_constructor_field_writes(&mut idx);
        // Precompute `self.<field> → Type` bindings from each
        // class's constructor `receiver_field_writes` so receiver-
        // typed dispatch through stable instance state is an O(1)
        // lookup against the method's `type_aliases` instead of a
        // per-call walk over sibling decls.
        // Local constructor-result receiver typing (`var c = new Foo()`
        // → `c: Foo`) is driven by the object-creation CST node or an
        // exactly resolved declaration. Identifier casing is never type
        // evidence: legal C# type names need not follow style conventions.
        bonsai_lang_api::apply_constructor_result_type_aliases(&mut idx);
        bonsai_lang_api::apply_class_field_type_aliases(&mut idx);
        idx
    }
    fn extract_imports(&self, file: FileId, ctx: &AdapterContext<'_>) -> ImportIndex {
        extract_imports_via(PACK_NAME, file, ctx, parse_imports)
    }
}

/// Synthesize getter `Method` decls for C# expression-bodied properties
/// (`public string Cmd => Data.Cmd;`). The grammar emits these as a
/// `property_declaration` whose body is an `arrow_expression_clause` with
/// no `accessor_declaration` child — so the HANDLER's fn-kind extraction
/// (which keys on `accessor_declaration`) produces no decl at all and the
/// property's return expression is invisible to the IDG. Mirror the
/// record-accessor synthesis: one zero-arg `Method` named after the
/// property whose single `Return` forwards the (receiver-qualified) body
/// expression, so a getter call resolves the property's value and a
/// tainted receiver field flows out through the property.
fn synthesize_csharp_expression_bodied_properties(
    index: &mut DeclIndex,
    tree: &Tree,
    src: &[u8],
    file: FileId,
) {
    let mut next_symbol = index
        .defs
        .iter()
        .map(|d| d.symbol.raw())
        .max()
        .map_or(1, |m| m + 1);
    let mut synthesized: Vec<bonsai_lang_api::Decl> = Vec::new();
    for prop in collect_kinds(tree, &["property_declaration"]) {
        // Expression-bodied only: a direct `arrow_expression_clause`
        // child. Properties with an `accessor_list` (`{ get; set; }`)
        // surface their bodies through `accessor_declaration` decls.
        let mut pc = prop.walk();
        let Some(arrow) = prop
            .children(&mut pc)
            .find(|c| c.kind() == "arrow_expression_clause")
        else {
            continue;
        };
        let Some(name_node) = prop.child_by_field_name("name") else {
            continue;
        };
        let name = node_text(&name_node, src).trim().to_string();
        if name.is_empty() {
            continue;
        }
        // Body expression = the arrow clause's last named child (the
        // node after the `=>` token).
        let mut ac = arrow.walk();
        let named: Vec<_> = arrow.children(&mut ac).filter(|c| c.is_named()).collect();
        let Some(expr) = named.last().copied() else {
            continue;
        };
        let body = node_text(&expr, src).trim().to_string();
        if body.is_empty() {
            continue;
        }
        // Qualify a bare member read against the receiver so the field
        // base resolves to `this` (`Data.Cmd` → `this.Data.Cmd`), which
        // is what the receiver-state machinery keys on.
        let qualified = if body.starts_with("this.") || body.starts_with("base.") {
            body.clone()
        } else {
            format!("this.{body}")
        };
        let Some((parent, module_path, visibility)) = csharp_enclosing_type_decl(index, prop, file) else {
            continue;
        };
        // A property with an explicit getter/field of the same name
        // already covers this; don't double-declare.
        if index
            .defs
            .iter()
            .chain(synthesized.iter())
            .any(|d| d.parent == parent && d.name == name && d.params.is_empty())
        {
            continue;
        }
        let body_span = span_of(file, &expr);
        // If the body is a simple dotted member access (`Data.Cmd` —
        // optionally prefixed with `this.`/`base.`), model it as a
        // CALL chain rather than a single 2-level field read. The
        // IDG's interprocedural receiver-field bridge is 1-level, so
        // `Cmd => Data.Cmd` modeled as `Return this.Data.Cmd` (2-
        // level read) never connects to the caller's tainted
        // `repo.Data.Cmd`. Modeling as `Call Data.Cmd(); Return
        // call-result` mirrors the Java accessor pattern
        // (`String cmd() { return data.cmd(); }`) which the bridge
        // already handles — the call resolves to the receiver-typed
        // member (e.g. the record component's synthesized accessor),
        // and that 1-level hop forwards the tainted field.
        let flow_events =
            if let Some((call_receiver, call_name)) = dotted_member_access_call_parts(&qualified) {
                // Look up the receiver's static type from sibling
                // `property_declaration` / `field_declaration` siblings in
                // the same class so the resolver can disambiguate the
                // call's `name` against the receiver's class instead of
                // resolving back to the synthesizing property itself
                // (which would self-recurse).
                let lookup_member = csharp_receiver_member_lookup_name(&call_receiver);
                let receiver_types = csharp_lookup_member_type(prop, lookup_member, src)
                    .into_iter()
                    .collect();
                let mut return_flow = bonsai_lang_api::ExpressionFlow::from_place(qualified.clone());
                return_flow.call_sites.push(body_span);
                vec![
                    FlowEvent::Call {
                        span: body_span,
                        name: call_name.clone(),
                        receiver: Some(call_receiver),
                        receiver_types,
                        call_kind: CallKind::Method,
                        args: Vec::new(),
                    },
                    FlowEvent::Return {
                        span: body_span,
                        value_kind: Some(bonsai_lang_api::AssignValueKind::CallResult),
                        value_text: Some(call_name.clone()),
                        value_name: Some(call_name),
                        // Preserve both compiler facts: this is a resolved
                        // nested member call and an exact projected value.
                        // The call-site fact composes accessor summaries;
                        // the projection lets field-sensitive lowering
                        // consume only the selected member (`Data.Cmd`) and
                        // never a sibling (`Data.User`).
                        value_flow: return_flow,
                    },
                ]
            } else {
                vec![FlowEvent::Return {
                    span: body_span,
                    value_kind: Some(bonsai_lang_api::AssignValueKind::Compound),
                    value_text: Some(qualified.clone()),
                    value_name: Some(qualified.clone()),
                    value_flow: bonsai_lang_api::ExpressionFlow::from_place(qualified.clone()),
                }]
            };
        synthesized.push(bonsai_lang_api::Decl {
            symbol: bonsai_common::SymbolId::new(next_symbol),
            kind: DeclKind::Method,
            name,
            qualified_name: None,
            module_path,
            span: span_of(file, &name_node),
            name_span: span_of(file, &name_node),
            visibility,
            parent,
            body_span: Some(body_span),
            flow_events,
            has_implicit_returns: false,
            params: Vec::new(),
            param_annotations: Vec::new(),
            param_default_calls: Vec::new(),
            type_aliases: Vec::new(),
            bases: Vec::new(),
            receiver_param_index: None,
            receiver_field_writes: Vec::new(),
            receiver_field_initializers: Vec::new(),
            implicit_receiver_names: vec!["this".to_string(), "base".to_string()],
            receiver_state_sources: vec![qualified],
            return_type: None,
            is_variadic: false,
        });
        next_symbol += 1;
    }
    index.defs.extend(synthesized);
}

/// For each C# `constructor_declaration` whose extracted decl has
/// no `Return` event yet, synthesize one whose `value_text` includes
/// the constructor body + initializer text (`: base(data)`). The IDG
/// transfer's Return handler tokenizes that text via
/// `bridge_value_expr_to_node`, so each identifier (in particular the
/// `data` param forwarded to `base`) bridges to `Place::Return`. The
/// caller's `new R(envelope)` site then connects via the standard
/// callee-Return → caller-CallRet edge, tainting `repo` whole-object
/// — matching the Java adapter's constructor propagation
/// (`constructor_body` falls into the kit's implicit-
/// return path automatically; C#'s `block` doesn't).
fn synthesize_csharp_constructor_implicit_returns(
    index: &mut DeclIndex,
    tree: &Tree,
    src: &[u8],
    file: FileId,
) {
    let class_info_by_symbol: std::collections::HashMap<_, _> = index
        .defs
        .iter()
        .filter(|decl| is_class_like(decl.kind))
        .map(|decl| (decl.symbol, (decl.name.clone(), decl.bases.clone())))
        .collect();
    for ctor_node in collect_kinds(tree, &["constructor_declaration"]) {
        let ctor_span = span_of(file, &ctor_node);
        let Some(decl) = index
            .defs
            .iter_mut()
            .find(|d| matches!(d.kind, DeclKind::Constructor) && d.span == ctor_span)
        else {
            continue;
        };
        let parent_info = decl.parent.and_then(|parent| class_info_by_symbol.get(&parent));
        // Build value_text from the constructor_initializer + body
        // texts. Concatenating both surfaces param identifiers from
        // either side (`: base(data)` or `{ Data = data; }`) so
        // tokenization can bridge them.
        let mut parts: Vec<String> = Vec::new();
        let mut initializer_call: Option<FlowEvent> = None;
        let mut cw = ctor_node.walk();
        for child in ctor_node.children(&mut cw) {
            if child.kind() == "constructor_initializer" {
                let t = node_text(&child, src).trim().to_string();
                if let Some((callee, args)) =
                    csharp_constructor_initializer_call(child, file, src, parent_info)
                {
                    let span = span_of(file, &child);
                    initializer_call = Some(FlowEvent::Call {
                        span,
                        name: callee,
                        receiver: None,
                        receiver_types: Vec::new(),
                        call_kind: CallKind::Constructor,
                        args,
                    });
                }
                if !t.is_empty() {
                    parts.push(t);
                }
            } else if child.kind() == "block" {
                let t = node_text(&child, src).trim().to_string();
                if !t.is_empty() {
                    parts.push(t);
                }
            }
        }
        if let Some(call) = initializer_call {
            let already_present = decl.flow_events.iter().any(|event| {
                matches!(
                    (event, &call),
                    (
                        FlowEvent::Call { span: existing_span, name: existing_name, .. },
                        FlowEvent::Call { span, name, .. }
                    ) if existing_span == span && existing_name == name
                )
            });
            if !already_present {
                decl.flow_events.insert(0, call);
            }
        }
        if decl
            .flow_events
            .iter()
            .any(|e| matches!(e, FlowEvent::Return { .. }))
            || parts.is_empty()
        {
            continue;
        }
        let value_text = parts.join(" ");
        let body_span = ctor_node
            .child_by_field_name("body")
            .map(|b| span_of(file, &b))
            .unwrap_or_else(|| span_of(file, &ctor_node));
        decl.flow_events.push(FlowEvent::Return {
            span: body_span,
            value_kind: Some(bonsai_lang_api::AssignValueKind::Compound),
            value_text: Some(value_text),
            value_name: None,
            value_flow: bonsai_lang_api::ExpressionFlow::from_source_names(decl.params.clone()),
        });
    }
}

fn csharp_constructor_initializer_call(
    initializer: tree_sitter::Node<'_>,
    file: FileId,
    src: &[u8],
    parent_info: Option<&(String, Vec<String>)>,
) -> Option<(String, Vec<CallArg>)> {
    if initializer.kind() != "constructor_initializer" {
        return None;
    }
    let mut children = initializer.walk();
    let target = initializer
        .children(&mut children)
        .find_map(|child| match child.kind() {
            "base" => parent_info.and_then(|(_, bases)| bases.first()).cloned(),
            "this" => parent_info.map(|(name, _)| name.clone()),
            _ => None,
        })?;
    let argument_list = initializer
        .named_children(&mut initializer.walk())
        .find(|child| child.kind() == "argument_list")?;
    let mut args = Vec::new();
    let mut cursor = argument_list.walk();
    for argument in argument_list.named_children(&mut cursor) {
        if argument.kind() != "argument" {
            continue;
        }
        let name = argument
            .child_by_field_name("name")
            .map(|name| node_text(&name, src).trim().to_string())
            .filter(|name| !name.is_empty());
        if let Some(argument) = call_arg_from_node_with_handler(argument, file, src, name, &HANDLER) {
            args.push(argument);
        }
    }
    let callee = target;
    Some((callee, args))
}

fn csharp_bare_identifier(text: &str) -> Option<&str> {
    let trimmed = text.trim();
    let mut chars = trimmed.chars();
    let first = chars.next()?;
    if !(first == '_' || first.is_ascii_alphabetic()) {
        return None;
    }
    if chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric()) {
        Some(trimmed)
    } else {
        None
    }
}

fn csharp_receiver_member_lookup_name(receiver: &str) -> &str {
    receiver
        .trim()
        .strip_prefix("this.")
        .or_else(|| receiver.trim().strip_prefix("base."))
        .unwrap_or_else(|| receiver.trim())
        .rsplit('.')
        .next()
        .unwrap_or_else(|| receiver.trim())
}

/// Find a sibling `property_declaration` / `field_declaration` named
/// `member` in the type that lexically encloses `prop`, returning its
/// declared (canonical) type name. Used to set `receiver_types` on a
/// synthesized member-access Call so the resolver dispatches against
/// the receiver's class — without this, `Cmd => Data.Cmd` resolves
/// `Data.Cmd` back to the same `Cmd` property and self-recurses.
fn csharp_lookup_member_type(prop: tree_sitter::Node<'_>, member: &str, src: &[u8]) -> Option<String> {
    let mut cur = prop.parent();
    let mut class_node = None;
    while let Some(n) = cur {
        if matches!(
            n.kind(),
            "class_declaration" | "struct_declaration" | "record_declaration" | "interface_declaration"
        ) {
            class_node = Some(n);
            break;
        }
        cur = n.parent();
    }
    let class_node = class_node?;
    let body = class_node.child_by_field_name("body")?;
    let mut walker = body.walk();
    for child in body.children(&mut walker) {
        match child.kind() {
            "property_declaration" => {
                let name_node = child.child_by_field_name("name")?;
                if node_text(&name_node, src).trim() == member {
                    let type_node = child.child_by_field_name("type")?;
                    let raw = node_text(&type_node, src).trim();
                    if raw.is_empty() {
                        return None;
                    }
                    return Some(canonical_simple_type_name(raw).to_string());
                }
            }
            "field_declaration" => {
                // C# field_declaration: `Type Name [, Name2];` — the
                // type is the `type` field; the name(s) are inside
                // `variable_declaration` children.
                let Some(type_node) = child.child_by_field_name("type") else {
                    continue;
                };
                let mut cw = child.walk();
                for cc in child.children(&mut cw) {
                    if cc.kind() != "variable_declaration" {
                        continue;
                    }
                    let mut vw = cc.walk();
                    for v in cc.children(&mut vw) {
                        if v.kind() != "variable_declarator" {
                            continue;
                        }
                        if let Some(name_node) = v.child_by_field_name("name") {
                            if node_text(&name_node, src).trim() == member {
                                let raw = node_text(&type_node, src).trim();
                                if raw.is_empty() {
                                    return None;
                                }
                                return Some(canonical_simple_type_name(raw).to_string());
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }
    None
}

/// If `body` is a simple dotted member-access of identifiers
/// (`Data.Cmd`, optionally prefixed `this.`/`base.`), return
/// `(receiver, call_name)` modeling it as a method call — `this.Data.Cmd`
/// becomes `(receiver="this.Data", call_name="this.Data.Cmd")` so the
/// IDG's receiver-state bridge preserves exact field taint while still
/// resolving to the receiver-typed member (e.g. a record component's
/// synthesized accessor). Returns `None` for any non-trivial body (call,
/// indexer, literal, complex expression) so those keep the Return-only
/// fallback.
fn dotted_member_access_call_parts(body: &str) -> Option<(String, String)> {
    let trimmed = body.trim();
    // The text must be a pure dotted identifier path of at least two
    // segments (`A.B`/`this.A.B`/`A.B.C`/...).
    let inner = trimmed;
    let segments: Vec<&str> = inner.split('.').collect();
    if segments.len() < 2 {
        return None;
    }
    for seg in &segments {
        if seg.is_empty()
            || !seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
            || !seg
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        {
            return None;
        }
    }
    // Receiver = everything up to the last dot; call_name = full dotted
    // form mirroring Java's `data.cmd` pattern (`receiver="data",
    // name="data.cmd"`).
    let last_dot = inner.rfind('.')?;
    let receiver = inner[..last_dot].to_string();
    Some((receiver, inner.to_string()))
}

/// Resolve the type declaration (`class`/`struct`/`record`/`interface`)
/// that lexically encloses `node`, returning its symbol / module / visibility.
fn csharp_enclosing_type_decl(
    index: &DeclIndex,
    node: tree_sitter::Node<'_>,
    file: FileId,
) -> Option<(
    Option<bonsai_common::SymbolId>,
    bonsai_lang_api::ModulePath,
    Visibility,
)> {
    let mut cur = node.parent();
    while let Some(n) = cur {
        if matches!(
            n.kind(),
            "class_declaration" | "struct_declaration" | "record_declaration" | "interface_declaration"
        ) {
            let span = span_of(file, &n);
            return index
                .defs
                .iter()
                .find(|d| d.span == span)
                .map(|d| (Some(d.symbol), d.module_path.clone(), d.visibility));
        }
        cur = n.parent();
    }
    None
}

/// Rewrite bare reads of zero-arg member accessors (C# properties /
/// expression-bodied `=> expr` getters) into getter calls. C# reads a
/// property by its bare name (`var c = Cmd;` for `string Cmd =>
/// Data.Cmd;`), which the generic walker emits as `Assign { source_name:
/// "Cmd" }` — a plain identifier read that never connects to the
/// property's return, so taint stops at the property boundary. When the
/// bare RHS name matches a zero-arg member decl in this file and is NOT
/// a local/param of the method, convert it into a `source_call` so the
/// IDG resolves the getter and forwards its return into the assignment.
fn qualify_csharp_implicit_member_accesses(
    index: &mut DeclIndex,
    class_member_names_by_symbol: &std::collections::HashMap<
        bonsai_common::SymbolId,
        std::collections::HashSet<String>,
    >,
) {
    use std::collections::{HashMap, HashSet};
    // Member lookup is lexical: a getter in another class or a typed local
    // that happens to share a field's type is not an implicit `this` member.
    // Keep the declaration owner's symbol in the key instead of building a
    // file-wide name inventory.
    let mut getter_names_by_parent: HashMap<Option<bonsai_common::SymbolId>, HashSet<String>> =
        HashMap::new();
    let mut class_symbols_by_name: HashMap<String, Vec<bonsai_common::SymbolId>> = HashMap::new();
    let mut class_bases_by_symbol: HashMap<bonsai_common::SymbolId, Vec<String>> = HashMap::new();
    for decl in &index.defs {
        if matches!(decl.kind, DeclKind::Method) && decl.params.is_empty() && !decl.name.is_empty() {
            getter_names_by_parent
                .entry(decl.parent)
                .or_default()
                .insert(decl.name.clone());
        }
        if is_class_like(decl.kind) {
            class_symbols_by_name
                .entry(decl.name.clone())
                .or_default()
                .push(decl.symbol);
            class_bases_by_symbol.insert(decl.symbol, decl.bases.clone());
        }
    }
    for decl in &mut index.defs {
        if decl.flow_events.is_empty() {
            continue;
        }
        // A local binding (param or assignment target) shadows the
        // member, so those names must keep their plain-read semantics.
        let mut locals: HashSet<String> = decl.params.iter().cloned().collect();
        collect_assign_targets(&decl.flow_events, &mut locals);
        let mut getter_names = HashSet::new();
        let mut member_names = HashSet::new();
        let mut owner_stack: Vec<bonsai_common::SymbolId> = decl.parent.into_iter().collect();
        let mut seen_owners = HashSet::new();
        while let Some(owner) = owner_stack.pop() {
            if !seen_owners.insert(owner) {
                continue;
            }
            if let Some(names) = getter_names_by_parent.get(&Some(owner)) {
                getter_names.extend(names.iter().cloned());
            }
            if let Some(names) = class_member_names_by_symbol.get(&owner) {
                member_names.extend(names.iter().cloned());
            }
            for base in class_bases_by_symbol.get(&owner).into_iter().flatten() {
                if let Some(symbols) = class_symbols_by_name.get(base) {
                    owner_stack.extend(symbols.iter().copied());
                }
            }
        }
        // File-level functions have no class owner. Preserve ordinary
        // top-level getter semantics without mixing them into class methods.
        if decl.parent.is_none() {
            if let Some(names) = getter_names_by_parent.get(&None) {
                getter_names.extend(names.iter().cloned());
            }
        }
        member_names.extend(getter_names.iter().cloned());
        let params: HashSet<String> = decl.params.iter().cloned().collect();
        bonsai_lang_api::qualify_implicit_member_assign_targets(
            &mut decl.flow_events,
            &member_names,
            &params,
            |name| csharp_bare_identifier(name).map(|_| format!("this.{name}")),
        );
        bonsai_lang_api::rewrite_implicit_member_reads(
            &mut decl.flow_events,
            &getter_names,
            &locals,
            |name| bonsai_lang_api::ImplicitMemberReadCall {
                source_call: format!("this.{name}"),
                call_name: format!("this.{name}"),
                receiver: Some("this".to_string()),
                call_kind: CallKind::Method,
            },
        );
    }
}

fn enrich_csharp_receiver_field_writes(decl: &mut bonsai_lang_api::Decl) {
    if !matches!(decl.kind, DeclKind::Constructor | DeclKind::Method) {
        return;
    }
    let writes = collect_receiver_field_writes(
        &decl.flow_events,
        &decl.params,
        decl.receiver_param_index,
        &["this", "base"],
        &[],
    );
    decl.receiver_field_writes.extend(writes);
    dedup_csharp_receiver_field_writes(&mut decl.receiver_field_writes);
}

fn propagate_csharp_base_constructor_field_writes(index: &mut DeclIndex) {
    for _ in 0..8 {
        let snapshot = index.defs.clone();
        let mut changed = false;
        for decl in index
            .defs
            .iter_mut()
            .filter(|decl| matches!(decl.kind, DeclKind::Constructor))
        {
            let mut inherited = csharp_inherited_constructor_field_writes(decl, &snapshot);
            if inherited.is_empty() {
                continue;
            }
            let before = decl.receiver_field_writes.len();
            decl.receiver_field_writes.append(&mut inherited);
            dedup_csharp_receiver_field_writes(&mut decl.receiver_field_writes);
            changed |= decl.receiver_field_writes.len() != before;
        }
        if !changed {
            break;
        }
    }
}

fn csharp_inherited_constructor_field_writes(
    decl: &bonsai_lang_api::Decl,
    snapshot: &[bonsai_lang_api::Decl],
) -> Vec<FieldWrite> {
    let mut out = Vec::new();
    collect_csharp_inherited_constructor_field_writes(&decl.flow_events, decl, snapshot, &mut out);
    dedup_csharp_receiver_field_writes(&mut out);
    out
}

fn collect_csharp_inherited_constructor_field_writes(
    events: &[FlowEvent],
    decl: &bonsai_lang_api::Decl,
    snapshot: &[bonsai_lang_api::Decl],
    out: &mut Vec<FieldWrite>,
) {
    for event in events {
        match event {
            FlowEvent::Call {
                name,
                call_kind,
                args,
                ..
            } if *call_kind == CallKind::Constructor => {
                let Some(callee) = snapshot.iter().find(|candidate| {
                    matches!(candidate.kind, DeclKind::Constructor) && candidate.name == *name
                }) else {
                    continue;
                };
                for write in &callee.receiver_field_writes {
                    let mut mapped_sources = Vec::new();
                    for source_param in &write.source_param_indices {
                        let Some(arg) = args.get(*source_param) else {
                            continue;
                        };
                        if let Some(current_param) = csharp_param_index_for_bare_arg(decl, &arg.value_text) {
                            if !mapped_sources.contains(&current_param) {
                                mapped_sources.push(current_param);
                            }
                        }
                    }
                    if !mapped_sources.is_empty() {
                        out.push(FieldWrite {
                            span: write.span,
                            target: write.target.clone(),
                            source_param_indices: mapped_sources,
                        });
                    }
                }
            }
            FlowEvent::Branch {
                then_events,
                else_events,
                ..
            } => {
                collect_csharp_inherited_constructor_field_writes(then_events, decl, snapshot, out);
                collect_csharp_inherited_constructor_field_writes(else_events, decl, snapshot, out);
            }
            FlowEvent::Loop { body, .. } | FlowEvent::Defer { body, .. } | FlowEvent::Using { body, .. } => {
                collect_csharp_inherited_constructor_field_writes(body, decl, snapshot, out);
            }
            FlowEvent::Try {
                body,
                catch_events,
                finally_events,
                ..
            } => {
                collect_csharp_inherited_constructor_field_writes(body, decl, snapshot, out);
                collect_csharp_inherited_constructor_field_writes(catch_events, decl, snapshot, out);
                collect_csharp_inherited_constructor_field_writes(finally_events, decl, snapshot, out);
            }
            _ => {}
        }
    }
}

fn csharp_param_index_for_bare_arg(decl: &bonsai_lang_api::Decl, arg: &str) -> Option<usize> {
    let bare = csharp_bare_identifier(arg)?;
    decl.params.iter().position(|param| param == bare)
}

fn dedup_csharp_receiver_field_writes(writes: &mut Vec<FieldWrite>) {
    for write in writes.iter_mut() {
        write.source_param_indices.sort_unstable();
        write.source_param_indices.dedup();
    }
    writes.sort_by_key(|write| {
        (
            write.span.start,
            write.target.clone(),
            write.source_param_indices.clone(),
        )
    });
    writes.dedup_by(|a, b| {
        a.span == b.span && a.target == b.target && a.source_param_indices == b.source_param_indices
    });
}

/// Lift every `using_directive` into an `ImportSpec`. C# splits the
/// alias out of the path: `using IO = System.IO` exposes `IO` as
/// `name:` and `System.IO` as the trailing qualified path child.
fn parse_imports(tree: &Tree, src: &[u8], file: FileId) -> Vec<ImportSpec> {
    let mut imports = Vec::new();
    // `using_directive` shapes:
    //   `using System.Data;`              → qualified_name only
    //   `using static System.Math;`       → qualified_name (with `static` keyword)
    //   `using IO = System.IO;`           → name: identifier (alias) + qualified_name
    for using_node in collect_kinds(tree, &["using_directive"]) {
        let mut child_cursor = using_node.walk();
        // The path is the *last* qualified_name / identifier child that
        // isn't the alias `name:` field — this is the only shape that
        // works across all three forms above.
        let mut last_path: Option<tree_sitter::Node<'_>> = None;
        for child in using_node.named_children(&mut child_cursor) {
            if matches!(child.kind(), "qualified_name" | "identifier")
                && Some(child) != using_node.child_by_field_name("name")
            {
                last_path = Some(child);
            }
        }
        let Some(path_node) = last_path.or_else(|| using_node.child_by_field_name("name")) else {
            continue;
        };
        let module = node_text(&path_node, src).trim().to_string();
        if module.is_empty() {
            continue;
        }
        let alias = using_node
            .child_by_field_name("name")
            .map(|alias_node| node_text(&alias_node, src).to_string());
        imports.push(ImportSpec {
            span: span_of(file, &using_node),
            module: module.clone(),
            alias,
            is_wildcard: false,
            original_name: None,
            scope: ImportScope::Module,
        });
        if csharp_using_is_static(&using_node) {
            imports.push(ImportSpec {
                span: span_of(file, &using_node),
                module,
                alias: None,
                is_wildcard: true,
                original_name: None,
                scope: ImportScope::Local,
            });
        }
    }
    imports
}

fn csharp_using_is_static(using_node: &tree_sitter::Node<'_>) -> bool {
    // `static` is an anonymous grammar token on `using_directive`. Inspect
    // that CST child directly; re-tokenizing the whole statement would make
    // comments and whitespace part of semantic classification.
    (0..using_node.child_count())
        .filter_map(|index| u32::try_from(index).ok())
        .any(|index| {
            using_node
                .child(index)
                .is_some_and(|child| child.kind() == "static")
        })
}

/// Walk every C# class-like declaration and pull `(name, type)`
/// bindings from its `field_declaration` and `property_declaration`
/// children. Returns `(class_span, [TypeAliasBinding])` so the
/// per-method merge can attach a class's bindings to every method
/// nested inside it, matching the resolver's caller-decl
/// `type_aliases` lookup contract.
/// Collect locally-declared receiver types per method
/// (`SqlCommand c = (SqlCommand) o;`, `using var conn = Open();`),
/// keyed by the owning method/constructor span. The cast type the goal
/// (WS2) calls out surfaces on the LOCAL DECLARATION, not the
/// taint-engine flow event (which strips it), so capturing the declared
/// type here lets `receiver_type_in` / `[Type, method]` resolve a cast
/// or factory-typed receiver. Reuses the field extractor since a C#
/// `local_declaration_statement` wraps the same `variable_declaration`
/// (`type` + `variable_declarator`) shape as a `field_declaration`.
fn collect_csharp_local_type_aliases(
    tree: &Tree,
    file: FileId,
    src: &[u8],
) -> std::collections::HashMap<bonsai_common::Span, Vec<TypeAliasBinding>> {
    let fn_kinds = &[
        "method_declaration",
        "constructor_declaration",
        "local_function_statement",
    ];
    let mut out = std::collections::HashMap::new();
    for fn_node in collect_kinds(tree, fn_kinds) {
        let mut aliases: Vec<TypeAliasBinding> = Vec::new();
        let mut work = vec![fn_node];
        while let Some(node) = work.pop() {
            // A nested local function owns its own locals; let its own
            // iteration scope them rather than leaking into the parent.
            if node != fn_node && fn_kinds.contains(&node.kind()) {
                continue;
            }
            if node.kind() == "local_declaration_statement" {
                extend_aliases_from_field_or_event(node, src, &mut aliases);
                // WS2: `var c = (Foo) x` / `var c = x as Foo` — an inferred
                // (`var`) LHS leaves the type only on the cast, which the
                // declared-type extractor (it sees `var`) drops. Capture the
                // cast/as type so `c.Method(...)` resolves receiver_type_in.
                extend_aliases_from_var_cast(node, src, &mut aliases);
            }
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                work.push(child);
            }
        }
        if !aliases.is_empty() {
            out.insert(span_of(file, &fn_node), aliases);
        }
    }
    out
}

/// WS2 cast-expression typing for inferred (`var`) locals. The declared
/// type `var` carries no class, so the only type signal is the cast on the
/// initializer (`var c = (Foo) x` / `var c = x as Foo`). Reads ONLY the
/// direct initializer (not nested casts in arguments, which would mistype
/// the local), and only when the declared type is `var` — so it never
/// clobbers a real declared type already captured by the field extractor.
fn extend_aliases_from_var_cast(
    node: tree_sitter::Node<'_>,
    src: &[u8],
    aliases: &mut Vec<TypeAliasBinding>,
) {
    let mut var_decl = node.child_by_field_name("declaration");
    if var_decl.is_none() {
        let mut cursor = node.walk();
        for child in node.named_children(&mut cursor) {
            if child.kind() == "variable_declaration" {
                var_decl = Some(child);
                break;
            }
        }
    }
    let Some(var_decl) = var_decl else {
        return;
    };
    let Some(type_node) = var_decl.child_by_field_name("type") else {
        return;
    };
    if node_text(&type_node, src).trim() != "var" {
        return;
    }
    let mut cursor = var_decl.walk();
    for declarator in var_decl.named_children(&mut cursor) {
        if declarator.kind() != "variable_declarator" {
            continue;
        }
        let mut name_node = declarator.child_by_field_name("name");
        if name_node.is_none() {
            let mut inner = declarator.walk();
            for child in declarator.named_children(&mut inner) {
                if child.kind() == "identifier" {
                    name_node = Some(child);
                    break;
                }
            }
        }
        let Some(name_node) = name_node else {
            continue;
        };
        let name = node_text(&name_node, src).trim().to_string();
        if name.is_empty() {
            continue;
        }
        // The initializer is the declarator's `value` field (the
        // top-level RHS expression). Use the field directly so a cast
        // nested inside a call argument (`var c = Wrap((Foo) x)`) does NOT
        // mistype the local — only a cast that IS the initializer counts.
        let mut init = declarator.child_by_field_name("value");
        if init.is_none() {
            // Fallback for grammars that don't field-tag the value: take
            // the last named child that is not the binding name.
            let mut inner = declarator.walk();
            for child in declarator.named_children(&mut inner) {
                if child.id() != name_node.id() {
                    init = Some(child);
                }
            }
        }
        let Some(init) = init else {
            continue;
        };
        let Some(type_name) = csharp_cast_type_of_init(init, src) else {
            continue;
        };
        let canonical = canonical_simple_type_name(&type_name);
        if canonical.is_empty() {
            continue;
        }
        // Replace any non-useful `var`-typed binding the field extractor
        // added for this same local; the cast type is the real one.
        aliases.retain(|a| a.name != name);
        aliases.push(TypeAliasBinding {
            name,
            type_name: canonical,
        });
    }
}

/// The cast/as type of a direct initializer expression (`(Foo) x` →
/// `Foo`, `x as Foo` → `Foo`), unwrapping redundant parentheses. Returns
/// `None` for any other initializer shape so only genuine casts type the
/// local.
fn csharp_cast_type_of_init(init: tree_sitter::Node<'_>, src: &[u8]) -> Option<String> {
    let mut n = init;
    while n.kind() == "parenthesized_expression" {
        let mut cursor = n.walk();
        n = n.named_children(&mut cursor).next()?;
    }
    match n.kind() {
        "cast_expression" => n
            .child_by_field_name("type")
            .map(|t| node_text(&t, src).to_string()),
        "as_expression" => n
            .child_by_field_name("type")
            .or_else(|| n.child_by_field_name("right"))
            .map(|t| node_text(&t, src).to_string()),
        _ => None,
    }
}

fn collect_csharp_class_field_aliases(
    tree: &Tree,
    file: FileId,
    src: &[u8],
) -> Vec<(bonsai_common::Span, Vec<TypeAliasBinding>)> {
    let class_kinds = &[
        "class_declaration",
        "struct_declaration",
        "record_declaration",
        "record_struct_declaration",
        "interface_declaration",
    ];
    let mut out = Vec::new();
    for class_node in collect_kinds(tree, class_kinds) {
        let mut aliases: Vec<TypeAliasBinding> = Vec::new();
        let mut work = vec![class_node];
        while let Some(node) = work.pop() {
            // Don't descend into nested classes — their own iteration
            // produces the right scope for their methods. A nested
            // class's fields are visible only to its own methods, not
            // the outer class's methods.
            if node != class_node && class_kinds.contains(&node.kind()) {
                continue;
            }
            match node.kind() {
                "field_declaration" | "event_field_declaration" => {
                    extend_aliases_from_field_or_event(node, src, &mut aliases);
                }
                "property_declaration" => {
                    if let Some(binding) = property_alias_from_node(node, src) {
                        if !aliases.contains(&binding) {
                            aliases.push(binding);
                        }
                    }
                }
                _ => {}
            }
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                work.push(child);
            }
        }
        if !aliases.is_empty() {
            out.push((span_of(file, &class_node), aliases));
        }
    }
    out
}

fn extend_aliases_from_field_or_event(
    node: tree_sitter::Node<'_>,
    src: &[u8],
    aliases: &mut Vec<TypeAliasBinding>,
) {
    // C# `field_declaration` wraps a `variable_declaration` whose
    // `type` field carries the field type and whose
    // `variable_declarator` children name each binding. Multi-name
    // forms (`Foo a, b, c;`) are valid for value-type fields.
    let var_decl = node.child_by_field_name("declaration").or_else(|| {
        let mut cursor = node.walk();
        let mut found = None;
        for child in node.named_children(&mut cursor) {
            if child.kind() == "variable_declaration" {
                found = Some(child);
                break;
            }
        }
        found
    });
    let Some(var_decl) = var_decl else {
        return;
    };
    let Some(type_node) = var_decl.child_by_field_name("type") else {
        return;
    };
    // `var` is an inference marker, not a declared receiver type. Cast
    // initializers are handled by `extend_aliases_from_var_cast`; all real
    // type nodes, including lowercase user-defined identifiers and language
    // primitives, remain exact compiler facts.
    if type_node.kind() == "implicit_type" || node_text(&type_node, src).trim() == "var" {
        return;
    }
    let canonical = canonical_simple_type_name(node_text(&type_node, src));
    if canonical.is_empty() {
        return;
    }
    let mut cursor = var_decl.walk();
    for declarator in var_decl.named_children(&mut cursor) {
        if declarator.kind() != "variable_declarator" {
            continue;
        }
        let name_node = declarator.child_by_field_name("name").or_else(|| {
            let mut inner = declarator.walk();
            let mut found = None;
            for child in declarator.named_children(&mut inner) {
                if child.kind() == "identifier" {
                    found = Some(child);
                    break;
                }
            }
            found
        });
        let Some(name_node) = name_node else {
            continue;
        };
        let name = node_text(&name_node, src).trim().to_string();
        if name.is_empty() || name == canonical {
            continue;
        }
        let binding = TypeAliasBinding {
            name,
            type_name: canonical.clone(),
        };
        if !aliases.contains(&binding) {
            aliases.push(binding);
        }
    }
}

fn property_alias_from_node(node: tree_sitter::Node<'_>, src: &[u8]) -> Option<TypeAliasBinding> {
    let type_node = node.child_by_field_name("type")?;
    let canonical = canonical_simple_type_name(node_text(&type_node, src));
    if canonical.is_empty() {
        return None;
    }
    let name_node = node.child_by_field_name("name")?;
    let name = node_text(&name_node, src).trim().to_string();
    if name.is_empty() || name == canonical {
        return None;
    }
    Some(TypeAliasBinding {
        name,
        type_name: canonical,
    })
}

/// C#-aware visibility collector.
///
/// Differs from the generic `collect_modifier_visibility` helper in
/// that it recognises the compound forms `protected internal` (broader
/// than either alone — caller is in the same assembly OR is a derived
/// class anywhere) and `private protected` (narrower — derived classes
/// in the same assembly only). Maps to the four-level lattice in
/// `Visibility` as follows:
///
/// - `private`            → `Private`
/// - `private protected`  → `Protected` (assembly-bounded but derived-callable)
/// - `protected`          → `Protected`
/// - `protected internal` → `Crate` (visible to whole assembly)
/// - `internal`           → `Crate`
/// - `public`             → `Public`
///
/// Visibility comes from real syntax markers; per-language
/// compound-modifier handling lives in the adapter.
fn collect_csharp_visibility(
    root: tree_sitter::Node<'_>,
    file: FileId,
    src: &[u8],
) -> std::collections::HashMap<Span, Visibility> {
    let mut visibility_by_span = std::collections::HashMap::new();
    // Iterative DFS over the whole tree. Every CSHARP_DECL_KINDS node
    // contributes one entry; nested classes / nested local functions
    // each get their own.
    let mut work_stack = vec![root];
    while let Some(node) = work_stack.pop() {
        if CSHARP_DECL_KINDS.contains(&node.kind()) {
            visibility_by_span.insert(span_of(file, &node), csharp_node_visibility(node, src));
        }
        let mut child_cursor = node.walk();
        for child in node.children(&mut child_cursor) {
            work_stack.push(child);
        }
    }
    visibility_by_span
}

/// Resolve a single decl's visibility from its `modifier` children.
/// Compound forms (`protected internal`, `private protected`) are
/// distinct visibility levels in C# that don't map 1:1 to either side.
fn csharp_node_visibility(node: tree_sitter::Node<'_>, src: &[u8]) -> Visibility {
    let mut keywords: Vec<&str> = Vec::new();
    let mut child_cursor = node.walk();
    for child in node.children(&mut child_cursor) {
        if child.kind() == "modifier" {
            let text = node_text(&child, src);
            if matches!(text, "private" | "protected" | "internal" | "public") {
                keywords.push(text);
            }
        }
    }
    let has_private = keywords.contains(&"private");
    let has_protected = keywords.contains(&"protected");
    let has_internal = keywords.contains(&"internal");
    let has_public = keywords.contains(&"public");
    // `public` always wins — C# doesn't allow it to combine with the
    // other access modifiers.
    if has_public {
        return Visibility::Public;
    }
    if has_protected && has_internal {
        // `protected internal` — accessible in the whole assembly +
        // derived classes outside. Closest in the four-level lattice
        // is `Crate` (assembly-wide).
        return Visibility::Crate;
    }
    if has_private && has_protected {
        // `private protected` — derived classes in the same assembly
        // only. Closer to `Protected` than `Private` for resolver
        // narrowing purposes; assembly-bounded narrowing is the
        // module_path filter applied separately.
        return Visibility::Protected;
    }
    if has_protected {
        return Visibility::Protected;
    }
    if has_internal {
        return Visibility::Crate;
    }
    if has_private {
        return Visibility::Private;
    }
    CSHARP_DEFAULT_VISIBILITY
}

/// True for decl kinds that can carry a `bases` list (class super /
/// interface impl). Shared with the post-processing loop that copies
/// `bases_by_span` onto matching decls.
fn is_class_like(kind: DeclKind) -> bool {
    matches!(
        kind,
        DeclKind::Class | DeclKind::Interface | DeclKind::Trait | DeclKind::Struct | DeclKind::Enum
    )
}

/// Walk C# class / struct / record / interface declarations and
/// pull bare base type names from `base_list`. Grammar shape:
///
///   `class Echo : Base, IFoo, IBar { ... }` →
///     (class_declaration name: (identifier)
///        (base_list (identifier) (identifier) (identifier))
///        body: ...)
///
/// The `base_list` lists both the parent class and any implemented
/// interfaces in source order; C# does not distinguish them
/// syntactically. Generic / qualified bases collapse to the bare tail.
fn collect_csharp_class_bases(
    tree: &Tree,
    file: FileId,
    src: &[u8],
) -> Vec<(bonsai_common::Span, Vec<String>)> {
    let mut bases_table = Vec::new();
    let class_kinds = &[
        "class_declaration",
        "struct_declaration",
        "record_declaration",
        "record_struct_declaration",
        "interface_declaration",
    ];
    for class_node in collect_kinds(tree, class_kinds) {
        let mut bases: Vec<String> = Vec::new();
        let mut class_cursor = class_node.walk();
        for child in class_node.named_children(&mut class_cursor) {
            if child.kind() != "base_list" {
                continue;
            }
            let mut entry_cursor = child.walk();
            for entry in child.named_children(&mut entry_cursor) {
                let raw = node_text(&entry, src);
                if let Some(name) = canonical_csharp_base_name(raw) {
                    if !bases.iter().any(|existing| existing == &name) {
                        bases.push(name);
                    }
                }
            }
        }
        if !bases.is_empty() {
            bases_table.push((span_of(file, &class_node), bases));
        }
    }
    bases_table
}

/// Strip a base entry down to the bare type name. Drops generic
/// parameters (`Foo<T>` -> `Foo`) and namespace qualification
/// (`System.IO.Stream` -> `Stream`); the resolver keys on bare names.
fn canonical_csharp_base_name(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    let head = trimmed.split('<').next().unwrap_or(trimmed).trim();
    let bare = head.rsplit('.').next().unwrap_or(head).trim();
    if bare.is_empty() {
        return None;
    }
    Some(bare.to_string())
}

/// Walk `decl.flow_events` recursively and populate
/// `Throw::thrown_type` / `Try::catch_types` from the C# parse tree.
/// C# syntax:
///   throw new IOException("...")  → thrown_type: "IOException"
///   throw err                     → thrown_type: None (need data-flow)
///   `try { } catch (IOException e) { } catch (FormatException e) { }`
///                                 → `catch_types = vec!["IOException", "FormatException"]`
///   `try { } catch { }`           → `catch_types = vec![]` (catch-all)
fn populate_csharp_exception_types(
    events: &mut [bonsai_lang_api::FlowEvent],
    tree: &tree_sitter::Tree,
    src: &[u8],
) {
    use bonsai_lang_api::FlowEvent;
    for event in events {
        match event {
            FlowEvent::Throw {
                span, thrown_type, ..
            } => {
                if thrown_type.is_some() {
                    continue;
                }
                if let Some(node) = bonsai_lang_api::kit::node_at_span(
                    tree.root_node(),
                    *span,
                    &["throw_statement", "throw_expression"],
                ) {
                    if let Some(name) = csharp_thrown_type_for_node(node, src) {
                        *thrown_type = Some(name);
                    }
                }
            }
            FlowEvent::Try {
                span,
                body,
                catch_events,
                finally_events,
                catch_types,
                catch_param,
                ..
            } => {
                if let Some(node) =
                    bonsai_lang_api::kit::node_at_span(tree.root_node(), *span, &["try_statement"])
                {
                    if catch_types.is_empty() {
                        *catch_types = collect_csharp_catch_types(node, src);
                    }
                    // The kit's generic catch_param extractor picks the
                    // type identifier (or qualified type) on C#'s
                    // `catch (T name)` shape. Fix in the adapter where
                    // we have the structural context.
                    if let Some(name) = collect_csharp_catch_param_name(node, src) {
                        *catch_param = Some(name);
                    }
                }
                populate_csharp_exception_types(body, tree, src);
                populate_csharp_exception_types(catch_events, tree, src);
                populate_csharp_exception_types(finally_events, tree, src);
            }
            FlowEvent::Branch {
                then_events,
                else_events,
                ..
            } => {
                populate_csharp_exception_types(then_events, tree, src);
                populate_csharp_exception_types(else_events, tree, src);
            }
            FlowEvent::Loop { body, .. } | FlowEvent::Defer { body, .. } | FlowEvent::Using { body, .. } => {
                populate_csharp_exception_types(body, tree, src);
            }
            _ => {}
        }
    }
}

/// Pull the constructor type out of `throw new Foo(...)`. Returns
/// `None` for re-throws (`throw e`), where the thrown type is whatever
/// data-flow eventually proves about `e` — beyond syntactic reach.
fn csharp_thrown_type_for_node(throw_node: tree_sitter::Node<'_>, src: &[u8]) -> Option<String> {
    // throw_statement > object_creation_expression > identifier (or qualified_name)
    let mut throw_cursor = throw_node.walk();
    for child in throw_node.named_children(&mut throw_cursor) {
        if child.kind() == "object_creation_expression" {
            // Newer grammar releases expose the type via the `type:` field.
            if let Some(type_node) = child.child_by_field_name("type") {
                return Some(bonsai_lang_api::kit::canonical_simple_type_name(node_text(
                    &type_node, src,
                )));
            }
            // Older releases inline the identifier as a named child.
            let mut type_cursor = child.walk();
            for descendant in child.named_children(&mut type_cursor) {
                if matches!(
                    descendant.kind(),
                    "identifier" | "qualified_name" | "generic_name"
                ) {
                    return Some(bonsai_lang_api::kit::canonical_simple_type_name(node_text(
                        &descendant,
                        src,
                    )));
                }
            }
        }
    }
    None
}

/// Pull the binding name out of `catch (T name)`. Returns `None` for
/// catch-all (`catch { }`) and for catch declarations that omit the
/// name (`catch (T) { }` — unusual but legal in C#).
fn collect_csharp_catch_param_name(try_node: tree_sitter::Node<'_>, src: &[u8]) -> Option<String> {
    let mut try_cursor = try_node.walk();
    for child in try_node.named_children(&mut try_cursor) {
        if child.kind() != "catch_clause" {
            continue;
        }
        let mut clause_cursor = child.walk();
        for sub in child.named_children(&mut clause_cursor) {
            if sub.kind() != "catch_declaration" {
                continue;
            }
            // The `name` field is the binding identifier; the `type`
            // field is the exception type.
            if let Some(name_node) = sub.child_by_field_name("name") {
                return Some(node_text(&name_node, src).trim().to_string());
            }
            // Fallback: rightmost named identifier after the type.
            let mut pcur = sub.walk();
            let mut last_ident: Option<tree_sitter::Node<'_>> = None;
            for n in sub.named_children(&mut pcur) {
                if n.kind() == "identifier" {
                    last_ident = Some(n);
                }
            }
            if let Some(n) = last_ident {
                return Some(node_text(&n, src).trim().to_string());
            }
        }
    }
    None
}

/// Collect the `catch (T e)` types in source order. Catch-all (`catch
/// { }`) is omitted — the engine's seed-on-any-throw path handles it.
fn collect_csharp_catch_types(try_node: tree_sitter::Node<'_>, src: &[u8]) -> Vec<String> {
    let mut catch_types: Vec<String> = Vec::new();
    let mut try_cursor = try_node.walk();
    for child in try_node.named_children(&mut try_cursor) {
        if child.kind() != "catch_clause" {
            continue;
        }
        // catch_clause > catch_declaration > type
        let mut clause_cursor = child.walk();
        for sub in child.named_children(&mut clause_cursor) {
            if sub.kind() != "catch_declaration" {
                continue;
            }
            if let Some(type_node) = sub.child_by_field_name("type") {
                let name = bonsai_lang_api::kit::canonical_simple_type_name(node_text(&type_node, src));
                if !name.is_empty() && !catch_types.iter().any(|existing| existing == &name) {
                    catch_types.push(name);
                }
            }
        }
    }
    catch_types
}

/// Find the file's top-level `namespace` declaration and return its
/// dotted segments. Both block-form (`namespace Foo.Bar { ... }`) and
/// file-scoped (`namespace Foo.Bar;`) shapes resolve identically.
fn extract_csharp_namespace(root: tree_sitter::Node<'_>, src: &[u8]) -> Option<Vec<String>> {
    let mut child_cursor = root.walk();
    for child in root.children(&mut child_cursor) {
        if !matches!(
            child.kind(),
            "namespace_declaration" | "file_scoped_namespace_declaration"
        ) {
            continue;
        }
        if let Some(name_node) = child.child_by_field_name("name") {
            let text = node_text(&name_node, src);
            let segments: Vec<String> = text
                .split('.')
                .map(str::trim)
                .filter(|segment| !segment.is_empty())
                .map(str::to_string)
                .collect();
            if !segments.is_empty() {
                return Some(segments);
            }
        }
    }
    None
}

#[cfg(test)]
#[path = "tests.rs"]
mod tests;