-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast_java.py
More file actions
2813 lines (2538 loc) · 95.9 KB
/
ast_java.py
File metadata and controls
2813 lines (2538 loc) · 95.9 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
"""Deterministic Java AST extraction on top of tree-sitter.
Produces a typed, stable view of a single .java compilation unit:
package, imports, and a tree of TypeDecl (class/interface/enum/record/annotation)
with their annotations, fields, methods, and nested types. Anonymous classes
(`new T() { … }`) become synthetic nested TypeDecl rows (`<anon:startByte>`) so
their method bodies own call-site lists (see `propose/completed/CALL-GRAPH-PROPOSE.md` §4.1).
The output is deliberately language-model friendly (simple names, no tree-sitter
Nodes leak through) so downstream graph / chunk-enrichment code can stay pure
Python with no tree-sitter dependency.
"""
from __future__ import annotations
import posixpath
from dataclasses import dataclass, field
from functools import lru_cache
from typing import Iterable
import tree_sitter_java as _ts_java
from brownfield_events import (
emit_brownfield_exclusivity_shadowing,
emit_brownfield_method_string_literal,
)
from tree_sitter import Language, Node, Parser
__all__ = [
"AnnotationRef",
"CallSite",
"FieldDecl",
"FileImports",
"ParamDecl",
"MethodDecl",
"OutgoingCallDecl",
"RouteDecl",
"ROUTE_META_ANNOTATION_NAMES",
"CODEBASE_ROUTE_ANNOTATIONS",
"CODEBASE_HTTP_CLIENT_ANNOTATIONS",
"CODEBASE_PRODUCER_ANNOTATIONS",
"TypeDecl",
"JavaFileAst",
"parse_java",
"infer_role",
"infer_role_for_type",
"infer_capabilities_for_type",
"ROLE_ANNOTATIONS",
"ONTOLOGY_VERSION",
"_METHOD_ANN_TO_CAPABILITY",
"_TYPE_ANN_TO_CAPABILITY",
"_INJECTED_TYPES_TO_CAPABILITY",
"_SUPERTYPE_TO_CAPABILITY",
]
# Name suffixes that strongly indicate a passive data-carrier type when the
# type is not annotated as a Spring/JPA component. Kept conservative on
# purpose: a single clear suffix match is enough, but only when role
# inference would otherwise return OTHER (so @Service FooRequest stays a
# SERVICE). Checked case-sensitively against the simple type name.
_DTO_NAME_SUFFIXES: tuple[str, ...] = (
"Dto", "DTO",
"Request", "Response",
"Payload", "Model",
"Event", "Message",
"Body", "Form",
"Command", "Query",
"Record", "View",
)
# Lombok value / builder annotations typical of DTO-style types. Presence of
# any one of these promotes an otherwise role-less type to DTO.
_DTO_LOMBOK_ANNOTATIONS: frozenset[str] = frozenset({
"Data", "Value", "Builder",
"Getter", "Setter",
"EqualsAndHashCode", "ToString",
})
# Phase 5: HTTP_CALLS + ASYNC_CALLS (B2b); Phase 6: cross-service resolution mode on GraphMeta;
# Phase 7: FEIGN_CLIENT role -> CLIENT + HTTP_CLIENT capability vocabulary cleanup;
# Phase 8: first-class Client node + DECLARES_CLIENT relation, separating outbound declarations from Route.
# Phase 9: `@CodebaseAsyncRoute` replaces same-method built-in `@KafkaListener` routes in graph composition.
# Phase 10: `@CodebaseHttpClient` rename + `CodebaseHttpMethod` enum; inbound HTTP layer-C replaces built-in rows.
# Phase 11: `EDGE_SCHEMA` in `java_ontology.py` (canonical edge navigation schema; v14 re-index).
# Phase 12: CALLS `callee_declaring_role`, supertype-walk dedup, pass3 unresolved counters (v15 re-index).
# Bumps whenever extraction / enrichment semantics change.
ONTOLOGY_VERSION = 15
ROLE_ANNOTATIONS: dict[str, str] = {
# Spring Web
"RestController": "CONTROLLER",
"Controller": "CONTROLLER",
# Spring stereotypes
"Service": "SERVICE",
"Repository": "REPOSITORY",
"Component": "COMPONENT",
"Configuration": "CONFIG",
# Persistence
"Entity": "ENTITY",
"MappedSuperclass": "ENTITY",
"Embeddable": "ENTITY",
# Remoting / messaging
"FeignClient": "CLIENT",
# Mappers
"Mapper": "MAPPER",
}
_INJECT_FIELD_ANNOTATIONS = frozenset({"Autowired", "Inject", "Resource"})
_LOMBOK_RAC = frozenset({"RequiredArgsConstructor", "AllArgsConstructor"})
# ---------- capability detector tables ----------
_METHOD_ANN_TO_CAPABILITY: dict[str, str] = {
"KafkaListener": "MESSAGE_LISTENER",
"RabbitListener": "MESSAGE_LISTENER",
"JmsListener": "MESSAGE_LISTENER",
"SqsListener": "MESSAGE_LISTENER",
"EventListener": "MESSAGE_LISTENER",
"StreamListener": "MESSAGE_LISTENER",
"Scheduled": "SCHEDULED_TASK",
"ExceptionHandler": "EXCEPTION_HANDLER",
}
_TYPE_ANN_TO_CAPABILITY: dict[str, str] = {
"ControllerAdvice": "EXCEPTION_HANDLER",
"RestControllerAdvice": "EXCEPTION_HANDLER",
"FeignClient": "HTTP_CLIENT",
}
_INJECTED_TYPES_TO_CAPABILITY: dict[str, str] = {
"KafkaTemplate": "MESSAGE_PRODUCER",
"RabbitTemplate": "MESSAGE_PRODUCER",
"JmsTemplate": "MESSAGE_PRODUCER",
"StreamBridge": "MESSAGE_PRODUCER",
"ApplicationEventPublisher": "MESSAGE_PRODUCER",
}
_SUPERTYPE_TO_CAPABILITY: dict[str, str] = {
"Job": "SCHEDULED_TASK",
}
_ROUTE_HTTP_MAPPING_NAMES = frozenset({
"RequestMapping",
"GetMapping",
"PostMapping",
"PutMapping",
"DeleteMapping",
"PatchMapping",
})
# Seeds for `collect_annotation_meta_chain` so custom @interface meta-annotations
# (e.g. @AcmeGet meta-@GetMapping) resolve in Layer A (see graph_enrich._meta_builtins).
ROUTE_META_ANNOTATION_NAMES: frozenset[str] = _ROUTE_HTTP_MAPPING_NAMES | frozenset({
"KafkaListener",
"RabbitListener",
"JmsListener",
"StreamListener",
})
CODEBASE_ROUTE_ANNOTATIONS: frozenset[str] = frozenset({
"CodebaseHttpRoute",
"CodebaseHttpRoutes",
"CodebaseAsyncRoute",
"CodebaseAsyncRoutes",
})
CODEBASE_HTTP_CLIENT_ANNOTATIONS: frozenset[str] = frozenset(
{"CodebaseHttpClient", "CodebaseHttpClients"}
)
# Framework annotations bypassed when `@CodebaseHttpRoute` / `@CodebaseHttpClient` wins (verbose INFO).
_BROWNFIELD_SHADOWABLE_HTTP_FRAMEWORK_METHOD_ANNOTATIONS: frozenset[str] = (
_ROUTE_HTTP_MAPPING_NAMES
| frozenset({
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"HEAD",
"OPTIONS",
})
)
CODEBASE_PRODUCER_ANNOTATIONS: frozenset[str] = frozenset({"CodebaseProducer", "CodebaseProducers"})
_ROUTE_ASYNC_METHOD_NAMES = frozenset({
"KafkaListener",
"RabbitListener",
"JmsListener",
"StreamListener",
})
_TYPE_KINDS = {
"class_declaration": "class",
"interface_declaration": "interface",
"enum_declaration": "enum",
"record_declaration": "record",
"annotation_type_declaration": "annotation",
}
# For `new Super() { }` when `Super` is not declared in the same compilation unit:
# treat these simple names as interfaces (implements) vs classes (extends).
_ANON_SUPER_AS_INTERFACE: frozenset[str] = frozenset({
"Runnable", "Callable", "Comparable", "Iterable", "Iterator", "AutoCloseable",
"Closeable", "Flushable", "Readable", "Appendable", "Cloneable", "Serializable",
"Externalizable", "InvocationHandler", "ThreadFactory", "PrivilegedAction",
"PrivilegedExceptionAction", "Comparator", "Consumer", "BiConsumer", "Supplier",
"Function", "BiFunction", "UnaryOperator", "BinaryOperator", "Predicate",
"BiPredicate", "IntConsumer", "LongConsumer", "DoubleConsumer", "IntFunction",
"LongFunction", "DoubleFunction", "IntPredicate", "LongPredicate", "DoublePredicate",
"IntSupplier", "LongSupplier", "DoubleSupplier", "ToIntFunction", "ToLongFunction",
"ToDoubleFunction", "Stream", "BaseStream", "Collector", "Observer", "Observable",
"List", "Set", "Map", "Queue", "Deque", "Collection", "EventListener",
"ActionListener", "MouseListener", "KeyListener", "WindowListener", "RowMapper",
"ResultSetExtractor", "PreparedStatementCreator", "CallableStatementCallback",
})
@lru_cache(maxsize=1)
def _parser() -> Parser:
lang = Language(_ts_java.language())
return Parser(lang)
# ---------- dataclasses ----------
@dataclass
class AnnotationRef:
name: str # simple (last segment); e.g. "RestController"
qualified: str # raw source text, e.g. "org.springframework.web.bind.annotation.RestController"
arguments: dict[str, str] = field(default_factory=dict)
# Argument origin by key: "enum" | "string".
argument_kinds: dict[str, str] = field(default_factory=dict)
# Populated for `@CodebaseCapabilities({@CodebaseCapability("a"), ...})` — inner values.
container_capability_values: tuple[str, ...] = field(default_factory=tuple)
# Entry-aligned with `container_capability_values`; each value is "enum" | "string".
container_capability_kinds: tuple[str, ...] = field(default_factory=tuple)
@dataclass
class FieldDecl:
name: str
type_name: str # simple name, generics + arrays stripped
type_raw: str # original text
modifiers: list[str] = field(default_factory=list)
annotations: list[AnnotationRef] = field(default_factory=list)
start_byte: int = 0
end_byte: int = 0
start_line: int = 0
end_line: int = 0
@dataclass
class ParamDecl:
name: str
type_name: str
type_raw: str
annotations: list[AnnotationRef] = field(default_factory=list)
@dataclass
class FileImports:
"""Per-compilation-unit import maps used by call-site resolution."""
explicit: dict[str, str] = field(default_factory=dict) # SimpleType -> type FQN
static_methods: dict[str, str] = field(default_factory=dict) # simple method name -> "pkg.Type.method"
static_wildcards: list[str] = field(default_factory=list) # type FQNs for `import static T.*`
@dataclass
class CallSite:
"""A single static call site inside a method or constructor body."""
caller_fqn: str # type_fqn#signature (matches Symbol.fqn for method nodes)
receiver_expr: str # raw receiver text; "" for bare calls
callee_simple: str # method name or "<init>"
arg_count: int # -1 for method references (unknown)
is_static_call: bool
is_constructor: bool
in_lambda: bool
line: int
byte: int
chained_method_reference: bool = False # true for ``expr::name`` where expr is a call chain
@dataclass
class MethodDecl:
name: str
return_type: str # simple name; "" for constructors / void kept as "void"
is_constructor: bool
parameters: list[ParamDecl] = field(default_factory=list)
modifiers: list[str] = field(default_factory=list)
annotations: list[AnnotationRef] = field(default_factory=list)
signature: str = "" # "name(T1,T2)"
start_byte: int = 0
end_byte: int = 0
start_line: int = 0
end_line: int = 0
call_sites: list[CallSite] = field(default_factory=list)
# Ordered (name, simple_type_name) from `local_variable_declaration` in body.
local_vars: list[tuple[str, str]] = field(default_factory=list)
routes: list["RouteDecl"] = field(default_factory=list)
outgoing_calls: list["OutgoingCallDecl"] = field(default_factory=list)
@dataclass
class RouteDecl:
"""Extracted route declaration anchored on a method (B2a).
`method_fqn` matches graph Symbol.fqn (`type.pkg.Type#name(T1,T2)`).
"""
method_fqn: str
method_sig: str
kind: str
framework: str
http_method: str
path: str
topic: str
broker: str
feign_name: str
feign_url: str
resolution_strategy: str
confidence: float
resolved: bool
filename: str
start_line: int
end_line: int
# brownfield / B2a composition (graph_enrich.resolve_routes_for_method); not a Kuzu column.
route_source_layer: str = "builtin"
@dataclass
class OutgoingCallDecl:
method_fqn: str
method_sig: str
client_kind: str
channel: str
feign_target_name: str
feign_target_url: str
path_template_call: str
method_call: str
topic_call: str
broker_call: str
raw_uri: str
raw_topic: str
resolution_strategy: str
confidence_base: float
resolved: bool
filename: str
start_line: int
end_line: int
@dataclass
class TypeDecl:
name: str
kind: str
fqn: str
modifiers: list[str] = field(default_factory=list)
annotations: list[AnnotationRef] = field(default_factory=list)
extends: list[str] = field(default_factory=list) # simple names
implements: list[str] = field(default_factory=list)
fields: list[FieldDecl] = field(default_factory=list)
methods: list[MethodDecl] = field(default_factory=list)
nested: list["TypeDecl"] = field(default_factory=list)
start_byte: int = 0
end_byte: int = 0
start_line: int = 0
end_line: int = 0
outer_fqn: str | None = None # None for top-level
capabilities: list[str] = field(default_factory=list)
@dataclass
class JavaFileAst:
package: str
imports: list[str] # raw, as written (may include ".*" suffix)
wildcard_imports: list[str] # e.g. "java.util"
explicit_imports: dict[str, str] # "List" -> "java.util.List"
top_level_types: list[TypeDecl]
all_types: list[TypeDecl] # flat, includes nested
parse_error: bool = False
source_bytes: int = 0
file_imports: FileImports = field(default_factory=FileImports)
routes_skipped_unresolved: int = 0
@dataclass
class _ParseCtx:
routes_skipped_unresolved: int = 0
verbose: bool = False
# ---------- helpers ----------
def _txt(node: Node, src: bytes) -> str:
return src[node.start_byte:node.end_byte].decode("utf-8", errors="replace")
def _annotation_name(node: Node, src: bytes) -> tuple[str, str]:
"""Extract ('simple', 'qualified-as-written') from an annotation node."""
name_node = node.child_by_field_name("name")
qualified = _txt(name_node, src) if name_node is not None else _txt(node, src).lstrip("@").split("(", 1)[0]
simple = qualified.rsplit(".", 1)[-1]
return simple, qualified
def _string_literal_value(node: Node, src: bytes) -> str | None:
if node.type != "string_literal":
return None
for ch in node.children:
if ch.type == "string_fragment":
return _txt(ch, src)
return None
def _annotation_value(
node: Node, src: bytes
) -> tuple[str | None, str | None]:
"""Extract annotation value and its kind.
Returns `(value, kind)` where kind is one of "enum" / "string".
Enum-like expressions are normalized to the terminal constant name:
`CodebaseRoleKind.SERVICE` -> `SERVICE`.
"""
if node.type == "element_value" and node.named_children:
return _annotation_value(node.named_children[0], src)
sval = _string_literal_value(node, src)
if sval is not None:
return sval, "string"
if node.type in ("identifier", "scoped_identifier", "field_access"):
raw = _txt(node, src).strip()
if not raw:
return None, None
return raw.rsplit(".", 1)[-1], "enum"
return None, None
def _parse_annotation_argument_list(
alist: Node, src: bytes
) -> tuple[dict[str, str], dict[str, str]]:
"""Map argument names to normalized enum/string values and value kinds."""
out: dict[str, str] = {}
kinds: dict[str, str] = {}
for ch in alist.named_children:
if ch.type == "element_value_pair":
key_node = ch.child_by_field_name("key")
val_node = ch.child_by_field_name("value")
if key_node is None:
ids = [c for c in ch.children if c.type == "identifier"]
key_node = ids[0] if ids else None
if val_node is None:
for c in reversed(ch.named_children):
if c is not key_node:
val_node = c
break
if key_node is None or val_node is None:
continue
key = _txt(key_node, src)
val, kind = _annotation_value(val_node, src)
if val is not None and kind is not None:
out[key] = val
kinds[key] = kind
else:
v, kind = _annotation_value(ch, src)
if v is not None and kind is not None and "value" not in out:
out["value"] = v
kinds["value"] = kind
return out, kinds
def _codebase_capability_values_from_array(
ann_node: Node, src: bytes
) -> tuple[tuple[str, ...], tuple[str, ...]]:
found: list[str] = []
kinds: list[str] = []
def visit(n: Node) -> None:
if n.type == "annotation":
name_node = n.child_by_field_name("name")
n_simple = _txt(name_node, src).rsplit(".", 1)[-1] if name_node is not None else ""
if n_simple == "CodebaseCapability":
for c in n.children:
if c.type == "annotation_argument_list":
m, mk = _parse_annotation_argument_list(c, src)
v = m.get("value")
k = mk.get("value")
if v is not None and k is not None:
found.append(v)
kinds.append(k)
for c in n.children:
visit(c)
visit(ann_node)
return tuple(found), tuple(kinds)
def _parse_annotation_ref_node(node: Node, src: bytes) -> AnnotationRef:
"""Build `AnnotationRef` for a `marker_annotation` or `annotation` node."""
simple, qualified = _annotation_name(node, src)
t = node.type
if t == "marker_annotation":
return AnnotationRef(name=simple, qualified=qualified, arguments={})
args: dict[str, str] = {}
arg_kinds: dict[str, str] = {}
container: tuple[str, ...] = ()
container_kinds: tuple[str, ...] = ()
alist = node.child_by_field_name("arguments")
if alist is None:
for ch in node.children:
if ch.type == "annotation_argument_list":
alist = ch
break
if alist is not None:
args, arg_kinds = _parse_annotation_argument_list(alist, src)
if simple == "CodebaseCapabilities" and alist is not None:
container, container_kinds = _codebase_capability_values_from_array(node, src)
return AnnotationRef(
name=simple,
qualified=qualified,
arguments=args,
argument_kinds=arg_kinds,
container_capability_values=container,
container_capability_kinds=container_kinds,
)
_MODIFIER_KEYWORDS = frozenset({
"public",
"private",
"protected",
"static",
"final",
"abstract",
"default",
"synchronized",
"native",
"transient",
"volatile",
"strictfp",
"sealed",
"non-sealed",
})
def _find_modifiers_child(parent: Node) -> Node | None:
"""tree-sitter-java exposes `modifiers` as an unnamed-field child node."""
for ch in parent.children:
if ch.type == "modifiers":
return ch
return None
def _collect_annotations_and_modifiers(
parent: Node, src: bytes
) -> tuple[list[str], list[AnnotationRef]]:
"""Extract modifiers + annotations from the `modifiers` sibling of `parent`."""
mods_node = _find_modifiers_child(parent)
if mods_node is None:
return [], []
mods: list[str] = []
anns: list[AnnotationRef] = []
for child in mods_node.children:
t = child.type
if t in ("marker_annotation", "annotation"):
anns.append(_parse_annotation_ref_node(child, src))
elif t in _MODIFIER_KEYWORDS:
mods.append(t)
return mods, anns
def _strip_type_to_simple(type_node: Node, src: bytes) -> str:
"""Reduce any type expression to its head simple name.
Examples:
List<String> -> List
java.util.List<Foo> -> List
Map<String,Integer>[][] -> Map
String[] -> String
void -> void
int -> int
"""
t = type_node.type
if t == "generic_type":
# first child is the name part (type_identifier | scoped_type_identifier)
for ch in type_node.children:
if ch.type in ("type_identifier", "scoped_type_identifier"):
return _strip_type_to_simple(ch, src)
return _txt(type_node, src).split("<", 1)[0].rsplit(".", 1)[-1]
if t == "array_type":
elem = type_node.child_by_field_name("element") or (type_node.named_children[0] if type_node.named_children else None)
if elem is not None:
return _strip_type_to_simple(elem, src)
return _txt(type_node, src).split("[", 1)[0]
if t == "scoped_type_identifier":
return _txt(type_node, src).rsplit(".", 1)[-1]
if t == "type_identifier":
return _txt(type_node, src)
# primitive / void / anything else: return raw
return _txt(type_node, src)
def _collect_type_list(node: Node, src: bytes) -> list[str]:
"""Turn an `interface_type_list` / `type_list` / single type into simple names."""
out: list[str] = []
if node.type in ("type_list", "interface_type_list", "super_interfaces", "extends_interfaces"):
for ch in node.named_children:
if ch.type == "type_list" or ch.type == "interface_type_list":
out.extend(_collect_type_list(ch, src))
else:
out.append(_strip_type_to_simple(ch, src))
return out
return [_strip_type_to_simple(node, src)]
def _extends_of(type_node: Node, src: bytes) -> list[str]:
out: list[str] = []
# class: superclass field; interface: extends_interfaces field
sc = type_node.child_by_field_name("superclass")
if sc is not None:
# `superclass` node has children like `extends` + type
for ch in sc.named_children:
out.append(_strip_type_to_simple(ch, src))
ei = type_node.child_by_field_name("interfaces")
# for interface declarations, the extends clause uses field "extends" via `extends_interfaces`
if ei is None:
for ch in type_node.children:
if ch.type in ("extends_interfaces",):
for sub in ch.named_children:
if sub.type in ("type_list", "interface_type_list"):
out.extend(_collect_type_list(sub, src))
else:
out.append(_strip_type_to_simple(sub, src))
return out
def _implements_of(type_node: Node, src: bytes) -> list[str]:
out: list[str] = []
si = type_node.child_by_field_name("interfaces")
if si is not None:
for ch in si.named_children:
if ch.type in ("type_list", "interface_type_list"):
out.extend(_collect_type_list(ch, src))
else:
out.append(_strip_type_to_simple(ch, src))
return out
# fallback for grammars exposing super_interfaces unnamed
for ch in type_node.children:
if ch.type == "super_interfaces":
for sub in ch.named_children:
if sub.type in ("type_list", "interface_type_list"):
out.extend(_collect_type_list(sub, src))
else:
out.append(_strip_type_to_simple(sub, src))
return out
def _iter_body_members(body: Node) -> Iterable[Node]:
if body is None:
return []
return [c for c in body.named_children]
def _pre_scan_declared_type_kinds(root: Node, src: bytes) -> dict[str, str]:
"""Map simple type name -> kind for declarations in this CU (for anonymous super)."""
out: dict[str, str] = {}
def visit(n: Node) -> None:
t = n.type
if t in _TYPE_KINDS:
nn = n.child_by_field_name("name")
if nn is not None:
nm = _txt(nn, src)
if nm and nm != "<anon>":
out[nm] = _TYPE_KINDS[t]
for c in n.children:
visit(c)
visit(root)
return out
def _anonymous_extends_implements(
super_simple: str, kind_by_simple: dict[str, str],
) -> tuple[list[str], list[str]]:
"""Java: anonymous extends class X, or extends Object + implements I."""
k = kind_by_simple.get(super_simple)
if k == "interface":
return [], [super_simple]
if k in ("class", "enum", "record"):
return [super_simple], []
if super_simple in _ANON_SUPER_AS_INTERFACE:
return [], [super_simple]
return [super_simple], []
def _parse_type_body_into_decl(
body: Node,
src: bytes,
*,
package: str,
fqn: str,
kind: str,
extends: list[str],
implements: list[str],
modifiers: list[str],
annotations: list[AnnotationRef],
kind_by_simple: dict[str, str],
start_byte: int,
end_byte: int,
start_line: int,
end_line: int,
outer_fqn: str | None,
enclosing_type_node: Node | None,
file_rel: str,
ctx: _ParseCtx,
) -> TypeDecl:
"""Shared member parsing for named types and synthetic anonymous classes."""
fields: list[FieldDecl] = []
methods: list[MethodDecl] = []
nested: list[TypeDecl] = []
anon_nested: list[TypeDecl] = []
for ch in _iter_body_members(body):
if ch.type == "field_declaration":
fields.extend(_parse_field(ch, src))
elif ch.type == "method_declaration":
m, anons = _parse_method(
ch, src, is_constructor=False, type_fqn=fqn,
package=package, kind_by_simple=kind_by_simple,
ctx=ctx,
enclosing_type_node=enclosing_type_node,
type_kind=kind,
type_anns=annotations,
file_rel=file_rel,
)
methods.append(m)
anon_nested.extend(anons)
elif ch.type == "constructor_declaration":
m, anons = _parse_method(
ch, src, is_constructor=True, type_fqn=fqn,
package=package, kind_by_simple=kind_by_simple,
ctx=ctx,
enclosing_type_node=enclosing_type_node,
type_kind=kind,
type_anns=annotations,
file_rel=file_rel,
)
methods.append(m)
anon_nested.extend(anons)
elif ch.type in _TYPE_KINDS:
nested.append(
_parse_type(
ch, src,
package=package, outer_fqn=fqn, kind_by_simple=kind_by_simple,
file_rel=file_rel, ctx=ctx,
),
)
nested.extend(anon_nested)
ann_names_set = {a.name for a in annotations}
if (
kind in ("class", "enum")
and not any(m.is_constructor for m in methods)
and not (_LOMBOK_RAC & ann_names_set)
):
default_ctor_sig = "<init>()"
methods.append(
MethodDecl(
name="<init>",
return_type="",
is_constructor=True,
parameters=[],
modifiers=[],
annotations=[],
signature=default_ctor_sig,
start_byte=start_byte,
end_byte=start_byte,
start_line=start_line,
end_line=start_line,
call_sites=[],
local_vars=[],
)
)
name = fqn.rsplit(".", 1)[-1]
type_decl = TypeDecl(
name=name,
kind=kind,
fqn=fqn,
modifiers=modifiers,
annotations=annotations,
extends=extends,
implements=implements,
fields=fields,
methods=methods,
nested=nested,
start_byte=start_byte,
end_byte=end_byte,
start_line=start_line,
end_line=end_line,
outer_fqn=outer_fqn,
)
type_decl.capabilities = infer_capabilities_for_type(type_decl)
return type_decl
def _parse_synthetic_anonymous_type(
object_creation: Node,
class_body: Node,
src: bytes,
*,
package: str,
host_type_fqn: str,
kind_by_simple: dict[str, str],
file_rel: str,
ctx: _ParseCtx,
) -> TypeDecl:
label = f"<anon:{object_creation.start_byte}>"
fqn = f"{host_type_fqn}.{label}"
type_node = object_creation.child_by_field_name("type")
super_simple = _strip_type_to_simple(type_node, src) if type_node is not None else "Object"
extends, implements = _anonymous_extends_implements(super_simple, kind_by_simple)
return _parse_type_body_into_decl(
class_body,
src,
package=package,
fqn=fqn,
kind="class",
extends=extends,
implements=implements,
modifiers=[],
annotations=[],
kind_by_simple=kind_by_simple,
start_byte=object_creation.start_byte,
end_byte=object_creation.end_byte,
start_line=object_creation.start_point[0] + 1,
end_line=object_creation.end_point[0] + 1,
outer_fqn=host_type_fqn,
enclosing_type_node=None,
file_rel=file_rel,
ctx=ctx,
)
def _extract_anonymous_types_in_subtree(
root: Node,
src: bytes,
*,
package: str,
host_type_fqn: str,
kind_by_simple: dict[str, str],
file_rel: str,
ctx: _ParseCtx,
) -> list[TypeDecl]:
"""Find every `new T() { }` with class_body under root; skip bodies (parsed separately)."""
found: list[TypeDecl] = []
def visit(n: Node) -> None:
if n.type == "object_creation_expression":
class_body: Node | None = None
for ch in n.named_children:
if ch.type == "class_body":
class_body = ch
break
if class_body is not None:
found.append(
_parse_synthetic_anonymous_type(
n, class_body, src,
package=package, host_type_fqn=host_type_fqn, kind_by_simple=kind_by_simple,
file_rel=file_rel,
ctx=ctx,
)
)
for ch in n.named_children:
if ch.type == "class_body":
continue
visit(ch)
return
for ch in n.children:
visit(ch)
visit(root)
return found
def _import_declaration_is_static(node: Node, src: bytes) -> bool:
for c in node.children:
if c.type == "static" and _txt(c, src) == "static":
return True
return False
def _arg_list_count(arg_list: Node | None) -> int:
if arg_list is None:
return 0
return len(arg_list.named_children)
def _infer_static_method_invocation(obj: Node | None, src: bytes) -> bool:
"""Heuristic: ClassName.method() vs instance.method().
TODO: Uppercase ``identifier`` receivers are treated as types; the graph
builder may override via the per-method scope table when the name is a local.
"""
if obj is None:
return False
if obj.type in ("type_identifier", "scoped_type_identifier"):
return True
if obj.type == "this" or obj.type == "super":
return False
if obj.type == "identifier":
name = _txt(obj, src)
return len(name) > 0 and name[0].isupper()
return False
def _collect_local_vars(body: Node, src: bytes) -> list[tuple[str, str]]:
"""Declaration order: (variable name, head simple type name)."""
out: list[tuple[str, str]] = []
if body is None:
return out
def visit(n: Node) -> None:
if n.type == "local_variable_declaration":
type_node = n.child_by_field_name("type")
if type_node is None:
return
t_simple = _strip_type_to_simple(type_node, src)
for ch in n.named_children:
if ch.type != "variable_declarator":
continue
name_node = ch.child_by_field_name("name")
if name_node is not None:
out.append((_txt(name_node, src), t_simple))
return
for c in n.children:
visit(c)
visit(body)
return out
def _collect_call_sites(
body: Node,
src: bytes,
*,
caller_fqn: str,
in_lambda: bool,
) -> list[CallSite]:
"""Walk a block body and collect CallSite records (attributed to caller_fqn)."""
out: list[CallSite] = []
def add_site(
*,
receiver_expr: str,
callee_simple: str,
arg_count: int,
is_static_call: bool,
is_constructor: bool,
line: int,
byte: int,
lam: bool,
chained_method_reference: bool = False,
) -> None:
out.append(
CallSite(
caller_fqn=caller_fqn,
receiver_expr=receiver_expr,
callee_simple=callee_simple,
arg_count=arg_count,
is_static_call=is_static_call,
is_constructor=is_constructor,
in_lambda=lam,
chained_method_reference=chained_method_reference,
line=line,
byte=byte,
)
)
def visit(n: Node, lam: bool) -> None:
t = n.type
if t == "lambda_expression":
body_node = n.child_by_field_name("body")
if body_node is not None:
visit(body_node, True)
return
if t == "object_creation_expression":
type_node = n.child_by_field_name("type")
args = n.child_by_field_name("arguments")
if type_node is not None:
recv = _txt(type_node, src)
line = n.start_point[0] + 1
add_site(
receiver_expr=recv,
callee_simple="<init>",