-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_ast_graph.py
More file actions
3081 lines (2780 loc) · 115 KB
/
build_ast_graph.py
File metadata and controls
3081 lines (2780 loc) · 115 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
#!/usr/bin/env python3
"""Four-pass AST-derived Knowledge Base builder (Kuzu).
Walks a Java source tree with `tree_sitter_java`, writes a deterministic graph of:
Symbol nodes: package, file, class, interface, enum, record, annotation, method, constructor
Route nodes: declaration-site routes (Spring MVC/WebFlux, Feign, Kafka, …)
Rel tables: EXTENDS, IMPLEMENTS, INJECTS, DECLARES, OVERRIDES, CALLS, EXPOSES
Pass 1 builds every node and in-memory resolution indexes.
Pass 2 resolves each extends/implements/injection target using Java's lookup order
(same file → explicit import → same package → wildcard import → java.lang → phantom).
Pass 3 resolves static call sites into confidence-scored CALLS edges and DECLARES.
Pass 4 emits Route rows plus Symbol→Route EXPOSES edges from literal annotation metadata.
Usage:
build_ast_graph.py --source-root <repo> [--kuzu-path <path>] [--verbose]
Default Kuzu database path resolution order:
--kuzu-path CLI arg (path passed to kuzu.Database(...))
JAVA_CODEBASE_RAG_INDEX_DIR/code_graph.kuzu (if set and local)
./.java-codebase-rag/code_graph.kuzu under cwd
The Kuzu DB is dropped and rebuilt on every run (Phase 1 is a full rebuild).
"""
from __future__ import annotations
import argparse
import hashlib
import json
import logging
import os
import re
import sys
import threading
import time
from collections import defaultdict
from dataclasses import asdict, dataclass, field, replace
from pathlib import Path
import kuzu
from ast_java import (
ONTOLOGY_VERSION,
CallSite,
JavaFileAst,
MethodDecl,
OutgoingCallDecl,
TypeDecl,
injection_annotation_names,
lombok_required_args_annotations,
parse_java,
)
from graph_enrich import (
_load_config_cross_service_resolution,
collect_annotation_meta_chain,
load_brownfield_overrides,
microservice_for_path,
module_for_path,
phantom_id,
resolve_async_producer_for_method,
resolve_http_client_for_method,
resolve_role_and_capabilities,
resolve_routes_for_method,
symbol_id,
)
from path_filtering import LayeredIgnore, iter_java_source_files
from java_ontology import VALID_CLIENT_KINDS, VALID_HTTP_CALL_MATCHES, VALID_PRODUCER_KINDS
log = logging.getLogger(__name__)
_VERBOSE_STDERR_LOCK = threading.Lock()
_PASS1_START = "[pass1] starting · parsing Java files under source root"
_PASS2_START = "[pass2] starting · emitting EXTENDS / IMPLEMENTS / DECLARES rows"
_PASS3_START = "[pass3] starting · call resolution (outgoing calls per site)"
_PASS4_START = "[pass4] starting · route and EXPOSES extraction"
_PASS5_START = "[pass5] starting · imperative HTTP_CALLS / ASYNC_CALLS edges"
_PASS6_START = "[pass6] starting · cross-service call-edge matching"
_WRITE_START = "[write] starting · writing Kuzu graph to disk"
def _verbose_stderr_line(content: str) -> None:
with _VERBOSE_STDERR_LOCK:
print(content, file=sys.stderr, flush=True)
class _VerbosePassHeartbeats:
"""Emit ``[tag] running … Ns elapsed`` every 5s on stderr while in scope (verbose only)."""
def __init__(self, tag: str, *, verbose: bool) -> None:
self._tag = tag
self._verbose = verbose
self._thr: threading.Thread | None = None
self._stop: threading.Event | None = None
def __enter__(self) -> None:
if not self._verbose:
return None
self._stop = threading.Event()
stop = self._stop
tag = self._tag
def worker() -> None:
t0 = time.monotonic()
while not stop.wait(timeout=5.0):
elapsed = int(time.monotonic() - t0)
_verbose_stderr_line(f"{tag} running … {elapsed}s elapsed")
self._thr = threading.Thread(target=worker, name=f"hb-{tag}", daemon=True)
self._thr.start()
return None
def __exit__(self, exc_type, exc, tb) -> bool:
if self._thr is not None and self._stop is not None:
self._stop.set()
self._thr.join(timeout=2.0)
return False
_JAVA_LANG_SIMPLE = frozenset({
"Object", "String", "Integer", "Long", "Short", "Byte", "Boolean", "Double",
"Float", "Character", "Number", "Void", "Class", "Enum", "Record",
"Throwable", "Exception", "RuntimeException", "Error", "Thread", "Runnable",
"Iterable", "Comparable", "CharSequence", "StringBuilder", "StringBuffer",
"Math", "System", "AutoCloseable", "Cloneable",
})
# ---------- dataclasses ----------
@dataclass
class TypeIndexEntry:
"""Pass-1 record for a type declaration + any methods/constructors inside it."""
decl: TypeDecl
file_path: str
module: str
microservice: str
package: str
outer_fqn: str | None
node_id: str
@dataclass
class MemberEntry:
kind: str # method | constructor
decl: MethodDecl
parent_id: str
parent_fqn: str
file_path: str
module: str
microservice: str
node_id: str
@dataclass
class EdgeRow:
src_id: str
dst_id: str
dst_name: str
dst_fqn: str
resolved: bool
@dataclass
class InjectsRow(EdgeRow):
mechanism: str = ""
annotation: str = ""
field_or_param: str = ""
@dataclass
class CallsRow:
src_id: str
dst_id: str
call_site_line: int = 0
call_site_byte: int = 0
arg_count: int = 0
confidence: float = 0.0
strategy: str = "phantom"
source: str = "static"
resolved: bool = True
callee_declaring_role: str = "OTHER"
@dataclass
class UnresolvedCallSiteRow:
id: str
caller_id: str
call_site_line: int
call_site_byte: int
arg_count: int
callee_simple: str
receiver_expr: str
reason: str
@dataclass
class DeclaresRow:
src_id: str
dst_id: str
@dataclass
class CallResolutionStats:
total: int = 0
by_strategy: dict[str, int] = field(default_factory=lambda: defaultdict(int))
phantom_chained: int = 0
phantom_other: int = 0
callee_unresolved: int = 0
skipped_cross_service: int = 0
@dataclass
class RouteRow:
id: str
kind: str
framework: str
method: str
path: str
path_template: str
path_regex: str
topic: str
broker: str
feign_name: str
feign_url: str
microservice: str
module: str
filename: str
start_line: int
end_line: int
resolved: bool
# B2a brownfield composition (PR-A3); not persisted on Kuzu `Route` nodes.
source_layer: str = "builtin"
@dataclass
class ExposesRow:
symbol_id: str
route_id: str
confidence: float
strategy: str
@dataclass
class RouteExtractionStats:
routes_skipped_unresolved: int = 0
by_framework: dict[str, int] = field(default_factory=lambda: defaultdict(int))
by_kind: dict[str, int] = field(default_factory=lambda: defaultdict(int))
routes_resolved_pct: float = 100.0
# Percentage of emitted `Route` rows whose `source_layer` is not `builtin`.
# Brownfield layers: `layer_b_ann`, `layer_a_meta`, `layer_c_source`, `layer_b_fqn`.
routes_from_brownfield_pct: float = 0.0
routes_by_layer: dict[str, int] = field(default_factory=dict)
exposes_suppressed_feign: int = 0
@dataclass
class HttpCallRow:
client_id: str
route_id: str
confidence: float
strategy: str
method_call: str
raw_uri: str
match: str
@dataclass
class AsyncCallRow:
producer_id: str
route_id: str
confidence: float
strategy: str
direction: str
raw_topic: str
match: str
@dataclass
class ClientRow:
id: str
client_kind: str
target_service: str
path: str
path_template: str
path_regex: str
method: str
member_fqn: str
member_id: str
microservice: str
module: str
filename: str
start_line: int
end_line: int
resolved: bool
source_layer: str
@dataclass
class DeclaresClientRow:
symbol_id: str
client_id: str
confidence: float
strategy: str
@dataclass
class ProducerRow:
id: str
producer_kind: str
topic: str
broker: str
direction: str
member_fqn: str
member_id: str
microservice: str
module: str
filename: str
start_line: int
end_line: int
resolved: bool
source_layer: str
@dataclass
class DeclaresProducerRow:
symbol_id: str
producer_id: str
confidence: float
strategy: str
@dataclass
class ClientExtractionStats:
clients_total: int = 0
declares_client_total: int = 0
clients_by_kind: dict[str, int] = field(default_factory=lambda: defaultdict(int))
@dataclass
class ProducerExtractionStats:
producers_total: int = 0
declares_producer_total: int = 0
producers_by_kind: dict[str, int] = field(default_factory=lambda: defaultdict(int))
@dataclass
class CallEdgeStats:
http_calls_total: int = 0
async_calls_total: int = 0
http_calls_by_client_kind: dict[str, int] = field(default_factory=lambda: defaultdict(int))
async_calls_by_client_kind: dict[str, int] = field(default_factory=lambda: defaultdict(int))
http_calls_by_strategy: dict[str, int] = field(default_factory=lambda: defaultdict(int))
async_calls_by_strategy: dict[str, int] = field(default_factory=lambda: defaultdict(int))
http_calls_skipped_unresolved: int = 0
async_calls_skipped_unresolved: int = 0
http_clients_from_brownfield_pct: float = 0.0
async_producers_from_brownfield_pct: float = 0.0
http_calls_match_breakdown: dict[str, int] = field(default_factory=lambda: defaultdict(int))
async_calls_match_breakdown: dict[str, int] = field(default_factory=lambda: defaultdict(int))
cross_service_calls_total: int = 0
@dataclass
class GraphTables:
types: dict[str, TypeIndexEntry] = field(default_factory=dict) # fqn -> entry
by_simple_name: dict[str, list[TypeIndexEntry]] = field(default_factory=dict)
by_package: dict[str, list[TypeIndexEntry]] = field(default_factory=dict)
files: dict[str, str] = field(default_factory=dict) # path -> node id
packages: dict[str, str] = field(default_factory=dict) # pkg -> node id
members: list[MemberEntry] = field(default_factory=list)
phantoms: dict[str, dict] = field(default_factory=dict) # id -> row
extends_rows: list[EdgeRow] = field(default_factory=list)
implements_rows: list[EdgeRow] = field(default_factory=list)
injects_rows: list[InjectsRow] = field(default_factory=list)
calls_rows: list[CallsRow] = field(default_factory=list)
unresolved_call_site_rows: list[UnresolvedCallSiteRow] = field(default_factory=list)
declares_rows: list[DeclaresRow] = field(default_factory=list)
routes_rows: list[RouteRow] = field(default_factory=list)
exposes_rows: list[ExposesRow] = field(default_factory=list)
http_call_rows: list[HttpCallRow] = field(default_factory=list)
async_call_rows: list[AsyncCallRow] = field(default_factory=list)
client_rows: list[ClientRow] = field(default_factory=list)
declares_client_rows: list[DeclaresClientRow] = field(default_factory=list)
producer_rows: list[ProducerRow] = field(default_factory=list)
declares_producer_rows: list[DeclaresProducerRow] = field(default_factory=list)
overrides_rows: list[DeclaresRow] = field(default_factory=list)
route_stats: RouteExtractionStats = field(default_factory=RouteExtractionStats)
call_edge_stats: CallEdgeStats = field(default_factory=CallEdgeStats)
client_stats: ClientExtractionStats = field(default_factory=ClientExtractionStats)
producer_stats: ProducerExtractionStats = field(default_factory=ProducerExtractionStats)
methods_by_type: dict[str, list[MemberEntry]] = field(default_factory=dict)
parse_errors: int = 0
skipped_files: int = 0
pass3_skipped_cross_service: int = 0
pass3_unresolved_phantom_receiver: int = 0
pass3_unresolved_chained: int = 0
cross_service_resolution: str = "auto"
# Populated in _write_nodes (same overrides + meta_chain as Symbol.role).
type_role_by_node_id: dict[str, str] = field(default_factory=dict)
# ---------- file walk (see `path_filtering.iter_java_source_files`) ----------
# ---------- pass 1 ----------
def _register_type(
tables: GraphTables,
decl: TypeDecl,
*,
file_path: str,
module: str,
microservice: str,
outer_fqn: str | None,
) -> TypeIndexEntry:
package = decl.fqn.rsplit(".", 1)[0] if "." in decl.fqn and outer_fqn is None else (
outer_fqn.rsplit(".", 1)[0] if outer_fqn and "." in outer_fqn else ""
)
# top-level: package = fqn - name; nested: inherit from outer
if outer_fqn is None:
package = decl.fqn[: -(len(decl.name) + 1)] if decl.fqn.endswith("." + decl.name) else ""
else:
# walk outward to find a top-level fqn; package is everything before its simple name
top = outer_fqn
while top in tables.types and tables.types[top].outer_fqn:
top = tables.types[top].outer_fqn # type: ignore[assignment]
package = top[: top.rfind(".")] if "." in top else ""
node_id = symbol_id(decl.kind, decl.fqn, file_path, decl.start_byte)
entry = TypeIndexEntry(
decl=decl,
file_path=file_path,
module=module,
microservice=microservice,
package=package,
outer_fqn=outer_fqn,
node_id=node_id,
)
tables.types[decl.fqn] = entry
tables.by_simple_name.setdefault(decl.name, []).append(entry)
tables.by_package.setdefault(package, []).append(entry)
for m in decl.methods:
kind = "constructor" if m.is_constructor else "method"
mid = symbol_id(kind, f"{decl.fqn}#{m.signature}", file_path, m.start_byte)
tables.members.append(MemberEntry(
kind=kind, decl=m, parent_id=node_id, parent_fqn=decl.fqn,
file_path=file_path, module=module, microservice=microservice,
node_id=mid,
))
for nested in decl.nested:
_register_type(
tables, nested, file_path=file_path,
module=module, microservice=microservice, outer_fqn=decl.fqn,
)
return entry
def pass1_parse(root: Path, tables: GraphTables, *, verbose: bool) -> dict[str, JavaFileAst]:
"""Walk files, parse them, populate node indexes. Returns path -> AST."""
asts: dict[str, JavaFileAst] = {}
ignore = LayeredIgnore(root)
t0 = time.time()
n_files = 0
if verbose:
_verbose_stderr_line(_PASS1_START)
slow_sec = 0.0
raw_slow = os.environ.get("JAVA_CODEBASE_RAG_TEST_GRAPH_SLOW_SEC", "").strip()
if raw_slow:
try:
slow_sec = float(raw_slow)
except ValueError:
slow_sec = 0.0
with _VerbosePassHeartbeats("[pass1]", verbose=verbose):
if verbose and slow_sec > 0:
time.sleep(slow_sec)
for p in iter_java_source_files(root, ignore=ignore):
n_files += 1
try:
content = p.read_bytes()
except OSError:
tables.skipped_files += 1
continue
if not content.strip():
continue
try:
rel = p.resolve().relative_to(root.resolve()).as_posix()
except ValueError:
rel = p.as_posix()
try:
ast = parse_java(content, filename=rel, verbose=verbose)
except Exception:
tables.parse_errors += 1
continue
if ast.parse_error:
tables.parse_errors += 1
# Still index what tree-sitter gave us; robust to syntax errors.
module = module_for_path(str(p), root)
microservice = microservice_for_path(str(p), root)
asts[rel] = ast
# file node
file_id = symbol_id("file", rel, rel, 0)
tables.files[rel] = file_id
# package node (created lazily; nodes deduped by id)
if ast.package and ast.package not in tables.packages:
tables.packages[ast.package] = symbol_id("package", ast.package, "", 0)
for t in ast.top_level_types:
_register_type(
tables, t, file_path=rel,
module=module, microservice=microservice, outer_fqn=None,
)
if verbose:
elapsed = time.time() - t0
_verbose_stderr_line(
f"[pass1] parsed {n_files} files in {elapsed:.2f}s: "
f"{len(tables.types)} types, {len(tables.members)} members, "
f"{tables.parse_errors} parse errors, {tables.skipped_files} skipped",
)
return asts
# ---------- pass 2: resolution + edges ----------
def _resolve_simple(
name: str,
*,
current: TypeIndexEntry,
ast: JavaFileAst,
tables: GraphTables,
) -> TypeIndexEntry | None:
"""Java-ish name resolution. Returns a known TypeIndexEntry or None (phantom)."""
# Strip trailing generics the caller may have left in, defensively.
bare = name.split("<", 1)[0].strip()
if not bare:
return None
# 0. Nested inside the same top-level hierarchy — try `Outer.Bare` fqn.
outer = current.outer_fqn
while outer is not None and outer in tables.types:
candidate = f"{outer}.{bare}"
if candidate in tables.types:
return tables.types[candidate]
outer = tables.types[outer].outer_fqn
# 1. Same-file siblings (same outer as `current`).
same_outer = current.outer_fqn or current.package
for e in tables.by_simple_name.get(bare, ()):
e_parent = e.outer_fqn or e.package
if e.file_path == current.file_path and e_parent == same_outer:
return e
# 2. Explicit import.
if bare in ast.explicit_imports:
fq = ast.explicit_imports[bare]
if fq in tables.types:
return tables.types[fq]
# Known FQN (outside our codebase) → unresolved; caller will phantom-ise.
return None
# 3. Same package.
if current.package:
candidate = f"{current.package}.{bare}"
if candidate in tables.types:
return tables.types[candidate]
# 4. Wildcard imports.
for wild in ast.wildcard_imports:
candidate = f"{wild}.{bare}"
if candidate in tables.types:
return tables.types[candidate]
# 5. java.lang best-effort (unresolved but deterministic phantom).
return None
def _phantom_target(
tables: GraphTables,
simple: str,
ast: JavaFileAst,
*,
current: TypeIndexEntry,
) -> tuple[str, str, str]:
"""Produce (id, simple, fqn-or-best-guess) for an unresolved type reference.
The fqn falls back through: explicit import → wildcard → java.lang → bare name.
"""
bare = simple.split("<", 1)[0].strip()
guess_fqn = bare
if bare in ast.explicit_imports:
guess_fqn = ast.explicit_imports[bare]
elif bare in _JAVA_LANG_SIMPLE:
guess_fqn = f"java.lang.{bare}"
elif ast.wildcard_imports:
# Pick first wildcard as a hint (imperfect but useful for display).
guess_fqn = f"{ast.wildcard_imports[0]}.{bare}"
pid = phantom_id(guess_fqn)
if pid not in tables.phantoms:
tables.phantoms[pid] = {
"id": pid,
"kind": "class",
"name": bare,
"fqn": guess_fqn,
"package": guess_fqn.rsplit(".", 1)[0] if "." in guess_fqn else "",
"module": "",
"microservice": "",
"filename": "",
"start_line": 0,
"end_line": 0,
"start_byte": 0,
"end_byte": 0,
"modifiers": [],
"annotations": [],
"capabilities": [],
"role": "OTHER",
"signature": "",
"parent_id": "",
"resolved": False,
}
return pid, bare, guess_fqn
def _edge_for(
*,
src: TypeIndexEntry,
target_simple: str,
ast: JavaFileAst,
tables: GraphTables,
) -> tuple[str, str, str, bool]:
resolved = _resolve_simple(target_simple, current=src, ast=ast, tables=tables)
if resolved is not None:
return resolved.node_id, resolved.decl.name, resolved.decl.fqn, True
pid, simple, fqn = _phantom_target(tables, target_simple, ast, current=src)
return pid, simple, fqn, False
def _emit_extends_implements(
entry: TypeIndexEntry,
ast: JavaFileAst,
tables: GraphTables,
*,
seen_ext: set[tuple[str, str]],
seen_impl: set[tuple[str, str]],
) -> None:
for name in entry.decl.extends:
dst_id, dst_simple, dst_fqn, ok = _edge_for(
src=entry, target_simple=name, ast=ast, tables=tables,
)
key = (entry.node_id, dst_id)
if key in seen_ext:
continue
seen_ext.add(key)
tables.extends_rows.append(EdgeRow(
src_id=entry.node_id, dst_id=dst_id,
dst_name=dst_simple, dst_fqn=dst_fqn, resolved=ok,
))
for name in entry.decl.implements:
dst_id, dst_simple, dst_fqn, ok = _edge_for(
src=entry, target_simple=name, ast=ast, tables=tables,
)
key = (entry.node_id, dst_id)
if key in seen_impl:
continue
seen_impl.add(key)
tables.implements_rows.append(EdgeRow(
src_id=entry.node_id, dst_id=dst_id,
dst_name=dst_simple, dst_fqn=dst_fqn, resolved=ok,
))
def _emit_injects(
entry: TypeIndexEntry,
ast: JavaFileAst,
tables: GraphTables,
*,
seen: set[tuple[str, str, str, str]],
) -> None:
if entry.decl.kind == "interface":
return
ann_names = [a.name for a in entry.decl.annotations]
inject_set = injection_annotation_names()
lombok_rac = lombok_required_args_annotations()
has_lombok_rac = any(a in lombok_rac for a in ann_names)
def _add(
target: str, mechanism: str, annotation: str, slot: str,
) -> None:
dst_id, dst_simple, dst_fqn, ok = _edge_for(
src=entry, target_simple=target, ast=ast, tables=tables,
)
key = (entry.node_id, dst_id, mechanism, slot)
if key in seen:
return
seen.add(key)
tables.injects_rows.append(InjectsRow(
src_id=entry.node_id, dst_id=dst_id,
dst_name=dst_simple, dst_fqn=dst_fqn, resolved=ok,
mechanism=mechanism, annotation=annotation, field_or_param=slot,
))
# Field injection: @Autowired / @Inject / @Resource.
for f in entry.decl.fields:
annotated = next((a.name for a in f.annotations if a.name in inject_set), None)
if annotated:
_add(f.type_name, "field", annotated, f.name)
# Lombok: @RequiredArgsConstructor -> each `final` non-static field becomes an injection;
# @AllArgsConstructor -> every non-static field.
if has_lombok_rac:
all_args = "AllArgsConstructor" in ann_names
for f in entry.decl.fields:
if "static" in f.modifiers:
continue
if not all_args and "final" not in f.modifiers:
continue
_add(f.type_name, "lombok_required_args",
"AllArgsConstructor" if all_args else "RequiredArgsConstructor",
f.name)
# Constructor injection:
ctors = [m for m in entry.decl.methods if m.is_constructor]
if ctors:
chosen = None
autowired = [c for c in ctors if any(a.name == "Autowired" for a in c.annotations)]
if autowired:
chosen = autowired[0]
elif len(ctors) == 1 and ctors[0].parameters:
chosen = ctors[0]
if chosen is not None:
annotation = "Autowired" if any(a.name == "Autowired" for a in chosen.annotations) else ""
for p in chosen.parameters:
_add(p.type_name, "constructor", annotation, p.name)
# Setter injection: setXxx annotated @Autowired with 1 parameter.
for m in entry.decl.methods:
if m.is_constructor or not m.name.startswith("set") or len(m.parameters) != 1:
continue
if any(a.name == "Autowired" for a in m.annotations):
_add(m.parameters[0].type_name, "setter", "Autowired",
m.parameters[0].name)
def pass2_edges(tables: GraphTables, asts: dict[str, JavaFileAst], *, verbose: bool) -> None:
t0 = time.time()
seen_ext: set[tuple[str, str]] = set()
seen_impl: set[tuple[str, str]] = set()
seen_inj: set[tuple[str, str, str, str]] = set()
if verbose:
_verbose_stderr_line(_PASS2_START)
with _VerbosePassHeartbeats("[pass2]", verbose=verbose):
for fqn, entry in tables.types.items():
ast = asts.get(entry.file_path)
if ast is None:
continue
_emit_extends_implements(entry, ast, tables, seen_ext=seen_ext, seen_impl=seen_impl)
_emit_injects(entry, ast, tables, seen=seen_inj)
if verbose:
elapsed = time.time() - t0
_verbose_stderr_line(
f"[pass2] emitted {len(tables.extends_rows)} EXTENDS, "
f"{len(tables.implements_rows)} IMPLEMENTS, "
f"{len(tables.injects_rows)} INJECTS, "
f"{len(tables.phantoms)} phantoms in {elapsed:.2f}s",
)
# ---------- pass 3: call graph ----------
def _build_member_indexes(tables: GraphTables) -> None:
tables.methods_by_type = {}
for m in tables.members:
tables.methods_by_type.setdefault(m.parent_fqn, []).append(m)
def _direct_supertype_fqns(entry: TypeIndexEntry, tables: GraphTables) -> list[str]:
out: list[str] = []
for r in tables.extends_rows:
if r.src_id == entry.node_id and r.dst_fqn in tables.types:
out.append(r.dst_fqn)
for r in tables.implements_rows:
if r.src_id == entry.node_id and r.dst_fqn in tables.types:
out.append(r.dst_fqn)
return out
def _first_supertype_fqn(tables: GraphTables, type_fqn: str) -> str | None:
entry = tables.types.get(type_fqn)
if entry is None:
return None
for r in tables.extends_rows:
if r.src_id == entry.node_id and r.dst_fqn in tables.types:
return r.dst_fqn
for r in tables.implements_rows:
if r.src_id == entry.node_id and r.dst_fqn in tables.types:
return r.dst_fqn
return None
def _is_chained_receiver_text(receiver_expr: str) -> bool:
"""Heuristic: call chain or complex expr (contains a completed call)."""
s = receiver_expr.strip()
return "(" in s and ")" in s
def _resolve_this_super_field_chain(
expr: str,
*,
member: MemberEntry,
ast: JavaFileAst,
tables: GraphTables,
) -> str | None:
"""Resolve `this.a.b` / `super.a` (no calls) to the final field's type FQN."""
s = expr.strip()
if "(" in s or ")" in s or "." not in s:
return None
entry = tables.types.get(member.parent_fqn)
if entry is None:
return None
parts = s.split(".")
if len(parts) < 2:
return None
if parts[0] == "this":
cur = entry
elif parts[0] == "super":
sup = _first_supertype_fqn(tables, member.parent_fqn)
if sup is None or sup not in tables.types:
return None
cur = tables.types[sup]
else:
return None
for fname in parts[1:]:
fld = next((f for f in cur.decl.fields if f.name == fname), None)
if fld is None:
return None
resolved = _resolve_simple(fld.type_name, current=cur, ast=ast, tables=tables)
if resolved is None:
return None
cur = resolved
return cur.decl.fqn
def _scope_table(member: MemberEntry, ast: JavaFileAst, tables: GraphTables) -> dict[str, str]:
"""Map simple variable/field/param name -> resolved declaring type FQN."""
scope: dict[str, str] = {}
entry = tables.types.get(member.parent_fqn)
if entry is None:
return scope
def add_fields(tentry: TypeIndexEntry) -> None:
for f in tentry.decl.fields:
resolved = _resolve_simple(f.type_name, current=tentry, ast=ast, tables=tables)
if resolved is not None:
scope[f.name] = resolved.decl.fqn
add_fields(entry)
seen: set[str] = {member.parent_fqn}
queue = list(_direct_supertype_fqns(entry, tables))
while queue:
sup = queue.pop()
if sup in seen or sup not in tables.types:
continue
seen.add(sup)
te = tables.types[sup]
for f in te.decl.fields:
if f.name not in scope:
resolved = _resolve_simple(f.type_name, current=te, ast=ast, tables=tables)
if resolved is not None:
scope[f.name] = resolved.decl.fqn
queue.extend(_direct_supertype_fqns(te, tables))
for p in member.decl.parameters:
resolved = _resolve_simple(p.type_name, current=entry, ast=ast, tables=tables)
if resolved is not None:
scope[p.name] = resolved.decl.fqn
# Locals shadow fields and parameters (same simple name → local wins).
for name, t_simple in member.decl.local_vars:
resolved = _resolve_simple(t_simple, current=entry, ast=ast, tables=tables)
if resolved is not None:
scope[name] = resolved.decl.fqn
return scope
def _lookup_method_candidates(
type_fqn: str,
callee_simple: str,
arg_count: int,
tables: GraphTables,
ast: JavaFileAst,
*,
visited: set[str] | None = None,
) -> tuple[list[MemberEntry], bool]:
"""Return (candidates, used_name_only_fallback). Walks type + supertypes.
When ``used_name_only_fallback`` is true and ``len(candidates) == 1``, the
caller may reuse the receiver-resolution strategy (see ``_resolve_and_emit_call``)
instead of tagging ``overload_ambiguous``.
"""
if visited is None:
visited = set()
exact: list[MemberEntry] = []
name_only: list[MemberEntry] = []
def collect_on_type(tfqn: str) -> None:
nonlocal exact, name_only
for m in tables.methods_by_type.get(tfqn, ()):
if callee_simple == "<init>":
if not m.decl.is_constructor:
continue
np = len(m.decl.parameters)
if arg_count < 0:
name_only.append(m)
elif np == arg_count:
exact.append(m)
else:
name_only.append(m)
continue
if m.decl.is_constructor:
continue
if m.decl.name != callee_simple:
continue
np = len(m.decl.parameters)
if arg_count < 0:
name_only.append(m)
elif np == arg_count:
exact.append(m)
else:
name_only.append(m)
queue = [type_fqn]
while queue:
tfqn = queue.pop(0)
if tfqn in visited or tfqn not in tables.types:
continue
visited.add(tfqn)
collect_on_type(tfqn)
te = tables.types[tfqn]
for sup in _direct_supertype_fqns(te, tables):
if sup not in visited:
queue.append(sup)
# Synthetic anonymous classes (`….<anon:byte>`): unqualified instance calls
# may target the lexically enclosing type (D3), e.g. `pingFromAnon()` from
# `NestedCalls` inside `new Runnable() { void run() { … } }`.
if ".<anon:" in tfqn and te.outer_fqn and te.outer_fqn not in visited:
queue.append(te.outer_fqn)
if exact:
return exact, False
if name_only:
return name_only, True
return [], False
def _static_wildcard_resolve(
callee_simple: str,
ast: JavaFileAst,
tables: GraphTables,
current: TypeIndexEntry,
) -> str | None:
for tw in ast.file_imports.static_wildcards:
if tw not in tables.types:
continue
for m in tables.methods_by_type.get(tw, ()):
if m.decl.name != callee_simple or m.decl.is_constructor:
continue
if "static" not in m.decl.modifiers:
continue
return tw
return None
def _unique_type_simple_resolve(simple: str, tables: GraphTables) -> str | None:
"""Return the type FQN iff exactly one indexed type uses `simple` as `decl.name`.
Used only for receiver / static-qualifier disambiguation. Do not use the
method index here: an unresolved identifier that equals some method's
simple name elsewhere in the project is not evidence about the receiver type.
"""
hits = tables.by_simple_name.get(simple, [])
if len(hits) != 1:
return None
return hits[0].decl.fqn
def _suffix_resolve(receiver_simple: str, tables: GraphTables) -> str | None:
matches = [fq for fq in tables.types if fq.endswith("." + receiver_simple)]