code2graph 0.0.0-beta.6

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
// SPDX-License-Identifier: Apache-2.0

//! C# extractor — one tree-sitter pass yielding definitions and references.
//!
//! Definitions: all type declarations (`class`, `struct`, `interface`, `enum`,
//! `record`) and their members (methods, constructors, properties, fields, enum
//! members), each tagged with a real [`Visibility`]. Interface members are treated
//! as implicitly public. Qualified identity follows the `namespace_declaration` or
//! `file_scoped_namespace_declaration` if present; otherwise falls back to a
//! path-derived namespace.
//!
//! References: callee identifiers from `invocation_expression` (free calls and
//! member calls), `object_creation_expression` (constructor calls), inheritance
//! via `base_list`, and `using_directive` imports.
//!
//! 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;

use super::{
    ExtractCtx, Extractor, MIN_REF_LEN, attach_reference_scopes, collect_call_references,
    definition_bindings, field_text, import_bindings, innermost_scope, make_symbol, node_span,
    node_text, one_line_signature, push_binding, push_import_ref, push_ref, push_scope,
    push_type_ref, simple_type_name,
};

/// Tree-sitter query capturing call-callee identifiers.
///
/// Pattern 1: free call `Foo()` — identifier/generic_name directly under invocation_expression's `function` field.
/// Pattern 2: member call `obj.Foo()` — member_access_expression under `function` field; captures
///            receiver as `@qualifier` and final name as `@callee`.
/// Pattern 3: constructor call `new Foo(...)` — type identifier under object_creation_expression.
const CALL_QUERY: &str = r#"
[
  (invocation_expression function: (identifier) @callee)
  (invocation_expression function: (generic_name (identifier) @callee))
  (invocation_expression function: (member_access_expression expression: (_) @qualifier name: (identifier) @callee))
  (invocation_expression function: (member_access_expression expression: (_) @qualifier name: (generic_name (identifier) @callee)))
  (object_creation_expression type: (identifier) @callee)
  (object_creation_expression type: (qualified_name name: (identifier) @callee))
  (object_creation_expression type: (generic_name (identifier) @callee))
]
"#;

/// Extracts C# symbols and references.
pub struct CSharpExtractor;

impl Extractor for CSharpExtractor {
    fn lang(&self) -> Language {
        Language::CSharp
    }

    fn extract(&self, source: &str, file: &str) -> Result<FileFacts> {
        let ts_language = crate::grammar::csharp();
        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 = csharp_namespaces(&root, bytes, file);

        let defs = collect_symbols(&root, bytes, file, &namespaces);
        let def_bindings = definition_bindings(&defs);
        let mut symbols = defs;
        let mod_sym = super::module_symbol(Language::CSharp, &namespaces, file, source.len());
        let module_id = mod_sym.id.to_scip_string();
        symbols.push(mod_sym);

        let mut references = collect_call_references(
            &root,
            &ts_language,
            CALL_QUERY,
            Language::CSharp,
            bytes,
            file,
        )?;
        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);

        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::CSharp.as_str().to_owned(),
            symbols,
            references,
            scopes,
            bindings,
            ffi_exports: Vec::new(),
        })
    }
}

// ── Namespace derivation ─────────────────────────────────────────────────────

/// Derive namespace descriptors from the `namespace_declaration` or
/// `file_scoped_namespace_declaration`, falling back to path-derived segments.
///
/// With a namespace: `namespace A.B.C { … }` → `["A", "B", "C"]`.
/// File-scoped: `namespace A.B.C;` → same.
/// Without: `src/A/B/MyClass.cs` → `["A", "B", "MyClass"]`.
fn csharp_namespaces(root: &Node, bytes: &[u8], file: &str) -> Vec<String> {
    // Search among compilation_unit's direct children.
    for child in root.children(&mut root.walk()) {
        let kind = child.kind();
        if kind != "namespace_declaration" && kind != "file_scoped_namespace_declaration" {
            continue;
        }
        if let Some(name_node) = child.child_by_field_name("name") {
            let text = node_text(&name_node, bytes);
            return text
                .split('.')
                .filter(|s| !s.is_empty())
                .map(str::to_owned)
                .collect();
        }
    }

    // Fallback: derive from file path (strip `.cs`, strip leading `src/`).
    let p = file.strip_suffix(".cs").unwrap_or(file);
    let p = p.strip_prefix("src/").unwrap_or(p);
    p.split('/')
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
        .collect()
}

// ── Visibility ───────────────────────────────────────────────────────────────

/// Read the declared visibility from a declaration node's modifier children.
///
/// Precedence (checked in order):
/// 1. `private` keyword present → `Visibility::Private`
///    (covers `private protected`: `private` is checked first).
/// 2. `protected` keyword present → `Visibility::Protected`
///    (covers `protected internal`: `protected` is checked second).
/// 3. `public` keyword present → `Visibility::Public`.
/// 4. `internal` keyword present, OR no access modifier at all →
///    `Visibility::Internal` (C# namespace-level default).
///
/// Interface members carry no modifiers but are implicitly public; callers
/// that know they are inside an interface should use `Visibility::Public`
/// directly rather than calling this function.
fn read_visibility(node: &Node, bytes: &[u8]) -> Visibility {
    let mut has_private = false;
    let mut has_protected = false;
    let mut has_public = false;

    for child in node.children(&mut node.walk()) {
        if child.kind() == "modifier" {
            match node_text(&child, bytes) {
                "private" => has_private = true,
                "protected" => has_protected = true,
                "public" => has_public = true,
                _ => {}
            }
        }
    }

    if has_private {
        Visibility::Private
    } else if has_protected {
        Visibility::Protected
    } else if has_public {
        Visibility::Public
    } else {
        // `internal` explicit, or no access modifier → internal (C# namespace default).
        Visibility::Internal
    }
}

/// Whether `node` carries a `modifier` child whose text equals `kw`.
fn has_modifier(node: &tree_sitter::Node, bytes: &[u8], kw: &str) -> bool {
    node.children(&mut node.walk())
        .any(|c| c.kind() == "modifier" && node_text(&c, bytes) == kw)
}

// ── Symbol collection ────────────────────────────────────────────────────────

fn collect_symbols(root: &Node, bytes: &[u8], file: &str, namespaces: &[String]) -> Vec<Symbol> {
    let mut out = Vec::new();
    let ctx = ExtractCtx {
        bytes,
        file,
        lang: Language::CSharp,
    };
    let ns_descriptors: Vec<Descriptor> = namespaces
        .iter()
        .cloned()
        .map(Descriptor::Namespace)
        .collect();

    // Walk looking for namespace or type declarations at the top level.
    collect_types_in(root, &ctx, &ns_descriptors, false, &mut out);
    out
}

/// Recursively collect type (class/struct/interface/enum/record) declarations
/// and their members from `node`, building descriptor paths from `prefix`.
///
/// `implicit_public` is true when we are inside an interface body (all members
/// are implicitly public regardless of modifiers).
fn collect_types_in(
    node: &Node,
    ctx: &ExtractCtx,
    prefix: &[Descriptor],
    implicit_public: bool,
    out: &mut Vec<Symbol>,
) {
    for child in node.children(&mut node.walk()) {
        match child.kind() {
            // Namespace block — recurse with the same prefix; the namespace
            // descriptors were already derived at the file level.
            "namespace_declaration" | "file_scoped_namespace_declaration" => {
                // The body holds the type declarations.
                if let Some(body) = child.child_by_field_name("body") {
                    collect_types_in(&body, ctx, prefix, false, out);
                } else {
                    // file-scoped namespace: members are siblings in compilation_unit
                    // — they will be visited in the outer loop.
                }
            }
            k @ ("class_declaration"
            | "struct_declaration"
            | "interface_declaration"
            | "enum_declaration"
            | "record_declaration") => {
                let Some(type_name) = field_text(&child, "name", ctx.bytes) else {
                    continue;
                };
                let type_kind = match k {
                    "class_declaration" | "record_declaration" => SymbolKind::Class,
                    "struct_declaration" => SymbolKind::Struct,
                    "interface_declaration" => SymbolKind::Interface,
                    "enum_declaration" => SymbolKind::Enum,
                    _ => SymbolKind::Class,
                };
                let vis = if implicit_public {
                    Visibility::Public
                } else {
                    read_visibility(&child, ctx.bytes)
                };

                let mut type_descriptors = prefix.to_vec();
                type_descriptors.push(Descriptor::Type(type_name.clone()));
                let sig = one_line_signature(node_text(&child, ctx.bytes), &['{', ';']);
                out.push(make_symbol(
                    ctx,
                    &child,
                    type_name.clone(),
                    type_kind,
                    vis,
                    type_descriptors.clone(),
                    sig,
                ));

                let implicit = k == "interface_declaration";

                // Descend into the type body for members.
                if let Some(body) = child.child_by_field_name("body") {
                    collect_members(&body, ctx, &type_descriptors, implicit, out);
                }
            }
            _ => {}
        }
    }
}

/// Collect members from a type body (`declaration_list` or
/// `enum_member_declaration_list`).
fn collect_members(
    body: &Node,
    ctx: &ExtractCtx,
    type_prefix: &[Descriptor],
    implicit_public: bool,
    out: &mut Vec<Symbol>,
) {
    for member in body.children(&mut body.walk()) {
        match member.kind() {
            "method_declaration" | "constructor_declaration" | "property_declaration" => {
                let Some(name) = field_text(&member, "name", ctx.bytes) else {
                    continue;
                };
                let vis = if implicit_public {
                    Visibility::Public
                } else {
                    read_visibility(&member, ctx.bytes)
                };
                let mut descriptors = type_prefix.to_vec();
                descriptors.push(Descriptor::Method {
                    name: name.clone(),
                    disambiguator: String::new(),
                });
                let sig = one_line_signature(node_text(&member, ctx.bytes), &['{', ';']);
                // A `static Main` (case-sensitive) method is the C# entry point.
                let is_main = member.kind() == "method_declaration"
                    && name == "Main"
                    && has_modifier(&member, ctx.bytes, "static");
                out.push(make_symbol(
                    ctx,
                    &member,
                    name,
                    SymbolKind::Method,
                    vis,
                    descriptors,
                    sig,
                ));
                if is_main {
                    if let Some(s) = out.last_mut() {
                        s.entry_points.push(EntryPoint::Main);
                    }
                }
            }
            "field_declaration" => {
                let vis = if implicit_public {
                    Visibility::Public
                } else {
                    read_visibility(&member, ctx.bytes)
                };
                // field_declaration has no `name` field — descend into
                // variable_declaration → variable_declarator.
                collect_field_declarators(&member, ctx, type_prefix, vis, out);
            }
            "enum_member_declaration" => {
                // Enum members are always public.
                let Some(name) = field_text(&member, "name", ctx.bytes) else {
                    continue;
                };
                let mut descriptors = type_prefix.to_vec();
                descriptors.push(Descriptor::Term(name.clone()));
                let sig = one_line_signature(node_text(&member, ctx.bytes), &['{', ';', ',']);
                out.push(make_symbol(
                    ctx,
                    &member,
                    name,
                    SymbolKind::Const,
                    Visibility::Public,
                    descriptors,
                    sig,
                ));
            }
            // Nested type declarations inside another type.
            k @ ("class_declaration"
            | "struct_declaration"
            | "interface_declaration"
            | "enum_declaration"
            | "record_declaration") => {
                let Some(nested_name) = field_text(&member, "name", ctx.bytes) else {
                    continue;
                };
                let nested_kind = match k {
                    "class_declaration" | "record_declaration" => SymbolKind::Class,
                    "struct_declaration" => SymbolKind::Struct,
                    "interface_declaration" => SymbolKind::Interface,
                    "enum_declaration" => SymbolKind::Enum,
                    _ => SymbolKind::Class,
                };
                let vis = if implicit_public {
                    Visibility::Public
                } else {
                    read_visibility(&member, ctx.bytes)
                };
                let mut nested_descriptors = type_prefix.to_vec();
                nested_descriptors.push(Descriptor::Type(nested_name.clone()));
                let sig = one_line_signature(node_text(&member, ctx.bytes), &['{', ';']);
                out.push(make_symbol(
                    ctx,
                    &member,
                    nested_name.clone(),
                    nested_kind,
                    vis,
                    nested_descriptors.clone(),
                    sig,
                ));
                let implicit = k == "interface_declaration";
                if let Some(nested_body) = member.child_by_field_name("body") {
                    collect_members(&nested_body, ctx, &nested_descriptors, implicit, out);
                }
            }
            _ => {}
        }
    }
}

/// Emit a `Term`/`Static` symbol for each variable declared in a
/// `field_declaration`. The grammar nests as:
///   field_declaration → variable_declaration → variable_declarator* → identifier
fn collect_field_declarators(
    field: &Node,
    ctx: &ExtractCtx,
    type_prefix: &[Descriptor],
    visibility: Visibility,
    out: &mut Vec<Symbol>,
) {
    for child in field.children(&mut field.walk()) {
        if child.kind() != "variable_declaration" {
            continue;
        }
        for decl in child.children(&mut child.walk()) {
            if decl.kind() != "variable_declarator" {
                continue;
            }
            // First named child that is an identifier is the variable name.
            for id_node in decl.children(&mut decl.walk()) {
                if id_node.kind() == "identifier" {
                    let name = node_text(&id_node, ctx.bytes).to_owned();
                    let mut descriptors = type_prefix.to_vec();
                    descriptors.push(Descriptor::Term(name.clone()));
                    let sig = one_line_signature(node_text(field, ctx.bytes), &['{', ';']);
                    out.push(make_symbol(
                        ctx,
                        field,
                        name,
                        SymbolKind::Static,
                        visibility,
                        descriptors,
                        sig,
                    ));
                    break; // only the first identifier is the name
                }
            }
        }
    }
}

// ── Inheritance (base_list) ──────────────────────────────────────────────────

/// Walk the tree and emit `IsImplementation` references for base types listed
/// in a `base_list` node (both `class X : Base, IFoo` and interface extends).
fn collect_inheritance(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    if node.kind() == "base_list" {
        for child in node.children(&mut node.walk()) {
            match child.kind() {
                "identifier" => {
                    push_ref(
                        out,
                        node_text(&child, bytes),
                        &child,
                        file,
                        RefRole::IsImplementation,
                    );
                }
                "qualified_name" | "generic_name" => {
                    let name = simple_type_name(node_text(&child, bytes), ".");
                    push_ref(out, name, &child, file, RefRole::IsImplementation);
                }
                _ => {}
            }
        }
    }
    for child in node.children(&mut node.walk()) {
        collect_inheritance(&child, bytes, file, out);
    }
}

// ── Imports (using_directive) ────────────────────────────────────────────────

/// Walk the tree emitting `Import` references for `using_directive` nodes.
///
/// Handles `using A.B.C;` — the leaf name is `C`, the from_path is `A.B`.
/// Alias forms (`using Alias = X.Y`) and `using static X.Y` are skipped
/// to avoid ambiguity; they do not crash.
fn collect_imports(
    node: &Node,
    bytes: &[u8],
    file: &str,
    out: &mut Vec<Reference>,
    module_id: &str,
) {
    if node.kind() == "using_directive" {
        // Look for the namespace name: a qualified_name or identifier child.
        // Skip alias directives: they have an `=` among their children (name_equals).
        let has_alias = node
            .children(&mut node.walk())
            .any(|c| c.kind() == "name_equals");
        if !has_alias {
            // Find the name node — could be qualified_name or identifier.
            let mut name_node: Option<Node> = None;
            for child in node.children(&mut node.walk()) {
                match child.kind() {
                    "qualified_name" | "identifier" => {
                        name_node = Some(child);
                        break;
                    }
                    _ => {}
                }
            }
            if let Some(qn) = name_node {
                let full_text = node_text(&qn, bytes);
                if qn.kind() == "qualified_name" {
                    // Split on last `.` to get leaf name and from_path.
                    if let Some(dot) = full_text.rfind('.') {
                        let from_path = &full_text[..dot];
                        let leaf = &full_text[dot + 1..];
                        // Find the leaf identifier node for position.
                        if let Some(name_field) = qn.child_by_field_name("name") {
                            push_import_ref(out, leaf, &name_field, file, module_id, from_path);
                        } else {
                            push_import_ref(out, leaf, &qn, file, module_id, from_path);
                        }
                    } else {
                        // Malformed qualified_name — emit as bare.
                        push_import_ref(out, full_text, &qn, file, module_id, "");
                    }
                } else {
                    // Bare identifier: `using Foo;`
                    push_import_ref(out, full_text, &qn, file, module_id, "");
                }
            }
        }
        return;
    }
    for child in node.children(&mut node.walk()) {
        collect_imports(&child, bytes, file, out, module_id);
    }
}

// ── Read / Write references ──────────────────────────────────────────────────

/// Returns `true` when `node` (an `identifier`) is in a position already
/// captured by another collector (call callee, declaration name, parameter
/// name, import binding, assignment LHS, or member-access leaf) so it must
/// NOT also be emitted as a Read reference.
fn is_non_read_position(node: &Node) -> bool {
    let parent = match node.parent() {
        Some(p) => p,
        None => return true, // root — not a read
    };
    // General type-field exclusion: if this identifier IS the `type` field of
    // its parent (covers variable_declaration, parameter, field_declaration →
    // variable_declaration, property_declaration, object_creation_expression,
    // etc.) it is a type-annotation position, not a value read.
    if parent.child_by_field_name("type").as_ref() == Some(node) {
        return true;
    }
    // Method return-type uses the `returns` field (not `type`), also type-position.
    if parent.child_by_field_name("returns").as_ref() == Some(node) {
        return true;
    }
    match parent.kind() {
        // Call callee: `Foo()` — `function:` field of invocation_expression.
        "invocation_expression" => parent.child_by_field_name("function").as_ref() == Some(node),
        // Declaration names: method/constructor/class/struct/interface/enum/record.
        "method_declaration"
        | "constructor_declaration"
        | "property_declaration"
        | "class_declaration"
        | "struct_declaration"
        | "interface_declaration"
        | "enum_declaration"
        | "record_declaration"
        | "enum_member_declaration" => parent.child_by_field_name("name").as_ref() == Some(node),
        // Local variable declarator: the `name:` field is the binding introduction.
        "variable_declarator" => parent.child_by_field_name("name").as_ref() == Some(node),
        // Parameter binding name.
        "parameter" => parent.child_by_field_name("name").as_ref() == Some(node),
        // Using-directive — already Import refs.
        "using_directive" => true,
        // Member-access leaf (`obj.Field` — skip `Field`, keep `obj`).
        "member_access_expression" => parent.child_by_field_name("name").as_ref() == Some(node),
        // Qualified name — type-position names (e.g. in base_list or generic types).
        "qualified_name" => true,
        // Generic name — the type identifier inside `List<T>`.
        "generic_name" => parent.child_by_field_name("name").as_ref() == Some(node),
        // Assignment LHS — handled by collect_write_references.
        "assignment_expression" => parent.child_by_field_name("left").as_ref() == Some(node),
        _ => false,
    }
}

/// Recursively walk `node` and emit [`RefRole::Read`] references for bare
/// `identifier` nodes used in value/expression positions.
///
/// Skips identifiers already captured by other collectors (call callees,
/// declaration names, parameter names, import bindings, assignment LHS,
/// member-access leaf names, type-annotation positions).
/// Applies [`MIN_REF_LEN`] (same threshold as calls).
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_expression` nodes
/// (e.g. `x = 5`, `total += bonus`).
///
/// C# uses `assignment_expression` for both plain (`=`) and compound
/// (`+=`, `-=`, …) assignments — both are covered here.
/// Member / subscript LHS (`obj.Field = …`, `arr[i] = …`) are out of scope
/// in v1 — bare identifiers only.  Applies [`MIN_REF_LEN`].
fn collect_write_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    if node.kind() == "assignment_expression" {
        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);
    }
}

// ── TypeRef edges ────────────────────────────────────────────────────────────

/// Recursively walk `node` emitting [`RefRole::TypeRef`] references for
/// user-defined type names in typed positions.
///
/// Covers: method return types (`returns` field), parameter types, field/property
/// types. Skips C# predefined types (`predefined_type`).
fn collect_type_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    match node.kind() {
        "method_declaration" => {
            if let Some(ret) = node.child_by_field_name("returns") {
                type_leaf(&ret, bytes, file, TypeRefContext::ReturnType, out);
            }
        }
        "parameter" => {
            if let Some(ty) = node.child_by_field_name("type") {
                type_leaf(&ty, bytes, file, TypeRefContext::ParameterType, out);
            }
        }
        "field_declaration" => {
            for child in node.children(&mut node.walk()) {
                if child.kind() == "variable_declaration" {
                    if let Some(ty) = child.child_by_field_name("type") {
                        type_leaf(&ty, bytes, file, TypeRefContext::Field, out);
                    }
                }
            }
        }
        "property_declaration" => {
            if let Some(ty) = node.child_by_field_name("type") {
                type_leaf(&ty, bytes, file, TypeRefContext::Field, out);
            }
        }
        _ => {}
    }
    for child in node.children(&mut node.walk()) {
        collect_type_references(&child, bytes, file, out);
    }
}

fn type_leaf(node: &Node, bytes: &[u8], file: &str, ctx: TypeRefContext, out: &mut Vec<Reference>) {
    match node.kind() {
        "predefined_type" | "void_keyword" => {}
        "identifier" => {
            let name = node_text(node, bytes);
            push_type_ref(out, name, node, file, ctx);
        }
        "qualified_name" | "generic_name" => {
            let name = simple_type_name(node_text(node, bytes), ".");
            push_type_ref(out, name, node, file, ctx);
        }
        "nullable_type" | "array_type" => {
            if let Some(elem) = node.named_children(&mut node.walk()).next() {
                type_leaf(&elem, bytes, file, ctx, out);
            }
        }
        _ => {
            // For other composed types, recurse into named children.
            for child in node.named_children(&mut node.walk()) {
                type_leaf(&child, bytes, file, ctx, out);
            }
        }
    }
}

// ── Scope tree ───────────────────────────────────────────────────────────────

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
}

fn scope_dfs(node: &Node, parent_id: ScopeId, scopes: &mut Vec<Scope>) {
    match node.kind() {
        "namespace_declaration" | "file_scoped_namespace_declaration" => {
            let ns_id = push_scope(scopes, Some(parent_id), node_span(node), ScopeKind::Module);
            if let Some(body) = node.child_by_field_name("body") {
                for child in body.children(&mut body.walk()) {
                    scope_dfs(&child, ns_id, scopes);
                }
            }
        }
        "class_declaration"
        | "struct_declaration"
        | "interface_declaration"
        | "enum_declaration"
        | "record_declaration" => {
            let type_id = push_scope(scopes, Some(parent_id), node_span(node), ScopeKind::Type);
            if let Some(body) = node.child_by_field_name("body") {
                for child in body.children(&mut body.walk()) {
                    scope_dfs(&child, type_id, scopes);
                }
            }
        }
        "method_declaration" | "constructor_declaration" => {
            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);
                }
            }
        }
        "block" => {
            let block_id = push_scope(scopes, Some(parent_id), node_span(node), ScopeKind::Block);
            for child in node.children(&mut node.walk()) {
                scope_dfs(&child, block_id, scopes);
            }
        }
        _ => {
            for child in node.children(&mut node.walk()) {
                scope_dfs(&child, parent_id, scopes);
            }
        }
    }
}

// ── Bindings ─────────────────────────────────────────────────────────────────

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() {
        "method_declaration" | "constructor_declaration" => {
            if let Some(params) = node.child_by_field_name("parameters") {
                collect_params(&params, bytes, scopes, out);
            }
        }
        "local_declaration_statement" => {
            // local_declaration_statement → variable_declaration → variable_declarator* → identifier
            for child in node.children(&mut node.walk()) {
                if child.kind() == "variable_declaration" {
                    for decl in child.children(&mut child.walk()) {
                        if decl.kind() == "variable_declarator" {
                            for id_node in decl.children(&mut decl.walk()) {
                                if id_node.kind() == "identifier" {
                                    let name = node_text(&id_node, bytes);
                                    let intro = id_node.start_byte();
                                    if name.len() >= MIN_REF_LEN
                                        && innermost_scope(intro, scopes) != Some(0)
                                    {
                                        push_binding(
                                            out,
                                            name.to_owned(),
                                            intro,
                                            BindingKind::Local,
                                            scopes,
                                        );
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        "for_each_statement" => {
            if let Some(name_node) = node.child_by_field_name("left") {
                if name_node.kind() == "identifier" {
                    let name = node_text(&name_node, bytes);
                    let intro = name_node.start_byte();
                    if innermost_scope(intro, scopes) != Some(0) {
                        push_binding(out, name.to_owned(), intro, BindingKind::Local, scopes);
                    }
                }
            }
        }
        "catch_clause" => {
            if let Some(decl) = node.child_by_field_name("declaration") {
                if let Some(name_node) = decl.child_by_field_name("name") {
                    let name = node_text(&name_node, bytes);
                    let intro = name_node.start_byte();
                    push_binding(out, name.to_owned(), intro, BindingKind::Param, scopes);
                }
            }
        }
        _ => {}
    }
    for child in node.children(&mut node.walk()) {
        collect_bindings_dfs(&child, bytes, scopes, out);
    }
}

fn collect_params(params: &Node, bytes: &[u8], scopes: &[Scope], out: &mut Vec<Binding>) {
    for child in params.named_children(&mut params.walk()) {
        if child.kind() == "parameter" {
            if let Some(name_node) = child.child_by_field_name("name") {
                let name = node_text(&name_node, bytes);
                let intro = name_node.start_byte();
                push_binding(out, name.to_owned(), intro, BindingKind::Param, scopes);
            }
        }
    }
}

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

    #[test]
    fn static_main_is_entry_point() {
        let src = r#"
class Program {
    static void Main(string[] args) {}
}
"#;
        let facts = CSharpExtractor.extract(src, "src/Program.cs").unwrap();
        let main = facts.symbols.iter().find(|s| s.name == "Main").unwrap();
        assert!(
            main.entry_points
                .iter()
                .any(|e| matches!(e, EntryPoint::Main))
        );
    }

    #[test]
    fn instance_main_is_not_entry_point() {
        let src = r#"
class Program {
    void Main() {}
}
"#;
        let facts = CSharpExtractor.extract(src, "src/Program.cs").unwrap();
        let main = facts.symbols.iter().find(|s| s.name == "Main").unwrap();
        assert!(
            !main
                .entry_points
                .iter()
                .any(|e| matches!(e, EntryPoint::Main))
        );
    }

    // ── Definitions ──────────────────────────────────────────────────────────

    #[test]
    fn class_and_method_get_correct_scip_strings() {
        let src = r#"
namespace MyApp.Auth {
    public class SessionManager {
        public bool Validate(string token) { return true; }
        private void Secret() {}
    }
}
"#;
        let facts = CSharpExtractor
            .extract(src, "src/MyApp/Auth/SessionManager.cs")
            .unwrap();

        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let sm = by_name("SessionManager").unwrap();
        assert_eq!(sm.kind, SymbolKind::Class);
        assert_eq!(sm.visibility, Visibility::Public);
        assert_eq!(
            sm.id.to_scip_string(),
            "codegraph . . . MyApp/Auth/SessionManager#"
        );

        let validate = by_name("Validate").unwrap();
        assert_eq!(validate.kind, SymbolKind::Method);
        assert_eq!(validate.visibility, Visibility::Public);
        assert_eq!(
            validate.id.to_scip_string(),
            "codegraph . . . MyApp/Auth/SessionManager#Validate()."
        );

        // private method must appear with Visibility::Private
        let secret = by_name("Secret").expect("private method 'Secret' must now be emitted");
        assert_eq!(secret.visibility, Visibility::Private);
        assert_eq!(
            secret.id.to_scip_string(),
            "codegraph . . . MyApp/Auth/SessionManager#Secret()."
        );

        assert_eq!(facts.lang, "csharp");
    }

    #[test]
    fn namespace_block_yields_correct_descriptors() {
        let src = r#"
namespace A.B {
    public class C {
        public void M() {}
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/A/B/C.cs").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let c = by_name("C").unwrap();
        assert_eq!(c.id.to_scip_string(), "codegraph . . . A/B/C#");

        let m = by_name("M").unwrap();
        assert_eq!(m.id.to_scip_string(), "codegraph . . . A/B/C#M().");
    }

    #[test]
    fn file_scoped_namespace_works() {
        let src = r#"
namespace A.B;

public class Foo {
    public void Bar() {}
}
"#;
        let facts = CSharpExtractor.extract(src, "src/A/B/Foo.cs").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let foo = by_name("Foo").unwrap();
        assert_eq!(foo.id.to_scip_string(), "codegraph . . . A/B/Foo#");

        let bar = by_name("Bar").unwrap();
        assert_eq!(bar.id.to_scip_string(), "codegraph . . . A/B/Foo#Bar().");
    }

    #[test]
    fn enum_and_enum_member_are_extracted() {
        let src = r#"
namespace N {
    public enum Color { Red, Green, Blue }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/Color.cs").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let color = by_name("Color").unwrap();
        assert_eq!(color.kind, SymbolKind::Enum);
        assert_eq!(color.id.to_scip_string(), "codegraph . . . N/Color#");

        let red = by_name("Red").unwrap();
        assert_eq!(red.kind, SymbolKind::Const);
        assert_eq!(red.id.to_scip_string(), "codegraph . . . N/Color#Red.");
    }

    #[test]
    fn field_is_extracted() {
        let src = r#"
namespace N {
    public class C {
        public int Count;
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/C.cs").unwrap();
        let count = facts
            .symbols
            .iter()
            .find(|s| s.name == "Count")
            .expect("expected field Count");
        assert_eq!(count.kind, SymbolKind::Static);
        assert_eq!(count.id.to_scip_string(), "codegraph . . . N/C#Count.");
    }

    // ── References ───────────────────────────────────────────────────────────

    #[test]
    fn qualified_call_captures_qualifier() {
        let src = r#"
public class Client {
    public void Run() {
        var obj = new Service();
        obj.Foo();
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/Client.cs").unwrap();

        // Foo should appear as a Call reference.
        let foo = facts
            .references
            .iter()
            .find(|r| r.name == "Foo")
            .expect("expected Call ref for 'Foo'");
        assert_eq!(foo.role, RefRole::Call);
        // The receiver must be captured as the call's qualifier (so Tier-B can
        // disambiguate), not emitted as a separate reference.
        assert_eq!(
            foo.qualifier.as_deref(),
            Some("obj"),
            "expected qualifier 'obj' on the Foo call ref",
        );
    }

    #[test]
    fn using_directive_produces_import_reference() {
        let src = r#"
using System.Collections.Generic;
public class C {}
"#;
        let facts = CSharpExtractor.extract(src, "src/C.cs").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(&"Generic"),
            "expected 'Generic' in import refs: {import_names:?}"
        );
        // Verify from_path is set.
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Import && r.name == "Generic")
            .unwrap();
        assert_eq!(
            r.from_path,
            Some("System.Collections".to_owned()),
            "from_path should be 'System.Collections', got {:?}",
            r.from_path
        );
    }

    #[test]
    fn inheritance_produces_is_implementation_references() {
        let src = r#"
public class Foo : Bar, IBaz {}
"#;
        let facts = CSharpExtractor.extract(src, "src/Foo.cs").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(&"Bar"),
            "expected 'Bar' in {inherit_names:?}"
        );
        assert!(
            inherit_names.contains(&"IBaz"),
            "expected 'IBaz' in {inherit_names:?}"
        );
    }

    #[test]
    fn interface_members_emitted_without_public_modifier() {
        let src = r#"
namespace Svc {
    public interface IReader {
        int Read();
        void Close();
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/Svc/IReader.cs").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let read = by_name("Read").unwrap();
        assert_eq!(read.kind, SymbolKind::Method);
        let close = by_name("Close").unwrap();
        assert_eq!(close.kind, SymbolKind::Method);
    }

    // ── Read / Write references ──────────────────────────────────────────────

    #[test]
    fn reassignment_emits_write_for_lhs_and_read_for_rhs() {
        // `total = total + bonus;` — Write for the LHS `total`, Read for the
        // RHS `total` and for `bonus`.
        let src = r#"
public class Calc {
    public int Run(int total, int bonus) {
        total = total + bonus;
        return total;
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/Calc.cs").unwrap();

        let writes: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Write)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            writes.contains(&"total"),
            "expected Write for 'total', got: {writes:?}",
        );

        let reads: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            reads.contains(&"bonus"),
            "expected Read for 'bonus', got: {reads:?}",
        );
        // The RHS `total` should also be a Read.
        assert!(
            reads.contains(&"total"),
            "expected Read for RHS 'total', got: {reads:?}",
        );
    }

    #[test]
    fn local_declaration_does_not_emit_write() {
        // `var result = Compute();` — `result` is a binding introduction, NOT a Write.
        let src = r#"
public class Worker {
    public int Run() {
        var result = Compute();
        return result;
    }
    private int Compute() { return 42; }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/Worker.cs").unwrap();

        let writes: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Write)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            !writes.contains(&"result"),
            "declaration binding must NOT produce a Write ref; got writes: {writes:?}",
        );
    }

    #[test]
    fn call_argument_emits_read_but_not_callee() {
        // `Log(config);` — `config` is a Read; `Log` is a Call, NOT a Read.
        let src = r#"
public class App {
    public void Run(object config) {
        Log(config);
    }
    private void Log(object msg) {}
}
"#;
        let facts = CSharpExtractor.extract(src, "src/App.cs").unwrap();

        let reads: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            reads.contains(&"config"),
            "expected Read for 'config', got: {reads:?}",
        );
        assert!(
            !reads.contains(&"Log"),
            "callee 'Log' must NOT appear as a Read ref; reads: {reads:?}",
        );
    }

    #[test]
    fn member_access_emits_read_for_base_not_leaf() {
        // `value = source.Field;` — Read for `source` (base), NOT for `Field` (leaf).
        let src = r#"
public class Copier {
    public int Run(DataObj source) {
        int value = source.Field;
        return value;
    }
}
public class DataObj { public int Field; }
"#;
        let facts = CSharpExtractor.extract(src, "src/Copier.cs").unwrap();

        let reads: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            reads.contains(&"source"),
            "expected Read for 'source', got: {reads:?}",
        );
        assert!(
            !reads.contains(&"Field"),
            "member-access leaf 'Field' must NOT be a Read ref; reads: {reads:?}",
        );
    }

    #[test]
    fn type_name_in_typed_local_is_not_a_read() {
        // `Helper result = source;` — `Helper` is a type annotation (TypeRef),
        // NOT a value read. `source` IS a value read.
        let src = r#"
class C {
    void M(Helper source) {
        Helper result = source;
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/C.cs").unwrap();

        let reads: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            !reads.contains(&"Helper"),
            "type name 'Helper' must NOT appear as a Read ref; reads: {reads:?}",
        );
        assert!(
            reads.contains(&"source"),
            "initializer value 'source' must appear as a Read ref; reads: {reads:?}",
        );
    }

    // ── Visibility tagging ────────────────────────────────────────────────────

    #[test]
    fn public_visibility_tagged_correctly() {
        let src = r#"
namespace N {
    public class Svc {
        public void Open() {}
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/Svc.cs").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        assert_eq!(by_name("Svc").unwrap().visibility, Visibility::Public);
        assert_eq!(by_name("Open").unwrap().visibility, Visibility::Public);
    }

    #[test]
    fn private_def_emitted_with_private_visibility() {
        let src = r#"
namespace N {
    public class Worker {
        private void Helper() {}
        private int count;
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/Worker.cs").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let helper = by_name("Helper").expect("private method must be emitted");
        assert_eq!(helper.visibility, Visibility::Private);

        let count = by_name("count").expect("private field must be emitted");
        assert_eq!(count.visibility, Visibility::Private);
    }

    #[test]
    fn protected_def_emitted_with_protected_visibility() {
        let src = r#"
namespace N {
    public class Base {
        protected void OnInit() {}
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/Base.cs").unwrap();
        let on_init = facts
            .symbols
            .iter()
            .find(|s| s.name == "OnInit")
            .expect("protected method must be emitted");
        assert_eq!(on_init.visibility, Visibility::Protected);
    }

    #[test]
    fn internal_def_emitted_with_internal_visibility() {
        let src = r#"
namespace N {
    internal class Cache {
        internal void Flush() {}
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/Cache.cs").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let cache = by_name("Cache").expect("internal class must be emitted");
        assert_eq!(cache.visibility, Visibility::Internal);

        let flush = by_name("Flush").expect("internal method must be emitted");
        assert_eq!(flush.visibility, Visibility::Internal);
    }

    #[test]
    fn no_modifier_maps_to_internal() {
        // A class with no access modifier at namespace level defaults to internal in C#.
        let src = r#"
namespace N {
    class Hidden {
        void DoWork() {}
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/Hidden.cs").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        let hidden = by_name("Hidden").expect("no-modifier class must be emitted");
        assert_eq!(hidden.visibility, Visibility::Internal);

        let do_work = by_name("DoWork").expect("no-modifier method must be emitted");
        assert_eq!(do_work.visibility, Visibility::Internal);
    }

    #[test]
    fn private_protected_maps_to_private() {
        let src = r#"
namespace N {
    public class Base {
        private protected void Hook() {}
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/Base.cs").unwrap();
        let hook = facts
            .symbols
            .iter()
            .find(|s| s.name == "Hook")
            .expect("private protected method must be emitted");
        // private is checked first → Private
        assert_eq!(hook.visibility, Visibility::Private);
    }

    #[test]
    fn protected_internal_maps_to_protected() {
        let src = r#"
namespace N {
    public class Base {
        protected internal void Extend() {}
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/Base.cs").unwrap();
        let extend = facts
            .symbols
            .iter()
            .find(|s| s.name == "Extend")
            .expect("protected internal method must be emitted");
        // private absent, protected present → Protected
        assert_eq!(extend.visibility, Visibility::Protected);
    }

    #[test]
    fn interface_members_tagged_public_implicitly() {
        let src = r#"
namespace N {
    public interface IFoo {
        void Bar();
        int Baz { get; }
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/IFoo.cs").unwrap();
        let by_name = |n: &str| facts.symbols.iter().find(|s| s.name == n).cloned();

        assert_eq!(by_name("Bar").unwrap().visibility, Visibility::Public);
        assert_eq!(by_name("Baz").unwrap().visibility, Visibility::Public);
    }

    #[test]
    fn nested_private_type_emitted_with_private_visibility() {
        let src = r#"
namespace N {
    public class Outer {
        private class Inner {}
    }
}
"#;
        let facts = CSharpExtractor.extract(src, "src/N/Outer.cs").unwrap();
        let inner = facts
            .symbols
            .iter()
            .find(|s| s.name == "Inner")
            .expect("nested private class must be emitted");
        assert_eq!(inner.visibility, Visibility::Private);
    }
}