claude-code-router 0.1.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.
- ccr/__init__.py +0 -0
- ccr/__main__.py +4 -0
- ccr/cli.py +595 -0
- ccr/config.py +518 -0
- ccr/detect/__init__.py +123 -0
- ccr/doctor.py +208 -0
- ccr/entry.py +23 -0
- ccr/evaluate/__init__.py +13 -0
- ccr/evaluate/classify.py +335 -0
- ccr/evaluate/llm.py +182 -0
- ccr/evaluate/locate.py +359 -0
- ccr/evaluate/risk.py +285 -0
- ccr/evaluate/text.py +190 -0
- ccr/graph/__init__.py +15 -0
- ccr/graph/build.py +475 -0
- ccr/graph/db.py +88 -0
- ccr/graph/files.py +169 -0
- ccr/graph/git.py +90 -0
- ccr/graph/parse.py +510 -0
- ccr/graph/query.py +359 -0
- ccr/graph/resolve.py +256 -0
- ccr/headless.py +363 -0
- ccr/history/__init__.py +172 -0
- ccr/history/calibrate.py +161 -0
- ccr/history/dashboard.py +374 -0
- ccr/history/feedback.py +91 -0
- ccr/history/learn.py +184 -0
- ccr/history/prompts.py +120 -0
- ccr/history/redact.py +45 -0
- ccr/history/savings.py +187 -0
- ccr/history/shadow.py +114 -0
- ccr/history/stats.py +172 -0
- ccr/history/tune.py +80 -0
- ccr/history/why.py +186 -0
- ccr/hooks/__init__.py +134 -0
- ccr/hooks/bg.py +68 -0
- ccr/hooks/common.py +159 -0
- ccr/hooks/prompt.py +322 -0
- ccr/hooks/session_start.py +91 -0
- ccr/hooks/stop.py +52 -0
- ccr/hooks/tasks.py +170 -0
- ccr/install/__init__.py +388 -0
- ccr/install/agents.py +200 -0
- ccr/install/command.py +159 -0
- ccr/install/settings.py +175 -0
- ccr/memory/__init__.py +87 -0
- ccr/memory/signals.py +210 -0
- ccr/memory/sources.py +422 -0
- ccr/report.py +40 -0
- ccr/route/__init__.py +527 -0
- ccr/route/budget.py +166 -0
- ccr/statusline.py +143 -0
- ccr/transcript.py +98 -0
- claude_code_router-0.1.1.dist-info/METADATA +291 -0
- claude_code_router-0.1.1.dist-info/RECORD +58 -0
- claude_code_router-0.1.1.dist-info/WHEEL +4 -0
- claude_code_router-0.1.1.dist-info/entry_points.txt +2 -0
- claude_code_router-0.1.1.dist-info/licenses/LICENSE +21 -0
ccr/graph/parse.py
ADDED
|
@@ -0,0 +1,510 @@
|
|
|
1
|
+
"""Per-file extraction: symbols, call references, imports and complexity.
|
|
2
|
+
|
|
3
|
+
tree-sitter (via tree-sitter-language-pack) is used when a grammar is available locally;
|
|
4
|
+
otherwise regex heuristics run. Nothing in here may raise for a bad input file.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import bisect
|
|
9
|
+
import hashlib
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from ccr.graph.files import MAX_PARSE_BYTES, family_of
|
|
16
|
+
|
|
17
|
+
log = logging.getLogger("ccr.graph")
|
|
18
|
+
|
|
19
|
+
DEF_KINDS = {"function": "function", "method": "method", "class": "class",
|
|
20
|
+
"interface": "interface", "module": "module", "type": "type", "macro": "macro"}
|
|
21
|
+
CLASSLIKE = {"class", "interface", "type", "module", "struct", "impl", "trait", "enum"}
|
|
22
|
+
METHOD_PARENTS = CLASSLIKE - {"module"}
|
|
23
|
+
|
|
24
|
+
NEST_TYPES = [
|
|
25
|
+
"if_statement", "if_expression", "unless", "for_statement", "for_in_statement",
|
|
26
|
+
"for_of_statement", "enhanced_for_statement", "foreach_statement", "for_expression",
|
|
27
|
+
"for_range_loop", "while_statement", "while_expression", "do_statement", "loop_expression",
|
|
28
|
+
"until", "switch_statement", "switch_expression", "expression_switch_statement",
|
|
29
|
+
"type_switch_statement", "select_statement", "match_expression", "match_statement",
|
|
30
|
+
"case_statement", "when_expression", "try_statement", "try_expression", "begin_block",
|
|
31
|
+
]
|
|
32
|
+
BRANCH_TYPES = [
|
|
33
|
+
"elif_clause", "else_if_clause", "case_clause", "switch_case", "switch_section", "match_arm",
|
|
34
|
+
"when_entry", "catch_clause", "except_clause", "rescue", "conditional_expression",
|
|
35
|
+
"ternary_expression", "boolean_operator", "expression_case", "type_case",
|
|
36
|
+
"communication_case", "when", "elsif",
|
|
37
|
+
]
|
|
38
|
+
BRANCH_PATTERNS = ['(binary_expression operator: "&&")', '(binary_expression operator: "||")',
|
|
39
|
+
'(binary_expression operator: "and")', '(binary_expression operator: "or")']
|
|
40
|
+
NO_BRANCH = {"try_statement", "try_expression", "begin_block"}
|
|
41
|
+
IF_TYPES = {"if_statement", "if_expression"}
|
|
42
|
+
ELSE_PARENTS = {"else_clause", "else"}
|
|
43
|
+
|
|
44
|
+
# Supplemental call patterns for grammars whose bundled tags query has no reference.call.
|
|
45
|
+
CALL_PATTERNS = [
|
|
46
|
+
"(call_expression function: (identifier) @name) @reference.call",
|
|
47
|
+
"(call_expression function: (member_expression property: (property_identifier) @name))"
|
|
48
|
+
" @reference.call",
|
|
49
|
+
"(call_expression function: (field_expression field: (field_identifier) @name))"
|
|
50
|
+
" @reference.call",
|
|
51
|
+
"(call_expression function: (selector_expression field: (field_identifier) @name))"
|
|
52
|
+
" @reference.call",
|
|
53
|
+
"(call_expression function: (qualified_identifier name: (identifier) @name))"
|
|
54
|
+
" @reference.call",
|
|
55
|
+
"(invocation_expression function: (identifier) @name) @reference.call",
|
|
56
|
+
"(invocation_expression function: (member_access_expression name: (identifier) @name))"
|
|
57
|
+
" @reference.call",
|
|
58
|
+
"(new_expression constructor: (identifier) @name) @reference.call",
|
|
59
|
+
"(method_invocation name: (identifier) @name) @reference.call",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
# ----------------------------------------------------------------------------- imports
|
|
63
|
+
_R = lambda p: re.compile(p, re.MULTILINE) # noqa: E731
|
|
64
|
+
_PY_FROM = _R(r"^[ \t]*from[ \t]+(\.*[\w.]*)[ \t]+import[ \t]+(\([^)]*\)|[^\n#;]+)")
|
|
65
|
+
_PY_IMPORT = _R(r"^[ \t]*import[ \t]+([\w.]+(?:[ \t]+as[ \t]+\w+)?(?:[ \t]*,[ \t]*[\w.]+"
|
|
66
|
+
r"(?:[ \t]+as[ \t]+\w+)?)*)")
|
|
67
|
+
_GO_BLOCK = _R(r"^\s*import\s*\(([^)]*)\)")
|
|
68
|
+
IMPORT_RX: dict[str, list[tuple[re.Pattern, str]]] = {
|
|
69
|
+
"js": [
|
|
70
|
+
(re.compile(r"\b(?:import|export)\s+(?:type\s+)?[\w\s{},*$]*?\bfrom\s*['\"]([^'\"\n]+)['\"]"), ""),
|
|
71
|
+
(re.compile(r"\bimport\s*['\"]([^'\"\n]+)['\"]"), ""),
|
|
72
|
+
(re.compile(r"\b(?:require|import)\s*\(\s*['\"]([^'\"\n]+)['\"]\s*\)"), ""),
|
|
73
|
+
],
|
|
74
|
+
"go": [(_R(r"^\s*import\s+(?:[\w.]+\s+)?\"([^\"]+)\""), "")],
|
|
75
|
+
"jvm": [(_R(r"^\s*import\s+(?:static\s+)?([\w.]+(?:\.\*)?)"), "")],
|
|
76
|
+
"rust": [(_R(r"^\s*(?:pub(?:\([^)]*\))?\s+)?use\s+((?:::)?[\w:]+)"), ""),
|
|
77
|
+
(_R(r"^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+(\w+)\s*;"), "mod:")],
|
|
78
|
+
"c": [(_R(r"^\s*#\s*(?:include|import)\s*\"([^\"]+)\""), ""),
|
|
79
|
+
(_R(r"^\s*#\s*(?:include|import)\s*<([^>]+)>"), "<")],
|
|
80
|
+
"ruby": [(_R(r"^\s*require_relative\s*\(?\s*['\"]([^'\"]+)['\"]"), "./"),
|
|
81
|
+
(_R(r"^\s*(?:require|load)\s*\(?\s*['\"]([^'\"]+)['\"]"), "")],
|
|
82
|
+
"php": [(re.compile(r"\b(?:require|include)(?:_once)?\s*\(?\s*['\"]([^'\"]+)['\"]"), ""),
|
|
83
|
+
(_R(r"^\s*use\s+([\w\\]+)"), "ns:")],
|
|
84
|
+
"csharp": [(_R(r"^\s*using\s+(?:static\s+)?([\w.]+)\s*;"), "ns:")],
|
|
85
|
+
"zig": [(re.compile(r"@import\(\s*\"([^\"]+)\"\s*\)"), "")],
|
|
86
|
+
"lua": [(re.compile(r"\brequire\s*\(?\s*['\"]([^'\"]+)['\"]"), "")],
|
|
87
|
+
"elixir": [(_R(r"^\s*(?:alias|import|use|require)\s+([A-Z][\w.]*)"), "")],
|
|
88
|
+
"dart": [(_R(r"^\s*(?:import|export|part)\s+['\"]([^'\"]+)['\"]"), "")],
|
|
89
|
+
"swift": [(_R(r"^\s*import\s+(\w+)"), "ns:")],
|
|
90
|
+
"shell": [(_R(r"^\s*(?:source|\.)\s+['\"]?([\w./-]+\.(?:sh|bash))"), "")],
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _line_of(text: str, pos: int, starts: list[int]) -> int:
|
|
95
|
+
return bisect.bisect_right(starts, pos)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def extract_imports(text: str, family: str) -> list[tuple[str, int, bool]]:
|
|
99
|
+
"""Return (spec, line, optional). Optional specs are dropped when they do not resolve."""
|
|
100
|
+
starts = [0] + [m.end() for m in re.finditer("\n", text)]
|
|
101
|
+
out: list[tuple[str, int, bool]] = []
|
|
102
|
+
if family == "python":
|
|
103
|
+
for m in _PY_FROM.finditer(text):
|
|
104
|
+
mod, names = m.group(1), m.group(2).strip("() \t\n")
|
|
105
|
+
line = _line_of(text, m.start(), starts)
|
|
106
|
+
for item in names.split(","):
|
|
107
|
+
item = item.strip().split()[0] if item.strip() else ""
|
|
108
|
+
if item and item != "*" and item.isidentifier():
|
|
109
|
+
sep = "" if mod.endswith(".") or not mod else "."
|
|
110
|
+
out.append((f"{mod}{sep}{item}", line, True))
|
|
111
|
+
out.append((mod, line, False))
|
|
112
|
+
for m in _PY_IMPORT.finditer(text):
|
|
113
|
+
line = _line_of(text, m.start(), starts)
|
|
114
|
+
for part in m.group(1).split(","):
|
|
115
|
+
part = part.strip().split()[0] if part.strip() else ""
|
|
116
|
+
if part:
|
|
117
|
+
out.append((part, line, False))
|
|
118
|
+
return out
|
|
119
|
+
if family == "go":
|
|
120
|
+
for m in _GO_BLOCK.finditer(text):
|
|
121
|
+
base = _line_of(text, m.start(), starts)
|
|
122
|
+
for sm in re.finditer(r"\"([^\"]+)\"", m.group(1)):
|
|
123
|
+
out.append((sm.group(1), base + m.group(1).count("\n", 0, sm.start()), False))
|
|
124
|
+
for rx, prefix in IMPORT_RX.get(family, []):
|
|
125
|
+
for m in rx.finditer(text):
|
|
126
|
+
out.append((prefix + m.group(1), _line_of(text, m.start(), starts), False))
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# ----------------------------------------------------------------------------- regex symbols
|
|
131
|
+
_RX_FUNC = _R(r"^([ \t]*)(?:export\s+)?(?:default\s+)?(?:pub(?:\([^)]*\))?\s+)?"
|
|
132
|
+
r"(?:(?:public|private|protected|static|async|inline|extern|override|suspend)\s+)*"
|
|
133
|
+
r"(?:fn|func|function|def|defp|sub|proc|fun)\s+(?:\([^)]*\)\s*)?([A-Za-z_][\w!?]*)")
|
|
134
|
+
_RX_CLASS = _R(r"^([ \t]*)(?:export\s+)?(?:pub(?:\([^)]*\))?\s+)?"
|
|
135
|
+
r"(?:(?:public|private|protected|abstract|final|sealed|data|open|static)\s+)*"
|
|
136
|
+
r"(class|struct|interface|trait|enum|module|object|protocol|impl|defmodule)\s+"
|
|
137
|
+
r"([A-Za-z_][\w.]*)")
|
|
138
|
+
_RX_ZIG_TYPE = _R(r"^([ \t]*)(?:pub\s+)?const\s+(\w+)\s*=\s*(?:packed\s+|extern\s+)?"
|
|
139
|
+
r"(struct|enum|union)\b")
|
|
140
|
+
_RX_BRANCH = re.compile(r"\b(?:if|elif|elsif|for|foreach|while|until|case|when|catch|except|"
|
|
141
|
+
r"rescue|guard|unless)\b|&&|\|\|")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _indent_nesting(lines: list[str]) -> int:
|
|
145
|
+
indents = []
|
|
146
|
+
for ln in lines:
|
|
147
|
+
s = ln.expandtabs(4)
|
|
148
|
+
stripped = s.lstrip()
|
|
149
|
+
if stripped:
|
|
150
|
+
indents.append(len(s) - len(stripped))
|
|
151
|
+
nz = [i for i in indents if i > 0]
|
|
152
|
+
if not nz:
|
|
153
|
+
return 0
|
|
154
|
+
unit = max(1, min(nz))
|
|
155
|
+
return min(50, max(indents) // unit)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def regex_extract(text: str) -> tuple[list[list], int, int]:
|
|
159
|
+
"""Symbols via regex. Returns (symbols, branches, nesting)."""
|
|
160
|
+
lines = text.split("\n")
|
|
161
|
+
starts = [0] + [m.end() for m in re.finditer("\n", text)]
|
|
162
|
+
found: list[tuple[int, int, str, str]] = [] # (line, indent, kind, name)
|
|
163
|
+
for m in _RX_CLASS.finditer(text):
|
|
164
|
+
kind = m.group(2)
|
|
165
|
+
kind = "class" if kind not in ("interface", "module", "defmodule") else (
|
|
166
|
+
"interface" if kind == "interface" else "module")
|
|
167
|
+
found.append((_line_of(text, m.start(), starts), len(m.group(1).expandtabs(4)),
|
|
168
|
+
kind, m.group(3)))
|
|
169
|
+
for m in _RX_ZIG_TYPE.finditer(text):
|
|
170
|
+
found.append((_line_of(text, m.start(), starts), len(m.group(1).expandtabs(4)),
|
|
171
|
+
"class", m.group(2)))
|
|
172
|
+
for m in _RX_FUNC.finditer(text):
|
|
173
|
+
found.append((_line_of(text, m.start(), starts), len(m.group(1).expandtabs(4)),
|
|
174
|
+
"function", m.group(2)))
|
|
175
|
+
found.sort()
|
|
176
|
+
symbols: list[list] = []
|
|
177
|
+
stack: list[int] = [] # indices of open class-like symbols
|
|
178
|
+
for i, (line, indent, kind, name) in enumerate(found):
|
|
179
|
+
end = len(lines)
|
|
180
|
+
for nline, nindent, _, _ in found[i + 1:]:
|
|
181
|
+
if nindent <= indent:
|
|
182
|
+
end = max(line, nline - 1)
|
|
183
|
+
break
|
|
184
|
+
while stack and not (symbols[stack[-1]][2] < line <= symbols[stack[-1]][3]):
|
|
185
|
+
stack.pop()
|
|
186
|
+
parent = stack[-1] if stack else -1
|
|
187
|
+
if kind == "function" and parent >= 0 and symbols[parent][0] in METHOD_PARENTS:
|
|
188
|
+
kind = "method"
|
|
189
|
+
body = "\n".join(lines[line - 1:end])
|
|
190
|
+
symbols.append([kind, name, line, end, parent, len(_RX_BRANCH.findall(body)),
|
|
191
|
+
_indent_nesting(lines[line:end]) if end > line else 0])
|
|
192
|
+
if kind in CLASSLIKE:
|
|
193
|
+
stack.append(len(symbols) - 1)
|
|
194
|
+
return symbols, len(_RX_BRANCH.findall(text)), _indent_nesting(lines)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# ----------------------------------------------------------------------------- tree-sitter
|
|
198
|
+
_TS: dict[str, Any] = {} # lang -> (parser, tags query | None, branch query | None) or None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _compile_ok(lang_obj, src: str):
|
|
202
|
+
from tree_sitter import Query
|
|
203
|
+
try:
|
|
204
|
+
return Query(lang_obj, src)
|
|
205
|
+
except Exception: # QueryError, NameError on unknown nodes/fields
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
TAGS_INHERIT = {"typescript": ["javascript"], "tsx": ["javascript"]}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def split_patterns(src: str) -> list[str]:
|
|
213
|
+
"""Split a query source into top-level patterns (with trailing captures/quantifiers)."""
|
|
214
|
+
out: list[str] = []
|
|
215
|
+
i, n, depth, start = 0, len(src), 0, None
|
|
216
|
+
while i < n:
|
|
217
|
+
c = src[i]
|
|
218
|
+
if c == ";":
|
|
219
|
+
j = src.find("\n", i)
|
|
220
|
+
i = n if j == -1 else j
|
|
221
|
+
continue
|
|
222
|
+
if c == '"':
|
|
223
|
+
i += 1
|
|
224
|
+
while i < n and src[i] != '"':
|
|
225
|
+
i += 2 if src[i] == "\\" else 1
|
|
226
|
+
i += 1
|
|
227
|
+
continue
|
|
228
|
+
if c in "([":
|
|
229
|
+
if depth == 0 and start is None:
|
|
230
|
+
start = i
|
|
231
|
+
depth += 1
|
|
232
|
+
elif c in ")]":
|
|
233
|
+
depth -= 1
|
|
234
|
+
if depth == 0:
|
|
235
|
+
j = i + 1
|
|
236
|
+
while True: # trailing quantifiers / captures belong to this pattern
|
|
237
|
+
m = re.match(r"\s*(?:[*+?]|@[\w.-]+)", src[j:])
|
|
238
|
+
if not m:
|
|
239
|
+
break
|
|
240
|
+
j += m.end()
|
|
241
|
+
out.append(src[start:j])
|
|
242
|
+
start, i = None, j
|
|
243
|
+
continue
|
|
244
|
+
i += 1
|
|
245
|
+
return out
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _compile_lenient(lang_obj, src: str):
|
|
249
|
+
q = _compile_ok(lang_obj, src)
|
|
250
|
+
if q is not None or not src.strip():
|
|
251
|
+
return q
|
|
252
|
+
good = [p for p in split_patterns(src) if _compile_ok(lang_obj, p) is not None]
|
|
253
|
+
return _compile_ok(lang_obj, "\n".join(good)) if good else None
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _ts_for(lang: str):
|
|
257
|
+
if lang in _TS:
|
|
258
|
+
return _TS[lang]
|
|
259
|
+
entry = None
|
|
260
|
+
try:
|
|
261
|
+
import tree_sitter_language_pack as tslp
|
|
262
|
+
lang_obj = tslp.get_language(lang)
|
|
263
|
+
parser = tslp.get_parser(lang)
|
|
264
|
+
tags_src = "\n".join(filter(None, [tslp.get_tags_query(x) or ""
|
|
265
|
+
for x in TAGS_INHERIT.get(lang, []) + [lang]]))
|
|
266
|
+
tags = _compile_lenient(lang_obj, tags_src) if tags_src.strip() else None
|
|
267
|
+
has_calls = tags is not None and "reference.call" in tags_src
|
|
268
|
+
extra = []
|
|
269
|
+
if not has_calls:
|
|
270
|
+
extra = [p for p in CALL_PATTERNS if _compile_ok(lang_obj, p) is not None]
|
|
271
|
+
calls = _compile_ok(lang_obj, "\n".join(extra)) if extra else None
|
|
272
|
+
nest = [t for t in NEST_TYPES if _compile_ok(lang_obj, f"({t}) @n") is not None]
|
|
273
|
+
branch = [t for t in BRANCH_TYPES if _compile_ok(lang_obj, f"({t}) @b") is not None]
|
|
274
|
+
parts = []
|
|
275
|
+
if nest:
|
|
276
|
+
parts.append("[" + " ".join(f"({t})" for t in nest) + "] @nest")
|
|
277
|
+
branch = [f"({t})" for t in branch]
|
|
278
|
+
branch += [p for p in BRANCH_PATTERNS if _compile_ok(lang_obj, p + " @b") is not None]
|
|
279
|
+
if branch:
|
|
280
|
+
parts.append("[" + " ".join(branch) + "] @branch")
|
|
281
|
+
bq = _compile_ok(lang_obj, "\n".join(parts)) if parts else None
|
|
282
|
+
entry = (parser, tags, calls, bq)
|
|
283
|
+
except Exception as e: # grammar missing / download failure / ABI mismatch
|
|
284
|
+
log.debug("tree-sitter unavailable for %s: %s", lang, e)
|
|
285
|
+
entry = None
|
|
286
|
+
_TS[lang] = entry
|
|
287
|
+
return entry
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
_STRUCT_KIND = {"function": "function", "method": "method", "class": "class", "struct": "class",
|
|
291
|
+
"interface": "interface", "enum": "class", "module": "module",
|
|
292
|
+
"trait": "interface", "impl": "class", "namespace": "module"}
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _process_structure(text: str, lang: str) -> list[tuple[int, int, str, str]]:
|
|
296
|
+
"""Fallback symbols via tree_sitter_language_pack.process when no tags query exists.
|
|
297
|
+
|
|
298
|
+
Returns (start_line, end_line, kind, name)."""
|
|
299
|
+
import tree_sitter_language_pack as tslp
|
|
300
|
+
res = tslp.process(text, tslp.ProcessConfig(language=lang, structure=True, imports=False,
|
|
301
|
+
exports=False))
|
|
302
|
+
out: list[tuple[int, int, str, str]] = []
|
|
303
|
+
|
|
304
|
+
def walk(items):
|
|
305
|
+
for it in items:
|
|
306
|
+
raw = str(getattr(it.kind, "name", it.kind)).rsplit(".", 1)[-1].lower()
|
|
307
|
+
kind = _STRUCT_KIND.get(raw)
|
|
308
|
+
if kind and it.name and it.span:
|
|
309
|
+
out.append((it.span.start_line + 1, it.span.end_line + 1, kind, it.name))
|
|
310
|
+
walk(it.children or [])
|
|
311
|
+
|
|
312
|
+
walk(res.structure or [])
|
|
313
|
+
return out
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _collect_captures(root, data: bytes, tags, calls_q):
|
|
317
|
+
"""Definitions and call references from the tags / calls queries, by byte position."""
|
|
318
|
+
from tree_sitter import QueryCursor
|
|
319
|
+
defs: list[tuple[int, int, str, str, int, int]] = [] # (start, end, kind, name, sl, el)
|
|
320
|
+
refs_raw: list[tuple[int, str, int, int]] = [] # (pos, name, line, qualified)
|
|
321
|
+
seen: set[tuple[int, str]] = set()
|
|
322
|
+
for q in (tags, calls_q):
|
|
323
|
+
if q is None:
|
|
324
|
+
continue
|
|
325
|
+
for _, caps in QueryCursor(q).matches(root):
|
|
326
|
+
names = caps.get("name")
|
|
327
|
+
if not names:
|
|
328
|
+
continue
|
|
329
|
+
nm = names[0]
|
|
330
|
+
name = data[nm.start_byte:nm.end_byte].decode("utf-8", "replace")
|
|
331
|
+
for cname, nodes in caps.items():
|
|
332
|
+
if cname.startswith("definition."):
|
|
333
|
+
kind = DEF_KINDS.get(cname.split(".", 1)[1])
|
|
334
|
+
n = nodes[0]
|
|
335
|
+
if not kind or (n.start_byte, name) in seen:
|
|
336
|
+
continue
|
|
337
|
+
seen.add((n.start_byte, name))
|
|
338
|
+
defs.append((n.start_byte, n.end_byte, kind, name, n.start_point[0] + 1,
|
|
339
|
+
n.end_point[0] + 1))
|
|
340
|
+
elif cname == "reference.call":
|
|
341
|
+
call = nodes[0]
|
|
342
|
+
qual = (nm.parent is None or nm.parent.id != call.id
|
|
343
|
+
or call.child_by_field_name("object") is not None
|
|
344
|
+
or call.child_by_field_name("receiver") is not None)
|
|
345
|
+
refs_raw.append((call.start_byte, name, nm.start_point[0] + 1, int(qual)))
|
|
346
|
+
return defs, refs_raw
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _complexity(root, bq, pos) -> tuple[list[int], list[tuple[int, int]], int]:
|
|
350
|
+
"""Decision points and control-structure nesting: (branch positions, (pos, depth), max depth)."""
|
|
351
|
+
nests: list[tuple[int, int]] = []
|
|
352
|
+
branch_pos: list[int] = []
|
|
353
|
+
max_depth = 0
|
|
354
|
+
if bq is not None:
|
|
355
|
+
from tree_sitter import QueryCursor
|
|
356
|
+
caps = QueryCursor(bq).captures(root)
|
|
357
|
+
items = [(n.start_byte, -n.end_byte, "nest", n) for n in caps.get("nest", [])]
|
|
358
|
+
items += [(n.start_byte, -n.end_byte, "branch", n) for n in caps.get("branch", [])]
|
|
359
|
+
items.sort(key=lambda x: (x[0], x[1]))
|
|
360
|
+
stack: list[int] = []
|
|
361
|
+
for sb, neb, cap, n in items:
|
|
362
|
+
if cap == "branch":
|
|
363
|
+
branch_pos.append(pos(n))
|
|
364
|
+
continue
|
|
365
|
+
while stack and stack[-1] <= sb:
|
|
366
|
+
stack.pop()
|
|
367
|
+
if n.type not in NO_BRANCH:
|
|
368
|
+
branch_pos.append(pos(n))
|
|
369
|
+
if n.type in IF_TYPES and n.parent is not None and n.parent.type in ELSE_PARENTS:
|
|
370
|
+
continue # else-if chains do not deepen nesting
|
|
371
|
+
stack.append(-neb)
|
|
372
|
+
nests.append((pos(n), len(stack)))
|
|
373
|
+
max_depth = max(max_depth, len(stack))
|
|
374
|
+
branch_pos.sort()
|
|
375
|
+
nests.sort()
|
|
376
|
+
return branch_pos, nests, max_depth
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _assemble(defs, refs_raw, branch_pos: list[int], nests: list[tuple[int, int]]):
|
|
380
|
+
"""Symbols in start order (parent = innermost enclosing symbol) and refs attached to them."""
|
|
381
|
+
nest_pos = [p for p, _ in nests]
|
|
382
|
+
defs.sort(key=lambda d: (d[0], -d[1]))
|
|
383
|
+
symbols: list[list] = []
|
|
384
|
+
spans: list[tuple[int, int]] = []
|
|
385
|
+
st: list[int] = []
|
|
386
|
+
for s, e, kind, name, sl, el in defs:
|
|
387
|
+
while st and not (spans[st[-1]][0] <= s and e <= spans[st[-1]][1]):
|
|
388
|
+
st.pop()
|
|
389
|
+
parent = st[-1] if st else -1
|
|
390
|
+
if kind == "function" and parent >= 0 and symbols[parent][0] in METHOD_PARENTS:
|
|
391
|
+
kind = "method"
|
|
392
|
+
nb = bisect.bisect_left(branch_pos, e) - bisect.bisect_left(branch_pos, s)
|
|
393
|
+
depths = [d for _, d in nests[bisect.bisect_left(nest_pos, s):
|
|
394
|
+
bisect.bisect_left(nest_pos, e)]]
|
|
395
|
+
nd = (max(depths) - min(depths) + 1) if depths else 0
|
|
396
|
+
symbols.append([kind, name, sl, el, parent, nb, nd])
|
|
397
|
+
spans.append((s, e))
|
|
398
|
+
st.append(len(symbols) - 1)
|
|
399
|
+
|
|
400
|
+
starts = [sp[0] for sp in spans]
|
|
401
|
+
refs: list[tuple[int, str, int, int]] = []
|
|
402
|
+
for p, name, line, qual in refs_raw:
|
|
403
|
+
k = bisect.bisect_right(starts, p) - 1
|
|
404
|
+
while k >= 0 and not (spans[k][0] <= p < spans[k][1]):
|
|
405
|
+
k = symbols[k][4]
|
|
406
|
+
refs.append((k, name, line, qual))
|
|
407
|
+
return symbols, refs
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def ts_extract(data: bytes, lang: str):
|
|
411
|
+
"""Returns (symbols, refs, branches, nesting) or None when tree-sitter is unavailable.
|
|
412
|
+
|
|
413
|
+
symbols: [kind, name, start_line, end_line, parent_idx, branches, nesting]
|
|
414
|
+
refs: (caller_idx or -1, callee name, line, qualified 0/1)
|
|
415
|
+
"""
|
|
416
|
+
entry = _ts_for(lang)
|
|
417
|
+
if entry is None:
|
|
418
|
+
return None
|
|
419
|
+
parser, tags, calls_q, bq = entry
|
|
420
|
+
root = parser.parse(data).root_node
|
|
421
|
+
# Positions are byte offsets, or line numbers when symbols come from the line-based
|
|
422
|
+
# process() fallback; containment logic works the same in either unit.
|
|
423
|
+
defs, refs_raw = _collect_captures(root, data, tags, calls_q)
|
|
424
|
+
line_based = tags is None
|
|
425
|
+
if line_based:
|
|
426
|
+
try:
|
|
427
|
+
structure = _process_structure(data.decode("utf-8", "replace"), lang)
|
|
428
|
+
except Exception:
|
|
429
|
+
structure = []
|
|
430
|
+
if not structure:
|
|
431
|
+
return None # no tags query and no structure: regex does better here
|
|
432
|
+
defs = [(sl, el + 1, kind, name, sl, el) for sl, el, kind, name in structure]
|
|
433
|
+
refs_raw = [(line, name, line, q) for _, name, line, q in refs_raw]
|
|
434
|
+
|
|
435
|
+
def pos(n) -> int:
|
|
436
|
+
return n.start_point[0] + 1 if line_based else n.start_byte
|
|
437
|
+
|
|
438
|
+
branch_pos, nests, max_depth = _complexity(root, bq, pos)
|
|
439
|
+
symbols, refs = _assemble(defs, refs_raw, branch_pos, nests)
|
|
440
|
+
return symbols, refs, len(branch_pos), max_depth
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
# ----------------------------------------------------------------------------- entry point
|
|
444
|
+
_ALLOWED: frozenset[str] | None = None
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def init_worker(allowed: frozenset[str] | None) -> None:
|
|
448
|
+
global _ALLOWED
|
|
449
|
+
_ALLOWED = allowed
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def file_hash(data: bytes) -> str:
|
|
453
|
+
return hashlib.blake2b(data, digest_size=16).hexdigest()
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def parse_file(job: tuple[str, str, str | None, str | None]) -> dict:
|
|
457
|
+
"""job = (root, rel, ts_language or None, previous hash or None)."""
|
|
458
|
+
root, rel, lang, old_hash = job
|
|
459
|
+
res: dict = {"rel": rel, "status": "error", "lang": lang or "", "parser": "none",
|
|
460
|
+
"symbols": [], "refs": [], "imports": [], "loc": 0, "branches": 0,
|
|
461
|
+
"nesting": 0, "size": 0, "mtime_ns": 0, "hash": None}
|
|
462
|
+
path = os.path.join(root, rel)
|
|
463
|
+
try:
|
|
464
|
+
st = os.stat(path)
|
|
465
|
+
res["size"], res["mtime_ns"] = st.st_size, st.st_mtime_ns
|
|
466
|
+
with open(path, "rb") as f:
|
|
467
|
+
data = f.read()
|
|
468
|
+
except OSError:
|
|
469
|
+
return res
|
|
470
|
+
h = file_hash(data)
|
|
471
|
+
res["hash"] = h
|
|
472
|
+
if old_hash is not None and h == old_hash:
|
|
473
|
+
res["status"] = "unchanged"
|
|
474
|
+
return res
|
|
475
|
+
if b"\0" in data[:8192]:
|
|
476
|
+
res["status"] = "skipped"
|
|
477
|
+
return res
|
|
478
|
+
res["status"] = "parsed"
|
|
479
|
+
res["loc"] = sum(1 for ln in data.split(b"\n") if ln.strip())
|
|
480
|
+
if len(data) > MAX_PARSE_BYTES:
|
|
481
|
+
res["parser"] = "size-only"
|
|
482
|
+
return res
|
|
483
|
+
text = data.decode("utf-8", "replace")
|
|
484
|
+
try:
|
|
485
|
+
res["imports"] = extract_imports(text, family_of(rel))
|
|
486
|
+
except Exception as e:
|
|
487
|
+
log.debug("import extraction failed for %s: %s", rel, e)
|
|
488
|
+
out = None
|
|
489
|
+
if lang and (_ALLOWED is None or lang in _ALLOWED):
|
|
490
|
+
try:
|
|
491
|
+
out = ts_extract(data, lang)
|
|
492
|
+
except Exception as e:
|
|
493
|
+
log.debug("tree-sitter failed for %s: %s", rel, e)
|
|
494
|
+
out = None
|
|
495
|
+
if out is not None:
|
|
496
|
+
res["symbols"], res["refs"], res["branches"], res["nesting"] = out
|
|
497
|
+
res["parser"] = "tree-sitter"
|
|
498
|
+
return res
|
|
499
|
+
try:
|
|
500
|
+
res["symbols"], res["branches"], res["nesting"] = regex_extract(text)
|
|
501
|
+
res["parser"] = "regex"
|
|
502
|
+
except Exception as e:
|
|
503
|
+
log.debug("regex extraction failed for %s: %s", rel, e)
|
|
504
|
+
res["parser"] = "size-only"
|
|
505
|
+
return res
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def parse_many(jobs: list[tuple], allowed: frozenset[str] | None) -> list[dict]:
|
|
509
|
+
init_worker(allowed)
|
|
510
|
+
return [parse_file(j) for j in jobs]
|