graphite-code 1.3.0__py3-none-any.whl → 1.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- graphite/__init__.py +1 -1
- graphite/agent_hooks.py +105 -3
- graphite/cli.py +20 -3
- graphite/doctor.py +2 -2
- graphite/extract/ast.py +274 -39
- graphite/extract/pyscope.py +57 -7
- graphite/hookinstall.py +17 -0
- graphite/init.py +1 -0
- graphite/resolve.py +140 -1
- {graphite_code-1.3.0.dist-info → graphite_code-1.4.1.dist-info}/METADATA +2 -2
- {graphite_code-1.3.0.dist-info → graphite_code-1.4.1.dist-info}/RECORD +14 -14
- {graphite_code-1.3.0.dist-info → graphite_code-1.4.1.dist-info}/WHEEL +0 -0
- {graphite_code-1.3.0.dist-info → graphite_code-1.4.1.dist-info}/entry_points.txt +0 -0
- {graphite_code-1.3.0.dist-info → graphite_code-1.4.1.dist-info}/licenses/LICENSE +0 -0
graphite/__init__.py
CHANGED
|
@@ -38,4 +38,4 @@ __all__ = ["__version__"]
|
|
|
38
38
|
#: Coarse and hand-maintained by construction. It is a release label, not
|
|
39
39
|
#: evidence that a given fix is present -- to answer that, survey for the marker
|
|
40
40
|
#: the fix introduced, or compare `graphite --version` fingerprints.
|
|
41
|
-
__version__ = "1.
|
|
41
|
+
__version__ = "1.4.1"
|
graphite/agent_hooks.py
CHANGED
|
@@ -136,6 +136,7 @@ def handle_session_start(payload: dict[str, Any]) -> dict[str, Any] | None:
|
|
|
136
136
|
cwd = _payload_cwd(payload)
|
|
137
137
|
root = _repo_root(cwd)
|
|
138
138
|
_activate(root)
|
|
139
|
+
_open_session_books(root, str(payload.get("session_id") or ""), str(payload.get("source") or ""))
|
|
139
140
|
if (root / "graph-out" / "graph.json").is_file():
|
|
140
141
|
state, reason = _freshness_within_budget(root)
|
|
141
142
|
if state == "stale":
|
|
@@ -968,6 +969,54 @@ def _forget_what_may_be_set_again(assigned: dict[str, str], argv: list[str], pow
|
|
|
968
969
|
assigned.pop(named.group().lower() if powershell else named.group(), None)
|
|
969
970
|
|
|
970
971
|
|
|
972
|
+
# PowerShell commands whose output is the files (or folders) of a path, so that a
|
|
973
|
+
# `Select-String` after a pipe searches what they hand it (#84).
|
|
974
|
+
_FILE_LISTINGS = frozenset({"get-childitem", "gci", "ls", "dir"})
|
|
975
|
+
# The searches that take files from the pipeline. `grep` does not: it reads the
|
|
976
|
+
# lines of what is piped, so `ls | grep name` filters a list of names.
|
|
977
|
+
_POWERSHELL_SEARCHES = frozenset({"select-string", "sls"})
|
|
978
|
+
# What may stand between such a listing and the search and still hand the search
|
|
979
|
+
# files: a stage that only keeps or orders them. Any other stage (`ForEach-Object`,
|
|
980
|
+
# `Out-String`, `Select-Object -ExpandProperty`) may make text, and ends the chain.
|
|
981
|
+
_FILE_KEEPING_STAGES = frozenset({
|
|
982
|
+
"where-object", "where", "?", "select-object", "select", "sort-object", "sort",
|
|
983
|
+
})
|
|
984
|
+
# Listing flags that take a word, so the word is not a path. `-Path` and
|
|
985
|
+
# `-LiteralPath` are the exceptions: their word IS one.
|
|
986
|
+
_LISTING_VALUE_FLAGS = frozenset({
|
|
987
|
+
"-filter", "-include", "-exclude", "-depth", "-attributes",
|
|
988
|
+
})
|
|
989
|
+
_LISTING_PATH_FLAGS = frozenset({"-path", "-literalpath"})
|
|
990
|
+
|
|
991
|
+
|
|
992
|
+
def _listed_paths(name: str, rest: list[str]) -> list[str] | None:
|
|
993
|
+
"""The paths a file listing names, else None where `name` lists no files.
|
|
994
|
+
|
|
995
|
+
An empty list is a listing of the current directory. `-Name` makes the
|
|
996
|
+
listing text, and what is piped on is then a filter of it.
|
|
997
|
+
"""
|
|
998
|
+
if name not in _FILE_LISTINGS:
|
|
999
|
+
return None
|
|
1000
|
+
paths: list[str] = []
|
|
1001
|
+
expecting = False
|
|
1002
|
+
skipping = False
|
|
1003
|
+
for token in rest:
|
|
1004
|
+
lowered = token.lower()
|
|
1005
|
+
if expecting or skipping:
|
|
1006
|
+
if expecting:
|
|
1007
|
+
paths.append(token)
|
|
1008
|
+
expecting = skipping = False
|
|
1009
|
+
elif lowered == "-name" or lowered == "-n":
|
|
1010
|
+
return None
|
|
1011
|
+
elif lowered in _LISTING_PATH_FLAGS:
|
|
1012
|
+
expecting = True
|
|
1013
|
+
elif lowered in _LISTING_VALUE_FLAGS:
|
|
1014
|
+
skipping = True
|
|
1015
|
+
elif not token.startswith("-"):
|
|
1016
|
+
paths.append(token)
|
|
1017
|
+
return paths
|
|
1018
|
+
|
|
1019
|
+
|
|
971
1020
|
def _bash_searches(
|
|
972
1021
|
command: str, root: Path, msys: bool = False, cwd: Path | None = None, powershell: bool = False
|
|
973
1022
|
) -> list[_Search]:
|
|
@@ -1024,9 +1073,11 @@ def _bash_searches(
|
|
|
1024
1073
|
base, placed = start, start_placed # `base` is where the shell is
|
|
1025
1074
|
moved = False # a `cd`, or a command the hook does not model, has run in this shell
|
|
1026
1075
|
pipeline_base, pipeline_placed = base, placed # where the pipeline being read started
|
|
1076
|
+
listed: list[str] | None = None # the paths of the file listing whose output the stage before gives
|
|
1027
1077
|
for head in _bash_command_heads(lines, powershell):
|
|
1028
1078
|
piped = head.before in ("|", "|&") # `||` is or-else, not a pipe
|
|
1029
1079
|
if not piped:
|
|
1080
|
+
listed = None
|
|
1030
1081
|
if head.before != "&&":
|
|
1031
1082
|
base, placed = (None, False) if moved else (start, start_placed)
|
|
1032
1083
|
pipeline_base, pipeline_placed = base, placed
|
|
@@ -1040,6 +1091,16 @@ def _bash_searches(
|
|
|
1040
1091
|
if len(head.argv) == 1 and _NESTED_RE.fullmatch(head.argv[0]):
|
|
1041
1092
|
continue # a subshell standing alone
|
|
1042
1093
|
if piped and _command_name(head.argv[0]) != "xargs":
|
|
1094
|
+
stage = _command_name(head.argv[0])
|
|
1095
|
+
if listed is not None and stage in _POWERSHELL_SEARCHES:
|
|
1096
|
+
# `Get-ChildItem -Recurse src | Select-String name` searches
|
|
1097
|
+
# the files it is handed (#84), as `xargs grep` does.
|
|
1098
|
+
found = _search_in(stage, [_expanded(t, assigned, powershell) for t in head.argv[1:]], here, msys)
|
|
1099
|
+
if found is not None:
|
|
1100
|
+
found = found._replace(paths=_located(listed, here, msys))
|
|
1101
|
+
searches.append(found if here_placed or cwd is None else _unplaced(found, cwd))
|
|
1102
|
+
if stage not in _FILE_KEEPING_STAGES:
|
|
1103
|
+
listed = None
|
|
1043
1104
|
continue # a filter: it reads what the command before it wrote
|
|
1044
1105
|
assignments = _assignments(head.argv, powershell)
|
|
1045
1106
|
if assignments is not None:
|
|
@@ -1063,6 +1124,7 @@ def _bash_searches(
|
|
|
1063
1124
|
continue
|
|
1064
1125
|
name = _command_name(argv[0])
|
|
1065
1126
|
rest = [_expanded(token, assigned, powershell) for token in argv[1:]]
|
|
1127
|
+
listed = _listed_paths(name, rest) if len(argv) == len(written) else None
|
|
1066
1128
|
# A `cd` behind a wrapper is not the shell's: `env cd docs` moves a
|
|
1067
1129
|
# program that then exits, and `! cd docs && ...` goes on only when
|
|
1068
1130
|
# the `cd` failed. It is read below, as a command that may move.
|
|
@@ -1234,6 +1296,43 @@ def _strict_denial(payload: dict[str, Any], root: Path, cwd: Path | None = None)
|
|
|
1234
1296
|
MAX_CURSOR_SESSIONS = 20
|
|
1235
1297
|
|
|
1236
1298
|
|
|
1299
|
+
def _keep_newest_sessions(sessions: dict[str, Any]) -> None:
|
|
1300
|
+
while len(sessions) > MAX_CURSOR_SESSIONS:
|
|
1301
|
+
sessions.pop(next(iter(sessions)))
|
|
1302
|
+
|
|
1303
|
+
|
|
1304
|
+
def _open_session_books(root: Path, session_id: str, source: str) -> None:
|
|
1305
|
+
"""Start a new session's savings books where the usage ledger ends now.
|
|
1306
|
+
|
|
1307
|
+
The ledger holds every session's entries, so a session that counted from
|
|
1308
|
+
byte 0 took all of them as its own (#108). A session the cursor already
|
|
1309
|
+
knows keeps its totals: SessionStart fires again on a resume or a compact.
|
|
1310
|
+
On a resume its books move to the ledger's end as well: what the ledger
|
|
1311
|
+
gained while it was away is other sessions' use, and a turn of its own
|
|
1312
|
+
whose Stop never fired is not counted. A compact falls inside a turn, so
|
|
1313
|
+
the books stay where they are.
|
|
1314
|
+
"""
|
|
1315
|
+
try:
|
|
1316
|
+
if not session_id:
|
|
1317
|
+
return
|
|
1318
|
+
sessions = usage_ledger.read_cursor(root).get("sessions")
|
|
1319
|
+
if not isinstance(sessions, dict):
|
|
1320
|
+
sessions = {}
|
|
1321
|
+
known = sessions.pop(session_id, None)
|
|
1322
|
+
if isinstance(known, dict) and source != "resume":
|
|
1323
|
+
return
|
|
1324
|
+
ledger = usage_ledger.ledger_path(root)
|
|
1325
|
+
ledger_stat = ledger.stat() if ledger.is_file() else None
|
|
1326
|
+
books = known if isinstance(known, dict) else {"tokens": 0, "seconds": 0.0}
|
|
1327
|
+
books["offset"] = ledger_stat.st_size if ledger_stat is not None else 0
|
|
1328
|
+
books["ino"] = ledger_stat.st_ino if ledger_stat is not None else None
|
|
1329
|
+
sessions[session_id] = books
|
|
1330
|
+
_keep_newest_sessions(sessions)
|
|
1331
|
+
usage_ledger.write_cursor(root, {"sessions": sessions})
|
|
1332
|
+
except Exception:
|
|
1333
|
+
return
|
|
1334
|
+
|
|
1335
|
+
|
|
1237
1336
|
def _entries_between(path: Path, start: int, end: int) -> list[dict[str, Any]]:
|
|
1238
1337
|
entries: list[dict[str, Any]] = []
|
|
1239
1338
|
with open(path, "rb") as handle:
|
|
@@ -1287,7 +1386,11 @@ def handle_stop(payload: dict[str, Any]) -> dict[str, Any] | None:
|
|
|
1287
1386
|
sessions = {}
|
|
1288
1387
|
state = sessions.pop(session_id, None)
|
|
1289
1388
|
if not isinstance(state, dict):
|
|
1290
|
-
|
|
1389
|
+
# No books were opened for this session: its SessionStart was not
|
|
1390
|
+
# seen, or the session was pruned from the cursor. What the ledger
|
|
1391
|
+
# holds now is other sessions' history (#108), so the books start
|
|
1392
|
+
# at its end. This turn's own entries are lost; none are invented.
|
|
1393
|
+
state = {"offset": size, "tokens": 0, "seconds": 0.0, "ino": current_ino}
|
|
1291
1394
|
offset = state.get("offset", 0)
|
|
1292
1395
|
stored_ino = state.get("ino")
|
|
1293
1396
|
# A stored `ino` that isn't an int (missing key on the older 3-key cursor
|
|
@@ -1317,8 +1420,7 @@ def handle_stop(payload: dict[str, Any]) -> dict[str, Any] | None:
|
|
|
1317
1420
|
state["tokens"] = _cursor_number(state.get("tokens", 0), int) + turn_tokens
|
|
1318
1421
|
state["seconds"] = _cursor_number(state.get("seconds", 0.0), float) + turn_seconds
|
|
1319
1422
|
sessions[session_id] = state # re-insert -> newest position
|
|
1320
|
-
|
|
1321
|
-
sessions.pop(next(iter(sessions)))
|
|
1423
|
+
_keep_newest_sessions(sessions)
|
|
1322
1424
|
usage_ledger.write_cursor(root, {"sessions": sessions})
|
|
1323
1425
|
if not new_entries or not usage_ledger.savings_display_enabled(root):
|
|
1324
1426
|
return None
|
graphite/cli.py
CHANGED
|
@@ -255,12 +255,17 @@ def _write_json(path: Path, data: dict[str, Any]) -> None:
|
|
|
255
255
|
atomic_write_json(path, data, indent=2)
|
|
256
256
|
|
|
257
257
|
|
|
258
|
-
def
|
|
259
|
-
|
|
260
|
-
root = Path(args.path).resolve()
|
|
258
|
+
def _require_existing(root: Path) -> None:
|
|
259
|
+
"""Exit 1 with `path not found` for a path that is not there."""
|
|
261
260
|
if not root.exists():
|
|
262
261
|
print(f"[graphite] path not found: {root}", file=sys.stderr)
|
|
263
262
|
raise SystemExit(1)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _scan(args: argparse.Namespace, cfg: Config) -> tuple[dict[str, Any], list[Any]]:
|
|
266
|
+
cfg = cfg.canonical_graph()
|
|
267
|
+
root = Path(args.path).resolve()
|
|
268
|
+
_require_existing(root)
|
|
264
269
|
top = _root_above(root)
|
|
265
270
|
if top is not None:
|
|
266
271
|
raise ValueError(_below_a_root(root, top))
|
|
@@ -727,6 +732,9 @@ def cmd_build(args: argparse.Namespace) -> int:
|
|
|
727
732
|
top = _root_above(asked)
|
|
728
733
|
if top is not None:
|
|
729
734
|
raise ValueError(_below_a_root(asked, top))
|
|
735
|
+
# A path that is not there is refused as `scan` refuses it (#88): the lock
|
|
736
|
+
# below would otherwise make it, and a detached child could not start in it.
|
|
737
|
+
_require_existing(asked)
|
|
730
738
|
if getattr(args, "detach", False):
|
|
731
739
|
root = Path(args.path).resolve()
|
|
732
740
|
# Deliberately omits --detach: the child must build, not re-spawn.
|
|
@@ -839,6 +847,10 @@ def cmd_doctor(args: argparse.Namespace) -> int:
|
|
|
839
847
|
root = Path(args.path).resolve()
|
|
840
848
|
if not root.is_dir():
|
|
841
849
|
raise ValueError("doctor path must be an existing directory")
|
|
850
|
+
# The report is about the repository the folder is in (#89), as the read
|
|
851
|
+
# commands are: from a subfolder the graph is the root's, and so are the
|
|
852
|
+
# incidents. A root graphite does not take (`repository_root`) is not followed.
|
|
853
|
+
root = repository_root(root)
|
|
842
854
|
cfg = _project_scoped_config(args, root)
|
|
843
855
|
report = run_doctor(
|
|
844
856
|
root,
|
|
@@ -1204,6 +1216,11 @@ def cmd_init(args: argparse.Namespace) -> int:
|
|
|
1204
1216
|
extra += f", reason={hooks['reason']}"
|
|
1205
1217
|
if hooks.get("relocated"):
|
|
1206
1218
|
extra += f", relocated={', '.join(hooks['relocated'])}"
|
|
1219
|
+
if hooks.get("chain_slots"):
|
|
1220
|
+
# Said in either install order: with graphite first nothing is in
|
|
1221
|
+
# these slots yet, and this is where another tool's hook goes.
|
|
1222
|
+
files = ", ".join(slot["file"] for slot in hooks["chain_slots"].values())
|
|
1223
|
+
extra += f"; another tool's hook for the same event belongs in {files} there, run first"
|
|
1207
1224
|
print(f" - hooks: {hooks.get('action')} ({hooks.get('path')}{extra})")
|
|
1208
1225
|
allowlist = result["allowlist"]
|
|
1209
1226
|
if allowlist.get("changed"):
|
graphite/doctor.py
CHANGED
|
@@ -20,7 +20,7 @@ from .daemon import read_daemon_status
|
|
|
20
20
|
from .daemon_health import HealthOptions, evaluate_daemon_health
|
|
21
21
|
from .freshness import FreshnessLimitError, check_graph_freshness
|
|
22
22
|
from .git import GitError, GitRunner
|
|
23
|
-
from .hookinstall import DEFAULT_HOOKS_DIRNAME, hook_shim_present, hooks_dir
|
|
23
|
+
from .hookinstall import DEFAULT_HOOKS_DIRNAME, chain_slots, hook_shim_present, hooks_dir
|
|
24
24
|
from .init import gitignored_managed_paths, managed_doc_paths
|
|
25
25
|
from .hookshim import TRIGGERS
|
|
26
26
|
from .llm import canonical_provider_name
|
|
@@ -179,7 +179,7 @@ def check_hooks(root: Path) -> DoctorCheck:
|
|
|
179
179
|
installed = all(hook_shim_present(hdir / hook) for hook in TRIGGERS)
|
|
180
180
|
configured = _hooks_path_configured(root)
|
|
181
181
|
custom_hooks_dir = hdir != root / DEFAULT_HOOKS_DIRNAME
|
|
182
|
-
details = {"onboarded": True, "custom_hooks_dir": custom_hooks_dir, "hookspath_configured": configured, "trampolines_installed": installed}
|
|
182
|
+
details = {"onboarded": True, "custom_hooks_dir": custom_hooks_dir, "hookspath_configured": configured, "trampolines_installed": installed, "chain_slots": chain_slots(hdir)}
|
|
183
183
|
|
|
184
184
|
if configured and installed:
|
|
185
185
|
return DoctorCheck("hooks", "Hooks", "ready", "Git hooks are installed and enforced.", details)
|
graphite/extract/ast.py
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
"""Deterministic structural extraction via tree-sitter."""
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
|
+
import builtins
|
|
4
5
|
import hashlib
|
|
5
6
|
import importlib
|
|
6
7
|
import re
|
|
7
8
|
import sys
|
|
8
9
|
import unicodedata
|
|
10
|
+
import dataclasses
|
|
9
11
|
from dataclasses import dataclass, field
|
|
10
12
|
from pathlib import Path
|
|
11
|
-
from typing import Any, Collection, Final, Sequence
|
|
13
|
+
from typing import Any, Collection, Final, Iterable, Sequence
|
|
12
14
|
|
|
13
15
|
from ..cache import Cache
|
|
14
16
|
from ..config import Config
|
|
15
17
|
from ..graph import normalize_id
|
|
16
18
|
from ..ingest import LANGUAGE_BY_EXT, FileEntry
|
|
17
|
-
from ..resolve import SourceIndex, should_keep_call_target
|
|
19
|
+
from ..resolve import MAX_REEXPORT_HOPS, SourceIndex, python_reexports_of, should_keep_call_target
|
|
18
20
|
from .pyscope import (
|
|
19
21
|
PyScope,
|
|
20
22
|
Resolution,
|
|
@@ -214,8 +216,10 @@ def _make_id(*parts: str) -> str:
|
|
|
214
216
|
Known residual: two DIFFERENT part tuples can still produce one id when the
|
|
215
217
|
only difference is a separator versus a literal underscore — `a/b.py` and
|
|
216
218
|
`a_b.py` both reach `a_b_py`, and both are ambiguity-free by this test.
|
|
217
|
-
Closing it would mean discriminating every path containing an
|
|
218
|
-
which is most of `tests/`.
|
|
219
|
+
Closing it here would mean discriminating every path containing an
|
|
220
|
+
underscore, which is most of `tests/`. For FILE ids it is closed another
|
|
221
|
+
way (#82): `_colliding_file_ids` marks the paths of a tree that actually
|
|
222
|
+
collide and no others. For a definition's id within one file it remains.
|
|
219
223
|
"""
|
|
220
224
|
kept = [p for p in parts if p]
|
|
221
225
|
combined = unicodedata.normalize("NFKC", "_".join(p.strip("_.") for p in kept))
|
|
@@ -262,7 +266,52 @@ def _scoped_id(file_id: str, qualname: str, salt: int = 0) -> str:
|
|
|
262
266
|
return f"{readable[: _MAX_ID_LEN - len(marker) - 1].rstrip('_')}_{marker}"
|
|
263
267
|
|
|
264
268
|
|
|
265
|
-
def _file_node_id(rel_path: str) -> str:
|
|
269
|
+
def _file_node_id(rel_path: str, source_index: SourceIndex | None = None) -> str:
|
|
270
|
+
"""The id of a file's node: its plain id, or the one the tree gave it (#82).
|
|
271
|
+
|
|
272
|
+
A path whose plain id another path of the tree also has is given a marker
|
|
273
|
+
by `_colliding_file_ids`, which `extract_all` records on the source index.
|
|
274
|
+
Everything else keeps its plain id.
|
|
275
|
+
"""
|
|
276
|
+
if source_index is not None and source_index.file_ids:
|
|
277
|
+
marked = source_index.file_ids.get(rel_path)
|
|
278
|
+
if marked is not None:
|
|
279
|
+
return marked
|
|
280
|
+
return _plain_file_node_id(rel_path)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _colliding_file_ids(rel_paths: Iterable[str]) -> dict[str, str]:
|
|
284
|
+
"""rel path -> file node id, for each path whose plain id another path has.
|
|
285
|
+
|
|
286
|
+
`a/b.py`, `a_b.py` and `a/b_py` all slug to `a_b_py`, a loss `_make_id`
|
|
287
|
+
cannot see from one path. Every member of such a group is marked, with a
|
|
288
|
+
hash of its own exact path, so no id depends on which of them is listed
|
|
289
|
+
first or on whether the others are still there. A path that collides with
|
|
290
|
+
nothing is not in the result: ids of files without a twin do not move.
|
|
291
|
+
"""
|
|
292
|
+
groups: dict[str, list[str]] = {}
|
|
293
|
+
for rel_path in rel_paths:
|
|
294
|
+
groups.setdefault(_plain_file_node_id(rel_path), []).append(rel_path)
|
|
295
|
+
taken = set(groups)
|
|
296
|
+
marked: dict[str, str] = {}
|
|
297
|
+
for plain, members in sorted(groups.items()):
|
|
298
|
+
if len(members) < 2:
|
|
299
|
+
continue
|
|
300
|
+
for rel_path in sorted(members):
|
|
301
|
+
salt = 0
|
|
302
|
+
while True:
|
|
303
|
+
tag = f"file-path\x00{rel_path}" + (f"\x00{salt}" if salt else "")
|
|
304
|
+
marker = hashlib.blake2s(tag.encode("utf-8"), digest_size=_ID_DISCRIMINATOR_LEN // 2).hexdigest()
|
|
305
|
+
candidate = f"{plain[: _MAX_ID_LEN - len(marker) - 1].rstrip('_')}_{marker}"
|
|
306
|
+
if candidate not in taken:
|
|
307
|
+
break
|
|
308
|
+
salt += 1
|
|
309
|
+
taken.add(candidate)
|
|
310
|
+
marked[rel_path] = candidate
|
|
311
|
+
return marked
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _plain_file_node_id(rel_path: str) -> str:
|
|
266
315
|
"""Stable node id for a file: a slug of the FULL repo-relative path AND name.
|
|
267
316
|
|
|
268
317
|
Two claims this docstring used to make were false, and both were disproved
|
|
@@ -396,7 +445,7 @@ def _extract_ts_js(file_id: str, rel_path: str, source: bytes, tree: Any, source
|
|
|
396
445
|
root = tree.root_node
|
|
397
446
|
|
|
398
447
|
def _line(node: Any) -> int:
|
|
399
|
-
return
|
|
448
|
+
return node.start_point[0] + 1
|
|
400
449
|
|
|
401
450
|
def _name(node: Any) -> str | None:
|
|
402
451
|
# identifiers, property_identifier, type_identifier, etc.
|
|
@@ -424,7 +473,7 @@ def _extract_ts_js(file_id: str, rel_path: str, source: bytes, tree: Any, source
|
|
|
424
473
|
def _anon_scope(node: Any) -> _Scope:
|
|
425
474
|
syn = _safe_label(_synthetic_fn_name(node, source))
|
|
426
475
|
line = _line(node)
|
|
427
|
-
col =
|
|
476
|
+
col = node.start_point[1] + 1
|
|
428
477
|
mid = _make_id(file_id, syn, f"l{line}", f"c{col}")
|
|
429
478
|
pending = _node(mid, "function", syn, rel_path, line, extra={"anonymous": True})
|
|
430
479
|
return _Scope(mid, pending=pending)
|
|
@@ -517,7 +566,7 @@ def _extract_ts_js(file_id: str, rel_path: str, source: bytes, tree: Any, source
|
|
|
517
566
|
result.edges.append(
|
|
518
567
|
_edge(
|
|
519
568
|
file_id,
|
|
520
|
-
_file_node_id(resolved.rel_path),
|
|
569
|
+
_file_node_id(resolved.rel_path, source_index),
|
|
521
570
|
"imports",
|
|
522
571
|
rel_path,
|
|
523
572
|
_line(node),
|
|
@@ -540,7 +589,7 @@ def _extract_ts_js(file_id: str, rel_path: str, source: bytes, tree: Any, source
|
|
|
540
589
|
result.edges.append(
|
|
541
590
|
_edge(
|
|
542
591
|
file_id,
|
|
543
|
-
_file_node_id(required.rel_path),
|
|
592
|
+
_file_node_id(required.rel_path, source_index),
|
|
544
593
|
"imports",
|
|
545
594
|
rel_path,
|
|
546
595
|
_line(node),
|
|
@@ -646,7 +695,7 @@ def _extract_ts_js(file_id: str, rel_path: str, source: bytes, tree: Any, source
|
|
|
646
695
|
result.edges.append(
|
|
647
696
|
_edge(
|
|
648
697
|
file_id,
|
|
649
|
-
_file_node_id(edge.target),
|
|
698
|
+
_file_node_id(edge.target, source_index),
|
|
650
699
|
edge.relation,
|
|
651
700
|
rel_path,
|
|
652
701
|
edge.line,
|
|
@@ -724,7 +773,7 @@ def _collect_ts_import_symbols(root: Any, rel_path: str, source_index: SourceInd
|
|
|
724
773
|
# Resolved module: every name it binds is proven in-repo, regardless
|
|
725
774
|
# of binding form -- must win over an _EXTERNAL_GLOBALS collision.
|
|
726
775
|
in_repo.update(_iter_bound_local_names(clause))
|
|
727
|
-
target_file_id = _file_node_id(resolved.rel_path)
|
|
776
|
+
target_file_id = _file_node_id(resolved.rel_path, source_index)
|
|
728
777
|
for local, original in _iter_named_imports(clause):
|
|
729
778
|
symbols[local] = _make_id(target_file_id, original)
|
|
730
779
|
for child in clause.children:
|
|
@@ -766,7 +815,7 @@ def _collect_ts_import_symbols(root: Any, rel_path: str, source_index: SourceInd
|
|
|
766
815
|
external.update(bound)
|
|
767
816
|
return
|
|
768
817
|
in_repo.update(bound)
|
|
769
|
-
target_file_id = _file_node_id(resolved.rel_path)
|
|
818
|
+
target_file_id = _file_node_id(resolved.rel_path, source_index)
|
|
770
819
|
if pairs:
|
|
771
820
|
for local, original in pairs:
|
|
772
821
|
symbols[local] = _make_id(target_file_id, original)
|
|
@@ -1314,7 +1363,7 @@ def _python_import_bindings(
|
|
|
1314
1363
|
out.append((root, "unknown", None))
|
|
1315
1364
|
elif "." not in module:
|
|
1316
1365
|
resolved = source_index.resolve_python_module(rel_path, module)
|
|
1317
|
-
out.append((module, "alias", _file_node_id(resolved)) if resolved else (module, "external", None))
|
|
1366
|
+
out.append((module, "alias", _file_node_id(resolved, source_index)) if resolved else (module, "external", None))
|
|
1318
1367
|
elif source_index.resolve_python_module(rel_path, root) is None:
|
|
1319
1368
|
# `import pkg.sub` binds only the root name `pkg`. Mark it
|
|
1320
1369
|
# external ONLY if that root does not resolve in-repo -- a
|
|
@@ -1331,7 +1380,7 @@ def _python_import_bindings(
|
|
|
1331
1380
|
out.append((local, "unknown", None))
|
|
1332
1381
|
continue
|
|
1333
1382
|
resolved = source_index.resolve_python_module(rel_path, module)
|
|
1334
|
-
out.append((local, "alias", _file_node_id(resolved)) if resolved else (local, "external", None))
|
|
1383
|
+
out.append((local, "alias", _file_node_id(resolved, source_index)) if resolved else (local, "external", None))
|
|
1335
1384
|
elif node.type == "import_from_statement":
|
|
1336
1385
|
modules = _python_import_modules(node)
|
|
1337
1386
|
if not modules:
|
|
@@ -1359,16 +1408,43 @@ def _python_import_bindings(
|
|
|
1359
1408
|
sub = f"{base_module}.{original}" if base_module else original
|
|
1360
1409
|
as_module = source_index.resolve_python_module(rel_path, sub, dots)
|
|
1361
1410
|
if as_module:
|
|
1362
|
-
out.append((local, "alias", _file_node_id(as_module)))
|
|
1411
|
+
out.append((local, "alias", _file_node_id(as_module, source_index)))
|
|
1363
1412
|
continue
|
|
1364
1413
|
parent = source_index.resolve_python_module(rel_path, base_module, dots)
|
|
1365
1414
|
if parent:
|
|
1366
|
-
|
|
1415
|
+
# A package that only re-exports the name does not define it:
|
|
1416
|
+
# bind to the file that does (#87).
|
|
1417
|
+
defining, defined_as = source_index.follow_python_reexport(parent, original)
|
|
1418
|
+
out.append((local, "symbol", _make_id(_file_node_id(defining, source_index), defined_as)))
|
|
1367
1419
|
else:
|
|
1368
1420
|
out.append((local, "external", None))
|
|
1369
1421
|
return out
|
|
1370
1422
|
|
|
1371
1423
|
|
|
1424
|
+
def _python_module_reexports(
|
|
1425
|
+
file_id: str, rel_path: str, source: bytes, source_index: SourceIndex
|
|
1426
|
+
) -> dict[str, str]:
|
|
1427
|
+
"""`<module>.<name>` -> where the module's own `from X import name` says it is (#107).
|
|
1428
|
+
|
|
1429
|
+
The key is the id a call of `module.name` gets, `_make_id(<file id>,
|
|
1430
|
+
<name>)`; the value is the id of `name` in the file `X` resolves to. Only
|
|
1431
|
+
a name the module binds by that one statement is recorded (the rule #87
|
|
1432
|
+
applies to a package's `__init__.py`), and one that names a submodule
|
|
1433
|
+
(`from pkg import sub`) is not: `pkg.sub` is the module, not a name of
|
|
1434
|
+
`pkg`. The dispatch post-pass follows these across files, so a value
|
|
1435
|
+
depends on the module's own bytes and the file set alone, as its cache
|
|
1436
|
+
key does.
|
|
1437
|
+
"""
|
|
1438
|
+
out: dict[str, str] = {}
|
|
1439
|
+
for (_, local), (module, level, original) in python_reexports_of(rel_path, source).items():
|
|
1440
|
+
if source_index.resolve_python_module(rel_path, f"{module}.{original}", level):
|
|
1441
|
+
continue
|
|
1442
|
+
defining = source_index.resolve_python_module(rel_path, module, level)
|
|
1443
|
+
if defining:
|
|
1444
|
+
out[_make_id(file_id, local)] = _make_id(_file_node_id(defining, source_index), original)
|
|
1445
|
+
return out
|
|
1446
|
+
|
|
1447
|
+
|
|
1372
1448
|
def _python_definition_name(node: Any) -> str | None:
|
|
1373
1449
|
"""A def/class node's name exactly as its graph node records it."""
|
|
1374
1450
|
name_node = node.child_by_field_name("name")
|
|
@@ -1459,6 +1535,9 @@ def _python_bare_call(
|
|
|
1459
1535
|
return ids[(resolution.qualname, resolution.module_level)], confidence
|
|
1460
1536
|
if resolution.kind == "symbol" and resolution.target is not None:
|
|
1461
1537
|
return resolution.target, confidence
|
|
1538
|
+
if resolution.kind == "member" and resolution.target is not None and resolution.qualname is not None:
|
|
1539
|
+
# `t = mod.attr; t()`: the call `mod.attr()` makes (#90).
|
|
1540
|
+
return _make_id(resolution.target, resolution.qualname), confidence
|
|
1462
1541
|
if resolution.kind in ("value", "alias", "ambiguous-import") and table.module_defines(name):
|
|
1463
1542
|
return ids[(f"<local>.{name}", False)], confidence
|
|
1464
1543
|
return _resolve_call(file_id, name), confidence
|
|
@@ -1505,14 +1584,21 @@ def _python_attribute_root(node: Any) -> str | None:
|
|
|
1505
1584
|
return None
|
|
1506
1585
|
|
|
1507
1586
|
|
|
1508
|
-
def _extract_python(file_id: str, rel_path: str,
|
|
1587
|
+
def _extract_python(file_id: str, rel_path: str, source: bytes, tree: Any, source_index: SourceIndex | None = None) -> ExtractionResult:
|
|
1509
1588
|
result = ExtractionResult()
|
|
1510
1589
|
root = tree.root_node
|
|
1511
1590
|
|
|
1512
1591
|
def _line(node: Any) -> int:
|
|
1513
|
-
return
|
|
1592
|
+
return node.start_point[0] + 1
|
|
1514
1593
|
|
|
1515
|
-
|
|
1594
|
+
file_node = _node(file_id, "file", Path(rel_path).name, rel_path)
|
|
1595
|
+
if source_index is not None:
|
|
1596
|
+
# For the dispatch post-pass, which takes it off again: what a call of
|
|
1597
|
+
# `<this module>.<name>` reaches where the module only imports the name.
|
|
1598
|
+
reexports = _python_module_reexports(file_id, rel_path, source, source_index)
|
|
1599
|
+
if reexports:
|
|
1600
|
+
file_node["_reexports"] = reexports
|
|
1601
|
+
result.nodes.append(file_node)
|
|
1516
1602
|
|
|
1517
1603
|
# One pass builds every Python scope and what each binds (#70, #71). The walk
|
|
1518
1604
|
# below reads it: each def/class gets its scope-qualified identity, and each
|
|
@@ -1550,8 +1636,9 @@ def _extract_python(file_id: str, rel_path: str, _source: bytes, tree: Any, sour
|
|
|
1550
1636
|
class_node = _node(did, "class", name, rel_path, _line(node), {"qualname": qualname})
|
|
1551
1637
|
body_scope = table.class_scope.get(node.id)
|
|
1552
1638
|
if body_scope is not None and body_scope.parent is not None:
|
|
1553
|
-
# For the dispatch post-pass (#73), which takes all
|
|
1554
|
-
# again: the bases in order,
|
|
1639
|
+
# For the dispatch post-pass (#73), which takes all six off
|
|
1640
|
+
# again: the bases in order, which of them are builtin classes
|
|
1641
|
+
# (#106), the names the body binds in some
|
|
1555
1642
|
# other way than one `def` written straight in it (a `def`
|
|
1556
1643
|
# under an `if` is there only if the `if` ran it, and one
|
|
1557
1644
|
# under `global` or `nonlocal` binds the name somewhere
|
|
@@ -1560,7 +1647,9 @@ def _extract_python(file_id: str, rel_path: str, _source: bytes, tree: Any, sour
|
|
|
1560
1647
|
# is made beyond its body and bases. With them `self.m()` and
|
|
1561
1648
|
# `super().m()` are bound to the method Python finds, not to
|
|
1562
1649
|
# every method called `m`.
|
|
1563
|
-
class_node["_bases"] = _python_class_bases(
|
|
1650
|
+
class_node["_bases"], class_node["_builtin_bases"] = _python_class_bases(
|
|
1651
|
+
node, body_scope.parent, table, ids
|
|
1652
|
+
)
|
|
1564
1653
|
class_node["_stops"] = sorted(
|
|
1565
1654
|
{
|
|
1566
1655
|
bound for bound, binders in body_scope.binders.items()
|
|
@@ -1582,7 +1671,15 @@ def _extract_python(file_id: str, rel_path: str, _source: bytes, tree: Any, sour
|
|
|
1582
1671
|
for arg in base.children:
|
|
1583
1672
|
if arg.type.endswith("identifier") and arg.text:
|
|
1584
1673
|
base_name = arg.text.decode("utf-8", errors="ignore")
|
|
1585
|
-
|
|
1674
|
+
base_target = _make_id(base_name)
|
|
1675
|
+
if body_scope is not None and body_scope.parent is not None:
|
|
1676
|
+
# Where the source states which class the name
|
|
1677
|
+
# is, the edge ends at that class (#86); any
|
|
1678
|
+
# other base keeps its placeholder.
|
|
1679
|
+
named = resolve(body_scope.parent, base_name)
|
|
1680
|
+
if named.kind in ("def", "symbol"):
|
|
1681
|
+
base_target = _python_definition_id(named, ids) or base_target
|
|
1682
|
+
result.edges.append(_edge(did, base_target, "inherits", rel_path, _line(arg)))
|
|
1586
1683
|
walk_children(node, did, scope_id)
|
|
1587
1684
|
elif node.type in ("import_statement", "import_from_statement"):
|
|
1588
1685
|
for module, dots in _python_import_modules(node):
|
|
@@ -1593,7 +1690,7 @@ def _extract_python(file_id: str, rel_path: str, _source: bytes, tree: Any, sour
|
|
|
1593
1690
|
)
|
|
1594
1691
|
if resolved:
|
|
1595
1692
|
result.edges.append(_edge(
|
|
1596
|
-
file_id, _file_node_id(resolved), "imports", rel_path,
|
|
1693
|
+
file_id, _file_node_id(resolved, source_index), "imports", rel_path,
|
|
1597
1694
|
_line(node), confidence="EXACT_IMPORT",
|
|
1598
1695
|
))
|
|
1599
1696
|
# `import pkg.sub` also imports `pkg` (#55). Deliberately NOT
|
|
@@ -1606,7 +1703,7 @@ def _extract_python(file_id: str, rel_path: str, _source: bytes, tree: Any, sour
|
|
|
1606
1703
|
if node.type == "import_statement" else ()
|
|
1607
1704
|
):
|
|
1608
1705
|
result.edges.append(_edge(
|
|
1609
|
-
file_id, _file_node_id(ancestor), "imports", rel_path,
|
|
1706
|
+
file_id, _file_node_id(ancestor, source_index), "imports", rel_path,
|
|
1610
1707
|
_line(node), confidence="EXACT_IMPORT",
|
|
1611
1708
|
))
|
|
1612
1709
|
else:
|
|
@@ -1616,7 +1713,7 @@ def _extract_python(file_id: str, rel_path: str, _source: bytes, tree: Any, sour
|
|
|
1616
1713
|
))
|
|
1617
1714
|
for sub in _python_from_import_submodules(node, rel_path, source_index):
|
|
1618
1715
|
result.edges.append(_edge(
|
|
1619
|
-
file_id, _file_node_id(sub), "imports", rel_path,
|
|
1716
|
+
file_id, _file_node_id(sub, source_index), "imports", rel_path,
|
|
1620
1717
|
_line(node), confidence="EXACT_IMPORT",
|
|
1621
1718
|
))
|
|
1622
1719
|
walk_children(node, parent_id, scope_id)
|
|
@@ -1628,8 +1725,14 @@ def _extract_python(file_id: str, rel_path: str, _source: bytes, tree: Any, sour
|
|
|
1628
1725
|
bare, obj_name, attr = _python_call_target(func) if func is not None else (None, None, None)
|
|
1629
1726
|
edge = None
|
|
1630
1727
|
scope = table.scope_of_call(node)
|
|
1631
|
-
|
|
1632
|
-
|
|
1728
|
+
# The list holds the builtins of every language, so a name on it is
|
|
1729
|
+
# left without an edge only where the file binds nothing by that
|
|
1730
|
+
# name: a class `Error` or a function `make` of this file or one it
|
|
1731
|
+
# imports is called like any other (#85).
|
|
1732
|
+
resolution = resolve(scope, bare) if bare else None
|
|
1733
|
+
if bare and resolution is not None and (
|
|
1734
|
+
bare not in _LANGUAGE_BUILTIN_GLOBALS or resolution.kind != "none"
|
|
1735
|
+
):
|
|
1633
1736
|
target, confidence = _python_bare_call(file_id, bare, resolution, table, ids)
|
|
1634
1737
|
edge = _edge(scope_id, target, "calls", rel_path, _line(node), confidence=confidence)
|
|
1635
1738
|
elif attr:
|
|
@@ -1716,7 +1819,7 @@ def _extract_go(file_id: str, rel_path: str, source: bytes, tree: Any) -> Extrac
|
|
|
1716
1819
|
root = tree.root_node
|
|
1717
1820
|
|
|
1718
1821
|
def _line(node: Any) -> int:
|
|
1719
|
-
return
|
|
1822
|
+
return node.start_point[0] + 1
|
|
1720
1823
|
|
|
1721
1824
|
def _text(node: Any) -> str | None:
|
|
1722
1825
|
return node.text.decode("utf-8", errors="ignore") if node is not None and node.text else None
|
|
@@ -1814,7 +1917,7 @@ def _extract_rust(
|
|
|
1814
1917
|
root = tree.root_node
|
|
1815
1918
|
|
|
1816
1919
|
def _line(node: Any) -> int:
|
|
1817
|
-
return
|
|
1920
|
+
return node.start_point[0] + 1
|
|
1818
1921
|
|
|
1819
1922
|
def _text(node: Any) -> str | None:
|
|
1820
1923
|
return node.text.decode("utf-8", errors="ignore") if node is not None and node.text else None
|
|
@@ -1887,7 +1990,7 @@ def _extract_rust(
|
|
|
1887
1990
|
result.edges.append(
|
|
1888
1991
|
_edge(
|
|
1889
1992
|
file_id,
|
|
1890
|
-
_file_node_id(resolved),
|
|
1993
|
+
_file_node_id(resolved, source_index),
|
|
1891
1994
|
"imports",
|
|
1892
1995
|
rel_path,
|
|
1893
1996
|
_line(node),
|
|
@@ -1913,7 +2016,7 @@ def _extract_rust(
|
|
|
1913
2016
|
result.edges.append(
|
|
1914
2017
|
_edge(
|
|
1915
2018
|
file_id,
|
|
1916
|
-
_file_node_id(resolution.rel_path),
|
|
2019
|
+
_file_node_id(resolution.rel_path, source_index),
|
|
1917
2020
|
"imports",
|
|
1918
2021
|
rel_path,
|
|
1919
2022
|
_line(node),
|
|
@@ -2058,6 +2161,18 @@ def extract_file(entry: FileEntry, cfg: Config, cache: Cache | None = None, sour
|
|
|
2058
2161
|
# Only resolver-consulting languages pay this invalidation: Go and Rust
|
|
2059
2162
|
# extraction is file-local and cannot go stale this way.
|
|
2060
2163
|
cache_language = f"{cache_language}:fs{source_index.file_set_digest()}"
|
|
2164
|
+
if entry.language == "python":
|
|
2165
|
+
# A name imported through a package is bound to the file the
|
|
2166
|
+
# package's `__init__.py` re-exports it from, and that file's bytes
|
|
2167
|
+
# are not the importer's (#87).
|
|
2168
|
+
cache_language = f"{cache_language}:rx{source_index.python_reexport_digest()}"
|
|
2169
|
+
if source_index is not None and source_index.file_ids:
|
|
2170
|
+
# A file node id is the plain one unless another path shares it, and an
|
|
2171
|
+
# import edge names its target by that id; so a cached extraction is
|
|
2172
|
+
# good only for the same set of marked ids (#82). A tree with no such
|
|
2173
|
+
# pair adds nothing here, and its keys are what they were.
|
|
2174
|
+
marked = "\0".join(f"{path}\0{file_id}" for path, file_id in sorted(source_index.file_ids.items()))
|
|
2175
|
+
cache_language = f"{cache_language}:fid{hashlib.blake2s(marked.encode('utf-8'), digest_size=8).hexdigest()}"
|
|
2061
2176
|
# What is cached names the file: every node id and `source_file` in it is
|
|
2062
2177
|
# built from the path. Keyed on the bytes and the language alone, two files
|
|
2063
2178
|
# with the same bytes shared one entry, so one of them was answered with
|
|
@@ -2070,7 +2185,7 @@ def extract_file(entry: FileEntry, cfg: Config, cache: Cache | None = None, sour
|
|
|
2070
2185
|
return _result_from_dict(cached)
|
|
2071
2186
|
|
|
2072
2187
|
rel_path = entry.rel_path
|
|
2073
|
-
file_id = _file_node_id(rel_path)
|
|
2188
|
+
file_id = _file_node_id(rel_path, source_index)
|
|
2074
2189
|
|
|
2075
2190
|
try:
|
|
2076
2191
|
with open(entry.abs_path, "rb") as f:
|
|
@@ -2134,6 +2249,9 @@ def extract_all(entries: list[FileEntry], cfg: Config, cache: Cache | None = Non
|
|
|
2134
2249
|
results: list[ExtractionResult] = []
|
|
2135
2250
|
error_records: list[dict[str, Any]] = []
|
|
2136
2251
|
source_index = SourceIndex.from_entries(entries, cfg)
|
|
2252
|
+
file_ids = _colliding_file_ids(entry.rel_path for entry in entries)
|
|
2253
|
+
if file_ids:
|
|
2254
|
+
source_index = dataclasses.replace(source_index, file_ids=file_ids)
|
|
2137
2255
|
if cfg.workers <= 1:
|
|
2138
2256
|
for entry in entries:
|
|
2139
2257
|
result = extract_file(entry, cfg, cache, source_index)
|
|
@@ -2171,7 +2289,7 @@ _MAX_METHOD_DISPATCH_CANDIDATES = 3
|
|
|
2171
2289
|
|
|
2172
2290
|
def _python_class_bases(
|
|
2173
2291
|
node: Any, scope: PyScope, table: ScopeTable, ids: dict[tuple[str, bool], str]
|
|
2174
|
-
) -> list[str | None]:
|
|
2292
|
+
) -> tuple[list[str | None], list[str | None]]:
|
|
2175
2293
|
"""Each base of a class statement, in order: the id of the class it names, or None.
|
|
2176
2294
|
|
|
2177
2295
|
A base is resolved where the source states it: a bare name that denotes a
|
|
@@ -2181,15 +2299,26 @@ def _python_class_bases(
|
|
|
2181
2299
|
It may bind any name, and it may derive from a class that was read.
|
|
2182
2300
|
`object` is left out: it is last in every linearisation and defines no
|
|
2183
2301
|
method of the repository. Class keywords (`metaclass=...`) are not bases.
|
|
2302
|
+
|
|
2303
|
+
The second list is as long as the first: the name of the builtin class a
|
|
2304
|
+
base is, where it is one (a bare name the file does not bind), and None
|
|
2305
|
+
elsewhere. Only `super()` reads it (#106): no class of the repository
|
|
2306
|
+
stands behind a builtin, so where the method `super()` finds is a
|
|
2307
|
+
builtin's, it is none of the repository's. A star import may bind the
|
|
2308
|
+
name; `super()` itself is not read beside one (`_is_bare_super`), so the
|
|
2309
|
+
list needs no check of its own for it.
|
|
2184
2310
|
"""
|
|
2185
2311
|
bases: list[str | None] = []
|
|
2312
|
+
builtin_bases: list[str | None] = []
|
|
2186
2313
|
arguments = node.child_by_field_name("superclasses")
|
|
2187
2314
|
for arg in arguments.named_children if arguments is not None else ():
|
|
2188
2315
|
if arg.type in ("comment", "keyword_argument", "dictionary_splat"):
|
|
2189
2316
|
continue
|
|
2190
|
-
|
|
2317
|
+
written = arg.text.decode("utf-8", errors="ignore")
|
|
2318
|
+
found = resolve(scope, written) if arg.type == "identifier" else None
|
|
2191
2319
|
if found is not None and found.kind in ("def", "symbol"):
|
|
2192
2320
|
bases.append(_python_definition_id(found, ids))
|
|
2321
|
+
builtin_bases.append(None)
|
|
2193
2322
|
elif (
|
|
2194
2323
|
found is not None and found.kind == "none"
|
|
2195
2324
|
and arg.text == b"object" and not table.module.star_import
|
|
@@ -2197,7 +2326,28 @@ def _python_class_bases(
|
|
|
2197
2326
|
continue
|
|
2198
2327
|
else:
|
|
2199
2328
|
bases.append(None)
|
|
2200
|
-
|
|
2329
|
+
builtin = (
|
|
2330
|
+
found is not None and found.kind == "none"
|
|
2331
|
+
and isinstance(getattr(builtins, written, None), type)
|
|
2332
|
+
)
|
|
2333
|
+
builtin_bases.append(written if builtin else None)
|
|
2334
|
+
return bases, builtin_bases
|
|
2335
|
+
|
|
2336
|
+
|
|
2337
|
+
#: What `class_method` answers where the method `super()` finds is a builtin's (#106).
|
|
2338
|
+
_A_BUILTIN_S_METHOD = "<builtin>"
|
|
2339
|
+
|
|
2340
|
+
|
|
2341
|
+
def _a_builtin_has(builtin_names: Collection[str], method: str) -> bool:
|
|
2342
|
+
"""Whether a method lookup that reaches these builtin classes finds `method`
|
|
2343
|
+
in one of them or in a class they derive from (`object` among them).
|
|
2344
|
+
|
|
2345
|
+
Each class's own namespace is read, not `hasattr`: `hasattr(dict, "mro")`
|
|
2346
|
+
is true because `type` defines `mro`, and `super()` never looks there.
|
|
2347
|
+
"""
|
|
2348
|
+
return any(
|
|
2349
|
+
method in vars(cls) for name in builtin_names for cls in getattr(builtins, name).__mro__
|
|
2350
|
+
)
|
|
2201
2351
|
|
|
2202
2352
|
|
|
2203
2353
|
def _python_class_making(node: Any, scope: PyScope, table: ScopeTable) -> list[str]:
|
|
@@ -2444,6 +2594,46 @@ def _dispatch_is_gated(source_file: str | None) -> bool:
|
|
|
2444
2594
|
return language in _DISPATCH_GATED_LANGUAGES
|
|
2445
2595
|
|
|
2446
2596
|
|
|
2597
|
+
def _follow_python_reexports(nodes: list[dict[str, Any]], edges: list[dict[str, Any]]) -> None:
|
|
2598
|
+
"""Re-point each id of a name a Python module only imports to its definition (#107).
|
|
2599
|
+
|
|
2600
|
+
`front.target(x)`, where `front.py` binds `target` only by `from pkg.impl
|
|
2601
|
+
import target`, was extracted as a call of `pkg_front_py_target`, which no
|
|
2602
|
+
file defines; so were `t = front.target; t(x)`, `from pkg.front import
|
|
2603
|
+
target` and a base class or receiver named that way. Each module's own
|
|
2604
|
+
imports are on its file node (`_reexports`); here they are followed across
|
|
2605
|
+
files, for as many hops as the source states, to the id the last module
|
|
2606
|
+
names. A definition is never moved: a module that defines a name binds it
|
|
2607
|
+
twice, and such a name is not recorded. A cycle stops at
|
|
2608
|
+
`MAX_REEXPORT_HOPS`, on an id no file defines.
|
|
2609
|
+
|
|
2610
|
+
Edge targets of every relation are re-pointed, and so are ``_receiver``
|
|
2611
|
+
on an edge and ``_bases`` on a class node, the other two places a
|
|
2612
|
+
definition id is read; ``_reexports`` is taken off every node.
|
|
2613
|
+
"""
|
|
2614
|
+
hops: dict[str, str] = {}
|
|
2615
|
+
for n in nodes:
|
|
2616
|
+
hops.update(n.pop("_reexports", None) or {})
|
|
2617
|
+
if not hops:
|
|
2618
|
+
return
|
|
2619
|
+
|
|
2620
|
+
def follow(target: str) -> str:
|
|
2621
|
+
for _ in range(MAX_REEXPORT_HOPS):
|
|
2622
|
+
hop = hops.get(target)
|
|
2623
|
+
if hop is None:
|
|
2624
|
+
break
|
|
2625
|
+
target = hop
|
|
2626
|
+
return target
|
|
2627
|
+
|
|
2628
|
+
for e in edges:
|
|
2629
|
+
e["target"] = follow(e["target"])
|
|
2630
|
+
if e.get("_receiver") is not None:
|
|
2631
|
+
e["_receiver"] = follow(e["_receiver"])
|
|
2632
|
+
for n in nodes:
|
|
2633
|
+
if n.get("_bases") is not None:
|
|
2634
|
+
n["_bases"] = [None if base is None else follow(base) for base in n["_bases"]]
|
|
2635
|
+
|
|
2636
|
+
|
|
2447
2637
|
def _resolve_method_dispatch(
|
|
2448
2638
|
nodes: list[dict[str, Any]], edges: list[dict[str, Any]]
|
|
2449
2639
|
) -> list[dict[str, Any]]:
|
|
@@ -2507,9 +2697,23 @@ def _resolve_method_dispatch(
|
|
|
2507
2697
|
`__init_subclass__` there can set a name on the class itself, over its own
|
|
2508
2698
|
`def`. So "bound" says what the classes that were read state, and not more.
|
|
2509
2699
|
|
|
2700
|
+
One case of a base that was not read is read for `super()` alone (#106):
|
|
2701
|
+
a builtin class, named in ``_builtin_bases``. No class of the repository
|
|
2702
|
+
stands behind a builtin. So where no class that was read binds the name,
|
|
2703
|
+
every base that was not read is a builtin, and a builtin (or `object`)
|
|
2704
|
+
has the name, what `super()` finds is the builtin's, and the call gets no
|
|
2705
|
+
edge, as a call of a builtin gets none. Bound by name, it was a call to
|
|
2706
|
+
every method of the name in reach.
|
|
2707
|
+
|
|
2708
|
+
Before any of it, a name a Python module only imports is followed to its
|
|
2709
|
+
definition (`_follow_python_reexports`, #107), so the ids read below are
|
|
2710
|
+
the definitions' own.
|
|
2711
|
+
|
|
2510
2712
|
``_member``, ``_receiver`` and ``_walk`` are stripped from every returned
|
|
2511
|
-
edge, and the
|
|
2713
|
+
edge, and the six class tags and ``_reexports`` from every node, so none
|
|
2714
|
+
leaks into the graph.
|
|
2512
2715
|
"""
|
|
2716
|
+
_follow_python_reexports(nodes, edges)
|
|
2513
2717
|
# method name (casefolded) -> set of definition node ids. A set collapses the
|
|
2514
2718
|
# same method appearing twice in the pre-dedup node list, so the cap counts
|
|
2515
2719
|
# distinct definitions.
|
|
@@ -2534,14 +2738,17 @@ def _resolve_method_dispatch(
|
|
|
2534
2738
|
instance_binds_of: dict[str, frozenset[str]] = {}
|
|
2535
2739
|
class_binds_of: dict[str, frozenset[str]] = {}
|
|
2536
2740
|
made_of: dict[str, frozenset[str]] = {}
|
|
2741
|
+
builtin_bases_of: dict[str, list[str | None]] = {}
|
|
2537
2742
|
for n in nodes:
|
|
2538
2743
|
bases = n.pop("_bases", None)
|
|
2744
|
+
builtin_bases = n.pop("_builtin_bases", None)
|
|
2539
2745
|
stops = n.pop("_stops", None)
|
|
2540
2746
|
instance_binds = n.pop("_self_binds", None)
|
|
2541
2747
|
class_binds = n.pop("_class_binds", None)
|
|
2542
2748
|
made = n.pop("_made", None)
|
|
2543
2749
|
if bases is not None:
|
|
2544
2750
|
bases_of[n["id"]] = bases
|
|
2751
|
+
builtin_bases_of[n["id"]] = list(builtin_bases or ())
|
|
2545
2752
|
stops_of[n["id"]] = frozenset(stops or ())
|
|
2546
2753
|
instance_binds_of[n["id"]] = frozenset(instance_binds or ())
|
|
2547
2754
|
class_binds_of[n["id"]] = frozenset(class_binds or ())
|
|
@@ -2604,6 +2811,21 @@ def _resolve_method_dispatch(
|
|
|
2604
2811
|
if (walk == "self" if current == cls else not private)
|
|
2605
2812
|
and ("decorator" in made_of[current] or body_binds(current, method))
|
|
2606
2813
|
]
|
|
2814
|
+
if walk == "super" and not binders and unread:
|
|
2815
|
+
# No class that was read binds the name. Where every base that
|
|
2816
|
+
# was not read is a builtin, no class of the repository stands
|
|
2817
|
+
# behind any of them, and one of them has the name, `super()`
|
|
2818
|
+
# finds a builtin's method (#106).
|
|
2819
|
+
builtin_names: list[str] = []
|
|
2820
|
+
for current, position in unread:
|
|
2821
|
+
named = builtin_bases_of.get(current, [])
|
|
2822
|
+
builtin = named[position] if position < len(named) else None
|
|
2823
|
+
if builtin is None:
|
|
2824
|
+
break
|
|
2825
|
+
builtin_names.append(builtin)
|
|
2826
|
+
else:
|
|
2827
|
+
if _a_builtin_has(builtin_names, method):
|
|
2828
|
+
return _A_BUILTIN_S_METHOD
|
|
2607
2829
|
if not unread:
|
|
2608
2830
|
# Every base was read, so the order is Python's own.
|
|
2609
2831
|
line = _c3_linearisation(cls, bases_of, linearisations) or ()
|
|
@@ -2627,8 +2849,17 @@ def _resolve_method_dispatch(
|
|
|
2627
2849
|
# Which file each definition lives in, and which files each file imports
|
|
2628
2850
|
# DIRECTLY. Both are needed to answer "could this caller have reached that
|
|
2629
2851
|
# definition at all" -- see the reachability filter below (#54).
|
|
2852
|
+
# The id a path's file node was given is read off that node: a path whose
|
|
2853
|
+
# plain id another path has was given another (#82).
|
|
2854
|
+
file_node_of_path: dict[str, str] = {
|
|
2855
|
+
n["source_file"]: n["id"] for n in nodes if n.get("kind") == "file" and n.get("source_file")
|
|
2856
|
+
}
|
|
2857
|
+
|
|
2858
|
+
def file_node_id_of(path: str) -> str:
|
|
2859
|
+
return file_node_of_path.get(path) or _file_node_id(path)
|
|
2860
|
+
|
|
2630
2861
|
file_of_node: dict[str, str] = {
|
|
2631
|
-
n["id"]:
|
|
2862
|
+
n["id"]: file_node_id_of(n["source_file"]) for n in nodes if n.get("source_file")
|
|
2632
2863
|
}
|
|
2633
2864
|
# Which interop family each definition belongs to, for the family gate below.
|
|
2634
2865
|
family_of_node: dict[str, str | None] = {
|
|
@@ -2676,6 +2907,10 @@ def _resolve_method_dispatch(
|
|
|
2676
2907
|
# `self.m()` / `super().m()`: the first `m` along the bases of the
|
|
2677
2908
|
# class the call is written in (#73).
|
|
2678
2909
|
own = class_method(receiver, method, walk)
|
|
2910
|
+
if own == _A_BUILTIN_S_METHOD:
|
|
2911
|
+
# What runs is a builtin's method: no edge, as a call of a
|
|
2912
|
+
# builtin has none (#106).
|
|
2913
|
+
continue
|
|
2679
2914
|
else:
|
|
2680
2915
|
own = own_methods.get(receiver, {}).get(method) if receiver else None
|
|
2681
2916
|
if own is not None:
|
|
@@ -2733,7 +2968,7 @@ def _resolve_method_dispatch(
|
|
|
2733
2968
|
# reachable definition now resolves instead of being abandoned as
|
|
2734
2969
|
# "too generic to guess".
|
|
2735
2970
|
if candidates and _dispatch_is_gated(e.get("source_file")):
|
|
2736
|
-
caller_file =
|
|
2971
|
+
caller_file = file_node_id_of(e["source_file"])
|
|
2737
2972
|
reachable: set[str] | frozenset[str] = imports_by_file.get(caller_file, frozenset())
|
|
2738
2973
|
in_file = methods_by_name_and_file[name]
|
|
2739
2974
|
candidates = {
|
graphite/extract/pyscope.py
CHANGED
|
@@ -112,7 +112,8 @@ class PyScope:
|
|
|
112
112
|
class Resolution:
|
|
113
113
|
"""What a bare name denotes at one call site."""
|
|
114
114
|
|
|
115
|
-
|
|
115
|
+
#: "member" is `qualname`, an attribute of the in-repo module file `target` (#90).
|
|
116
|
+
kind: str # "def" | "symbol" | "alias" | "member" | "external" | "ambiguous-import" | "value" | "none"
|
|
116
117
|
qualname: str | None = None
|
|
117
118
|
module_level: bool = False
|
|
118
119
|
target: str | None = None
|
|
@@ -211,6 +212,25 @@ def _value_origin(node: Any) -> tuple[str, str] | None:
|
|
|
211
212
|
return None
|
|
212
213
|
|
|
213
214
|
|
|
215
|
+
def _alias_origin(node: Any) -> tuple[str, str] | None:
|
|
216
|
+
"""("name", text) for a bare name, ("attr", "obj.attr") for one attribute of a name.
|
|
217
|
+
|
|
218
|
+
What an assignment of such an expression binds is the thing the expression
|
|
219
|
+
names, so a call of the new name is a call of that thing (#90). Anything
|
|
220
|
+
longer (`a.b.c`, `f().x`, a subscript) says too little and gives None.
|
|
221
|
+
"""
|
|
222
|
+
node = _unparenthesized(node)
|
|
223
|
+
if node is None:
|
|
224
|
+
return None
|
|
225
|
+
if node.type == "identifier":
|
|
226
|
+
return ("name", _text(node))
|
|
227
|
+
if node.type == "attribute":
|
|
228
|
+
obj, attr = node.child_by_field_name("object"), node.child_by_field_name("attribute")
|
|
229
|
+
if obj is not None and obj.type == "identifier" and attr is not None:
|
|
230
|
+
return ("attr", f"{_text(obj)}.{_text(attr)}")
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
|
|
214
234
|
def _value_binder(value: Any, scope: PyScope, handed_over: bool = False) -> Binder:
|
|
215
235
|
"""The binder of a name one statement binds to `value`, evaluated in `scope`.
|
|
216
236
|
|
|
@@ -219,7 +239,8 @@ def _value_binder(value: Any, scope: PyScope, handed_over: bool = False) -> Bind
|
|
|
219
239
|
"""
|
|
220
240
|
origin = _value_origin(value)
|
|
221
241
|
if origin is None:
|
|
222
|
-
|
|
242
|
+
alias = None if handed_over else _alias_origin(value)
|
|
243
|
+
return _VALUE if alias is None else Binder("value", origin=(alias[0], alias[1], scope))
|
|
223
244
|
how, name = origin
|
|
224
245
|
return Binder("value", origin=("with" if handed_over and how == "call" else how, name, scope))
|
|
225
246
|
|
|
@@ -599,20 +620,44 @@ def resolving_scope(scope: PyScope, name: str) -> PyScope | None:
|
|
|
599
620
|
return None
|
|
600
621
|
|
|
601
622
|
|
|
602
|
-
def resolve(scope: PyScope, name: str) -> Resolution:
|
|
623
|
+
def resolve(scope: PyScope, name: str, _following: frozenset[int] = frozenset()) -> Resolution:
|
|
603
624
|
"""What a bare `name` denotes when called from `scope`."""
|
|
604
625
|
home = resolving_scope(scope, name)
|
|
605
|
-
return Resolution("none") if home is None else _outcome(home.binders[name])
|
|
626
|
+
return Resolution("none") if home is None else _outcome(home.binders[name], _following)
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _aliased(binder: Binder, origin: tuple[str, str, PyScope], following: frozenset[int]) -> Resolution:
|
|
630
|
+
"""What the one assignment `name = <name or module.attr>` makes the name denote (#90).
|
|
631
|
+
|
|
632
|
+
A definition or an imported symbol stays what it is. `module.attr` is
|
|
633
|
+
"member": the attribute of an in-repo module, bound as the call
|
|
634
|
+
`module.attr()` is. Anything else, and a name that leads back to itself, is
|
|
635
|
+
a value as before.
|
|
636
|
+
"""
|
|
637
|
+
how, text, scope = origin
|
|
638
|
+
if id(binder) in following:
|
|
639
|
+
return Resolution("value")
|
|
640
|
+
following = following | {id(binder)}
|
|
641
|
+
if how == "name":
|
|
642
|
+
found = resolve(scope, text, following)
|
|
643
|
+
return found if found.kind in ("def", "symbol", "member") else Resolution("value")
|
|
644
|
+
module_name, attr = text.split(".", 1)
|
|
645
|
+
root = resolve(scope, module_name, following)
|
|
646
|
+
if root.kind == "alias" and root.target:
|
|
647
|
+
return Resolution("member", qualname=attr, target=root.target)
|
|
648
|
+
return Resolution("value")
|
|
606
649
|
|
|
607
650
|
|
|
608
|
-
def _outcome(binders: list[Binder]) -> Resolution:
|
|
651
|
+
def _outcome(binders: list[Binder], following: frozenset[int] = frozenset()) -> Resolution:
|
|
609
652
|
"""§4.2's outcome table, for the binders of one name in its resolving scope."""
|
|
610
|
-
distinct: dict[tuple[str | None, ...], Binder] = {}
|
|
653
|
+
distinct: dict[tuple[str | int | None, ...], Binder] = {}
|
|
611
654
|
for binder in binders:
|
|
612
655
|
if binder.kind in ("def", "class"):
|
|
613
|
-
key: tuple[str | None, ...] = ("def", binder.qualname)
|
|
656
|
+
key: tuple[str | int | None, ...] = ("def", binder.qualname)
|
|
614
657
|
elif binder.kind == "import":
|
|
615
658
|
key = ("import", binder.import_kind, binder.target)
|
|
659
|
+
elif binder.origin is not None and binder.origin[0] in ("name", "attr"):
|
|
660
|
+
key = ("alias", binder.origin[0], binder.origin[1], id(binder.origin[2]))
|
|
616
661
|
else:
|
|
617
662
|
key = ("value",)
|
|
618
663
|
distinct.setdefault(key, binder)
|
|
@@ -622,6 +667,8 @@ def _outcome(binders: list[Binder]) -> Resolution:
|
|
|
622
667
|
return Resolution("def", qualname=binder.qualname, module_level=binder.module_level)
|
|
623
668
|
if binder.kind == "import" and binder.import_kind is not None and binder.import_kind != "unknown":
|
|
624
669
|
return Resolution(binder.import_kind, target=binder.target)
|
|
670
|
+
if binder.origin is not None and binder.origin[0] in ("name", "attr"):
|
|
671
|
+
return _aliased(binder, binder.origin, following)
|
|
625
672
|
return Resolution("value")
|
|
626
673
|
# Unresolved imports of one name (`try: import ujson as json` /
|
|
627
674
|
# `except ImportError: import json`) leave the repo whichever one runs. So
|
|
@@ -643,6 +690,9 @@ def _origin_receiver(how: str, name: str, scope: PyScope) -> Receiver | None:
|
|
|
643
690
|
"""What a value of this origin is, with the name it calls resolved in `scope`."""
|
|
644
691
|
if how == "literal":
|
|
645
692
|
return _BUILTIN_RECEIVER
|
|
693
|
+
if how in ("name", "attr"):
|
|
694
|
+
# An alias (#90) is the thing it names, not what that thing returns.
|
|
695
|
+
return None
|
|
646
696
|
found = resolve(scope, name)
|
|
647
697
|
if found.kind == "none":
|
|
648
698
|
# Bound nowhere in the file, so the name is the builtin's own -- unless
|
graphite/hookinstall.py
CHANGED
|
@@ -159,6 +159,23 @@ def install_hooks(root: Path, interpreter: Path) -> list[str]:
|
|
|
159
159
|
return relocated
|
|
160
160
|
|
|
161
161
|
|
|
162
|
+
def chain_slots(hdir: Path) -> dict[str, dict[str, str | bool]]:
|
|
163
|
+
"""Where another tool's hook for each trigger goes, and whether one is there.
|
|
164
|
+
|
|
165
|
+
Each trampoline runs `<hook>.local` beside it first when that file exists,
|
|
166
|
+
so that is where another tool's hook for the same event belongs, in either
|
|
167
|
+
install order. The name is part of the hook contract (docs/compatibility.md);
|
|
168
|
+
`doctor --json` and `init` report it so another tool need not read it out of
|
|
169
|
+
the trampoline's shell (channel rounds 323, 324). It is named relative to
|
|
170
|
+
the hooks directory, which `core.hooksPath` may put outside the repository,
|
|
171
|
+
so the report carries no path. `present` is the trampoline's own `[ -f ]`.
|
|
172
|
+
"""
|
|
173
|
+
return {
|
|
174
|
+
hook: {"file": f"{hook}{CHAINED_SUFFIX}", "present": (hdir / f"{hook}{CHAINED_SUFFIX}").is_file()}
|
|
175
|
+
for hook in TRIGGERS
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
162
179
|
def uninstall_hooks(root: Path) -> list[str]:
|
|
163
180
|
"""Remove graphite's trampolines, restoring anything they chained.
|
|
164
181
|
|
graphite/init.py
CHANGED
|
@@ -397,6 +397,7 @@ def init_project(
|
|
|
397
397
|
"path": str(hookinstall.hooks_dir(root)),
|
|
398
398
|
"action": "installed",
|
|
399
399
|
"relocated": relocated,
|
|
400
|
+
"chain_slots": hookinstall.chain_slots(hookinstall.hooks_dir(root)),
|
|
400
401
|
}
|
|
401
402
|
elif install_hooks:
|
|
402
403
|
# Not a git repo (yet). `hookinstall.install_hooks` would still write
|
graphite/resolve.py
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
"""Source resolution helpers for Graphite extraction."""
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
|
+
import ast
|
|
4
5
|
import hashlib
|
|
5
6
|
import json
|
|
6
7
|
import posixpath
|
|
7
8
|
import tomllib
|
|
8
|
-
from dataclasses import dataclass
|
|
9
|
+
from dataclasses import dataclass, field
|
|
9
10
|
from functools import lru_cache
|
|
10
11
|
from pathlib import Path, PurePosixPath
|
|
11
12
|
from typing import TYPE_CHECKING, Final, Iterable
|
|
@@ -31,6 +32,102 @@ def _rel_path_set_digest(rel_paths: frozenset[str]) -> str:
|
|
|
31
32
|
digest.update(b"\0")
|
|
32
33
|
return digest.hexdigest()
|
|
33
34
|
|
|
35
|
+
#: How many re-exports one name is followed through. A real package chain is a
|
|
36
|
+
#: hop or two; the bound only has to be finite beside the cycle guard.
|
|
37
|
+
MAX_REEXPORT_HOPS: Final = 8
|
|
38
|
+
|
|
39
|
+
#: `(module path, name it binds) -> (module, leading dots, name there)`
|
|
40
|
+
ReexportTable = dict[tuple[str, str], tuple[str, int, str]]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _module_level_bindings(body: list[ast.stmt]) -> dict[str, list[ast.stmt]]:
|
|
44
|
+
"""Every statement that binds each name at module level, nested ones included.
|
|
45
|
+
|
|
46
|
+
A name bound under `if` or `try` counts as bound there, and so does a
|
|
47
|
+
name an `import` or `def` binds: the statement list is what lets the caller
|
|
48
|
+
tell a name bound exactly once, by one `from X import name`, from a name
|
|
49
|
+
the module binds some other way too. So does a `global` declaration of the
|
|
50
|
+
name in any function or class of the module, which binds it from there
|
|
51
|
+
(#107).
|
|
52
|
+
"""
|
|
53
|
+
bound: dict[str, list[ast.stmt]] = {}
|
|
54
|
+
|
|
55
|
+
def add(name: str, stmt: ast.stmt) -> None:
|
|
56
|
+
bound.setdefault(name, []).append(stmt)
|
|
57
|
+
|
|
58
|
+
def visit(stmts: list[ast.stmt]) -> None:
|
|
59
|
+
for stmt in stmts:
|
|
60
|
+
if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
61
|
+
add(stmt.name, stmt)
|
|
62
|
+
elif isinstance(stmt, ast.Import):
|
|
63
|
+
for alias in stmt.names:
|
|
64
|
+
add((alias.asname or alias.name).split(".", 1)[0], stmt)
|
|
65
|
+
elif isinstance(stmt, ast.ImportFrom):
|
|
66
|
+
for alias in stmt.names:
|
|
67
|
+
if alias.name != "*":
|
|
68
|
+
add(alias.asname or alias.name, stmt)
|
|
69
|
+
else:
|
|
70
|
+
for node in ast.walk(stmt):
|
|
71
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)):
|
|
72
|
+
add(node.id, stmt)
|
|
73
|
+
elif isinstance(node, ast.ExceptHandler) and node.name:
|
|
74
|
+
add(node.name, stmt)
|
|
75
|
+
elif isinstance(node, ast.alias):
|
|
76
|
+
add((node.asname or node.name).split(".", 1)[0], stmt)
|
|
77
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
78
|
+
add(node.name, stmt)
|
|
79
|
+
|
|
80
|
+
visit(body)
|
|
81
|
+
for stmt in body:
|
|
82
|
+
for node in ast.walk(stmt):
|
|
83
|
+
if isinstance(node, ast.Global):
|
|
84
|
+
for name in node.names:
|
|
85
|
+
add(name, node)
|
|
86
|
+
return bound
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def python_reexports_of(rel_path: str, source: bytes) -> ReexportTable:
|
|
90
|
+
"""The names one module binds only by a top-level `from X import name`.
|
|
91
|
+
|
|
92
|
+
A name the file binds any other way too (assigned, defined, imported a
|
|
93
|
+
second time, imported under a condition, rebound under `global`) is left
|
|
94
|
+
out, and so is a file that does not parse: the name then stays bound to
|
|
95
|
+
the module, as it was before re-exports were followed. A star import is
|
|
96
|
+
not read.
|
|
97
|
+
"""
|
|
98
|
+
try:
|
|
99
|
+
tree = ast.parse(source)
|
|
100
|
+
except (SyntaxError, ValueError, RecursionError):
|
|
101
|
+
return {}
|
|
102
|
+
bound = _module_level_bindings(tree.body)
|
|
103
|
+
table: ReexportTable = {}
|
|
104
|
+
for stmt in tree.body:
|
|
105
|
+
if not isinstance(stmt, ast.ImportFrom) or not stmt.module:
|
|
106
|
+
# `from . import sub` binds a submodule, which has its own path.
|
|
107
|
+
continue
|
|
108
|
+
for alias in stmt.names:
|
|
109
|
+
local = alias.asname or alias.name
|
|
110
|
+
if alias.name == "*" or len(bound.get(local, ())) != 1:
|
|
111
|
+
continue
|
|
112
|
+
table[(rel_path, local)] = (stmt.module, stmt.level, alias.name)
|
|
113
|
+
return table
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _python_reexports(entries: Iterable[FileEntry]) -> ReexportTable:
|
|
117
|
+
"""The re-export table of every package `__init__.py` among the entries."""
|
|
118
|
+
table: ReexportTable = {}
|
|
119
|
+
for entry in entries:
|
|
120
|
+
rel_path = PurePosixPath(entry.rel_path).as_posix()
|
|
121
|
+
if PurePosixPath(rel_path).name != "__init__.py":
|
|
122
|
+
continue
|
|
123
|
+
try:
|
|
124
|
+
source = Path(entry.abs_path).read_bytes()
|
|
125
|
+
except OSError:
|
|
126
|
+
continue
|
|
127
|
+
table.update(python_reexports_of(rel_path, source))
|
|
128
|
+
return table
|
|
129
|
+
|
|
130
|
+
|
|
34
131
|
_TS_EXTENSIONS = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs")
|
|
35
132
|
_INDEX_NAMES = tuple(f"index{ext}" for ext in _TS_EXTENSIONS)
|
|
36
133
|
_BUILTIN_OBJECTS = {
|
|
@@ -92,6 +189,14 @@ class SourceIndex:
|
|
|
92
189
|
# (crate dir, declared idents) per manifest -- the authoritative answer to
|
|
93
190
|
# "did THIS file's crate declare that dependency". See issue #38.
|
|
94
191
|
cargo_crate_dependencies: tuple[tuple[str, frozenset[str]], ...] = ()
|
|
192
|
+
# What each package `__init__.py` re-exports by a plain `from X import name`
|
|
193
|
+
# (#87). Read from the files themselves, so extraction of an importer that
|
|
194
|
+
# did not change depends on it: see `python_reexport_digest`.
|
|
195
|
+
python_reexports: ReexportTable = field(default_factory=dict, compare=False, repr=False)
|
|
196
|
+
# rel path -> file node id, for the paths of the tree whose plain id another
|
|
197
|
+
# path has too (#82). Empty for a tree without such a pair. Set by
|
|
198
|
+
# `extract_all`, which owns how a file node id is made.
|
|
199
|
+
file_ids: dict[str, str] = field(default_factory=dict, compare=False, repr=False)
|
|
95
200
|
|
|
96
201
|
@classmethod
|
|
97
202
|
def from_entries(cls, entries: Iterable[FileEntry], cfg: Config | None = None) -> "SourceIndex":
|
|
@@ -116,8 +221,42 @@ class SourceIndex:
|
|
|
116
221
|
cargo_crates=_load_cargo_crates(root, frozenset(rel_paths)),
|
|
117
222
|
cargo_dependencies=_load_cargo_dependencies(root, frozenset(rel_paths)),
|
|
118
223
|
cargo_crate_dependencies=_load_cargo_crate_dependencies(root, frozenset(rel_paths)),
|
|
224
|
+
python_reexports=_python_reexports(entries),
|
|
119
225
|
)
|
|
120
226
|
|
|
227
|
+
def python_reexport_digest(self) -> str:
|
|
228
|
+
"""Digest of the re-export table, for the cache key of a Python file.
|
|
229
|
+
|
|
230
|
+
An importer binds `from pkg import name` to whatever `pkg/__init__.py`
|
|
231
|
+
re-exports, and its bytes do not change when that does.
|
|
232
|
+
"""
|
|
233
|
+
digest = hashlib.blake2b(digest_size=8)
|
|
234
|
+
for (rel_path, name), (module, level, original) in sorted(self.python_reexports.items()):
|
|
235
|
+
digest.update(f"{rel_path}\0{name}\0{level}\0{module}\0{original}\0".encode("utf-8", errors="replace"))
|
|
236
|
+
return digest.hexdigest()
|
|
237
|
+
|
|
238
|
+
def follow_python_reexport(self, rel_path: str, name: str) -> tuple[str, str]:
|
|
239
|
+
"""The file and name that define `name` as `rel_path` exports it.
|
|
240
|
+
|
|
241
|
+
Follows `from X import name` statements the package `__init__.py`
|
|
242
|
+
makes, for as many steps as the source states. It stops where a hop does
|
|
243
|
+
not resolve to a file of the tree, where a name is bound some other way,
|
|
244
|
+
at a cycle, and at `MAX_REEXPORT_HOPS`; each returns the last place
|
|
245
|
+
reached, which is `(rel_path, name)` itself when nothing is followed.
|
|
246
|
+
"""
|
|
247
|
+
seen = {(rel_path, name)}
|
|
248
|
+
for _ in range(MAX_REEXPORT_HOPS):
|
|
249
|
+
hop = self.python_reexports.get((rel_path, name))
|
|
250
|
+
if hop is None:
|
|
251
|
+
break
|
|
252
|
+
module, level, original = hop
|
|
253
|
+
target = self.resolve_python_module(rel_path, module, level)
|
|
254
|
+
if target is None or (target, original) in seen:
|
|
255
|
+
break
|
|
256
|
+
seen.add((target, original))
|
|
257
|
+
rel_path, name = target, original
|
|
258
|
+
return rel_path, name
|
|
259
|
+
|
|
121
260
|
def file_set_digest(self) -> str:
|
|
122
261
|
"""Stable digest of the repo's file set.
|
|
123
262
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: graphite-code
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.1
|
|
4
4
|
Summary: Local-first, zero-LLM knowledge graph extraction for codebases.
|
|
5
5
|
Project-URL: Homepage, https://github.com/jared0565/graphite
|
|
6
6
|
Project-URL: Repository, https://github.com/jared0565/graphite
|
|
@@ -48,7 +48,7 @@ Description-Content-Type: text/markdown
|
|
|
48
48
|
|
|
49
49
|
Local-first, deterministic knowledge graph extraction for codebases — zero-LLM, daemon-maintained, agent-agnostic.
|
|
50
50
|
|
|
51
|
-
**Status: 1.
|
|
51
|
+
**Status: 1.4.1, production/stable.** Published on PyPI as
|
|
52
52
|
[`graphite-code`](https://pypi.org/project/graphite-code/) with PEP 740
|
|
53
53
|
attestations; supported on Windows, Linux and macOS with Python 3.11–3.14
|
|
54
54
|
(every cell gates CI). What 1.x promises — CLI, JSON outputs, `graph.json`,
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
graphite/__init__.py,sha256=
|
|
1
|
+
graphite/__init__.py,sha256=fJubHU5xsygeZUKPeWNvTkFskaO2ii3gcrbZasRIGzQ,2181
|
|
2
2
|
graphite/__main__.py,sha256=Bp5bcXE6M0AnuNW1LjOXOEvGG5r0fXZoeRb_k5Yxphs,149
|
|
3
3
|
graphite/_cleanup_worker.py,sha256=oIXOPa1jHVP8ePRSwn27nZEHOAc4DSBrjeH2Ds9wuq8,19619
|
|
4
4
|
graphite/_win32_ctypes.py,sha256=YLH4kpKjL7zUUOs9E8C-Kjdy45PJBd6eRUeKwiKdSV4,1476
|
|
5
5
|
graphite/activation.py,sha256=Jcgk8AFvqbMNQiPAa2MTzSO0BAYRC5FX6MsZUjbDe1I,5249
|
|
6
|
-
graphite/agent_hooks.py,sha256=
|
|
6
|
+
graphite/agent_hooks.py,sha256=cGNcInhk8B0Ek5V3vTtXtT1h_GOrttb0g9-0pwNZWII,66273
|
|
7
7
|
graphite/agent_settings.py,sha256=Ec95ilPhkPOM3vW67pdsjYivnCyc5uCqWfCBu-DLI3A,11085
|
|
8
8
|
graphite/analyze.py,sha256=BwiZ4lkQ8Oo8WvnIGLI03YSNUpynYvV46tVbzHH5iWQ,9304
|
|
9
9
|
graphite/answer_contract.py,sha256=KTnGmtT6gvi28-PhLZp9vaj7FDvGrqLW_BvhAa-VPR4,31237
|
|
@@ -11,7 +11,7 @@ graphite/bootstrap.py,sha256=OPDzN9jSr8IE1N7xOnVKk3FgO2UqBTOUNcNV-pZAsus,8448
|
|
|
11
11
|
graphite/buildlock.py,sha256=QXo4cnGGCmhxuuYdy6f5OHF82Yg6zHUMxLVdxwG49ic,5393
|
|
12
12
|
graphite/cache.py,sha256=Mh28dYg9irXBvH-oa8jpFSM-ehXcs5FuNVHVzF_WRA8,9143
|
|
13
13
|
graphite/channel.py,sha256=UNFAGuws6XFbkBu0fnVLepBDxT1BWAJlW33IPVlDi9M,72908
|
|
14
|
-
graphite/cli.py,sha256=
|
|
14
|
+
graphite/cli.py,sha256=JYypUmsaV3c3VILwI7ay0wd_D2m5PfAWStu55w0nMNg,161757
|
|
15
15
|
graphite/cluster.py,sha256=j5dFT40DD7scD4h8d7XJoAGQIcJKpsKsrFceiJkOuzw,4066
|
|
16
16
|
graphite/config.py,sha256=ZWhWOWYEyKGoHCp6vWI4M4NQM57ohf5BaX0Ty8HfWYM,9267
|
|
17
17
|
graphite/context.py,sha256=vWMuFxqDGby-9Gs_t9XNJzKR-nZqwMdbU2y6N_GypWU,13215
|
|
@@ -21,7 +21,7 @@ graphite/daemon_launch.py,sha256=d6VhJVARdhBSdGWPHxKgveDisX5JWHlDJeV6tjLJWKw,232
|
|
|
21
21
|
graphite/debt.py,sha256=mvxoFrICwbWP19YKlf1cZIPFg8qIf7Jgyr9kIweVBbE,4664
|
|
22
22
|
graphite/dependency_install.py,sha256=hcwRmg74BfweXfRzzgRqHhLGEEIWokNLebJCxM2D80k,58600
|
|
23
23
|
graphite/detach.py,sha256=BlUjeh_UcjpQ9DMRZFOgxhk83zUbMSTPmXe6t1FFEKE,1270
|
|
24
|
-
graphite/doctor.py,sha256=
|
|
24
|
+
graphite/doctor.py,sha256=4ZocGDXNFfAAeWempEjIe2-WwxROKygM04P3FfLC1qw,34733
|
|
25
25
|
graphite/doctor_probes.py,sha256=pSU62zuHv3pxcXZWquUUvd6UVur-grfrr3CJ0PM8uis,89852
|
|
26
26
|
graphite/engine_identity.py,sha256=hZYA9fBsg2fj_61Rtkc84XzJrdsa2MaDFOLZJV4I7eE,8951
|
|
27
27
|
graphite/freshness.py,sha256=kkhs-ArInlv1XxedmQRAFiThvrHt11mN5UAGCQCU4A8,5284
|
|
@@ -30,11 +30,11 @@ graphite/graph.py,sha256=2mhbIrx4ekidgXnw3gLWDtGcVdvOmYfpZ4oATtwbao0,4284
|
|
|
30
30
|
graphite/graph_io.py,sha256=rWjc3_Lq7DOg1_XuM4eY8GH9GwIHowo0CcABTIRtLyc,6563
|
|
31
31
|
graphite/health.py,sha256=Sh8P6_RvEBaFeICUbhncqw5I-Nlge9ASTkQpxSUtKfs,5525
|
|
32
32
|
graphite/hook_entry.py,sha256=0lfCZB9-B_9QBKagLhV_VIMVFcrOeAwpLcFXUjhMMpg,2655
|
|
33
|
-
graphite/hookinstall.py,sha256=
|
|
33
|
+
graphite/hookinstall.py,sha256=7qfboCBjP7DAeugbXXjZDDg-0aP7GJc_WhqxgJsOlV4,10215
|
|
34
34
|
graphite/hookshim.py,sha256=4to9xkNOWPjbk1Es97KTTknjJM9gdHkbEDjCQq8ntec,3771
|
|
35
35
|
graphite/incident_ledger.py,sha256=wHW-P_PJNollM_L9bAXHaxFeLb89wMXs7XX0VrH7aSw,8654
|
|
36
36
|
graphite/ingest.py,sha256=0uzPN7fyokVOL622TTXd7COpd5CpViOrsRYDm53Q1Qw,11952
|
|
37
|
-
graphite/init.py,sha256=
|
|
37
|
+
graphite/init.py,sha256=yoCyQ83UJ7Nb_suq_HUAVOwPhHbqpWfKtfD4P3n_LPE,41322
|
|
38
38
|
graphite/io.py,sha256=YBXfMcPsv1Lzun8ByW4BQlfgMm54akckLFrUhwWtleI,2996
|
|
39
39
|
graphite/launchd_agent.py,sha256=rmKhhCbB-9FDU_3A1b2OlZxKpxZqdgtYnLbzkFMs_rI,4529
|
|
40
40
|
graphite/listing.py,sha256=fxKBK7_1q9IcFK_VAhpQCKyDV7q_RajJ0r8O2h9rqes,1666
|
|
@@ -54,7 +54,7 @@ graphite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
|
54
54
|
graphite/query.py,sha256=qOObUOJGtHTf_MWrxNM1ykfl7TR2aqZ7MBvjib4i01Y,29659
|
|
55
55
|
graphite/query_plan.py,sha256=TLGwOnsL6Ia1hCsDzmWWBwtcn37Dn6aOuAvGowtgSXg,3768
|
|
56
56
|
graphite/replacement_audit.py,sha256=AR97eZ0h8Rx5VWOW2rJSqDGwEVwEDj08kcSiepyidaE,12393
|
|
57
|
-
graphite/resolve.py,sha256
|
|
57
|
+
graphite/resolve.py,sha256=bjpi2Lzti3GZheIJa8hM6HSOu9uKqiHz8vNGfq2pNOY,35103
|
|
58
58
|
graphite/review.py,sha256=Dd35aA8n5R1Osoop769uymdOFFZMB4BFexAKJD9bO7o,27810
|
|
59
59
|
graphite/savings.py,sha256=W5FbXScpteMTwngVUtDqPct99tHY7W8s3XlT4hbPJCY,3175
|
|
60
60
|
graphite/systemd_unit.py,sha256=oPfdHwFJpfW1RnQeIkyVnOYvDhSRjll57424whQYWg4,4503
|
|
@@ -71,8 +71,8 @@ graphite/export/html.py,sha256=WB-9p0fpjFh-bTpHl5aYg1UdM_PGXwaZEtyR3lleNZU,8949
|
|
|
71
71
|
graphite/export/json.py,sha256=oUrR1aXE5eiRDrj1_oXIl6qOPsTiqP3rmGtLfHF_nJc,1267
|
|
72
72
|
graphite/export/md.py,sha256=JqxULAZHdsxBsbgeZVzZ08C0_ZmQ9Tsln_dAmvHmbjY,2557
|
|
73
73
|
graphite/extract/__init__.py,sha256=HsF3yU1VcT3EsvUfxMJ0iVW2Ud_XrivnBGmdi9QTK3M,118
|
|
74
|
-
graphite/extract/ast.py,sha256=
|
|
75
|
-
graphite/extract/pyscope.py,sha256=
|
|
74
|
+
graphite/extract/ast.py,sha256=A7MrdPg-ibVyqTvi3Rtqbs3LR6u4iZbTxbTjJUws3QY,151139
|
|
75
|
+
graphite/extract/pyscope.py,sha256=bLsH5vJI10nLM12lGEeyvI3uG5uKXX0Jq4wl5TjfJc4,36460
|
|
76
76
|
graphite/routing/__init__.py,sha256=QlzeC4TbkzJNPn6vVrMH36FmpHrH0ZoJzjK_ckF-Z54,177
|
|
77
77
|
graphite/routing/approval.py,sha256=9roEO0d5hBhg3VgUaN8cw4wxzgJn6oKzhO7eQQ9cShQ,13872
|
|
78
78
|
graphite/routing/classifier.py,sha256=9JcVhxWnt9K_xMJkS-xiLUKYHi3LZiTGefkqBUSvvKc,6836
|
|
@@ -113,8 +113,8 @@ graphite/routing/zai_edit.py,sha256=Kra2tI9GkntQAhV1vNHlFlp4sY-ksq2-bY4N9fEfLEc,
|
|
|
113
113
|
graphite/routing/zai_executor.py,sha256=cHUl7DbWRUhYg9Lwm3OiP6H3dI70y_b8iAWCyfgOPi0,6636
|
|
114
114
|
graphite/routing/zai_probe.py,sha256=HL2vM8s2J4-n8Bp3l7QLpWLEk-PhZrt_rLc2cY65hvU,4771
|
|
115
115
|
graphite/ts_resolver.mjs,sha256=wiKDWkJIC9__3wL49ty4W8hRc5biisNNtFhH1aFA47A,10822
|
|
116
|
-
graphite_code-1.
|
|
117
|
-
graphite_code-1.
|
|
118
|
-
graphite_code-1.
|
|
119
|
-
graphite_code-1.
|
|
120
|
-
graphite_code-1.
|
|
116
|
+
graphite_code-1.4.1.dist-info/METADATA,sha256=k8GFijBqjBVrmtncEsLuh7QlrMuJBvJhWDb2KEoOnNY,48476
|
|
117
|
+
graphite_code-1.4.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
118
|
+
graphite_code-1.4.1.dist-info/entry_points.txt,sha256=-BpYAYFyn58DYi-hrFW9hMz6mTwNsYI44s9gaef4MiM,87
|
|
119
|
+
graphite_code-1.4.1.dist-info/licenses/LICENSE,sha256=mfotJ1Lk0VVUgoEPOIR7-x5cvYiz2UkuVH7e3fhoDiY,1066
|
|
120
|
+
graphite_code-1.4.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|