-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegraph_java.py
More file actions
9471 lines (9003 loc) · 452 KB
/
Copy pathcodegraph_java.py
File metadata and controls
9471 lines (9003 loc) · 452 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
# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Piyush Katariya
#
# @author Piyush Katariya
"""codegraph_java.py -- parse a Java tree into a graph and query it.
Targets Java 25 (LTS, GA 2025-09-16). Parses with tree-sitter-java.
SpotBugs, Error Prone and the compiler already catch the single-method mistakes,
so this does not compete with them. What it adds is the shape no per-file
checker can see: which resource is opened in one class and closed in another,
which two functions take the same two locks in opposite orders, which reflective
call is reachable from a public entry point and therefore bounds your
`--add-opens` list and your native-image reflect-config.
Four Java facts this bakes in, because getting any of them wrong dates the tool:
* JEP 491 (JDK 24) REMOVED virtual-thread pinning by `synchronized` and by
`Object.wait`, and removed `-Djdk.tracePinnedThreads` with it. On Java 24+ a
`synchronized` block inside a virtual thread is a NON-FINDING and is not
reported as one. What still pins is JNI and an FFM downcall, so the pinning
query targets `java.lang.foreign`, `System.loadLibrary` and `native` methods
reachable from a virtual-thread root -- and says in as many words that
synchronized is excluded.
* A virtual thread dies with its task, so a ThreadLocal it set cannot leak.
Only a POOLED carrier can leak one, which is why `is_pooled_executor_root` is
a separate column from `is_executor_root` rather than a flag on it.
* Compact source files (JEP 512) have no class declaration at all. A file whose
entire content is `void main() {}` parses to `program > method_declaration`,
its `owner_type` is empty, and it is a real entry point. Nothing here requires
a declaring type.
* `sealed`, `non-sealed`, `permits`, `record`, `yield`, `when` and `var` are
CONTEXTUAL keywords and are legal identifiers. They are read from the grammar,
never from a regex over the token.
One grammar limitation, recorded in `meta.grammar_note` so nobody has to read
this docstring to find it: tree-sitter-java 0.23.5 predates module import
declarations (JEP 511, final in 25), so `import module java.base;` parses as an
ERROR and raises `files.n_parse_errors` by one -- through no fault of the code
being analysed. Those imports are recovered by a text scan into
`jpms_directives` and the `parse-coverage` query says so.
Usage:
python3 codegraph_java.py /path/to/repo --report
python3 codegraph_java.py /path/to/repo --list
python3 codegraph_java.py --deps"""
__author__ = "Piyush Katariya"
__license__ = "MIT"
# ---------------------------------------------------------------------------
# Self-contained on purpose: this one file is the whole tool. Copy it anywhere
# and run it. Requires CPython 3.14+ and its bundled SQLite 3.37 or newer --
# 3.37 for STRICT tables, which the schema uses throughout.
#
# Dependencies are declared in DEPS with a reason and installed with
# --install-deps. A grammar-backed analyzer REFUSES to run without its grammar:
# there is no regex fallback, and an empty graph reads exactly like a clean
# repository. codegraph_python.py and codegraph_c.py need no grammar at all.
#
# Nothing here is imported from a sibling file, and the schema below is this
# language's own. Other analyzers in this repo differ wherever their languages
# differ. Edit this file directly.
# ---------------------------------------------------------------------------
import sys as _sys
if _sys.version_info < (3, 14): # noqa: E402
_sys.exit(
"codegraph needs CPython 3.14 or newer; this is %d.%d.%d at %s.\n"
"The schema uses STRICT tables (SQLite 3.37+) and codegraph_python.py\n"
"parses with the running interpreter's own grammar, so on an older\n"
"Python it would silently see less of a repository than is there.\n"
"The other analyzers share this floor rather than each having one."
% (_sys.version_info[0], _sys.version_info[1], _sys.version_info[2],
_sys.executable))
import argparse
import array
import csv
import hashlib
import importlib
import importlib.util
import os
import re
import sqlite3
import stat
import subprocess
import sys
import time
from dataclasses import dataclass
from dataclasses import dataclass, field
from dataclasses import dataclass, field as dc_field
from typing import Any, Callable, Iterable, Iterator, Optional
from typing import Any, Callable, Iterable, Optional, Sequence
from typing import Any, Callable, Iterator, Optional
from typing import Any, Optional
# ==========================================================================
# _deps.py
# Dependency declaration and optional installation.
#
# Every language analyzer declares exactly what it needs and why. Nothing is
# installed behind the user's back: `ensure()` only reports, and only
# `--install-deps` actually runs pip.
#
# An analyzer must still RUN with nothing installed. A missing grammar downgrades
# the parse from a syntax tree to regex scanning; it never aborts the run. Which
# mode was used is recorded in the `meta` table so a query result can never be
# mistaken for something more precise than it is.
# ==========================================================================
@dataclass(frozen=True)
class Dep:
"""One importable module and the pip requirement that provides it."""
module: str
pip: str
why: str
optional: bool = True
#: Minimum version we have actually verified against, for the record.
verified: str = ""
@property
def present(self) -> bool:
try:
return importlib.util.find_spec(self.module) is not None
except (ImportError, ValueError):
return False
def version(self) -> str:
try:
mod = importlib.import_module(self.module)
except Exception:
return ""
for attr in ("__version__", "VERSION", "version"):
v = getattr(mod, attr, None)
if isinstance(v, str):
return v
if isinstance(v, tuple):
return ".".join(str(p) for p in v)
try:
from importlib.metadata import version as _v
return _v(self.pip.split("[")[0].split("=")[0].split(">")[0])
except Exception:
return "?"
@dataclass
class DepSet:
"""The dependency surface of one analyzer."""
lang: str
deps: list[Dep] = field(default_factory=list)
def missing(self) -> list[Dep]:
return [d for d in self.deps if not d.present]
def present(self) -> list[Dep]:
return [d for d in self.deps if d.present]
def required_missing(self) -> list[Dep]:
return [d for d in self.missing() if not d.optional]
# -- reporting ---------------------------------------------------------
def describe(self) -> str:
out = ["dependencies for codegraph-%s:" % self.lang]
if not self.deps:
out.append(" (none -- pure standard library)")
return "\n".join(out)
for d in self.deps:
mark = "ok " if d.present else ("MISSING" if not d.optional else "absent ")
ver = d.version() if d.present else ""
tag = "required" if not d.optional else "optional"
out.append(" [%-7s] %-28s %-10s %s" % (mark, d.pip, ver, tag))
out.append(" %s" % d.why)
if d.verified:
out.append(" verified against %s" % d.verified)
miss = self.missing()
if miss:
out.append("")
out.append("install with:")
out.append(" %s" % self.pip_command())
out.append("or let the tool do it:")
out.append(" python3 %s --install-deps" % _script_name())
return "\n".join(out)
def pip_command(self, missing_only: bool = True) -> str:
want = self.missing() if missing_only else self.deps
if not want:
return "(nothing to install)"
return "%s -m pip install %s" % (
sys.executable, " ".join(sorted(d.pip for d in want)))
# -- installation ------------------------------------------------------
def install(self, quiet: bool = False, only_binary: bool = True) -> bool:
"""pip-install everything missing. Returns True if all present after."""
want = self.missing()
if not want:
if not quiet:
print("all dependencies already present")
return True
cmd = [sys.executable, "-m", "pip", "install"]
if only_binary:
# Source builds of a tree-sitter grammar need a C toolchain and
# take minutes. If there is no wheel we would rather fail loudly
# and fall back to regex than silently start compiling.
cmd += ["--only-binary", ":all:"]
cmd += sorted(d.pip for d in want)
if not quiet:
print("running: %s" % " ".join(cmd))
proc = subprocess.run(cmd, capture_output=True, text=True)
rc = proc.returncode
out = (proc.stdout or "") + (proc.stderr or "")
if not quiet and out.strip():
print(out.rstrip())
if rc != 0 and "externally-managed-environment" in out:
# A Homebrew or distro Python refuses to be written to (PEP 668).
# Telling the user to pass --break-system-packages would be
# advising them to damage the interpreter their OS depends on.
print(_pep668_advice(self))
return False
if rc != 0 and only_binary:
if not quiet:
print("no wheel available for this interpreter; "
"retrying without --only-binary (needs a C compiler)")
rc = subprocess.call([c for c in cmd
if c not in ("--only-binary", ":all:")])
importlib.invalidate_caches()
still = self.missing()
if still and not quiet:
print("still missing: %s" % ", ".join(d.pip for d in still))
print("the analyzer will run in degraded (regex) mode")
return not still
def _script_name() -> str:
import os
return os.path.basename(sys.argv[0] or "codegraph_<lang>.py")
def _pep668_advice(ds: "DepSet") -> str:
return (
"\nthis Python is externally managed (PEP 668) -- pip will not write "
"to it,\nand overriding that with --break-system-packages can break "
"the interpreter\nyour OS depends on. Use a virtual environment "
"instead:\n\n"
" python3 -m venv .venv\n"
" .venv/bin/pip install %s\n"
" .venv/bin/python %s <repo>\n\n"
"There is no way to run without the grammar: an analyzer with no\n"
"parser refuses rather than emitting an empty graph, because an\n"
"empty graph reads exactly like a clean repository."
% (" ".join(sorted(d.pip for d in ds.missing())), _script_name()))
TREE_SITTER = Dep(
module="tree_sitter",
pip="tree-sitter>=0.25",
why="incremental parser runtime. Without it a grammar-backed analyzer "
"will NOT run -- there is no regex fallback, because an empty graph "
"reads exactly like a clean repository",
verified="0.26.0 (cp314 macOS arm64 wheel)",
)
def grammar(lang: str, module: str, pip: str, verified: str = "") -> Dep:
return Dep(
module=module,
pip=pip,
why="tree-sitter grammar for %s. Required: without it this analyzer "
"refuses to run rather than produce an empty graph" % lang,
verified=verified,
)
# ==========================================================================
# _ts.py
# tree-sitter loading, with an honest fallback.
#
# Two rules govern this module.
#
# 1. A missing grammar is not an error. The analyzer degrades to regex scanning
# and says so. A tool that refuses to start is worth less than a tool that
# tells you which of its answers are approximate.
#
# 2. The parse mode is recorded, per run, in the `meta` table. Every report
# prints it. `n_parse_errors` on `files` counts tree-sitter ERROR nodes, so a
# file the grammar could not handle is visible rather than silently thin.
#
# The py-tree-sitter API changed incompatibly at 0.22/0.23 (`Language(ptr, name)`
# became `Language(ptr)`, `Parser.set_language()` became the `parser.language`
# property). Everything here targets the >=0.25 API and probes for the old one so
# an older wheel already on the box does not produce a confusing AttributeError.
# ==========================================================================
MODE_TREE_SITTER = "tree-sitter"
MODE_REGEX = "regex-fallback"
MODE_NATIVE = "native-ast"
MODE_BRACE_SCAN = "brace-scan"
@dataclass
class ParserHandle:
"""A parser plus the story of how we got it."""
mode: str
parser: Any = None
language: Any = None
lang_name: str = ""
grammar_pip: str = ""
grammar_version: str = ""
runtime_version: str = ""
note: str = ""
@property
def ok(self) -> bool:
return self.parser is not None
def parse(self, src: bytes):
return self.parser.parse(src)
def banner(self) -> str:
if self.mode == MODE_TREE_SITTER:
return "parser: tree-sitter %s + %s %s" % (
self.runtime_version, self.grammar_pip, self.grammar_version)
if self.mode == MODE_NATIVE:
return "parser: %s" % self.note
return "parser: REGEX FALLBACK (%s) -- spans and nesting are approximate" % self.note
def load(lang_name: str, grammar_module: str, grammar_pip: str,
symbol: str = "language") -> ParserHandle:
"""Build a tree-sitter parser for `lang_name`, or explain why not."""
try:
ts = importlib.import_module("tree_sitter")
except ImportError:
return ParserHandle(mode=MODE_REGEX, lang_name=lang_name,
grammar_pip=grammar_pip,
note="tree_sitter not installed")
try:
gm = importlib.import_module(grammar_module)
except ImportError:
return ParserHandle(mode=MODE_REGEX, lang_name=lang_name,
grammar_pip=grammar_pip,
note="%s not installed" % grammar_pip)
fn = getattr(gm, symbol, None) or getattr(gm, "language", None)
if fn is None:
return ParserHandle(mode=MODE_REGEX, lang_name=lang_name,
grammar_pip=grammar_pip,
note="%s exposes no %s()" % (grammar_module, symbol))
try:
ptr = fn()
except Exception as exc: # pragma: no cover
return ParserHandle(mode=MODE_REGEX, lang_name=lang_name,
grammar_pip=grammar_pip,
note="%s() raised %s" % (symbol, exc))
language = _make_language(ts, ptr, lang_name)
if language is None:
return ParserHandle(mode=MODE_REGEX, lang_name=lang_name,
grammar_pip=grammar_pip,
note="ABI mismatch between tree-sitter runtime and "
"%s -- upgrade both together" % grammar_pip)
abi_note = _check_abi(ts, language, grammar_pip)
if abi_note:
return ParserHandle(mode=MODE_REGEX, lang_name=lang_name,
grammar_pip=grammar_pip, note=abi_note)
parser = _make_parser(ts, language)
if parser is None:
return ParserHandle(mode=MODE_REGEX, lang_name=lang_name,
grammar_pip=grammar_pip,
note="could not attach language to parser")
return ParserHandle(
mode=MODE_TREE_SITTER, parser=parser, language=language,
lang_name=lang_name, grammar_pip=grammar_pip,
grammar_version=_ver(gm, grammar_pip),
runtime_version=_ver(ts, "tree-sitter"),
)
def _make_language(ts: Any, ptr: Any, name: str) -> Optional[Any]:
if isinstance(ptr, getattr(ts, "Language", ())):
return ptr
for args in ((ptr,), (ptr, name)): # >=0.22 first, then legacy
try:
return ts.Language(*args)
except (TypeError, ValueError):
continue
except Exception:
return None
return None
def _check_abi(ts: Any, language: Any, grammar_pip: str) -> str:
"""Refuse a grammar the runtime cannot speak, with a message that says why.
Several grammars have not been rebuilt in well over a year and sit at an
older ABI than the runtime's floor. When that floor rises, construction
fails somewhere deep in the C extension with nothing naming the culprit.
Checking here turns that into one sentence naming the package and the two
numbers involved.
"""
abi = getattr(language, "abi_version", None)
if abi is None:
abi = getattr(language, "version", None)
if abi is None:
return ""
lo = getattr(ts, "MIN_COMPATIBLE_LANGUAGE_VERSION", None)
hi = getattr(ts, "LANGUAGE_VERSION", None)
if lo is not None and abi < lo:
return ("%s is ABI %d but this tree-sitter runtime accepts %d-%s; "
"upgrade the grammar or pin tree-sitter lower"
% (grammar_pip, abi, lo, hi if hi is not None else "?"))
if hi is not None and abi > hi:
return ("%s is ABI %d, newer than this tree-sitter runtime supports "
"(max %d); upgrade tree-sitter" % (grammar_pip, abi, hi))
return ""
def _make_parser(ts: Any, language: Any) -> Optional[Any]:
try: # >=0.22
return ts.Parser(language)
except TypeError:
pass
except Exception:
return None
try:
p = ts.Parser()
try:
p.language = language # >=0.22 property
except AttributeError:
p.set_language(language) # <=0.21
return p
except Exception: # pragma: no cover
return None
def _ver(mod: Any, pip_name: str) -> str:
v = getattr(mod, "__version__", None)
if isinstance(v, str):
return v
try:
from importlib.metadata import version
return version(pip_name.split(">")[0].split("=")[0])
except Exception:
return "?"
def walk(node: Any) -> Iterator[Any]:
"""Every node in the subtree, parents before children.
Uses an explicit stack rather than recursion: a minified bundle or a
generated parser table nests deep enough to blow the Python stack, and a
RecursionError halfway through a repo scan is indistinguishable from a
crash.
"""
stack = [node]
while stack:
n = stack.pop()
yield n
stack.extend(reversed(n.children))
def walk_cursor(node: Any) -> Iterator[tuple[Any, int]]:
"""Every node with its depth, using a TreeCursor (much faster than
touching `.children`, which materialises a Python list per node)."""
cursor = node.walk()
depth = 0
while True:
yield cursor.node, depth
if cursor.goto_first_child():
depth += 1
continue
while not cursor.goto_next_sibling():
if not cursor.goto_parent():
return
depth -= 1
def named_children(node: Any, *types: str) -> list[Any]:
if not types:
return [c for c in node.named_children]
want = set(types)
return [c for c in node.named_children if c.type in want]
def child_by_field(node: Any, field: str) -> Optional[Any]:
return node.child_by_field_name(field)
_TEXT_CACHE: dict[int, tuple[bytes, Optional[str]]] = {}
_TEXT_CACHE_MAX = 8
_ASCII_SCAN = re.compile(rb'^[\x00-\x7f]*$')
def text_of(node: Any, src: bytes) -> str:
"""Node text; ASCII files get a cached decoded string to slice.
measure() calls this millions of times per build, each paying a fresh
UTF-8 decode (8.4M on elasticsearch). For an ALL-ASCII file, byte
offsets and character indices are identical, so the decoded string can
be cached and sliced directly -- no per-call decode at all. A file
containing any non-ASCII byte caches None and takes the plain path:
its node offsets are BYTE offsets, and slicing the decoded STR by them
is wrong (a 3-byte CJK char is ONE str index -- the fuzz test catches
this in seconds).
"""
ent = _TEXT_CACHE.get(id(src))
if ent is None or ent[0] is not src:
ascii_ok = _ASCII_SCAN.match(src) is not None
cached = src.decode("ascii") if ascii_ok else None
if len(_TEXT_CACHE) >= _TEXT_CACHE_MAX:
_TEXT_CACHE.clear()
_TEXT_CACHE[id(src)] = (src, cached)
ent = _TEXT_CACHE[id(src)]
if ent[1] is not None: # ascii: offsets are 1:1
return ent[1][node.start_byte:node.end_byte]
return src[node.start_byte:node.end_byte].decode("utf-8", "replace")
def field_text(node: Any, field: str, src: bytes, default: str = "") -> str:
c = node.child_by_field_name(field)
return text_of(c, src) if c is not None else default
def descendants_of_type(node: Any, *types: str) -> Iterator[Any]:
want = set(types)
for n in walk(node):
if n.type in want:
yield n
def count_types(node: Any, counter_types: dict[str, str]) -> dict[str, int]:
"""One pass over a subtree, counting node types into named buckets.
`counter_types` maps a tree-sitter node type to the metric it feeds. One
walk for all metrics: walking a large function body once per metric is the
difference between a repo scan taking seconds and taking minutes.
"""
out: dict[str, int] = {}
for n in walk(node):
key = counter_types.get(n.type)
if key is not None:
out[key] = out.get(key, 0) + 1
return out
def has_error(node: Any) -> bool:
return node.has_error
def count_errors(root: Any) -> tuple[int, int]:
"""(error nodes, missing nodes) in the tree.
A file with errors is still indexed -- tree-sitter recovers and the symbols
around the damage are real. The count travels with the file row so a query
can exclude, or specifically hunt, the parts we got wrong.
"""
if not root.has_error:
return 0, 0
errs = miss = 0
for n in walk(root):
if n.type == "ERROR":
errs += 1
elif n.is_missing:
miss += 1
return errs, miss
class Query:
"""A compiled tree-sitter query, tolerant of the 0.24->0.25 API split.
`Language.query()` was removed in 0.25 in favour of a standalone `Query`
class and a `QueryCursor` for execution. Both spellings are probed so one
analyzer source works across the wheels people actually have installed.
"""
def __init__(self, handle: ParserHandle, source: str):
self.ok = False
self._q = None
self._cursor_cls = None
if not handle.ok:
return
try:
ts = importlib.import_module("tree_sitter")
qcls = getattr(ts, "Query", None)
if qcls is not None:
try:
self._q = qcls(handle.language, source)
except TypeError:
self._q = handle.language.query(source)
else:
self._q = handle.language.query(source)
self._cursor_cls = getattr(ts, "QueryCursor", None)
self.ok = True
except Exception:
self.ok = False
self._q = None
def captures(self, node: Any) -> dict[str, list[Any]]:
if not self.ok:
return {}
try:
if self._cursor_cls is not None:
return self._cursor_cls(self._q).captures(node)
return self._q.captures(node)
except Exception:
return {}
def matches(self, node: Any) -> list[Any]:
if not self.ok:
return []
try:
if self._cursor_cls is not None:
return self._cursor_cls(self._q).matches(node)
return self._q.matches(node)
except Exception:
return []
# ==========================================================================
# _core.py
# The part of a code graph that does not depend on the language.
#
# Every analyzer in this repo re-reads and re-parses the tree on every run and
# builds the whole graph in a `:memory:` database. A graph file on disk gets read
# after the code it describes has moved on, and a stale graph is worse than none:
# it answers confidently and wrongly.
#
# What lives here: the file walk, the universal schema, the build driver, the
# aggregate pass, the renderer and the CLI. What does not: anything that knows
# what a function looks like. That is the analyzer's job, and it is the only part
# that needs writing per language.
#
# The universal schema is deliberately wider than any one language needs. A
# column that is always zero for Go costs nothing and keeps one query catalogue
# readable across nine languages; a column that exists only for Rust would force
# every shared query to branch.
# ==========================================================================
SCHEMA_VERSION = 2
COMMON_SKIP_DIRS = {
".git", ".hg", ".svn", ".jj", ".idea", ".vscode", ".vs", ".claude",
"node_modules", "bower_components", "vendor", "third_party", "thirdparty",
"external", "externals", "deps", "Godeps", "_vendor",
"__pycache__", ".mypy_cache", ".pytest_cache", ".ruff_cache", ".tox",
".venv", "venv", "env", ".env", "virtualenv",
"build", "_build", "dist", "out", "target", "bin", "obj", ".gradle",
".next", ".nuxt", ".svelte-kit", ".parcel-cache", ".turbo", ".cache",
"coverage", "htmlcov", ".nyc_output", "site-packages",
}
GENERATED_MARKERS = (
"@generated", "DO NOT EDIT", "Code generated by", "AUTO-GENERATED",
"autogenerated", "This file was automatically generated",
"Generated by the protocol buffer compiler", "@flow-generated",
)
GENERATED_NAME_RE = re.compile(
r'(\.min\.|\.bundle\.|[-_.](gen|generated|pb|g)\.|_pb2|\.g\.dart$'
r'|\.designer\.|^zz_generated)', re.I)
TEST_PATH_RE = re.compile(
r'(^|/)(tests?|test-d|spec|specs|__tests__|__snapshots__|testing|'
r'e2e|integration[-_]tests?|testdata|test_data|test-data|'
r'fixtures?)(/|$)', re.I)
TEST_NAME_RE_BY_LANG: dict[str, "re.Pattern[str]"] = {
"python": re.compile(r'(^test_|_test\.py$|^conftest\.py$)'),
"go": re.compile(r'_test\.go$'),
"rust": re.compile(r'(^tests?\.rs$|_test\.rs$)'),
"java": re.compile(r'(^Test[A-Z]|Tests?\.java$|TestCase\.java$|IT\.java$)'),
"javascript": re.compile(r'(\.test\.|\.spec\.|^test-|-test\.)'),
"typescript": re.compile(r'(\.test\.|\.spec\.|\.test-d\.|^test-|-test\.)'),
"php": re.compile(r'(Test\.php$|^test_)'),
"ruby": re.compile(r'(_spec\.rb$|_test\.rb$|^test_)'),
"c": re.compile(r'(^test_|_test\.[ch]$|^t_)'),
}
TEST_NAME_RE = re.compile(r'(^test_|_test\.|\.test\.|\.spec\.)')
VENDOR_PATH_RE = re.compile(
r'(^|/)(vendor|third_party|thirdparty|external|node_modules|deps)(/|$)', re.I)
MARKER_RE = re.compile(
r'\b(TODO|FIXME|XXX|HACK|BUG|NOTE|WARNING|OPTIMIZE|REVIEW|DEPRECATED|'
r'SAFETY|PANIC|UNSAFE)\b[ \t]*[:\-(]', re.I)
MAGIC_OK = {0, 1, 2, -1, 10, 100, 1000, 8, 16, 32, 64, 128, 256, 512, 1024,
255, 65535, 4096, 24, 60, 365, 7, 12, 3, 4, 6}
def module_of(rel: str, depth: int = 2) -> str:
"""A stable grouping key for a path.
Two levels, not one: `src/` alone puts an entire repo in one bucket, and
the full directory makes every leaf its own module. Two levels is what
actually separates subsystems in the repos this was tested against.
"""
parts = rel.replace(os.sep, "/").split("/")
if len(parts) <= 1:
return "(root)"
head = parts[:-1]
if head and head[0] in ("src", "lib", "source", "internal", "pkg", "app"):
head = head[:depth + 1]
else:
head = head[:depth]
return "/".join(head) or "(root)"
def is_generated(name: str, head: str) -> bool:
if GENERATED_NAME_RE.search(name):
return True
return any(m in head for m in GENERATED_MARKERS)
@dataclass
class FileRec:
"""One source file, already read and classified."""
fid: int
mid: int
rel: str
abspath: str
text: str
data: bytes
lang: str
is_test: bool
is_generated: bool
is_vendored: bool
@dataclass
class Buffers:
"""Row accumulators.
Everything is buffered and flushed with `executemany`. Per-row `INSERT`
across a million-symbol repo spends more time in the sqlite3 binding layer
than in parsing.
"""
params: list[tuple] = field(default_factory=list)
fields: list[tuple] = field(default_factory=list)
locals: list[tuple] = field(default_factory=list)
literals: list[tuple] = field(default_factory=list)
markers: list[tuple] = field(default_factory=list)
attributes: list[tuple] = field(default_factory=list)
imports: list[tuple] = field(default_factory=list)
hazards: list[tuple] = field(default_factory=list)
enum_members: list[tuple] = field(default_factory=list)
edges: dict[tuple[int, int], list[int]] = field(default_factory=dict)
callsites: set[tuple[int, int, int]] = field(default_factory=set)
unresolved: dict[tuple[int, str], list[int]] = field(default_factory=dict)
extra: dict[str, list[tuple]] = field(default_factory=dict)
def rows(self, table: str) -> list[tuple]:
"""Accumulator for a language-specific table."""
return self.extra.setdefault(table, [])
def add_edge(self, caller: int, callee: int, same_file: bool,
same_module: bool, line: int = 0) -> None:
key = (caller, callee)
e = self.edges.get(key)
if e is None:
self.edges[key] = [1, int(same_file), int(same_module),
int(caller == callee)]
else:
e[0] += 1
if line:
self.callsites.add((caller, callee, line))
def add_unresolved(self, caller: int, name: str, line: int) -> None:
"""A call we saw but could not point at a definition.
This is the honesty column. Dynamic dispatch, reflection, function
pointers and cross-language calls all land here, and a query that
reasons over the call graph can check how blind it is before trusting
its own answer.
"""
key = (caller, name)
u = self.unresolved.get(key)
if u is None:
self.unresolved[key] = [1, line]
else:
u[0] += 1
def add_hazard(self, sid: int, pattern: str, category: str,
n: int = 1, line: int = 0) -> None:
self.hazards.append((sid, pattern, category, n, line))
PRAGMAS = """
PRAGMA journal_mode=OFF;
PRAGMA synchronous=OFF;
PRAGMA page_size=16384;
PRAGMA temp_store=MEMORY;
PRAGMA cache_size=-262144;
PRAGMA foreign_keys=OFF;
"""
BASE_SCHEMA = r"""
CREATE TABLE meta(
key TEXT PRIMARY KEY,
value TEXT NOT NULL
) WITHOUT ROWID, STRICT;
CREATE TABLE modules(
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL DEFAULT 'source',
n_files INT NOT NULL DEFAULT 0,
n_symbols INT NOT NULL DEFAULT 0,
n_public INT NOT NULL DEFAULT 0,
sloc INT NOT NULL DEFAULT 0,
fan_in INT NOT NULL DEFAULT 0,
fan_out INT NOT NULL DEFAULT 0,
instability REAL NOT NULL DEFAULT 0.0
) STRICT;
CREATE TABLE files(
id INTEGER PRIMARY KEY,
path TEXT NOT NULL UNIQUE,
dir TEXT NOT NULL,
basename TEXT NOT NULL,
ext TEXT NOT NULL,
lang TEXT NOT NULL,
module_id INT REFERENCES modules(id),
bytes INT NOT NULL,
lines INT NOT NULL,
sloc INT NOT NULL,
blank_lines INT NOT NULL DEFAULT 0,
comment_lines INT NOT NULL DEFAULT 0,
doc_lines INT NOT NULL DEFAULT 0,
max_line_len INT NOT NULL DEFAULT 0,
sha1 TEXT NOT NULL,
parsed INT NOT NULL DEFAULT 0,
is_test INT NOT NULL DEFAULT 0,
is_generated INT NOT NULL DEFAULT 0,
is_vendored INT NOT NULL DEFAULT 0,
n_parse_errors INT NOT NULL DEFAULT 0,
n_missing_nodes INT NOT NULL DEFAULT 0,
parse_ms REAL NOT NULL DEFAULT 0.0,
n_symbols INT NOT NULL DEFAULT 0,
n_functions INT NOT NULL DEFAULT 0,
n_types INT NOT NULL DEFAULT 0,
n_imports INT NOT NULL DEFAULT 0,
total_cyclo INT NOT NULL DEFAULT 0,
max_cyclo INT NOT NULL DEFAULT 0,
total_risk INT NOT NULL DEFAULT 0
) STRICT;
CREATE TABLE symbols(
id INTEGER PRIMARY KEY,
file_id INT NOT NULL REFERENCES files(id),
module_id INT REFERENCES modules(id),
parent_id INT REFERENCES symbols(id),
name TEXT NOT NULL,
qual_name TEXT NOT NULL DEFAULT '',
kind TEXT NOT NULL,
line_start INT NOT NULL,
line_end INT NOT NULL,
n_lines INT NOT NULL DEFAULT 0,
byte_start INT NOT NULL DEFAULT 0,
byte_end INT NOT NULL DEFAULT 0,
signature TEXT,
return_type TEXT,
visibility TEXT NOT NULL DEFAULT '',
-- shape
n_params INT NOT NULL DEFAULT 0,
n_optional_params INT NOT NULL DEFAULT 0,
n_generic_params INT NOT NULL DEFAULT 0,
n_overloads INT NOT NULL DEFAULT 0,
arity_rank INT NOT NULL DEFAULT 0,
-- flags
is_public INT NOT NULL DEFAULT 0,
is_static INT NOT NULL DEFAULT 0,
is_async INT NOT NULL DEFAULT 0,
is_generator INT NOT NULL DEFAULT 0,
is_abstract INT NOT NULL DEFAULT 0,
is_override INT NOT NULL DEFAULT 0,
is_exported INT NOT NULL DEFAULT 0,
is_test INT NOT NULL DEFAULT 0,
is_deprecated INT NOT NULL DEFAULT 0,
is_entrypoint INT NOT NULL DEFAULT 0,
is_generated INT NOT NULL DEFAULT 0,
-- size
sloc INT NOT NULL DEFAULT 0,
body_bytes INT NOT NULL DEFAULT 0,
n_comment_lines INT NOT NULL DEFAULT 0,
n_doc_lines INT NOT NULL DEFAULT 0,
has_doc INT NOT NULL DEFAULT 0,
-- complexity
cyclomatic INT NOT NULL DEFAULT 0,
cognitive INT NOT NULL DEFAULT 0,
max_nesting INT NOT NULL DEFAULT 0,
n_tokens INT NOT NULL DEFAULT 0,
n_operators INT NOT NULL DEFAULT 0,
n_operands INT NOT NULL DEFAULT 0,
n_distinct_operators INT NOT NULL DEFAULT 0,
n_distinct_operands INT NOT NULL DEFAULT 0,
halstead_volume INT NOT NULL DEFAULT 0,
maintainability INT NOT NULL DEFAULT 0,
-- control flow
n_loops INT NOT NULL DEFAULT 0,
n_branches INT NOT NULL DEFAULT 0,
n_returns INT NOT NULL DEFAULT 0,
n_early_returns INT NOT NULL DEFAULT 0,
n_switch INT NOT NULL DEFAULT 0,
n_cases INT NOT NULL DEFAULT 0,
n_ternary INT NOT NULL DEFAULT 0,
n_logical INT NOT NULL DEFAULT 0,
n_try INT NOT NULL DEFAULT 0,
n_catch INT NOT NULL DEFAULT 0,
n_catch_broad INT NOT NULL DEFAULT 0,
n_catch_empty INT NOT NULL DEFAULT 0,
n_finally INT NOT NULL DEFAULT 0,
n_throw INT NOT NULL DEFAULT 0,
n_labels INT NOT NULL DEFAULT 0,
n_gotos INT NOT NULL DEFAULT 0,
-- what sits inside a loop
max_loop_depth INT NOT NULL DEFAULT 0,
call_in_loop INT NOT NULL DEFAULT 0,
alloc_in_loop INT NOT NULL DEFAULT 0,
io_in_loop INT NOT NULL DEFAULT 0,
await_in_loop INT NOT NULL DEFAULT 0,
lock_in_loop INT NOT NULL DEFAULT 0,
concat_in_loop INT NOT NULL DEFAULT 0,
regex_in_loop INT NOT NULL DEFAULT 0,
query_in_loop INT NOT NULL DEFAULT 0,
branch_in_loop INT NOT NULL DEFAULT 0,
-- data texture
n_locals INT NOT NULL DEFAULT 0,
n_assign INT NOT NULL DEFAULT 0,
n_compound_assign INT NOT NULL DEFAULT 0,
n_incdec INT NOT NULL DEFAULT 0,
n_cmp INT NOT NULL DEFAULT 0,
n_bitop INT NOT NULL DEFAULT 0,
n_shift INT NOT NULL DEFAULT 0,
n_arith INT NOT NULL DEFAULT 0,
n_string_lit INT NOT NULL DEFAULT 0,
n_regex_lit INT NOT NULL DEFAULT 0,
n_float_lit INT NOT NULL DEFAULT 0,
n_magic INT NOT NULL DEFAULT 0,
n_null_check INT NOT NULL DEFAULT 0,
n_subscript INT NOT NULL DEFAULT 0,
n_member_access INT NOT NULL DEFAULT 0,
n_lambda INT NOT NULL DEFAULT 0,
n_closure_capture INT NOT NULL DEFAULT 0,
-- the call graph
n_calls INT NOT NULL DEFAULT 0,
n_unique_calls INT NOT NULL DEFAULT 0,
n_dynamic_calls INT NOT NULL DEFAULT 0,
n_unresolved_calls INT NOT NULL DEFAULT 0,
fan_in INT NOT NULL DEFAULT 0,
fan_out INT NOT NULL DEFAULT 0,
n_callsites INT NOT NULL DEFAULT 0,
is_recursive INT NOT NULL DEFAULT 0,
is_leaf INT NOT NULL DEFAULT 0,
is_root INT NOT NULL DEFAULT 0,
-- hazards
n_hazards INT NOT NULL DEFAULT 0,
risk_score INT NOT NULL DEFAULT 0
{EXTRA_SYMBOL_COLS}
) STRICT;
CREATE TABLE params(
symbol_id INT NOT NULL REFERENCES symbols(id),
pos INT NOT NULL,
name TEXT,
type TEXT NOT NULL DEFAULT '',
default_value TEXT,
is_optional INT NOT NULL DEFAULT 0,
is_variadic INT NOT NULL DEFAULT 0,
is_ref INT NOT NULL DEFAULT 0,
is_mutable INT NOT NULL DEFAULT 0,
is_nullable INT NOT NULL DEFAULT 0,
is_generic INT NOT NULL DEFAULT 0,
is_untyped INT NOT NULL DEFAULT 0,
type_depth INT NOT NULL DEFAULT 0,
PRIMARY KEY(symbol_id, pos)
) WITHOUT ROWID, STRICT;
CREATE TABLE fields(
symbol_id INT NOT NULL REFERENCES symbols(id),
ordinal INT NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL DEFAULT '',
visibility TEXT NOT NULL DEFAULT '',
line INT NOT NULL DEFAULT 0,
is_static INT NOT NULL DEFAULT 0,
is_const INT NOT NULL DEFAULT 0,
is_mutable INT NOT NULL DEFAULT 0,
is_nullable INT NOT NULL DEFAULT 0,
is_collection INT NOT NULL DEFAULT 0,
is_untyped INT NOT NULL DEFAULT 0,
has_default INT NOT NULL DEFAULT 0,
type_depth INT NOT NULL DEFAULT 0,
PRIMARY KEY(symbol_id, ordinal)
) WITHOUT ROWID, STRICT;
CREATE TABLE locals(
symbol_id INT NOT NULL REFERENCES symbols(id),
ordinal INT NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL DEFAULT '',
line INT NOT NULL DEFAULT 0,
is_const INT NOT NULL DEFAULT 0,
is_mutable INT NOT NULL DEFAULT 0,
is_untyped INT NOT NULL DEFAULT 0,
has_init INT NOT NULL DEFAULT 0,
in_loop INT NOT NULL DEFAULT 0,
scope_depth INT NOT NULL DEFAULT 0,
PRIMARY KEY(symbol_id, ordinal)