codecop 0.1.0__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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,4565 @@
1
+ """Where each call site runs from, and what kind of code it lives in.
2
+
3
+ Built after the language extractors: a function index and a by-name call graph
4
+ per language (tree-sitter), entry points from `rules/entry_points.toml`, then a
5
+ breadth-first walk from each site's enclosing function up through its callers.
6
+
7
+ Precision comes first: a call is only followed when the receiver, the imports or
8
+ a unique name say which definition it is. A site with no origin is the honest
9
+ answer when the chain cannot be seen statically.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import bisect
15
+ import functools
16
+ import os
17
+ import re
18
+ import sys
19
+ import time
20
+ import tomllib
21
+ from collections import Counter, defaultdict, deque
22
+ from dataclasses import dataclass, fields, replace
23
+ from importlib import resources
24
+ from pathlib import Path
25
+
26
+ from tree_sitter import Language, Node, Parser, Query, QueryCursor
27
+
28
+ from .base import READ, is_test_path
29
+
30
+ @dataclass
31
+ class Settings:
32
+ """The limits of origin tracing. Every one is a setting: `[discover.origins]` in codecop.toml can override it
33
+ through `discover(..., settings=...)` -> `origins.annotate(..., settings=...)`, or `origins.SETTINGS` can be
34
+ changed for the process. The defaults are generous; lowering one trades origins for time."""
35
+
36
+ max_depth: int = 10 # caller hops walked up from a site
37
+ max_nodes: int = 4000 # functions visited per site before the walk stops
38
+ max_origins: int = 5 # origins listed per site (`origin_count` always has the full number)
39
+ max_implementations: int = 40 # Go: implementations of an interface followed from one call through it
40
+ max_overrides: int = 12 # Java: definitions of a method followed in a class, its ancestors and descendants
41
+
42
+ @classmethod
43
+ def of(cls, value: "Settings | dict | None") -> "Settings":
44
+ """A Settings from None (the module's SETTINGS), a Settings, or a mapping of some of its fields."""
45
+ if value is None:
46
+ return SETTINGS
47
+ if isinstance(value, cls):
48
+ return value
49
+ known = {f.name for f in fields(cls)}
50
+ return replace(SETTINGS, **{k: int(v) for k, v in dict(value).items() if k in known and v is not None})
51
+
52
+
53
+ SETTINGS = Settings()
54
+ DEBUG = bool(os.environ.get("CODECOP_ORIGINS_DEBUG")) # re-raise instead of counting an internal error
55
+ RECORD_PATHS = bool(os.environ.get("CODECOP_ORIGINS_PATHS")) # debugging: each origin lists the functions on its path
56
+ KEEP_CALLS = False # debugging: keep each function's raw call list after linking
57
+ TEST_KINDS = {"test"}
58
+ JOB_KINDS = {"workflow", "activity", "job", "consumer"}
59
+ KIND_ORDER = {"http": 0, "workflow": 1, "activity": 2, "consumer": 3, "job": 4, "main": 5, "cli": 6, "test": 7}
60
+ HTTP_VERBS = {"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "ANY", "WS", "TRACE", "CONNECT"}
61
+
62
+
63
+ _dirname = functools.lru_cache(maxsize=None)(os.path.dirname) # called per candidate while linking
64
+
65
+
66
+ def load_entry_rules() -> dict:
67
+ return tomllib.loads(resources.files("codecop.rules").joinpath("entry_points.toml").read_text())
68
+
69
+
70
+ # --------------------------------------------------------------------------- model
71
+
72
+ class Fn:
73
+ """One function or method definition (or a handler written inline as a closure)."""
74
+
75
+ __slots__ = ("id", "file", "lang", "name", "symbol", "container", "start", "end", "sb", "eb", "method",
76
+ "nparams", "lex", "loop", "test", "calls", "inline", "module", "extra", "abstract")
77
+
78
+ def __init__(self, file: str, lang: str, name: str, symbol: str, container: str, node_or_range, *,
79
+ method: bool = False, nparams: int = -1, test: bool = False, inline: bool = False, module: bool = False):
80
+ self.id = -1
81
+ self.file, self.lang, self.name, self.symbol, self.container = file, lang, name, symbol, container
82
+ if isinstance(node_or_range, tuple):
83
+ self.sb, self.eb, self.start, self.end = node_or_range
84
+ else:
85
+ n = node_or_range
86
+ self.sb, self.eb, self.start, self.end = n.start_byte, n.end_byte, n.start_point[0] + 1, n.end_point[0] + 1
87
+ self.method, self.nparams, self.test, self.inline, self.module = method, nparams, test, inline, module
88
+ self.lex: Fn | None = None # lexically enclosing function
89
+ self.loop = False # body holds an unbounded loop
90
+ self.calls: list[tuple] = [] # (kind 'c'|'r', name, qualifier, line, nargs)
91
+ self.extra = None # language-specific (Go/Java variable types)
92
+ self.abstract = False # declared without a body (an interface method): never an implementation
93
+
94
+
95
+ class Entry:
96
+ __slots__ = ("kind", "name", "file", "line", "targets", "pending", "decl", "path", "method", "loop_only",
97
+ "structs", "tag", "each", "only", "view")
98
+
99
+ def __init__(self, kind: str, name: str, file: str, line: int, *, targets=None, pending=None, decl: Fn | None = None,
100
+ path: str | None = None, method: str = "", loop_only: bool = False, structs: bool = False):
101
+ self.kind, self.name, self.file, self.line = kind, name, file, line
102
+ self.targets: list[Fn] = list(targets or [])
103
+ self.pending: list[tuple[Fn, tuple]] = list(pending or []) # (context function, call) resolved after parsing
104
+ self.decl = decl # function that declares the route (for nest prefixes)
105
+ self.path, self.method = path, method
106
+ self.loop_only, self.structs = loop_only, structs
107
+ self.tag = ""
108
+ self.each = "" # "method" | "verb": one entry point per target (a gRPC service, a class view)
109
+ self.only = None # with `each`: a callable giving the method names that are entry points, or None
110
+ self.view = None # Python: (file, class) of the view class this entry point is a method of
111
+
112
+
113
+ def _t(node: Node | None) -> str:
114
+ return node.text.decode("utf-8", "replace") if node is not None else ""
115
+
116
+
117
+ _STR = r'''(?:[rRbBfFuU]{0,2}"(?:[^"\\\n]|\\.)*"|[rRbBfFuU]{0,2}'(?:[^'\\\n]|\\.)*'|`[^`]*`)'''
118
+ _STR_RE = re.compile(_STR)
119
+ _TERM = re.compile(r"\s*(" + _STR + r"|[A-Za-z_][\w.:]*)\s*(\+|$)")
120
+ _VERB_WORD = re.compile(r"\b(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS|ANY|get|post|put|delete|patch|head|options)\b")
121
+
122
+
123
+ def _unquote(lit: str) -> str:
124
+ lit = lit.lstrip("rRbBfFuU")
125
+ if lit[:3] in ('"""', "'''") and len(lit) >= 6:
126
+ return lit[3:-3]
127
+ return lit[1:-1]
128
+
129
+
130
+ class Consts:
131
+ """String constants by name, for route paths written as `PREFIX + "/x"` or `SOME_PATH`."""
132
+
133
+ PATTERNS = {
134
+ "python": re.compile(rb"(?m)^[ \t]*([A-Za-z_]\w*)[ \t]*(?::[ \t]*[\w\[\], .]+)?=[ \t]*((?:[rf]?\"[^\"\n]*\"|[rf]?'[^'\n]*'|[A-Za-z_][\w.]*)(?:[ \t]*\+[ \t]*(?:[rf]?\"[^\"\n]*\"|[rf]?'[^'\n]*'|[A-Za-z_][\w.]*))*)[ \t]*$"),
135
+ "go": re.compile(rb"(?m)^[ \t]*(?:const[ \t]+|var[ \t]+)?([A-Za-z_]\w*)(?:[ \t]+string)?[ \t]*:?=[ \t]*((?:\"[^\"\n]*\"|`[^`\n]*`|[A-Za-z_][\w.]*)(?:[ \t]*\+[ \t]*(?:\"[^\"\n]*\"|`[^`\n]*`|[A-Za-z_][\w.]*))*)[ \t]*$"),
136
+ "rust": re.compile(rb"(?:const|static)\s+([A-Za-z_]\w*)\s*:\s*&\s*(?:'static\s+)?str\s*=\s*(\"(?:[^\"\\\n]|\\.)*\")\s*;"),
137
+ "java": re.compile(rb"String\s+([A-Za-z_]\w*)\s*=\s*((?:\"[^\"\n]*\"|[A-Za-z_][\w.]*)(?:\s*\+\s*(?:\"[^\"\n]*\"|[A-Za-z_][\w.]*))*)\s*;"),
138
+ }
139
+
140
+ def __init__(self):
141
+ self.by_name: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list)
142
+ self.importers: dict[str, object] = {} # language -> (file, name) -> (file, name) through an import alias
143
+
144
+ def scan(self, lang: str, rel: str, src: bytes) -> None:
145
+ for m in self.PATTERNS[lang].finditer(src):
146
+ expr = m.group(2)
147
+ if b'"' not in expr and b"'" not in expr and b"`" not in expr:
148
+ continue
149
+ self.by_name[(lang, m.group(1).decode())].append((rel, expr.decode("utf-8", "replace")))
150
+
151
+ def lookup(self, lang: str, rel: str, name: str) -> tuple[str, str] | None:
152
+ cands = self.by_name.get((lang, name), [])
153
+ same = [c for c in cands if c[0] == rel]
154
+ if same:
155
+ return same[-1] if len({c[1] for c in same}) == 1 else None
156
+ via = self.importers.get(lang)
157
+ if via is not None: # `from mod import PATH as OTHER_PATH`
158
+ src = via(rel, name)
159
+ if src is not None:
160
+ hit = [c for c in self.by_name.get((lang, src[1]), []) if c[0] == src[0]]
161
+ if hit:
162
+ return hit[-1]
163
+ if not cands:
164
+ return None
165
+ d = os.path.dirname(rel)
166
+ near = [c for c in cands if os.path.dirname(c[0]) == d]
167
+ if near and len({c[1] for c in near}) == 1:
168
+ return near[0]
169
+ return cands[0] if len({c[1] for c in cands}) == 1 else None
170
+
171
+ def eval(self, lang: str, rel: str, text: str, depth: int = 0, unknown=()) -> tuple[str, bool]:
172
+ """Value of a string expression; unknown parts become `…`. Returns (value, fully resolved).
173
+ `unknown`: names that are parameters of the enclosing function, never a constant of that name elsewhere."""
174
+ text = text.strip()
175
+ out, ok, pos = [], True, 0
176
+ while pos < len(text):
177
+ m = _TERM.match(text, pos)
178
+ if not m:
179
+ return ("".join(out) + "…", False) if out else ("…", False)
180
+ term = m.group(1)
181
+ if term[0] in "\"'`" or (len(term) > 1 and term[1] in "\"'") or (len(term) > 2 and term[2] in "\"'"):
182
+ out.append(_unquote(term))
183
+ else:
184
+ hit = self.lookup(lang, rel, re.split(r"\.|::", term)[-1]) if depth < 4 and term not in unknown else None
185
+ if hit is None:
186
+ out.append("…")
187
+ ok = False
188
+ else:
189
+ value, sub_ok = self.eval(lang, hit[0], hit[1], depth + 1)
190
+ out.append(value)
191
+ ok = ok and sub_ok
192
+ pos = m.end()
193
+ value = "".join(out)
194
+ return re.sub(r"…+", "…", value), ok
195
+
196
+
197
+ def _join_path(prefix: str, path: str) -> str:
198
+ if not prefix:
199
+ return path
200
+ if not path:
201
+ return prefix
202
+ return prefix.rstrip("/") + "/" + path.lstrip("/")
203
+
204
+
205
+ _ROUTE_REGEX = re.compile(r"\(\?P<|^\^|\$$|\\[dwWsS.\-/]|\[\^/\]|\(\?:")
206
+
207
+
208
+ def _readable_route(path: str) -> str:
209
+ """A route written as a regular expression (Django `re_path` / `url`, Tornado, Sentry), as a route with
210
+ named parameters: `^(?P<org>[^/]+)/issues/(?P<id>\\d+)/$` -> `/{org}/issues/{id}/`. A group without a name
211
+ becomes `{}`; an optional trailing slash is dropped. A path that is not a regular expression is returned as is."""
212
+ if not _ROUTE_REGEX.search(path):
213
+ return path
214
+ out, i, n = [], 0, len(path)
215
+ while i < n:
216
+ c = path[i]
217
+ if c == "(":
218
+ depth, j, in_class = 1, i + 1, False
219
+ while j < n and depth:
220
+ ch = path[j]
221
+ if ch == "\\":
222
+ j += 1
223
+ elif in_class:
224
+ in_class = ch != "]"
225
+ elif ch == "[":
226
+ in_class = True
227
+ elif ch == "(":
228
+ depth += 1
229
+ elif ch == ")":
230
+ depth -= 1
231
+ j += 1
232
+ group = path[i + 1:j - 1] if not depth else path[i + 1:]
233
+ m = re.match(r"\?P<(\w+)>", group)
234
+ if m:
235
+ out.append("{" + m.group(1) + "}")
236
+ elif group.startswith("?:") and "|" not in group and not re.search(r"[\[\\(.*+]", group[2:]):
237
+ out.append(group[2:]) # (?:literal)
238
+ else:
239
+ out.append("{}")
240
+ i = j
241
+ if i < n and path[i] in "?*+": # an optional group: the parameter may be absent
242
+ i += 1
243
+ continue
244
+ if c == "\\" and i + 1 < n:
245
+ nxt = path[i + 1]
246
+ out.append("{}" if nxt in "dwWsS" else nxt)
247
+ i += 2
248
+ if nxt in "dwWsS" and i < n and path[i] in "+*?":
249
+ i += 1
250
+ continue
251
+ if c == "[": # a character class outside a group: one unnamed part
252
+ j = path.find("]", i + 2)
253
+ j = n if j < 0 else j + 1
254
+ if j < n and path[j] in "+*?":
255
+ j += 1
256
+ out.append("{}")
257
+ i = j
258
+ continue
259
+ if c in "^$":
260
+ i += 1
261
+ continue
262
+ if c == "?" and out and out[-1] == "/": # `/?`: the slash is optional
263
+ out.pop()
264
+ i += 1
265
+ continue
266
+ out.append(c)
267
+ i += 1
268
+ text = re.sub(r"(?:\{\})+", "{}", "".join(out))
269
+ return text if text.startswith(("/", "…")) or not text else "/" + text
270
+
271
+
272
+ def _http_name(method: str, path: str) -> str:
273
+ path = _readable_route(path.strip())
274
+ first = path.split(" ", 1)
275
+ if len(first) == 2 and first[0] in HTTP_VERBS:
276
+ return path
277
+ return f"{method or 'ANY'} {path or '…'}"
278
+
279
+
280
+ # --------------------------------------------------------------------------- shared language base
281
+
282
+ class Lang:
283
+ name = ""
284
+ exts: tuple[str, ...] = ()
285
+
286
+ def __init__(self, index: "Index", rules: dict):
287
+ self.ix = index
288
+ self.rules = rules
289
+ self.loop_re = re.compile(rules["loop"].encode()) if rules.get("loop") else None
290
+ self.fn_names: set[str] = set()
291
+ self.by_name: dict[str, list[Fn]] = defaultdict(list)
292
+ self._lex_index: dict[tuple[str, bool], tuple[int, dict[tuple[int, str], Fn]]] = {}
293
+
294
+ def _compile(self, key: str) -> list[tuple[re.Pattern, dict]]:
295
+ return [(re.compile(r["match"]), r) for r in self.rules.get(key, [])]
296
+
297
+ # -- per file --------------------------------------------------------------
298
+ def prescan(self, rel: str, src: bytes) -> None: ...
299
+ def parse(self, rel: str, src: bytes) -> None: ...
300
+ def finish(self) -> None: ...
301
+ def resolve(self, fn: Fn, call: tuple) -> list[Fn]:
302
+ return []
303
+
304
+ def add_fn(self, fn: Fn) -> Fn:
305
+ self.ix.add_fn(fn)
306
+ if not fn.module and not fn.inline:
307
+ self.by_name[fn.name].append(fn)
308
+ return fn
309
+
310
+ def link(self, rel: str, src: bytes) -> list[Fn]:
311
+ """Sort a file's functions, set lexical parents and loop flags. Returns them sorted."""
312
+ fns = self.ix.by_file.get(rel, [])
313
+ fns.sort(key=lambda f: (f.sb, -f.eb))
314
+ stack: list[Fn] = []
315
+ for f in fns:
316
+ while stack and stack[-1].eb <= f.sb:
317
+ stack.pop()
318
+ f.lex = stack[-1] if stack else None
319
+ stack.append(f)
320
+ self.ix.starts[rel] = [f.sb for f in fns]
321
+ if self.loop_re is not None:
322
+ for m in self.loop_re.finditer(src):
323
+ owner = self.ix.at_byte(rel, m.start())
324
+ if owner is not None and not owner.module:
325
+ owner.loop = True
326
+ return fns
327
+
328
+ def lex_child(self, rel: str, parent: Fn, name: str, *, containers: bool) -> Fn | None:
329
+ """The first function of file `rel` defined directly inside `parent` under this name (closures excluded;
330
+ methods only when `containers`). An index per file, rebuilt when the file gains a function."""
331
+ fns = self.ix.by_file[rel]
332
+ got = self._lex_index.get((rel, containers))
333
+ if got is None or got[0] != len(fns):
334
+ table: dict[tuple[int, str], Fn] = {}
335
+ for g in fns:
336
+ if g.lex is not None and not g.inline and (containers or not g.container):
337
+ table.setdefault((g.lex.id, g.name), g)
338
+ got = self._lex_index[(rel, containers)] = (len(fns), table)
339
+ return got[1].get((parent.id, name))
340
+
341
+ # -- fuzzy by-name resolution, shared -------------------------------------
342
+ def by_unique_name(self, fn: Fn, name: str, nargs: int, *, methods: bool | None = True, same_file_max: int = 3,
343
+ scope=None, repo_wide: bool = True) -> list[Fn]:
344
+ """A method called on a receiver of unknown type: same file, then the same package, then a repo-wide unique name."""
345
+ cands = self.by_name.get(name)
346
+ if not cands or name in self.ix.ambiguous or len(name) < 4:
347
+ return []
348
+ if methods is not None:
349
+ cands = [c for c in cands if c.method == methods]
350
+ if not fn.test:
351
+ cands = [c for c in cands if not c.test] or []
352
+ if nargs >= 0:
353
+ cands = [c for c in cands if c.nparams < 0 or c.nparams == nargs]
354
+ if not cands:
355
+ return []
356
+ local = [c for c in cands if c.file == fn.file]
357
+ if local:
358
+ got = local if len(local) <= same_file_max else []
359
+ else:
360
+ near = [c for c in cands if scope(c)] if scope is not None else []
361
+ if near:
362
+ got = near if len(near) == 1 else []
363
+ else:
364
+ got = cands if repo_wide and len(cands) == 1 else []
365
+ if got:
366
+ self.ix.by_name = True # the receiver's type was not known: whoever asked got a match by name
367
+ return got
368
+
369
+
370
+ class Index:
371
+ def __init__(self, root: Path, rules: dict, settings: Settings | None = None):
372
+ self.root = root
373
+ self.rules = rules
374
+ self.settings = settings or SETTINGS
375
+ self.ambiguous = set(rules.get("common", {}).get("ambiguous", []))
376
+ self.fns: list[Fn] = []
377
+ self.by_file: dict[str, list[Fn]] = defaultdict(list)
378
+ self.starts: dict[str, list[int]] = {}
379
+ self.entries: list[Entry] = []
380
+ self.consts = Consts()
381
+ self.nests: list[tuple[Fn, str, tuple]] = [] # (function that nests, prefix, call to the nested router fn)
382
+ self.const_uses: dict[tuple[str, str], set[int]] = defaultdict(set) # (lang, const name) -> fn ids using it
383
+ self.files_seen: set[str] = set()
384
+ self.errors = 0
385
+ self.fanout: dict[tuple[int, str], int] = {} # (caller, method) -> implementations, where one was preferred
386
+ self.guessed: dict[tuple[int, int], int] = {} # (callee, caller) -> implementations, for edges that are guesses
387
+ self.framework_edges: dict[tuple[int, int], str] = {} # (callee, caller) -> why: a call the framework makes, not in the source
388
+ self.by_name = False # set by a resolution that matched a method by name alone
389
+
390
+ def add_fn(self, fn: Fn) -> None:
391
+ fn.id = len(self.fns)
392
+ self.fns.append(fn)
393
+ self.by_file[fn.file].append(fn)
394
+
395
+ def at_byte(self, rel: str, pos: int) -> Fn | None:
396
+ fns = self.by_file.get(rel)
397
+ if not fns:
398
+ return None
399
+ i = bisect.bisect_right(self.starts[rel], pos) - 1
400
+ f = fns[i] if i >= 0 else None
401
+ while f is not None and not (f.sb <= pos < f.eb):
402
+ f = f.lex
403
+ return f
404
+
405
+ def at_line(self, rel: str, line: int, end_line: int | None = None) -> Fn | None:
406
+ best = None
407
+ for f in self.by_file.get(rel, ()):
408
+ if f.start <= line <= f.end and (best is None or (f.end - f.start) <= (best.end - best.start)):
409
+ best = f
410
+ return best
411
+
412
+
413
+ def _args(node: Node | None) -> tuple[list[Node], dict[str, Node]]:
414
+ """Positional and keyword arguments of a Python / generic argument list."""
415
+ pos, kw = [], {}
416
+ if node is None:
417
+ return pos, kw
418
+ for a in node.named_children:
419
+ if a.type == "keyword_argument":
420
+ k, v = a.child_by_field_name("name"), a.child_by_field_name("value")
421
+ if k is not None and v is not None:
422
+ kw[_t(k)] = v
423
+ elif a.type not in ("comment", "line_comment", "block_comment"):
424
+ pos.append(a)
425
+ return pos, kw
426
+
427
+
428
+ class RuleHit:
429
+ __slots__ = ("kind", "name", "path", "method", "handlers", "rule")
430
+
431
+
432
+ def apply_rule(lang: Lang, rel: str, rule: dict, m: re.Match, pos: list[Node], kw: dict[str, Node],
433
+ chain_text: str = "", default_name: str = "", unknown=()) -> RuleHit | None:
434
+ """Read kind, name and handler arguments of a registration call or decorator from a rule."""
435
+ ev = lambda node: lang.ix.consts.eval(lang.name, rel, _t(node), unknown=unknown) # noqa: E731
436
+ kind = rule["kind"]
437
+ hit = RuleHit()
438
+ hit.kind, hit.rule, hit.path, hit.method = kind, rule, None, ""
439
+ used: set[int] = set()
440
+ if rule.get("requires") and not re.search(rule["requires"], chain_text):
441
+ return None
442
+ if kind == "http":
443
+ p = rule.get("path", 0)
444
+ path = None
445
+ if isinstance(p, str): # "$1": the path is group 1 of `match` (`server.com.atproto.x.getY({...})`)
446
+ path = m.group(int(p[1:])) if p[1:].isdigit() and (m.lastindex or 0) >= int(p[1:]) else None
447
+ if path is None:
448
+ return None
449
+ p = -1
450
+ if p == -2: # auto: the first argument that reads as a path
451
+ for i, a in enumerate(pos[:3]):
452
+ if a.type in ("string", "interpreted_string_literal", "raw_string_literal", "string_literal",
453
+ "binary_expression", "binary_operator", "concatenated_string"):
454
+ value, _ = ev(a)
455
+ if value.startswith(("/", "^", "…/")) or " /" in value[:9]:
456
+ path, _ = value, used.add(i)
457
+ break
458
+ elif p >= 0 and p < len(pos):
459
+ a = pos[p]
460
+ if rule.get("path_literal") and a.type not in ("string", "interpreted_string_literal", "raw_string_literal",
461
+ "string_literal", "concatenated_string"):
462
+ return None
463
+ if rule.get("path_text"): # the argument is a dotted name that is the route (`com.atproto.server.getSession`)
464
+ path = re.sub(r"\s+", "", _t(a)) if a.type in ("member_expression", "attribute", "selector_expression", "scoped_identifier") else None
465
+ elif a.type in ("identifier", "field_identifier") and (_t(a) in unknown or lang.ix.consts.lookup(lang.name, rel, _t(a)) is None):
466
+ path = None if rule.get("path_regex") else "…"
467
+ else:
468
+ path, _ = ev(a)
469
+ used.add(p)
470
+ if path is None:
471
+ for k in rule.get("path_kwargs", []):
472
+ if k in kw:
473
+ path, _ = ev(kw[k])
474
+ break
475
+ if p != -1 and path is None:
476
+ if rule.get("path_regex") or p == -2 or not rule.get("path_optional", True):
477
+ return None
478
+ path = ""
479
+ if rule.get("path_regex") and not re.search(rule["path_regex"], path or ""):
480
+ return None
481
+ spec = rule.get("method", "")
482
+ method = ""
483
+ if spec == "$1":
484
+ method = m.group(1).upper() if m.lastindex else ""
485
+ elif spec.startswith("arg:"):
486
+ i = int(spec[4:])
487
+ if i < len(pos):
488
+ method = "|".join(v.upper() for v in _VERB_WORD.findall(_t(pos[i])))
489
+ used.add(i)
490
+ elif spec.startswith("kw:"):
491
+ node = kw.get(spec[3:])
492
+ if node is not None:
493
+ method = "|".join(dict.fromkeys(v.upper() for v in _VERB_WORD.findall(_t(node))))
494
+ elif spec.startswith("chain:"):
495
+ mm = re.search(r"\." + spec[6:] + r"\(([^)]*)\)", chain_text)
496
+ if mm:
497
+ method = "|".join(dict.fromkeys(v.upper() for v in _VERB_WORD.findall(mm.group(1))))
498
+ else:
499
+ method = spec
500
+ if not method and p == -2: # add_route("GET", "/x", handler)
501
+ for i, a in enumerate(pos[:3]):
502
+ if i not in used and a.type in ("string", "interpreted_string_literal", "string_literal"):
503
+ v = _unquote(_t(a)).upper()
504
+ if v in HTTP_VERBS:
505
+ method = v
506
+ used.add(i)
507
+ break
508
+ hit.path, hit.method = path, method
509
+ hit.name = _http_name(method, path or "") if path is not None else ""
510
+ else:
511
+ name = ""
512
+ n = rule.get("name")
513
+ if n is not None and n < len(pos):
514
+ value, ok = ev(pos[n])
515
+ if pos[n].type not in ("identifier", "selector_expression", "attribute", "call", "call_expression") or ok:
516
+ name = value
517
+ used.add(n)
518
+ if not name:
519
+ for k in rule.get("name_kwargs", []):
520
+ if k in kw:
521
+ name, _ = ev(kw[k])
522
+ break
523
+ hit.name = name or default_name
524
+ h = rule.get("handler")
525
+ handlers: list[Node] = []
526
+ if h is not None:
527
+ if h == -1:
528
+ handlers = [a for i, a in enumerate(pos) if i not in used]
529
+ elif h < len(pos):
530
+ handlers = [pos[h]]
531
+ for k in rule.get("handler_kwargs", []): # also for a rule that names its handler by keyword only
532
+ if k in kw:
533
+ handlers.append(kw[k])
534
+ hit.handlers = handlers
535
+ return hit
536
+
537
+
538
+ # --------------------------------------------------------------------------- Python
539
+
540
+ _PY_CALL_ATTR = re.compile(rb"\)\.([A-Za-z_]\w*)[ \t]*(?:#[^\n]*)?\r?$", re.M)
541
+ # annotations that say nothing about the class of a value
542
+ _PY_NOT_A_CLASS = {"Any", "Optional", "Union", "Callable", "Awaitable", "Coroutine", "Dict", "List", "Set", "Tuple", "Type",
543
+ "Sequence", "Mapping", "MutableMapping", "Iterable", "Iterator", "Generator", "Protocol", "Literal",
544
+ "Final", "ClassVar", "Self", "T", "None"}
545
+ _PY_WRAPPED = re.compile(r"^(?:Optional|Annotated)\[\s*([\w.]+).*$")
546
+ _PY_DOTTED = re.compile(r"[A-Za-z_][\w.]*")
547
+
548
+
549
+ class Python(Lang):
550
+ name = "python"
551
+
552
+ def __init__(self, index, rules):
553
+ super().__init__(index, rules)
554
+ import tree_sitter_python
555
+ self.language = Language(tree_sitter_python.language())
556
+ self.parser = Parser(self.language)
557
+ self.q = Query(self.language, """
558
+ (function_definition) @func
559
+ (class_definition) @class
560
+ (call) @call
561
+ (import_statement) @imp
562
+ (import_from_statement) @imp
563
+ (list (identifier) @ref)
564
+ (tuple (identifier) @ref)
565
+ (pair value: (identifier) @ref)
566
+ (assignment left: (identifier) right: (identifier) @ref)
567
+ """)
568
+ self.dec_rules = self._compile("decorator")
569
+ self.dec_pre = re.compile("|".join(f"(?:{r['match']})" for r in rules.get("decorator", [])) or r"\b\B")
570
+ # class rules: methods of a class are entry points by their name (and the names of the class's bases)
571
+ self.class_rules = [(re.compile(r["methods"]), re.compile(r["bases"]) if r.get("bases") else None, r)
572
+ for r in rules.get("class", [])]
573
+ views = rules.get("views", {})
574
+ self.view_factories = set(views.get("factory", [])) # `View.as_view()`
575
+ self.view_verbs = {v: v.upper() for v in views.get("verbs", [])} # method name -> HTTP method
576
+ self.view_actions = dict(views.get("actions", {})) # DRF viewset action -> HTTP method
577
+ self.view_action_decorator = re.compile(views.get("action_decorator", r"\b\B"))
578
+ self.viewset_bases = re.compile(views.get("viewset_bases", r"\b\B"))
579
+ self.action_fns: set[int] = set() # methods under such a decorator
580
+ # actions a framework base class brings when the repository's class does not define them (DRF ModelViewSet)
581
+ self.view_provided = {k: list(v) for k, v in (views.get("provided") or {}).items()}
582
+ self._implicit: dict[tuple[str, str, str], Fn] = {} # (file, class, action) -> stand-in for the inherited method
583
+ # helper classes a framework runs inside a view (`serializer_class = X`): [[python.framework]] rules
584
+ self.framework_rules = [dict(r, _reads=re.compile(r.get("reads", r"\b\B")), _writes=re.compile(r.get("writes", r"\b\B")),
585
+ _write_actions=re.compile(r.get("write_actions", r"\b\B")), _never=re.compile(r.get("never", r"\b\B")))
586
+ for r in rules.get("framework", [])]
587
+ self.helper_attrs = {a for r in self.framework_rules for a in r.get("attrs", [])}
588
+ self.helper_methods = {m for r in self.framework_rules for m in r.get("methods", [])}
589
+ self.class_helpers: dict[tuple[str, str], list[tuple[str, str]]] = defaultdict(list) # (file, class) -> (attr or method, class named)
590
+ self.class_strs: dict[tuple[str, str], dict[str, str]] = defaultdict(dict) # (file, class) -> NAME -> first string
591
+ self.attr_fn: dict[tuple[str, str, str], Fn] = {} # (file, class, attribute) -> the method that assigns it
592
+ self.call_rules = self._compile("call")
593
+ self.call_pre = re.compile("|".join(f"(?:{r['match']})" for r in rules.get("call", [])) or r"\b\B")
594
+ self.service_main = re.compile(rules.get("service_main", r"\b\B").encode())
595
+ tests = rules.get("tests", {})
596
+ self.test_fn = re.compile(tests.get("function", "^test"))
597
+ self.test_cls = re.compile(tests.get("class", "^Test"))
598
+ self.tails: dict[str, list[str]] = defaultdict(list) # dotted module tail -> files
599
+ self.imports: dict[str, dict[str, tuple[str, str | None, int]]] = {} # file -> name -> (module, attr, level)
600
+ self.stars: dict[str, list[tuple[str, int]]] = defaultdict(list)
601
+ self.top: dict[str, dict[str, Fn]] = defaultdict(dict) # file -> top-level function name -> Fn
602
+ self.classes: dict[str, dict[str, dict]] = defaultdict(dict) # file -> class -> {"methods": {}, "bases": []}
603
+ self.modfn: dict[str, Fn] = {}
604
+ self.main_files: dict[str, tuple[int, bool]] = {}
605
+ self.imported_files: set[str] = set()
606
+ self._mod_cache: dict[tuple[str, str, int], str | None] = {}
607
+ self.prefixes: dict[tuple[str, str], str] = {} # (file, router variable) -> path prefix
608
+ self.instances: dict[str, dict[str, str]] = defaultdict(dict) # file -> module variable -> class or "call:f"
609
+ self.attrs: dict[tuple[str, str], dict[str, str]] = defaultdict(dict) # (file, class) -> self attribute -> same
610
+ self.subclasses: dict[str, list[tuple[str, str]]] = defaultdict(list) # base class name -> (file, class)
611
+ self._nesting = 0
612
+ index.consts.importers["python"] = self._const_source
613
+
614
+ DEF_RE = re.compile(rb"(?m)^[ \t]*(?:async[ \t]+)?def[ \t]+(\w+)")
615
+ # `store = UserStore(...)`, `self.repo: Repo = make()`, `db = get_db()`: what a name holds
616
+ ASSIGN_RE = re.compile(rb"(?m)^([ \t]*)(self\.)?([A-Za-z_]\w*)[ \t]*(?::[ \t]*\"?([A-Za-z_][\w.]*)\"?[ \t]*)?=[ \t]*"
617
+ rb"(?:await[ \t]+)?([A-Za-z_][\w.]*)\(")
618
+ SELF_PARAM_RE = re.compile(rb"(?m)^[ \t]+self\.([A-Za-z_]\w*)[ \t]*(?::[ \t]*\"?([A-Za-z_][\w.]*)\"?[ \t]*)?=[ \t]*([A-Za-z_]\w*)[ \t]*(?:#[^\n]*)?\r?$")
619
+ MAIN_RE = re.compile(rb"(?m)^if[ \t]+__name__[ \t]*==[ \t]*[\"']__main__[\"'][ \t]*:")
620
+ PREFIX_RE = re.compile(rb"(?m)^[ \t]*(\w+)[ \t]*=[ \t]*(?:\w+\.)?(?:APIRouter|Blueprint|Router|RouteTableDef)\(([^)]*)\)")
621
+
622
+ def prescan(self, rel, src):
623
+ for m in self.DEF_RE.finditer(src):
624
+ self.fn_names.add(m.group(1).decode())
625
+ parts = rel[:-3].split("/")
626
+ if parts[-1] == "__init__":
627
+ parts = parts[:-1]
628
+ for i in range(len(parts)):
629
+ self.tails[".".join(parts[i:])].append(rel)
630
+
631
+ def parse(self, rel, src):
632
+ tree = self.parser.parse(src)
633
+ if TREE_HOOK is not None:
634
+ TREE_HOOK(self.name, self.language, rel, src, tree)
635
+ caps = QueryCursor(self.q).captures(tree.root_node)
636
+ is_test_file = is_test_path(rel)
637
+ mod = self.add_fn(Fn(rel, "python", "<module>", "", "", (0, len(src) + 1, 1, src.count(b"\n") + 2), module=True,
638
+ test=is_test_file))
639
+ self.modfn[rel] = mod
640
+ imports = self.imports.setdefault(rel, {})
641
+ for node in caps.get("imp", []):
642
+ self._import(rel, node, imports)
643
+ for m in self.PREFIX_RE.finditer(src):
644
+ pm = re.search(rb"(?:url_)?prefix\s*=\s*([\"'][^\"']*[\"'])", m.group(2))
645
+ if pm:
646
+ self.prefixes[(rel, m.group(1).decode())] = _unquote(pm.group(1).decode())
647
+ class_rules: dict[int, tuple[dict, str]] = {}
648
+ for node in caps.get("class", []):
649
+ name = _t(node.child_by_field_name("name"))
650
+ bases = []
651
+ sup = node.child_by_field_name("superclasses")
652
+ if sup is not None:
653
+ for b in sup.named_children:
654
+ if b.type == "subscript": # `Base[Model]`: the generic's own name
655
+ b = b.child_by_field_name("value") or b
656
+ if b.type in ("identifier", "attribute"):
657
+ bases.append(_t(b))
658
+ self.classes[rel].setdefault(name, {"methods": {}, "bases": bases, "line": node.start_point[0] + 1,
659
+ "end": node.end_point[0] + 1})
660
+ for b in bases:
661
+ self.subclasses[b.split(".")[-1]].append((rel, name))
662
+ body = node.child_by_field_name("body")
663
+ for st in (body.named_children if body is not None else ()):
664
+ a = st.named_children[0] if st.type == "expression_statement" and st.named_children else None
665
+ if a is None or a.type != "assignment":
666
+ continue
667
+ left, typ, right = a.child_by_field_name("left"), a.child_by_field_name("type"), a.child_by_field_name("right")
668
+ if left is None or left.type != "identifier":
669
+ continue
670
+ if typ is not None: # `main: "DataStore"`: what an attribute of the class holds
671
+ tt = _PY_WRAPPED.sub(r"\1", _t(typ).strip("\"' ")).split("|")[0].strip()
672
+ if _PY_DOTTED.fullmatch(tt) and tt[:1].isupper() and tt.split(".")[-1] not in _PY_NOT_A_CLASS:
673
+ self.attrs[(rel, name)].setdefault(_t(left), tt)
674
+ if right is not None and _t(left) in self.helper_attrs and right.type in ("identifier", "attribute"):
675
+ self.class_helpers[(rel, name)].append((_t(left), _t(right)))
676
+ if right is not None and right.end_byte - right.start_byte < 4000: # `PATH = "/x"`, `PATTERNS = patterns("/x")`
677
+ sm = _STR_RE.search(_t(right))
678
+ if sm:
679
+ self.class_strs[(rel, name)].setdefault(_t(left), _unquote(sm.group(0)))
680
+ for dec in self._decorators(node):
681
+ dotted, pos, kw = self._dec_parts(dec)
682
+ for rx, rule in self.dec_rules:
683
+ if rule.get("on") == "class" and rule.get("views") and rx.search(dotted):
684
+ # `@register_model_view(Site, "edit")`: the framework routes to the class. Its verb methods,
685
+ # its own or inherited from the repository's base views, are the entry points.
686
+ parts = [_t(a) if a.type in ("identifier", "attribute") else _unquote(_t(a)) for a in pos[:2]
687
+ if a.type in ("identifier", "attribute", "string")]
688
+ for key in rule.get("path_kwargs", ()):
689
+ if key in kw and kw[key].type == "string":
690
+ parts = parts[:1] + [_unquote(_t(kw[key]))]
691
+ e = Entry(rule["kind"], "", rel, dec.start_point[0] + 1, pending=[(mod, ("v", name, "", dec.start_point[0] + 1, -1))],
692
+ decl=mod, path="/".join(x for x in parts if x) or name)
693
+ e.each = "verb"
694
+ self.ix.entries.append(e)
695
+ continue
696
+ if rule.get("on") == "class" and rx.search(dotted):
697
+ hit = apply_rule(self, rel, rule, rx.search(dotted), pos, kw, default_name=name)
698
+ class_rules[node.id] = (rule, (hit.name if hit else name) or name)
699
+ pending_entries = []
700
+ for node in sorted(caps.get("func", []), key=lambda n: n.start_byte):
701
+ name = _t(node.child_by_field_name("name"))
702
+ p = node.parent
703
+ if p is not None and p.type == "decorated_definition":
704
+ p = p.parent
705
+ owner = p.parent if p is not None and p.type == "block" else p
706
+ container, cls_node = "", None
707
+ if owner is not None and owner.type == "class_definition":
708
+ cls_node = owner
709
+ container = _t(owner.child_by_field_name("name"))
710
+ symbol = self._symbol(node, name)
711
+ is_test = is_test_file
712
+ fn = self.add_fn(Fn(rel, "python", name, symbol, container, node, method=bool(container), test=is_test))
713
+ vars_: dict[str, str] = {}
714
+ params = node.child_by_field_name("parameters")
715
+ if params is not None:
716
+ for prm in params.named_children:
717
+ if prm.type in ("typed_parameter", "typed_default_parameter"):
718
+ typ = prm.child_by_field_name("type")
719
+ pn = prm.child_by_field_name("name") or (prm.named_children[0] if prm.named_children else None)
720
+ tt = _PY_WRAPPED.sub(r"\1", _t(typ).strip("\"' "))
721
+ tt = tt.split("|")[0].strip()
722
+ if pn is not None and _PY_DOTTED.fullmatch(tt) and tt[:1].isupper():
723
+ vars_[_t(pn)] = tt
724
+ ret = node.child_by_field_name("return_type")
725
+ rt = _PY_WRAPPED.sub(r"\1", _t(ret).strip("\"' ")) if ret is not None else ""
726
+ fn.extra = {"vars": vars_, "ret": rt if _PY_DOTTED.fullmatch(rt) and rt[:1].isupper() else ""}
727
+ if container:
728
+ self.classes[rel][container]["methods"].setdefault(name, fn)
729
+ if name in self.helper_methods: # `def get_serializer_class(self): return A if ... else B`
730
+ for hm in re.finditer(r"(?:\breturn|\belse)\s+([A-Z][\w.]*)\b(?!\s*\()", _t(node)):
731
+ self.class_helpers[(rel, container)].append((name, hm.group(1)))
732
+ elif owner is not None and owner.type == "module":
733
+ self.top[rel].setdefault(name, fn)
734
+ line = node.start_point[0] + 1
735
+ decs = self._decorators(node)
736
+ for dec in decs:
737
+ dotted, pos, kw = self._dec_parts(dec)
738
+ if container and self.view_action_decorator.search(dotted):
739
+ self.action_fns.add(fn.id)
740
+ if cls_node is not None and cls_node.id in class_rules:
741
+ rule, cname = class_rules[cls_node.id]
742
+ if re.search(rule["via"], dotted):
743
+ self.ix.entries.append(Entry(rule["kind"], cname if dotted.endswith(".run") else f"{cname}.{name}",
744
+ rel, line, targets=[fn]))
745
+ continue
746
+ if not self.dec_pre.search(dotted):
747
+ continue # no decorator rule can match
748
+ for rx, rule in self.dec_rules:
749
+ if rule.get("on") == "class":
750
+ continue
751
+ m = rx.search(dotted)
752
+ if not m:
753
+ continue
754
+ if rule["kind"] in ("job", "cli", "consumer") and "." not in dotted and dotted not in rule.get("bare", ()):
755
+ continue # a bare @command / @subscribe is too loose to trust
756
+ hit = apply_rule(self, rel, rule, m, pos, kw, default_name=symbol)
757
+ if hit is None:
758
+ continue
759
+ ename = hit.name
760
+ if hit.kind == "http":
761
+ prefix = self.prefixes.get((rel, dotted.split(".")[0]), "")
762
+ if hit.path is None:
763
+ ename = f"{hit.method or 'ANY'} {symbol}"
764
+ else:
765
+ ename = _http_name(hit.method, _join_path(prefix, hit.path))
766
+ elif hit.kind == "main":
767
+ ename = ("shutdown: " if re.search(r"stop|shutdown", dotted) else "startup: ") + symbol
768
+ self.ix.entries.append(Entry(hit.kind, ename, rel, line, targets=[fn], path=hit.path, method=hit.method))
769
+ break
770
+ if is_test and (self.test_fn.search(name) and (not container or self.test_cls.search(container))):
771
+ pending_entries.append(Entry("test", f"{rel}::{symbol}", rel, line, targets=[fn]))
772
+ self.ix.entries.extend(pending_entries)
773
+ self.link(rel, src)
774
+ for m in self.ASSIGN_RE.finditer(src):
775
+ callee = m.group(5).decode()
776
+ ann = m.group(4).decode() if m.group(4) else ""
777
+ last = callee.split(".")[-1]
778
+ what = ann if ann[:1].isupper() else (callee if last[:1].isupper() else "call:" + callee)
779
+ if what.startswith("call:"): # `store = hs.get_datastores().main`: an attribute of what the call returns
780
+ am = _PY_CALL_ATTR.match(src, m.end())
781
+ if am:
782
+ what += "#" + am.group(1).decode()
783
+ var = m.group(3).decode()
784
+ owner = self.ix.at_byte(rel, m.start(3))
785
+ if m.group(2):
786
+ if owner is not None and owner.container:
787
+ if var not in self.attrs[(rel, owner.container)]:
788
+ self.attr_fn[(rel, owner.container, var)] = owner
789
+ self.attrs[(rel, owner.container)].setdefault(var, what)
790
+ elif owner is None or owner.module:
791
+ if not m.group(1):
792
+ self.instances[rel].setdefault(var, what)
793
+ elif owner.extra is not None:
794
+ owner.extra["vars"].setdefault(var, what)
795
+ for m in self.SELF_PARAM_RE.finditer(src): # `self.stores = stores` / `self.repo: Repo = repo`
796
+ owner = self.ix.at_byte(rel, m.start(1))
797
+ if owner is None or not owner.container or owner.extra is None:
798
+ continue
799
+ what = m.group(2).decode() if m.group(2) else owner.extra["vars"].get(m.group(3).decode(), "")
800
+ if what[:1].isupper() and _PY_DOTTED.fullmatch(what) and what.split(".")[-1] not in _PY_NOT_A_CLASS:
801
+ self.attrs[(rel, owner.container)].setdefault(m.group(1).decode(), what)
802
+ m = self.MAIN_RE.search(src)
803
+ if m:
804
+ self.main_files[rel] = (src.count(b"\n", 0, m.start()) + 1, bool(self.service_main.search(src)))
805
+ local = set(self.top[rel]) | set(imports) | {n for c in self.classes[rel].values() for n in c["methods"]}
806
+ # a bare name can only mean a function defined in this file (top level or inside another) or an import
807
+ nested = {f.name for f in self.ix.by_file[rel] if not f.module and not f.container and f.lex is not None
808
+ and not f.lex.module}
809
+ at = self.ix.at_byte
810
+ bound: dict[tuple[int, str], bool] = {}
811
+
812
+ def is_local(owner: Fn, name: str) -> bool:
813
+ """A parameter or local variable that happens to share a function's name."""
814
+ if owner.module:
815
+ return False
816
+ key = (owner.id, name)
817
+ if key not in bound:
818
+ bound[key] = _binds(PY_BIND, name, src[owner.sb:owner.eb])
819
+ return bound[key]
820
+
821
+ for node in caps.get("ref", []):
822
+ name = _t(node)
823
+ if name in local or name in nested:
824
+ owner = at(rel, node.start_byte)
825
+ if owner is not None and not is_local(owner, name):
826
+ owner.calls.append(("r", name, "", node.start_point[0] + 1, -1))
827
+ pre = self.call_pre
828
+ for node in caps.get("call", []):
829
+ f = node.child_by_field_name("function")
830
+ if f is None:
831
+ continue
832
+ ft = f.type
833
+ if ft == "identifier":
834
+ name, qual = _t(f), ""
835
+ elif ft == "attribute":
836
+ obj = f.child_by_field_name("object")
837
+ name = _t(f.child_by_field_name("attribute"))
838
+ if obj is None:
839
+ continue
840
+ if obj.type in ("identifier", "attribute") and obj.end_byte - obj.start_byte < 80:
841
+ qual = _t(obj)
842
+ elif obj.type == "call" and _t(obj).startswith("super("):
843
+ qual = "super"
844
+ else:
845
+ qual = "?"
846
+ else:
847
+ continue
848
+ owner = at(rel, node.start_byte) or mod
849
+ args = node.child_by_field_name("arguments")
850
+ line = node.start_point[0] + 1
851
+ dotted = f"{qual}.{name}" if qual else name
852
+ is_reg = False
853
+ if pre.search(dotted):
854
+ is_reg = self._registration(rel, node, dotted, args, owner, line)
855
+ if name in self.fn_names or (not qual and name in imports) or (not qual and name in self.classes[rel]):
856
+ owner.calls.append(("c", name, qual, line, -1))
857
+ if args is not None and args.type == "argument_list" and not is_reg:
858
+ for a in args.named_children:
859
+ if a.type == "keyword_argument":
860
+ a = a.child_by_field_name("value")
861
+ if a is None:
862
+ continue
863
+ if a.type == "identifier":
864
+ nm = _t(a)
865
+ if (nm in local or nm in nested) and not is_local(owner, nm):
866
+ owner.calls.append(("r", nm, "", line, -1))
867
+ elif a.type == "attribute":
868
+ o = a.child_by_field_name("object")
869
+ nm = _t(a.child_by_field_name("attribute"))
870
+ if o is not None and o.type == "identifier" and nm in self.fn_names:
871
+ q = _t(o)
872
+ if q in ("self", "cls") or q in imports:
873
+ owner.calls.append(("r", nm, q, line, -1))
874
+
875
+ def _const_source(self, rel: str, name: str) -> tuple[str, str] | None:
876
+ imp = self.imports.get(rel, {}).get(name)
877
+ if imp is None or imp[1] is None:
878
+ return None
879
+ f = self.module_file(rel, imp[0], imp[2])
880
+ return (f, imp[1]) if f else None
881
+
882
+ def _symbol(self, node: Node, name: str) -> str:
883
+ names, n = [name], node.parent
884
+ while n is not None:
885
+ if n.type in ("function_definition", "class_definition"):
886
+ names.append(_t(n.child_by_field_name("name")))
887
+ n = n.parent
888
+ return ".".join(reversed(names))
889
+
890
+ @staticmethod
891
+ def _decorators(node: Node) -> list[Node]:
892
+ p = node.parent
893
+ if p is None or p.type != "decorated_definition":
894
+ return []
895
+ return [c for c in p.children if c.type == "decorator"]
896
+
897
+ @staticmethod
898
+ def _dec_parts(dec: Node) -> tuple[str, list[Node], dict[str, Node]]:
899
+ expr = dec.named_children[0] if dec.named_children else None
900
+ if expr is None:
901
+ return "", [], {}
902
+ if expr.type == "call":
903
+ pos, kw = _args(expr.child_by_field_name("arguments"))
904
+ return _t(expr.child_by_field_name("function")), pos, kw
905
+ return _t(expr), [], {}
906
+
907
+ def _handler_refs(self, node: Node, out: list[tuple], line: int) -> Node | None:
908
+ """Function references inside a handler expression. Returns an inline lambda, if that is the handler."""
909
+ if node.type == "identifier":
910
+ out.append(("r", _t(node), "", line, -1))
911
+ elif node.type == "attribute":
912
+ o = node.child_by_field_name("object")
913
+ if o is not None and o.type in ("identifier", "attribute"):
914
+ out.append(("r", _t(node.child_by_field_name("attribute")), _t(o), line, -1))
915
+ elif node.type == "call":
916
+ f = node.child_by_field_name("function")
917
+ if f is not None:
918
+ self._handler_refs(f, out, line)
919
+ pos, kw = _args(node.child_by_field_name("arguments"))
920
+ for a in pos + list(kw.values()):
921
+ self._handler_refs(a, out, line)
922
+ elif node.type == "lambda":
923
+ return node
924
+ return None
925
+
926
+ def _registration(self, rel, node, dotted, args, owner, line) -> bool:
927
+ for rx, rule in self.call_rules:
928
+ m = rx.search(dotted)
929
+ if not m:
930
+ continue
931
+ pos, kw = _args(args)
932
+ hit = apply_rule(self, rel, rule, m, pos, kw, chain_text=_t(node)[:200])
933
+ if hit is None or not hit.handlers:
934
+ continue
935
+ refs: list[tuple] = []
936
+ targets = []
937
+ each = ""
938
+ for h in hit.handlers:
939
+ view = self._view_ref(h, rule, line)
940
+ if view is not None: # a class is registered: its methods are the entry points
941
+ refs.append(view)
942
+ each = "method" if view[0] == "V" else "verb"
943
+ if view[0] == "w":
944
+ hit.method = ""
945
+ continue
946
+ if rule.get("views"):
947
+ continue
948
+ lam = self._handler_refs(h, refs, line)
949
+ if lam is not None:
950
+ targets.append(self.add_fn(Fn(rel, "python", "<lambda>", owner.symbol, owner.container, lam, inline=True,
951
+ test=owner.test)))
952
+ refs = [r for r in refs if not (r[2] == "" and r[1] in ("None", "True", "False"))]
953
+ if not refs and not targets:
954
+ continue
955
+ name = hit.name
956
+ if hit.kind == "http":
957
+ var = dotted.split(".")[0]
958
+ name = _http_name(hit.method, _join_path(self.prefixes.get((rel, var), ""), hit.path or ""))
959
+ elif not name:
960
+ name = refs[-1][1] if refs else owner.symbol
961
+ e = Entry(hit.kind, name, rel, line, targets=targets, pending=[(owner, r) for r in refs],
962
+ decl=owner, path=hit.path, method=hit.method, loop_only=bool(rule.get("loop_only")))
963
+ if each == "verb":
964
+ e.each = each
965
+ e.path = _join_path(self.prefixes.get((rel, dotted.split(".")[0]), ""), hit.path or "")
966
+ elif each:
967
+ service = m.group(1) if m.lastindex else ""
968
+ e.each, e.name = each, f"{hit.method or 'ANY'} {service}".strip()
969
+ e.only = (lambda base=service + rule.get("each_class", ""): self._class_method_names(base))
970
+ self.ix.entries.append(e)
971
+ # the handler stays a reference of the calling function (an edge from it) for background loops,
972
+ # for deferred calls (`keep_edge`: the caller's origin and the job both reach it) and for classes
973
+ return not (rule.get("loop_only") or rule.get("keep_edge") or each)
974
+ return False
975
+
976
+ def _view_ref(self, node: Node, rule: dict, line: int) -> tuple | None:
977
+ """A handler that is a class: `View.as_view()` in a route, the viewset of `router.register(...)`
978
+ (`views = "class"`), or the servicer instance of a gRPC registration (`views = "service"`)."""
979
+ mode = rule.get("views", "")
980
+ if node.type == "call":
981
+ f = node.child_by_field_name("function")
982
+ if f is not None and f.type == "attribute" and _t(f.child_by_field_name("attribute")) in self.view_factories:
983
+ node, mode = f.child_by_field_name("object"), "class"
984
+ elif mode == "service" and f is not None:
985
+ node = f # `add_FooServicer_to_server(FooService(db), server)`
986
+ else:
987
+ return None
988
+ elif not mode:
989
+ return None
990
+ if node is None:
991
+ return None
992
+ kind = "V" if mode == "service" else ("w" if mode == "viewset" else "v")
993
+ if node.type == "identifier":
994
+ return (kind, _t(node), "", line, -1)
995
+ if node.type == "attribute":
996
+ o = node.child_by_field_name("object")
997
+ if o is not None and o.type in ("identifier", "attribute"):
998
+ return (kind, _t(node.child_by_field_name("attribute")), _t(o), line, -1)
999
+ return None
1000
+
1001
+ def _class_ref(self, fn: Fn, name: str, qual: str) -> tuple[str, str] | None:
1002
+ """(file, class) a name refers to: a class, or a variable holding an instance of one."""
1003
+ rel = fn.file
1004
+ if qual:
1005
+ if qual in ("self", "cls") and fn.container:
1006
+ return self._attr_class((rel, fn.container), name)
1007
+ got = self._lookup(rel, qual.split(".")[0])
1008
+ for part in qual.split(".")[1:]:
1009
+ if got is None or got[0] != "module":
1010
+ return None
1011
+ got = self._lookup(got[1], part)
1012
+ if got is None or got[0] != "module":
1013
+ return None
1014
+ got = self._lookup(got[1], name)
1015
+ else:
1016
+ got = self._lookup(rel, name)
1017
+ if got is None:
1018
+ held = self._var_class(fn, name)
1019
+ return held if held else None
1020
+ return got[1] if got is not None and got[0] in ("class", "instance") else None
1021
+
1022
+ def _mro(self, cls: tuple[str, str], depth: int = 0, seen: set | None = None) -> list[tuple[str, str]]:
1023
+ """The class and its bases that are declared in the repo, nearest first."""
1024
+ seen = seen if seen is not None else set()
1025
+ if cls in seen or depth > 6:
1026
+ return []
1027
+ seen.add(cls)
1028
+ out = [cls]
1029
+ info = self.classes.get(cls[0], {}).get(cls[1])
1030
+ for base in (info["bases"] if info else ()):
1031
+ got = self._lookup(cls[0], base.split(".")[0])
1032
+ if got is not None and got[0] == "module" and "." in base:
1033
+ got = self._lookup(got[1], base.split(".")[-1])
1034
+ if got is not None and got[0] == "class":
1035
+ out += self._mro(got[1], depth + 1, seen)
1036
+ return out
1037
+
1038
+ def _view_methods(self, cls: tuple[str, str], kind: str) -> list[Fn]:
1039
+ """Entry-point methods of a registered class: HTTP verbs, viewset actions and `@action` methods of a
1040
+ view; every public method of a service. A method of a base class counts unless the class redefines it."""
1041
+ out: dict[str, Fn] = {}
1042
+ for file, cname in self._mro(cls):
1043
+ for mname, f in self.classes.get(file, {}).get(cname, {}).get("methods", {}).items():
1044
+ if mname in out:
1045
+ continue
1046
+ if kind == "V":
1047
+ if not mname.startswith("_"):
1048
+ out[mname] = f
1049
+ elif mname in self.view_verbs or mname in self.view_actions or f.id in self.action_fns:
1050
+ out[mname] = f
1051
+ if kind != "V" and self.view_provided:
1052
+ # `class X(ModelViewSet)` with no `update` of its own still serves PUT: the framework's method runs. It has
1053
+ # no source here, so a stand-in carries the entry point and the calls the framework makes from it.
1054
+ for file, cname in self._mro(cls):
1055
+ for base in self.classes.get(file, {}).get(cname, {}).get("bases", ()):
1056
+ for action in self.view_provided.get(base.split(".")[-1], ()):
1057
+ if action not in out:
1058
+ out[action] = self._implicit_action(cls, action)
1059
+ return list(out.values())
1060
+
1061
+ def _implicit_action(self, cls: tuple[str, str], action: str) -> Fn:
1062
+ key = (cls[0], cls[1], action)
1063
+ fn = self._implicit.get(key)
1064
+ if fn is None:
1065
+ line = self.classes[cls[0]][cls[1]]["line"]
1066
+ fn = self._implicit[key] = Fn(cls[0], "python", action, f"{cls[1]}.{action}", cls[1], (0, 0, line, line), method=True,
1067
+ test=is_test_path(cls[0]))
1068
+ fn.id = len(self.ix.fns) # in the graph, not in the file's list of functions: no source line is inside it
1069
+ self.ix.fns.append(fn)
1070
+ return fn
1071
+
1072
+ def _framework_edges(self) -> None:
1073
+ """Calls a framework makes that the source does not show: a view's actions run its serializer's methods."""
1074
+ if not self.framework_rules:
1075
+ return
1076
+ for (rel, cname), named in list(self.class_helpers.items()):
1077
+ if is_test_path(rel):
1078
+ continue
1079
+ callers = self._view_methods((rel, cname), "v")
1080
+ for sub in self.views_using((rel, cname), {}, collect=True):
1081
+ if sub != (rel, cname) and not self.class_helpers.get(sub):
1082
+ callers = callers + self._view_methods(sub, "v")
1083
+ if not callers:
1084
+ continue
1085
+ for how, dotted in named:
1086
+ rule = next((r for r in self.framework_rules if how in r.get("attrs", ()) or how in r.get("methods", ())), None)
1087
+ got = self._lookup(rel, dotted.split(".")[0]) if rule else None
1088
+ if got is not None and got[0] == "module" and "." in dotted:
1089
+ got = self._lookup(got[1], dotted.split(".")[-1])
1090
+ if got is None or got[0] != "class":
1091
+ continue
1092
+ for file, hname in self._mro(got[1]):
1093
+ for mname, m in self.classes.get(file, {}).get(hname, {}).get("methods", {}).items():
1094
+ reads, writes = rule["_reads"].search(mname), rule["_writes"].search(mname)
1095
+ if not (reads or writes):
1096
+ continue
1097
+ for c in callers:
1098
+ if c.id == m.id or c.test or rule["_never"].search(c.name):
1099
+ continue
1100
+ # the helper's `create` runs for a creating action, its `update` for an updating one
1101
+ if c.id not in self.action_fns and ((mname == "create" and c.name in ("update", "partial_update", "put", "patch"))
1102
+ or (mname == "update" and c.name in ("create", "post"))):
1103
+ continue
1104
+ if reads or rule["_write_actions"].search(c.name) or c.id in self.action_fns:
1105
+ self.ix.framework_edges.setdefault((m.id, c.id), rule.get("label", "called by the framework"))
1106
+
1107
+ def class_at(self, rel: str, line: int) -> tuple[str, str] | None:
1108
+ """The innermost class whose body holds a line (asked for lines outside every method)."""
1109
+ best = None
1110
+ for cname, info in self.classes.get(rel, {}).items():
1111
+ if info["line"] <= line <= info.get("end", 0) and (best is None or info["line"] >= best[1]):
1112
+ best = (cname, info["line"])
1113
+ return (rel, best[0]) if best else None
1114
+
1115
+ def views_using(self, cls: tuple[str, str], by_view: dict, depth: int = 0, seen: set | None = None, collect: bool = False,
1116
+ names: dict | None = None) -> list:
1117
+ """Entry points of a view class and of the classes that inherit from it: a `queryset = ...` written in a
1118
+ class body is read by the methods the framework calls on that class and on its subclasses."""
1119
+ seen = seen if seen is not None else set()
1120
+ names = names if names is not None else {}
1121
+ if cls in seen or depth > 4:
1122
+ return []
1123
+ seen.add(cls)
1124
+ out = [cls] if collect else list(by_view.get(cls, ())) # `collect`: the classes themselves
1125
+ # Subclasses are listed by the base's name, so every class of one name has the same list. Walking it again
1126
+ # from a class of that name at the same depth or deeper finds nothing new (all of it is seen or too deep);
1127
+ # without this, a few thousand classes called `Migration` cost the square of their number.
1128
+ if names.get(cls[1], 99) > depth:
1129
+ names[cls[1]] = depth
1130
+ for sub in self.subclasses.get(cls[1], ()):
1131
+ out += self.views_using(sub, by_view, depth + 1, seen, collect, names)
1132
+ return out
1133
+
1134
+ def _class_method_names(self, cname: str) -> set[str] | None:
1135
+ """Method names of the one class in the repo called `cname` (a generated gRPC servicer base), else None."""
1136
+ found = [info for classes in self.classes.values() for n, info in classes.items() if n == cname]
1137
+ return set(found[0]["methods"]) if len(found) == 1 else None
1138
+
1139
+ def _import(self, rel: str, node: Node, imports: dict) -> None:
1140
+ if node.type == "import_statement":
1141
+ for c in node.named_children:
1142
+ if c.type == "dotted_name":
1143
+ full = _t(c)
1144
+ imports.setdefault(full.split(".")[0], (full.split(".")[0], None, 0))
1145
+ if "." in full:
1146
+ imports.setdefault(full, (full, None, 0))
1147
+ elif c.type == "aliased_import":
1148
+ imports[_t(c.child_by_field_name("alias"))] = (_t(c.child_by_field_name("name")), None, 0)
1149
+ return
1150
+ mod_node = node.child_by_field_name("module_name")
1151
+ if mod_node is None:
1152
+ return
1153
+ text = _t(mod_node)
1154
+ level = len(text) - len(text.lstrip("."))
1155
+ module = text.lstrip(".")
1156
+ for c in node.named_children:
1157
+ if c is mod_node or c.start_byte < mod_node.end_byte:
1158
+ continue
1159
+ if c.type == "dotted_name":
1160
+ imports[_t(c)] = (module, _t(c), level)
1161
+ elif c.type == "aliased_import":
1162
+ imports[_t(c.child_by_field_name("alias"))] = (module, _t(c.child_by_field_name("name")), level)
1163
+ elif c.type == "wildcard_import":
1164
+ self.stars[rel].append((module, level))
1165
+
1166
+ # -- resolution -----------------------------------------------------------
1167
+ def module_file(self, rel: str, module: str, level: int = 0) -> str | None:
1168
+ key = (_dirname(rel), module, level)
1169
+ if key in self._mod_cache:
1170
+ return self._mod_cache[key]
1171
+ result = None
1172
+ if level:
1173
+ base = os.path.dirname(rel).split("/") if os.path.dirname(rel) else []
1174
+ base = base[: len(base) - (level - 1)] if level > 1 else base
1175
+ stem = "/".join(base + (module.split(".") if module else []))
1176
+ for cand in (stem + ".py", stem + "/__init__.py"):
1177
+ if cand in self.ix.files_seen:
1178
+ result = cand
1179
+ break
1180
+ else:
1181
+ cands = self.tails.get(module, [])
1182
+ want = module.replace(".", "/")
1183
+ cands = [c for c in cands if c[:-3].endswith(want) or c.endswith(want + "/__init__.py")]
1184
+ if len(cands) == 1:
1185
+ result = cands[0]
1186
+ elif cands:
1187
+ here = os.path.dirname(rel).split("/")
1188
+
1189
+ def shared(c: str) -> int:
1190
+ n = 0
1191
+ for a, b in zip(here, c.split("/")):
1192
+ if a != b:
1193
+ break
1194
+ n += 1
1195
+ return n
1196
+ # a module name resolves from the importing file's own tree first
1197
+ roots = sorted(cands, key=lambda c: (-shared(c), len(c)))
1198
+ if shared(roots[0]) > shared(roots[1]) or len(roots[0]) < len(roots[1]) and shared(roots[0]) == shared(roots[1]) and shared(roots[0]) > 0:
1199
+ result = roots[0]
1200
+ self._mod_cache[key] = result
1201
+ return result
1202
+
1203
+ def _lookup(self, rel: str, name: str, depth: int = 0) -> tuple[str, object] | None:
1204
+ """What `name` means at the top level of file `rel`: ("fn", Fn) | ("class", (file, name)) | ("module", file)."""
1205
+ if depth > 4:
1206
+ return None
1207
+ fn = self.top[rel].get(name)
1208
+ if fn is not None:
1209
+ return ("fn", fn)
1210
+ if name in self.classes[rel]:
1211
+ return ("class", (rel, name))
1212
+ inst = self.instances.get(rel, {}).get(name)
1213
+ if inst is not None:
1214
+ cls = self._holds(rel, None, inst, depth + 1)
1215
+ return ("instance", cls) if cls is not None else None
1216
+ imp = self.imports.get(rel, {}).get(name)
1217
+ if imp is not None:
1218
+ module, attr, level = imp
1219
+ if attr is None:
1220
+ f = self.module_file(rel, module, level)
1221
+ return ("module", f) if f else None
1222
+ f = self.module_file(rel, module, level)
1223
+ if f is not None:
1224
+ got = self._lookup(f, attr, depth + 1)
1225
+ if got is not None:
1226
+ return got
1227
+ sub = self.module_file(rel, f"{module}.{attr}" if module else attr, level)
1228
+ if sub is not None:
1229
+ return ("module", sub)
1230
+ return None
1231
+ for module, level in self.stars.get(rel, ()):
1232
+ f = self.module_file(rel, module, level)
1233
+ if f is not None and f != rel:
1234
+ got = self._lookup(f, name, depth + 1)
1235
+ if got is not None:
1236
+ return got
1237
+ return None
1238
+
1239
+ def _holds(self, rel: str, fn: Fn | None, what: str, depth: int = 0) -> tuple[str, str] | None:
1240
+ """(file, class) a variable holds, from `Cls(...)`, an annotation, or the return annotation of `call:f`."""
1241
+ if depth > 4:
1242
+ return None
1243
+ if what.startswith("call:") and "#" in what:
1244
+ what, _, attr = what.partition("#")
1245
+ cls = self._holds(rel, fn, what, depth)
1246
+ return self._attr_class(cls, attr) if cls is not None else None
1247
+ if what.startswith("call:"):
1248
+ dotted = what[5:]
1249
+ ctx = fn or self.modfn.get(rel)
1250
+ if ctx is None or self._nesting > 4:
1251
+ return None
1252
+ self._nesting += 1 # `x = x.next()` and mutually defined names must not recurse forever
1253
+ try:
1254
+ targets = self.resolve(ctx, ("c", dotted.split(".")[-1], ".".join(dotted.split(".")[:-1]), 0, -1), depth + 1)
1255
+ finally:
1256
+ self._nesting -= 1
1257
+ rets = {(t.file, t.extra["ret"]) for t in targets if t.extra and t.extra["ret"]}
1258
+ if len(rets) != 1:
1259
+ return None
1260
+ f, r = next(iter(rets))
1261
+ return self._holds(f, None, r, depth + 1)
1262
+ got = self._lookup(rel, what.split(".")[0], depth + 1)
1263
+ for part in what.split(".")[1:]:
1264
+ if got is None or got[0] != "module":
1265
+ return None
1266
+ got = self._lookup(got[1], part, depth + 1)
1267
+ return got[1] if got is not None and got[0] == "class" else None
1268
+
1269
+ def _attr_class(self, cls: tuple[str, str], attr: str, depth: int = 0) -> tuple[str, str] | None:
1270
+ """(file, class) held by attribute `attr` of a class, from its annotation or `self.attr = Cls(...)`,
1271
+ looked up through the class's bases."""
1272
+ if depth > 6:
1273
+ return None
1274
+ what = self.attrs.get(cls, {}).get(attr)
1275
+ if what is not None:
1276
+ return self._holds(cls[0], self.attr_fn.get((cls[0], cls[1], attr)), what, depth + 1)
1277
+ info = self.classes.get(cls[0], {}).get(cls[1])
1278
+ for base in (info["bases"] if info else ()):
1279
+ got = self._lookup(cls[0], base.split(".")[0])
1280
+ if got is not None and got[0] == "module" and "." in base:
1281
+ got = self._lookup(got[1], base.split(".")[-1])
1282
+ if got is not None and got[0] == "class":
1283
+ found = self._attr_class(got[1], attr, depth + 1)
1284
+ if found is not None:
1285
+ return found
1286
+ return None
1287
+
1288
+ def _var_class(self, fn: Fn, qual: str, depth: int = 0) -> tuple[str, str] | None | bool:
1289
+ """Class of the object a call is made on; False when it is known to be a library object."""
1290
+ parts = qual.split(".")
1291
+ what = None
1292
+ if parts[0] in ("self", "cls") and len(parts) == 2 and fn.container:
1293
+ what = self.attrs.get((fn.file, fn.container), {}).get(parts[1])
1294
+ if what is None: # set by a base class: `self.store` from the handler base
1295
+ cls = self._attr_class((fn.file, fn.container), parts[1])
1296
+ if cls is not None:
1297
+ return cls
1298
+ elif parts[0] in ("self", "cls") and 2 < len(parts) <= 5 and fn.container:
1299
+ # `self.controllers.purge_events.run()`: each attribute's class in turn
1300
+ cls = (fn.file, fn.container)
1301
+ for part in parts[1:]:
1302
+ cls = self._attr_class(cls, part)
1303
+ if cls is None:
1304
+ return None
1305
+ return cls
1306
+ elif len(parts) == 1:
1307
+ scope = fn
1308
+ while scope is not None and what is None:
1309
+ if scope.extra is not None:
1310
+ what = scope.extra["vars"].get(parts[0])
1311
+ scope = scope.lex
1312
+ if what is None:
1313
+ return None
1314
+ ctx = fn
1315
+ if parts[0] in ("self", "cls") and fn.container:
1316
+ # `self.store = hs.get_store()` is read where it was assigned: `hs` is a name of that method
1317
+ ctx = self.attr_fn.get((fn.file, fn.container, parts[1]), fn)
1318
+ cls = self._holds(fn.file, ctx, what, depth)
1319
+ if cls is None:
1320
+ # `x = Thing(...)` where Thing is imported from a library: its methods are not ours
1321
+ head = what.removeprefix("call:").split(".")[0]
1322
+ return False if not what.startswith("call:") and head in self.imports.get(fn.file, {}) else None
1323
+ return cls
1324
+
1325
+ def _class_method(self, file: str, cls: str, name: str, depth: int = 0) -> Fn | None:
1326
+ info = self.classes.get(file, {}).get(cls)
1327
+ if info is None or depth > 4:
1328
+ return None
1329
+ fn = info["methods"].get(name)
1330
+ if fn is not None:
1331
+ return fn
1332
+ for base in info["bases"]:
1333
+ got = self._lookup(file, base.split(".")[0])
1334
+ if got is None:
1335
+ continue
1336
+ if got[0] == "class":
1337
+ found = self._class_method(got[1][0], got[1][1], name, depth + 1)
1338
+ elif got[0] == "module" and "." in base:
1339
+ found = self._class_method(got[1], base.split(".")[-1], name, depth + 1)
1340
+ else:
1341
+ found = None
1342
+ if found is not None:
1343
+ return found
1344
+ return None
1345
+
1346
+ def _with_overrides(self, cls: tuple[str, str], name: str, found: Fn) -> list[Fn]:
1347
+ """A method called on a value typed as `cls` may run in a subclass that redefines it: the method found,
1348
+ and the redefinitions in the classes derived from `cls` (by name, three levels; none when too many)."""
1349
+ out, seen, todo = [found], {cls}, [(cls, 0)]
1350
+ while todo:
1351
+ (_, cname), depth = todo.pop()
1352
+ if depth >= 3:
1353
+ continue
1354
+ for sub in self.subclasses.get(cname, ()):
1355
+ if sub in seen:
1356
+ continue
1357
+ seen.add(sub)
1358
+ todo.append((sub, depth + 1))
1359
+ m = self.classes.get(sub[0], {}).get(sub[1], {}).get("methods", {}).get(name)
1360
+ if m is not None and m not in out and not (m.test and not found.test):
1361
+ out.append(m)
1362
+ return out if len(out) <= self.ix.settings.max_overrides else [found]
1363
+
1364
+ def _as_fn(self, got, kind: str) -> list[Fn]:
1365
+ if got is None:
1366
+ return []
1367
+ if got[0] == "fn":
1368
+ return [got[1]]
1369
+ if got[0] == "class" and kind == "c":
1370
+ init = self._class_method(got[1][0], got[1][1], "__init__")
1371
+ return [init] if init is not None else []
1372
+ return []
1373
+
1374
+ def resolve(self, fn, call, depth: int = 0):
1375
+ kind, name, qual, _line, _n = call
1376
+ rel = fn.file
1377
+ if depth > 3:
1378
+ return []
1379
+ if kind in ("v", "w", "V"):
1380
+ cls = self._class_ref(fn, name, qual)
1381
+ if cls is None:
1382
+ return []
1383
+ if kind == "w" and not any(self.viewset_bases.search(b) for c in self._mro(cls)
1384
+ for b in self.classes[c[0]][c[1]]["bases"]):
1385
+ return [] # `registry.register("name", Thing)`: not a viewset
1386
+ self.last_view = cls
1387
+ return self._view_methods(cls, kind)
1388
+ if not qual:
1389
+ f = fn
1390
+ while f is not None and not f.module: # a function defined inside this one
1391
+ g = self.lex_child(rel, f, name, containers=False)
1392
+ if g is not None:
1393
+ return [g]
1394
+ f = f.lex
1395
+ return self._as_fn(self._lookup(rel, name), kind)
1396
+ head = qual.split(".")[0]
1397
+ if qual in ("self", "cls", "super") and fn.container:
1398
+ if qual == "super":
1399
+ info = self.classes[rel].get(fn.container, {"bases": []})
1400
+ for base in info["bases"]:
1401
+ got = self._lookup(rel, base.split(".")[0])
1402
+ if got and got[0] == "class":
1403
+ m = self._class_method(got[1][0], got[1][1], name)
1404
+ if m is not None:
1405
+ return [m]
1406
+ return []
1407
+ m = self._class_method(rel, fn.container, name)
1408
+ if m is not None:
1409
+ return [m]
1410
+ # a mixin calling a method that another mixin of the same concrete class provides
1411
+ subs = self.subclasses.get(fn.container, [])
1412
+ found = [m for m in (self._class_method(f, c, name) for f, c in subs[:6]) if m is not None]
1413
+ if found:
1414
+ return list(dict.fromkeys(found))[:3]
1415
+ return self.by_unique_name(fn, name, -1, methods=True, same_file_max=1, repo_wide=False) if kind == "c" else []
1416
+ held = self._var_class(fn, qual, depth) if qual != "?" else None
1417
+ if held is False:
1418
+ return []
1419
+ if held and any(b.split(".")[-1] == "Protocol" for b in self.classes.get(held[0], {}).get(held[1], {}).get("bases", ())):
1420
+ held = None # a structural type: its implementations do not derive from it, so the name decides
1421
+ if held:
1422
+ m = self._class_method(held[0], held[1], name)
1423
+ return self._with_overrides(held, name, m) if m is not None else []
1424
+ got = self._lookup(rel, head) if head not in ("self", "cls") else None
1425
+ rest = qual.split(".")[1:]
1426
+ if got is not None:
1427
+ while rest and got is not None and got[0] == "module":
1428
+ got = self._lookup(got[1], rest[0])
1429
+ rest = rest[1:]
1430
+ if got is None or rest:
1431
+ return []
1432
+ if got[0] == "module":
1433
+ return self._as_fn(self._lookup(got[1], name), kind)
1434
+ if got[0] in ("class", "instance"):
1435
+ m = self._class_method(got[1][0], got[1][1], name)
1436
+ return [m] if m is not None else []
1437
+ return []
1438
+ if head in self.imports.get(rel, {}) or kind == "r":
1439
+ return [] # an external library, or a reference through an unknown object
1440
+ if qual == "?" and name in self.ix.ambiguous:
1441
+ return []
1442
+ imported = self._imported_files(rel)
1443
+ return self.by_unique_name(fn, name, -1, methods=True, scope=lambda c: c.file in imported, repo_wide=False)
1444
+
1445
+ def _imported_files(self, rel: str) -> set[str]:
1446
+ cache = self.__dict__.setdefault("_imp_files", {})
1447
+ got = cache.get(rel)
1448
+ if got is None:
1449
+ got = set()
1450
+ for module, attr, level in self.imports.get(rel, {}).values():
1451
+ f = self.module_file(rel, module, level)
1452
+ if f:
1453
+ got.add(f)
1454
+ if attr:
1455
+ sub = self.module_file(rel, f"{module}.{attr}" if module else attr, level)
1456
+ if sub:
1457
+ got.add(sub)
1458
+ cache[rel] = got
1459
+ return got
1460
+
1461
+ def _class_entries(self) -> None:
1462
+ """Entry points from `[[python.class]]` rules: a method whose name matches, in a class whose own name
1463
+ or one of whose bases (through the classes of the repo, by name) matches `bases` when the rule has it."""
1464
+ if not self.class_rules:
1465
+ return
1466
+ bases_of: dict[str, set[str]] = defaultdict(set)
1467
+ for classes in self.classes.values():
1468
+ for cname, info in classes.items():
1469
+ bases_of[cname].update(b.split(".")[-1] for b in info["bases"])
1470
+ family: dict[str, set[str]] = {}
1471
+
1472
+ def ancestors(cname: str) -> set[str]:
1473
+ got = family.get(cname)
1474
+ if got is None:
1475
+ got = family[cname] = set()
1476
+ todo = [cname]
1477
+ while todo and len(got) < 64:
1478
+ for b in bases_of.get(todo.pop(), ()):
1479
+ if b not in got:
1480
+ got.add(b)
1481
+ todo.append(b)
1482
+ return got
1483
+
1484
+ for rel, classes in self.classes.items():
1485
+ if is_test_path(rel):
1486
+ continue
1487
+ for cname, info in classes.items():
1488
+ for mname, fn in info["methods"].items():
1489
+ for mrx, brx, rule in self.class_rules:
1490
+ m = mrx.search(mname)
1491
+ if not m or fn.test:
1492
+ continue
1493
+ if brx is not None and not any(brx.search(b) for b in ancestors(cname)):
1494
+ continue
1495
+ kind = rule["kind"]
1496
+ if kind == "http":
1497
+ spec = rule.get("method", "")
1498
+ method = (m.group(1).upper() if m.lastindex else "") if spec == "$1" else spec
1499
+ path = next((self.class_strs[(rel, cname)][a] for a in rule.get("path_attrs", [])
1500
+ if a in self.class_strs.get((rel, cname), {})), None)
1501
+ name = _http_name(method, path) if path is not None else f"{method or 'ANY'} {cname}"
1502
+ if path is None and spec != "$1" and m.lastindex: # `resolve_(\w+)`: the field the method serves
1503
+ name += "." + m.group(1)
1504
+ self.ix.entries.append(Entry("http", name, rel, fn.start, targets=[fn], path=path, method=method))
1505
+ else:
1506
+ label = next((self.class_strs[(rel, cname)][a] for a in rule.get("name_attrs", [])
1507
+ if a in self.class_strs.get((rel, cname), {})), None)
1508
+ self.ix.entries.append(Entry(kind, label or fn.symbol, rel, fn.start, targets=[fn]))
1509
+ break
1510
+
1511
+ def finish(self):
1512
+ self._class_entries()
1513
+ self._framework_edges()
1514
+ for rel in self.imports:
1515
+ self.imported_files |= self._imported_files(rel)
1516
+ for rel, (line, service) in self.main_files.items():
1517
+ mod = self.modfn[rel]
1518
+ if is_test_path(rel):
1519
+ continue
1520
+ self.ix.entries.append(Entry("main" if service else "cli", f"python {rel}", rel, line, targets=[mod]))
1521
+
1522
+
1523
+ # --------------------------------------------------------------------------- Rust
1524
+
1525
+ RUST_BIND = (r"\b(?:let|for|mut|ref)\s+(?:mut\s+)?NAME\b|\bNAME\s*:[^:]|\|[^|\n]*\bNAME\b[^|\n]*\||"
1526
+ r"\b[A-Z]\w*\s*\(\s*(?:mut\s+)?NAME\s*\)|\blet\s*\([^)]*\bNAME\b|\bNAME\s*@|\{[^{}()]*\bNAME\s*[,}]")
1527
+ PY_BIND = (r"\bNAME\s*(?::[^=\n]+)?=[^=]|\bfor\s+[^\n:]*\bNAME\b[^\n:]*\bin\b|\bas\s+NAME\b|"
1528
+ r"\bdef\s+\w+\s*\([^)]*\bNAME\b|\blambda\b[^:\n]*\bNAME\b[^:\n]*:|\bNAME\s*,[^=\n()]*=[^=]")
1529
+ _BIND_CACHE: dict[tuple[str, str], object] = {}
1530
+
1531
+
1532
+ _WORD_BYTES = frozenset(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_")
1533
+
1534
+
1535
+ def _whole_words(text: bytes, word: bytes):
1536
+ """Start offsets where `word` (plain ASCII word characters) stands as a whole word: what `\\bword\\b` finds."""
1537
+ n, size, i = len(word), len(text), 0
1538
+ find = text.find
1539
+ while True:
1540
+ j = find(word, i)
1541
+ if j < 0:
1542
+ return
1543
+ e = j + n
1544
+ if (j and text[j - 1] in _WORD_BYTES) or (e < size and text[e] in _WORD_BYTES):
1545
+ i = j + 1
1546
+ continue
1547
+ yield j
1548
+ i = e
1549
+
1550
+
1551
+ _BIND_WORD = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
1552
+ _BIND_KEYWORDS = {"for", "as", "def", "lambda", "in", "let", "mut", "ref"}
1553
+ _BIND_HOLDERS = (b"Zcodecopboundnamez", b"zcodecopboundnamez") # stands in for the name: same word class, same first-letter case
1554
+
1555
+
1556
+ def _binds(template: str, name: str, body: bytes) -> bool:
1557
+ """True when `name` is bound as a local (parameter, let, pattern) in this function body.
1558
+
1559
+ Compiling the template once per name is the slow part, so the usual case renames instead: every
1560
+ whole-word occurrence of the name in the body becomes a placeholder word and one pattern, compiled
1561
+ once per template for that placeholder, is searched. The templates only ever match the name as a
1562
+ whole word and treat it as a word, so the answer is the same. Names that are not plain ASCII words,
1563
+ keywords of the templates, or bodies that already hold the placeholder take the per-name pattern."""
1564
+ holder = _BIND_HOLDERS[0] if name[:1].isupper() and name[:1].isascii() else _BIND_HOLDERS[1]
1565
+ if _BIND_WORD.fullmatch(name) and name not in _BIND_KEYWORDS and b"codecopboundnamez" not in body:
1566
+ raw = name.encode()
1567
+ if raw not in body:
1568
+ return False # every alternative of the templates needs the name itself
1569
+ rx = _BIND_CACHE.get((template, ""))
1570
+ if rx is None:
1571
+ rx = _BIND_CACHE[(template, "")] = (re.compile(template.replace("NAME", _BIND_HOLDERS[0].decode()).encode()),
1572
+ re.compile(template.replace("NAME", _BIND_HOLDERS[1].decode()).encode()))
1573
+ parts, start = [], 0
1574
+ for at in _whole_words(body, raw):
1575
+ parts.append(body[start:at])
1576
+ start = at + len(raw)
1577
+ if not parts:
1578
+ return False
1579
+ parts.append(body[start:])
1580
+ return rx[holder is _BIND_HOLDERS[1]].search(holder.join(parts)) is not None
1581
+ rx = _BIND_CACHE.get((template, name))
1582
+ if rx is None:
1583
+ rx = _BIND_CACHE[(template, name)] = re.compile(template.replace("NAME", re.escape(name)).encode())
1584
+ return rx.search(body) is not None
1585
+
1586
+
1587
+ def _strip_generics(text: str) -> str:
1588
+ text = text.strip().lstrip("&").strip()
1589
+ for prefix in ("mut ", "dyn ", "impl "):
1590
+ if text.startswith(prefix):
1591
+ text = text[len(prefix):]
1592
+ depth, out = 0, []
1593
+ for ch in text:
1594
+ if ch == "<":
1595
+ depth += 1
1596
+ elif ch == ">":
1597
+ depth -= 1
1598
+ elif depth == 0:
1599
+ out.append(ch)
1600
+ return "".join(out).strip().split("::")[-1].strip()
1601
+
1602
+
1603
+ _RUST_WRAPPERS = ("Arc", "Box", "Rc", "Option", "Result", "Pin", "Cow", "Ref", "RefMut", "MutexGuard", "Lazy",
1604
+ "OnceCell", "OnceLock", "State", "Extension", "Data", "Json")
1605
+
1606
+
1607
+ def _rust_type(text: str) -> str:
1608
+ """`&Arc<Repo>`, `Result<Option<Repo>, Error>`, `impl Store + Send` -> `Repo` / `Store`."""
1609
+ text = text.strip()
1610
+ for _ in range(6):
1611
+ text = re.sub(r"^(&\s*)?('\w+\s+)?(mut\s+|dyn\s+|impl\s+)*", "", text).strip()
1612
+ m = re.match(r"^(?:[\w]+::)*(\w+)\s*<(.*)>$", text, re.S)
1613
+ if not m or m.group(1) not in _RUST_WRAPPERS:
1614
+ break
1615
+ inner, depth, cut = m.group(2), 0, None
1616
+ for i, ch in enumerate(inner):
1617
+ if ch in "<(":
1618
+ depth += 1
1619
+ elif ch in ">)":
1620
+ depth -= 1
1621
+ elif ch == "," and depth == 0:
1622
+ cut = i
1623
+ break
1624
+ text = inner[:cut] if cut is not None else inner
1625
+ text = text.split("+")[0].strip()
1626
+ return _strip_generics(text) if re.match(r"^[\w:<>,\s&']+$", text) else ""
1627
+
1628
+
1629
+ def _rust_chain(node: Node | None, depth: int = 0) -> str | None:
1630
+ """A receiver as steps we can type later: `self.repo.pool()` -> `self.f:repo.m:pool`."""
1631
+ if node is None or depth > 5:
1632
+ return None
1633
+ t = node.type
1634
+ if t == "self":
1635
+ return "self"
1636
+ if t == "identifier":
1637
+ return "v:" + _t(node)
1638
+ if t == "field_expression":
1639
+ base = _rust_chain(node.child_by_field_name("value"), depth + 1)
1640
+ field = node.child_by_field_name("field")
1641
+ if base is None or field is None or field.type != "field_identifier":
1642
+ return None
1643
+ return f"{base}.f:{_t(field)}"
1644
+ if t == "call_expression":
1645
+ f = node.child_by_field_name("function")
1646
+ if f is None:
1647
+ return None
1648
+ if f.type == "generic_function":
1649
+ f = f.child_by_field_name("function")
1650
+ if f is None:
1651
+ return None
1652
+ if f.type == "field_expression":
1653
+ base = _rust_chain(f.child_by_field_name("value"), depth + 1)
1654
+ return None if base is None else f"{base}.m:{_t(f.child_by_field_name('field'))}"
1655
+ if f.type in ("identifier", "scoped_identifier") and f.end_byte - f.start_byte < 80:
1656
+ return "c:" + _t(f).replace(" ", "").replace("\n", "").replace(".", "")
1657
+ return None
1658
+ if t in ("await_expression", "try_expression", "reference_expression", "parenthesized_expression", "unary_expression"):
1659
+ kids = node.named_children
1660
+ return _rust_chain(kids[-1] if t != "await_expression" else kids[0], depth + 1) if kids else None
1661
+ return None
1662
+
1663
+
1664
+ class Rust(Lang):
1665
+ name = "rust"
1666
+
1667
+ FN_RE = re.compile(rb"\bfn\s+(\w+)")
1668
+ INLINE_MOD_RE = re.compile(rb"\bmod\s+(\w+)\s*\{")
1669
+ ALIAS_RE = re.compile(rb"\w\s+as\s+([a-z_]\w*)\s*[,;}]")
1670
+ MACRO_STR = re.compile(r'r#*"[\s\S]*?"#*|"(?:[^"\\]|\\.)*"')
1671
+ MACRO_CALL = re.compile(r"(?<![\w!.:])((?:[A-Za-z_]\w*\s*::\s*)*[a-z_]\w*)\s*\(")
1672
+ MACRO_METHOD = re.compile(r"\.\s*([a-z_]\w*)\s*\(")
1673
+ KEYWORDS = {"if", "while", "match", "for", "fn", "return", "loop", "let", "in", "as", "move", "async", "await", "else",
1674
+ "unsafe", "where", "impl", "dyn", "ref", "mut", "pub", "use", "mod", "crate", "self", "super"}
1675
+
1676
+ def __init__(self, index, rules):
1677
+ super().__init__(index, rules)
1678
+ import tree_sitter_rust
1679
+ self.language = Language(tree_sitter_rust.language())
1680
+ self.parser = Parser(self.language)
1681
+ self.q = Query(self.language, """
1682
+ (function_item) @func
1683
+ (call_expression) @call
1684
+ (macro_invocation) @macro
1685
+ (use_declaration argument: (_) @use)
1686
+ (arguments (identifier) @ref)
1687
+ (arguments (scoped_identifier) @ref)
1688
+ (struct_item) @struct
1689
+ (let_declaration) @let
1690
+ """)
1691
+ self.fields: dict[tuple[str, str], set[str]] = defaultdict(set) # (struct, field) -> type names
1692
+ self.known_types: set[str] = set()
1693
+ self.attr_rules = self._compile("attribute")
1694
+ self.call_rules = self._compile("call")
1695
+ self.call_pre = re.compile("|".join(f"(?:{r['match']})" for r in rules.get("call", [])) or r"\b\B")
1696
+ router = rules.get("router", {})
1697
+ self.route_names = set(router.get("route", []))
1698
+ self.method_names = set(router.get("methods", []))
1699
+ self.nest_names = set(router.get("nest", []))
1700
+ self.merge_names = set(router.get("merge", []))
1701
+ self.fallback_names = set(router.get("fallback", []))
1702
+ self.route_macros = set(router.get("macros", []))
1703
+ self.router_names = self.route_names | self.nest_names | self.merge_names | self.fallback_names
1704
+ self.reg_bytes = re.compile(b"|".join(re.escape(n.encode()) + rb"\s*\(" for n in sorted(self.router_names)) + rb"|spawn")
1705
+ self.uses: dict[str, dict[str, list[str]]] = {}
1706
+ self.globs: dict[str, list[list[str]]] = defaultdict(list)
1707
+ self.crate_of: dict[str, tuple[str, tuple[str, ...]]] = {} # file -> (crate root dir, module path)
1708
+ self.crate_names: dict[str, str] = {} # crate name -> crate root dir
1709
+ self.mods: dict[tuple[str, tuple[str, ...]], str] = {} # (crate root, module path) -> file
1710
+ self.free: dict[str, dict[str, list[Fn]]] = defaultdict(lambda: defaultdict(list)) # file -> name -> free fns
1711
+ self.by_type: dict[tuple[str, str], list[Fn]] = defaultdict(list) # (type, method) -> fns
1712
+ self.trait_impls: dict[str, list[tuple[str, Fn]]] = defaultdict(list) # type -> (trait, method) of its `impl Trait for Type` blocks
1713
+ self.fn_bounds: dict[str, set[str]] = defaultdict(set) # generic free function -> names in its bounds
1714
+ self.http_attr: dict[int, Entry] = {}
1715
+ self.inline_mods: dict[str, set[str]] = {}
1716
+
1717
+ def prescan(self, rel, src):
1718
+ for m in self.FN_RE.finditer(src):
1719
+ self.fn_names.add(m.group(1).decode())
1720
+ for m in self.ALIAS_RE.finditer(src): # `use a::real as alias`: calls go by the alias
1721
+ self.fn_names.add(m.group(1).decode())
1722
+ inline = {m.group(1).decode() for m in self.INLINE_MOD_RE.finditer(src)}
1723
+ if inline:
1724
+ self.inline_mods[rel] = inline
1725
+ parts = rel.split("/")
1726
+ if "src" in parts:
1727
+ i = len(parts) - 1 - parts[::-1].index("src")
1728
+ root, tail = "/".join(parts[:i]), parts[i + 1:]
1729
+ else:
1730
+ root, tail = os.path.dirname(rel), [parts[-1]]
1731
+ stem = tail[-1][:-3]
1732
+ modpath = tuple(tail[:-1]) + (() if stem in ("mod", "lib", "main") else (stem,))
1733
+ self.crate_of[rel] = (root, modpath)
1734
+ self.mods.setdefault((root, modpath), rel)
1735
+ if root not in self.crate_names.values():
1736
+ name = os.path.basename(root) or self.ix.root.name
1737
+ try:
1738
+ cargo = (self.ix.root / root / "Cargo.toml").read_text(errors="replace")
1739
+ m = re.search(r'(?m)^\[package\][\s\S]*?^name\s*=\s*"([^"]+)"', cargo)
1740
+ if m:
1741
+ name = m.group(1)
1742
+ except OSError:
1743
+ pass
1744
+ self.crate_names.setdefault(name.replace("-", "_"), root)
1745
+
1746
+ def parse(self, rel, src):
1747
+ tree = self.parser.parse(src)
1748
+ if TREE_HOOK is not None:
1749
+ TREE_HOOK(self.name, self.language, rel, src, tree)
1750
+ caps = QueryCursor(self.q).captures(tree.root_node)
1751
+ file_test = is_test_path(rel) or bool(re.search(r"(^|/)(tests?|[^/]*_tests?|test_[^/]*|testing|test_support|test_helpers|bench[^/]*)\.rs$|(^|/)benches/", rel))
1752
+ uses = self.uses.setdefault(rel, {})
1753
+ for node in caps.get("use", []):
1754
+ for path, alias in self._expand_use(_t(node)):
1755
+ if path and path[-1] == "*":
1756
+ self.globs[rel].append(path[:-1])
1757
+ elif path:
1758
+ uses[alias or path[-1]] = path
1759
+ for node in caps.get("struct", []):
1760
+ sname = _t(node.child_by_field_name("name"))
1761
+ self.known_types.add(sname)
1762
+ body = node.child_by_field_name("body")
1763
+ if body is not None and body.type == "field_declaration_list":
1764
+ for fd in body.named_children:
1765
+ if fd.type == "field_declaration":
1766
+ ft = _rust_type(_t(fd.child_by_field_name("type")))
1767
+ if ft:
1768
+ self.fields[(sname, _t(fd.child_by_field_name("name")))].add(ft)
1769
+ test_mods: dict[int, bool] = {}
1770
+ for node in sorted(caps.get("func", []), key=lambda n: n.start_byte):
1771
+ name = _t(node.child_by_field_name("name"))
1772
+ container, names, in_test, p = "", [name], file_test, node.parent
1773
+ nested = False
1774
+ trait = ""
1775
+ while p is not None:
1776
+ pt = p.type
1777
+ if pt in ("impl_item", "trait_item"):
1778
+ t = _strip_generics(_t(p.child_by_field_name("type") or p.child_by_field_name("name")))
1779
+ if not container and not nested:
1780
+ container = t
1781
+ tr = p.child_by_field_name("trait") if pt == "impl_item" else None
1782
+ trait = _strip_generics(_t(tr)) if tr is not None else ""
1783
+ names.append(t)
1784
+ elif pt == "function_item":
1785
+ nested = True
1786
+ names.append(_t(p.child_by_field_name("name")))
1787
+ elif pt == "mod_item":
1788
+ cached = test_mods.get(p.id)
1789
+ if cached is None:
1790
+ cached = any("test" in a for a in self._attrs(p))
1791
+ test_mods[p.id] = cached
1792
+ in_test = in_test or cached
1793
+ p = p.parent
1794
+ attrs = self._attrs(node)
1795
+ params = node.child_by_field_name("parameters")
1796
+ is_method, nparams = False, 0
1797
+ vars_: dict[str, tuple[str, str]] = {}
1798
+ if params is not None:
1799
+ for c in params.named_children:
1800
+ if c.type == "self_parameter":
1801
+ is_method = True
1802
+ elif c.type in ("parameter", "variadic_parameter"):
1803
+ nparams += 1
1804
+ pat, typ = c.child_by_field_name("pattern"), c.child_by_field_name("type")
1805
+ if pat is not None and typ is not None:
1806
+ pname = re.sub(r"^.*\(\s*(?:mut\s+)?(\w+)\s*\)$", r"\1", _t(pat)).removeprefix("mut ").strip()
1807
+ if pname.isidentifier():
1808
+ vars_[pname] = ("t", _rust_type(_t(typ)))
1809
+ line = node.start_point[0] + 1
1810
+ entry_specs = []
1811
+ for attr in attrs:
1812
+ m0 = re.match(r"#!?\[\s*([\w:]+)\s*(?:\(([\s\S]*)\))?\s*\]", attr)
1813
+ if not m0:
1814
+ continue
1815
+ aname, abody = m0.group(1), m0.group(2) or ""
1816
+ for rx, rule in self.attr_rules:
1817
+ m = rx.search(aname)
1818
+ if m:
1819
+ entry_specs.append((rule, m, abody))
1820
+ break
1821
+ if any(r["kind"] == "test" for r, _, _ in entry_specs):
1822
+ in_test = True
1823
+ fn = self.add_fn(Fn(rel, "rust", name, "::".join(reversed(names)), container, node, method=is_method,
1824
+ nparams=nparams, test=in_test))
1825
+ ret = node.child_by_field_name("return_type")
1826
+ fn.extra = {"vars": vars_, "ret": _rust_type(_t(ret)) if ret is not None else ""}
1827
+ if container:
1828
+ self.known_types.add(container)
1829
+ self.by_type[(container, name)].append(fn)
1830
+ if trait: # `impl Store for PgStore`: a `dyn Store` receiver reaches it
1831
+ self.known_types.add(trait)
1832
+ self.by_type[(trait, name)].append(fn)
1833
+ self.trait_impls[container].append((trait, fn))
1834
+ elif not nested:
1835
+ self.free[rel][name].append(fn)
1836
+ # `fn route<Data>(..) where Data: Perform + Send`: the traits a type handed in by turbofish must implement
1837
+ bounds = " ".join(_t(node.child_by_field_name(k)) for k in ("type_parameters",) if node.child_by_field_name(k) is not None)
1838
+ bounds += " " + " ".join(_t(c) for c in node.named_children if c.type == "where_clause")
1839
+ if bounds.strip():
1840
+ self.fn_bounds[name].update(re.findall(r"\b[A-Z]\w*", bounds))
1841
+ for rule, m, abody in entry_specs:
1842
+ kind = rule["kind"]
1843
+ if kind == "test":
1844
+ self.ix.entries.append(Entry("test", f"{rel}::{fn.symbol}", rel, line, targets=[fn]))
1845
+ elif kind == "main":
1846
+ self.ix.entries.append(Entry("main", f"main {self._main_name(rel)}", rel, line, targets=[fn]))
1847
+ elif kind == "http":
1848
+ method, path = self._attr_route(rel, rule, m, abody)
1849
+ if path is None:
1850
+ continue
1851
+ e = Entry("http", _http_name(method, path), rel, line, targets=[fn], path=path, method=method)
1852
+ self.http_attr[fn.id] = e
1853
+ self.ix.entries.append(e)
1854
+ if name == "main" and not container and not nested and not in_test and not any(r["kind"] == "main" for r, _, _ in entry_specs):
1855
+ self.ix.entries.append(Entry("main", f"main {self._main_name(rel)}", rel, line, targets=[fn]))
1856
+ calls = caps.get("call", [])
1857
+ self.link(rel, src)
1858
+ at = self.ix.at_byte
1859
+ reg_ids: set[int] = set()
1860
+ if self.reg_bytes.search(src):
1861
+ # routes and spawns first: a handler written inline becomes a function of its own
1862
+ before = len(self.ix.by_file[rel])
1863
+ for node in calls:
1864
+ f = node.child_by_field_name("function")
1865
+ if f is None:
1866
+ continue
1867
+ if f.type == "field_expression":
1868
+ fname = _t(f.child_by_field_name("field"))
1869
+ if fname in self.router_names:
1870
+ self._route(rel, node, fname, at(rel, node.start_byte), reg_ids)
1871
+ elif f.type in ("identifier", "scoped_identifier"):
1872
+ text = _t(f).replace(" ", "")
1873
+ if self.call_pre.search(text):
1874
+ self._spawn(rel, node, text, at(rel, node.start_byte))
1875
+ if len(self.ix.by_file[rel]) != before:
1876
+ self.link(rel, src)
1877
+ for node in caps.get("let", []):
1878
+ pat = node.child_by_field_name("pattern")
1879
+ if pat is None or pat.type != "identifier":
1880
+ continue
1881
+ owner = at(rel, node.start_byte)
1882
+ while owner is not None and owner.extra is None:
1883
+ owner = owner.lex
1884
+ if owner is None:
1885
+ continue
1886
+ typ, value = node.child_by_field_name("type"), node.child_by_field_name("value")
1887
+ if typ is not None:
1888
+ owner.extra["vars"].setdefault(_t(pat), ("t", _rust_type(_t(typ))))
1889
+ elif value is not None:
1890
+ ch = _rust_chain(value)
1891
+ if ch is not None and ch != "v:" + _t(pat):
1892
+ owner.extra["vars"].setdefault(_t(pat), ("x", ch))
1893
+ names = self.fn_names
1894
+ local = set(self.free[rel]) | set(uses)
1895
+ bound: dict[tuple[int, str], bool] = {}
1896
+ for node in caps.get("ref", []):
1897
+ if node.id in reg_ids:
1898
+ continue
1899
+ if node.type == "identifier":
1900
+ name = _t(node)
1901
+ if name in local and name in names:
1902
+ owner = at(rel, node.start_byte)
1903
+ if owner is None:
1904
+ continue
1905
+ key = (owner.id, name)
1906
+ if key not in bound:
1907
+ bound[key] = _binds(RUST_BIND, name, src[owner.sb:owner.eb])
1908
+ if not bound[key]:
1909
+ owner.calls.append(("r", name, "", node.start_point[0] + 1, -1))
1910
+ else:
1911
+ name = _t(node.child_by_field_name("name"))
1912
+ if name in names:
1913
+ owner = at(rel, node.start_byte)
1914
+ if owner is not None:
1915
+ owner.calls.append(("r", name, _t(node.child_by_field_name("path")).replace(" ", ""),
1916
+ node.start_point[0] + 1, -1))
1917
+ for node in calls:
1918
+ f = node.child_by_field_name("function")
1919
+ if f is None:
1920
+ continue
1921
+ if f.type == "generic_function":
1922
+ f = f.child_by_field_name("function")
1923
+ if f is None:
1924
+ continue
1925
+ ft = f.type
1926
+ if ft == "identifier":
1927
+ name, qual = _t(f), ""
1928
+ elif ft == "scoped_identifier":
1929
+ name = _t(f.child_by_field_name("name"))
1930
+ qual = _t(f.child_by_field_name("path")).replace(" ", "").replace("\n", "") or "crate"
1931
+ elif ft == "field_expression":
1932
+ name = _t(f.child_by_field_name("field"))
1933
+ if name not in names:
1934
+ continue
1935
+ qual = "." + (_rust_chain(f.child_by_field_name("value")) or "")
1936
+ else:
1937
+ continue
1938
+ if name not in names and not (ft == "identifier" and name in uses): # `use a::real as alias`
1939
+ continue
1940
+ owner = at(rel, node.start_byte)
1941
+ if owner is None:
1942
+ continue
1943
+ args = node.child_by_field_name("arguments")
1944
+ owner.calls.append(("c", name, qual, node.start_point[0] + 1, args.named_child_count if args is not None else -1))
1945
+ for node in caps.get("macro", []):
1946
+ mname = _t(node.child_by_field_name("macro")).split("::")[-1]
1947
+ owner = at(rel, node.start_byte)
1948
+ if mname in self.route_macros:
1949
+ self._routes_macro(rel, node, owner)
1950
+ continue
1951
+ if owner is None or node.end_byte - node.start_byte > 20000:
1952
+ continue
1953
+ p = node.parent
1954
+ inner = False
1955
+ while p is not None and p.type != "function_item":
1956
+ if p.type == "macro_invocation":
1957
+ inner = True
1958
+ break
1959
+ p = p.parent
1960
+ if inner:
1961
+ continue
1962
+ text = self.MACRO_STR.sub('""', _t(node))
1963
+ line = node.start_point[0] + 1
1964
+ for m in self.MACRO_CALL.finditer(text):
1965
+ path = m.group(1).replace(" ", "").replace("\n", "")
1966
+ name = path.split("::")[-1]
1967
+ if (name in names or ("::" not in path and name in uses)) and name not in self.KEYWORDS:
1968
+ owner.calls.append(("c", name, "::".join(path.split("::")[:-1]), line, -1))
1969
+ for m in self.MACRO_METHOD.finditer(text):
1970
+ if m.group(1) in names:
1971
+ owner.calls.append(("c", m.group(1), ".", line, -1))
1972
+
1973
+ def _main_name(self, rel: str) -> str:
1974
+ root = self.crate_of[rel][0]
1975
+ if "/bin/" in rel or "/examples/" in rel:
1976
+ return rel
1977
+ return root or rel
1978
+
1979
+ @staticmethod
1980
+ def _attrs(node: Node) -> list[str]:
1981
+ out, p = [], node.prev_sibling
1982
+ while p is not None and p.type in ("attribute_item", "line_comment", "block_comment", "inner_attribute_item"):
1983
+ if p.type == "attribute_item":
1984
+ out.append(_t(p))
1985
+ p = p.prev_sibling
1986
+ return out
1987
+
1988
+ def _attr_route(self, rel: str, rule: dict, m: re.Match, body: str) -> tuple[str, str | None]:
1989
+ spec = rule.get("method", "")
1990
+ if spec == "utoipa":
1991
+ mm = re.match(r"\s*(get|post|put|delete|patch|head|options|trace)\b", body)
1992
+ pm = re.search(r"\bpath\s*=\s*(\"(?:[^\"\\]|\\.)*\"|[A-Za-z_][\w:]*)", body)
1993
+ if pm is None:
1994
+ return "", None
1995
+ path, _ = self.ix.consts.eval("rust", rel, pm.group(1))
1996
+ cm = re.search(r"\bcontext_path\s*=\s*(\"(?:[^\"\\]|\\.)*\"|[A-Za-z_][\w:]*)", body)
1997
+ if cm:
1998
+ path = _join_path(self.ix.consts.eval("rust", rel, cm.group(1))[0], path)
1999
+ if mm is None:
2000
+ mm = re.search(r"\bmethod\s*\(\s*(\w+)", body)
2001
+ return (mm.group(1).upper() if mm else ""), path
2002
+ pm = re.match(r"\s*(\"(?:[^\"\\]|\\.)*\"|[A-Z_][A-Z0-9_]*)", body)
2003
+ if pm is None:
2004
+ return "", None
2005
+ path, _ = self.ix.consts.eval("rust", rel, pm.group(1))
2006
+ if spec == "$1":
2007
+ return m.group(1).upper(), path
2008
+ mm = re.search(r"\bmethod\s*=\s*\"?(\w+)", body)
2009
+ return (mm.group(1).upper() if mm else ""), path
2010
+
2011
+ @staticmethod
2012
+ def _expand_use(text: str) -> list[tuple[list[str], str]]:
2013
+ text = re.sub(r"\s+", " ", text.strip())
2014
+ out: list[tuple[list[str], str]] = []
2015
+
2016
+ def walk(prefix: list[str], s: str) -> None:
2017
+ s = s.strip()
2018
+ if not s:
2019
+ return
2020
+ i = s.find("{")
2021
+ if i < 0:
2022
+ alias = ""
2023
+ if " as " in s:
2024
+ s, alias = s.split(" as ", 1)
2025
+ parts = [p.strip() for p in s.split("::") if p.strip()]
2026
+ if parts and parts[-1] == "self":
2027
+ parts = parts[:-1]
2028
+ out.append((prefix + parts, alias.strip()))
2029
+ return
2030
+ head = [p.strip() for p in s[:i].split("::") if p.strip()]
2031
+ depth, start, j = 0, i + 1, i
2032
+ for j in range(i, len(s)):
2033
+ ch = s[j]
2034
+ if ch == "{":
2035
+ depth += 1
2036
+ elif ch == "}":
2037
+ depth -= 1
2038
+ if depth == 0:
2039
+ walk(prefix + head, s[start:j])
2040
+ break
2041
+ elif ch == "," and depth == 1:
2042
+ walk(prefix + head, s[start:j])
2043
+ start = j + 1
2044
+ try:
2045
+ walk([], text)
2046
+ except RecursionError:
2047
+ pass
2048
+ return out
2049
+
2050
+ def _handler(self, rel: str, node: Node, owner: Fn | None, label: str, refs: list, targets: list, seen: set) -> None:
2051
+ """A handler argument: a function by name, or a closure / async block written inline."""
2052
+ line = node.start_point[0] + 1
2053
+ seen.add(node.id)
2054
+ if node.type == "identifier":
2055
+ refs.append(("r", _t(node), "", line, -1))
2056
+ elif node.type == "scoped_identifier":
2057
+ refs.append(("r", _t(node.child_by_field_name("name")), _t(node.child_by_field_name("path")).replace(" ", ""), line, -1))
2058
+ elif node.type == "generic_function":
2059
+ # `route_get::<GetPosts>`: a generic handler made for one type. It runs that type's methods of the traits
2060
+ # its bounds name (`where Data: Perform`), so those are reached by the route as well.
2061
+ f = node.child_by_field_name("function")
2062
+ if f is not None and f.type in ("identifier", "scoped_identifier"):
2063
+ self._handler(rel, f, owner, label, refs, targets, seen)
2064
+ fname = _t(f).rsplit("::", 1)[-1]
2065
+ types = node.child_by_field_name("type_arguments")
2066
+ for a in (types.named_children if types is not None else ()):
2067
+ if a.type in ("type_identifier", "scoped_type_identifier", "generic_type"):
2068
+ refs.append(("G", _strip_generics(_t(a)).rsplit("::", 1)[-1], fname, line, -1))
2069
+ elif node.type in ("closure_expression", "async_block"):
2070
+ sym = (owner.symbol if owner else "") or label
2071
+ targets.append(self.add_fn(Fn(rel, "rust", "<closure>", sym, owner.container if owner else "", node, inline=True,
2072
+ test=owner.test if owner else False)))
2073
+ elif node.type == "call_expression":
2074
+ f = node.child_by_field_name("function")
2075
+ if f is not None and f.type in ("identifier", "scoped_identifier", "generic_function"):
2076
+ if f.type == "generic_function":
2077
+ f = f.child_by_field_name("function")
2078
+ self._handler(rel, f, owner, label, refs, targets, seen)
2079
+ args = node.child_by_field_name("arguments")
2080
+ if args is not None:
2081
+ for a in args.named_children:
2082
+ if a.type in ("identifier", "scoped_identifier", "closure_expression", "call_expression"):
2083
+ self._handler(rel, a, owner, label, refs, targets, seen)
2084
+
2085
+ def _method_router(self, node: Node, out: list[tuple[str, Node]]) -> None:
2086
+ """`get(h).post(h2)` -> [("GET", h), ("POST", h2)]."""
2087
+ if node.type != "call_expression":
2088
+ return
2089
+ f = node.child_by_field_name("function")
2090
+ args = node.child_by_field_name("arguments")
2091
+ if f is None or args is None:
2092
+ return
2093
+ if f.type == "field_expression":
2094
+ name = _t(f.child_by_field_name("field"))
2095
+ value = f.child_by_field_name("value")
2096
+ if value is not None:
2097
+ self._method_router(value, out)
2098
+ else:
2099
+ name = _t(f).split("::")[-1]
2100
+ if name in self.method_names and args.named_children:
2101
+ verb = name.replace("_service", "").upper()
2102
+ out.append(("ANY" if verb == "ON" else verb, args.named_children[-1]))
2103
+ elif name == "to" and f.type == "field_expression" and args.named_children:
2104
+ # actix-web: `web::get().to(handler)`, `web::route().to(handler)`
2105
+ value = f.child_by_field_name("value")
2106
+ vf = value.child_by_field_name("function") if value is not None and value.type == "call_expression" else None
2107
+ verb = _t(vf).split("::")[-1] if vf is not None and vf.type in ("identifier", "scoped_identifier") else ""
2108
+ if verb in self.method_names or verb == "route":
2109
+ out.append(("ANY" if verb == "route" else verb.upper(), args.named_children[-1]))
2110
+ self._actix = True
2111
+
2112
+ def _actix_scope(self, rel: str, call: Node | None) -> str:
2113
+ """The path a builder chain starts with: `web::scope("/post").wrap(x)` or `web::resource("/x")` -> its path."""
2114
+ while call is not None and call.type == "call_expression":
2115
+ f = call.child_by_field_name("function")
2116
+ if f is None:
2117
+ return ""
2118
+ if f.type == "field_expression":
2119
+ call = f.child_by_field_name("value")
2120
+ continue
2121
+ if _t(f).split("::")[-1] in ("scope", "resource"):
2122
+ args = call.child_by_field_name("arguments")
2123
+ if args is not None and args.named_children:
2124
+ return self._path(rel, args.named_children[0])
2125
+ return ""
2126
+ return ""
2127
+
2128
+ def _actix_prefix(self, rel: str, node: Node) -> str:
2129
+ """Path prefix of an actix-web route: the scope or resource its own chain starts with, then the scope of
2130
+ every `.service(...)` it is nested in."""
2131
+ f = node.child_by_field_name("function")
2132
+ prefix = self._actix_scope(rel, f.child_by_field_name("value") if f is not None and f.type == "field_expression" else None)
2133
+ p = node.parent
2134
+ while p is not None and p.type not in ("function_item", "closure_expression"):
2135
+ if p.type == "arguments" and p.parent is not None and p.parent.type == "call_expression":
2136
+ pf = p.parent.child_by_field_name("function")
2137
+ if pf is not None and pf.type == "field_expression" and _t(pf.child_by_field_name("field")) == "service":
2138
+ prefix = _join_path(self._actix_scope(rel, pf.child_by_field_name("value")), prefix)
2139
+ p = p.parent
2140
+ return prefix
2141
+
2142
+ def _route(self, rel: str, node: Node, fname: str, owner: Fn | None, seen: set) -> None:
2143
+ args = node.child_by_field_name("arguments")
2144
+ if args is None:
2145
+ return
2146
+ pos = [a for a in args.named_children if a.type not in ("line_comment", "block_comment")]
2147
+ field = node.child_by_field_name("function").child_by_field_name("field")
2148
+ line = (field or node).start_point[0] + 1 # the `.route` of a builder chain, not where the chain starts
2149
+ if fname in self.route_names and len(pos) in (1, 2):
2150
+ path = self._path(rel, pos[0]) if len(pos) == 2 else ""
2151
+ pairs: list[tuple[str, Node]] = []
2152
+ self._actix = False
2153
+ self._method_router(pos[-1], pairs)
2154
+ if len(pos) == 1 and not self._actix: # `.route(x)` with one argument is only actix's `resource("/x").route(web::get().to(h))`
2155
+ pairs = []
2156
+ if self._actix and pairs:
2157
+ path = _join_path(self._actix_prefix(rel, node), path) or "/"
2158
+ for verb, h in pairs:
2159
+ refs, targets = [], []
2160
+ self._handler(rel, h, owner, f"{verb} {path}", refs, targets, seen)
2161
+ if refs or targets:
2162
+ self.ix.entries.append(Entry("http", _http_name(verb, path), rel, line, targets=targets,
2163
+ pending=[(owner, r) for r in refs] if owner else [], decl=owner,
2164
+ path=path, method=verb))
2165
+ elif fname in self.nest_names and len(pos) == 2 and owner is not None:
2166
+ prefix, ok = self.ix.consts.eval("rust", rel, _t(pos[0]))
2167
+ self._nest(owner, prefix if pos[0].type in ("string_literal", "raw_string_literal") or ok else None, pos[1])
2168
+ elif fname in self.merge_names and len(pos) == 1 and owner is not None:
2169
+ self._nest(owner, "", pos[0])
2170
+ elif fname in self.fallback_names and len(pos) == 1:
2171
+ refs, targets = [], []
2172
+ self._handler(rel, pos[0], owner, "fallback", refs, targets, seen)
2173
+ if owner is not None and (refs or targets) and not (owner.test):
2174
+ self.ix.entries.append(Entry("http", "ANY (fallback)", rel, line, targets=targets,
2175
+ pending=[(owner, r) for r in refs], decl=owner, path=None, method="ANY"))
2176
+
2177
+ def _path(self, rel: str, node: Node) -> str:
2178
+ """A route path: a literal, a constant, or `&format!("{BASE}/x")` with constants filled in."""
2179
+ while node.type in ("reference_expression", "parenthesized_expression") and node.named_children:
2180
+ node = node.named_children[-1]
2181
+ if node.type in ("string_literal", "raw_string_literal", "scoped_identifier"):
2182
+ return self.ix.consts.eval("rust", rel, _t(node))[0]
2183
+ if node.type == "identifier":
2184
+ return self.ix.consts.eval("rust", rel, _t(node))[0] if self.ix.consts.lookup("rust", rel, _t(node)) else "…"
2185
+ if node.type == "macro_invocation" and _t(node.child_by_field_name("macro")) in ("format", "concat"):
2186
+ m = re.fullmatch(r'\w+!\s*\(\s*"((?:[^"\\]|\\.)*)"\s*,?\s*\)', _t(node), re.S)
2187
+ if m:
2188
+ def fill(mm: re.Match) -> str:
2189
+ hit = self.ix.consts.lookup("rust", rel, mm.group(1))
2190
+ return self.ix.consts.eval("rust", hit[0], hit[1])[0] if hit else mm.group(0)
2191
+ return re.sub(r"\{([A-Z][A-Z0-9_]*)\}", fill, m.group(1))
2192
+ return "…"
2193
+
2194
+ def _nest(self, owner: Fn, prefix: str | None, node: Node) -> None:
2195
+ if node.type != "call_expression":
2196
+ return
2197
+ f = node.child_by_field_name("function")
2198
+ while f is not None and f.type == "field_expression": # `routes::router().with_state(s)`
2199
+ inner = f.child_by_field_name("value")
2200
+ if inner is None or inner.type != "call_expression":
2201
+ return
2202
+ f = inner.child_by_field_name("function")
2203
+ if f is None or f.type not in ("identifier", "scoped_identifier"):
2204
+ return
2205
+ if f.type == "identifier":
2206
+ call = ("c", _t(f), "", node.start_point[0] + 1, -1)
2207
+ else:
2208
+ call = ("c", _t(f.child_by_field_name("name")), _t(f.child_by_field_name("path")).replace(" ", ""),
2209
+ node.start_point[0] + 1, -1)
2210
+ self.ix.nests.append((owner, prefix, call))
2211
+
2212
+ def _routes_macro(self, rel: str, node: Node, owner: Fn | None) -> None:
2213
+ """`routes!(a, module::b)`: the named handlers are routed (their #[utoipa::path] names them)."""
2214
+ tt = node.named_children[-1] if node.named_children else None
2215
+ text = _t(tt)[1:-1] if tt is not None else ""
2216
+ line = node.start_point[0] + 1
2217
+ for part in text.split(","):
2218
+ part = part.strip().replace(" ", "")
2219
+ if not re.fullmatch(r"[\w:]+", part):
2220
+ continue
2221
+ segs = part.split("::")
2222
+ e = Entry("http", "", rel, line, pending=[(owner, ("r", segs[-1], "::".join(segs[:-1]), line, -1))] if owner else [],
2223
+ decl=owner, path=None, method="")
2224
+ e.tag = "routes!"
2225
+ self.ix.entries.append(e)
2226
+
2227
+ def _spawn(self, rel: str, node: Node, callee: str, owner: Fn | None) -> None:
2228
+ """`tokio::spawn(run_loop(state))` or `tokio::spawn(async move { loop { ... } })`: a background job."""
2229
+ for rx, rule in self.call_rules:
2230
+ if not rx.search(callee):
2231
+ continue
2232
+ args = node.child_by_field_name("arguments")
2233
+ i = rule.get("handler", 0)
2234
+ if args is None or owner is None or i >= args.named_child_count:
2235
+ return
2236
+ a = args.named_children[i]
2237
+ line = node.start_point[0] + 1
2238
+ if a.type == "call_expression":
2239
+ f = a.child_by_field_name("function")
2240
+ if f is not None and f.type == "generic_function":
2241
+ f = f.child_by_field_name("function")
2242
+ if f is None:
2243
+ return
2244
+ if f.type == "identifier":
2245
+ call = ("r", _t(f), "", line, -1)
2246
+ elif f.type == "scoped_identifier":
2247
+ call = ("r", _t(f.child_by_field_name("name")), _t(f.child_by_field_name("path")).replace(" ", ""), line, -1)
2248
+ elif f.type == "field_expression":
2249
+ call = ("c", _t(f.child_by_field_name("field")), "." + (_rust_chain(f.child_by_field_name("value")) or ""), line, -1)
2250
+ else:
2251
+ return
2252
+ self.ix.entries.append(Entry(rule["kind"], call[1], rel, line, pending=[(owner, call)], decl=owner,
2253
+ loop_only=bool(rule.get("loop_only"))))
2254
+ elif a.type in ("async_block", "closure_expression") and self.loop_re is not None and self.loop_re.search(a.text):
2255
+ if owner.test:
2256
+ return
2257
+ fn = self.add_fn(Fn(rel, "rust", "<spawned loop>", owner.symbol, owner.container, a, inline=True))
2258
+ e = Entry(rule["kind"], f"{owner.symbol} (spawned loop)", rel, line, targets=[fn])
2259
+ e.tag = "loop"
2260
+ self.ix.entries.append(e)
2261
+ return
2262
+
2263
+ # -- resolution -----------------------------------------------------------
2264
+ def _module_files(self, rel: str, path: list[str], depth: int = 0) -> tuple[str, tuple[str, ...]] | None:
2265
+ """(crate root, module path) a `use`-style path points into, or None for an external crate."""
2266
+ if not path or depth > 6:
2267
+ return None
2268
+ root, here = self.crate_of[rel]
2269
+ head = path[0]
2270
+ if head == "crate":
2271
+ return self._canon(root, (), path[1:], depth)
2272
+ if head == "self":
2273
+ return self._canon(root, here, path[1:], depth)
2274
+ if head == "super":
2275
+ cur, rest = here, path
2276
+ while rest and rest[0] == "super":
2277
+ cur, rest = cur[:-1], rest[1:]
2278
+ return self._canon(root, cur, rest, depth)
2279
+ if head in self.crate_names:
2280
+ return self._canon(self.crate_names[head], (), path[1:], depth)
2281
+ used = self.uses.get(rel, {}).get(head)
2282
+ if used is not None and used[0] != head:
2283
+ return self._module_files(rel, used + path[1:], depth + 1)
2284
+ if (root, here + (head,)) in self.mods:
2285
+ return self._canon(root, here, path, depth)
2286
+ for g in self.globs.get(rel, ()): # `use super::*` brings the parent's imports and modules in
2287
+ where = self._module_files(rel, g, depth + 1) if g and g[0] in ("super", "crate", "self") else None
2288
+ if where is None:
2289
+ continue
2290
+ f = self.mods.get(where)
2291
+ if f is None or f == rel:
2292
+ continue
2293
+ used = self.uses.get(f, {}).get(head)
2294
+ if used is not None and used[0] != head:
2295
+ return self._module_files(f, used + path[1:], depth + 1)
2296
+ if (where[0], where[1] + (head,)) in self.mods:
2297
+ return self._canon(where[0], where[1], path, depth)
2298
+ if self.globs.get(f): # the parent itself has `use super::*`
2299
+ got = self._module_files(f, path, depth + 2)
2300
+ if got is not None:
2301
+ return got
2302
+ if (root, (head,)) in self.mods:
2303
+ return self._canon(root, (), path, depth)
2304
+ return None
2305
+
2306
+ def _canon(self, root: str, base: tuple[str, ...], rest: list[str], depth: int = 0) -> tuple[str, tuple[str, ...]] | None:
2307
+ """Walk module segments from `base`, following `pub use other_crate::module` re-exports."""
2308
+ cur = base
2309
+ for i, seg in enumerate(rest):
2310
+ if (root, cur + (seg,)) in self.mods:
2311
+ cur = cur + (seg,)
2312
+ continue
2313
+ f = self.mods.get((root, cur))
2314
+ used = self.uses.get(f, {}).get(seg) if f is not None else None
2315
+ if used is not None and depth < 6 and used != [seg]:
2316
+ return self._module_files(f, used + list(rest[i + 1:]), depth + 1)
2317
+ if f is not None and seg in self.inline_mods.get(f, ()):
2318
+ continue # `mod seg { pub use ...; }` in this file: its items are indexed with the file
2319
+ return root, cur + tuple(rest[i:]) # a path we cannot see
2320
+ return root, cur
2321
+
2322
+ def _free_in(self, root: str, modpath: tuple[str, ...], name: str, depth: int = 0) -> list[Fn]:
2323
+ f = self.mods.get((root, modpath))
2324
+ if f is None and modpath: # an inline module of the parent file
2325
+ f = self.mods.get((root, modpath[:-1]))
2326
+ if f is not None:
2327
+ hit = self.free[f].get(name)
2328
+ if hit:
2329
+ return [c for c in hit if not c.test] or hit
2330
+ if depth < 5:
2331
+ used = self.uses.get(f, {}).get(name) # `pub use child::name`
2332
+ if used is not None and len(used) > 1:
2333
+ where = self._module_files(f, used[:-1])
2334
+ if where is not None and where != (root, modpath):
2335
+ got = self._free_in(where[0], where[1], used[-1], depth + 1)
2336
+ if got:
2337
+ return got
2338
+ for g in self.globs.get(f, ()): # `pub use child::*`
2339
+ where = self._module_files(f, g)
2340
+ if where is not None and where != (root, modpath):
2341
+ got = self._free_in(where[0], where[1], name, depth + 1)
2342
+ if got:
2343
+ return got
2344
+ # declared by a macro or re-exported in a way we did not follow: unique under that module
2345
+ cands = [c for c in self.by_name.get(name, ()) if not c.container and not c.test
2346
+ and self.crate_of[c.file][0] == root and self.crate_of[c.file][1][:len(modpath)] == modpath]
2347
+ return cands if len(cands) == 1 else []
2348
+
2349
+ def _typed(self, fn: Fn, typ: str, name: str) -> list[Fn]:
2350
+ cands = self.by_type.get((typ, name))
2351
+ if not cands:
2352
+ return []
2353
+ if not fn.test:
2354
+ cands = [c for c in cands if not c.test] or cands
2355
+ same = [c for c in cands if c.file == fn.file]
2356
+ if same:
2357
+ return same[:3]
2358
+ root = self.crate_of[fn.file][0]
2359
+ near = [c for c in cands if self.crate_of[c.file][0] == root]
2360
+ if near:
2361
+ return near if len(near) <= 4 else []
2362
+ return cands if len(cands) <= 3 else []
2363
+
2364
+ def resolve(self, fn, call):
2365
+ kind, name, qual, _line, nargs = call
2366
+ rel = fn.file
2367
+ if kind == "G": # the trait methods of the type a generic handler was made for
2368
+ wanted = self.fn_bounds.get(qual) or ()
2369
+ found = [m for trait, m in self.trait_impls.get(name, ()) if trait in wanted]
2370
+ if not fn.test:
2371
+ found = [m for m in found if not m.test] or found
2372
+ return found
2373
+ if qual == "":
2374
+ f = fn
2375
+ while f is not None:
2376
+ g = self.lex_child(rel, f, name, containers=True)
2377
+ if g is not None:
2378
+ return [g]
2379
+ f = f.lex
2380
+ local = self.free[rel].get(name)
2381
+ if local:
2382
+ if len(local) > 1 and not fn.test:
2383
+ local = [c for c in local if not c.test] or local
2384
+ return local[:2]
2385
+ used = self.uses.get(rel, {}).get(name)
2386
+ if used is not None:
2387
+ where = self._module_files(rel, used[:-1])
2388
+ if where is None:
2389
+ return []
2390
+ return self._free_in(where[0], where[1], used[-1])
2391
+ for g in self.globs.get(rel, ()):
2392
+ where = self._module_files(rel, g)
2393
+ if where is not None:
2394
+ hit = self._free_in(where[0], where[1], name)
2395
+ if hit:
2396
+ return hit
2397
+ if kind == "r" or name in self.ix.ambiguous:
2398
+ return []
2399
+ root = self.crate_of[rel][0]
2400
+ cands = [c for c in self.by_name.get(name, ()) if not c.container and (fn.test or not c.test)
2401
+ and self.crate_of[c.file][0] == root and (c.nparams == nargs or nargs < 0)]
2402
+ return cands if len(cands) == 1 else []
2403
+ if qual == ".self":
2404
+ if fn.container:
2405
+ hit = self._typed(fn, fn.container, name)
2406
+ if hit:
2407
+ return hit
2408
+ return self.by_unique_name(fn, name, nargs, methods=True, same_file_max=1, scope=self._same_crate(rel))
2409
+ if qual.startswith("."):
2410
+ typ = self._chain_type(fn, qual[1:]) if len(qual) > 1 else None
2411
+ if typ:
2412
+ if typ not in self.known_types:
2413
+ return [] # a library type (`Pool`, `Client`): not ours, whatever the method is called
2414
+ hit = self._typed(fn, typ, name)
2415
+ if hit:
2416
+ return hit
2417
+ return self.by_unique_name(fn, name, nargs, methods=True, same_file_max=2, scope=self._same_crate(rel))
2418
+ segs = [s for s in qual.split("::") if s]
2419
+ last = _strip_generics(segs[-1]) if segs else ""
2420
+ if last == "Self":
2421
+ return self._typed(fn, fn.container, name) if fn.container else []
2422
+ if last[:1].isupper():
2423
+ return self._typed(fn, last, name)
2424
+ where = self._module_files(rel, segs)
2425
+ if where is None:
2426
+ return []
2427
+ return self._free_in(where[0], where[1], name)
2428
+
2429
+ def _chain_type(self, fn: Fn, chain: str, depth: int = 0) -> str | None:
2430
+ """Type name of a receiver chain (`self.f:repo.m:pool`), or None when it cannot be told."""
2431
+ if depth > 4:
2432
+ return None
2433
+ steps = chain.split(".")
2434
+ head = steps[0]
2435
+ typ: str | None
2436
+ if head == "self":
2437
+ typ = fn.container or None
2438
+ elif head.startswith("v:"):
2439
+ scope, got = fn, None
2440
+ while scope is not None and got is None:
2441
+ if scope.extra is not None:
2442
+ got = scope.extra["vars"].get(head[2:])
2443
+ scope = scope.lex
2444
+ if got is None:
2445
+ return None
2446
+ typ = got[1] if got[0] == "t" else self._chain_type(fn, got[1], depth + 1)
2447
+ elif head.startswith("c:"):
2448
+ path = head[2:].split("::")
2449
+ targets = self.resolve(fn, ("c", path[-1], "::".join(path[:-1]), 0, -1))
2450
+ typ = self._ret(targets)
2451
+ else:
2452
+ return None
2453
+ for step in steps[1:]:
2454
+ if not typ:
2455
+ return None
2456
+ if step.startswith("f:"):
2457
+ types = self.fields.get((typ, step[2:]))
2458
+ typ = next(iter(types)) if types and len(types) == 1 else None
2459
+ elif step.startswith("m:"):
2460
+ targets = self.by_type.get((typ, step[2:]), [])
2461
+ got = self._ret(targets)
2462
+ typ = typ if got == "Self" else got
2463
+ else:
2464
+ return None
2465
+ return typ or None
2466
+
2467
+ @staticmethod
2468
+ def _ret(targets: list[Fn]) -> str | None:
2469
+ rets = {(t.container if t.extra["ret"] == "Self" else t.extra["ret"]) for t in targets if t.extra}
2470
+ return next(iter(rets)) if len(rets) == 1 else None
2471
+
2472
+ def _same_crate(self, rel: str):
2473
+ root = self.crate_of[rel][0]
2474
+ return lambda c: self.crate_of[c.file][0] == root
2475
+
2476
+
2477
+ # --------------------------------------------------------------------------- Go
2478
+
2479
+ def _go_sig(params: Node | None, result: Node | None) -> str:
2480
+ """A method's signature without names: parameter types, then result types, package qualifiers dropped
2481
+ (`(Context,int)->(*User,error)`). Enough to tell apart two methods that share a name and an arity."""
2482
+ def types(node: Node | None) -> list[str]:
2483
+ if node is None:
2484
+ return []
2485
+ if node.type != "parameter_list":
2486
+ return [_sig_type(_t(node))]
2487
+ out: list[str] = []
2488
+ for p in node.named_children:
2489
+ if p.type not in ("parameter_declaration", "variadic_parameter_declaration"):
2490
+ continue
2491
+ typ = p.child_by_field_name("type")
2492
+ names = [c for c in p.named_children if c.type == "identifier"]
2493
+ text = ("..." if p.type.startswith("variadic") else "") + _sig_type(_t(typ) if typ is not None else _t(p))
2494
+ out.extend([text] * max(1, len(names)))
2495
+ return out
2496
+ return "(" + ",".join(types(params)) + ")->(" + ",".join(types(result)) + ")"
2497
+
2498
+
2499
+ _GO_BUILTIN = re.compile(r"^(?:\.\.\.|\*|\[\])*(?:string|bool|error|any|byte|rune|u?int(?:8|16|32|64)?|uintptr|float(?:32|64))$")
2500
+
2501
+
2502
+ def _sig_fits(want: str, got: str | None) -> bool:
2503
+ """Can a method with signature `got` be the interface method `want`? The counts of parameters and results
2504
+ must agree, and a built-in type must face that same type. Two different named types may still be
2505
+ the same type (`type Resp = api.UserResponse`), so names alone never exclude."""
2506
+ if got is None or got == want:
2507
+ return True
2508
+ wp, _, wr = want.partition("->")
2509
+ gp, _, gr = got.partition("->")
2510
+ for w, g in ((wp, gp), (wr, gr)):
2511
+ ws, gs = _split_types(w), _split_types(g)
2512
+ if len(ws) != len(gs):
2513
+ return False
2514
+ for x, y in zip(ws, gs):
2515
+ if x != y and (_GO_BUILTIN.match(x) or _GO_BUILTIN.match(y)):
2516
+ return False
2517
+ return True
2518
+
2519
+
2520
+ def _split_types(text: str) -> list[str]:
2521
+ text = text.strip()[1:-1]
2522
+ out, depth, cur = [], 0, ""
2523
+ for ch in text:
2524
+ if ch in "([{":
2525
+ depth += 1
2526
+ elif ch in ")]}":
2527
+ depth -= 1
2528
+ if ch == "," and depth == 0:
2529
+ out.append(cur)
2530
+ cur = ""
2531
+ else:
2532
+ cur += ch
2533
+ return out + [cur] if cur else out
2534
+
2535
+
2536
+ def _sig_type(text: str) -> str:
2537
+ text = re.sub(r"\s+", "", text).replace("interface{}", "any")
2538
+ return re.sub(r"\b[A-Za-z_]\w*\.(?=[A-Za-z_])", "", text)
2539
+
2540
+
2541
+ def _go_type(text: str) -> str:
2542
+ """`*store.Store`, `[]Store`, `Store[T]` -> `store.Store` / `Store`."""
2543
+ text = text.strip()
2544
+ while text[:1] in "*&" or text.startswith("[]"):
2545
+ text = text[2:] if text.startswith("[]") else text[1:]
2546
+ text = text.strip()
2547
+ i = text.find("[")
2548
+ if i > 0:
2549
+ text = text[:i]
2550
+ return text if re.fullmatch(r"[\w.]+", text) else ""
2551
+
2552
+
2553
+ # generated and hand-written test doubles: never the implementation a production call reaches
2554
+ _GO_MOCK_PATH = re.compile(r"(^|/)(\w*mocks?|\w*fakes?|mock_\w+|fake_\w+)/|(^|/)(mock_[^/]*|[^/]*_mocks?|mocks?|[^/]*_fakes?|fakes?)\.go$")
2555
+ _GO_MOCK_TYPE = re.compile(r"^(Mock|mock|Fake|fake)(?![a-z])|Mock$|Fake$")
2556
+
2557
+
2558
+ class Go(Lang):
2559
+ name = "go"
2560
+
2561
+ FN_RE = re.compile(rb"(?m)^func\s+(?:\([^)]*\)\s*)?(\w+)")
2562
+
2563
+ def __init__(self, index, rules):
2564
+ super().__init__(index, rules)
2565
+ import tree_sitter_go
2566
+ self.language = Language(tree_sitter_go.language())
2567
+ self.parser = Parser(self.language)
2568
+ self.q = Query(self.language, """
2569
+ (function_declaration) @func
2570
+ (method_declaration) @func
2571
+ (call_expression) @call
2572
+ (import_spec) @imp
2573
+ (type_spec) @type
2574
+ (go_statement) @go
2575
+ (short_var_declaration) @svd
2576
+ (var_spec) @var
2577
+ (argument_list (identifier) @ref)
2578
+ (argument_list (selector_expression) @ref)
2579
+ (keyed_element (literal_element (identifier) @ref))
2580
+ (keyed_element (literal_element (selector_expression) @ref))
2581
+ (literal_value (literal_element (identifier) @ref))
2582
+ (literal_value (literal_element (selector_expression) @ref))
2583
+ """)
2584
+ self.call_rules = self._compile("call")
2585
+ named = [r["match"] for r in rules.get("call", []) if r["match"]]
2586
+ self.call_pre = re.compile("|".join(f"(?:{r})" for r in named) or r"\b\B")
2587
+ self.generic_rules = [(rx, r) for rx, r in self.call_rules if not r["match"]]
2588
+ self.group_names = set(rules.get("router", {}).get("group", []))
2589
+ self.combo_names = set(rules.get("router", {}).get("combo", []))
2590
+ self.test_fn = re.compile(rules.get("tests", {}).get("function", "^Test"))
2591
+ self.modules: list[tuple[str, str]] = [] # (module path, dir)
2592
+ self.imports: dict[str, dict[str, str]] = {} # file -> alias -> package dir
2593
+ self.ext_alias: dict[str, set[str]] = defaultdict(set) # file -> aliases of packages outside the repo
2594
+ self.funcs: dict[str, dict[str, list[Fn]]] = defaultdict(lambda: defaultdict(list)) # dir -> name -> funcs
2595
+ self.methods: dict[tuple[str, str], dict[str, list[Fn]]] = defaultdict(lambda: defaultdict(list)) # (dir, type)
2596
+ self.structs: dict[tuple[str, str], dict[str, str]] = {} # (dir, type) -> field -> type text
2597
+ self.embeds: dict[tuple[str, str], list[str]] = defaultdict(list)
2598
+ self.ifaces: dict[tuple[str, str], set[str]] = {} # (dir, interface) -> method names
2599
+ self.returns: dict[int, str] = {} # fn id -> first result type
2600
+ self.pkg_name: dict[str, str] = {}
2601
+ self.pkg_vars: dict[tuple[str, str], str] = {} # (dir, package-level var) -> type text
2602
+ self.dir_alias: dict[tuple[str, str], str] = {} # (dir, import alias) -> package dir, first file wins
2603
+ self.test_support: set[str] = set() # files that import "testing"
2604
+ self.iface_embeds: dict[tuple[str, str], list[str]] = defaultdict(list) # (dir, interface) -> embedded type texts
2605
+ self.params: dict[int, frozenset[str]] = {} # fn id -> its parameter and receiver names
2606
+ self._iface_sets: dict[tuple[str, str], frozenset[str]] = {}
2607
+ self._name_sets: dict[tuple[str, str], frozenset[str] | None] = {}
2608
+ self._embedded_in: dict[tuple[str, str], list[tuple[str, str]]] | None = None
2609
+ self._dispatch_memo: dict[tuple, list[Fn]] = {}
2610
+ self.iface_sigs: dict[tuple, str] = {} # ((package dir, interface), method) -> signature
2611
+ self.sigs: dict[int, str] = {} # method id -> signature
2612
+ self.dir_types: dict[str, list[tuple[str, str]]] = defaultdict(list) # dir -> (dir, type) keys of `methods`
2613
+ self._imported_dirs: dict[str, set[str]] = {} # file -> dirs it imports, plus its own
2614
+
2615
+ def prescan(self, rel, src):
2616
+ for m in self.FN_RE.finditer(src):
2617
+ self.fn_names.add(m.group(1).decode())
2618
+ d = os.path.dirname(rel)
2619
+ if d not in self.pkg_name:
2620
+ m = re.search(rb"(?m)^package\s+(\w+)", src)
2621
+ if m:
2622
+ self.pkg_name[d] = m.group(1).decode().removesuffix("_test")
2623
+ if not self.modules:
2624
+ for dirpath in {""} | {"/".join(p.split("/")[:i]) for p in self.ix.files_seen if p.endswith(".go")
2625
+ for i in range(1, min(4, p.count("/") + 1))}:
2626
+ try:
2627
+ text = (self.ix.root / dirpath / "go.mod").read_text(errors="replace")
2628
+ except OSError:
2629
+ continue
2630
+ m = re.search(r"(?m)^module\s+(\S+)", text)
2631
+ if m:
2632
+ self.modules.append((m.group(1), dirpath))
2633
+ self.modules.sort(key=lambda t: -len(t[0]))
2634
+ if not self.modules:
2635
+ self.modules.append(("\0", ""))
2636
+
2637
+ def _import_dir(self, path: str) -> str | None:
2638
+ for mod, d in self.modules:
2639
+ if path == mod:
2640
+ return d
2641
+ if path.startswith(mod + "/"):
2642
+ return (d + "/" if d else "") + path[len(mod) + 1:]
2643
+ return None
2644
+
2645
+ def parse(self, rel, src):
2646
+ tree = self.parser.parse(src)
2647
+ if TREE_HOOK is not None:
2648
+ TREE_HOOK(self.name, self.language, rel, src, tree)
2649
+ caps = QueryCursor(self.q).captures(tree.root_node)
2650
+ d = os.path.dirname(rel)
2651
+ is_test = rel.endswith("_test.go") or is_test_path(rel)
2652
+ imports = self.imports.setdefault(rel, {})
2653
+ for node in caps.get("imp", []):
2654
+ path = _t(node.child_by_field_name("path")).strip('"`')
2655
+ if path == "testing":
2656
+ self.test_support.add(rel) # a helper for tests outside a _test.go file: it wires up no real entry point
2657
+ alias_node = node.child_by_field_name("name")
2658
+ target = self._import_dir(path)
2659
+ alias = _t(alias_node) if alias_node is not None else ""
2660
+ if target is None:
2661
+ self.ext_alias[rel].add(alias or re.sub(r"^(go-|golang-)|(-go|\.go)$", "", path.rstrip("/").split("/")[-1] if not re.fullmatch(r"v\d+", path.split("/")[-1]) else path.split("/")[-2]))
2662
+ continue
2663
+ if alias in ("_", "."):
2664
+ continue
2665
+ imports[alias or self.pkg_name.get(target) or path.split("/")[-1]] = target
2666
+ if not alias:
2667
+ imports.setdefault(path.split("/")[-1], target)
2668
+ for alias, target in imports.items():
2669
+ self.dir_alias.setdefault((d, alias), target)
2670
+ for node in caps.get("type", []):
2671
+ name = _t(node.child_by_field_name("name"))
2672
+ typ = node.child_by_field_name("type")
2673
+ if typ is None:
2674
+ continue
2675
+ if typ.type == "interface_type":
2676
+ self.ifaces.setdefault((d, name), set()).update(re.findall(r"(?m)^\s*([A-Za-z_]\w*)\s*\(", _t(typ)))
2677
+ for el in typ.named_children:
2678
+ if el.type in ("method_elem", "method_spec"):
2679
+ mname = _t(el.child_by_field_name("name"))
2680
+ if mname:
2681
+ self.iface_sigs[((d, name), mname)] = _go_sig(el.child_by_field_name("parameters"),
2682
+ el.child_by_field_name("result"))
2683
+ for el in typ.named_children: # `interface { querier; io.Closer; Ping() }`: the embedded ones
2684
+ if el.type in ("type_elem", "constraint_elem", "type_identifier", "qualified_type", "interface_type_name"):
2685
+ emb = _go_type(_t(el))
2686
+ if emb:
2687
+ self.iface_embeds[(d, name)].append(emb)
2688
+ elif typ.type == "struct_type":
2689
+ fields: dict[str, str] = {}
2690
+ for fl in typ.named_children:
2691
+ if fl.type != "field_declaration_list":
2692
+ continue
2693
+ for fd in fl.named_children:
2694
+ if fd.type != "field_declaration":
2695
+ continue
2696
+ ft = fd.child_by_field_name("type")
2697
+ names = [c for c in fd.named_children if c.type == "field_identifier"]
2698
+ ttext = _go_type(_t(ft)) if ft is not None else ""
2699
+ if not names and ttext:
2700
+ self.embeds[(d, name)].append(ttext)
2701
+ fields.setdefault(ttext.split(".")[-1], ttext)
2702
+ for n in names:
2703
+ fields[_t(n)] = ttext
2704
+ self.structs.setdefault((d, name), {}).update(fields)
2705
+ for node in caps.get("var", []):
2706
+ if node.parent is not None and node.parent.parent is not None and node.parent.parent.type == "source_file" or \
2707
+ (node.parent is not None and node.parent.type == "var_spec_list"):
2708
+ typ = node.child_by_field_name("type")
2709
+ if typ is not None:
2710
+ for n in node.named_children:
2711
+ if n.type == "identifier":
2712
+ self.pkg_vars[(d, _t(n))] = _go_type(_t(typ))
2713
+ for node in sorted(caps.get("func", []), key=lambda n: n.start_byte):
2714
+ name = _t(node.child_by_field_name("name"))
2715
+ recv = node.child_by_field_name("receiver")
2716
+ container, symbol, vars_ = "", name, {}
2717
+ if recv is not None:
2718
+ for p in recv.named_children:
2719
+ typ = p.child_by_field_name("type")
2720
+ if typ is None:
2721
+ continue
2722
+ raw = _t(typ)
2723
+ container = _go_type(raw)
2724
+ symbol = f"(*{container}).{name}" if raw.strip().startswith("*") else f"{container}.{name}"
2725
+ rn = p.child_by_field_name("name")
2726
+ if rn is not None:
2727
+ vars_[_t(rn)] = container
2728
+ nparams = 0
2729
+ params = node.child_by_field_name("parameters")
2730
+ variadic = False
2731
+ if params is not None:
2732
+ for p in params.named_children:
2733
+ if p.type == "variadic_parameter_declaration":
2734
+ variadic = True
2735
+ continue
2736
+ if p.type != "parameter_declaration":
2737
+ continue
2738
+ typ = p.child_by_field_name("type")
2739
+ names = [c for c in p.named_children if c.type == "identifier"]
2740
+ nparams += max(1, len(names))
2741
+ ttext = _go_type(_t(typ)) if typ is not None else ""
2742
+ for n in names:
2743
+ vars_[_t(n)] = ttext if typ is not None and typ.type != "function_type" else "func"
2744
+ fn_test = is_test
2745
+ fn = self.add_fn(Fn(rel, "go", name, symbol, container, node, method=bool(container),
2746
+ nparams=-1 if variadic else nparams, test=fn_test))
2747
+ fn.extra = vars_
2748
+ self.params[fn.id] = frozenset(vars_)
2749
+ res = node.child_by_field_name("result")
2750
+ if container:
2751
+ self.sigs[fn.id] = _go_sig(params, res)
2752
+ if res is not None:
2753
+ rt = res
2754
+ if res.type == "parameter_list" and res.named_children:
2755
+ first = res.named_children[0]
2756
+ rt = first.child_by_field_name("type") or first
2757
+ self.returns[fn.id] = _go_type(_t(rt))
2758
+ if container:
2759
+ if (d, container) not in self.methods:
2760
+ self.dir_types[d].append((d, container))
2761
+ self.methods[(d, container)][name].append(fn)
2762
+ else:
2763
+ self.funcs[d][name].append(fn)
2764
+ line = node.start_point[0] + 1
2765
+ if not container:
2766
+ if is_test and rel.endswith("_test.go") and self.test_fn.search(name):
2767
+ self.ix.entries.append(Entry("test", f"{rel}::{name}", rel, line, targets=[fn]))
2768
+ elif name == "main" and self.pkg_name.get(d) == "main" and not is_test:
2769
+ self.ix.entries.append(Entry("main", f"main {d or rel}", rel, line, targets=[fn]))
2770
+ calls = caps.get("call", [])
2771
+ regs = []
2772
+ for node in calls:
2773
+ f = node.child_by_field_name("function")
2774
+ if f is None:
2775
+ continue
2776
+ text = _t(f) if f.end_byte - f.start_byte < 120 else ""
2777
+ if text and (self.call_pre.search(text) or text.rpartition(".")[2] in self.group_names):
2778
+ regs.append((node, text, True))
2779
+ elif self.combo_names and self._combo(f) is not None: # `m.Combo("/x").Get(a).<newline>Post(b)`
2780
+ regs.append((node, "combo", True))
2781
+ elif self.generic_rules:
2782
+ args = node.child_by_field_name("arguments")
2783
+ if args is not None and args.named_child_count >= 2:
2784
+ a0 = args.named_children[0]
2785
+ if a0.type in ("interpreted_string_literal", "binary_expression") and a0.text[:1] == b'"' and \
2786
+ a0.text[1:8].split(b" ")[0] in (b"GET", b"POST", b"PUT", b"PATCH", b"DELETE", b"HEAD", b"OPTIONS"):
2787
+ regs.append((node, text, False))
2788
+ self.link(rel, src)
2789
+ pend = []
2790
+ for node, text, named in regs:
2791
+ pend.append(self._registration(rel, node, text, named))
2792
+ for node in caps.get("go", []):
2793
+ call = node.named_children[0] if node.named_children else None
2794
+ if call is not None and call.type == "call_expression":
2795
+ pend.append(self._go_stmt(rel, call))
2796
+ if any(pend):
2797
+ self.link(rel, src)
2798
+ at = self.ix.at_byte
2799
+ reg_args = {id_ for p in pend if p for id_ in p}
2800
+ for node in caps.get("svd", []) + caps.get("var", []):
2801
+ owner = at(rel, node.start_byte)
2802
+ if owner is None or owner.extra is None and not owner.inline:
2803
+ continue
2804
+ target = owner
2805
+ while target is not None and target.extra is None:
2806
+ target = target.lex
2807
+ if target is None:
2808
+ continue
2809
+ if node.type == "var_spec":
2810
+ typ = node.child_by_field_name("type")
2811
+ if typ is not None:
2812
+ for n in node.named_children:
2813
+ if n.type == "identifier":
2814
+ target.extra.setdefault(_t(n), _go_type(_t(typ)))
2815
+ continue
2816
+ left, right = node.child_by_field_name("left"), node.child_by_field_name("right")
2817
+ if left is None or right is None or not left.named_children or not right.named_children:
2818
+ continue
2819
+ for other in left.named_children[1:]:
2820
+ if other.type == "identifier":
2821
+ target.extra.setdefault(_t(other), "")
2822
+ lhs, rhs = left.named_children[0], right.named_children[0]
2823
+ if lhs.type != "identifier":
2824
+ continue
2825
+ target.extra.setdefault(_t(lhs), "")
2826
+ nm = _t(lhs)
2827
+ if rhs.type == "unary_expression" and rhs.named_children:
2828
+ rhs = rhs.named_children[-1]
2829
+ if rhs.type == "composite_literal":
2830
+ target.extra[nm] = _go_type(_t(rhs.child_by_field_name("type")))
2831
+ elif rhs.type == "call_expression":
2832
+ cf = rhs.child_by_field_name("function")
2833
+ # a builder chain: `handlers.NewUserHandler(db).WithLogger(log)`: the constructor, then each method
2834
+ inner, methods = rhs, []
2835
+ while inner.type == "call_expression":
2836
+ f = inner.child_by_field_name("function")
2837
+ op = f.child_by_field_name("operand") if f is not None and f.type == "selector_expression" else None
2838
+ if op is None or op.type != "call_expression":
2839
+ break
2840
+ methods.append(_t(f.child_by_field_name("field")))
2841
+ inner = op
2842
+ icf = inner.child_by_field_name("function") if methods else None
2843
+ if icf is not None and icf.end_byte - icf.start_byte < 80:
2844
+ target.extra[nm] = "chain:" + _t(icf) + "|" + ",".join(reversed(methods))
2845
+ elif cf is not None and cf.end_byte - cf.start_byte < 80:
2846
+ target.extra[nm] = "call:" + _t(cf)
2847
+ elif rhs.type == "func_literal":
2848
+ target.extra[nm] = "func"
2849
+ elif rhs.type == "selector_expression" and rhs.end_byte - rhs.start_byte < 80:
2850
+ target.extra[nm] = "sel:" + _t(rhs)
2851
+ names = self.fn_names
2852
+ for node in caps.get("ref", []):
2853
+ if node.id in reg_args:
2854
+ continue
2855
+ if node.type == "identifier":
2856
+ name = _t(node)
2857
+ if name not in names:
2858
+ continue
2859
+ # the field name in `T{New: value}` is not a reference to a function called New
2860
+ holder = node.parent
2861
+ if holder is not None and holder.type == "literal_element" and holder.parent is not None \
2862
+ and holder.parent.type == "keyed_element":
2863
+ key = holder.parent.child_by_field_name("key")
2864
+ if key is not None and key.id == holder.id:
2865
+ continue
2866
+ qual = ""
2867
+ else:
2868
+ name = _t(node.child_by_field_name("field"))
2869
+ if name not in names:
2870
+ continue
2871
+ op = node.child_by_field_name("operand")
2872
+ if op is None or op.end_byte - op.start_byte > 80:
2873
+ continue
2874
+ qual = _t(op)
2875
+ owner = at(rel, node.start_byte)
2876
+ if owner is not None:
2877
+ owner.calls.append(("r", name, qual, node.start_point[0] + 1, -1))
2878
+ for node in calls:
2879
+ f = node.child_by_field_name("function")
2880
+ if f is None:
2881
+ continue
2882
+ ft = f.type
2883
+ if ft == "identifier":
2884
+ name, qual = _t(f), ""
2885
+ elif ft == "selector_expression":
2886
+ name = _t(f.child_by_field_name("field"))
2887
+ op = f.child_by_field_name("operand")
2888
+ if op is None:
2889
+ continue
2890
+ while op.type in ("parenthesized_expression", "unary_expression") and op.named_children:
2891
+ op = op.named_children[-1] # (&T{...}).run()
2892
+ if op.type in ("identifier", "selector_expression") and op.end_byte - op.start_byte < 80:
2893
+ qual = _t(op)
2894
+ elif op.type == "call_expression":
2895
+ cf = op.child_by_field_name("function")
2896
+ qual = "call:" + _t(cf) if cf is not None and cf.end_byte - cf.start_byte < 80 else "?"
2897
+ elif op.type == "composite_literal":
2898
+ qual = "lit:" + _go_type(_t(op.child_by_field_name("type")))
2899
+ else:
2900
+ qual = "?"
2901
+ else:
2902
+ continue
2903
+ if name not in names:
2904
+ continue
2905
+ owner = at(rel, node.start_byte)
2906
+ if owner is None:
2907
+ continue
2908
+ args = node.child_by_field_name("arguments")
2909
+ owner.calls.append(("c", name, qual, node.start_point[0] + 1, args.named_child_count if args is not None else -1))
2910
+
2911
+ def _handler(self, rel: str, node: Node, owner: Fn | None, refs: list, targets: list, seen: set) -> None:
2912
+ line = node.start_point[0] + 1
2913
+ t = node.type
2914
+ seen.add(node.id)
2915
+ if t == "identifier":
2916
+ refs.append(("r", _t(node), "", line, -1))
2917
+ elif t == "selector_expression":
2918
+ op = node.child_by_field_name("operand")
2919
+ if op is not None and op.end_byte - op.start_byte < 80:
2920
+ refs.append(("r", _t(node.child_by_field_name("field")), _t(op), line, -1))
2921
+ elif t == "func_literal":
2922
+ targets.append(self.add_fn(Fn(rel, "go", "<func>", owner.symbol if owner else "", owner.container if owner else "",
2923
+ node, inline=True, test=owner.test if owner else False)))
2924
+ elif t == "call_expression":
2925
+ f = node.child_by_field_name("function")
2926
+ if f is not None:
2927
+ self._handler(rel, f, owner, refs, targets, seen)
2928
+ args = node.child_by_field_name("arguments")
2929
+ if args is not None:
2930
+ for a in args.named_children:
2931
+ if a.type in ("identifier", "selector_expression", "func_literal", "call_expression", "unary_expression"):
2932
+ self._handler(rel, a, owner, refs, targets, seen)
2933
+ elif t == "unary_expression" and node.named_children: # &Activities{...}
2934
+ self._handler(rel, node.named_children[-1], owner, refs, targets, seen)
2935
+ elif t == "composite_literal":
2936
+ typ = node.child_by_field_name("type")
2937
+ if typ is not None:
2938
+ refs.append(("s", _go_type(_t(typ)), "", line, -1))
2939
+ elif t == "parenthesized_expression" and node.named_children:
2940
+ self._handler(rel, node.named_children[0], owner, refs, targets, seen)
2941
+
2942
+ def _params(self, owner: Fn | None) -> frozenset[str]:
2943
+ """Parameter names of the function around a registration: `baseURL` there is not a constant elsewhere."""
2944
+ while owner is not None and owner.extra is None:
2945
+ owner = owner.lex
2946
+ return self.params.get(owner.id, frozenset()) if owner is not None else frozenset()
2947
+
2948
+ def _prefix(self, rel: str, node: Node, recv: str, owner: Fn | None) -> str:
2949
+ """Path prefix from enclosing `r.Route("/p", func(...){})` blocks and `g := r.Group("/p")` variables."""
2950
+ prefix = ""
2951
+ unknown = self._params(owner)
2952
+ p = node.parent
2953
+ while p is not None and p.type not in ("function_declaration", "method_declaration"):
2954
+ if p.type == "func_literal":
2955
+ call = p.parent.parent if p.parent is not None else None
2956
+ if call is not None and call.type == "call_expression":
2957
+ f = call.child_by_field_name("function")
2958
+ if f is not None and f.type == "selector_expression" and _t(f.child_by_field_name("field")) in self.group_names:
2959
+ args = call.child_by_field_name("arguments")
2960
+ if args is not None and args.named_children and args.named_children[0] is not p:
2961
+ prefix = _join_path(self.ix.consts.eval("go", rel, _t(args.named_children[0]), unknown=unknown)[0], prefix)
2962
+ p = p.parent
2963
+ scope = owner
2964
+ while scope is not None and scope.extra is None:
2965
+ scope = scope.lex
2966
+ seen = 0
2967
+ while scope is not None and recv and seen < 4:
2968
+ src = (scope.extra or {}).get("grp:" + recv)
2969
+ if src is None:
2970
+ break
2971
+ prefix = _join_path(src[1], prefix)
2972
+ recv = src[0]
2973
+ seen += 1
2974
+ return prefix
2975
+
2976
+ _VERBS = {"Get", "Post", "Put", "Delete", "Patch", "Head", "Options", "Any"}
2977
+
2978
+ def _combo(self, f: Node | None) -> Node | None:
2979
+ """The `m.Combo("/path")` call a verb is chained on: `m.Combo("/x").Get(list).Post(create)` (macaron,
2980
+ Gitea's router, flamego). The path is the Combo's argument; each verb call names handlers only."""
2981
+ if f is None or f.type != "selector_expression" or _t(f.child_by_field_name("field")) not in self._VERBS:
2982
+ return None
2983
+ op = f.child_by_field_name("operand")
2984
+ while op is not None and op.type == "call_expression":
2985
+ cf = op.child_by_field_name("function")
2986
+ if cf is None or cf.type != "selector_expression":
2987
+ return None
2988
+ if _t(cf.child_by_field_name("field")) in self.combo_names:
2989
+ return op
2990
+ op = cf.child_by_field_name("operand")
2991
+ return None
2992
+
2993
+ def _combo_route(self, rel: str, node: Node, f: Node, combo: Node, pos: list[Node], owner: Fn | None):
2994
+ cargs = combo.child_by_field_name("arguments")
2995
+ first = [a for a in cargs.named_children if a.type != "comment"][:1] if cargs is not None else []
2996
+ path = self.ix.consts.eval("go", rel, _t(first[0]), unknown=self._params(owner))[0] if first else ""
2997
+ refs, targets, seen = [], [], set()
2998
+ for h in pos:
2999
+ self._handler(rel, h, owner, refs, targets, seen)
3000
+ if not refs and not targets:
3001
+ return None
3002
+ verb = _t(f.child_by_field_name("field"))
3003
+ method = "" if verb == "Any" else verb.upper()
3004
+ recv = _t(combo.child_by_field_name("function").child_by_field_name("operand"))
3005
+ name = _http_name(method, _join_path(self._prefix(rel, node, recv, owner), path))
3006
+ line = f.child_by_field_name("field").start_point[0] + 1
3007
+ self.ix.entries.append(Entry("http", name, rel, line, targets=targets, pending=[(owner, r) for r in refs] if owner else [],
3008
+ decl=owner, path=path, method=method))
3009
+ return seen
3010
+
3011
+ def _registration(self, rel: str, node: Node, text: str, named: bool):
3012
+ owner = self.ix.at_byte(rel, node.start_byte)
3013
+ args = node.child_by_field_name("arguments")
3014
+ if args is None or rel in self.test_support:
3015
+ return None
3016
+ pos = [a for a in args.named_children if a.type != "comment"]
3017
+ f = node.child_by_field_name("function")
3018
+ if self.combo_names:
3019
+ combo = self._combo(f)
3020
+ if combo is not None:
3021
+ return self._combo_route(rel, node, f, combo, pos, owner)
3022
+ field = f.child_by_field_name("field") if f is not None and f.type == "selector_expression" else None
3023
+ line = (field or node).start_point[0] + 1
3024
+ recv = _t(f.child_by_field_name("operand")) if f is not None and f.type == "selector_expression" else ""
3025
+ # `g := r.Group("/api")`: remember the prefix on the variable
3026
+ if f is not None and f.type == "selector_expression" and _t(f.child_by_field_name("field")) in self.group_names:
3027
+ p = node.parent
3028
+ while p is not None and p.type in ("expression_list", "call_expression", "selector_expression"):
3029
+ p = p.parent
3030
+ if p is not None and p.type in ("short_var_declaration", "assignment_statement") and pos:
3031
+ left = p.child_by_field_name("left")
3032
+ scope = owner
3033
+ while scope is not None and scope.extra is None:
3034
+ scope = scope.lex
3035
+ if left is not None and left.named_children and scope is not None:
3036
+ scope.extra["grp:" + _t(left.named_children[0])] = (
3037
+ recv, self.ix.consts.eval("go", rel, _t(pos[0]), unknown=self._params(owner))[0])
3038
+ chain = ""
3039
+ if node.parent is not None and node.parent.type == "selector_expression" and node.parent.parent is not None:
3040
+ chain = _t(node.parent.parent)[-200:]
3041
+ for rx, rule in (self.call_rules if named else self.generic_rules):
3042
+ if named and not rule["match"]:
3043
+ continue
3044
+ m = rx.search(text)
3045
+ if not m:
3046
+ continue
3047
+ hit = apply_rule(self, rel, rule, m, pos, {}, chain_text=chain or _t(node)[:300], unknown=self._params(owner))
3048
+ if hit is None or not hit.handlers:
3049
+ continue
3050
+ refs, targets, seen = [], [], set()
3051
+ each = "method" if rule.get("each_method") else ""
3052
+ for h in hit.handlers:
3053
+ if not each:
3054
+ self._handler(rel, h, owner, refs, targets, seen)
3055
+ if rule.get("structs"):
3056
+ # the value registered: a variable, a field (`s.handler`), `&T{}` or what a constructor returns
3057
+ while h.type in ("unary_expression", "parenthesized_expression") and h.named_children:
3058
+ h = h.named_children[-1]
3059
+ if h.type in ("identifier", "selector_expression") and h.end_byte - h.start_byte < 80:
3060
+ refs.append(("t", _t(h), "", line, -1))
3061
+ elif h.type == "call_expression" and each:
3062
+ cf = h.child_by_field_name("function")
3063
+ if cf is not None and cf.end_byte - cf.start_byte < 80:
3064
+ refs.append(("T", _t(cf), "", line, -1))
3065
+ elif h.type == "composite_literal" and each:
3066
+ refs.append(("s", _go_type(_t(h.child_by_field_name("type"))), "", line, -1))
3067
+ if not refs and not targets:
3068
+ continue
3069
+ name = hit.name
3070
+ only = None
3071
+ if each:
3072
+ # `pb.RegisterFooServer(srv, impl)`: the methods of the generated `FooServer` interface, when it is in the repo
3073
+ service = m.group(1) if m.lastindex else ""
3074
+ name = f"{hit.method or 'ANY'} {service}".strip()
3075
+ pkg = self.imports.get(rel, {}).get(text.rpartition(".")[0]) if "." in text else _dirname(rel)
3076
+ if pkg is not None:
3077
+ only = (lambda key=(pkg, f"{service}{rule.get('each_interface', '')}"):
3078
+ self._iface_methods(key) if key in self.ifaces else None)
3079
+ elif hit.kind == "http":
3080
+ name = _http_name(hit.method, hit.path or "")
3081
+ pre = self._prefix(rel, node, recv, owner)
3082
+ if pre and hit.path == "":
3083
+ name = _http_name(hit.method, pre) # `orgs.GET("", h)`: the group's own route
3084
+ elif pre:
3085
+ verb, _, path = name.partition(" ")
3086
+ name = f"{verb} {_join_path(pre, path)}"
3087
+ opt = rule.get("name_option")
3088
+ if opt:
3089
+ mm = re.search(r"\b" + opt + r"\s*:\s*([^,}\n]+)", _t(node))
3090
+ if mm:
3091
+ value, ok = self.ix.consts.eval("go", rel, mm.group(1))
3092
+ if ok and value and "…" not in value:
3093
+ name = value
3094
+ e = Entry(hit.kind, name, rel, line, targets=targets, pending=[(owner, r) for r in refs] if owner else [],
3095
+ decl=owner, path=hit.path, method=hit.method, loop_only=bool(rule.get("loop_only")),
3096
+ structs=bool(rule.get("structs")))
3097
+ e.each, e.only = each, only
3098
+ self.ix.entries.append(e)
3099
+ return seen
3100
+ return None
3101
+
3102
+ def _go_stmt(self, rel: str, call: Node):
3103
+ rules = [(rx, r) for rx, r in self.call_rules if r["match"] and rx.fullmatch("go")]
3104
+ if not rules:
3105
+ return None
3106
+ rule = rules[0][1]
3107
+ owner = self.ix.at_byte(rel, call.start_byte)
3108
+ f = call.child_by_field_name("function")
3109
+ if f is None or owner is None:
3110
+ return None
3111
+ line = call.start_point[0] + 1
3112
+ if f.type == "func_literal":
3113
+ if self.loop_re is not None and self.loop_re.search(f.text):
3114
+ fn = self.add_fn(Fn(rel, "go", "<go func>", owner.symbol, owner.container, f, inline=True, test=owner.test))
3115
+ e = Entry(rule["kind"], f"{owner.symbol} (goroutine)", rel, line, targets=[fn])
3116
+ e.tag = "loop"
3117
+ self.ix.entries.append(e)
3118
+ return {f.id}
3119
+ return None
3120
+ refs, targets, seen = [], [], set()
3121
+ self._handler(rel, f, owner, refs, targets, seen)
3122
+ if refs:
3123
+ self.ix.entries.append(Entry(rule["kind"], refs[0][1], rel, line, pending=[(owner, r) for r in refs], decl=owner,
3124
+ loop_only=True))
3125
+ return None
3126
+
3127
+ # -- resolution -----------------------------------------------------------
3128
+ def _type_of(self, fn: Fn, expr: str, depth: int = 0) -> tuple[str, str] | None | bool:
3129
+ """(package dir, type name) of an expression; False = a type outside the repo; None = unknown."""
3130
+ if depth > 5:
3131
+ return None
3132
+ d = _dirname(fn.file)
3133
+ scope = fn
3134
+ while scope is not None and scope.extra is None:
3135
+ scope = scope.lex
3136
+ vars_ = scope.extra if scope is not None else {}
3137
+ if "." not in expr:
3138
+ t = vars_.get(expr)
3139
+ if t is None:
3140
+ t = self.pkg_vars.get((d, expr))
3141
+ if t is None:
3142
+ return None
3143
+ if t.startswith("call:"):
3144
+ return self._type_of_value(fn, t, vars_, depth)
3145
+ if t.startswith("chain:"):
3146
+ # what the constructor returns, then what each chained method returns on it (a builder returns its own type)
3147
+ head, _, meths = t[6:].partition("|")
3148
+ typ = self._type_of_value(fn, "call:" + head, vars_, depth)
3149
+ for m in [x for x in meths.split(",") if x]:
3150
+ if not typ:
3151
+ return typ
3152
+ rts = {(c.file, self.returns.get(c.id, "")) for c in self._methods_of(typ, m)}
3153
+ if len(rts) != 1:
3154
+ return None
3155
+ rf, rt = next(iter(rts))
3156
+ typ = self._named(_dirname(rf), rf, rt) if rt else None
3157
+ return typ
3158
+ if t.startswith("sel:"):
3159
+ return self._type_of(fn, t[4:], depth + 1)
3160
+ if t in ("func", ""):
3161
+ return None
3162
+ return self._named(d, fn.file, t)
3163
+ head, _, field = expr.rpartition(".")
3164
+ if head in self.imports.get(fn.file, {}) and head not in vars_:
3165
+ return None
3166
+ base = self._type_of(fn, head, depth + 1)
3167
+ if not base:
3168
+ return base
3169
+ ft = self._field(base, field)
3170
+ if ft is None:
3171
+ return None
3172
+ owner_file = next((f.file for ms in self.methods.get(base, {}).values() for f in ms), None)
3173
+ return self._named(base[0], owner_file or fn.file, ft, strict_dir=base[0])
3174
+
3175
+ def _type_of_value(self, fn: Fn, t: str, vars_: dict, depth: int):
3176
+ """The type a `call:f` value has: what the one function it can call returns."""
3177
+ head = t[5:].split(".")[0]
3178
+ if "." in t[5:] and head in self.ext_alias.get(fn.file, ()) and head not in vars_:
3179
+ return False # `workflow.NewSelector(ctx)`: whatever a library returns is a library type
3180
+ targets = self.resolve(fn, ("c", t[5:].split(".")[-1], ".".join(t[5:].split(".")[:-1]), 0, -1), depth + 1)
3181
+ rts = {(_dirname(c.file), self.returns.get(c.id, "")) for c in targets}
3182
+ if len(rts) != 1:
3183
+ return None
3184
+ rd, rt = next(iter(rts))
3185
+ return self._named(rd, targets[0].file, rt) if rt else None
3186
+
3187
+ def _field(self, typ: tuple[str, str], field: str, depth: int = 0) -> str | None:
3188
+ fields = self.structs.get(typ)
3189
+ if fields is None:
3190
+ return None
3191
+ if field in fields:
3192
+ return fields[field]
3193
+ if depth < 2:
3194
+ for emb in self.embeds.get(typ, ()):
3195
+ if "." not in emb:
3196
+ got = self._field((typ[0], emb), field, depth + 1)
3197
+ if got is not None:
3198
+ return got
3199
+ return None
3200
+
3201
+ def _named(self, d: str, file: str, text: str, strict_dir: str | None = None):
3202
+ if not text:
3203
+ return None
3204
+ if "." in text:
3205
+ alias, _, name = text.partition(".")
3206
+ target = self.imports.get(file, {}).get(alias)
3207
+ if target is None:
3208
+ # the type was declared in another file of package `d`: look the alias up there
3209
+ target = self.dir_alias.get((d, alias))
3210
+ if target is None:
3211
+ return False
3212
+ return (target, name)
3213
+ if text in ("string", "int", "int64", "bool", "error", "any", "byte", "float64", "uint64", "int32", "uint32"):
3214
+ return False
3215
+ return (strict_dir if strict_dir is not None else d, text)
3216
+
3217
+ def _methods_of(self, typ: tuple[str, str], name: str, depth: int = 0) -> list[Fn]:
3218
+ hit = self.methods.get(typ, {}).get(name)
3219
+ if hit:
3220
+ return hit
3221
+ if depth < 3:
3222
+ for emb in self.embeds.get(typ, ()):
3223
+ sub = (typ[0], emb) if "." not in emb else None
3224
+ if sub is None:
3225
+ alias, _, tname = emb.partition(".")
3226
+ target = self.dir_alias.get((typ[0], alias))
3227
+ if target is not None:
3228
+ sub = (target, tname)
3229
+ if sub is not None:
3230
+ got = self._methods_of(sub, name, depth + 1)
3231
+ if got:
3232
+ return got
3233
+ return []
3234
+
3235
+ def resolve(self, fn, call, depth: int = 0):
3236
+ kind, name, qual, _line, nargs = call
3237
+ rel = fn.file
3238
+ d = _dirname(rel)
3239
+ if kind == "s": # a struct value registered as a whole: its exported methods
3240
+ typ = self._named(d, rel, name)
3241
+ return self._exported(fn, typ) if typ else []
3242
+ if kind == "t": # a variable or field holding such a struct
3243
+ typ = self._type_of(fn, name)
3244
+ return self._exported(fn, typ) if typ else []
3245
+ if kind == "T": # what a constructor call returns: `NewServer(db)`
3246
+ made = self.resolve(fn, ("c", name.split(".")[-1], ".".join(name.split(".")[:-1]), 0, -1), depth + 1) if depth < 3 else []
3247
+ rts = {(c.file, self.returns.get(c.id, "")) for c in made}
3248
+ if len(rts) != 1:
3249
+ return []
3250
+ rf, rt = next(iter(rts))
3251
+ typ = self._named(_dirname(rf), rf, rt) if rt else None
3252
+ return self._exported(fn, typ) if typ else []
3253
+ scope = fn
3254
+ while scope is not None and scope.extra is None:
3255
+ scope = scope.lex
3256
+ vars_ = scope.extra if scope is not None else {}
3257
+ if not qual:
3258
+ if name in vars_:
3259
+ return []
3260
+ cands = self.funcs[d].get(name, [])
3261
+ if len(cands) > 1 and not fn.test:
3262
+ cands = [c for c in cands if not c.test] or cands
3263
+ return cands[:2]
3264
+ if qual == "?":
3265
+ return self._fuzzy(fn, name, nargs) if kind == "c" else []
3266
+ if qual.startswith("lit:"):
3267
+ typ = self._named(d, rel, qual[4:])
3268
+ return self._on_type(fn, typ, name, nargs, kind) if typ else []
3269
+ if qual.startswith("call:"):
3270
+ inner = qual[5:]
3271
+ targets = self.resolve(fn, ("c", inner.split(".")[-1], ".".join(inner.split(".")[:-1]), 0, -1), depth + 1) if depth < 3 else []
3272
+ rts = {(c.file, self.returns.get(c.id, "")) for c in targets}
3273
+ if len(rts) == 1:
3274
+ rf, rt = next(iter(rts))
3275
+ typ = self._named(_dirname(rf), rf, rt) if rt else None
3276
+ if typ:
3277
+ return self._on_type(fn, typ, name, nargs, kind)
3278
+ if typ is False:
3279
+ return []
3280
+ return self._fuzzy(fn, name, nargs) if kind == "c" else []
3281
+ head = qual.split(".")[0]
3282
+ if "." not in qual and qual not in vars_:
3283
+ target = self.imports.get(rel, {}).get(qual)
3284
+ if target is not None:
3285
+ cands = self.funcs[target].get(name, [])
3286
+ return [c for c in cands if not c.test][:2] or cands[:1]
3287
+ if qual in self.ext_alias.get(rel, ()):
3288
+ return []
3289
+ # a type name: `Store.Method` (method expression) or package-level variable
3290
+ if (d, qual) in self.structs:
3291
+ return self._methods_of((d, qual), name)
3292
+ if head in self.ext_alias.get(rel, ()) and head not in vars_ and head not in self.imports.get(rel, {}):
3293
+ return []
3294
+ typ = self._type_of(fn, qual, depth)
3295
+ if typ is False:
3296
+ return []
3297
+ if typ:
3298
+ return self._on_type(fn, typ, name, nargs, kind)
3299
+ if kind == "r":
3300
+ cands = [c for ms in (self.methods.get(k, {}).get(name, []) for k in self.dir_types.get(d, ())) for c in ms
3301
+ if fn.test or not c.test]
3302
+ return cands if len(cands) == 1 and name not in self.ix.ambiguous else []
3303
+ return self._fuzzy(fn, name, nargs)
3304
+
3305
+ def _on_type(self, fn: Fn, typ: tuple[str, str], name: str, nargs: int, kind: str) -> list[Fn]:
3306
+ hit = self._methods_of(typ, name)
3307
+ if hit:
3308
+ return hit
3309
+ if typ in self.structs:
3310
+ # a method promoted from an embedded interface (`type querier struct{ database.Store }`) is a call
3311
+ # through that interface; anything else is a field holding a func or a method of an external type
3312
+ for emb in self._embeds_of(typ):
3313
+ if emb in self.ifaces and emb not in self.structs and name in self._iface_methods(emb):
3314
+ return self._dispatch(fn, emb, name, nargs)
3315
+ return []
3316
+ if typ in self.ifaces:
3317
+ return self._dispatch(fn, typ, name, nargs)
3318
+ return self._fuzzy(fn, name, nargs) if kind == "c" else []
3319
+
3320
+ # -- interfaces -----------------------------------------------------------
3321
+ def _embed_key(self, d: str, text: str) -> tuple[str, str] | None:
3322
+ """(package dir, type) of an embedded type written in package `d`; None for a type outside the repo."""
3323
+ if "." not in text:
3324
+ return (d, text)
3325
+ alias, _, tname = text.partition(".")
3326
+ target = self.dir_alias.get((d, alias))
3327
+ return (target, tname) if target is not None else None
3328
+
3329
+ def _embeds_of(self, typ: tuple[str, str]) -> list[tuple[str, str]]:
3330
+ return [k for k in (self._embed_key(typ[0], e) for e in self.embeds.get(typ, ())) if k is not None]
3331
+
3332
+ def _iface_methods(self, typ: tuple[str, str], depth: int = 0) -> frozenset[str]:
3333
+ """Method names of an interface, with those of the interfaces it embeds (the ones declared in the repo)."""
3334
+ got = self._iface_sets.get(typ)
3335
+ if got is not None:
3336
+ return got
3337
+ names = set(self.ifaces.get(typ, ()))
3338
+ if depth < 5:
3339
+ for emb in self.iface_embeds.get(typ, ()):
3340
+ key = self._embed_key(typ[0], emb)
3341
+ if key is not None and key != typ and key in self.ifaces:
3342
+ names |= self._iface_methods(key, depth + 1)
3343
+ got = frozenset(names)
3344
+ if depth == 0:
3345
+ self._iface_sets[typ] = got
3346
+ return got
3347
+
3348
+ def _method_names(self, typ: tuple[str, str], depth: int = 0) -> frozenset[str]:
3349
+ """Every method name a struct type answers to: its own and those promoted from the types it embeds."""
3350
+ got = self._name_sets.get(typ)
3351
+ if got is not None:
3352
+ return got
3353
+ names = set(self.methods.get(typ, ()))
3354
+ if depth < 4:
3355
+ for key in self._embeds_of(typ):
3356
+ if key == typ:
3357
+ continue
3358
+ if key in self.ifaces and key not in self.structs:
3359
+ names |= self._iface_methods(key)
3360
+ else:
3361
+ names |= self._method_names(key, depth + 1)
3362
+ got = frozenset(names)
3363
+ if depth == 0:
3364
+ self._name_sets[typ] = got
3365
+ return got
3366
+
3367
+ def _implements(self, typ: tuple[str, str], name: str, wanted: frozenset[str], depth: int = 0) -> bool:
3368
+ """True when `typ`, or a struct that embeds it without redefining `name`, has every method in `wanted`."""
3369
+ if wanted <= self._method_names(typ):
3370
+ return True
3371
+ if depth >= 3:
3372
+ return False
3373
+ if self._embedded_in is None:
3374
+ self._embedded_in = defaultdict(list)
3375
+ for outer in self.embeds:
3376
+ for key in self._embeds_of(outer):
3377
+ self._embedded_in[key].append(outer)
3378
+ for outer in self._embedded_in.get(typ, ()):
3379
+ if name not in self.methods.get(outer, ()) and self._implements(outer, name, wanted, depth + 1):
3380
+ return True
3381
+ return False
3382
+
3383
+ @staticmethod
3384
+ def _is_mock(c: Fn) -> bool:
3385
+ return bool(_GO_MOCK_PATH.search(c.file) or _GO_MOCK_TYPE.search(c.container))
3386
+
3387
+ def _dispatch(self, fn: Fn, typ: tuple[str, str], name: str, nargs: int) -> list[Fn]:
3388
+ """A call through an interface: the method of every type that implements it.
3389
+
3390
+ A type implements the interface when its method set (own methods, and those promoted from embedded
3391
+ types) covers the interface's; a struct that embeds the method's type counts for it. When no type is
3392
+ seen to cover it (part of the method set comes from a library type), the call is followed only if one
3393
+ single type outside tests and mocks has a method of that name and arity. Tests and mocks are left out
3394
+ unless the caller is a test."""
3395
+ wanted = self._iface_methods(typ)
3396
+ if name not in wanted:
3397
+ return []
3398
+ key = (typ, name, nargs, fn.test)
3399
+ out = self._dispatch_memo.get(key)
3400
+ if out is None:
3401
+ sig = self._iface_sig(typ, name)
3402
+ cands = [c for c in self.by_name.get(name, ())
3403
+ if c.method and (fn.test or not (c.test or self._is_mock(c))) and (nargs < 0 or c.nparams < 0 or c.nparams == nargs)
3404
+ # same name and arity is not enough: the parameter and result types must be the interface's
3405
+ and (sig is None or _sig_fits(sig, self.sigs.get(c.id)))]
3406
+ out = [c for c in cands if self._implements((_dirname(c.file), c.container), name, wanted)]
3407
+ if not out and name not in self.ix.ambiguous and len({(_dirname(c.file), c.container) for c in cands}) == 1:
3408
+ out = cands
3409
+ if len(out) > self.ix.settings.max_implementations:
3410
+ out = []
3411
+ self._dispatch_memo[key] = out
3412
+ # An implementation in the caller's own package, when there is exactly one, is the one this caller
3413
+ # was written against (a package-private interface with its local implementation).
3414
+ if len(out) > 1:
3415
+ d = _dirname(fn.file)
3416
+ local = [c for c in out if _dirname(c.file) == d and c.container != fn.container] # not the wrapper calling through itself
3417
+ if len({c.container for c in local}) == 1 and typ[0] == d:
3418
+ self.ix.fanout[(fn.id, name)] = len({(_dirname(c.file), c.container) for c in out})
3419
+ return local
3420
+ return out
3421
+
3422
+ def _iface_sig(self, typ: tuple[str, str], name: str, depth: int = 0) -> str | None:
3423
+ """Signature of an interface method, looked up through the interfaces it embeds."""
3424
+ got = self.iface_sigs.get((typ, name))
3425
+ if got is not None or depth > 4:
3426
+ return got
3427
+ for emb in self.iface_embeds.get(typ, ()):
3428
+ key = self._embed_key(typ[0], emb)
3429
+ if key is not None and key != typ and key in self.ifaces:
3430
+ got = self._iface_sig(key, name, depth + 1)
3431
+ if got is not None:
3432
+ return got
3433
+ return None
3434
+
3435
+ def _exported(self, fn: Fn, typ: tuple[str, str]) -> list[Fn]:
3436
+ """Exported methods of a registered value: of the struct and the structs it embeds, or, for an
3437
+ interface, of the types that implement it (at most three, else none)."""
3438
+ if typ in self.ifaces and typ not in self.structs and typ not in self.methods:
3439
+ wanted = self._iface_methods(typ)
3440
+ if not wanted:
3441
+ return []
3442
+ types: list[tuple[str, str]] = []
3443
+ for c in self.by_name.get(min(wanted), ()):
3444
+ t = (_dirname(c.file), c.container)
3445
+ if c.method and not c.test and not self._is_mock(c) and t not in types and wanted <= self._method_names(t):
3446
+ types.append(t)
3447
+ if not 1 <= len(types) <= 3:
3448
+ return []
3449
+ return [f for t in types for f in self._exported_of(t)]
3450
+ return self._exported_of(typ)
3451
+
3452
+ def _exported_of(self, typ: tuple[str, str], depth: int = 0) -> list[Fn]:
3453
+ out = [f for ms in self.methods.get(typ, {}).values() for f in ms if f.name[:1].isupper() and not f.test]
3454
+ if depth < 3:
3455
+ have = {f.name for f in out}
3456
+ for key in self._embeds_of(typ): # promoted methods, unless the outer type redefines them
3457
+ if key != typ and key in self.methods:
3458
+ for f in self._exported_of(key, depth + 1):
3459
+ if f.name not in have:
3460
+ have.add(f.name)
3461
+ out.append(f)
3462
+ return out
3463
+
3464
+ def _fuzzy(self, fn: Fn, name: str, nargs: int) -> list[Fn]:
3465
+ imported = self._imported_dirs.get(fn.file)
3466
+ if imported is None:
3467
+ imported = self._imported_dirs[fn.file] = set(self.imports.get(fn.file, {}).values()) | {_dirname(fn.file)}
3468
+ return self.by_unique_name(fn, name, nargs, methods=True, same_file_max=2,
3469
+ scope=lambda c: _dirname(c.file) in imported, repo_wide=False)
3470
+
3471
+
3472
+ # --------------------------------------------------------------------------- Java
3473
+
3474
+ def _java_type(text: str) -> str:
3475
+ text = text.strip()
3476
+ i = text.find("<")
3477
+ if i > 0:
3478
+ text = text[:i]
3479
+ return text.replace("[]", "").split(".")[-1].strip()
3480
+
3481
+
3482
+ class Java(Lang):
3483
+ name = "java"
3484
+ CLASS_TYPES = ("class_declaration", "interface_declaration", "enum_declaration", "record_declaration")
3485
+
3486
+ def __init__(self, index, rules):
3487
+ super().__init__(index, rules)
3488
+ import tree_sitter_java
3489
+ self.language = Language(tree_sitter_java.language())
3490
+ self.parser = Parser(self.language)
3491
+ self.q = Query(self.language, """
3492
+ (class_declaration) @class
3493
+ (interface_declaration) @class
3494
+ (enum_declaration) @class
3495
+ (record_declaration) @class
3496
+ (method_declaration) @func
3497
+ (constructor_declaration) @func
3498
+ (method_invocation) @call
3499
+ (method_reference) @mref
3500
+ (object_creation_expression) @new
3501
+ (field_declaration) @field
3502
+ (local_variable_declaration) @local
3503
+ (formal_parameter) @param
3504
+ (resource) @res
3505
+ """)
3506
+ self.ann_rules = self._compile("annotation")
3507
+ self.iface_rules = self._compile("interface")
3508
+ self.prefix_anns = set(rules.get("prefix_annotations", []))
3509
+ self.classes: dict[str, list[dict]] = defaultdict(list) # simple name -> class infos
3510
+ self.subs: dict[str, set[str]] = defaultdict(set) # type -> direct subtypes
3511
+ self.class_methods: dict[tuple[str, str], list[Fn]] = defaultdict(list) # (class, method) -> fns
3512
+ self.abstract: set[int] = set() # methods declared without a body (interface, abstract class)
3513
+
3514
+ def prescan(self, rel, src):
3515
+ pass
3516
+
3517
+ @staticmethod
3518
+ def _annotations(node: Node) -> list[tuple[str, Node | None]]:
3519
+ out = []
3520
+ for c in node.children:
3521
+ if c.type == "modifiers":
3522
+ for a in c.named_children:
3523
+ if a.type in ("marker_annotation", "annotation"):
3524
+ out.append((_t(a.child_by_field_name("name")).split(".")[-1], a.child_by_field_name("arguments")))
3525
+ return out
3526
+
3527
+ def _ann_value(self, rel: str, args: Node | None, keys: tuple[str, ...]) -> str | None:
3528
+ if args is None:
3529
+ return None
3530
+ for c in args.named_children:
3531
+ if c.type == "element_value_pair":
3532
+ if _t(c.child_by_field_name("key")) in keys:
3533
+ return self._first_string(rel, c.child_by_field_name("value"))
3534
+ else:
3535
+ return self._first_string(rel, c)
3536
+ return None
3537
+
3538
+ def _first_string(self, rel: str, node: Node | None) -> str | None:
3539
+ if node is None:
3540
+ return None
3541
+ if node.type == "element_value_array_initializer":
3542
+ node = node.named_children[0] if node.named_children else None
3543
+ if node is None:
3544
+ return ""
3545
+ return self.ix.consts.eval("java", rel, _t(node))[0]
3546
+
3547
+ def parse(self, rel, src):
3548
+ tree = self.parser.parse(src)
3549
+ if TREE_HOOK is not None:
3550
+ TREE_HOOK(self.name, self.language, rel, src, tree)
3551
+ caps = QueryCursor(self.q).captures(tree.root_node)
3552
+ is_test = is_test_path(rel) or bool(re.search(r"(^|/)src/(test|it|integration-?test)/|(Test|Tests|IT|TestCase)\.java$", rel))
3553
+ infos: dict[int, dict] = {}
3554
+ for node in sorted(caps.get("class", []), key=lambda n: n.start_byte):
3555
+ name = _t(node.child_by_field_name("name"))
3556
+ supers = []
3557
+ for key in ("superclass", "interfaces"):
3558
+ s = node.child_by_field_name(key)
3559
+ if s is not None:
3560
+ supers += [_java_type(x) for x in re.split(r",(?![^<]*>)", re.sub(r"^\s*(extends|implements)\s+", "", _t(s)))]
3561
+ for c in node.children:
3562
+ if c.type == "extends_interfaces":
3563
+ supers += [_java_type(x) for x in re.split(r",(?![^<]*>)", re.sub(r"^\s*extends\s+", "", _t(c)))]
3564
+ anns = self._annotations(node)
3565
+ prefix = ""
3566
+ for an, args in anns:
3567
+ if an in self.prefix_anns:
3568
+ prefix = self._ann_value(rel, args, ("value", "path")) or ""
3569
+ outer, p = None, node.parent
3570
+ while p is not None and outer is None:
3571
+ if p.type in self.CLASS_TYPES:
3572
+ outer = infos.get(p.id)
3573
+ p = p.parent
3574
+ info = {"name": name, "file": rel, "supers": [s for s in supers if s], "fields": {}, "prefix": prefix,
3575
+ "anns": [a for a, _ in anns], "outer": outer}
3576
+ infos[node.id] = info
3577
+ self.classes[name].append(info)
3578
+ for s in info["supers"]:
3579
+ self.subs[s].add(name)
3580
+
3581
+ def owner_class(node: Node) -> dict | None:
3582
+ p = node.parent
3583
+ while p is not None:
3584
+ if p.type in self.CLASS_TYPES:
3585
+ return infos.get(p.id)
3586
+ p = p.parent
3587
+ return None
3588
+
3589
+ for node in caps.get("field", []):
3590
+ info = owner_class(node)
3591
+ typ = node.child_by_field_name("type")
3592
+ if info is None or typ is None:
3593
+ continue
3594
+ for c in node.named_children:
3595
+ if c.type == "variable_declarator":
3596
+ info["fields"][_t(c.child_by_field_name("name"))] = _java_type(_t(typ))
3597
+ for node in sorted(caps.get("func", []), key=lambda n: n.start_byte):
3598
+ if node.child_by_field_name("body") is None:
3599
+ # declared, not defined: `@Query("select ...") List<X> find(...)` in a repository or DAO interface.
3600
+ # It is a function so that the query on it has callers; it never defines an entry point, and it
3601
+ # is found by name alone only when it carries an annotation (its implementation is generated).
3602
+ info = owner_class(node)
3603
+ if info is None:
3604
+ continue
3605
+ name = _t(node.child_by_field_name("name"))
3606
+ params = node.child_by_field_name("parameters")
3607
+ nparams = params.named_child_count if params is not None else 0
3608
+ if params is not None and any(c.type == "spread_parameter" for c in params.named_children):
3609
+ nparams = -1
3610
+ fn = Fn(rel, "java", name, f"{info['name']}.{name}", info["name"], node, method=True, nparams=nparams, test=is_test)
3611
+ self.ix.add_fn(fn)
3612
+ fn.extra = {"vars": {}, "class": info}
3613
+ self.abstract.add(fn.id)
3614
+ self.class_methods[(info["name"], name)].append(fn)
3615
+ if any(a != "Override" for a, _ in self._annotations(node)):
3616
+ self.by_name[name].append(fn)
3617
+ continue
3618
+ info = owner_class(node)
3619
+ name = _t(node.child_by_field_name("name"))
3620
+ cname = info["name"] if info else ""
3621
+ params = node.child_by_field_name("parameters")
3622
+ nparams = params.named_child_count if params is not None else 0
3623
+ if params is not None and any(c.type == "spread_parameter" for c in params.named_children):
3624
+ nparams = -1
3625
+ names, p = [name], node.parent
3626
+ while p is not None:
3627
+ if p.type in self.CLASS_TYPES or p.type in ("method_declaration", "constructor_declaration"):
3628
+ names.append(_t(p.child_by_field_name("name")))
3629
+ p = p.parent
3630
+ fn = self.add_fn(Fn(rel, "java", name, ".".join(reversed(names)), cname, node, method=True, nparams=nparams,
3631
+ test=is_test))
3632
+ fn.extra = {"vars": {}, "class": info}
3633
+ self.class_methods[(cname, name)].append(fn)
3634
+ line = node.start_point[0] + 1
3635
+ anns = self._annotations(node)
3636
+ ann_names = {a for a, _ in anns}
3637
+ matched = False
3638
+ for an, args in anns:
3639
+ for rx, rule in self.ann_rules:
3640
+ m = rx.search(an)
3641
+ if not m:
3642
+ continue
3643
+ kind = rule["kind"]
3644
+ if kind == "http":
3645
+ path = self._ann_value(rel, args, ("value", "path"))
3646
+ if rule.get("path_annotation"):
3647
+ path = next((self._ann_value(rel, a2, ("value",)) for n2, a2 in anns if n2 == rule["path_annotation"]), "")
3648
+ spec = rule.get("method", "")
3649
+ method = m.group(1).upper() if spec == "$1" else ""
3650
+ if spec.startswith("kw:") and args is not None:
3651
+ for c in args.named_children:
3652
+ if c.type == "element_value_pair" and _t(c.child_by_field_name("key")) == spec[3:]:
3653
+ method = "|".join(dict.fromkeys(_VERB_WORD.findall(_t(c.child_by_field_name("value")))))
3654
+ full = _join_path(info["prefix"] if info else "", path or "") or "/"
3655
+ if not full.startswith(("/", "…")):
3656
+ full = "/" + full
3657
+ self.ix.entries.append(Entry("http", _http_name(method, full), rel, line, targets=[fn], path=full, method=method))
3658
+ elif kind == "test":
3659
+ fn.test = True
3660
+ self.ix.entries.append(Entry("test", f"{rel}::{fn.symbol}", rel, line, targets=[fn]))
3661
+ else:
3662
+ label = None
3663
+ if rule.get("name_kwargs"):
3664
+ label = self._ann_value(rel, args, tuple(rule["name_kwargs"]))
3665
+ if kind == "main":
3666
+ ename = f"startup: {fn.symbol}"
3667
+ else:
3668
+ ename = f"{fn.symbol} ({label})" if label else fn.symbol
3669
+ self.ix.entries.append(Entry(kind, ename, rel, line, targets=[fn]))
3670
+ matched = True
3671
+ break
3672
+ if matched:
3673
+ break
3674
+ if not matched and info is not None:
3675
+ for rx, rule in self.iface_rules:
3676
+ vm = re.search(rule["via"], name) if any(rx.search(s) for s in info["supers"]) else None
3677
+ if vm is None or (rule.get("override") and "Override" not in ann_names):
3678
+ continue
3679
+ if node.type != "method_declaration":
3680
+ continue
3681
+ kind = rule["kind"]
3682
+ if kind == "http": # `doGet` of a servlet, an RPC method of a gRPC service base
3683
+ spec = rule.get("method", "")
3684
+ method = (vm.group(1).upper() if vm.lastindex else "") if spec == "$1" else spec
3685
+ ename = f"{method or 'ANY'} {cname}.{name}" if not rule.get("service") else \
3686
+ f"{method or 'ANY'} {next((s for s in info['supers'] if rx.search(s)), cname).removesuffix(rule['service'])}/{name}"
3687
+ else:
3688
+ ename = f"startup: {fn.symbol}" if kind == "main" else fn.symbol
3689
+ self.ix.entries.append(Entry(kind, ename, rel, line, targets=[fn]))
3690
+ matched = True
3691
+ break
3692
+ if not matched and name == "main" and nparams == 1 and b"static" in src[node.start_byte:node.start_byte + 200] \
3693
+ and "String" in _t(params):
3694
+ self.ix.entries.append(Entry("test" if is_test else "main", f"main {cname}", rel, line, targets=[fn]))
3695
+ self.link(rel, src)
3696
+ at = self.ix.at_byte
3697
+ for cap in ("param", "local"):
3698
+ for node in caps.get(cap, []):
3699
+ owner = at(rel, node.start_byte)
3700
+ typ = node.child_by_field_name("type")
3701
+ if owner is None or typ is None or owner.extra is None:
3702
+ continue
3703
+ t = _java_type(_t(typ))
3704
+ if cap == "param":
3705
+ owner.extra["vars"][_t(node.child_by_field_name("name"))] = t
3706
+ else:
3707
+ for c in node.named_children:
3708
+ if c.type == "variable_declarator":
3709
+ owner.extra["vars"][_t(c.child_by_field_name("name"))] = \
3710
+ self._made_type(c.child_by_field_name("value")) or t if t == "var" else t
3711
+ for node in caps.get("res", []): # try (var qm = new QueryManager()) { ... }
3712
+ owner = at(rel, node.start_byte)
3713
+ typ, nm = node.child_by_field_name("type"), node.child_by_field_name("name")
3714
+ if owner is None or typ is None or nm is None or owner.extra is None:
3715
+ continue
3716
+ t = _java_type(_t(typ))
3717
+ owner.extra["vars"][_t(nm)] = self._made_type(node.child_by_field_name("value")) or t if t == "var" else t
3718
+ for node in caps.get("call", []):
3719
+ owner = at(rel, node.start_byte)
3720
+ if owner is None:
3721
+ continue
3722
+ obj = node.child_by_field_name("object")
3723
+ name = _t(node.child_by_field_name("name"))
3724
+ if obj is None:
3725
+ qual = ""
3726
+ elif obj.type in ("identifier", "this", "super"):
3727
+ qual = _t(obj)
3728
+ elif obj.type == "field_access" and _t(obj.child_by_field_name("object")) == "this":
3729
+ qual = _t(obj.child_by_field_name("field"))
3730
+ else:
3731
+ made = self._made_type(obj) # `handle.attach(FooDao.class).find()`, `new Foo().run()`
3732
+ qual = "#" + made if made else "?"
3733
+ args = node.child_by_field_name("arguments")
3734
+ owner.calls.append(("c", name, qual, node.start_point[0] + 1, args.named_child_count if args is not None else -1))
3735
+ for node in caps.get("mref", []):
3736
+ owner = at(rel, node.start_byte)
3737
+ kids = node.named_children
3738
+ if owner is None or len(kids) < 2 or kids[-1].type != "identifier":
3739
+ continue
3740
+ obj = kids[0]
3741
+ qual = _t(obj) if obj.type in ("identifier", "this", "super") else "?"
3742
+ owner.calls.append(("c", _t(kids[-1]), qual, node.start_point[0] + 1, -1))
3743
+ for node in caps.get("new", []):
3744
+ owner = at(rel, node.start_byte)
3745
+ typ = node.child_by_field_name("type")
3746
+ if owner is None or typ is None:
3747
+ continue
3748
+ args = node.child_by_field_name("arguments")
3749
+ owner.calls.append(("n", _java_type(_t(typ)), "", node.start_point[0] + 1, args.named_child_count if args is not None else -1))
3750
+
3751
+ @staticmethod
3752
+ def _made_type(value: Node | None) -> str:
3753
+ """Type of `new Foo(...)`, or of a call whose only argument is `Foo.class` (`handle.attach(FooDao.class)`,
3754
+ `ctx.getBean(Foo.class)`): what such a generic factory returns. "" when it cannot be told."""
3755
+ if value is None:
3756
+ return ""
3757
+ if value.type == "object_creation_expression":
3758
+ return _java_type(_t(value.child_by_field_name("type")))
3759
+ if value.type == "method_invocation":
3760
+ args = value.child_by_field_name("arguments")
3761
+ if args is not None and args.named_child_count == 1 and args.named_children[0].type == "class_literal":
3762
+ lit = args.named_children[0]
3763
+ return _java_type(_t(lit.named_children[0])) if lit.named_children else ""
3764
+ return ""
3765
+
3766
+ # -- resolution -----------------------------------------------------------
3767
+ def _family(self, cls: str, *, up: bool = True, down: bool = True) -> list[str]:
3768
+ """The class, its ancestors and its descendants. Never siblings: an inherited call cannot land in a sister class."""
3769
+ order, seen = [cls], {cls}
3770
+ for go_up in ([True] if up else []) + ([False] if down else []):
3771
+ todo = deque([(cls, 0)])
3772
+ while todo:
3773
+ c, depth = todo.popleft()
3774
+ if depth >= 6:
3775
+ continue
3776
+ if go_up:
3777
+ nxt = [s for info in self.classes.get(c, ()) for s in info["supers"]]
3778
+ else:
3779
+ nxt = sorted(self.subs.get(c, ()))
3780
+ for n in nxt:
3781
+ if n not in seen and n in self.classes:
3782
+ seen.add(n)
3783
+ order.append(n)
3784
+ todo.append((n, depth + 1))
3785
+ return order
3786
+
3787
+ def _in_class(self, cls: str, name: str, nargs: int, *, up: bool = True, down: bool = True) -> list[Fn]:
3788
+ out = []
3789
+ for c in self._family(cls, up=up, down=down):
3790
+ for f in self.class_methods.get((c, name), ()):
3791
+ if nargs < 0 or f.nparams < 0 or f.nparams == nargs:
3792
+ out.append(f)
3793
+ # the limit counts definitions: a declaration without a body is no alternative
3794
+ return out if sum(1 for f in out if f.id not in self.abstract) <= self.ix.settings.max_overrides else []
3795
+
3796
+ def _field_type(self, info: dict | None, var: str) -> str | None:
3797
+ seen = 0
3798
+ todo = [info] if info else []
3799
+ while todo and seen < 12:
3800
+ cur = todo.pop(0)
3801
+ seen += 1
3802
+ t = cur["fields"].get(var)
3803
+ if t is not None:
3804
+ return t
3805
+ for s in cur["supers"]:
3806
+ todo += self.classes.get(s, [])
3807
+ if cur["outer"] is not None: # an inner class reads the fields of the class around it
3808
+ todo.append(cur["outer"])
3809
+ return None
3810
+
3811
+ def resolve(self, fn, call):
3812
+ kind, name, qual, _line, nargs = call
3813
+ info = fn.extra["class"] if fn.extra else None
3814
+ cname = fn.container
3815
+ if kind == "n":
3816
+ if name not in self.classes:
3817
+ return []
3818
+ return [f for f in self.class_methods.get((name, name), ()) if f.nparams < 0 or nargs < 0 or f.nparams == nargs]
3819
+ if qual in ("", "this"):
3820
+ hit = self._in_class(cname, name, nargs)
3821
+ if hit or not info:
3822
+ return hit
3823
+ outer = info["outer"] # an inner class calling a method of the class around it
3824
+ while outer is not None:
3825
+ hit = self._in_class(outer["name"], name, nargs)
3826
+ if hit:
3827
+ return hit
3828
+ outer = outer["outer"]
3829
+ return []
3830
+ if qual == "super":
3831
+ return self._in_class(cname, name, nargs, down=False)[1:] or self._in_class(cname, name, nargs, down=False)
3832
+ if qual == "?":
3833
+ if name in self.ix.ambiguous or re.match(r"^(get|set|is)[A-Z]", name):
3834
+ return []
3835
+ return self.by_unique_name(fn, name, nargs, methods=True, same_file_max=1)
3836
+ if qual.startswith("#"):
3837
+ return self._in_class(qual[1:], name, nargs) if qual[1:] in self.classes else []
3838
+ t = fn.extra["vars"].get(qual) if fn.extra else None
3839
+ if t is None:
3840
+ t = self._field_type(info, qual)
3841
+ if t is None and qual[:1].isupper():
3842
+ t = qual # a static call on a class
3843
+ if t is None or t == "var":
3844
+ if name in self.ix.ambiguous or re.match(r"^(get|set|is)[A-Z]", name):
3845
+ return []
3846
+ return self.by_unique_name(fn, name, nargs, methods=True, same_file_max=1)
3847
+ if t not in self.classes:
3848
+ # a library type; when classes of this repository implement it (an interface from an API jar), the
3849
+ # call lands in those implementations
3850
+ return self._in_class(t, name, nargs, up=False) if t in self.subs else []
3851
+ return self._in_class(t, name, nargs)
3852
+
3853
+
3854
+ LANGS = {"python": Python, "rust": Rust, "go": Go, "java": Java}
3855
+
3856
+
3857
+ # --------------------------------------------------------------------------- roles by path
3858
+
3859
+ class PathRoles:
3860
+ def __init__(self, rules: dict):
3861
+ self.roles = []
3862
+ for role, spec in rules.get("roles", {}).items():
3863
+ self.roles.append((role, set(spec.get("dirs", [])), set(spec.get("tokens", [])),
3864
+ [re.compile(p) for p in spec.get("files", [])]))
3865
+ self._cache: dict[str, str] = {}
3866
+
3867
+ def of_dir(self, d: str) -> str:
3868
+ got = self._cache.get(d)
3869
+ if got is None:
3870
+ got = ""
3871
+ for seg in reversed([s for s in d.split("/") if s]):
3872
+ low = seg.lower()
3873
+ words = set(re.split(r"[-_. ]+", low))
3874
+ for role, dirs, tokens, _ in self.roles:
3875
+ if low in dirs or words & tokens:
3876
+ got = role
3877
+ break
3878
+ if got:
3879
+ break
3880
+ self._cache[d] = got
3881
+ return got
3882
+
3883
+ def of(self, rel: str) -> str:
3884
+ base = os.path.basename(rel)
3885
+ for role, _, _, files in self.roles:
3886
+ if any(p.search(base) for p in files):
3887
+ return role
3888
+ return self.of_dir(os.path.dirname(rel))
3889
+
3890
+
3891
+ # --------------------------------------------------------------------------- areas
3892
+
3893
+ def build_areas(sites: list[dict], roles: PathRoles) -> list[dict]:
3894
+ """Directory groups that hold call sites: top level, split deeper where one directory holds most of them."""
3895
+ total = len(sites)
3896
+ if not total:
3897
+ return []
3898
+
3899
+ def children(path: str, rows: list[dict]) -> dict[str, list[dict]]:
3900
+ """Rows by the next directory below `path`; files directly in `path` stay under `path`."""
3901
+ depth = 0 if path == "" else path.count("/") + 1
3902
+ parts: dict[str, list[dict]] = defaultdict(list)
3903
+ for s in rows:
3904
+ segs = os.path.dirname(s["file"]).split("/") if os.path.dirname(s["file"]) else []
3905
+ parts["/".join(segs[: depth + 1]) if len(segs) > depth else path].append(s)
3906
+ return parts
3907
+
3908
+ def collapse(path: str, rows: list[dict]) -> str:
3909
+ """Follow a chain of single directories (`src/main/java/com/acme`) down to where it branches."""
3910
+ while True:
3911
+ parts = children(path, rows)
3912
+ if len(parts) != 1 or path in parts:
3913
+ return path
3914
+ path = next(iter(parts))
3915
+
3916
+ groups: dict[str, list[dict]] = {}
3917
+ splits: dict[str, int] = {}
3918
+ for child, rows in children("", sites).items():
3919
+ key = collapse(child, rows) if child else "."
3920
+ groups[key], splits[key] = rows, 0
3921
+ final: set[str] = set()
3922
+ while len(groups) < 60:
3923
+ big = [g for g, rows in groups.items() if g != "." and g not in final and splits[g] < 3
3924
+ and len(rows) > max(0.12 * total, 40)]
3925
+ if not big:
3926
+ break
3927
+ g = max(big, key=lambda k: len(groups[k]))
3928
+ parts = children(g, groups[g])
3929
+ if len(parts) < 2 or len(groups) + len(parts) - 1 > 60:
3930
+ final.add(g)
3931
+ continue
3932
+ n = splits.pop(g)
3933
+ del groups[g]
3934
+ for child, rows in parts.items():
3935
+ if child == g: # files directly in the directory that was split
3936
+ groups[g], splits[g] = rows, n
3937
+ final.add(g)
3938
+ else:
3939
+ key = collapse(child, rows)
3940
+ groups[key], splits[key] = rows, n + 1
3941
+ areas = []
3942
+ for path, rows in sorted(groups.items(), key=lambda kv: (-len(kv[1]), kv[0])):
3943
+ live = [r for r in rows if not r["is_test"]] or rows # tests beside the code do not make the area a test area
3944
+ counts = Counter(r["role"] for r in live)
3945
+ by_path = roles.of_dir(path) if path != "." else ""
3946
+ top_role, top_n = counts.most_common(1)[0]
3947
+ if top_n * 2 > len(live):
3948
+ role = top_role
3949
+ basis = "entry_point" if any(r["role_basis"] == "entry_point" for r in live if r["role"] == top_role) else "path"
3950
+ else:
3951
+ role, basis = by_path or "unknown", "path"
3952
+ files = Counter(r["file"] for r in live)
3953
+ areas.append({"path": path, "role": role, "description": "", "basis": basis, "sites": len(rows),
3954
+ "sample_files": [f for f, _ in files.most_common(5)]})
3955
+ return areas
3956
+
3957
+
3958
+ # --------------------------------------------------------------------------- driver
3959
+
3960
+ CONST_DECL = {
3961
+ "python": re.compile(r"^\s*([A-Za-z_]\w*)\s*(?::[^=]+)?=(?!=)"),
3962
+ "rust": re.compile(r"\b(?:const|static)\s+(?:mut\s+)?([A-Za-z_]\w*)\s*:"),
3963
+ "go": re.compile(r"^\s*(?:const\s+|var\s+)?([A-Za-z_]\w*)(?:\s+[\w.\[\]*]+)?\s*:?=(?!=)"),
3964
+ "java": re.compile(r"\b(?:String|StringBuilder|var)\s+([A-Za-z_]\w*)\s*="),
3965
+ }
3966
+
3967
+
3968
+ def _const_names(root: Path, sites: list[dict]) -> dict[tuple[str, str], list[dict]]:
3969
+ """Names of the constants that hold SQL outside any function, so their uses can be found."""
3970
+ wanted: dict[tuple[str, str], list[dict]] = defaultdict(list)
3971
+ by_file: dict[str, list[dict]] = defaultdict(list)
3972
+ for s in sites:
3973
+ if s["kind"] == "sql_string" and s["language"] in CONST_DECL:
3974
+ by_file[s["file"]].append(s)
3975
+ for rel, rows in by_file.items():
3976
+ try:
3977
+ lines = (root / rel).read_text(encoding="utf-8", errors="replace").split("\n")
3978
+ except OSError:
3979
+ continue
3980
+ for s in rows:
3981
+ rx = CONST_DECL[s["language"]]
3982
+ for ln in range(s["line"], max(0, s["line"] - 3), -1):
3983
+ if ln - 1 >= len(lines):
3984
+ continue
3985
+ m = rx.search(lines[ln - 1])
3986
+ if m:
3987
+ if len(m.group(1)) >= 4:
3988
+ s["_const"] = m.group(1)
3989
+ wanted[(s["language"], m.group(1))].append(s)
3990
+ break
3991
+ return wanted
3992
+
3993
+
3994
+ _ASCII_WORD = re.compile(rb"[A-Za-z0-9_]+")
3995
+ _WORDS = re.compile(rb"\w{4,}") # a constant's name has four letters or more (`_const_names`)
3996
+
3997
+
3998
+ # Called with (language name, grammar, file, source, tree) for every file the call graph parses, while it has the
3999
+ # tree: the loop scan reads its part there instead of parsing the file again. Set by `annotate` for one run.
4000
+ TREE_HOOK = None
4001
+
4002
+
4003
+ def _read_source(root: Path, rel: str) -> bytes | None:
4004
+ try:
4005
+ p = root / rel
4006
+ if READ.too_large(p, p.stat().st_size): # the run's file-size setting; the skip is recorded there
4007
+ return None
4008
+ return p.read_bytes()
4009
+ except OSError:
4010
+ return None
4011
+
4012
+
4013
+ def _compact_calls(fns) -> None:
4014
+ """Keep one call per (kind, name, qualifier, arity) in each function and share the name strings.
4015
+ Linking resolves a function's calls by that key, so repeats only cost memory until then."""
4016
+ if KEEP_CALLS:
4017
+ return
4018
+ intern = sys.intern
4019
+ for f in fns:
4020
+ calls = f.calls
4021
+ if not calls:
4022
+ continue
4023
+ seen: dict[tuple, tuple] = {}
4024
+ for c in calls:
4025
+ key = (c[0], c[1], c[2], c[4])
4026
+ if key not in seen:
4027
+ seen[key] = (c[0], intern(c[1]), intern(c[2]), c[3], c[4])
4028
+ f.calls = list(seen.values())
4029
+
4030
+
4031
+ def build(root: Path, by_lang: dict[str, list[str]], rules: dict, wanted: dict | None = None, progress=None,
4032
+ settings: "Settings | dict | None" = None):
4033
+ """Parse every file and link the call graph. Returns (index, languages, entry points, callers by function id)."""
4034
+ ix = Index(root, rules, Settings.of(settings))
4035
+ for files in by_lang.values():
4036
+ ix.files_seen.update(files)
4037
+ wanted = wanted or {}
4038
+ langs: dict[str, Lang] = {}
4039
+ for lang, files in sorted(by_lang.items()):
4040
+ cls = LANGS.get(lang)
4041
+ if cls is None:
4042
+ continue
4043
+ try:
4044
+ handler = cls(ix, rules.get(lang, {}))
4045
+ except Exception: # a grammar that is not installed must not stop discovery
4046
+ ix.errors += 1
4047
+ continue
4048
+ langs[lang] = handler
4049
+ if progress:
4050
+ progress(f"origins: {lang} call graph")
4051
+ names = sorted({n for (lg, n) in wanted if lg == lang})
4052
+ # Uses of the SQL constants. One alternation of every name is slow on a big repository (each position
4053
+ # tries each name), so a file is first cut into words: only the names it really holds are searched.
4054
+ # A name that is not a plain ASCII word keeps the single alternation, whose matches may overlap others.
4055
+ plain = {n.encode() for n in names}
4056
+ if any(len(n) < 4 or not _ASCII_WORD.fullmatch(n) for n in plain):
4057
+ plain = set()
4058
+ const_re = re.compile(rb"\b(" + b"|".join(re.escape(n.encode()) for n in names) + rb")\b") if names and not plain else None
4059
+ sources: dict[str, bytes] = {}
4060
+ for rel in files:
4061
+ src = _read_source(root, rel)
4062
+ if src is None:
4063
+ continue
4064
+ sources[rel] = src
4065
+ try:
4066
+ handler.prescan(rel, src)
4067
+ ix.consts.scan(lang, rel, src)
4068
+ except Exception:
4069
+ if DEBUG:
4070
+ raise
4071
+ ix.errors += 1
4072
+ for rel in list(sources):
4073
+ src = sources.pop(rel) # a parsed file's text is let go: the graph grows as the sources shrink
4074
+ try:
4075
+ handler.parse(rel, src)
4076
+ except Exception:
4077
+ if DEBUG:
4078
+ raise
4079
+ ix.errors += 1
4080
+ continue
4081
+ finally:
4082
+ _compact_calls(ix.by_file.get(rel, ()))
4083
+ if plain:
4084
+ for raw in plain.intersection(_WORDS.findall(src)):
4085
+ name = raw.decode()
4086
+ for pos in _whole_words(src, raw):
4087
+ owner = ix.at_byte(rel, pos)
4088
+ if owner is not None and not owner.module:
4089
+ ix.const_uses[(lang, name)].add(owner.id)
4090
+ elif const_re is not None:
4091
+ for m in const_re.finditer(src):
4092
+ owner = ix.at_byte(rel, m.start())
4093
+ if owner is not None and not owner.module:
4094
+ ix.const_uses[(lang, m.group(1).decode())].add(owner.id)
4095
+ try:
4096
+ handler.finish()
4097
+ except Exception:
4098
+ if DEBUG:
4099
+ raise
4100
+ ix.errors += 1
4101
+
4102
+ if progress:
4103
+ progress(f"origins: linking {len(ix.fns)} functions, {len(ix.entries)} entry points")
4104
+ entries = _resolve_entries(ix, langs)
4105
+ callers = _build_graph(ix, langs, entries)
4106
+ return ix, langs, entries, callers
4107
+
4108
+
4109
+ def annotate(root: Path, by_lang: dict[str, list[str]], sites: list[dict], progress=None, *,
4110
+ settings: "Settings | dict | None" = None, extra: list[dict] | None = None) -> dict:
4111
+ """Add role, role_basis, origins and origin_count to every site. Returns entry_points, areas and counts.
4112
+ `settings`: a `Settings`, or a mapping of some of its fields (the `[discover.origins]` table); None = `SETTINGS`.
4113
+ `extra`: call sites of another kind of finding (kinds/pipeline.trace_proxies): traced the same way (origins, role,
4114
+ loops), never counted in the summary, the areas or an entry point's sites."""
4115
+ extra = list(extra or [])
4116
+ started = time.monotonic()
4117
+ cfg = Settings.of(settings)
4118
+ rules = load_entry_rules()
4119
+ roles = PathRoles(rules)
4120
+ wanted = _const_names(root, sites)
4121
+ from . import loops # loop_context: the loops a site's callers run it in (discover/loops.py)
4122
+ loop_settings = {**vars(cfg), **(settings if isinstance(settings, dict) else {})}
4123
+ global TREE_HOOK
4124
+ prescan = loops.Prescan() if loops.Settings.of(loop_settings).loops else None
4125
+ TREE_HOOK = prescan.add if prescan is not None else None
4126
+ try:
4127
+ ix, langs, entries, callers = build(root, by_lang, rules, wanted, progress, cfg)
4128
+ finally:
4129
+ TREE_HOOK = None
4130
+ lp = loops.Tracker(root, ix, langs, callers, entries, sites, loop_settings, prescan)
4131
+ by_target: dict[int, list[int]] = defaultdict(list)
4132
+ by_view: dict[tuple[str, str], list[int]] = defaultdict(list) # Python view class -> its entry points
4133
+ for i, e in enumerate(entries):
4134
+ for t in e.targets:
4135
+ by_target[t.id].append(i)
4136
+ if e.view is not None and e.kind not in TEST_KINDS:
4137
+ by_view[e.view].append(i)
4138
+
4139
+ cache: dict[int, dict[int, int]] = {}
4140
+ guessed = ix.guessed
4141
+ # entry -> (hops, implementations at the first guessed hop, the method there, guessed hops on the path,
4142
+ # the path) for the origins of the function last asked about that are only reached through a guessed hop
4143
+ via_cache: dict[int, dict[int, tuple]] = {}
4144
+ path_cache: dict[int, dict[int, list[int]]] = {}
4145
+
4146
+ def reach(fid: int) -> dict[int, int]:
4147
+ """Entry points that reach a function, with hops. A walk state is (function, came through a guessed
4148
+ hop): an entry point found without one is certain, and a certain path is preferred to a shorter guess."""
4149
+ got = cache.get(fid)
4150
+ if got is not None:
4151
+ return got
4152
+ start = (fid, 0)
4153
+ seen: dict[tuple[int, int], int] = {start: 0}
4154
+ parent: dict[tuple[int, int], tuple] = {}
4155
+ todo = deque([start])
4156
+ found: dict[int, int] = {}
4157
+ states: dict[int, tuple[int, int]] = {}
4158
+ while todo:
4159
+ state = todo.popleft()
4160
+ f, g = state
4161
+ depth = seen[state]
4162
+ for e in by_target.get(f, ()):
4163
+ if e not in found or (not g and states[e][1]):
4164
+ found[e], states[e] = depth, state
4165
+ if depth >= cfg.max_depth or len(seen) >= cfg.max_nodes:
4166
+ continue
4167
+ for c in callers.get(f, ()):
4168
+ n = guessed.get((f, c), 0)
4169
+ nxt = (c, 1 if (g or n) else 0)
4170
+ if nxt in seen or (nxt[1] and (c, 0) in seen):
4171
+ continue
4172
+ seen[nxt] = depth + 1
4173
+ parent[nxt] = (state, n, f)
4174
+ todo.append(nxt)
4175
+ via: dict[int, tuple] = {}
4176
+ paths: dict[int, list[int]] = {}
4177
+ keep = lp.keep(found, states)
4178
+ for e, state in states.items():
4179
+ if not state[1] and not RECORD_PATHS and e not in keep:
4180
+ continue
4181
+ edges, cur = [], state # (callee, caller, implementations), walked from the entry point down
4182
+ while cur in parent:
4183
+ prev, n, callee = parent[cur]
4184
+ edges.append((callee, cur[0], n))
4185
+ cur = prev
4186
+ edges.reverse() # now from the site up
4187
+ paths[e] = [fid] + [caller for _, caller, _ in edges]
4188
+ guesses = [(n, callee, hop) for hop, (callee, _, n) in enumerate(edges, 1) if n]
4189
+ if state[1] and guesses:
4190
+ via[e] = (guesses[0][0], guesses[0][1], guesses[0][2], len(guesses))
4191
+ lp.walked(fid, seen, parent)
4192
+ cache[fid], via_cache[fid], path_cache[fid] = found, via, paths
4193
+ return found
4194
+
4195
+ entry_sites = Counter()
4196
+ extra_ids = {id(s) for s in extra}
4197
+ for s in sites + extra:
4198
+ s["role"], s["role_basis"], s["origins"], s["origin_count"] = "unknown", "path", [], 0
4199
+ fn = ix.at_line(s["file"], s["line"]) if s["language"] in langs else None
4200
+ found: dict[int, int] = {}
4201
+ const = s.pop("_const", None)
4202
+ in_test_fn = False
4203
+ via: dict[int, tuple] = {}
4204
+ paths: dict[int, list[int]] = {}
4205
+ if fn is not None and not fn.module:
4206
+ found = reach(fn.id)
4207
+ via, paths = via_cache[fn.id], path_cache[fn.id]
4208
+ in_test_fn = fn.test
4209
+ else:
4210
+ users = _const_users(ix, s, const, wanted) if const else []
4211
+ if users:
4212
+ for u in users:
4213
+ for e, hops in reach(u).items():
4214
+ sure, was_sure = e not in via_cache[u], e in found and e not in via
4215
+ if e not in found or (sure and not was_sure) or (sure == was_sure and hops < found[e]):
4216
+ found[e] = hops
4217
+ via.pop(e, None)
4218
+ if not sure:
4219
+ via[e] = via_cache[u][e]
4220
+ if e in path_cache[u]:
4221
+ paths[e] = path_cache[u][e]
4222
+ elif fn is not None: # module-level Python code
4223
+ found = reach(fn.id)
4224
+ via, paths = via_cache[fn.id], path_cache[fn.id]
4225
+ py = langs.get("python")
4226
+ if not found and s["kind"] == "call" and isinstance(py, Python) and s["file"] not in py.imported_files \
4227
+ and not s["is_test"]:
4228
+ found = {-1: 0}
4229
+ if in_test_fn and not s["is_test"]:
4230
+ s["is_test"] = True
4231
+ if by_view and s["language"] == "python" and (fn is None or fn.module) and not s["is_test"]:
4232
+ # a statement written in a class body (`queryset = Site.objects.all()` of a view): the methods the framework
4233
+ # calls on that class, or on a class that inherits the attribute, are what runs it. Said as a guess.
4234
+ cls = langs["python"].class_at(s["file"], s["line"])
4235
+ users = langs["python"].views_using(cls, by_view) if cls is not None else []
4236
+ if users:
4237
+ found = {e: h for e, h in found.items() if e != -1}
4238
+ via = dict(via)
4239
+ for e in users:
4240
+ if e not in found:
4241
+ found[e] = 1
4242
+ via[e] = (0, -1, 1, 1)
4243
+ ranked = []
4244
+ for e, hops in found.items():
4245
+ if e == -1:
4246
+ ranked.append((False, False, 0, KIND_ORDER["cli"], f"python {s['file']}", "cli", s["file"], 1, -1))
4247
+ continue
4248
+ ent = entries[e]
4249
+ ranked.append((ent.kind in TEST_KINDS, e in via, hops, KIND_ORDER.get(ent.kind, 9), ent.name, ent.kind, ent.file, ent.line, e))
4250
+ if id(s) not in extra_ids:
4251
+ entry_sites[e] += 1
4252
+ real = [r for r in ranked if not r[0]]
4253
+ shown = sorted(real) if (real and not s["is_test"]) else sorted(ranked)
4254
+ if not s["is_test"]:
4255
+ s["test_origin_count"] = len(ranked) - len(real)
4256
+ counted = real
4257
+ else:
4258
+ counted = ranked
4259
+ s["origins"] = []
4260
+ for r in shown[:cfg.max_origins]:
4261
+ origin = {"kind": r[5], "name": r[4], "file": r[6], "line": r[7], "hops": r[2]}
4262
+ if r[1]:
4263
+ # reached only through a call that was followed to several implementations: a static guess
4264
+ n, callee, hop, count = via[r[8]]
4265
+ origin["verified"] = False
4266
+ if callee == -1:
4267
+ # kind "framework": no call in the source; the framework reads the class attribute the statement is in
4268
+ origin["via"] = {"kind": "framework", "method": "class attribute read by the view's methods", "implementations": 1,
4269
+ "hop": hop, "guessed_hops": count}
4270
+ s["origins"].append(origin)
4271
+ continue
4272
+ # kind "interface": the call went through an interface or base class with `implementations`
4273
+ # definitions of the method. kind "name": the receiver's type is not known and the method was
4274
+ # matched by name (`implementations` = how many were matched).
4275
+ origin["via"] = {"kind": "interface" if n > 0 else "name", "method": ix.fns[callee].symbol,
4276
+ "implementations": abs(n), "hop": hop, "guessed_hops": count}
4277
+ path = paths.get(r[8]) or ()
4278
+ why = ix.framework_edges.get((callee, path[hop])) if len(path) > hop else None
4279
+ if why: # kind "framework": the framework makes the call (a view's action runs its serializer)
4280
+ origin["via"].update(kind="framework", framework=why)
4281
+ # a kind's call site (extra) keeps its path: the heat of a finding (heat.py) reads the functions between
4282
+ # the site and the entry point, to find a measured statement in a caller up the chain
4283
+ if (RECORD_PATHS or id(s) in extra_ids) and r[8] in paths:
4284
+ origin["path"] = [f"{ix.fns[i].file}:{ix.fns[i].start}-{ix.fns[i].end} {ix.fns[i].symbol}" for i in paths[r[8]]]
4285
+ lp.attach(s, origin, paths.get(r[8]))
4286
+ s["origins"].append(origin)
4287
+ if not real and not s["is_test"]:
4288
+ s["origins"] = []
4289
+ s["origin_count"] = len(counted)
4290
+ lp.site(s, fn, [p[0] for p in paths.values()])
4291
+ if not s["is_test"]:
4292
+ s["origin_count_certain"] = sum(1 for r in real if not r[1])
4293
+ s["_kinds"] = {r[5] for r in real}
4294
+ s["_starts"] = {r[6] for r in real if r[5] in ("main", "cli")}
4295
+
4296
+ _assign_roles(sites + extra, roles)
4297
+ for s in sites + extra:
4298
+ s.pop("_kinds", None)
4299
+ s.pop("_starts", None)
4300
+
4301
+ entry_points = []
4302
+ for i, e in enumerate(entries):
4303
+ n = entry_sites.get(i, 0)
4304
+ if not n and (e.kind in TEST_KINDS or e.loop_only or e.tag == "loop"):
4305
+ continue # tests and spawned loops that reach no query are noise in the listing
4306
+ entry_points.append({"kind": e.kind, "name": e.name, "file": e.file, "line": e.line,
4307
+ "symbol": e.targets[0].symbol if e.targets else "", "sites": n})
4308
+ entry_points.sort(key=lambda e: (e["file"], e["line"], e["name"]))
4309
+ live = [s for s in sites if not s["is_test"]]
4310
+ hops = Counter(s["origins"][0]["hops"] for s in live if s["origins"])
4311
+ guess_only = sum(1 for s in live if s["origins"] and not s.get("origin_count_certain"))
4312
+ return {
4313
+ "entry_points": entry_points,
4314
+ "areas": build_areas(sites, roles),
4315
+ "summary": {
4316
+ "seconds": round(time.monotonic() - started, 1),
4317
+ "functions": len(ix.fns),
4318
+ "entry_points": dict(Counter(e.kind for e in entries).most_common()),
4319
+ "sites_with_origin": sum(1 for s in live if s["origins"]),
4320
+ # of those, the sites every origin of which goes through a call followed to several implementations
4321
+ "sites_with_guessed_origin_only": guess_only,
4322
+ "by_role": dict(Counter(s["role"] for s in sites).most_common()),
4323
+ "by_role_basis": dict(Counter(s["role_basis"] for s in sites).most_common()),
4324
+ "nearest_origin_hops": {str(k): v for k, v in sorted(hops.items())},
4325
+ "parse_errors": ix.errors,
4326
+ "loops": lp.summary(sites),
4327
+ },
4328
+ }
4329
+
4330
+
4331
+ def _const_users(ix: Index, site: dict, const: str, wanted: dict) -> list[int]:
4332
+ """Functions that read a SQL constant declared outside any function."""
4333
+ lang = site["language"]
4334
+ users = ix.const_uses.get((lang, const), ())
4335
+ if not users:
4336
+ return []
4337
+ same_file = [u for u in users if ix.fns[u].file == site["file"]]
4338
+ if same_file:
4339
+ return same_file
4340
+ if len({s["file"] for s in wanted.get((lang, const), ())}) != 1 or len(const) < 6:
4341
+ return [] # the same constant name is declared in several files: not followed across files
4342
+ d = os.path.dirname(site["file"])
4343
+ near = [u for u in users if os.path.dirname(ix.fns[u].file) == d]
4344
+ return near or list(users)[:50]
4345
+
4346
+
4347
+ def _resolve_entries(ix: Index, langs: dict[str, Lang]) -> list[Entry]:
4348
+ """Turn handler references into functions, apply nest prefixes, drop entries that point nowhere."""
4349
+ out: list[Entry] = []
4350
+ rust = langs.get("rust")
4351
+ go = langs.get("go")
4352
+ for e in ix.entries:
4353
+ lang = None
4354
+ if e.each == "verb" and langs.get("python") is not None:
4355
+ langs["python"].last_view = None
4356
+ for ctx, call in e.pending:
4357
+ if ctx is None:
4358
+ continue
4359
+ lang = langs.get(ctx.lang)
4360
+ if lang is None:
4361
+ continue
4362
+ try:
4363
+ found = lang.resolve(ctx, call)
4364
+ except Exception:
4365
+ if DEBUG:
4366
+ raise
4367
+ ix.errors += 1
4368
+ found = []
4369
+ for t in found:
4370
+ if t not in e.targets:
4371
+ e.targets.append(t)
4372
+ if not e.targets:
4373
+ continue
4374
+ if e.each:
4375
+ # a class or service registered as a whole: every method of it is an entry point of its own
4376
+ names = e.only() if callable(e.only) else None
4377
+ py = langs.get("python")
4378
+ for t in e.targets:
4379
+ if t.test or (isinstance(e.decl, Fn) and e.decl.test) or (names is not None and t.name not in names):
4380
+ continue
4381
+ if e.each == "verb" and isinstance(py, Python): # `GET /path` per verb method, `ANY /path/action` otherwise
4382
+ verb = py.view_verbs.get(t.name) or py.view_actions.get(t.name)
4383
+ path = e.path or "…"
4384
+ ename = _http_name(verb, path) if verb else _http_name("ANY", _join_path(path, t.name))
4385
+ else:
4386
+ if names is None and t.lang == "go" and t.nparams not in (1, 2):
4387
+ continue # not the shape of an RPC method: (ctx, request) or (request, stream) or (stream)
4388
+ ename = f"{e.name}/{t.name}"
4389
+ out.append(Entry(e.kind, ename, e.file, e.line, targets=[t], decl=e.decl, path=e.path, method=e.method))
4390
+ if e.each == "verb" and isinstance(py, Python):
4391
+ out[-1].view = getattr(py, "last_view", None)
4392
+ continue
4393
+ if e.loop_only:
4394
+ e.targets = [t for t in e.targets if t.loop]
4395
+ if not e.targets:
4396
+ continue
4397
+ e.name = e.targets[0].symbol or e.name
4398
+ if not e.name or e.name == "…":
4399
+ t = ([t for t in e.targets if not t.inline] or e.targets)[-1]
4400
+ e.name = t.symbol or t.name
4401
+ if t.lang == "go" and not t.container and isinstance(go, Go): # `Workflow` exists in many packages
4402
+ e.name = f"{go.pkg_name.get(os.path.dirname(t.file), '')}.{t.name}".lstrip(".")
4403
+ if e.tag == "routes!": # utoipa-axum: the handler's own attribute names the route
4404
+ if isinstance(rust, Rust) and any(t.id in rust.http_attr for t in e.targets):
4405
+ continue
4406
+ e.name = f"ANY {e.targets[0].symbol}"
4407
+ if e.kind not in TEST_KINDS and (all(t.test for t in e.targets) or (isinstance(e.decl, Fn) and e.decl.test)):
4408
+ continue # a route, worker or job wired up inside test code
4409
+ out.append(e)
4410
+ # nest("/prefix", child_router()) -> prefix for the routes declared in child_router
4411
+ if ix.nests:
4412
+ parents: dict[int, list[tuple[int, str | None]]] = defaultdict(list)
4413
+ for owner, prefix, call in ix.nests:
4414
+ lang = langs.get(owner.lang)
4415
+ if lang is None:
4416
+ continue
4417
+ for t in lang.resolve(owner, call):
4418
+ parents[t.id].append((owner.id, prefix))
4419
+
4420
+ def prefix_of(fid: int, depth: int = 0) -> str | None:
4421
+ ps = [p for p in parents.get(fid, ()) if not ix.fns[p[0]].test]
4422
+ if not ps:
4423
+ return ""
4424
+ if len(ps) > 1 or depth > 6 or ps[0][1] is None:
4425
+ return None
4426
+ up = prefix_of(ps[0][0], depth + 1)
4427
+ return None if up is None else _join_path(up, ps[0][1])
4428
+
4429
+ for e in out:
4430
+ if e.kind == "http" and isinstance(e.decl, Fn) and e.path is not None and e.decl.id in parents:
4431
+ pre = prefix_of(e.decl.id)
4432
+ if pre is None:
4433
+ e.name = _http_name(e.method, _join_path("…", e.path))
4434
+ elif pre:
4435
+ e.name = _http_name(e.method, _join_path(pre, e.path))
4436
+ # the same route registered twice (two mounts of one handler) stays two entries; exact duplicates collapse
4437
+ seen: dict[tuple, Entry] = {}
4438
+ uniq = []
4439
+ for e in out:
4440
+ key = (e.kind, e.name, e.file, e.line, tuple(sorted(t.id for t in e.targets)))
4441
+ if key in seen:
4442
+ continue
4443
+ seen[key] = e
4444
+ uniq.append(e)
4445
+ return uniq
4446
+
4447
+
4448
+ def _build_graph(ix: Index, langs: dict[str, Lang], entries: list[Entry]) -> dict[int, list[int]]:
4449
+ targets = {t.id for e in entries for t in e.targets}
4450
+ # a handler passed by name to something that is not a known registration call (`App::new().service(item)`)
4451
+ # is not a call from the function that wires it up: the entry point already says how it is reached
4452
+ # (a workflow that names an activity keeps its edge: that is how the activity is run)
4453
+ handlers = {t.id for e in entries if e.kind == "http" for t in e.targets}
4454
+ callers: dict[int, set[int]] = defaultdict(set)
4455
+ # (callee, caller) -> number of implementations, for an edge that exists only because one call through an
4456
+ # interface or a base class was followed to several definitions of the method: a guess, not a fact
4457
+ guessed: dict[tuple[int, int], int] = {}
4458
+ certain: set[tuple[int, int]] = set()
4459
+ for fn in ix.fns:
4460
+ lang = langs.get(fn.lang)
4461
+ if lang is None:
4462
+ continue
4463
+ if fn.calls:
4464
+ memo: dict[tuple, list[Fn]] = {}
4465
+ for call in fn.calls:
4466
+ key = (call[0], call[1], call[2], call[4])
4467
+ hit = memo.get(key)
4468
+ if hit is None:
4469
+ ix.by_name = False
4470
+ try:
4471
+ found = lang.resolve(fn, call)
4472
+ except Exception:
4473
+ if DEBUG:
4474
+ raise
4475
+ ix.errors += 1
4476
+ found = []
4477
+ hit = memo[key] = (found, ix.by_name)
4478
+ found, by_name = hit
4479
+ owners = {(t.file.rpartition("/")[0] if t.lang == "go" else "", t.container)
4480
+ for t in found if t.container and t.id not in getattr(lang, "abstract", ())}
4481
+ fan = len(owners) if len(owners) > 1 and len({t.name for t in found}) == 1 else 0
4482
+ fan = fan or ix.fanout.get((fn.id, call[1]), 0)
4483
+ if not fan and by_name and found:
4484
+ fan = -len(found) # negative: matched by method name, the receiver's type unknown
4485
+ for t in found:
4486
+ if t.id != fn.id and not (call[0] == "r" and t.id in handlers):
4487
+ callers[t.id].add(fn.id)
4488
+ if fan:
4489
+ guessed[(t.id, fn.id)] = max(fan, guessed.get((t.id, fn.id), fan))
4490
+ else:
4491
+ certain.add((t.id, fn.id))
4492
+ if not KEEP_CALLS:
4493
+ fn.calls = []
4494
+ # a function defined inside another is taken to run when the outer one does,
4495
+ # unless it is itself an entry point (a route handler declared inside a setup function)
4496
+ if fn.lex is not None and not fn.lex.module and not fn.inline and fn.id not in targets and not fn.container:
4497
+ callers[fn.id].add(fn.lex.id)
4498
+ elif fn.inline and fn.lex is not None and fn.id not in targets:
4499
+ callers[fn.id].add(fn.lex.id)
4500
+ for (callee, caller), _label in ix.framework_edges.items(): # stated as guesses: nothing in the source makes the call
4501
+ if (callee, caller) not in certain:
4502
+ callers[callee].add(caller)
4503
+ guessed.setdefault((callee, caller), 1)
4504
+ ix.guessed = {k: n for k, n in guessed.items() if k not in certain}
4505
+ return {k: sorted(v) for k, v in callers.items()}
4506
+
4507
+
4508
+ from ..runsonce import RUNS_ONCE_PATH # noqa: E402
4509
+
4510
+
4511
+ def _assign_roles(sites: list[dict], roles: PathRoles) -> None:
4512
+ undecided = []
4513
+ for s in sites:
4514
+ kinds = s["_kinds"]
4515
+ by_path = roles.of(s["file"])
4516
+ if s["is_test"]:
4517
+ s["role"], s["role_basis"] = "test", "path"
4518
+ elif RUNS_ONCE_PATH.search(s["file"]):
4519
+ s["role"], s["role_basis"] = "migration", "path" # migrations, seeds, backfills: run once, whatever reaches them
4520
+ elif s["kind"] == "sql_file":
4521
+ if by_path:
4522
+ s["role"] = by_path
4523
+ elif s.get("statement") == "ddl":
4524
+ s["role"] = "migration"
4525
+ else:
4526
+ undecided.append(s)
4527
+ elif "http" in kinds:
4528
+ s["role"], s["role_basis"] = "app", "entry_point"
4529
+ elif kinds & JOB_KINDS:
4530
+ s["role"], s["role_basis"] = "job", "entry_point"
4531
+ elif by_path:
4532
+ s["role"] = by_path
4533
+ elif kinds:
4534
+ # reached only from programs: a service's `main` makes it app code, unless every
4535
+ # program that reaches it lives in a scripts or tools directory
4536
+ started = {roles.of(f) for f in s["_starts"]}
4537
+ if started and "" not in started:
4538
+ s["role"] = "tooling" if started == {"tooling"} else "script"
4539
+ else:
4540
+ s["role"] = "app" if "main" in kinds else "script"
4541
+ s["role_basis"] = "entry_point"
4542
+ else:
4543
+ undecided.append(s)
4544
+ # no origin and no telling path: take the role of the code around it, when that is clear
4545
+ by_file: dict[str, Counter] = defaultdict(Counter)
4546
+ by_dir: dict[str, Counter] = defaultdict(Counter)
4547
+ for s in sites:
4548
+ if s["role_basis"] == "entry_point" and s["kind"] != "sql_file":
4549
+ by_file[s["file"]][s["role"]] += 1
4550
+ by_dir[os.path.dirname(s["file"])][s["role"]] += 1
4551
+ for s in undecided:
4552
+ if s["kind"] == "sql_file":
4553
+ continue
4554
+ for counts in (by_file.get(s["file"]), by_dir.get(os.path.dirname(s["file"]))):
4555
+ if counts:
4556
+ role, n = counts.most_common(1)[0]
4557
+ if n * 3 >= sum(counts.values()) * 2:
4558
+ s["role"] = role
4559
+ break
4560
+
4561
+
4562
+ try: # TypeScript / JavaScript live in their own file and register themselves in LANGS
4563
+ from . import origins_ts # noqa: E402,F401
4564
+ except ImportError: # a grammar that is not installed must not stop discovery
4565
+ pass