-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathcsharp.go
More file actions
2304 lines (2179 loc) · 79.5 KB
/
Copy pathcsharp.go
File metadata and controls
2304 lines (2179 loc) · 79.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"
"math"
"regexp"
"sort"
"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
; An invocation that spells explicit type arguments parses its callee
; name as a generic_name, never a bare identifier — so pinning the name
; to (identifier) dropped every generic call site outright, with no edge
; and no unresolved stub. That is the dominant .NET call shape
; (GetRequiredService<T>(), AddSingleton<TI, TImpl>()), and it left
; heavily-called methods looking like dead code. Each alternation
; captures the inner identifier, so the callee name stays bare.
(invocation_expression
function: [
(identifier) @call.name
(generic_name (identifier) @call.name)
]) @call.expr
(invocation_expression
function: (member_access_expression
expression: (_) @callm.receiver
name: [
(identifier) @callm.method
(generic_name (identifier) @callm.method)
])) @callm.expr
(invocation_expression
function: (conditional_access_expression
condition: (_) @callm.receiver
(member_binding_expression
name: [
(identifier) @callm.method
(generic_name (identifier) @callm.method)
]))) @callm.expr
(invocation_expression
function: (conditional_access_expression
"this"
(member_binding_expression
name: [
(identifier) @callself.method
(generic_name (identifier) @callself.method)
]))) @callself.expr
(invocation_expression
function: (conditional_access_expression
"base"
(member_binding_expression
name: [
(identifier) @callbase.method
(generic_name (identifier) @callbase.method)
]))) @callbase.expr
(invocation_expression
function: (member_access_expression
"this"
name: [
(identifier) @callself.method
(generic_name (identifier) @callself.method)
])) @callself.expr
(invocation_expression
function: (member_access_expression
"base"
name: [
(identifier) @callbase.method
(generic_name (identifier) @callbase.method)
])) @callbase.expr
(local_declaration_statement
(variable_declaration
type: (_) @lvar.type
(variable_declarator
(identifier) @lvar.name))) @lvar.def
(member_access_expression
name: [
(identifier) @maccess.name
(generic_name (identifier) @maccess.name)
]) @maccess.expr
(conditional_access_expression
(member_binding_expression
name: [
(identifier) @maccess.condname
(generic_name (identifier) @maccess.condname)
])) @maccess.condexpr
]
`
// 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
// recvType is the receiver type a `this.`/`base.` qualifier names —
// resolved at capture time from the enclosing declaration, since the
// keyword itself never appears in any tenv.
recvType 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
// argCount / typeArgCount are the call's applicability evidence:
// how many arguments it passes and how many type arguments it
// spells explicitly. Their *Known flags keep "no evidence"
// distinguishable from a genuine zero — narrowing an overload set
// on a count we never measured would be a guess, not a rule.
argCount int
argKnown bool
typeArgCount int
typeArgKnown bool
}
// withCSharpCallArity records the applicability counts an invocation
// node carries, so every capture site stamps the same evidence.
func withCSharpCallArity(c csharpDeferredCall, inv *sitter.Node) csharpDeferredCall {
c.argCount, c.argKnown = csharpCallArgCount(inv)
c.typeArgCount, c.typeArgKnown = csharpCallTypeArgCount(inv)
return c
}
// 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
}
// csharpTypeUse buffers a type referenced only in a local-variable
// annotation (`HttpResponse resp = Get();`) so the post-pass can emit an
// EdgeTypedAs from the enclosing function once funcRanges are built.
// Field / property annotations emit their edge inline from the member
// node, so they don't ride this buffer.
type csharpTypeUse struct {
typeText string
line int
}
// 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)
stampCSharpUsings(root, src, 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
var typeUses []csharpTypeUse
var accesses []csharpDeferredAccess
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, withCSharpCallArity(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),
}, expr.Node))
case m.Captures["callself.expr"] != nil:
expr := m.Captures["callself.expr"]
calls = append(calls, withCSharpCallArity(csharpDeferredCall{
name: m.Captures["callself.method"].Text,
receiver: "this",
recvType: csharpQualifiedReceiverType(expr.Node, src, "this"),
line: expr.StartLine + 1,
isMember: true,
returnUsage: classifyReturnUsage(expr.Node, src, csharpReturnUsageSpec),
}, expr.Node))
case m.Captures["callbase.expr"] != nil:
expr := m.Captures["callbase.expr"]
calls = append(calls, withCSharpCallArity(csharpDeferredCall{
name: m.Captures["callbase.method"].Text,
receiver: "base",
recvType: csharpQualifiedReceiverType(expr.Node, src, "base"),
line: expr.StartLine + 1,
isMember: true,
returnUsage: classifyReturnUsage(expr.Node, src, csharpReturnUsageSpec),
}, expr.Node))
// A receiverless call carries no applicability stamps: nothing
// resolves it through the extension binder, and the scope rules
// that do bind it never consult arity.
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["maccess.expr"] != nil:
accesses = append(accesses, csharpDeferredAccess{
name: m.Captures["maccess.name"].Text,
node: m.Captures["maccess.expr"].Node,
line: m.Captures["maccess.expr"].StartLine + 1,
})
case m.Captures["maccess.condexpr"] != nil:
accesses = append(accesses, csharpDeferredAccess{
name: m.Captures["maccess.condname"].Text,
node: m.Captures["maccess.condexpr"].Node,
line: m.Captures["maccess.condexpr"].StartLine + 1,
conditional: true,
})
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,
})
// Buffer the annotated type so the post-pass (once
// funcRanges exist) can attribute an EdgeTypedAs to the
// enclosing function — a type used only in a local
// annotation seeds tenv but otherwise emits no reference,
// so find_usages would miss it without an LSP.
typeUses = append(typeUses, csharpTypeUse{
typeText: m.Captures["lvar.type"].Text,
line: m.Captures["lvar.type"].StartLine + 1,
})
}
})
// 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
}
}
// Resolve calls against the function-range lookup + the per-method
// type environments. Owner attribution runs once per local, call and
// type use — the sorted lookup keeps that from multiplying into an
// O(locals×functions) linear-scan product on member-heavy files.
funcRanges := newCSharpFuncLookup(buildFuncRanges(result))
// Build type environments in legacy precedence, scoped per enclosing
// method — a same-named local of a different type in a sibling method
// must not bleed into this method's receiver stamps (a file-scoped
// last-wins map mis-typed the receiver and both the extension binder
// and the receiver gate act on that evidence):
// Tier 0 — explicit type annotations (skip "var" placeholder)
// Tier 1 — `var x = new Foo()` walk for `var`-keyed locals only
// Tier 2 — `var x = await LoadAsync()` walk → the awaited Task<T>'s T
localOwner := func(l csharpDeferredLocal) string {
if l.defNode == nil {
return ""
}
return funcRanges.enclosing(int(l.defNode.StartPoint().Row) + 1)
}
tenvByOwner := map[string]typeEnv{}
setLocalType := func(owner, name, typeName string) {
env := tenvByOwner[owner]
if env == nil {
env = make(typeEnv)
tenvByOwner[owner] = env
}
env[name] = typeName
}
for _, l := range locals {
owner := localOwner(l)
if owner == "" {
continue
}
typeName := normalizeCSharpTypeName(l.rawType)
if typeName != "" && typeName != "var" {
setLocalType(owner, l.name, typeName)
}
}
for _, l := range locals {
owner := localOwner(l)
if owner == "" || l.rawType != "var" || l.defNode == nil {
continue
}
if _, exists := tenvByOwner[owner][l.name]; exists {
continue
}
// First creation in document order = the outermost one; a
// nested `new` inside a collection/object initializer must
// not override it.
done := false
walkNodes(l.defNode, func(n *sitter.Node) {
if !done && n.Type() == "object_creation_expression" {
typeName := inferTypeFromCSharpNew(n, src)
if typeName != "" {
setLocalType(owner, l.name, typeName)
done = true
}
}
})
}
// Tier 2 — `var x = await LoadAsync()` walk: no object_creation ever
// appears; the local's type is the T inside the awaited call's Task<T>,
// reachable through the called method's declared return shape.
for _, l := range locals {
owner := localOwner(l)
if owner == "" || l.rawType != "var" || l.defNode == nil {
continue
}
if _, exists := tenvByOwner[owner][l.name]; exists {
continue
}
done := false
walkNodes(l.defNode, func(n *sitter.Node) {
if done || n.Type() != "await_expression" {
return
}
done = true
// The initializer must BE the await (parens aside): in
// `var w = (await Load()).Weigh()` the local holds Weigh's
// return, and stamping the awaited T would hand the
// resolver a confident wrong answer.
for p := n.Parent(); p != nil; p = p.Parent() {
switch p.Type() {
case "parenthesized_expression":
continue
case "equals_value_clause", "variable_declarator":
// direct initializer — accept
default:
return // nested inside a longer expression
}
break
}
inner := n.NamedChild(0)
if inner == nil {
return
}
if t := csharpAwaitedCallType(inner.Content(src), csharpOwnerTypeName(owner), tenvByOwner[owner], result); t != "" {
setLocalType(owner, l.name, t)
}
})
}
// Type SHAPE rides in a parallel per-method map: the core stamps keep
// their bare spelling (every downstream consumer stays valid), while
// array/nullable suffixes and generic arguments — which are part of
// applicability — survive in a receiver_shape stamp.
shapesByOwner := map[string]map[string]string{}
setLocalShape := func(owner, name, shape string) {
m := shapesByOwner[owner]
if m == nil {
m = map[string]string{}
shapesByOwner[owner] = m
}
m[name] = shape
}
for _, l := range locals {
owner := localOwner(l)
if owner == "" {
continue
}
if _, exists := shapesByOwner[owner][l.name]; exists {
continue
}
if shape := csharpCanonTypeShape(l.rawType); shape != "" {
setLocalShape(owner, l.name, shape)
} else if l.rawType == "var" && l.defNode != nil {
// Same first-creation rule as the type walk above — the
// two stamps must describe the same creation expression.
done := false
walkNodes(l.defNode, func(n *sitter.Node) {
if !done && n.Type() == "object_creation_expression" {
if tn := n.ChildByFieldName("type"); tn != nil {
if s := csharpCanonTypeShape(tn.Content(src)); s != "" {
setLocalShape(owner, l.name, s)
done = true
}
}
}
})
}
}
// Builtin locals key per enclosing method: a same-named local of a
// different type in a sibling method must not bleed into this
// method's receiver stamp (a file-scoped last-wins map mis-typed
// the receiver and the extension binder would act on it).
builtinsByOwner := map[string]map[string]string{}
for _, l := range locals {
if l.defNode == nil {
continue
}
bt := csharpBuiltinTypeName(l.rawType)
if bt == "" {
continue
}
owner := funcRanges.enclosing(int(l.defNode.StartPoint().Row) + 1)
if owner == "" {
continue
}
m := builtinsByOwner[owner]
if m == nil {
m = map[string]string{}
builtinsByOwner[owner] = m
}
m[l.name] = bt
}
// Local-variable type annotations → EdgeTypedAs from the enclosing
// function (file node as fallback). Mirrors the parameter/return
// type-use emission so a type referenced only in a local body
// declaration is still a navigable reference without an LSP.
for _, tu := range typeUses {
ownerID := funcRanges.enclosing(tu.line)
if ownerID == "" {
ownerID = fileID
}
emitCSharpTypeUseEdges(ownerID, tu.typeText, filePath, tu.line, result)
}
// Expression-site type references the symbol/annotation walk misses:
// instantiation (`new Foo()`), casts / type-tests (`(Foo)x`, `x is Foo`,
// `x as Foo`), static / const access (`Foo.Empty`, `typeof(Foo)`,
// `nameof(Foo)`), and attribute type names (`[Foo]`). Inheritance is
// already covered by emitCSharpBaseList, so it is not re-emitted here.
emitCSharpReferenceForms(root, src, filePath, fileID, result)
for _, c := range calls {
callerID := funcRanges.enclosing(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 c.recvType != "" {
// this./base.-qualified: the receiver type came from the
// enclosing declaration, not from any variable lookup.
edge.Meta = map[string]any{"receiver_type": c.recvType}
} else if recvType, ok := tenvByOwner[callerID][c.receiver]; ok {
edge.Meta = map[string]any{"receiver_type": recvType}
if shape := shapesByOwner[callerID][c.receiver]; shape != "" && shape != recvType {
edge.Meta["receiver_shape"] = shape
}
} else if bt := builtinsByOwner[callerID][c.receiver]; bt != "" {
// Builtins stay out of receiver_type (the receiver-gate
// passes key on user types); extension eligibility still
// needs them — `n.Foo()` on an int must match
// `Foo(this int)` and refuse `Foo(this string)`.
edge.Meta = map[string]any{"receiver_builtin": bt}
if shape := shapesByOwner[callerID][c.receiver]; shape != "" && shape != bt {
edge.Meta["receiver_shape"] = shape
}
} else if inner := csharpAwaitedReceiver(c.receiver); inner != "" {
// `(await LoadAsync()).X()` — the chain walker collapses a
// fully-parenthesized receiver to nothing; the receiver is
// the T inside the awaited call's Task<T>.
if t := csharpAwaitedCallType(inner, csharpOwnerTypeName(callerID), tenvByOwner[callerID], result); t != "" {
edge.Meta = map[string]any{"receiver_type": t}
}
} else if strings.Contains(c.receiver, ".") || strings.Contains(c.receiver, "(") {
stampFactoryChainReceiver(edge, c.receiver, resolveChainType(c.receiver, tenvByOwner[callerID], result))
if edge.Meta == nil && !strings.Contains(c.receiver, "(") {
// A namespace-qualified receiver the chain walker could
// not type (`Lib.BagExt.Add(bag)`). That is the same
// static-form evidence as the bare spelling below —
// without it the binder reads the call as extension
// form, discounts a `this` slot the argument list never
// filled, and lands on the wrong overload.
edge.Meta = map[string]any{"receiver_name": c.receiver}
}
} else if c.receiver != "" {
// A bare receiver nothing above could type. Its spelling
// is still evidence: reaching here means no local, param
// or builtin in scope carries that name, so a receiver
// that names a static class is the STATIC form of an
// extension call (`BagExt.Add(bag)`) — where the `this`
// slot is filled by the first argument, not the
// receiver. The extension binder needs that distinction
// before it can compare argument counts.
edge.Meta = map[string]any{"receiver_name": c.receiver}
}
// Eviction restubs a member call to a bare unresolved name; the
// marker is what lets the resolver still route the rebind through
// the extension rule instead of a locality guess.
if edge.Meta == nil {
edge.Meta = map[string]any{}
}
edge.Meta["member_call"] = true
// Applicability evidence for the overload set behind this
// name. Member calls carry it because they are the shape
// the extension binder resolves; a plain `Foo()` is already
// bound by scope rules that never consult arity.
if c.argKnown {
edge.Meta["arg_count"] = c.argCount
}
if c.typeArgKnown {
edge.Meta["type_arg_count"] = c.typeArgCount
}
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)
}
// Member accesses ride the same deferred machinery as calls — the
// receiver-typing ladder needs the finished tenv.
emitCSharpMemberAccesses(accesses, src, filePath, funcRanges,
tenvByOwner, builtinsByOwner, result)
// .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)
captureMediatRDispatch(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
}
// Structural flavor, keyed off the capture that funnelled in here.
switch kind {
case "iface":
meta["type_flavor"] = "interface"
case "struct":
meta["type_flavor"] = "struct"
case "enum":
meta["type_flavor"] = "enum"
case "record":
meta["type_flavor"] = "record"
default:
meta["type_flavor"] = "class"
}
// 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)
// Classes, structs, records, and interfaces carry a base list;
// emitCSharpBaseList derives each entry's edge kind from the
// declaration (base class vs interface for classes, all-interface
// for structs and records, inheritance for interfaces).
switch kind {
case "class", "struct", "record", "iface":
emitCSharpBaseList(id, def.Node, src, filePath, localInterfaces, result)
case "enum":
e.emitCSharpEnumMembers(def.Node, src, filePath, id, name, result, seen)
}
if kind == "record" {
e.emitCSharpRecordPositionalProps(id, name, def.Node, src, filePath, fileID, result, seen)
}
}
// emitCSharpRecordPositionalProps fabricates property member nodes for a
// record's positional parameters — `record Medal(int Id, string Motto)`
// synthesizes public properties Id and Motto with no declaration node
// for the member walk to find, so the parameter list is the only source.
// Runs at container emission, which precedes the body's member matches
// in tree order: an explicit redeclaration of a positional property
// (legal C# — it replaces the synthesized one) hits the seen guard and
// stays a single node for the same logical member.
func (e *CSharpExtractor) emitCSharpRecordPositionalProps(ownerID, ownerName string, decl *sitter.Node, src []byte, filePath, fileID string, result *parser.ExtractionResult, seen map[string]bool) {
// The record's parameter_list is an unnamed child in this grammar —
// unlike method parameters, ChildByFieldName("parameters") finds
// nothing, so scan the direct children by type.
var params *sitter.Node
for i, _nc := 0, int(decl.NamedChildCount()); i < _nc; i++ {
if c := decl.NamedChild(i); c != nil && c.Type() == "parameter_list" {
params = c
break
}
}
if params == nil {
return
}
for i, _nc := 0, int(params.NamedChildCount()); i < _nc; i++ {
p := params.NamedChild(i)
if p == nil || p.Type() != "parameter" {
continue
}
nameNode := p.ChildByFieldName("name")
if nameNode == nil {
continue
}
pname := nameNode.Content(src)
id := filePath + "::" + ownerName + "." + pname
if seen[id] {
continue
}
seen[id] = true
line := int(p.StartPoint().Row) + 1
meta := map[string]any{
"receiver": ownerName,
"visibility": VisibilityPublic,
"kind": "property",
"positional": true,
}
if t := p.ChildByFieldName("type"); t != nil {
meta["field_type"] = strings.TrimSpace(t.Content(src))
}
result.Nodes = append(result.Nodes, &graph.Node{
ID: id, Kind: graph.KindField, Name: pname,
FilePath: filePath, StartLine: line, EndLine: line,
Language: "csharp",
Meta: meta,
})
result.Edges = append(result.Edges,
&graph.Edge{From: fileID, To: id, Kind: graph.EdgeDefines, FilePath: filePath, Line: line},
&graph.Edge{From: id, To: ownerID, Kind: graph.EdgeMemberOf, FilePath: filePath, Line: line})
}
}
// 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, _nc := 0, int(enumNode.ChildCount()); i < _nc; i++ {
if c := enumNode.Child(i); c != nil && c.Type() == "enum_member_declaration_list" {
list = c
break
}
}
if list == nil {
return
}
for i, _nc := 0, int(list.NamedChildCount()); i < _nc; 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, _nc := 0, int(mem.NamedChildCount()); j < _nc; 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, _nc := 0, int(decl.ChildCount()); i < _nc; i++ {
c := decl.Child(i)
if c != nil && c.Type() == "modifier" && strings.TrimSpace(c.Content(src)) == mod {
return true
}
}
return false
}
// csharpExtensionReceiverType returns the generics- and namespace-stripped
// type of a method's first parameter when that parameter carries the `this`
// modifier — the receiver type of a C# extension method (`static int Foo(this
// string s)` → "string"). Returns "" for a non-extension method. Unlike
// normalizeCSharpTypeName it keeps primitive receivers (string / int), since
// extension methods commonly extend them.
func csharpExtensionReceiverType(methodNode *sitter.Node, src []byte) string {
if t := csharpExtensionReceiverTypeNode(methodNode, src); t != nil {
return normalizeCSharpBaseName(t.Content(src))
}
return ""
}
// csharpExtensionReceiverRaw returns the this-param's type as written —
// qualification, generic arguments, and array/nullable suffixes intact.
// "" for a non-extension method.
func csharpExtensionReceiverRaw(methodNode *sitter.Node, src []byte) string {
if t := csharpExtensionReceiverTypeNode(methodNode, src); t != nil {
return t.Content(src)
}
return ""
}
// csharpExtensionReceiverTypeNode finds the type node of a method's
// `this`-marked first parameter — nil for a non-extension method.
func csharpExtensionReceiverTypeNode(methodNode *sitter.Node, src []byte) *sitter.Node {
if methodNode == nil {
return nil
}
params := methodNode.ChildByFieldName("parameters")
if params == nil {
return nil
}
var first *sitter.Node
for i, _nc := 0, int(params.NamedChildCount()); i < _nc; i++ {
c := params.NamedChild(i)
if c != nil && c.Type() == "parameter" {
first = c
break
}
}
if first == nil {
return nil
}
hasThis := false
for i, _nc := 0, int(first.ChildCount()); i < _nc; i++ {
c := first.Child(i)
if c == nil {
continue