-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathcsharp.go
More file actions
1127 lines (1042 loc) · 38.5 KB
/
Copy pathcsharp.go
File metadata and controls
1127 lines (1042 loc) · 38.5 KB
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
package languages
import (
"bytes"
"fmt"
"regexp"
"strings"
"github.com/zzet/gortex/internal/graph"
"github.com/zzet/gortex/internal/parser"
sitter "github.com/zzet/gortex/internal/parser/tsitter"
"github.com/zzet/gortex/internal/parser/tsitter/csharp"
)
// csharpInterfaceNamePattern encodes the C# `I`-prefix convention
// (IService, IRepository, IList): an interface name conventionally
// starts with a capital `I` followed by another uppercase letter. The
// base-list heuristic falls back to this when a base type is defined in
// another compilation unit and so cannot be matched against the file's
// own interface declarations.
var csharpInterfaceNamePattern = regexp.MustCompile(`^I[A-Z]`)
// qCSharpAll is a single tree-sitter query alternating over every
// pattern the C# extractor needs. One tree walk per file replaces the
// 13 `parser.RunQuery` calls the previous design made (each of which
// recompiled its query and ran an independent cursor over the whole
// tree). Capture names are disjoint across patterns so the dispatch in
// Extract can branch on which name is set. Class / struct / interface
// membership for methods, constructors, fields, and properties is
// resolved via a parent walk on the captured node — the legacy nested
// queries duplicated each member pattern across class_declaration and
// struct_declaration; the parent walk collapses them into a single
// pattern per member kind.
const qCSharpAll = `
[
(namespace_declaration
name: (_) @ns.name) @ns.def
(class_declaration
name: (identifier) @class.name) @class.def
(interface_declaration
name: (identifier) @iface.name) @iface.def
(struct_declaration
name: (identifier) @struct.name) @struct.def
(record_declaration
name: (identifier) @record.name) @record.def
(enum_declaration
name: (identifier) @enum.name) @enum.def
(anonymous_object_creation_expression) @anon.def
(method_declaration
name: (identifier) @method.name) @method.def
(constructor_declaration
name: (identifier) @ctor.name) @ctor.def
(field_declaration
(variable_declaration
(variable_declarator
name: (identifier) @field.name))) @field.def
(property_declaration
name: (identifier) @prop.name) @prop.def
(using_directive (_) @using.path) @using.def
(invocation_expression
function: (identifier) @call.name) @call.expr
(invocation_expression
function: (member_access_expression
expression: (_) @callm.receiver
name: (identifier) @callm.method)) @callm.expr
(local_declaration_statement
(variable_declaration
type: (_) @lvar.type
(variable_declarator
(identifier) @lvar.name))) @lvar.def
]
`
// CSharpExtractor extracts C# source files into graph nodes and edges.
type CSharpExtractor struct {
lang *sitter.Language
qAll *parser.PreparedQuery
}
func NewCSharpExtractor() *CSharpExtractor {
lang := csharp.GetLanguage()
return &CSharpExtractor{
lang: lang,
qAll: parser.MustPreparedQuery(qCSharpAll, lang),
}
}
func (e *CSharpExtractor) Language() string { return "csharp" }
func (e *CSharpExtractor) Extensions() []string { return []string{".cs"} }
// --- Deferred match buffers ----------------------------------------
type csharpDeferredCall struct {
name string
receiver string
line int
isMember bool
// returnUsage is how the call site consumes the return value
// (graph.ReturnUsage* label), classified at capture time and
// stamped as edge Meta on the EdgeCalls emitted for this site.
returnUsage string
}
// csharpDeferredLocal buffers a local variable declaration for the
// post-pass type-env build. Matches the legacy two-stage pass: Tier 0
// records explicit types (`Foo svc = ...`); Tier 1 walks the def node
// for `var svc = new Foo()` to recover the type when Tier 0 left a
// "var" key without a real annotation.
type csharpDeferredLocal struct {
name string
rawType string
defNode *sitter.Node
}
// Extract parses the C# source, adaptively recovering symbols that tree-sitter
// silently drops inside conditional-compilation branches. The grammar parses a
// #if/#elif/#else block without raising any error, yet omits every declaration
// inside its branches from the tree — so a method guarded by #if vanishes with
// no signal. When the source uses conditional compilation, Extract therefore
// also extracts from a directive-blanked copy (offset-preserving) and keeps
// whichever variant yields more symbols; native wins ties, so a file the
// grammar already handles cleanly is never perturbed. This beats an always-blank
// rewrite, which would discard the grammar's handling on files that don't need
// it and can unbalance braces when both branches are forced live.
func (e *CSharpExtractor) Extract(filePath string, src []byte) (*parser.ExtractionResult, error) {
res, _, err := e.extractCSharp(filePath, src)
if err != nil {
return nil, err
}
if hasCSharpConditional(src) {
if alt, _, altErr := e.extractCSharp(filePath, blankConditionalDirectives(src)); altErr == nil && csharpSymbolCount(alt) > csharpSymbolCount(res) {
return alt, nil
}
}
return res, nil
}
// hasCSharpConditional reports whether src contains a conditional-compilation
// directive — the cheap gate that decides whether the directive-blanked
// re-parse is worth attempting. A false positive (the token in a string or
// comment) only costs one extra parse whose result loses the symbol-count tie.
func hasCSharpConditional(src []byte) bool {
return bytes.Contains(src, []byte("#if"))
}
// csharpSymbolCount counts the non-file symbol nodes in a result — the metric
// the adaptive re-parse maximises when deciding whether the directive-blanked
// variant recovered more of the file than the native parse.
func csharpSymbolCount(r *parser.ExtractionResult) int {
if r == nil {
return 0
}
n := 0
for _, nd := range r.Nodes {
if nd != nil && nd.Kind != graph.KindFile {
n++
}
}
return n
}
func (e *CSharpExtractor) extractCSharp(filePath string, src []byte) (*parser.ExtractionResult, bool, error) {
tree, err := parser.ParseFile(src, e.lang)
if err != nil {
return nil, false, err
}
defer tree.Close()
root := tree.RootNode()
result := &parser.ExtractionResult{}
hadError := root.HasError()
fileNode := &graph.Node{
ID: filePath, Kind: graph.KindFile, Name: filePath,
FilePath: filePath, StartLine: 1, EndLine: int(root.EndPoint().Row) + 1,
Language: "csharp",
}
// Parse-health signal: a file the grammar could not fully parse (and that
// the blanked re-parse did not improve) is flagged so a consumer knows its
// C# member surface may be incomplete — codegraph parses silently with no
// such signal.
if hadError {
fileNode.Meta = map[string]any{"parse_health": "partial"}
}
fileID := fileNode.ID
result.Nodes = append(result.Nodes, fileNode)
seen := make(map[string]bool)
annotationSeen := make(map[string]bool)
ifaceMethods := make(map[string][]string) // interface name → method names
// Pre-scan the file's own interface declarations. A base type that
// names one of these is definitively an interface, even when its name
// doesn't follow the `I`-prefix convention — the base-list heuristic
// (emitCSharpBaseList) checks this set before falling back to name
// shape so a locally-known interface always wins.
localInterfaces := collectCSharpInterfaceNames(root, src)
var calls []csharpDeferredCall
var locals []csharpDeferredLocal
parser.EachMatch(e.qAll, root, src, func(m parser.QueryResult) {
switch {
case m.Captures["ns.def"] != nil:
e.emitNamespace(m, filePath, fileID, result, seen)
case m.Captures["class.def"] != nil:
e.emitContainer(m, "class", graph.KindType, filePath, fileID, src, result, seen, annotationSeen, localInterfaces)
case m.Captures["iface.def"] != nil:
e.emitContainer(m, "iface", graph.KindInterface, filePath, fileID, src, result, seen, annotationSeen, localInterfaces)
case m.Captures["struct.def"] != nil:
e.emitContainer(m, "struct", graph.KindType, filePath, fileID, src, result, seen, annotationSeen, localInterfaces)
case m.Captures["record.def"] != nil:
e.emitContainer(m, "record", graph.KindType, filePath, fileID, src, result, seen, annotationSeen, localInterfaces)
case m.Captures["enum.def"] != nil:
e.emitContainer(m, "enum", graph.KindType, filePath, fileID, src, result, seen, annotationSeen, localInterfaces)
case m.Captures["anon.def"] != nil:
e.emitAnonymousType(m, filePath, fileID, result, seen)
case m.Captures["method.def"] != nil:
e.emitMethod(m, filePath, fileID, src, result, seen, annotationSeen, ifaceMethods)
case m.Captures["ctor.def"] != nil:
e.emitConstructor(m, filePath, fileID, src, result, seen)
case m.Captures["field.def"] != nil:
e.emitField(m, filePath, fileID, src, result, seen)
case m.Captures["prop.def"] != nil:
e.emitProperty(m, filePath, fileID, src, result, seen)
case m.Captures["using.def"] != nil:
e.emitUsing(m, filePath, fileID, result)
case m.Captures["callm.expr"] != nil:
expr := m.Captures["callm.expr"]
calls = append(calls, csharpDeferredCall{
name: m.Captures["callm.method"].Text,
receiver: m.Captures["callm.receiver"].Text,
line: expr.StartLine + 1,
isMember: true,
returnUsage: classifyReturnUsage(expr.Node, src, csharpReturnUsageSpec),
})
case m.Captures["call.expr"] != nil:
expr := m.Captures["call.expr"]
calls = append(calls, csharpDeferredCall{
name: m.Captures["call.name"].Text,
line: expr.StartLine + 1,
returnUsage: classifyReturnUsage(expr.Node, src, csharpReturnUsageSpec),
})
case m.Captures["lvar.def"] != nil:
locals = append(locals, csharpDeferredLocal{
name: m.Captures["lvar.name"].Text,
rawType: m.Captures["lvar.type"].Text,
defNode: m.Captures["lvar.def"].Node,
})
}
})
// Stamp interface method names onto interface nodes' Meta["methods"].
for _, n := range result.Nodes {
if n.Kind != graph.KindInterface {
continue
}
if methods, ok := ifaceMethods[n.Name]; ok {
if n.Meta == nil {
n.Meta = make(map[string]any)
}
n.Meta["methods"] = methods
}
}
// Build type environment in legacy precedence:
// Tier 0 — explicit type annotations (skip "var" placeholder)
// Tier 1 — `var x = new Foo()` walk for `var`-keyed locals only
tenv := make(typeEnv)
for _, l := range locals {
typeName := normalizeCSharpTypeName(l.rawType)
if typeName != "" && typeName != "var" {
tenv[l.name] = typeName
}
}
for _, l := range locals {
if _, exists := tenv[l.name]; exists {
continue
}
if l.rawType != "var" {
continue
}
if l.defNode == nil {
continue
}
walkNodes(l.defNode, func(n *sitter.Node) {
if n.Type() == "object_creation_expression" {
typeName := inferTypeFromCSharpNew(n, src)
if typeName != "" {
tenv[l.name] = typeName
}
}
})
}
// Resolve calls against funcRanges + tenv.
funcRanges := buildFuncRanges(result)
for _, c := range calls {
callerID := findEnclosingFunc(funcRanges, c.line)
if callerID == "" {
continue
}
if c.isMember {
edge := &graph.Edge{
From: callerID, To: "unresolved::*." + c.name,
Kind: graph.EdgeCalls, FilePath: filePath, Line: c.line,
}
if recvType, ok := tenv[c.receiver]; ok {
edge.Meta = map[string]any{"receiver_type": recvType}
} else if strings.Contains(c.receiver, ".") || strings.Contains(c.receiver, "(") {
if chainType := resolveChainType(c.receiver, tenv, result); chainType != "" {
edge.Meta = map[string]any{"receiver_type": chainType}
}
}
stampReturnUsage(edge, c.returnUsage)
result.Edges = append(result.Edges, edge)
continue
}
edge := &graph.Edge{
From: callerID, To: "unresolved::" + c.name,
Kind: graph.EdgeCalls, FilePath: filePath, Line: c.line,
}
stampReturnUsage(edge, c.returnUsage)
result.Edges = append(result.Edges, edge)
}
// .NET surfaces a symbol walk misses: DI registrations + COM
// interop. Stamped onto the file node.
detectDotNetSurfaces(src, result)
// Same-file constant/variable value references → impact-radius reads.
captureValueRefCandidates(result, root, filePath, src)
captureFnValueCandidates(result, root, filePath, src)
return result, hadError, nil
}
// --- Per-match emit helpers -----------------------------------------
func (e *CSharpExtractor) emitNamespace(m parser.QueryResult, filePath, fileID string, result *parser.ExtractionResult, seen map[string]bool) {
name := m.Captures["ns.name"].Text
def := m.Captures["ns.def"]
id := filePath + "::" + name
if seen[id] {
return
}
seen[id] = true
result.Nodes = append(result.Nodes, &graph.Node{
ID: id, Kind: graph.KindPackage, Name: name,
FilePath: filePath, StartLine: def.StartLine + 1, EndLine: def.EndLine + 1,
Language: "csharp",
})
result.Edges = append(result.Edges, &graph.Edge{
From: fileID, To: id, Kind: graph.EdgeDefines, FilePath: filePath, Line: def.StartLine + 1,
})
}
// emitContainer collapses the per-kind class/interface/struct/enum
// node emission. The capture-name prefix selects which capture set to
// read from (the legacy code repeated this body four times).
func (e *CSharpExtractor) emitContainer(m parser.QueryResult, kind string, nodeKind graph.NodeKind, filePath, fileID string, src []byte, result *parser.ExtractionResult, seen, annotationSeen map[string]bool, localInterfaces map[string]bool) {
name := m.Captures[kind+".name"].Text
def := m.Captures[kind+".def"]
id := filePath + "::" + name
if seen[id] {
return
}
seen[id] = true
meta := map[string]any{"visibility": csharpVisibility(def.Node, src, VisibilityInternal)}
// A struct is a value type; record struct too. Surfacing it lets a
// consumer reason about copy-vs-reference semantics.
if kind == "struct" {
meta["value_type"] = true
}
// Namespace scope so a type in `namespace App.Core` is attributable
// without re-deriving its enclosing namespace from source.
if ns := csharpEnclosingNamespace(def.Node, src); ns != "" {
meta["scope_ns"] = ns
}
if doc := extractCSharpDoc(src, def.StartLine); doc != "" {
meta["doc"] = doc
}
result.Nodes = append(result.Nodes, &graph.Node{
ID: id, Kind: nodeKind, Name: name,
FilePath: filePath, StartLine: def.StartLine + 1, EndLine: def.EndLine + 1,
Language: "csharp",
Meta: meta,
})
result.Edges = append(result.Edges, &graph.Edge{
From: fileID, To: id, Kind: graph.EdgeDefines, FilePath: filePath, Line: def.StartLine + 1,
})
emitCSharpAnnotationEdges(csharpCollectAttributes(def.Node, src), id, filePath, result, annotationSeen)
emitCSharpGenericParamNodes(id, def.Node, src, filePath, def.StartLine+1, result)
// Only classes, structs, and records carry a base class / interface
// list that splits into EdgeExtends + EdgeImplements. Structs and
// `record struct` declarations have no base class — every base is an
// interface — which emitCSharpBaseList infers from the declaration.
switch kind {
case "class", "struct", "record":
emitCSharpBaseList(id, def.Node, src, filePath, localInterfaces, result)
case "enum":
e.emitCSharpEnumMembers(def.Node, src, filePath, id, name, result, seen)
}
}
// emitCSharpEnumMembers emits one KindEnumMember per `enum_member_declaration`
// in an enum body, with its explicit value (when given) and a MemberOf edge to
// the enum — so an enum's members are navigable symbols, not lost in the type.
func (e *CSharpExtractor) emitCSharpEnumMembers(enumNode *sitter.Node, src []byte, filePath, enumID, enumName string, result *parser.ExtractionResult, seen map[string]bool) {
var list *sitter.Node
for i := 0; i < int(enumNode.ChildCount()); i++ {
if c := enumNode.Child(i); c != nil && c.Type() == "enum_member_declaration_list" {
list = c
break
}
}
if list == nil {
return
}
for i := 0; i < int(list.NamedChildCount()); i++ {
mem := list.NamedChild(i)
if mem.Type() != "enum_member_declaration" {
continue
}
var nameNode, valNode *sitter.Node
if nn := mem.ChildByFieldName("name"); nn != nil {
nameNode = nn
}
for j := 0; j < int(mem.NamedChildCount()); j++ {
c := mem.NamedChild(j)
if c.Type() == "identifier" && nameNode == nil {
nameNode = c
} else if c != mem.ChildByFieldName("name") && c.Type() != "identifier" {
valNode = c
}
}
if nameNode == nil {
continue
}
mname := nameNode.Content(src)
line := int(mem.StartPoint().Row) + 1
id, ok := disambiguateID(seen, filePath+"::"+enumName+"."+mname, line)
if !ok {
continue
}
emeta := map[string]any{"enum": enumID, "receiver": enumName}
if valNode != nil {
emeta["value"] = strings.TrimSpace(valNode.Content(src))
}
result.Nodes = append(result.Nodes, &graph.Node{
ID: id, Kind: graph.KindEnumMember, Name: mname,
FilePath: filePath, StartLine: line, EndLine: line, Language: "csharp", Meta: emeta,
})
result.Edges = append(result.Edges, &graph.Edge{
From: id, To: enumID, Kind: graph.EdgeMemberOf, FilePath: filePath, Line: line,
})
}
}
// csharpHasModifier reports whether a declaration carries the given modifier
// keyword (const / static / async / readonly / …).
func csharpHasModifier(decl *sitter.Node, src []byte, mod string) bool {
if decl == nil {
return false
}
for i := 0; i < int(decl.ChildCount()); i++ {
c := decl.Child(i)
if c != nil && c.Type() == "modifier" && strings.TrimSpace(c.Content(src)) == mod {
return true
}
}
return false
}
// csharpEnclosingNamespace returns the dotted name of the nearest enclosing
// namespace declaration (block or file-scoped), or "".
func csharpEnclosingNamespace(node *sitter.Node, src []byte) string {
for n := node; n != nil; n = n.Parent() {
t := n.Type()
if t == "namespace_declaration" || t == "file_scoped_namespace_declaration" {
if nm := n.ChildByFieldName("name"); nm != nil {
return strings.TrimSpace(nm.Content(src))
}
for i := 0; i < int(n.NamedChildCount()); i++ {
c := n.NamedChild(i)
if c.Type() == "identifier" || c.Type() == "qualified_name" {
return strings.TrimSpace(c.Content(src))
}
}
}
}
return ""
}
// emitAnonymousType indexes a C# anonymous type — `new { Name = ..., Age = ... }`
// — as a synthetic KindType node with an EdgeExtends to object, its implicit
// base. C# anonymous types are nameless compiler-generated classes that derive
// directly from System.Object; surfacing each instantiation as a distinct type
// keeps the graph's type set complete and gives the projection a node to anchor
// to, rather than vanishing into the expression that produced it.
func (e *CSharpExtractor) emitAnonymousType(m parser.QueryResult, filePath, fileID string, result *parser.ExtractionResult, seen map[string]bool) {
def := m.Captures["anon.def"]
line := def.StartLine + 1
name := fmt.Sprintf("anon@%d", line)
id := filePath + "::" + name
if seen[id] {
return
}
seen[id] = true
result.Nodes = append(result.Nodes, &graph.Node{
ID: id, Kind: graph.KindType, Name: name,
FilePath: filePath, StartLine: line, EndLine: def.EndLine + 1,
Language: "csharp",
Meta: map[string]any{"anonymous": true},
})
result.Edges = append(result.Edges,
&graph.Edge{From: fileID, To: id, Kind: graph.EdgeDefines, FilePath: filePath, Line: line},
&graph.Edge{From: id, To: "unresolved::object", Kind: graph.EdgeExtends, FilePath: filePath, Line: line, Origin: graph.OriginASTInferred},
)
}
// csharpVisibility scans a declaration's modifier children for an
// access modifier. C# defaults are container-dependent — defaultVis is
// "internal" for top-level types and "private" for class members.
func csharpVisibility(decl *sitter.Node, src []byte, defaultVis string) string {
if decl == nil {
return defaultVis
}
for i := 0; i < int(decl.ChildCount()); i++ {
c := decl.Child(i)
if c == nil {
continue
}
if c.Type() != "modifier" {
continue
}
switch strings.TrimSpace(c.Content(src)) {
case "public":
return VisibilityPublic
case "private":
return VisibilityPrivate
case "protected":
return VisibilityProtected
case "internal":
return VisibilityInternal
}
}
return defaultVis
}
// csharpCollectAttributes walks a declaration's children for
// `attribute_list` nodes ([Attr1, Attr2(...)]) and returns each
// attribute's bare name plus verbatim args. Multiple attributes can
// appear inside one bracket pair, and multiple bracket pairs can
// stack on the same declaration.
func csharpCollectAttributes(decl *sitter.Node, src []byte) []javaAnnotation {
if decl == nil {
return nil
}
var out []javaAnnotation
for i := 0; i < int(decl.ChildCount()); i++ {
c := decl.Child(i)
if c == nil || c.Type() != "attribute_list" {
continue
}
for j := 0; j < int(c.ChildCount()); j++ {
a := c.Child(j)
if a == nil || a.Type() != "attribute" {
continue
}
var name, args string
line := int(a.StartPoint().Row) + 1
if nm := a.ChildByFieldName("name"); nm != nil {
name = nm.Content(src)
}
for k := 0; k < int(a.ChildCount()); k++ {
inner := a.Child(k)
if inner == nil {
continue
}
if inner.Type() == "attribute_argument_list" {
txt := inner.Content(src)
if len(txt) >= 2 && txt[0] == '(' && txt[len(txt)-1] == ')' {
txt = txt[1 : len(txt)-1]
}
args = txt
}
}
if name != "" {
out = append(out, javaAnnotation{name: name, args: args, line: line})
}
}
}
return out
}
func emitCSharpAnnotationEdges(anns []javaAnnotation, fromID, filePath string, result *parser.ExtractionResult, seen map[string]bool) {
for _, a := range anns {
if a.name == "" {
continue
}
EmitAnnotationEdge(fromID, "csharp", a.name, a.args, filePath, a.line, result, seen)
}
}
// extractCSharpDoc tries the XML-doc form first (/// <summary>…) and
// falls back to /** … */ block comments (less common in C# but valid).
func extractCSharpDoc(src []byte, startRow int) string {
if d := ExtractDocAbove(src, startRow, DocLangCSharpXML); d != "" {
return d
}
return ExtractDocAbove(src, startRow, DocLangBlockStar)
}
func (e *CSharpExtractor) emitMethod(m parser.QueryResult, filePath, fileID string, src []byte, result *parser.ExtractionResult, seen, annotationSeen map[string]bool, ifaceMethods map[string][]string) {
name := m.Captures["method.name"].Text
def := m.Captures["method.def"]
startLine1 := def.StartLine + 1
owner := csharpDirectMemberOwner(def.Node, src, "class_declaration", "struct_declaration", "interface_declaration")
if owner.kind == "" {
// Method outside a recognised container — legacy didn't emit
// these (its nested queries required class/struct/interface
// parentage), so skip.
return
}
// Interface methods: legacy only collected names; no graph node was
// emitted for them. Mirror that.
if owner.kind == "interface_declaration" {
ifaceMethods[owner.name] = append(ifaceMethods[owner.name], name)
return
}
id := filePath + "::" + owner.name + "." + name
if seen[id] {
id = filePath + "::" + owner.name + "." + name + "_L" + fmt.Sprint(startLine1)
}
if seen[id] {
return
}
seen[id] = true
meta := map[string]any{
"receiver": owner.name,
"visibility": csharpVisibility(def.Node, src, VisibilityPrivate),
}
if rt := extractCSharpMethodReturnType(def.Node, src, name); rt != "" {
meta["return_type"] = rt
}
if csharpHasModifier(def.Node, src, "async") {
meta["async"] = true
}
if csharpHasModifier(def.Node, src, "static") {
meta["static"] = true
}
if ns := csharpEnclosingNamespace(def.Node, src); ns != "" {
meta["scope_ns"] = ns
}
if doc := extractCSharpDoc(src, def.StartLine); doc != "" {
meta["doc"] = doc
}
result.Nodes = append(result.Nodes, &graph.Node{
ID: id, Kind: graph.KindMethod, Name: name,
FilePath: filePath, StartLine: startLine1, EndLine: def.EndLine + 1,
Language: "csharp",
Meta: meta,
})
result.Edges = append(result.Edges, &graph.Edge{
From: fileID, To: id, Kind: graph.EdgeDefines, FilePath: filePath, Line: startLine1,
})
ownerID := filePath + "::" + owner.name
result.Edges = append(result.Edges, &graph.Edge{
From: id, To: ownerID, Kind: graph.EdgeMemberOf, FilePath: filePath, Line: startLine1,
})
emitCSharpAnnotationEdges(csharpCollectAttributes(def.Node, src), id, filePath, result, annotationSeen)
if body := csharpFunctionBody(def.Node); body != nil {
emitCSharpAsyncSpawns(id, body, src, filePath, result)
}
emitCSharpFunctionShape(id, def.Node, src, filePath, startLine1, result)
}
func (e *CSharpExtractor) emitConstructor(m parser.QueryResult, filePath, fileID string, src []byte, result *parser.ExtractionResult, seen map[string]bool) {
def := m.Captures["ctor.def"]
startLine1 := def.StartLine + 1
owner := csharpDirectMemberOwner(def.Node, src, "class_declaration", "struct_declaration")
if owner.kind == "" {
return
}
id := filePath + "::" + owner.name + ".<init>"
if seen[id] {
id = filePath + "::" + owner.name + ".<init>_L" + fmt.Sprint(startLine1)
}
if seen[id] {
return
}
seen[id] = true
result.Nodes = append(result.Nodes, &graph.Node{
ID: id, Kind: graph.KindMethod, Name: owner.name + ".<init>",
FilePath: filePath, StartLine: startLine1, EndLine: def.EndLine + 1,
Language: "csharp",
Meta: map[string]any{"receiver": owner.name},
})
result.Edges = append(result.Edges, &graph.Edge{
From: fileID, To: id, Kind: graph.EdgeDefines, FilePath: filePath, Line: startLine1,
})
ownerID := filePath + "::" + owner.name
result.Edges = append(result.Edges, &graph.Edge{
From: id, To: ownerID, Kind: graph.EdgeMemberOf, FilePath: filePath, Line: startLine1,
})
// Constructor params: same shape as methods so DI containers and
// codegen tooling see the dependencies they need.
if body := csharpFunctionBody(def.Node); body != nil {
emitCSharpAsyncSpawns(id, body, src, filePath, result)
}
emitCSharpFunctionShape(id, def.Node, src, filePath, startLine1, result)
}
func (e *CSharpExtractor) emitField(m parser.QueryResult, filePath, fileID string, src []byte, result *parser.ExtractionResult, seen map[string]bool) {
def := m.Captures["field.def"]
owner := csharpDirectMemberOwner(def.Node, src, "class_declaration", "struct_declaration")
if owner.kind == "" {
return
}
name := m.Captures["field.name"].Text
id := filePath + "::" + owner.name + "." + name
if seen[id] {
return
}
seen[id] = true
meta := map[string]any{
"receiver": owner.name,
"visibility": csharpVisibility(def.Node, src, VisibilityPrivate),
}
if t := def.Node.ChildByFieldName("type"); t != nil {
meta["field_type"] = strings.TrimSpace(t.Content(src))
}
// A `const` field is a compile-time constant, not a mutable field —
// classify it as KindConstant so it joins the value-reference impact
// surface. `static` / `readonly` are stamped for completeness.
fieldKind := graph.KindField
if csharpHasModifier(def.Node, src, "const") {
fieldKind = graph.KindConstant
}
if csharpHasModifier(def.Node, src, "static") {
meta["static"] = true
}
if csharpHasModifier(def.Node, src, "readonly") {
meta["readonly"] = true
}
if doc := extractCSharpDoc(src, def.StartLine); doc != "" {
meta["doc"] = doc
}
result.Nodes = append(result.Nodes, &graph.Node{
ID: id, Kind: fieldKind, Name: name,
FilePath: filePath, StartLine: def.StartLine + 1, EndLine: def.EndLine + 1,
Language: "csharp",
Meta: meta,
})
result.Edges = append(result.Edges, &graph.Edge{
From: fileID, To: id, Kind: graph.EdgeDefines, FilePath: filePath, Line: def.StartLine + 1,
})
ownerID := filePath + "::" + owner.name
result.Edges = append(result.Edges, &graph.Edge{
From: id, To: ownerID, Kind: graph.EdgeMemberOf, FilePath: filePath, Line: def.StartLine + 1,
})
}
func (e *CSharpExtractor) emitProperty(m parser.QueryResult, filePath, fileID string, src []byte, result *parser.ExtractionResult, seen map[string]bool) {
def := m.Captures["prop.def"]
owner := csharpDirectMemberOwner(def.Node, src, "class_declaration", "struct_declaration")
if owner.kind == "" {
return
}
name := m.Captures["prop.name"].Text
id := filePath + "::" + owner.name + "." + name
if seen[id] {
return
}
seen[id] = true
meta := map[string]any{
"receiver": owner.name,
"visibility": csharpVisibility(def.Node, src, VisibilityPrivate),
"kind": "property",
}
if t := def.Node.ChildByFieldName("type"); t != nil {
meta["field_type"] = strings.TrimSpace(t.Content(src))
}
if doc := extractCSharpDoc(src, def.StartLine); doc != "" {
meta["doc"] = doc
}
result.Nodes = append(result.Nodes, &graph.Node{
ID: id, Kind: graph.KindField, Name: name,
FilePath: filePath, StartLine: def.StartLine + 1, EndLine: def.EndLine + 1,
Language: "csharp",
Meta: meta,
})
result.Edges = append(result.Edges, &graph.Edge{
From: fileID, To: id, Kind: graph.EdgeDefines, FilePath: filePath, Line: def.StartLine + 1,
})
ownerID := filePath + "::" + owner.name
result.Edges = append(result.Edges, &graph.Edge{
From: id, To: ownerID, Kind: graph.EdgeMemberOf, FilePath: filePath, Line: def.StartLine + 1,
})
}
func (e *CSharpExtractor) emitUsing(m parser.QueryResult, filePath, fileID string, result *parser.ExtractionResult) {
path := m.Captures["using.path"]
importPath := strings.ReplaceAll(path.Text, ".", "/")
result.Edges = append(result.Edges, &graph.Edge{
From: fileID, To: "unresolved::import::" + importPath,
Kind: graph.EdgeImports, FilePath: filePath, Line: path.StartLine + 1,
})
}
// --- Helpers --------------------------------------------------------
type csharpOwner struct {
kind string // class_declaration / struct_declaration / interface_declaration
name string
}
// csharpDirectMemberOwner mirrors the legacy nested queries: the
// member must be a direct child of the container's declaration_list.
// Returns kind == "" when the member isn't directly inside one of the
// allowed container kinds (skipping nested types, top-level statements,
// etc. — none of which the legacy extractor handled).
func csharpDirectMemberOwner(member *sitter.Node, src []byte, allowed ...string) csharpOwner {
if member == nil {
return csharpOwner{}
}
parent := member.Parent()
if parent == nil || parent.Type() != "declaration_list" {
return csharpOwner{}
}
grand := parent.Parent()
if grand == nil {
return csharpOwner{}
}
gtype := grand.Type()
for _, a := range allowed {
if gtype == a {
nameNode := grand.ChildByFieldName("name")
if nameNode == nil {
return csharpOwner{}
}
return csharpOwner{kind: gtype, name: nameNode.Content(src)}
}
}
return csharpOwner{}
}
// collectCSharpInterfaceNames walks the tree for every
// interface_declaration and records its bare name. The base-list
// heuristic consults this set first: a base type that names a
// locally-declared interface is unambiguously an interface, regardless
// of whether its name follows the `I`-prefix convention.
func collectCSharpInterfaceNames(root *sitter.Node, src []byte) map[string]bool {
names := make(map[string]bool)
walkNodes(root, func(n *sitter.Node) {
if n.Type() != "interface_declaration" {
return
}
if nameNode := n.ChildByFieldName("name"); nameNode != nil {
names[nameNode.Content(src)] = true
}
})
return names
}
// emitCSharpBaseList splits a class/struct/record base list into
// EdgeExtends (the superclass) and EdgeImplements (the interfaces).
//
// C# lists the optional base class and any implemented interfaces in a
// single comma-separated base_list, and — unlike Go or Java — the
// grammar does not tag which entry is the class. When a base type is
// defined elsewhere (another compilation unit) the extractor cannot
// resolve its kind, so it discriminates with a heuristic:
//
// 1. A base whose name matches a locally-declared interface (the
// prescan set) is definitively an interface → EdgeImplements.
// 2. Otherwise a base whose name matches the `I`-prefix convention
// (^I[A-Z], generics stripped first so IList<T> → IList) is treated
// as an interface → EdgeImplements.
// 3. The first base that is neither is the superclass → EdgeExtends.
// C# allows at most one base class and it must come first; every
// base after it is an interface. Structs and `record struct`
// declarations have no base class, so all of their bases are
// interfaces regardless of position.
//
// All edges ride at OriginASTInferred: the discrimination is a
// heuristic, not a type-checked fact. Targets are left unresolved so
// the resolver binds them like every other C# reference. A base that
// resolves to a same-file class still flows through unchanged — it is
// neither a known interface nor I-prefixed, so it lands as EdgeExtends.
func emitCSharpBaseList(typeID string, decl *sitter.Node, src []byte, filePath string, localInterfaces map[string]bool, result *parser.ExtractionResult) {
if decl == nil {
return
}
baseList := decl.ChildByFieldName("bases")
if baseList == nil {
// `bases` is not a named field in every grammar revision; fall
// back to a direct child scan for the base_list node.
for i := 0; i < int(decl.ChildCount()); i++ {
c := decl.Child(i)
if c != nil && c.Type() == "base_list" {
baseList = c
break
}
}
}
if baseList == nil {
return
}
// Structs and `record struct` cannot derive from a base class — the
// CLR forbids it — so every entry in their base list is an interface
// and the "first non-interface is the superclass" branch never runs.
allowsBaseClass := csharpDeclAllowsBaseClass(decl)
extendsTaken := false
for i := 0; i < int(baseList.NamedChildCount()); i++ {
entry := baseList.NamedChild(i)
if entry == nil {
continue
}
name, isCtorBase := csharpBaseTypeName(entry, src)
if name == "" {
continue
}
line := int(entry.StartPoint().Row) + 1
// A primary_constructor_base_type (`: Base(args)`) invokes a base
// constructor, which is only valid for a base class — it is never
// an interface.
isInterface := !isCtorBase &&
(localInterfaces[name] || csharpInterfaceNamePattern.MatchString(name))
kind := graph.EdgeImplements
if !isInterface && allowsBaseClass && !extendsTaken {
kind = graph.EdgeExtends
extendsTaken = true
}
result.Edges = append(result.Edges, &graph.Edge{
From: typeID, To: "unresolved::" + name,
Kind: kind, FilePath: filePath, Line: line,
Origin: graph.OriginASTInferred,
})
}
}
// csharpDeclAllowsBaseClass reports whether a class/struct/record
// declaration can have a base class. Structs never can; a record is a
// struct when its declaration carries the `struct` keyword
// (`record struct`), otherwise it is a reference type that can extend a
// base record/class.
func csharpDeclAllowsBaseClass(decl *sitter.Node) bool {
switch decl.Type() {
case "struct_declaration":
return false
case "record_declaration":
for i := 0; i < int(decl.ChildCount()); i++ {
if c := decl.Child(i); c != nil && c.Type() == "struct" {
return false
}
}
return true
default:
return true
}
}
// csharpBaseTypeName extracts the bare type name from a single base_list
// entry, stripping generic arguments and namespace qualification so the
// `I`-prefix test sees IList rather than IList<int> or System.IList. The
// bool return reports whether the entry is a primary_constructor_base_type