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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1584 @@
|
|
|
1
|
+
"""Call graph and entry points for TypeScript and JavaScript.
|
|
2
|
+
|
|
3
|
+
Registered with `origins.LANGS` when this module is imported (origins.py imports it last).
|
|
4
|
+
Entry-point rules live in `rules/entry_points.toml` under `[typescript]`:
|
|
5
|
+
|
|
6
|
+
* `[[typescript.call]]` a registration call: Express / Fastify / Koa / Hono routes, tRPC procedures,
|
|
7
|
+
BullMQ / pg-boss / node-cron handlers, commander actions
|
|
8
|
+
* `[[typescript.new]]` a constructor that takes a handler: `new Worker("queue", processor)`
|
|
9
|
+
* `[[typescript.decorator]]` NestJS controllers, resolvers, processors, cron and event handlers
|
|
10
|
+
* `[[typescript.file]]` file conventions: Next.js `app/**/route.ts`, `pages/api/**`, SvelteKit `+server.ts`
|
|
11
|
+
* `[[typescript.directive]]` `"use server"` modules: every export is a server action
|
|
12
|
+
|
|
13
|
+
A call is followed when the name is bound in the file (a declaration, an import, a `require`, a dynamic
|
|
14
|
+
`await import()`), when the receiver's type is known (`this`, a constructor-injected field, `new X()`, a
|
|
15
|
+
typed parameter, an exported object or class), or when a method name is unique in the repo. Imports are
|
|
16
|
+
followed through default exports, `export const x = () =>`, barrels (`export * from`, `export { a } from`),
|
|
17
|
+
tsconfig paths and workspace packages.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
from collections import defaultdict
|
|
25
|
+
|
|
26
|
+
from tree_sitter import Node, Parser, Query, QueryCursor
|
|
27
|
+
|
|
28
|
+
from . import origins
|
|
29
|
+
from .origins import Entry, Fn, Lang, _http_name, _join_path, _t, apply_rule
|
|
30
|
+
from .tsresolve import EXTS, Resolver
|
|
31
|
+
from .typescript import (CLASS_TYPES, INLINE_FUNCS, LANG_TS, LANG_TSX, UNWRAP_TYPES, _unwrap, call_args, decode_string,
|
|
32
|
+
func_name, is_ts_test, language_for, object_pairs, params_of)
|
|
33
|
+
|
|
34
|
+
SCAN_QUERY = """
|
|
35
|
+
(function_declaration) @func
|
|
36
|
+
(generator_function_declaration) @func
|
|
37
|
+
(method_definition) @func
|
|
38
|
+
(arrow_function) @afunc
|
|
39
|
+
(function_expression) @afunc
|
|
40
|
+
(call_expression) @call
|
|
41
|
+
(new_expression) @new
|
|
42
|
+
(import_statement) @imp
|
|
43
|
+
(export_statement) @exp
|
|
44
|
+
(class_declaration) @class
|
|
45
|
+
(abstract_class_declaration) @class
|
|
46
|
+
(class) @class
|
|
47
|
+
(interface_declaration) @iface
|
|
48
|
+
(required_parameter) @param
|
|
49
|
+
(optional_parameter) @param
|
|
50
|
+
(variable_declarator value: (new_expression)) @newvar
|
|
51
|
+
(variable_declarator value: (call_expression)) @callvar
|
|
52
|
+
(variable_declarator value: (await_expression (call_expression))) @callvar
|
|
53
|
+
(public_field_definition value: (call_expression)) @callfield
|
|
54
|
+
(variable_declarator name: (object_pattern) value: (identifier)) @destruct
|
|
55
|
+
(variable_declarator name: (object_pattern) value: (member_expression)) @destruct
|
|
56
|
+
(assignment_expression left: (member_expression)) @massign
|
|
57
|
+
(arguments (identifier) @ref)
|
|
58
|
+
(arguments (member_expression) @ref)
|
|
59
|
+
(pair value: (identifier) @ref)
|
|
60
|
+
(pair value: (member_expression) @ref)
|
|
61
|
+
(array (identifier) @ref)
|
|
62
|
+
(shorthand_property_identifier) @ref
|
|
63
|
+
"""
|
|
64
|
+
# Names that may be functions, as a cheap first filter on the calls kept for the graph (a superset is fine).
|
|
65
|
+
FN_NAME_RES = (
|
|
66
|
+
re.compile(rb"\bfunction\s*\*?\s*([A-Za-z_$][\w$]*)"),
|
|
67
|
+
re.compile(rb"(?<![\w$])([A-Za-z_$][\w$]*)[ \t]*[:=]\s*(?:async\b\s*)?(?:function\b|\(|<|[A-Za-z_$][\w$.]*\s*(?:=>|[,}(]))"),
|
|
68
|
+
re.compile(rb"(?m)^[ \t]+(?:(?:public|private|protected|static|async|override|readonly|get|set)[ \t]+)*\*?([A-Za-z_$#][\w$]*)[ \t]*(?:<[^>\n]*>)?\("),
|
|
69
|
+
)
|
|
70
|
+
NOT_FN_NAMES_B = {b"if", b"for", b"while", b"switch", b"catch", b"function", b"return", b"constructor", b"await", b"new", b"typeof"}
|
|
71
|
+
RETURN_NEW = re.compile(rb"\breturn\s+new\s+([A-Za-z_$][\w$.]*)\s*[(<]")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _directive(src: bytes) -> bytes:
|
|
75
|
+
"""The directive a module starts with (`"use server"`), after leading comments. b"" when there is none."""
|
|
76
|
+
i, n = 0, len(src)
|
|
77
|
+
while i < n:
|
|
78
|
+
c = src[i: i + 1]
|
|
79
|
+
if c.isspace():
|
|
80
|
+
i += 1
|
|
81
|
+
elif src.startswith(b"//", i):
|
|
82
|
+
j = src.find(b"\n", i)
|
|
83
|
+
i = n if j < 0 else j + 1
|
|
84
|
+
elif src.startswith(b"/*", i):
|
|
85
|
+
j = src.find(b"*/", i)
|
|
86
|
+
i = n if j < 0 else j + 2
|
|
87
|
+
elif c in (b"'", b'"'):
|
|
88
|
+
j = src.find(c, i + 1, i + 40)
|
|
89
|
+
return src[i + 1: j] if j > 0 else b""
|
|
90
|
+
else:
|
|
91
|
+
break
|
|
92
|
+
return b""
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
SHEBANG = re.compile(rb"^#!.*\b(?:node|tsx|ts-node|bun|deno|zx)\b")
|
|
96
|
+
MAIN_GUARD = re.compile(rb"require\.main\s*===?\s*module|import\.meta\.main\b|import\.meta\.url\s*===?\s*[^;\n]*process\.argv")
|
|
97
|
+
# Receivers of method calls that are too common to resolve by a repo-wide unique name.
|
|
98
|
+
TS_AMBIGUOUS = {
|
|
99
|
+
"then", "catch", "finally", "forEach", "reduce", "includes", "slice", "splice", "concat", "entries", "toJSON",
|
|
100
|
+
"toArray", "on", "off", "once", "use", "pipe", "unsubscribe", "focus", "blur", "click", "onChange", "toISOString",
|
|
101
|
+
"getTime", "toLowerCase", "toUpperCase", "startsWith", "endsWith", "indexOf", "trim", "padStart", "test", "match",
|
|
102
|
+
"exec", "bind", "resolve", "reject", "abort", "destroy", "end", "write", "emit", "addEventListener", "preventDefault",
|
|
103
|
+
"json", "text", "blob", "getItem", "setItem", "removeItem", "refetch", "invalidate", "mutate", "mutateAsync",
|
|
104
|
+
"parse", "safeParse", "optional", "nullable", "extend", "describe", "transform", "refine", "pick", "omit", "merge",
|
|
105
|
+
"query", "mutation", "input", "output", "where", "select", "from", "values", "returning", "limit", "offset",
|
|
106
|
+
"orderBy", "groupBy", "having", "innerJoin", "leftJoin", "execute", "toSQL", "compile", "as", "raw", "ref",
|
|
107
|
+
"findMany", "findFirst", "findUnique", "upsert", "createMany", "updateMany", "deleteMany", "aggregate", "count",
|
|
108
|
+
"handler", "default", "render", "toString", "valueOf", "next", "done", "error", "info", "warn", "debug", "log",
|
|
109
|
+
"start", "stop", "run", "init", "setup", "process", "handle", "get", "set", "has", "add", "delete", "clear",
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# A call that runs its callback at once: `xs.map(fn)` is not a new function named after the variable it fills.
|
|
114
|
+
IMMEDIATE = {"map", "forEach", "flatMap", "filter", "reduce", "some", "every", "find", "findIndex", "sort", "then", "catch",
|
|
115
|
+
"finally", "all", "allSettled", "race", "any", "from", "fromEntries", "entries", "keys", "values", "parse",
|
|
116
|
+
"safeParse", "object", "transaction", "$transaction", "useMemo", "useState", "useRef", "useEffect",
|
|
117
|
+
"useCallback", "useQuery", "useMutation", "describe", "it", "test", "expect", "require", "createContext"}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _ts_type(text: str) -> str:
|
|
121
|
+
"""The class name of a type annotation: `Foo<T> | undefined` -> Foo, `Promise<Foo>` -> Foo."""
|
|
122
|
+
text = text.lstrip(": ").strip()
|
|
123
|
+
while text.startswith(("Promise<", "Awaited<", "Readonly<", "Partial<", "Required<")):
|
|
124
|
+
text = text.split("<", 1)[1]
|
|
125
|
+
text = re.split(r"\s*[|&]\s*", text)[0].strip()
|
|
126
|
+
text = re.sub(r"^(?:readonly\s+|typeof\s+)", "", text)
|
|
127
|
+
m = re.match(r"[A-Za-z_$][\w$.]*", text)
|
|
128
|
+
if not m:
|
|
129
|
+
return ""
|
|
130
|
+
name = m.group(0).split(".")[-1]
|
|
131
|
+
return name if name[:1].isupper() and name not in ("Promise", "Array", "Record", "Map", "Set", "Partial", "Readonly") else ""
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def chain_text(node: Node | None, depth: int = 0) -> str:
|
|
135
|
+
"""`protectedProcedure.input(z.object({...})).query` -> `protectedProcedure.input().query`."""
|
|
136
|
+
node = _unwrap(node)
|
|
137
|
+
if node is None or depth > 14:
|
|
138
|
+
return "?"
|
|
139
|
+
t = node.type
|
|
140
|
+
if t in ("identifier", "property_identifier", "this", "super"):
|
|
141
|
+
return _t(node)
|
|
142
|
+
if t == "member_expression":
|
|
143
|
+
return chain_text(node.child_by_field_name("object"), depth + 1) + "." + _t(node.child_by_field_name("property"))
|
|
144
|
+
if t == "call_expression":
|
|
145
|
+
return chain_text(node.child_by_field_name("function"), depth + 1) + "()"
|
|
146
|
+
if t == "new_expression":
|
|
147
|
+
return "new " + chain_text(node.child_by_field_name("constructor"), depth + 1) + "()"
|
|
148
|
+
return "?"
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _chain_root(node: Node | None) -> str:
|
|
152
|
+
node = _unwrap(node)
|
|
153
|
+
for _ in range(20):
|
|
154
|
+
if node is None:
|
|
155
|
+
return ""
|
|
156
|
+
if node.type == "member_expression":
|
|
157
|
+
node = _unwrap(node.child_by_field_name("object"))
|
|
158
|
+
elif node.type == "call_expression":
|
|
159
|
+
node = _unwrap(node.child_by_field_name("function"))
|
|
160
|
+
else:
|
|
161
|
+
break
|
|
162
|
+
return _t(node) if node is not None and node.type in ("identifier", "this") else ""
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class TypeScript(Lang):
|
|
166
|
+
name = "typescript"
|
|
167
|
+
exts = EXTS
|
|
168
|
+
|
|
169
|
+
def __init__(self, index, rules):
|
|
170
|
+
super().__init__(index, rules)
|
|
171
|
+
self.parsers = {id(LANG_TS): Parser(LANG_TS), id(LANG_TSX): Parser(LANG_TSX)}
|
|
172
|
+
self.queries = {id(LANG_TS): Query(LANG_TS, SCAN_QUERY), id(LANG_TSX): Query(LANG_TSX, SCAN_QUERY)}
|
|
173
|
+
self.call_rules = self._compile("call")
|
|
174
|
+
self.new_rules = self._compile("new")
|
|
175
|
+
self.dec_rules = self._compile("decorator")
|
|
176
|
+
self.file_rules = self._compile("file")
|
|
177
|
+
self.directive_rules = self._compile("directive")
|
|
178
|
+
self.reg_names = {n for _, r in self.call_rules for n in r.get("names", [])}
|
|
179
|
+
self.new_names = {n for _, r in self.new_rules for n in r.get("names", [])}
|
|
180
|
+
router = rules.get("router", {})
|
|
181
|
+
self.mount_names = set(router.get("mount", []))
|
|
182
|
+
self.factory_names = set(router.get("factory", []))
|
|
183
|
+
self.class_prefix = set(router.get("class_prefix", []))
|
|
184
|
+
self.program_dirs = re.compile(rules.get("program_dirs", r"\b\B"))
|
|
185
|
+
self.service_main = re.compile(rules.get("service_main", r"\b\B").encode())
|
|
186
|
+
self.ambiguous = TS_AMBIGUOUS | set(rules.get("ambiguous", []))
|
|
187
|
+
self.resolver: Resolver | None = None
|
|
188
|
+
self.modfn: dict[str, Fn] = {}
|
|
189
|
+
self.imports: dict[str, dict[str, tuple[str | None, str]]] = {} # file -> local -> (target file, exported name)
|
|
190
|
+
self.exports: dict[str, dict[str, str]] = defaultdict(dict) # file -> exported name -> local name
|
|
191
|
+
self.reexports: dict[str, list[tuple[dict[str, str] | None, str]]] = defaultdict(list)
|
|
192
|
+
self.top: dict[str, dict[str, Fn]] = defaultdict(dict) # file -> name -> module-level function
|
|
193
|
+
self.members: dict[tuple[str, str], dict[str, list[Fn]]] = defaultdict(lambda: defaultdict(list))
|
|
194
|
+
self.objrefs: dict[tuple[str, str], dict[str, str]] = defaultdict(dict) # object member -> the name it refers to
|
|
195
|
+
self.class_info: dict[tuple[str, str], dict] = {}
|
|
196
|
+
self.classes: dict[str, list[str]] = defaultdict(list) # class name -> files
|
|
197
|
+
self.ifaces: set[str] = set()
|
|
198
|
+
self.subtypes: dict[str, list[tuple[str, str]]] = defaultdict(list)
|
|
199
|
+
self.modvars: dict[tuple[str, str], str] = {} # (file, name) -> class of `const x = new X()`
|
|
200
|
+
self.children: dict[int, dict[str, Fn]] = {}
|
|
201
|
+
self.fn_class: dict[int, tuple[str, str]] = {} # method fn id -> (file, class)
|
|
202
|
+
self.returns: dict[int, str] = {} # fn id -> class it returns
|
|
203
|
+
# routers declared at module level: (file, variable) -> mounts, and the entries each one declares
|
|
204
|
+
self.mounts: dict[tuple[str, str], list[tuple[tuple[str, str], str]]] = defaultdict(list)
|
|
205
|
+
self.pending_mounts: list[tuple[tuple[str, str], str, str, tuple[str, str], Fn]] = []
|
|
206
|
+
self.entry_owner: list[tuple[Entry, tuple[str, str], str]] = []
|
|
207
|
+
self.pending_exports: list[tuple[str, str, int, str | None, str, str]] = []
|
|
208
|
+
self.pkg_programs: dict[str, str] | None = None
|
|
209
|
+
# functions that hand one of their own parameters to a registration call (`register(queue, processor)`
|
|
210
|
+
# wrapping `new Worker(queue, processor)`), and the calls that may be calls to one
|
|
211
|
+
self.wrapper_like = re.compile(rules.get("registration_like", r"\b\B"))
|
|
212
|
+
self.reg_wrappers: dict[int, list[tuple[str, tuple[int, ...], int, str]]] = defaultdict(list)
|
|
213
|
+
self.wrapper_names: dict[str, list[Fn]] = defaultdict(list)
|
|
214
|
+
self.argcalls: dict[str, list[tuple]] = defaultdict(list)
|
|
215
|
+
|
|
216
|
+
# ---- per file ---------------------------------------------------------------------
|
|
217
|
+
def prescan(self, rel, src):
|
|
218
|
+
if self.resolver is None:
|
|
219
|
+
self.resolver = Resolver(self.ix.root, [f for f in self.ix.files_seen if f.endswith(EXTS)])
|
|
220
|
+
self._package_programs()
|
|
221
|
+
names = set()
|
|
222
|
+
for rx in FN_NAME_RES:
|
|
223
|
+
names.update(rx.findall(src))
|
|
224
|
+
self.fn_names.update(n.decode() for n in names if n not in NOT_FN_NAMES_B)
|
|
225
|
+
|
|
226
|
+
def _package_programs(self) -> None:
|
|
227
|
+
"""Files that a package.json `bin` or `scripts` entry runs: programs, whatever they look like."""
|
|
228
|
+
self.pkg_programs = {}
|
|
229
|
+
res = self.resolver
|
|
230
|
+
for d in sorted(res.dirs):
|
|
231
|
+
pkg = res.package_json(d)
|
|
232
|
+
if pkg is None:
|
|
233
|
+
continue
|
|
234
|
+
cmds: list[tuple[str, str]] = []
|
|
235
|
+
b = pkg.get("bin")
|
|
236
|
+
for name, path in (b.items() if isinstance(b, dict) else [(pkg.get("name", ""), b)] if isinstance(b, str) else []):
|
|
237
|
+
if isinstance(path, str):
|
|
238
|
+
cmds.append((str(name), path))
|
|
239
|
+
scripts = pkg.get("scripts")
|
|
240
|
+
for name, cmd in (scripts.items() if isinstance(scripts, dict) else []):
|
|
241
|
+
if isinstance(cmd, str):
|
|
242
|
+
for m in re.finditer(r"(?:^|\s)(?:node|tsx|ts-node|bun(?:\s+run)?|ts-node-dev|nodemon|esno|deno\s+run)\s+(?:-\S+\s+)*([\w./@-]+\.[cm]?[jt]s)\b", cmd):
|
|
243
|
+
cmds.append((f"{name}", m.group(1)))
|
|
244
|
+
for name, path in cmds:
|
|
245
|
+
for variant in res._source_variants(path.lstrip("./")):
|
|
246
|
+
hit = res.as_file((d + "/" if d else "") + variant)
|
|
247
|
+
if hit is not None:
|
|
248
|
+
self.pkg_programs.setdefault(hit, name)
|
|
249
|
+
break
|
|
250
|
+
|
|
251
|
+
def parse(self, rel, src):
|
|
252
|
+
if len(src) > 20_000 and len(src) / (src.count(b"\n") + 1) > 1000:
|
|
253
|
+
return # a bundle: no call graph worth having
|
|
254
|
+
lang = language_for(rel)
|
|
255
|
+
tree = self.parsers[id(lang)].parse(src)
|
|
256
|
+
if origins.TREE_HOOK is not None:
|
|
257
|
+
origins.TREE_HOOK(self.name, lang, rel, src, tree)
|
|
258
|
+
caps = QueryCursor(self.queries[id(lang)]).captures(tree.root_node)
|
|
259
|
+
is_test = is_ts_test(rel)
|
|
260
|
+
mod = self.add_fn(Fn(rel, self.name, "<module>", "", "", (0, len(src) + 1, 1, src.count(b"\n") + 2), module=True,
|
|
261
|
+
test=is_test))
|
|
262
|
+
self.modfn[rel] = mod
|
|
263
|
+
imports = self.imports.setdefault(rel, {})
|
|
264
|
+
resolve = self.resolver.resolve
|
|
265
|
+
for node in caps.get("imp", []):
|
|
266
|
+
source = node.child_by_field_name("source")
|
|
267
|
+
if source is None:
|
|
268
|
+
continue
|
|
269
|
+
target = resolve(rel, decode_string(source))
|
|
270
|
+
for c in node.named_children:
|
|
271
|
+
if c.type != "import_clause":
|
|
272
|
+
continue
|
|
273
|
+
for part in c.named_children:
|
|
274
|
+
if part.type == "identifier":
|
|
275
|
+
imports[_t(part)] = (target, "default")
|
|
276
|
+
elif part.type == "namespace_import":
|
|
277
|
+
ident = next((x for x in part.named_children if x.type == "identifier"), None)
|
|
278
|
+
if ident is not None:
|
|
279
|
+
imports[_t(ident)] = (target, "*")
|
|
280
|
+
elif part.type == "named_imports":
|
|
281
|
+
for spec in part.named_children:
|
|
282
|
+
if spec.type == "import_specifier":
|
|
283
|
+
nm, alias = spec.child_by_field_name("name"), spec.child_by_field_name("alias")
|
|
284
|
+
if nm is not None:
|
|
285
|
+
imports[_t(alias or nm)] = (target, _t(nm))
|
|
286
|
+
# classes and interfaces
|
|
287
|
+
class_at: dict[int, str] = {}
|
|
288
|
+
class_decs: dict[int, list[Node]] = {}
|
|
289
|
+
for node in caps.get("iface", []):
|
|
290
|
+
self.ifaces.add(_t(node.child_by_field_name("name")))
|
|
291
|
+
for node in caps.get("class", []):
|
|
292
|
+
name = _t(node.child_by_field_name("name"))
|
|
293
|
+
if not name:
|
|
294
|
+
p = node.parent
|
|
295
|
+
name = _t(p.child_by_field_name("name")) if p is not None and p.type == "variable_declarator" else ""
|
|
296
|
+
if not name:
|
|
297
|
+
continue
|
|
298
|
+
class_at[node.id] = name
|
|
299
|
+
info = self.class_info.setdefault((rel, name), {"extends": "", "implements": [], "fields": {}})
|
|
300
|
+
self.classes[name].append(rel)
|
|
301
|
+
decs = [c for c in node.children if c.type == "decorator"]
|
|
302
|
+
if node.parent is not None and node.parent.type == "export_statement":
|
|
303
|
+
decs += [c for c in node.parent.children if c.type == "decorator"]
|
|
304
|
+
class_decs[node.id] = decs
|
|
305
|
+
for c in node.children:
|
|
306
|
+
if c.type == "class_heritage":
|
|
307
|
+
for h in c.named_children:
|
|
308
|
+
if h.type == "extends_clause":
|
|
309
|
+
base = _ts_type(_t(h.child_by_field_name("value") or (h.named_children[0] if h.named_children else None)))
|
|
310
|
+
if base:
|
|
311
|
+
info["extends"] = base
|
|
312
|
+
self.subtypes[base].append((rel, name))
|
|
313
|
+
elif h.type == "implements_clause":
|
|
314
|
+
for tnode in h.named_children:
|
|
315
|
+
base = _ts_type(_t(tnode))
|
|
316
|
+
if base:
|
|
317
|
+
info["implements"].append(base)
|
|
318
|
+
self.subtypes[base].append((rel, name))
|
|
319
|
+
elif h.type in ("identifier", "member_expression"): # JavaScript: class A extends B
|
|
320
|
+
base = _ts_type(_t(h))
|
|
321
|
+
if base:
|
|
322
|
+
info["extends"] = base
|
|
323
|
+
self.subtypes[base].append((rel, name))
|
|
324
|
+
body = node.child_by_field_name("body")
|
|
325
|
+
for member in (body.named_children if body is not None else ()):
|
|
326
|
+
if member.type == "public_field_definition":
|
|
327
|
+
fname = _t(member.child_by_field_name("name"))
|
|
328
|
+
typ = member.child_by_field_name("type")
|
|
329
|
+
value = _unwrap(member.child_by_field_name("value"))
|
|
330
|
+
tt = _ts_type(_t(typ)) if typ is not None else ""
|
|
331
|
+
if not tt and value is not None and value.type == "new_expression":
|
|
332
|
+
tt = _ts_type(_t(value.child_by_field_name("constructor")))
|
|
333
|
+
if fname and tt:
|
|
334
|
+
info["fields"][fname] = tt
|
|
335
|
+
|
|
336
|
+
# functions
|
|
337
|
+
node_fn: dict[int, Fn] = {}
|
|
338
|
+
func_nodes = sorted(caps.get("func", []) + caps.get("afunc", []), key=lambda n: n.start_byte)
|
|
339
|
+
for node in func_nodes:
|
|
340
|
+
name = func_name(node)
|
|
341
|
+
if not name:
|
|
342
|
+
p = node.parent
|
|
343
|
+
if p is not None and p.type == "export_statement" and any(c.type == "default" for c in p.children):
|
|
344
|
+
name = "default"
|
|
345
|
+
else:
|
|
346
|
+
continue
|
|
347
|
+
if name.startswith(("'", '"', "`", "[")):
|
|
348
|
+
name = name.strip("'\"`[]")
|
|
349
|
+
container, cls_key = "", None
|
|
350
|
+
holder = node.parent
|
|
351
|
+
while holder is not None and holder.type in UNWRAP_TYPES:
|
|
352
|
+
holder = holder.parent
|
|
353
|
+
if node.type == "method_definition" or (holder is not None and holder.type == "public_field_definition"):
|
|
354
|
+
body = node.parent if node.type == "method_definition" else holder.parent
|
|
355
|
+
owner = body.parent if body is not None else None
|
|
356
|
+
if owner is not None and owner.id in class_at:
|
|
357
|
+
container = class_at[owner.id]
|
|
358
|
+
cls_key = (rel, container)
|
|
359
|
+
elif body is not None and body.type == "object":
|
|
360
|
+
container = self._object_name(body)
|
|
361
|
+
elif holder is not None and holder.type == "pair":
|
|
362
|
+
container = self._object_name(holder.parent) if holder.parent is not None else ""
|
|
363
|
+
params = params_of(node)
|
|
364
|
+
fn = self.add_fn(Fn(rel, self.name, name, f"{container}.{name}" if container else name, container, node,
|
|
365
|
+
method=bool(container), nparams=len(params), test=is_test))
|
|
366
|
+
fn.extra = {"$params": [_t(p) if p.type == "identifier" else "" for p in params]}
|
|
367
|
+
node_fn[node.id] = fn
|
|
368
|
+
rt = node.child_by_field_name("return_type")
|
|
369
|
+
body = node.child_by_field_name("body")
|
|
370
|
+
ret = _ts_type(_t(rt)) if rt is not None else ""
|
|
371
|
+
if not ret and body is not None:
|
|
372
|
+
made = _unwrap(body) if body.type != "statement_block" else None
|
|
373
|
+
if made is not None and made.type == "new_expression":
|
|
374
|
+
ret = _ts_type(_t(made.child_by_field_name("constructor")))
|
|
375
|
+
elif made is None and b"return new " in body.text:
|
|
376
|
+
m = RETURN_NEW.search(body.text)
|
|
377
|
+
ret = _ts_type(m.group(1).decode()) if m else ""
|
|
378
|
+
if ret:
|
|
379
|
+
self.returns[fn.id] = ret
|
|
380
|
+
if container:
|
|
381
|
+
self.members[(rel, container)][name].append(fn)
|
|
382
|
+
if cls_key is not None:
|
|
383
|
+
self.fn_class[fn.id] = cls_key
|
|
384
|
+
if name == "constructor": # constructor(private readonly users: UserService)
|
|
385
|
+
prm = node.child_by_field_name("parameters")
|
|
386
|
+
for p in (prm.named_children if prm is not None else ()):
|
|
387
|
+
if p.type in ("required_parameter", "optional_parameter"):
|
|
388
|
+
pat, typ = p.child_by_field_name("pattern"), p.child_by_field_name("type")
|
|
389
|
+
tt = _ts_type(_t(typ)) if typ is not None else ""
|
|
390
|
+
if pat is not None and pat.type == "identifier" and tt:
|
|
391
|
+
self.class_info[cls_key]["fields"].setdefault(_t(pat), tt)
|
|
392
|
+
# a name bound to a wrapped function is a function too: `export const getUser = cache(async (id) => ...)`,
|
|
393
|
+
# `check = withReporting(this._check.bind(this))`
|
|
394
|
+
local_names = {f.name for f in node_fn.values()}
|
|
395
|
+
for node in caps.get("callvar", []) + caps.get("callfield", []):
|
|
396
|
+
value = node.child_by_field_name("value")
|
|
397
|
+
nm = node.child_by_field_name("name")
|
|
398
|
+
if value is None or value.type != "call_expression" or nm is None or nm.id in node_fn:
|
|
399
|
+
continue
|
|
400
|
+
is_field = node.type == "public_field_definition"
|
|
401
|
+
if not is_field and (nm.type != "identifier" or node.parent is None or node.parent.parent is None or
|
|
402
|
+
node.parent.parent.type not in ("program", "export_statement")):
|
|
403
|
+
continue
|
|
404
|
+
if not self._wraps_function(value, local_names, 0):
|
|
405
|
+
continue
|
|
406
|
+
container = ""
|
|
407
|
+
if is_field:
|
|
408
|
+
owner = node.parent.parent if node.parent is not None else None
|
|
409
|
+
container = class_at.get(owner.id, "") if owner is not None else ""
|
|
410
|
+
if not container:
|
|
411
|
+
continue
|
|
412
|
+
name = _t(nm)
|
|
413
|
+
fn = self.add_fn(Fn(rel, self.name, name, f"{container}.{name}" if container else name, container, value,
|
|
414
|
+
method=bool(container), test=is_test))
|
|
415
|
+
fn.extra = {}
|
|
416
|
+
node_fn[value.id] = fn
|
|
417
|
+
if container:
|
|
418
|
+
self.members[(rel, container)][name].append(fn)
|
|
419
|
+
self.fn_class[fn.id] = (rel, container)
|
|
420
|
+
self.link(rel, src)
|
|
421
|
+
for fn in self.ix.by_file[rel]:
|
|
422
|
+
if fn.lex is mod and not fn.container:
|
|
423
|
+
self.top[rel].setdefault(fn.name, fn)
|
|
424
|
+
# exports
|
|
425
|
+
exports = self.exports[rel]
|
|
426
|
+
for node in caps.get("exp", []):
|
|
427
|
+
self._export_statement(rel, node, exports, node_fn)
|
|
428
|
+
for node in caps.get("massign", []): # module.exports = ..., exports.x = ...
|
|
429
|
+
left = _t(node.child_by_field_name("left"))
|
|
430
|
+
right = _unwrap(node.child_by_field_name("right"))
|
|
431
|
+
if right is None or not left.startswith(("module.exports", "exports.")):
|
|
432
|
+
continue
|
|
433
|
+
key = left.removeprefix("module.exports").removeprefix("exports").lstrip(".") or "default"
|
|
434
|
+
if "." in key:
|
|
435
|
+
continue
|
|
436
|
+
if right.type == "identifier":
|
|
437
|
+
exports.setdefault(key, _t(right))
|
|
438
|
+
elif right.id in node_fn:
|
|
439
|
+
exports.setdefault(key, node_fn[right.id].name)
|
|
440
|
+
self.top[rel].setdefault(node_fn[right.id].name, node_fn[right.id])
|
|
441
|
+
elif right.type == "object" and key != "default": # exports.repo = { find() {} }
|
|
442
|
+
exports.setdefault(key, key)
|
|
443
|
+
elif right.type == "object":
|
|
444
|
+
for k, v in object_pairs(right).items():
|
|
445
|
+
v = _unwrap(v)
|
|
446
|
+
if v is not None and v.type in ("identifier", "shorthand_property_identifier"):
|
|
447
|
+
exports.setdefault(k, _t(v))
|
|
448
|
+
elif v is not None and v.id in node_fn:
|
|
449
|
+
exports.setdefault(k, node_fn[v.id].name)
|
|
450
|
+
self.top[rel].setdefault(node_fn[v.id].name, node_fn[v.id])
|
|
451
|
+
|
|
452
|
+
# entry points: registration calls, constructors, decorators, file conventions
|
|
453
|
+
at = self.ix.at_byte
|
|
454
|
+
added = False
|
|
455
|
+
reg_args: set[int] = set()
|
|
456
|
+
calls = caps.get("call", [])
|
|
457
|
+
for node in calls:
|
|
458
|
+
f = _unwrap(node.child_by_field_name("function"))
|
|
459
|
+
if f is None:
|
|
460
|
+
continue
|
|
461
|
+
if f.type == "member_expression":
|
|
462
|
+
last = _t(f.child_by_field_name("property"))
|
|
463
|
+
elif f.type == "identifier":
|
|
464
|
+
last = _t(f)
|
|
465
|
+
elif f.type == "import":
|
|
466
|
+
self._dynamic_import(rel, node, at)
|
|
467
|
+
continue
|
|
468
|
+
else:
|
|
469
|
+
continue
|
|
470
|
+
if last == "require":
|
|
471
|
+
self._require(rel, node, imports)
|
|
472
|
+
if last in self.factory_names: # createTRPCRouter({ traces: traceRouter })
|
|
473
|
+
parent = (rel, self._binding_name(node) or ("default" if self._is_default_export(node) else ""))
|
|
474
|
+
for a in call_args(node):
|
|
475
|
+
a = _unwrap(a)
|
|
476
|
+
for k, v in (object_pairs(a).items() if a is not None and a.type == "object" else ()):
|
|
477
|
+
v = _unwrap(v)
|
|
478
|
+
if v is not None and v.type in ("identifier", "shorthand_property_identifier"):
|
|
479
|
+
self.pending_mounts.append((parent, k, rel, ("", _t(v)), mod))
|
|
480
|
+
if last in self.reg_names or last in self.mount_names:
|
|
481
|
+
added |= self._registration(rel, node, f, last, at, node_fn, reg_args, is_test)
|
|
482
|
+
if self.wrapper_like.match(last):
|
|
483
|
+
added |= self._arg_call(rel, node, f, last, at, node_fn)
|
|
484
|
+
for node in caps.get("new", []):
|
|
485
|
+
ctor = node.child_by_field_name("constructor")
|
|
486
|
+
if ctor is not None and _t(ctor).split(".")[-1] in self.new_names:
|
|
487
|
+
added |= self._new(rel, node, ctor, at, node_fn, reg_args)
|
|
488
|
+
for node in caps.get("class", []):
|
|
489
|
+
if node.id in class_at:
|
|
490
|
+
self._class_entries(rel, node, class_at[node.id], class_decs.get(node.id, []), node_fn)
|
|
491
|
+
added |= self._file_entries(rel, src, tree.root_node, exports, node_fn, mod, is_test)
|
|
492
|
+
if added:
|
|
493
|
+
self.link(rel, src)
|
|
494
|
+
|
|
495
|
+
# variable types: typed parameters and `const x = new X()`
|
|
496
|
+
for node in caps.get("param", []):
|
|
497
|
+
pat, typ = node.child_by_field_name("pattern"), node.child_by_field_name("type")
|
|
498
|
+
if pat is None or typ is None or pat.type != "identifier":
|
|
499
|
+
continue
|
|
500
|
+
tt = _ts_type(_t(typ))
|
|
501
|
+
owner = at(rel, node.start_byte)
|
|
502
|
+
if tt and owner is not None:
|
|
503
|
+
self._extra(owner)[_t(pat)] = tt
|
|
504
|
+
for node in caps.get("newvar", []):
|
|
505
|
+
nm = node.child_by_field_name("name")
|
|
506
|
+
value = node.child_by_field_name("value")
|
|
507
|
+
if nm is None or nm.type != "identifier" or value is None:
|
|
508
|
+
continue
|
|
509
|
+
tt = _ts_type(_t(value.child_by_field_name("constructor")))
|
|
510
|
+
owner = at(rel, node.start_byte)
|
|
511
|
+
if not tt or owner is None:
|
|
512
|
+
continue
|
|
513
|
+
if owner.module:
|
|
514
|
+
self.modvars[(rel, _t(nm))] = tt
|
|
515
|
+
else:
|
|
516
|
+
self._extra(owner)[_t(nm)] = tt
|
|
517
|
+
for node in caps.get("destruct", []): # const { rawQuery, parseFilters } = clickhouse
|
|
518
|
+
pattern, value = node.child_by_field_name("name"), node.child_by_field_name("value")
|
|
519
|
+
owner = at(rel, node.start_byte)
|
|
520
|
+
if owner is None or value is None or value.end_byte - value.start_byte > 60:
|
|
521
|
+
continue
|
|
522
|
+
source = re.sub(r"\s+", "", _t(value))
|
|
523
|
+
table = self._extra(owner).setdefault("$alias", {})
|
|
524
|
+
for c in pattern.named_children:
|
|
525
|
+
if c.type == "shorthand_property_identifier_pattern":
|
|
526
|
+
table[_t(c)] = (source, _t(c))
|
|
527
|
+
elif c.type == "pair_pattern":
|
|
528
|
+
v = c.child_by_field_name("value")
|
|
529
|
+
if v is not None and v.type == "identifier":
|
|
530
|
+
table[_t(v)] = (source, _t(c.child_by_field_name("key")))
|
|
531
|
+
for node in caps.get("callvar", []): # const repo = container.get<Repo>(TOKEN), const svc = getService()
|
|
532
|
+
nm = node.child_by_field_name("name")
|
|
533
|
+
call = _unwrap(node.child_by_field_name("value"))
|
|
534
|
+
if nm is None or nm.type != "identifier" or call is None or call.type != "call_expression" or call.id in node_fn:
|
|
535
|
+
continue
|
|
536
|
+
targs = call.child_by_field_name("type_arguments")
|
|
537
|
+
tt = _ts_type(_t(targs.named_children[0])) if targs is not None and targs.named_children else ""
|
|
538
|
+
if not tt:
|
|
539
|
+
cf = _unwrap(call.child_by_field_name("function"))
|
|
540
|
+
if cf is None or cf.type not in ("identifier", "member_expression") or cf.end_byte - cf.start_byte > 60:
|
|
541
|
+
continue
|
|
542
|
+
tt = "call:" + re.sub(r"\s+", "", _t(cf))
|
|
543
|
+
owner = at(rel, node.start_byte)
|
|
544
|
+
if owner is None:
|
|
545
|
+
continue
|
|
546
|
+
if owner.module:
|
|
547
|
+
self.modvars.setdefault((rel, _t(nm)), tt)
|
|
548
|
+
else:
|
|
549
|
+
self._extra(owner).setdefault(_t(nm), tt)
|
|
550
|
+
|
|
551
|
+
# references and calls
|
|
552
|
+
names = self.fn_names
|
|
553
|
+
for node in caps.get("ref", []):
|
|
554
|
+
if node.id in reg_args:
|
|
555
|
+
continue
|
|
556
|
+
if node.type == "member_expression":
|
|
557
|
+
name = _t(node.child_by_field_name("property"))
|
|
558
|
+
if name not in names:
|
|
559
|
+
continue
|
|
560
|
+
obj = node.child_by_field_name("object")
|
|
561
|
+
if obj is None or obj.end_byte - obj.start_byte > 80:
|
|
562
|
+
continue
|
|
563
|
+
qual = _t(obj)
|
|
564
|
+
else:
|
|
565
|
+
name = _t(node)
|
|
566
|
+
if name not in names and name not in imports:
|
|
567
|
+
continue
|
|
568
|
+
qual = ""
|
|
569
|
+
# `export const repo = { find, save: saveImpl }`: repo.save is saveImpl
|
|
570
|
+
holder = node.parent if node.type == "shorthand_property_identifier" else \
|
|
571
|
+
node.parent.parent if node.parent is not None and node.parent.type == "pair" else None
|
|
572
|
+
if holder is not None and holder.type == "object":
|
|
573
|
+
obj_name = self._object_name(holder)
|
|
574
|
+
if obj_name:
|
|
575
|
+
key = name if node.type == "shorthand_property_identifier" else \
|
|
576
|
+
_t(node.parent.child_by_field_name("key")).strip("'\"`")
|
|
577
|
+
self.objrefs[(rel, obj_name)].setdefault(key, name)
|
|
578
|
+
owner = at(rel, node.start_byte)
|
|
579
|
+
if owner is not None:
|
|
580
|
+
owner.calls.append(("r", name, qual, node.start_point[0] + 1, -1))
|
|
581
|
+
for node in calls:
|
|
582
|
+
f = _unwrap(node.child_by_field_name("function"))
|
|
583
|
+
if f is None:
|
|
584
|
+
continue
|
|
585
|
+
if f.type == "identifier":
|
|
586
|
+
name, qual = _t(f), ""
|
|
587
|
+
if name not in names and name not in imports:
|
|
588
|
+
continue
|
|
589
|
+
elif f.type == "member_expression":
|
|
590
|
+
name = _t(f.child_by_field_name("property"))
|
|
591
|
+
obj = f.child_by_field_name("object")
|
|
592
|
+
if name in ("bind", "call", "apply"): # this._impl.bind(this), handler.call(this, req)
|
|
593
|
+
inner = _unwrap(obj)
|
|
594
|
+
if inner is not None and inner.type == "member_expression":
|
|
595
|
+
name, obj = _t(inner.child_by_field_name("property")), inner.child_by_field_name("object")
|
|
596
|
+
elif inner is not None and inner.type == "identifier":
|
|
597
|
+
name, obj = _t(inner), None
|
|
598
|
+
if name not in names:
|
|
599
|
+
continue
|
|
600
|
+
qual = self._qual(obj) if obj is not None else ""
|
|
601
|
+
else:
|
|
602
|
+
continue
|
|
603
|
+
owner = at(rel, node.start_byte)
|
|
604
|
+
if owner is None:
|
|
605
|
+
continue
|
|
606
|
+
args = node.child_by_field_name("arguments")
|
|
607
|
+
owner.calls.append(("c", name, qual, node.start_point[0] + 1, args.named_child_count if args is not None else -1))
|
|
608
|
+
for node in caps.get("new", []): # new Foo(...) runs Foo's constructor
|
|
609
|
+
ctor = node.child_by_field_name("constructor")
|
|
610
|
+
if ctor is not None and ctor.type == "identifier" and (_t(ctor) in self.classes or _t(ctor) in imports):
|
|
611
|
+
owner = at(rel, node.start_byte)
|
|
612
|
+
if owner is not None:
|
|
613
|
+
owner.calls.append(("c", "constructor", "new:" + _t(ctor), node.start_point[0] + 1, -1))
|
|
614
|
+
|
|
615
|
+
def _wraps_function(self, call: Node, local_names: set[str], depth: int) -> bool:
|
|
616
|
+
"""Does a call take a function: `cache(async () => ...)`, `withAuth(handler)`, `wrap(this._impl.bind(this))`?"""
|
|
617
|
+
f = _unwrap(call.child_by_field_name("function"))
|
|
618
|
+
if f is None or depth > 2:
|
|
619
|
+
return False
|
|
620
|
+
last = _t(f.child_by_field_name("property")) if f.type == "member_expression" else _t(f) if f.type == "identifier" else ""
|
|
621
|
+
if not last or last in IMMEDIATE:
|
|
622
|
+
return False
|
|
623
|
+
for a in call_args(call):
|
|
624
|
+
a = _unwrap(a)
|
|
625
|
+
if a is None:
|
|
626
|
+
continue
|
|
627
|
+
if a.type in INLINE_FUNCS or (a.type == "identifier" and _t(a) in local_names):
|
|
628
|
+
return True
|
|
629
|
+
if a.type == "call_expression":
|
|
630
|
+
af = _unwrap(a.child_by_field_name("function"))
|
|
631
|
+
if af is not None and af.type == "member_expression" and _t(af.child_by_field_name("property")) == "bind":
|
|
632
|
+
return True
|
|
633
|
+
if self._wraps_function(a, local_names, depth + 1):
|
|
634
|
+
return True
|
|
635
|
+
return False
|
|
636
|
+
|
|
637
|
+
@staticmethod
|
|
638
|
+
def _extra(fn: Fn) -> dict:
|
|
639
|
+
if fn.extra is None:
|
|
640
|
+
fn.extra = {}
|
|
641
|
+
return fn.extra
|
|
642
|
+
|
|
643
|
+
@staticmethod
|
|
644
|
+
def _qual(obj: Node | None) -> str:
|
|
645
|
+
obj = _unwrap(obj)
|
|
646
|
+
if obj is None:
|
|
647
|
+
return "?"
|
|
648
|
+
t = obj.type
|
|
649
|
+
if t in ("this", "super", "identifier"):
|
|
650
|
+
return _t(obj)
|
|
651
|
+
if t == "member_expression" and obj.end_byte - obj.start_byte < 80:
|
|
652
|
+
return re.sub(r"\s+|\?|!", "", _t(obj))
|
|
653
|
+
if t == "new_expression":
|
|
654
|
+
return "new:" + _t(obj.child_by_field_name("constructor")).split(".")[-1]
|
|
655
|
+
if t == "call_expression":
|
|
656
|
+
f = _unwrap(obj.child_by_field_name("function"))
|
|
657
|
+
if f is not None and f.type == "import":
|
|
658
|
+
return "?"
|
|
659
|
+
return "call:" + re.sub(r"\s+", "", _t(f)) if f is not None and f.end_byte - f.start_byte < 80 else "?"
|
|
660
|
+
return "?"
|
|
661
|
+
|
|
662
|
+
@staticmethod
|
|
663
|
+
def _object_name(obj: Node | None) -> str:
|
|
664
|
+
"""The name an object literal is bound to: `const repo = { ... }`, `export default { ... }`, `module.exports = { ... }`."""
|
|
665
|
+
if obj is None or obj.type != "object":
|
|
666
|
+
return ""
|
|
667
|
+
p = obj.parent
|
|
668
|
+
while p is not None and (p.type in UNWRAP_TYPES or p.type in ("arguments", "call_expression")):
|
|
669
|
+
p = p.parent # defineConfig({ ... }), router({ ... })
|
|
670
|
+
if p is None:
|
|
671
|
+
return ""
|
|
672
|
+
if p.type == "variable_declarator":
|
|
673
|
+
nm = p.child_by_field_name("name")
|
|
674
|
+
return _t(nm) if nm is not None and nm.type == "identifier" else ""
|
|
675
|
+
if p.type == "export_statement":
|
|
676
|
+
return "default"
|
|
677
|
+
if p.type == "assignment_expression":
|
|
678
|
+
left = _t(p.child_by_field_name("left"))
|
|
679
|
+
return "default" if left == "module.exports" else left.rpartition(".")[2]
|
|
680
|
+
if p.type == "pair":
|
|
681
|
+
return _t(p.child_by_field_name("key")).strip("'\"`")
|
|
682
|
+
return ""
|
|
683
|
+
|
|
684
|
+
def _export_statement(self, rel: str, node: Node, exports: dict[str, str], node_fn: dict[int, Fn]) -> None:
|
|
685
|
+
source = node.child_by_field_name("source")
|
|
686
|
+
is_default = any(c.type == "default" for c in node.children)
|
|
687
|
+
if source is not None:
|
|
688
|
+
target = self.resolver.resolve(rel, decode_string(source))
|
|
689
|
+
if target is None:
|
|
690
|
+
return
|
|
691
|
+
clause = next((c for c in node.named_children if c.type == "export_clause"), None)
|
|
692
|
+
if clause is None:
|
|
693
|
+
if any(c.type == "namespace_export" for c in node.named_children):
|
|
694
|
+
return
|
|
695
|
+
self.reexports[rel].append((None, target)) # export * from "./x"
|
|
696
|
+
else:
|
|
697
|
+
names = {}
|
|
698
|
+
for spec in clause.named_children:
|
|
699
|
+
if spec.type == "export_specifier":
|
|
700
|
+
nm, alias = spec.child_by_field_name("name"), spec.child_by_field_name("alias")
|
|
701
|
+
if nm is not None:
|
|
702
|
+
names[_t(alias or nm)] = _t(nm)
|
|
703
|
+
self.reexports[rel].append((names, target))
|
|
704
|
+
return
|
|
705
|
+
decl = node.child_by_field_name("declaration")
|
|
706
|
+
if decl is not None:
|
|
707
|
+
if decl.type in ("function_declaration", "generator_function_declaration"):
|
|
708
|
+
name = _t(decl.child_by_field_name("name")) or "default"
|
|
709
|
+
exports["default" if is_default else name] = name
|
|
710
|
+
elif decl.type in CLASS_TYPES:
|
|
711
|
+
name = _t(decl.child_by_field_name("name"))
|
|
712
|
+
if name:
|
|
713
|
+
exports["default" if is_default else name] = name
|
|
714
|
+
elif decl.type in ("lexical_declaration", "variable_declaration"):
|
|
715
|
+
for d in decl.named_children:
|
|
716
|
+
if d.type == "variable_declarator":
|
|
717
|
+
nm = d.child_by_field_name("name")
|
|
718
|
+
if nm is not None and nm.type == "identifier":
|
|
719
|
+
exports[_t(nm)] = _t(nm)
|
|
720
|
+
return
|
|
721
|
+
if is_default:
|
|
722
|
+
value = _unwrap(node.child_by_field_name("value"))
|
|
723
|
+
if value is None:
|
|
724
|
+
return
|
|
725
|
+
if value.type == "identifier":
|
|
726
|
+
exports["default"] = _t(value)
|
|
727
|
+
elif value.id in node_fn:
|
|
728
|
+
exports["default"] = node_fn[value.id].name
|
|
729
|
+
self.top[rel].setdefault(node_fn[value.id].name, node_fn[value.id])
|
|
730
|
+
elif value.type in CLASS_TYPES:
|
|
731
|
+
exports["default"] = _t(value.child_by_field_name("name"))
|
|
732
|
+
elif value.type == "object":
|
|
733
|
+
exports["default"] = "default"
|
|
734
|
+
elif value.type == "call_expression": # export default withAuth(handler)
|
|
735
|
+
for a in call_args(value):
|
|
736
|
+
a = _unwrap(a)
|
|
737
|
+
if a is not None and a.type == "identifier":
|
|
738
|
+
exports.setdefault("default", _t(a))
|
|
739
|
+
elif a is not None and a.id in node_fn:
|
|
740
|
+
exports.setdefault("default", node_fn[a.id].name)
|
|
741
|
+
self.top[rel].setdefault(node_fn[a.id].name, node_fn[a.id])
|
|
742
|
+
exports.setdefault("default", "default")
|
|
743
|
+
return
|
|
744
|
+
clause = next((c for c in node.named_children if c.type == "export_clause"), None)
|
|
745
|
+
if clause is not None:
|
|
746
|
+
for spec in clause.named_children:
|
|
747
|
+
if spec.type == "export_specifier":
|
|
748
|
+
nm, alias = spec.child_by_field_name("name"), spec.child_by_field_name("alias")
|
|
749
|
+
if nm is not None:
|
|
750
|
+
exports[_t(alias or nm)] = _t(nm)
|
|
751
|
+
|
|
752
|
+
def _require(self, rel: str, call: Node, imports: dict) -> None:
|
|
753
|
+
args = call_args(call)
|
|
754
|
+
if len(args) != 1 or args[0].type != "string":
|
|
755
|
+
return
|
|
756
|
+
target = self.resolver.resolve(rel, decode_string(args[0]))
|
|
757
|
+
decl = call.parent
|
|
758
|
+
while decl is not None and decl.type in UNWRAP_TYPES:
|
|
759
|
+
decl = decl.parent
|
|
760
|
+
if decl is None or decl.type != "variable_declarator":
|
|
761
|
+
return
|
|
762
|
+
self._bind_import(decl.child_by_field_name("name"), target, imports, default="*")
|
|
763
|
+
|
|
764
|
+
@staticmethod
|
|
765
|
+
def _bind_import(name: Node | None, target: str | None, table: dict, default: str) -> None:
|
|
766
|
+
if name is None:
|
|
767
|
+
return
|
|
768
|
+
if name.type == "identifier":
|
|
769
|
+
table[_t(name)] = (target, default)
|
|
770
|
+
elif name.type == "object_pattern":
|
|
771
|
+
for c in name.named_children:
|
|
772
|
+
if c.type == "shorthand_property_identifier_pattern":
|
|
773
|
+
table[_t(c)] = (target, _t(c))
|
|
774
|
+
elif c.type == "pair_pattern":
|
|
775
|
+
v = c.child_by_field_name("value")
|
|
776
|
+
if v is not None and v.type == "identifier":
|
|
777
|
+
table[_t(v)] = (target, _t(c.child_by_field_name("key")))
|
|
778
|
+
|
|
779
|
+
def _dynamic_import(self, rel: str, call: Node, at) -> None:
|
|
780
|
+
"""`const { handler } = await import("./x")` binds names inside the function that does it."""
|
|
781
|
+
args = call_args(call)
|
|
782
|
+
if len(args) != 1 or args[0].type not in ("string", "template_string"):
|
|
783
|
+
return
|
|
784
|
+
target = self.resolver.resolve(rel, decode_string(args[0]))
|
|
785
|
+
if target is None:
|
|
786
|
+
return
|
|
787
|
+
owner = at(rel, call.start_byte)
|
|
788
|
+
if owner is None:
|
|
789
|
+
return
|
|
790
|
+
p = call.parent
|
|
791
|
+
while p is not None and p.type in UNWRAP_TYPES:
|
|
792
|
+
p = p.parent
|
|
793
|
+
table = self._extra(owner).setdefault("$imp", {})
|
|
794
|
+
if p is not None and p.type == "variable_declarator":
|
|
795
|
+
self._bind_import(p.child_by_field_name("name"), target, table, default="*")
|
|
796
|
+
elif p is not None and p.type == "member_expression": # (await import("./x")).default(...)
|
|
797
|
+
owner.calls.append(("c", _t(p.child_by_field_name("property")), "import:" + target, call.start_point[0] + 1, -1))
|
|
798
|
+
else:
|
|
799
|
+
table.setdefault("$lazy", []).append(target) # import("./x").then(...), lazy(() => import("./x"))
|
|
800
|
+
|
|
801
|
+
# ---- entry points -----------------------------------------------------------------
|
|
802
|
+
def _handler(self, rel: str, node: Node | None, owner: Fn | None, refs: list, targets: list, seen: set,
|
|
803
|
+
node_fn: dict[int, Fn], depth: int = 0) -> None:
|
|
804
|
+
node = _unwrap(node)
|
|
805
|
+
if node is None or depth > 6:
|
|
806
|
+
return
|
|
807
|
+
line = node.start_point[0] + 1
|
|
808
|
+
t = node.type
|
|
809
|
+
seen.add(node.id)
|
|
810
|
+
if t in ("identifier", "shorthand_property_identifier"):
|
|
811
|
+
refs.append(("r", _t(node), "", line, -1))
|
|
812
|
+
elif t == "member_expression":
|
|
813
|
+
obj = node.child_by_field_name("object")
|
|
814
|
+
if obj is not None and obj.end_byte - obj.start_byte < 80:
|
|
815
|
+
refs.append(("r", _t(node.child_by_field_name("property")), self._qual(obj), line, -1))
|
|
816
|
+
elif t in INLINE_FUNCS:
|
|
817
|
+
fn = node_fn.get(node.id)
|
|
818
|
+
if fn is None:
|
|
819
|
+
fn = self.add_fn(Fn(rel, self.name, "<fn>", owner.symbol if owner and not owner.module else "",
|
|
820
|
+
owner.container if owner else "", node, inline=True, test=owner.test if owner else False))
|
|
821
|
+
fn.extra = {}
|
|
822
|
+
node_fn[node.id] = fn
|
|
823
|
+
targets.append(fn)
|
|
824
|
+
elif t == "call_expression":
|
|
825
|
+
f = _unwrap(node.child_by_field_name("function"))
|
|
826
|
+
if f is not None and f.type == "import":
|
|
827
|
+
args = call_args(node)
|
|
828
|
+
if len(args) == 1 and args[0].type == "string":
|
|
829
|
+
target = self.resolver.resolve(rel, decode_string(args[0]))
|
|
830
|
+
if target is not None:
|
|
831
|
+
refs.append(("r", "default", "import:" + target, line, -1))
|
|
832
|
+
return
|
|
833
|
+
if f is not None and f.type in ("identifier", "member_expression"):
|
|
834
|
+
self._handler(rel, f, owner, refs, targets, seen, node_fn, depth + 1)
|
|
835
|
+
for a in call_args(node):
|
|
836
|
+
self._handler(rel, a, owner, refs, targets, seen, node_fn, depth + 1)
|
|
837
|
+
elif t == "array":
|
|
838
|
+
for a in node.named_children:
|
|
839
|
+
self._handler(rel, a, owner, refs, targets, seen, node_fn, depth + 1)
|
|
840
|
+
elif t == "object":
|
|
841
|
+
for v in object_pairs(node).values():
|
|
842
|
+
self._handler(rel, v, owner, refs, targets, seen, node_fn, depth + 1)
|
|
843
|
+
for m in node.named_children:
|
|
844
|
+
if m.type == "method_definition" and m.id in node_fn:
|
|
845
|
+
targets.append(node_fn[m.id])
|
|
846
|
+
|
|
847
|
+
@staticmethod
|
|
848
|
+
def _pos_kw(call: Node) -> tuple[list[Node], dict[str, Node]]:
|
|
849
|
+
pos, kw = [], {}
|
|
850
|
+
for a in call_args(call):
|
|
851
|
+
u = _unwrap(a)
|
|
852
|
+
if u is not None and u.type == "object":
|
|
853
|
+
for k, v in object_pairs(u).items():
|
|
854
|
+
kw.setdefault(k, v)
|
|
855
|
+
for m in u.named_children:
|
|
856
|
+
if m.type == "method_definition":
|
|
857
|
+
kw.setdefault(_t(m.child_by_field_name("name")), m)
|
|
858
|
+
pos.append(u if u is not None else a)
|
|
859
|
+
return pos, kw
|
|
860
|
+
|
|
861
|
+
def _registration(self, rel: str, node: Node, f: Node, last: str, at, node_fn: dict[int, Fn], reg_args: set[int],
|
|
862
|
+
is_test: bool) -> bool:
|
|
863
|
+
chain = chain_text(f)
|
|
864
|
+
owner = at(rel, node.start_byte)
|
|
865
|
+
pos, kw = self._pos_kw(node)
|
|
866
|
+
line = node.start_point[0] + 1
|
|
867
|
+
root = _chain_root(f)
|
|
868
|
+
key = (rel, root)
|
|
869
|
+
if last in self.mount_names and pos:
|
|
870
|
+
# app.use("/prefix", router), app.route("/prefix", sub), fastify.register(plugin, { prefix })
|
|
871
|
+
prefix = ""
|
|
872
|
+
first = pos[0]
|
|
873
|
+
rest = pos
|
|
874
|
+
if first.type in ("string", "template_string"):
|
|
875
|
+
prefix = self.ix.consts.eval(self.name, rel, _t(first))[0]
|
|
876
|
+
rest = pos[1:]
|
|
877
|
+
elif "prefix" in kw:
|
|
878
|
+
prefix = self.ix.consts.eval(self.name, rel, _t(kw["prefix"]))[0]
|
|
879
|
+
for a in rest:
|
|
880
|
+
a = _unwrap(a)
|
|
881
|
+
if a is None:
|
|
882
|
+
continue
|
|
883
|
+
if a.type == "identifier":
|
|
884
|
+
self.pending_mounts.append((key, prefix, rel, ("", _t(a)), owner))
|
|
885
|
+
elif a.type == "call_expression":
|
|
886
|
+
cf = _unwrap(a.child_by_field_name("function"))
|
|
887
|
+
if cf is not None and cf.type == "identifier" and _t(cf) == "require" and call_args(a):
|
|
888
|
+
spec = call_args(a)[0]
|
|
889
|
+
target = self.resolver.resolve(rel, decode_string(spec)) if spec.type == "string" else None
|
|
890
|
+
if target is not None:
|
|
891
|
+
self.pending_mounts.append((key, prefix, rel, (target, "default"), owner))
|
|
892
|
+
elif cf is not None and cf.type in ("identifier", "member_expression") and owner is not None:
|
|
893
|
+
name = _t(cf) if cf.type == "identifier" else _t(cf.child_by_field_name("property"))
|
|
894
|
+
qual = "" if cf.type == "identifier" else self._qual(cf.child_by_field_name("object"))
|
|
895
|
+
self.ix.nests.append((owner, prefix, ("c", name, qual, line, -1)))
|
|
896
|
+
if a.type == "identifier" and owner is not None: # a plugin function: fastify.register(routes, { prefix })
|
|
897
|
+
self.ix.nests.append((owner, prefix, ("r", _t(a), "", line, -1)))
|
|
898
|
+
added = False
|
|
899
|
+
for rx, rule in self.call_rules:
|
|
900
|
+
if last not in rule.get("names", ()):
|
|
901
|
+
continue
|
|
902
|
+
m = rx.search(chain)
|
|
903
|
+
if not m:
|
|
904
|
+
continue
|
|
905
|
+
rpos, rkw = pos, kw
|
|
906
|
+
path_from_chain = None
|
|
907
|
+
if rule["kind"] == "http" and rule.get("path", 0) == 0 and (not pos or pos[0].type not in ("string", "template_string",
|
|
908
|
+
"identifier", "binary_expression", "member_expression")):
|
|
909
|
+
# router.route("/x").get(handler)
|
|
910
|
+
inner = _unwrap(f.child_by_field_name("object")) if f.type == "member_expression" else None
|
|
911
|
+
while inner is not None and inner.type == "call_expression":
|
|
912
|
+
cf = _unwrap(inner.child_by_field_name("function"))
|
|
913
|
+
if cf is not None and cf.type == "member_expression" and _t(cf.child_by_field_name("property")) == "route":
|
|
914
|
+
a = call_args(inner)
|
|
915
|
+
if a and a[0].type in ("string", "template_string"):
|
|
916
|
+
path_from_chain = a[0]
|
|
917
|
+
break
|
|
918
|
+
inner = _unwrap(cf.child_by_field_name("object")) if cf is not None and cf.type == "member_expression" else None
|
|
919
|
+
if path_from_chain is None:
|
|
920
|
+
continue
|
|
921
|
+
rpos = [path_from_chain] + pos
|
|
922
|
+
hit = apply_rule(self, rel, rule, m, rpos, rkw, chain_text=chain)
|
|
923
|
+
if hit is None:
|
|
924
|
+
continue
|
|
925
|
+
refs, targets, seen = [], [], set()
|
|
926
|
+
for h in hit.handlers:
|
|
927
|
+
self._handler(rel, h, owner, refs, targets, seen, node_fn)
|
|
928
|
+
if rule.get("exports_of_kwargs"):
|
|
929
|
+
for k in rule["exports_of_kwargs"]:
|
|
930
|
+
if k in kw:
|
|
931
|
+
self._exports_of(rel, kw[k], rule["kind"], line, owner)
|
|
932
|
+
continue
|
|
933
|
+
if not refs and not targets:
|
|
934
|
+
continue
|
|
935
|
+
self._note_wrapper(owner, hit.kind, refs, rpos, rule.get("path", 0) if hit.kind == "http" else rule.get("name"),
|
|
936
|
+
hit.method)
|
|
937
|
+
name = hit.name
|
|
938
|
+
if rule.get("name_from") == "key":
|
|
939
|
+
name = self._binding_name(node)
|
|
940
|
+
if not name and hit.kind != "http" and not refs and all(t.inline and not t.symbol for t in targets):
|
|
941
|
+
name = f"{rel}:{line}" # an anonymous handler at module level: named by where it is
|
|
942
|
+
if hit.kind == "http" and rule.get("method") and hit.path is None:
|
|
943
|
+
name = f"{rule['method']} {name}" if name else ""
|
|
944
|
+
e = Entry(hit.kind, name, rel, line, targets=targets, pending=[(owner, r) for r in refs] if owner is not None else [],
|
|
945
|
+
decl=owner if owner is not None and not owner.module else None, path=hit.path, method=hit.method)
|
|
946
|
+
if rule.get("tag"):
|
|
947
|
+
e.tag = rule["tag"]
|
|
948
|
+
self.ix.entries.append(e)
|
|
949
|
+
reg_args.update(seen)
|
|
950
|
+
added |= bool(targets)
|
|
951
|
+
if hit.kind == "http" and (owner is None or owner.module) and root:
|
|
952
|
+
sep = rule.get("join", "/")
|
|
953
|
+
self.entry_owner.append((e, self._router_key(node, key, sep), sep))
|
|
954
|
+
break
|
|
955
|
+
return added
|
|
956
|
+
|
|
957
|
+
@staticmethod
|
|
958
|
+
def _param_owner(owner: Fn | None, name: str) -> tuple[Fn, int] | None:
|
|
959
|
+
"""The enclosing function that has `name` as a parameter, and its index."""
|
|
960
|
+
f = owner
|
|
961
|
+
while f is not None and not f.module:
|
|
962
|
+
params = f.extra.get("$params") if isinstance(f.extra, dict) else None
|
|
963
|
+
if params and name in params:
|
|
964
|
+
return f, params.index(name)
|
|
965
|
+
f = f.lex
|
|
966
|
+
return None
|
|
967
|
+
|
|
968
|
+
def _note_wrapper(self, owner: Fn | None, kind: str, refs: list, pos: list[Node], name_index, method: str) -> None:
|
|
969
|
+
"""A registration whose handler is a parameter of the enclosing function makes that function a registration too."""
|
|
970
|
+
by_fn: dict[int, tuple[Fn, set[int]]] = {}
|
|
971
|
+
for r in refs:
|
|
972
|
+
hit = self._param_owner(owner, r[1]) if not r[2] else None
|
|
973
|
+
if hit is not None:
|
|
974
|
+
by_fn.setdefault(hit[0].id, (hit[0], set()))[1].add(hit[1])
|
|
975
|
+
for fn, indexes in by_fn.values():
|
|
976
|
+
name_at = -1
|
|
977
|
+
if isinstance(name_index, int) and 0 <= name_index < len(pos) and pos[name_index].type == "identifier":
|
|
978
|
+
params = fn.extra.get("$params") or []
|
|
979
|
+
text = _t(pos[name_index])
|
|
980
|
+
name_at = params.index(text) if text in params else -1
|
|
981
|
+
spec = (kind, tuple(sorted(indexes - {name_at})), name_at, method)
|
|
982
|
+
if spec[1] and spec not in self.reg_wrappers[fn.id]:
|
|
983
|
+
self.reg_wrappers[fn.id].append(spec)
|
|
984
|
+
if fn not in self.wrapper_names[fn.name]:
|
|
985
|
+
self.wrapper_names[fn.name].append(fn)
|
|
986
|
+
|
|
987
|
+
def _arg_call(self, rel: str, node: Node, f: Node, last: str, at, node_fn: dict[int, Fn]) -> bool:
|
|
988
|
+
"""Remember a call that passes a function, in case its callee turns out to be a registration wrapper."""
|
|
989
|
+
args = call_args(node)
|
|
990
|
+
if not args or len(args) > 6:
|
|
991
|
+
return False
|
|
992
|
+
owner = at(rel, node.start_byte)
|
|
993
|
+
if owner is None:
|
|
994
|
+
return False
|
|
995
|
+
line = node.start_point[0] + 1
|
|
996
|
+
info: list = []
|
|
997
|
+
useful = added = False
|
|
998
|
+
for a in args:
|
|
999
|
+
u = _unwrap(a)
|
|
1000
|
+
if u is None:
|
|
1001
|
+
info.append(None)
|
|
1002
|
+
elif u.type == "identifier":
|
|
1003
|
+
info.append(("r", _t(u), "", line, -1))
|
|
1004
|
+
useful = True
|
|
1005
|
+
elif u.type == "member_expression" and u.end_byte - u.start_byte < 80:
|
|
1006
|
+
info.append(("r", _t(u.child_by_field_name("property")), self._qual(u.child_by_field_name("object")), line, -1))
|
|
1007
|
+
elif u.type in INLINE_FUNCS:
|
|
1008
|
+
fn = node_fn.get(u.id)
|
|
1009
|
+
if fn is None:
|
|
1010
|
+
fn = self.add_fn(Fn(rel, self.name, "<fn>", owner.symbol if not owner.module else "", owner.container, u,
|
|
1011
|
+
inline=True, test=owner.test))
|
|
1012
|
+
fn.extra = {}
|
|
1013
|
+
node_fn[u.id] = fn
|
|
1014
|
+
added = True
|
|
1015
|
+
info.append(fn)
|
|
1016
|
+
useful = True
|
|
1017
|
+
else:
|
|
1018
|
+
info.append(None)
|
|
1019
|
+
if useful:
|
|
1020
|
+
qual = self._qual(f.child_by_field_name("object")) if f.type == "member_expression" else ""
|
|
1021
|
+
texts = [_t(a)[:80] if a.end_byte - a.start_byte < 200 else "" for a in args]
|
|
1022
|
+
self.argcalls[last].append((owner, rel, line, qual, info, texts))
|
|
1023
|
+
return added
|
|
1024
|
+
|
|
1025
|
+
def _wrapper_entries(self) -> None:
|
|
1026
|
+
done: set[tuple] = set()
|
|
1027
|
+
for _ in range(4):
|
|
1028
|
+
fresh = False
|
|
1029
|
+
for wname, fns in list(self.wrapper_names.items()):
|
|
1030
|
+
for call in self.argcalls.get(wname, ()):
|
|
1031
|
+
owner, rel, line, qual, info, texts = call
|
|
1032
|
+
try:
|
|
1033
|
+
resolved = self.resolve(owner, ("c", wname, qual, line, -1))
|
|
1034
|
+
except Exception:
|
|
1035
|
+
resolved = []
|
|
1036
|
+
for wfn in fns:
|
|
1037
|
+
if wfn not in resolved:
|
|
1038
|
+
continue
|
|
1039
|
+
for spec in self.reg_wrappers[wfn.id]:
|
|
1040
|
+
key = (id(call), wfn.id, spec)
|
|
1041
|
+
if key in done:
|
|
1042
|
+
continue
|
|
1043
|
+
done.add(key)
|
|
1044
|
+
kind, indexes, name_at, method = spec
|
|
1045
|
+
targets, pending = [], []
|
|
1046
|
+
for i in indexes:
|
|
1047
|
+
a = info[i] if i < len(info) else None
|
|
1048
|
+
if isinstance(a, Fn):
|
|
1049
|
+
targets.append(a)
|
|
1050
|
+
elif a is not None:
|
|
1051
|
+
pending.append((owner, a))
|
|
1052
|
+
up = self._param_owner(owner, a[1]) if not a[2] else None
|
|
1053
|
+
if up is not None: # a wrapper around the wrapper
|
|
1054
|
+
up_name = -1
|
|
1055
|
+
if 0 <= name_at < len(info) and info[name_at] is not None and not isinstance(info[name_at], Fn):
|
|
1056
|
+
hit = self._param_owner(owner, info[name_at][1])
|
|
1057
|
+
up_name = hit[1] if hit is not None and hit[0] is up[0] else -1
|
|
1058
|
+
up_spec = (kind, (up[1],), up_name, method)
|
|
1059
|
+
if up_spec not in self.reg_wrappers[up[0].id]:
|
|
1060
|
+
self.reg_wrappers[up[0].id].append(up_spec)
|
|
1061
|
+
if up[0] not in self.wrapper_names[up[0].name]:
|
|
1062
|
+
self.wrapper_names[up[0].name].append(up[0])
|
|
1063
|
+
fresh = True
|
|
1064
|
+
if not targets and not pending:
|
|
1065
|
+
continue
|
|
1066
|
+
text = texts[name_at].strip() if 0 <= name_at < len(texts) else ""
|
|
1067
|
+
name = text[1:-1] if len(text) > 1 and text[0] in "'\"`" and text[-1] == text[0] else text
|
|
1068
|
+
if kind == "http":
|
|
1069
|
+
name = _http_name(method, name) if name else ""
|
|
1070
|
+
self.ix.entries.append(Entry(kind, name, rel, line, targets=targets, pending=pending))
|
|
1071
|
+
if not fresh:
|
|
1072
|
+
break
|
|
1073
|
+
|
|
1074
|
+
def _router_key(self, node: Node, key: tuple[str, str], sep: str) -> tuple[str, str]:
|
|
1075
|
+
"""For a tRPC procedure: the router object it sits in (`export const userRouter = router({ ... })`)."""
|
|
1076
|
+
if sep != ".":
|
|
1077
|
+
return key
|
|
1078
|
+
p = node.parent
|
|
1079
|
+
while p is not None and p.type != "program":
|
|
1080
|
+
if p.type == "variable_declarator":
|
|
1081
|
+
return (key[0], _t(p.child_by_field_name("name")))
|
|
1082
|
+
if p.type == "export_statement" and any(c.type == "default" for c in p.children):
|
|
1083
|
+
return (key[0], "default")
|
|
1084
|
+
p = p.parent
|
|
1085
|
+
return (key[0], "")
|
|
1086
|
+
|
|
1087
|
+
@staticmethod
|
|
1088
|
+
def _is_default_export(node: Node) -> bool:
|
|
1089
|
+
p = node.parent
|
|
1090
|
+
while p is not None and p.type in UNWRAP_TYPES:
|
|
1091
|
+
p = p.parent
|
|
1092
|
+
return p is not None and p.type == "export_statement" and any(c.type == "default" for c in p.children)
|
|
1093
|
+
|
|
1094
|
+
@staticmethod
|
|
1095
|
+
def _binding_name(node: Node) -> str:
|
|
1096
|
+
"""`list: procedure.query(...)` -> list; `export const list = procedure.query(...)` -> list."""
|
|
1097
|
+
p = node.parent
|
|
1098
|
+
while p is not None and (p.type in UNWRAP_TYPES or p.type in ("member_expression", "call_expression", "arguments")):
|
|
1099
|
+
p = p.parent
|
|
1100
|
+
if p is not None and p.type == "pair":
|
|
1101
|
+
return _t(p.child_by_field_name("key")).strip("'\"`")
|
|
1102
|
+
if p is not None and p.type == "variable_declarator":
|
|
1103
|
+
return _t(p.child_by_field_name("name"))
|
|
1104
|
+
return ""
|
|
1105
|
+
|
|
1106
|
+
def _new(self, rel: str, node: Node, ctor: Node, at, node_fn: dict[int, Fn], reg_args: set[int]) -> bool:
|
|
1107
|
+
text = _t(ctor)
|
|
1108
|
+
owner = at(rel, node.start_byte)
|
|
1109
|
+
pos, kw = self._pos_kw(node)
|
|
1110
|
+
for rx, rule in self.new_rules:
|
|
1111
|
+
m = rx.search(text)
|
|
1112
|
+
if not m:
|
|
1113
|
+
continue
|
|
1114
|
+
hit = apply_rule(self, rel, rule, m, pos, kw, chain_text=text)
|
|
1115
|
+
if hit is None:
|
|
1116
|
+
continue
|
|
1117
|
+
refs, targets, seen = [], [], set()
|
|
1118
|
+
for h in hit.handlers:
|
|
1119
|
+
self._handler(rel, h, owner, refs, targets, seen, node_fn)
|
|
1120
|
+
if not refs and not targets:
|
|
1121
|
+
continue
|
|
1122
|
+
self._note_wrapper(owner, hit.kind, refs, pos, rule.get("name"), "")
|
|
1123
|
+
e = Entry(hit.kind, hit.name, rel, node.start_point[0] + 1, targets=targets,
|
|
1124
|
+
pending=[(owner, r) for r in refs] if owner is not None else [])
|
|
1125
|
+
self.ix.entries.append(e)
|
|
1126
|
+
reg_args.update(seen)
|
|
1127
|
+
return bool(targets)
|
|
1128
|
+
return False
|
|
1129
|
+
|
|
1130
|
+
def _exports_of(self, rel: str, node: Node, kind: str, line: int, owner: Fn | None) -> None:
|
|
1131
|
+
"""Temporal: `Worker.create({ activities, workflowsPath: require.resolve("./workflows") })`."""
|
|
1132
|
+
node = _unwrap(node)
|
|
1133
|
+
if node is None:
|
|
1134
|
+
return
|
|
1135
|
+
target, local = None, ""
|
|
1136
|
+
if node.type in ("identifier", "shorthand_property_identifier"):
|
|
1137
|
+
imp = self.imports.get(rel, {}).get(_t(node))
|
|
1138
|
+
if imp is not None and imp[0] is not None:
|
|
1139
|
+
target, local = imp[0], imp[1]
|
|
1140
|
+
elif node.type == "call_expression":
|
|
1141
|
+
args = call_args(node)
|
|
1142
|
+
if args and args[0].type == "string":
|
|
1143
|
+
target, local = self.resolver.resolve(rel, decode_string(args[0])), "*"
|
|
1144
|
+
elif node.type == "object" and owner is not None:
|
|
1145
|
+
for k, v in object_pairs(node).items():
|
|
1146
|
+
v = _unwrap(v)
|
|
1147
|
+
if v is not None and v.type in ("identifier", "shorthand_property_identifier"):
|
|
1148
|
+
self.ix.entries.append(Entry(kind, k, rel, line, pending=[(owner, ("r", _t(v), "", line, -1))]))
|
|
1149
|
+
if target is not None:
|
|
1150
|
+
self.pending_exports.append((kind, target, line, None, rel, local))
|
|
1151
|
+
|
|
1152
|
+
@staticmethod
|
|
1153
|
+
def _decorators(node: Node) -> list[Node]:
|
|
1154
|
+
out = [c for c in node.children if c.type == "decorator"]
|
|
1155
|
+
prev = node.prev_named_sibling
|
|
1156
|
+
while prev is not None and prev.type in ("decorator", "comment"):
|
|
1157
|
+
if prev.type == "decorator":
|
|
1158
|
+
out.append(prev)
|
|
1159
|
+
prev = prev.prev_named_sibling
|
|
1160
|
+
return out
|
|
1161
|
+
|
|
1162
|
+
@staticmethod
|
|
1163
|
+
def _dec_parts(dec: Node) -> tuple[str, list[Node], dict[str, Node]]:
|
|
1164
|
+
inner = dec.named_children[0] if dec.named_children else None
|
|
1165
|
+
if inner is None:
|
|
1166
|
+
return "", [], {}
|
|
1167
|
+
if inner.type == "call_expression":
|
|
1168
|
+
pos, kw = TypeScript._pos_kw(inner)
|
|
1169
|
+
return _t(inner.child_by_field_name("function")), pos, kw
|
|
1170
|
+
return _t(inner), [], {}
|
|
1171
|
+
|
|
1172
|
+
def _class_entries(self, rel: str, node: Node, cls: str, decs: list[Node], node_fn: dict[int, Fn]) -> None:
|
|
1173
|
+
prefix = ""
|
|
1174
|
+
class_rules: list[tuple[dict, str]] = []
|
|
1175
|
+
for dec in decs:
|
|
1176
|
+
dotted, pos, kw = self._dec_parts(dec)
|
|
1177
|
+
if dotted.split(".")[-1] in self.class_prefix:
|
|
1178
|
+
if pos and pos[0].type in ("string", "template_string", "identifier", "member_expression"):
|
|
1179
|
+
prefix = self.ix.consts.eval(self.name, rel, _t(pos[0]))[0]
|
|
1180
|
+
elif "path" in kw:
|
|
1181
|
+
prefix = self.ix.consts.eval(self.name, rel, _t(kw["path"]))[0]
|
|
1182
|
+
for rx, rule in self.dec_rules:
|
|
1183
|
+
m = rx.search(dotted)
|
|
1184
|
+
if rule.get("on") == "class" and m:
|
|
1185
|
+
hit = apply_rule(self, rel, rule, m, pos, kw, default_name=cls)
|
|
1186
|
+
class_rules.append((rule, (hit.name if hit else cls) or cls))
|
|
1187
|
+
body = node.child_by_field_name("body")
|
|
1188
|
+
if body is None:
|
|
1189
|
+
return
|
|
1190
|
+
info = self.class_info.get((rel, cls), {})
|
|
1191
|
+
bases = [info.get("extends", "")] + info.get("implements", [])
|
|
1192
|
+
for member in body.named_children:
|
|
1193
|
+
fn = node_fn.get(member.id)
|
|
1194
|
+
if fn is None and member.type == "public_field_definition":
|
|
1195
|
+
value = _unwrap(member.child_by_field_name("value"))
|
|
1196
|
+
fn = node_fn.get(value.id) if value is not None else None
|
|
1197
|
+
if fn is None:
|
|
1198
|
+
continue
|
|
1199
|
+
line = member.start_point[0] + 1
|
|
1200
|
+
for rule, name in class_rules:
|
|
1201
|
+
if re.search(rule.get("via", "$^"), fn.name):
|
|
1202
|
+
self.ix.entries.append(Entry(rule["kind"], name if rule.get("via_name") is None else f"{name}.{fn.name}",
|
|
1203
|
+
rel, line, targets=[fn]))
|
|
1204
|
+
for rx, rule in self.dec_rules:
|
|
1205
|
+
if rule.get("on") == "extends" and any(b and rx.search(b) for b in bases) and re.search(rule.get("via", "$^"), fn.name):
|
|
1206
|
+
self.ix.entries.append(Entry(rule["kind"], cls, rel, line, targets=[fn]))
|
|
1207
|
+
for dec in self._decorators(member):
|
|
1208
|
+
dotted, pos, kw = self._dec_parts(dec)
|
|
1209
|
+
for rx, rule in self.dec_rules:
|
|
1210
|
+
if rule.get("on") in ("class", "extends"):
|
|
1211
|
+
continue
|
|
1212
|
+
m = rx.search(dotted)
|
|
1213
|
+
if not m:
|
|
1214
|
+
continue
|
|
1215
|
+
hit = apply_rule(self, rel, rule, m, pos, kw, default_name=fn.symbol)
|
|
1216
|
+
if hit is None:
|
|
1217
|
+
continue
|
|
1218
|
+
name = hit.name
|
|
1219
|
+
if hit.kind == "http":
|
|
1220
|
+
if hit.path is not None:
|
|
1221
|
+
name = _http_name(hit.method, "/" + _join_path(prefix, hit.path).strip("/"))
|
|
1222
|
+
else:
|
|
1223
|
+
name = f"{rule.get('method', 'ANY')} {fn.symbol}"
|
|
1224
|
+
self.ix.entries.append(Entry(hit.kind, name or fn.symbol, rel, line, targets=[fn]))
|
|
1225
|
+
break
|
|
1226
|
+
|
|
1227
|
+
def _file_entries(self, rel: str, src: bytes, root: Node, exports: dict[str, str], node_fn: dict[int, Fn], mod: Fn,
|
|
1228
|
+
is_test: bool) -> bool:
|
|
1229
|
+
added = False
|
|
1230
|
+
rules = [(rx.search(rel), rule) for rx, rule in self.file_rules]
|
|
1231
|
+
rules = [(m, rule) for m, rule in rules if m]
|
|
1232
|
+
if self.directive_rules and src[:1] in (b"'", b'"', b"/", b" ", b"\n", b"\r", b"\t"):
|
|
1233
|
+
directive = _directive(src).decode("utf-8", "replace")
|
|
1234
|
+
if directive:
|
|
1235
|
+
rules += [(None, rule) for rx, rule in self.directive_rules if rx.search(directive)]
|
|
1236
|
+
for m, rule in rules:
|
|
1237
|
+
want = re.compile(rule.get("exports", "^default$"))
|
|
1238
|
+
route = ""
|
|
1239
|
+
if m is not None and m.lastindex:
|
|
1240
|
+
route = "/" + "/".join(s for s in (m.group(1) or "").split("/")
|
|
1241
|
+
if s and not (s.startswith("(") and s.endswith(")")) and not s.startswith("@") and s != "index")
|
|
1242
|
+
for exported, local in list(exports.items()):
|
|
1243
|
+
if not want.search(exported):
|
|
1244
|
+
continue
|
|
1245
|
+
method = rule.get("method", "")
|
|
1246
|
+
method = exported if method == "$export" else method
|
|
1247
|
+
if rule["kind"] == "http":
|
|
1248
|
+
name = f"{method} {exported}" if m is None else _http_name(method, route)
|
|
1249
|
+
else:
|
|
1250
|
+
name = rule.get("name", "") or exported
|
|
1251
|
+
line = 1
|
|
1252
|
+
targets, refs = [], []
|
|
1253
|
+
fn = self.top[rel].get(local)
|
|
1254
|
+
if fn is not None:
|
|
1255
|
+
targets.append(fn)
|
|
1256
|
+
line = fn.start
|
|
1257
|
+
else:
|
|
1258
|
+
decl = self._top_declarator(root, local)
|
|
1259
|
+
if decl is not None:
|
|
1260
|
+
seen: set[int] = set()
|
|
1261
|
+
before = len(self.ix.fns)
|
|
1262
|
+
self._handler(rel, decl, mod, refs, targets, seen, node_fn)
|
|
1263
|
+
added |= len(self.ix.fns) > before
|
|
1264
|
+
line = decl.start_point[0] + 1
|
|
1265
|
+
else:
|
|
1266
|
+
refs.append(("r", local, "", 1, -1))
|
|
1267
|
+
self.ix.entries.append(Entry(rule["kind"], name, rel, line, targets=targets, pending=[(mod, r) for r in refs]))
|
|
1268
|
+
# programs: a shebang, a main guard, a package.json script or bin, or a file in a scripts directory
|
|
1269
|
+
program = self.pkg_programs.get(rel) if self.pkg_programs else None
|
|
1270
|
+
guessed = False
|
|
1271
|
+
if program is None and not is_test:
|
|
1272
|
+
if SHEBANG.match(src) or MAIN_GUARD.search(src):
|
|
1273
|
+
program = os.path.basename(rel)
|
|
1274
|
+
elif self.program_dirs.search(rel):
|
|
1275
|
+
program, guessed = os.path.basename(rel), True
|
|
1276
|
+
if program is not None and not is_test:
|
|
1277
|
+
kind = "main" if self.service_main.search(src) else "cli"
|
|
1278
|
+
e = Entry(kind, f"{'node' if kind == 'cli' else 'main'} {rel}", rel, 1, targets=[mod])
|
|
1279
|
+
if guessed:
|
|
1280
|
+
e.tag = "loop" # listed only when a query is reached from it
|
|
1281
|
+
self.ix.entries.append(e)
|
|
1282
|
+
if is_test:
|
|
1283
|
+
self.ix.entries.append(Entry("test", rel, rel, 1, targets=[mod]))
|
|
1284
|
+
return added
|
|
1285
|
+
|
|
1286
|
+
@staticmethod
|
|
1287
|
+
def _top_declarator(root: Node, name: str) -> Node | None:
|
|
1288
|
+
"""The value a module-level `const name = ...` (or `export default ...`) is bound to."""
|
|
1289
|
+
for n in root.named_children:
|
|
1290
|
+
decl = n
|
|
1291
|
+
if n.type == "export_statement":
|
|
1292
|
+
if name == "default" and any(c.type == "default" for c in n.children):
|
|
1293
|
+
return n.child_by_field_name("value")
|
|
1294
|
+
decl = n.child_by_field_name("declaration")
|
|
1295
|
+
if decl is None or decl.type not in ("lexical_declaration", "variable_declaration"):
|
|
1296
|
+
continue
|
|
1297
|
+
for d in decl.named_children:
|
|
1298
|
+
if d.type == "variable_declarator" and _t(d.child_by_field_name("name")) == name:
|
|
1299
|
+
return d.child_by_field_name("value")
|
|
1300
|
+
return None
|
|
1301
|
+
|
|
1302
|
+
# ---- linking ------------------------------------------------------------------------
|
|
1303
|
+
def finish(self):
|
|
1304
|
+
for fn in self.ix.fns:
|
|
1305
|
+
if fn.lang != self.name or fn.module or fn.inline or fn.lex is None:
|
|
1306
|
+
continue
|
|
1307
|
+
if not fn.lex.module and not fn.container:
|
|
1308
|
+
self.children.setdefault(fn.lex.id, {}).setdefault(fn.name, fn)
|
|
1309
|
+
self._wrapper_entries()
|
|
1310
|
+
self.argcalls.clear()
|
|
1311
|
+
# Temporal activities / workflows named by module
|
|
1312
|
+
for kind, target, line, _, rel, local in self.pending_exports:
|
|
1313
|
+
names = list(self.exports.get(target, {}).items())
|
|
1314
|
+
for exported, loc in names:
|
|
1315
|
+
fn = self.top[target].get(loc)
|
|
1316
|
+
if fn is not None and exported != "default":
|
|
1317
|
+
self.ix.entries.append(Entry(kind, exported, fn.file, fn.start, targets=[fn]))
|
|
1318
|
+
# routers mounted on routers: resolve the mounted name to the file that declares it
|
|
1319
|
+
for parent, prefix, rel, (tfile, tname), owner in self.pending_mounts:
|
|
1320
|
+
child = self._binding(rel, tname) if not tfile else (tfile, self.exports.get(tfile, {}).get(tname, tname))
|
|
1321
|
+
if child is not None and child != parent:
|
|
1322
|
+
self.mounts[child].append((parent, prefix))
|
|
1323
|
+
for e, key, sep in self.entry_owner:
|
|
1324
|
+
pre = self._mount_prefix(key, sep, 0, set())
|
|
1325
|
+
if sep == ".":
|
|
1326
|
+
name = e.name.split(" ", 1)[-1] if " " in e.name else e.name
|
|
1327
|
+
full = ".".join(p for p in (pre or "", name) if p) if pre is not None else name
|
|
1328
|
+
e.name = f"{e.method or 'TRPC'} {full}"
|
|
1329
|
+
elif e.path is not None and pre:
|
|
1330
|
+
e.name = _http_name(e.method, _join_path(pre, e.path).rstrip("/") or "/")
|
|
1331
|
+
elif e.path is not None and pre is None:
|
|
1332
|
+
e.name = _http_name(e.method, _join_path("…", e.path))
|
|
1333
|
+
|
|
1334
|
+
def _binding(self, rel: str, name: str, depth: int = 0) -> tuple[str, str] | None:
|
|
1335
|
+
"""(file, local name) that a name in `rel` is bound to, through imports and re-exports."""
|
|
1336
|
+
imp = self.imports.get(rel, {}).get(name)
|
|
1337
|
+
if imp is None:
|
|
1338
|
+
return (rel, name)
|
|
1339
|
+
target, exported = imp
|
|
1340
|
+
if target is None or depth > 6:
|
|
1341
|
+
return None
|
|
1342
|
+
return self._exported_binding(target, exported, depth + 1)
|
|
1343
|
+
|
|
1344
|
+
def _exported_binding(self, target: str, exported: str, depth: int = 0) -> tuple[str, str] | None:
|
|
1345
|
+
if depth > 8:
|
|
1346
|
+
return None
|
|
1347
|
+
local = self.exports.get(target, {}).get(exported)
|
|
1348
|
+
if local is not None:
|
|
1349
|
+
if local in self.imports.get(target, {}) and local not in self.top.get(target, {}):
|
|
1350
|
+
return self._binding(target, local, depth + 1)
|
|
1351
|
+
return (target, local)
|
|
1352
|
+
for names, nxt in self.reexports.get(target, ()):
|
|
1353
|
+
if names is None:
|
|
1354
|
+
hit = self._exported_binding(nxt, exported, depth + 1)
|
|
1355
|
+
if hit is not None and (hit[1] in self.top.get(hit[0], {}) or (hit[0], hit[1]) in self.members
|
|
1356
|
+
or (hit[0], hit[1]) in self.class_info or hit[1] in self.exports.get(hit[0], {}).values()):
|
|
1357
|
+
return hit
|
|
1358
|
+
elif exported in names:
|
|
1359
|
+
return self._exported_binding(nxt, names[exported], depth + 1)
|
|
1360
|
+
return None
|
|
1361
|
+
|
|
1362
|
+
def _mount_prefix(self, key: tuple[str, str], sep: str, depth: int, seen: set) -> str | None:
|
|
1363
|
+
ups = self.mounts.get(key)
|
|
1364
|
+
if not ups:
|
|
1365
|
+
return ""
|
|
1366
|
+
if len({u for u in ups}) > 1 or depth > 8 or key in seen:
|
|
1367
|
+
return None
|
|
1368
|
+
seen.add(key)
|
|
1369
|
+
parent, prefix = ups[0]
|
|
1370
|
+
up = self._mount_prefix(parent, sep, depth + 1, seen)
|
|
1371
|
+
if up is None:
|
|
1372
|
+
return None
|
|
1373
|
+
if sep == ".":
|
|
1374
|
+
return ".".join(p for p in (up, prefix) if p)
|
|
1375
|
+
return _join_path(up, prefix)
|
|
1376
|
+
|
|
1377
|
+
def _fn_of(self, binding: tuple[str, str] | None) -> list[Fn]:
|
|
1378
|
+
if binding is None:
|
|
1379
|
+
return []
|
|
1380
|
+
fn = self.top.get(binding[0], {}).get(binding[1])
|
|
1381
|
+
return [fn] if fn is not None else []
|
|
1382
|
+
|
|
1383
|
+
def _class_of(self, rel: str, name: str) -> tuple[str, str] | None:
|
|
1384
|
+
"""(file, class) for a class name as seen from `rel`: declared here, imported, or unique in the repo."""
|
|
1385
|
+
if (rel, name) in self.class_info:
|
|
1386
|
+
return (rel, name)
|
|
1387
|
+
b = self._binding(rel, name) if name in self.imports.get(rel, {}) else None
|
|
1388
|
+
if b is not None and b in self.class_info:
|
|
1389
|
+
return b
|
|
1390
|
+
files = self.classes.get(name)
|
|
1391
|
+
if files and len(set(files)) == 1:
|
|
1392
|
+
return (files[0], name)
|
|
1393
|
+
return None
|
|
1394
|
+
|
|
1395
|
+
def _methods(self, cls: tuple[str, str] | None, name: str, depth: int = 0, down: bool = True) -> list[Fn]:
|
|
1396
|
+
"""`name` on a class: its own method, an inherited one, or the implementations of an interface."""
|
|
1397
|
+
if cls is None or depth > 6:
|
|
1398
|
+
return []
|
|
1399
|
+
own = self.members.get(cls, {}).get(name)
|
|
1400
|
+
if own:
|
|
1401
|
+
return list(own)
|
|
1402
|
+
info = self.class_info.get(cls)
|
|
1403
|
+
if info is not None and info["extends"]:
|
|
1404
|
+
up = self._methods(self._class_of(cls[0], info["extends"]), name, depth + 1, down=False)
|
|
1405
|
+
if up:
|
|
1406
|
+
return up
|
|
1407
|
+
if down:
|
|
1408
|
+
subs = self.subtypes.get(cls[1], ())
|
|
1409
|
+
if 0 < len(subs) <= 8:
|
|
1410
|
+
out: list[Fn] = []
|
|
1411
|
+
for sub in subs:
|
|
1412
|
+
out += self.members.get(sub, {}).get(name, [])
|
|
1413
|
+
return out
|
|
1414
|
+
return []
|
|
1415
|
+
|
|
1416
|
+
def _typed(self, rel: str, type_name: str, name: str) -> list[Fn]:
|
|
1417
|
+
cls = self._class_of(rel, type_name)
|
|
1418
|
+
if cls is not None:
|
|
1419
|
+
return self._methods(cls, name)
|
|
1420
|
+
subs = self.subtypes.get(type_name, ()) # an interface: the classes that implement it
|
|
1421
|
+
if 0 < len(subs) <= 8:
|
|
1422
|
+
out: list[Fn] = []
|
|
1423
|
+
for sub in subs:
|
|
1424
|
+
out += self._methods(sub, name, down=False)
|
|
1425
|
+
return out
|
|
1426
|
+
return []
|
|
1427
|
+
|
|
1428
|
+
def _member_of(self, binding: tuple[str, str] | None, name: str, depth: int = 0) -> list[Fn]:
|
|
1429
|
+
"""`X.name` where X is an exported object, class or instance."""
|
|
1430
|
+
if binding is None or depth > 4:
|
|
1431
|
+
return []
|
|
1432
|
+
own = self.members.get(binding, {}).get(name)
|
|
1433
|
+
if own:
|
|
1434
|
+
return list(own)
|
|
1435
|
+
ref = self.objrefs.get(binding, {}).get(name)
|
|
1436
|
+
if ref is not None:
|
|
1437
|
+
return self._fn_of(self._binding(binding[0], ref))
|
|
1438
|
+
if binding in self.class_info:
|
|
1439
|
+
return self._methods(binding, name)
|
|
1440
|
+
cls = self.modvars.get(binding)
|
|
1441
|
+
if cls:
|
|
1442
|
+
return self._typed(binding[0], cls, name)
|
|
1443
|
+
return []
|
|
1444
|
+
|
|
1445
|
+
def _owner_class(self, fn: Fn) -> tuple[str, str] | None:
|
|
1446
|
+
f = fn
|
|
1447
|
+
while f is not None:
|
|
1448
|
+
key = self.fn_class.get(f.id)
|
|
1449
|
+
if key is not None:
|
|
1450
|
+
return key
|
|
1451
|
+
if f.container and (f.file, f.container) in self.members:
|
|
1452
|
+
return (f.file, f.container)
|
|
1453
|
+
f = f.lex
|
|
1454
|
+
return None
|
|
1455
|
+
|
|
1456
|
+
def resolve(self, fn, call, depth: int = 0):
|
|
1457
|
+
_, name, qual, _, nargs = call
|
|
1458
|
+
rel = fn.file
|
|
1459
|
+
if qual.startswith("import:"):
|
|
1460
|
+
target = qual[7:]
|
|
1461
|
+
if name == "default":
|
|
1462
|
+
return self._fn_of(self._exported_binding(target, "default"))
|
|
1463
|
+
return self._fn_of(self._exported_binding(target, name))
|
|
1464
|
+
if not qual:
|
|
1465
|
+
f = fn
|
|
1466
|
+
while f is not None:
|
|
1467
|
+
kids = self.children.get(f.id)
|
|
1468
|
+
if kids and name in kids:
|
|
1469
|
+
return [kids[name]]
|
|
1470
|
+
dyn = f.extra.get("$imp") if isinstance(f.extra, dict) else None
|
|
1471
|
+
if dyn and name in dyn:
|
|
1472
|
+
target, exported = dyn[name]
|
|
1473
|
+
return self._fn_of(self._exported_binding(target, "default" if exported == "*" else exported)) if target else []
|
|
1474
|
+
alias = f.extra.get("$alias") if isinstance(f.extra, dict) else None
|
|
1475
|
+
if alias and name in alias and depth < 3:
|
|
1476
|
+
source, member = alias[name]
|
|
1477
|
+
return self.resolve(fn, (call[0], member, source, call[3], nargs), depth + 1)
|
|
1478
|
+
f = f.lex
|
|
1479
|
+
top = self.top.get(rel, {}).get(name)
|
|
1480
|
+
if top is not None:
|
|
1481
|
+
return [top]
|
|
1482
|
+
imp = self.imports.get(rel, {}).get(name)
|
|
1483
|
+
if imp is not None:
|
|
1484
|
+
target, exported = imp
|
|
1485
|
+
if target is None:
|
|
1486
|
+
return []
|
|
1487
|
+
return self._fn_of(self._exported_binding(target, "default" if exported == "*" else exported))
|
|
1488
|
+
return []
|
|
1489
|
+
if qual in ("this", "super"):
|
|
1490
|
+
cls = self._owner_class(fn)
|
|
1491
|
+
if cls is None:
|
|
1492
|
+
return []
|
|
1493
|
+
if qual == "super":
|
|
1494
|
+
info = self.class_info.get(cls)
|
|
1495
|
+
return self._methods(self._class_of(cls[0], info["extends"]), name, down=False) if info and info["extends"] else []
|
|
1496
|
+
return self._methods(cls, name)
|
|
1497
|
+
if qual.startswith("this."):
|
|
1498
|
+
field = qual[5:]
|
|
1499
|
+
cls = self._owner_class(fn)
|
|
1500
|
+
if cls is not None and "." not in field:
|
|
1501
|
+
seen = 0
|
|
1502
|
+
cur = cls
|
|
1503
|
+
while cur is not None and seen < 5:
|
|
1504
|
+
info = self.class_info.get(cur)
|
|
1505
|
+
tt = info["fields"].get(field) if info else None
|
|
1506
|
+
if tt:
|
|
1507
|
+
return self._typed(cur[0], tt, name)
|
|
1508
|
+
cur = self._class_of(cur[0], info["extends"]) if info and info["extends"] else None
|
|
1509
|
+
seen += 1
|
|
1510
|
+
return self._fuzzy(fn, name)
|
|
1511
|
+
if qual.startswith("new:"):
|
|
1512
|
+
return self._typed(rel, qual[4:], name)
|
|
1513
|
+
if qual.startswith("call:"):
|
|
1514
|
+
return self._via_call(fn, qual[5:], name, depth) or self._fuzzy(fn, name)
|
|
1515
|
+
if qual == "?":
|
|
1516
|
+
return self._fuzzy(fn, name)
|
|
1517
|
+
if "." not in qual:
|
|
1518
|
+
f = fn
|
|
1519
|
+
while f is not None:
|
|
1520
|
+
extra = f.extra if isinstance(f.extra, dict) else None
|
|
1521
|
+
if extra:
|
|
1522
|
+
tt = extra.get(qual)
|
|
1523
|
+
if isinstance(tt, str) and tt.startswith("call:"):
|
|
1524
|
+
got = self._via_call(f, tt[5:], name, depth)
|
|
1525
|
+
if got:
|
|
1526
|
+
return got
|
|
1527
|
+
break
|
|
1528
|
+
if isinstance(tt, str) and tt:
|
|
1529
|
+
return self._typed(f.file, tt, name)
|
|
1530
|
+
dyn = extra.get("$imp")
|
|
1531
|
+
if dyn and qual in dyn:
|
|
1532
|
+
target, exported = dyn[qual]
|
|
1533
|
+
if target is None:
|
|
1534
|
+
return []
|
|
1535
|
+
if exported == "*":
|
|
1536
|
+
return self._fn_of(self._exported_binding(target, name)) or \
|
|
1537
|
+
self._member_of(self._exported_binding(target, "default"), name)
|
|
1538
|
+
return self._member_of(self._exported_binding(target, exported), name)
|
|
1539
|
+
f = f.lex
|
|
1540
|
+
imp = self.imports.get(rel, {}).get(qual)
|
|
1541
|
+
if imp is not None:
|
|
1542
|
+
target, exported = imp
|
|
1543
|
+
if target is None:
|
|
1544
|
+
return []
|
|
1545
|
+
if exported == "*":
|
|
1546
|
+
return self._fn_of(self._exported_binding(target, name)) or \
|
|
1547
|
+
self._member_of(self._exported_binding(target, "default"), name)
|
|
1548
|
+
return self._member_of(self._exported_binding(target, exported), name)
|
|
1549
|
+
local = self._member_of((rel, qual), name)
|
|
1550
|
+
if local:
|
|
1551
|
+
return local
|
|
1552
|
+
if qual[:1].isupper():
|
|
1553
|
+
cls = self._class_of(rel, qual)
|
|
1554
|
+
if cls is not None:
|
|
1555
|
+
return self._methods(cls, name)
|
|
1556
|
+
return self._fuzzy(fn, name)
|
|
1557
|
+
|
|
1558
|
+
def _via_call(self, fn: Fn, callee: str, name: str, depth: int) -> list[Fn]:
|
|
1559
|
+
"""`getService().method()`: the method of the class that `getService` returns."""
|
|
1560
|
+
if depth > 3:
|
|
1561
|
+
return []
|
|
1562
|
+
qual, _, last = callee.rpartition(".")
|
|
1563
|
+
if qual and qual != "this" and "." in qual:
|
|
1564
|
+
return []
|
|
1565
|
+
out: list[Fn] = []
|
|
1566
|
+
for target in self.resolve(fn, ("c", last, qual, 0, -1), depth + 1)[:3]:
|
|
1567
|
+
tt = self.returns.get(target.id)
|
|
1568
|
+
if tt:
|
|
1569
|
+
out += self._typed(target.file, tt, name)
|
|
1570
|
+
return out
|
|
1571
|
+
|
|
1572
|
+
def _fuzzy(self, fn: Fn, name: str) -> list[Fn]:
|
|
1573
|
+
if name in self.ambiguous:
|
|
1574
|
+
return []
|
|
1575
|
+
return self.by_unique_name(fn, name, -1, methods=True, same_file_max=1, repo_wide=True)
|
|
1576
|
+
|
|
1577
|
+
|
|
1578
|
+
# ---- registration ---------------------------------------------------------------------------
|
|
1579
|
+
_TS_STR = r"(?:\"[^\"\n]*\"|'[^'\n]*'|`[^`\n$]*`|[A-Za-z_$][\w$.]*)"
|
|
1580
|
+
origins.LANGS["typescript"] = TypeScript
|
|
1581
|
+
origins.Consts.PATTERNS["typescript"] = re.compile(
|
|
1582
|
+
(r"(?m)^[ \t]*(?:export\s+)?(?:const|let|var|static|readonly|public|private|protected)(?:\s+(?:static|readonly))*\s+"
|
|
1583
|
+
r"([A-Za-z_$][\w$]*)[ \t]*(?::[ \t]*[\w<>\[\], .|]+)?=[ \t]*(" + _TS_STR + r"(?:[ \t]*\+[ \t]*" + _TS_STR + r")*)[ \t]*(?:as\s+const)?;?[ \t]*$").encode())
|
|
1584
|
+
origins.CONST_DECL["typescript"] = re.compile(r"\b(?:const|let|var|static|readonly)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=(?!=)")
|