-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathjava_ast.go
More file actions
1143 lines (1054 loc) · 35.7 KB
/
Copy pathjava_ast.go
File metadata and controls
1143 lines (1054 loc) · 35.7 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 javaextractor
import (
"path/filepath"
"strings"
"github.com/enola-labs/enola/internal/facts"
sitter "github.com/tree-sitter/go-tree-sitter"
java "github.com/tree-sitter/tree-sitter-java/bindings/go"
)
// extractFileAST parses a single Java file with tree-sitter and emits architectural
// facts: declaration symbols (classes, interfaces, enums, records, methods, fields),
// import dependencies, and call-graph relations (RelImplements, RelInstantiates,
// RelInjects, RelCalls).
//
// Relation targets for type references (implements/instantiates/injects) are emitted
// as fully-qualified names — resolved through the file's import map, or assumed to be
// same-package when no import matches. java.go's canonicalizeTargets rewrites those
// FQNs to canonical "<dir>.<Type>" fact names once every file has been indexed.
func extractFileAST(src []byte, relFile string) []facts.Fact {
parser := sitter.NewParser()
defer parser.Close()
if err := parser.SetLanguage(sitter.NewLanguage(java.Language())); err != nil {
return nil
}
tree := parser.Parse(src, nil)
if tree == nil {
return nil
}
defer tree.Close()
w := &astWalker{
src: src,
relFile: relFile,
dir: filepath.Dir(relFile),
importMap: make(map[string]string),
}
root := tree.RootNode()
w.pkg = w.findPackage(root)
w.walkProgram(root)
return w.out
}
type astWalker struct {
src []byte
relFile string
dir string
pkg string // dotted package name, e.g. "com.example.auth" ("" if none)
out []facts.Fact
// importMap maps an imported simple type name to its fully-qualified name
// (e.g. "Store" -> "com.example.data.Store"). Used to resolve bare type
// references in supertypes, constructor calls, and injected parameters.
importMap map[string]string
// typeStack holds the simple names of the enclosing type declarations, so a
// method declared in class Foo is named "<dir>.Foo.method". methodStack is
// parallel and holds the method-name set of each enclosing type, used to
// resolve same-class bare calls.
typeStack []string
methodStack []map[string]bool
// ownerStack[len-1] is the symbol fact currently being built; call-graph edges
// discovered while walking its body attach to it.
ownerStack []*facts.Fact
// routeStack is parallel to typeStack: each entry carries the Spring route
// context (whether the enclosing type is a @Controller/@RestController and its
// class-level base path) so method handlers can emit route facts.
routeStack []routeScope
// Per-method complexity state, set up by handleMethod around walkForCalls and
// saved/restored across the re-entrant nested-type walk. metrics is nil outside
// a method body walk. loopDepth is the current loop nesting depth;
// selfName/selfShort are the enclosing method's full and short names (for
// direct-recursion detection).
metrics *javaBodyMetrics
loopDepth int
selfName string
selfShort string
// selfParams is the enclosing method's declared parameter count. A resolved
// self-call is only genuine recursion when its argument count matches — otherwise
// it is a call to a same-named overload, not recursion.
selfParams int
}
// javaBodyMetrics accumulates per-method complexity signals during the single
// walkForCalls body traversal — mirrors the other extractors.
type javaBodyMetrics struct {
loopDepth int // max loop nesting depth
loopCount int // number of loop constructs (syntactic + stream lambdas)
decisions int // decision points (cyclomatic = 1 + decisions)
callsInLoop []string // distinct call targets invoked at loop depth >= 1
inLoopSeen map[string]bool // dedup set for callsInLoop
recursive bool // body directly calls the enclosing method
sawSuperSelf bool // body calls super.<enclosingName>() (override delegation)
}
// javaIterators are Stream/Collection methods whose lambda argument runs once per
// element — i.e. a loop. A lambda passed to a method NOT in this set (Runnable,
// Comparator, a listener, a Supplier) is deferred and not treated as a loop.
var javaIterators = map[string]bool{
"forEach": true, "forEachOrdered": true, "map": true, "mapToInt": true,
"mapToLong": true, "mapToDouble": true, "mapToObj": true, "flatMap": true,
"filter": true, "reduce": true, "collect": true, "anyMatch": true,
"allMatch": true, "noneMatch": true, "peek": true, "sorted": true,
"removeIf": true, "replaceAll": true, "computeIfAbsent": true, "takeWhile": true,
"dropWhile": true,
}
// javaCheapMethods are obviously-cheap methods that are not I/O. Calls to these on
// an unknown receiver inside a loop are not recorded in calls_in_loop, keeping it
// focused (the enterprise keyword gate is the real precision filter).
var javaCheapMethods = map[string]bool{
"toString": true, "equals": true, "hashCode": true, "get": true, "set": true,
"add": true, "remove": true, "put": true, "contains": true, "size": true,
"isEmpty": true, "length": true, "name": true, "value": true, "builder": true,
"build": true, "stream": true, "iterator": true, "getClass": true, "valueOf": true,
"format": true, "append": true, "charAt": true, "substring": true, "trim": true,
"forEach": true, "map": true, "filter": true, "collect": true, "of": true,
}
// recordCallMetrics notes a resolved call target against the current method's
// complexity metrics: flags direct recursion and records calls made inside loops.
// argCount is the invocation's argument count; recursion is flagged only when it
// matches the enclosing method's parameter count, so a call to a same-named overload
// is not mistaken for self-recursion.
func (w *astWalker) recordCallMetrics(target string, argCount int) {
if w.metrics == nil || target == "" {
return
}
if (target == w.selfName || target == w.selfShort) && argCount == w.selfParams {
w.metrics.recursive = true
}
w.recordInLoop(target)
}
// javaArgCount returns the number of arguments of a method_invocation node.
func javaArgCount(node *sitter.Node) int {
args := node.ChildByFieldName("arguments")
if args == nil {
return 0
}
n := 0
for i := uint(0); i < uint(args.ChildCount()); i++ {
if args.Child(i).IsNamed() {
n++
}
}
return n
}
// javaParamCount returns the declared parameter count of a method declaration node.
func javaParamCount(node *sitter.Node) int {
params := node.ChildByFieldName("parameters")
if params == nil {
params = findChildByKind(node, "formal_parameters")
}
if params == nil {
return 0
}
n := 0
for i := uint(0); i < uint(params.ChildCount()); i++ {
switch params.Child(i).Kind() {
case "formal_parameter", "spread_parameter":
n++
}
}
return n
}
// recordInLoop adds a target to calls_in_loop (deduped) when inside a loop, without
// the recursion check — used for raw instance-method names.
func (w *astWalker) recordInLoop(target string) {
if w.metrics == nil || target == "" || w.loopDepth == 0 {
return
}
if w.metrics.inLoopSeen == nil {
w.metrics.inLoopSeen = make(map[string]bool)
}
if !w.metrics.inLoopSeen[target] {
w.metrics.inLoopSeen[target] = true
w.metrics.callsInLoop = append(w.metrics.callsInLoop, target)
}
}
func javaBooleanOp(node *sitter.Node) bool {
for i := uint(0); i < uint(node.ChildCount()); i++ {
switch node.Child(i).Kind() {
case "&&", "||":
return true
}
}
return false
}
func javaByteContains(outer, inner *sitter.Node) bool {
return inner.StartByte() >= outer.StartByte() && inner.EndByte() <= outer.EndByte()
}
// javaStreamLambda returns the lambda argument of a stream-iterator call
// (items.forEach(x -> …)), or nil if the call is not an iterator with a lambda.
func javaStreamLambda(call *sitter.Node, src []byte) *sitter.Node {
nameNode := call.ChildByFieldName("name")
if nameNode == nil || !javaIterators[nodeText(nameNode, src)] {
return nil
}
args := call.ChildByFieldName("arguments")
if args == nil {
return nil
}
for i := uint(0); i < uint(args.ChildCount()); i++ {
if c := args.Child(i); c.Kind() == "lambda_expression" {
return c
}
}
return nil
}
// walkJavaLambdaSubtree descends to a stream iterator's lambda and walks its BODY
// at +1 (it runs per element), while walking everything else (receiver, other args)
// at the current depth. Kind-checked so an ancestor with the same byte span isn't
// mistaken for the lambda.
func (w *astWalker) walkJavaLambdaSubtree(node, lambda *sitter.Node) {
if node == nil {
return
}
if node.Kind() == "lambda_expression" && node.StartByte() == lambda.StartByte() && node.EndByte() == lambda.EndByte() {
w.loopDepth++
for i := uint(0); i < uint(node.ChildCount()); i++ {
w.walkForCalls(node.Child(i))
}
w.loopDepth--
return
}
for i := uint(0); i < uint(node.ChildCount()); i++ {
if c := node.Child(i); javaByteContains(c, lambda) {
w.walkJavaLambdaSubtree(c, lambda)
} else {
w.walkForCalls(c)
}
}
}
type routeScope struct {
isController bool
isFeignClient bool
feignHint string
basePath string
}
func (w *astWalker) enclosingType() string { return strings.Join(w.typeStack, ".") }
func (w *astWalker) qualify(name string) string {
if t := w.enclosingType(); t != "" {
return t + "." + name
}
return name
}
func (w *astWalker) currentMethods() map[string]bool {
if len(w.methodStack) == 0 {
return nil
}
return w.methodStack[len(w.methodStack)-1]
}
func (w *astWalker) currentRoute() *routeScope {
if len(w.routeStack) == 0 {
return nil
}
return &w.routeStack[len(w.routeStack)-1]
}
func (w *astWalker) pushOwner(f *facts.Fact) { w.ownerStack = append(w.ownerStack, f) }
func (w *astWalker) popOwner() { w.ownerStack = w.ownerStack[:len(w.ownerStack)-1] }
func (w *astWalker) currentOwner() *facts.Fact {
if len(w.ownerStack) == 0 {
return nil
}
return w.ownerStack[len(w.ownerStack)-1]
}
// canonicalName is the "<dir>.<QualifiedType>" fact name of a declaration.
func (w *astWalker) canonicalName(qualified string) string { return w.dir + "." + qualified }
// fqn is the fully-qualified "<package>.<QualifiedType>" name of a declaration.
func (w *astWalker) fqn(qualified string) string {
if w.pkg == "" {
return qualified
}
return w.pkg + "." + qualified
}
func (w *astWalker) findPackage(root *sitter.Node) string {
if pd := findChildByKind(root, "package_declaration"); pd != nil {
// The package name is the scoped_identifier / identifier child.
for i := uint(0); i < uint(pd.ChildCount()); i++ {
c := pd.Child(i)
if c.Kind() == "scoped_identifier" || c.Kind() == "identifier" {
return nodeText(c, w.src)
}
}
}
return ""
}
func (w *astWalker) walkProgram(root *sitter.Node) {
for i := uint(0); i < uint(root.ChildCount()); i++ {
w.walkTopLevel(root.Child(i))
}
}
func (w *astWalker) walkTopLevel(node *sitter.Node) {
switch node.Kind() {
case "import_declaration":
w.handleImport(node)
case "class_declaration":
w.handleClassLike(node, facts.SymbolClass)
case "interface_declaration":
w.handleClassLike(node, facts.SymbolInterface)
case "enum_declaration":
w.handleClassLike(node, facts.SymbolEnum)
case "record_declaration":
w.handleClassLike(node, facts.SymbolClass)
case "annotation_type_declaration":
w.handleClassLike(node, facts.SymbolInterface)
}
}
func (w *astWalker) handleImport(node *sitter.Node) {
isStatic := false
isWildcard := false
var pathNode *sitter.Node
for i := uint(0); i < uint(node.ChildCount()); i++ {
c := node.Child(i)
switch c.Kind() {
case "static":
isStatic = true
case "asterisk":
isWildcard = true
case "scoped_identifier", "identifier":
pathNode = c
}
}
if pathNode == nil {
return
}
importPath := nodeText(pathNode, w.src)
props := map[string]any{
"language": "java",
"import": importPath,
"source": "external", // refined to "internal" in canonicalizeTargets
}
// Mark the import shape so resolveImport can apply the parent-FQN fallback to
// static-member / un-indexed-type imports but NOT to wildcards (whose import
// string is already the package — walking to the grandparent would mis-resolve).
if isStatic {
props["static"] = true
}
if isWildcard {
props["wildcard"] = true
}
w.out = append(w.out, facts.Fact{
Kind: facts.KindDependency,
Name: w.dir + " -> " + importPath,
File: w.relFile,
Line: int(node.StartPosition().Row) + 1,
Props: props,
Relations: []facts.Relation{
{Kind: facts.RelImports, Target: importPath},
},
})
// Record a non-static, non-wildcard import's simple name so bare type
// references resolve to its FQN. Static imports name a member, not a type;
// wildcard imports carry no simple name.
if isStatic || isWildcard {
return
}
simple := importPath
if i := strings.LastIndex(importPath, "."); i >= 0 {
simple = importPath[i+1:]
}
if simple != "" {
w.importMap[simple] = importPath
}
}
func (w *astWalker) handleClassLike(node *sitter.Node, kind string) {
nameNode := node.ChildByFieldName("name")
if nameNode == nil {
return
}
name := nodeText(nameNode, w.src)
modifiers := findChildByKind(node, "modifiers")
modifierText := ""
var annotations []javaAnnotation
if modifiers != nil {
modifierText = nodeText(modifiers, w.src)
annotations = parseAnnotations(modifiers, w.src)
}
// A top-level type is exported when public; nested types inherit visibility
// loosely — treat anything not explicitly private as part of the surface.
exported := strings.Contains(modifierText, "public") ||
(!strings.Contains(modifierText, "private") && len(w.typeStack) > 0)
f := facts.Fact{
Kind: facts.KindSymbol,
Name: w.canonicalName(w.qualify(name)),
File: w.relFile,
Line: int(node.StartPosition().Row) + 1,
Props: map[string]any{
"symbol_kind": kind,
"exported": exported,
"language": "java",
"fqn": w.fqn(w.qualify(name)),
},
Relations: []facts.Relation{
{Kind: facts.RelDeclares, Target: w.dir},
},
}
if strings.Contains(modifierText, "abstract") {
f.Props["abstract"] = true
}
if node.Kind() == "record_declaration" {
f.Props["record"] = true
}
if node.Kind() == "annotation_type_declaration" {
f.Props["annotation_class"] = true
}
// Inheritance: `extends` superclass + `implements`/`extends` interfaces.
for _, st := range w.supertypeTargets(node) {
f.Relations = append(f.Relations, facts.Relation{Kind: facts.RelImplements, Target: st})
}
// Framework classification (Spring component / JPA / Dubbo SPI) mutates props
// and may emit a companion storage fact.
classifyComponent(&f, name, annotations, w.supertypeSimpleNames(node))
if sf := detectJpaStorage(name, annotations, w.relFile, int(node.StartPosition().Row)+1, w.dir); sf != nil {
w.out = append(w.out, *sf)
}
w.out = append(w.out, f)
owner := &w.out[len(w.out)-1]
w.pushOwner(owner)
// Enter the type scope.
body := classBody(node)
w.typeStack = append(w.typeStack, name)
w.methodStack = append(w.methodStack, collectMethodNames(body, w.src))
w.routeStack = append(w.routeStack, routeScope{
isController: isSpringController(annotations),
isFeignClient: hasAnnotation(annotations, "FeignClient"),
feignHint: feignServiceHint(annotations),
basePath: requestMappingPath(annotations),
})
// Constructor-based DI: a class with a single constructor, or one annotated
// @Autowired/@Inject, injects each of that constructor's parameter types.
w.handleConstructorInjection(node, body, owner, annotations)
// Field-level @Autowired/@Inject and Lombok @RequiredArgsConstructor over
// `private final` fields also produce injection edges; emitted while walking
// the body below.
if body != nil {
w.walkBody(body, owner)
}
w.routeStack = w.routeStack[:len(w.routeStack)-1]
w.typeStack = w.typeStack[:len(w.typeStack)-1]
w.methodStack = w.methodStack[:len(w.methodStack)-1]
w.popOwner()
}
// walkBody iterates the direct members of a class/interface/enum body, handling
// nested declarations, methods, and fields. Non-declaration nodes are scanned for
// constructor calls attributed to `owner`.
func (w *astWalker) walkBody(body *sitter.Node, owner *facts.Fact) {
for i := uint(0); i < uint(body.ChildCount()); i++ {
c := body.Child(i)
switch c.Kind() {
case "class_declaration":
w.handleClassLike(c, facts.SymbolClass)
case "interface_declaration":
w.handleClassLike(c, facts.SymbolInterface)
case "enum_declaration":
w.handleClassLike(c, facts.SymbolEnum)
case "record_declaration":
w.handleClassLike(c, facts.SymbolClass)
case "annotation_type_declaration":
w.handleClassLike(c, facts.SymbolInterface)
case "method_declaration", "constructor_declaration":
w.handleMethod(c)
case "field_declaration":
w.handleField(c, owner)
default:
// init blocks, enum constants, etc. — scan for constructor calls.
w.walkForCalls(c)
}
}
}
func (w *astWalker) handleMethod(node *sitter.Node) {
nameNode := node.ChildByFieldName("name")
if nameNode == nil {
return
}
name := nodeText(nameNode, w.src)
modifiers := findChildByKind(node, "modifiers")
modifierText := ""
var annotations []javaAnnotation
if modifiers != nil {
modifierText = nodeText(modifiers, w.src)
annotations = parseAnnotations(modifiers, w.src)
}
exported := strings.Contains(modifierText, "public")
f := facts.Fact{
Kind: facts.KindSymbol,
Name: w.canonicalName(w.qualify(name)),
File: w.relFile,
Line: int(node.StartPosition().Row) + 1,
Props: map[string]any{
"symbol_kind": facts.SymbolMethod,
"exported": exported,
"language": "java",
},
Relations: []facts.Relation{
{Kind: facts.RelDeclares, Target: w.dir},
},
}
if t := w.enclosingType(); t != "" {
f.Props["receiver"] = t
}
if strings.Contains(modifierText, "static") {
f.Props["static"] = true
}
// Request-mapping annotation on a method: a server route on a @Controller, or an
// outbound client route on a @FeignClient interface (same annotations, the
// class-level annotation is the discriminator).
if rs := w.currentRoute(); rs != nil {
line := int(node.StartPosition().Row) + 1
switch {
case rs.isFeignClient:
w.out = append(w.out, feignClientFacts(rs.basePath, rs.feignHint, annotations, w.relFile, line, w.dir)...)
case rs.isController:
w.out = append(w.out, springRouteFacts(rs.basePath, annotations, w.relFile,
line, w.dir, w.canonicalName(w.qualify(name)))...)
}
}
w.out = append(w.out, f)
ownerIdx := len(w.out) - 1
w.pushOwner(&w.out[ownerIdx])
// Set up per-method complexity tracking. walkForCalls is re-entrant (it
// dispatches nested type declarations back through handleMethod), so save and
// restore the outer state. Props are written via the stable index (the pointer
// may be invalidated if the body walk grows w.out).
savedMetrics, savedDepth := w.metrics, w.loopDepth
savedName, savedShort := w.selfName, w.selfShort
savedParams := w.selfParams
w.metrics = &javaBodyMetrics{}
w.loopDepth = 0
w.selfName = f.Name
w.selfShort = name
w.selfParams = javaParamCount(node)
if body := node.ChildByFieldName("body"); body != nil {
w.walkForCalls(body)
}
m := w.metrics
props := w.out[ownerIdx].Props
props["cyclomatic"] = 1 + m.decisions
if m.loopDepth > 0 {
props["loop_depth"] = m.loopDepth
}
if m.loopCount > 0 {
props["loop_count"] = m.loopCount
}
if len(m.callsInLoop) > 0 {
props["calls_in_loop"] = m.callsInLoop
}
// A body that calls super.<self>() is an override delegating to a same-named
// overload, not genuine recursion — clear the arity-matched self-call flag.
if m.recursive && !m.sawSuperSelf {
props["recursive_self"] = true
}
w.metrics, w.loopDepth = savedMetrics, savedDepth
w.selfName, w.selfShort = savedName, savedShort
w.selfParams = savedParams
w.popOwner()
}
func (w *astWalker) handleField(node *sitter.Node, owner *facts.Fact) {
modifiers := findChildByKind(node, "modifiers")
modifierText := ""
var annotations []javaAnnotation
if modifiers != nil {
modifierText = nodeText(modifiers, w.src)
annotations = parseAnnotations(modifiers, w.src)
}
exported := strings.Contains(modifierText, "public")
symbolKind := facts.SymbolVariable
if strings.Contains(modifierText, "final") {
symbolKind = facts.SymbolConstant
}
// Field type — used for DI edges when @Autowired/@Inject is present.
typeNode := node.ChildByFieldName("type")
typeTarget := w.targetForType(typeNode)
injected := hasAnnotation(annotations, "Autowired", "Inject", "Resource", "Reference")
// A `static final String FOO = "literal"` constant exposes its value so that
// references to it (e.g. @Table(name = FOO)) can be resolved in a later pass.
captureValue := strings.Contains(modifierText, "static") &&
strings.Contains(modifierText, "final") &&
typeFullName(typeNode, w.src) == "String"
for i := uint(0); i < uint(node.ChildCount()); i++ {
c := node.Child(i)
if c.Kind() != "variable_declarator" {
continue
}
nameNode := c.ChildByFieldName("name")
if nameNode == nil {
continue
}
name := nodeText(nameNode, w.src)
props := map[string]any{
"symbol_kind": symbolKind,
"exported": exported,
"language": "java",
}
if captureValue && isScreamingSnake(name) {
if val, ok := stringLiteralValue(c.ChildByFieldName("value"), w.src); ok {
props["value"] = val
}
}
w.out = append(w.out, facts.Fact{
Kind: facts.KindSymbol,
Name: w.canonicalName(w.qualify(name)),
File: w.relFile,
Line: int(c.StartPosition().Row) + 1,
Props: props,
Relations: []facts.Relation{
{Kind: facts.RelDeclares, Target: w.dir},
},
})
}
if injected && typeTarget != "" && owner != nil {
owner.Relations = append(owner.Relations, facts.Relation{Kind: facts.RelInjects, Target: typeTarget})
}
// A field initializer may contain a constructor call (`= new Foo()`).
w.walkForCalls(node)
}
// handleConstructorInjection emits RelInjects edges from `owner` to each parameter
// type of an injectable constructor: a sole constructor, a constructor annotated
// @Autowired/@Inject, or (Lombok) when the class carries @RequiredArgsConstructor /
// @AllArgsConstructor.
func (w *astWalker) handleConstructorInjection(decl, body *sitter.Node, owner *facts.Fact, classAnns []javaAnnotation) {
lombokInject := hasAnnotation(classAnns, "RequiredArgsConstructor", "AllArgsConstructor")
// record_declaration parameters are constructor parameters too.
if decl.Kind() == "record_declaration" {
if params := decl.ChildByFieldName("parameters"); params != nil && lombokInject {
w.injectParams(params, owner)
}
}
if lombokInject {
// Inject each `private final` field's type.
if body != nil {
for i := uint(0); i < uint(body.ChildCount()); i++ {
c := body.Child(i)
if c.Kind() != "field_declaration" {
continue
}
mods := findChildByKind(c, "modifiers")
if mods == nil || !strings.Contains(nodeText(mods, w.src), "final") {
continue
}
if t := w.targetForType(c.ChildByFieldName("type")); t != "" && owner != nil {
owner.Relations = append(owner.Relations, facts.Relation{Kind: facts.RelInjects, Target: t})
}
}
}
}
if body == nil {
return
}
var ctors []*sitter.Node
for i := uint(0); i < uint(body.ChildCount()); i++ {
if c := body.Child(i); c.Kind() == "constructor_declaration" {
ctors = append(ctors, c)
}
}
for _, ctor := range ctors {
mods := findChildByKind(ctor, "modifiers")
annotated := false
if mods != nil {
annotated = hasAnnotation(parseAnnotations(mods, w.src), "Autowired", "Inject")
}
if annotated || (len(ctors) == 1 && !lombokInject) {
if params := ctor.ChildByFieldName("parameters"); params != nil {
w.injectParams(params, owner)
}
}
}
}
func (w *astWalker) injectParams(params *sitter.Node, owner *facts.Fact) {
if owner == nil {
return
}
for i := uint(0); i < uint(params.ChildCount()); i++ {
p := params.Child(i)
if p.Kind() != "formal_parameter" {
continue
}
if t := w.targetForType(p.ChildByFieldName("type")); t != "" {
owner.Relations = append(owner.Relations, facts.Relation{Kind: facts.RelInjects, Target: t})
}
}
}
// walkForCalls recursively scans a subtree for object_creation_expression (→
// RelInstantiates) and method_invocation (→ RelCalls for resolvable same-class
// calls), attributing each to the current owner. Nested type declarations are
// dispatched to their own handlers so their calls are attributed correctly.
func (w *astWalker) walkForCalls(node *sitter.Node) {
if node == nil {
return
}
kind := node.Kind()
// A lambda is a deferred scope: its body runs when invoked, NOT per-iteration of
// the enclosing loops — so reset the loop depth for its subtree (e.g. a Runnable
// or listener defined inside a loop). A stream iterator's OWN lambda is handled
// in the method_invocation branch (its body walks at +1).
if w.metrics != nil && kind == "lambda_expression" {
saved := w.loopDepth
w.loopDepth = 0
for i := uint(0); i < uint(node.ChildCount()); i++ {
w.walkForCalls(node.Child(i))
}
w.loopDepth = saved
return
}
// Complexity metrics: count decision points so the single body walk doubles as
// the cyclomatic pass.
if w.metrics != nil {
switch kind {
case "if_statement", "ternary_expression", "switch_label", "catch_clause":
w.metrics.decisions++
case "binary_expression":
if javaBooleanOp(node) {
w.metrics.decisions++
}
}
}
switch kind {
case "class_declaration":
w.handleClassLike(node, facts.SymbolClass)
return
case "interface_declaration":
w.handleClassLike(node, facts.SymbolInterface)
return
case "enum_declaration":
w.handleClassLike(node, facts.SymbolEnum)
return
case "record_declaration":
w.handleClassLike(node, facts.SymbolClass)
return
case "for_statement", "enhanced_for_statement", "while_statement", "do_statement":
// Syntactic loops: everything in the body runs per iteration.
if w.metrics != nil {
w.metrics.loopCount++
w.metrics.decisions++
if w.loopDepth+1 > w.metrics.loopDepth {
w.metrics.loopDepth = w.loopDepth + 1
}
}
w.loopDepth++
for i := uint(0); i < uint(node.ChildCount()); i++ {
w.walkForCalls(node.Child(i))
}
w.loopDepth--
return
case "object_creation_expression":
if t := w.targetForType(node.ChildByFieldName("type")); t != "" {
if owner := w.currentOwner(); owner != nil {
owner.Relations = append(owner.Relations, facts.Relation{Kind: facts.RelInstantiates, Target: t})
}
}
case "method_invocation":
w.handleInvocation(node)
// A Stream/Collection iterator with a lambda (items.forEach(x -> …)) is a
// loop: its lambda body runs per element, but the receiver/other args once.
if w.metrics != nil {
if lambda := javaStreamLambda(node, w.src); lambda != nil {
w.metrics.loopCount++
w.metrics.decisions++
if w.loopDepth+1 > w.metrics.loopDepth {
w.metrics.loopDepth = w.loopDepth + 1
}
for i := uint(0); i < uint(node.ChildCount()); i++ {
if c := node.Child(i); javaByteContains(c, lambda) {
w.walkJavaLambdaSubtree(c, lambda)
} else {
w.walkForCalls(c)
}
}
return
}
}
}
for i := uint(0); i < uint(node.ChildCount()); i++ {
w.walkForCalls(node.Child(i))
}
}
func (w *astWalker) handleInvocation(node *sitter.Node) {
owner := w.currentOwner()
if owner == nil {
return
}
nameNode := node.ChildByFieldName("name")
if nameNode == nil {
return
}
name := nodeText(nameNode, w.src)
obj := node.ChildByFieldName("object")
// HTTP client call site (RestTemplate). Emitted independently of the call-graph
// edge below; guarded by a path-like literal argument so non-HTTP same-named
// calls (map.put, list.delete) don't match.
w.detectRestTemplateCall(node, name)
// Resolve bare `foo()` and `this.foo()` calls against the enclosing class's
// own methods. Calls on other receivers are left unresolved (the receiver's
// type is not tracked), matching the Kotlin extractor's conservative model.
isThis := obj != nil && nodeText(obj, w.src) == "this"
if obj != nil && w.metrics != nil && name == w.selfShort && nodeText(obj, w.src) == "super" {
// super.<self>() — an override delegating to its supertype. Note it so an
// arity-matched bare <self>(…) call is read as overload delegation, not recursion.
w.metrics.sawSuperSelf = true
}
if obj == nil || isThis {
if methods := w.currentMethods(); methods[name] {
target := w.dir + "." + w.enclosingType() + "." + name
owner.Relations = append(owner.Relations, facts.Relation{
Kind: facts.RelCalls,
Target: target,
})
w.recordCallMetrics(target, javaArgCount(node))
}
} else if w.metrics != nil && w.loopDepth > 0 && !javaCheapMethods[name] {
// Method call on a non-this receiver inside a loop (repo.findById(), …). No
// graph edge today, but its name feeds the perf metric so the enterprise
// analyzer can flag per-iteration JPA/JDBC/network I/O.
tgt := name
if recv := nodeText(obj, w.src); recv != "" {
tgt = recv + "." + name
}
w.recordInLoop(tgt)
}
}
// targetForType returns a relation target for a `_type` node: the rightmost simple
// name resolved through the import map to an FQN, a same-package FQN when not
// imported, or the written FQN when the reference is already qualified. Returns ""
// for primitive/void/unresolvable types.
func (w *astWalker) targetForType(typeNode *sitter.Node) string {
if typeNode == nil {
return ""
}
full := typeFullName(typeNode, w.src)
if full == "" {
return ""
}
if isPrimitiveType(full) {
return ""
}
simple := full
if i := strings.LastIndex(full, "."); i >= 0 {
// Already qualified in source — use as written.
return full
}
if fqn, ok := w.importMap[simple]; ok {
return fqn
}
if javaLangTypes[simple] {
return ""
}
if w.pkg != "" {
return w.pkg + "." + simple
}
return simple
}
// supertypeTargets returns canonicalization targets (FQNs) for a type's superclass
// and implemented/extended interfaces.
func (w *astWalker) supertypeTargets(node *sitter.Node) []string {
var out []string
for _, n := range w.supertypeNodes(node) {
if t := w.targetForType(n); t != "" {
out = append(out, t)
}
}
return out
}
// supertypeSimpleNames returns the simple names of a type's supertypes (used by
// component classification, e.g. detecting Spring Data repository interfaces).
func (w *astWalker) supertypeSimpleNames(node *sitter.Node) []string {
var out []string
for _, n := range w.supertypeNodes(node) {
if s := lastTypeComponent(typeFullName(n, w.src)); s != "" {
out = append(out, s)
}
}
return out
}
func (w *astWalker) supertypeNodes(node *sitter.Node) []*sitter.Node {
var out []*sitter.Node
if sc := node.ChildByFieldName("superclass"); sc != nil {
out = append(out, firstTypeChild(sc))
}
// `interfaces` field (class/enum/record) or `extends_interfaces` child (interface).
if iface := node.ChildByFieldName("interfaces"); iface != nil {
out = append(out, typeListChildren(iface)...)
}
if ext := findChildByKind(node, "extends_interfaces"); ext != nil {
out = append(out, typeListChildren(ext)...)
}
// Filter nils.
kept := out[:0]
for _, n := range out {
if n != nil {
kept = append(kept, n)
}
}
return kept
}
// --- tree-sitter / type helpers ---
func classBody(node *sitter.Node) *sitter.Node {
if b := node.ChildByFieldName("body"); b != nil {
return b
}
return nil
}
// typeListChildren returns the concrete `_type` children of a super_interfaces /
// extends_interfaces node, which wrap a single type_list.
func typeListChildren(node *sitter.Node) []*sitter.Node {
tl := findChildByKind(node, "type_list")
if tl == nil {
return nil
}
var out []*sitter.Node
for i := uint(0); i < uint(tl.ChildCount()); i++ {
c := tl.Child(i)
if c.IsNamed() && c.Kind() != "annotation" && c.Kind() != "marker_annotation" {
out = append(out, c)
}
}
return out
}
// firstTypeChild returns the first named, non-annotation child of a wrapper node
// (e.g. the `_type` under a superclass node).
func firstTypeChild(node *sitter.Node) *sitter.Node {
if node == nil {
return nil
}
for i := uint(0); i < uint(node.ChildCount()); i++ {
c := node.Child(i)
if c.IsNamed() && c.Kind() != "annotation" && c.Kind() != "marker_annotation" {
return c
}
}
return nil
}