graphe-code 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.
- graphe/__init__.py +0 -0
- graphe/cli.py +991 -0
- graphe/core.py +461 -0
- graphe/generic.py +662 -0
- graphe/godot.py +386 -0
- graphe/js.py +564 -0
- graphe/python.py +917 -0
- graphe/root.py +82 -0
- graphe_code-0.1.0.dist-info/METADATA +24 -0
- graphe_code-0.1.0.dist-info/RECORD +14 -0
- graphe_code-0.1.0.dist-info/WHEEL +5 -0
- graphe_code-0.1.0.dist-info/entry_points.txt +2 -0
- graphe_code-0.1.0.dist-info/licenses/LICENSE +21 -0
- graphe_code-0.1.0.dist-info/top_level.txt +1 -0
graphe/js.py
ADDED
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
"""The host's JavaScript in the code graph (T-0014): `.js` and `.mjs`, read by tree-sitter (ADR 0002); `.ts` and a
|
|
2
|
+
`.svelte` component (T-0015) by the TypeScript grammar: its `<script>`, and the expressions of its markup as
|
|
3
|
+
statements of the module, their calls the component's (T-0022); the rest blanked out to keep the lines.
|
|
4
|
+
|
|
5
|
+
- a node per file, per top-level function (`function f`, `const f = () =>`), per class and per method
|
|
6
|
+
(`Class.method`), per method of an object literal a function returns or a module's `const` holds (T-0020), per
|
|
7
|
+
test (`test('title', () => ...)`, T-0021); the calls in a nested function belong to the function that contains it;
|
|
8
|
+
- the imports of our files (relative specifiers, re-exports followed): `imports` between files, and a call to an
|
|
9
|
+
imported name leads to its definition; a name of a package, re-exported or not, is `external` (T-0018);
|
|
10
|
+
- a call is sure (EXTRACTED) by a top-level definition, an import, a namespace (`import * as`, `export * as`),
|
|
11
|
+
`this.m()` in a class or its parents, `Class.m()`, or `x.m()` when x was assigned `new C()` or `[await] f()`
|
|
12
|
+
(T-0020); by the name alone (INFERRED) for `x.m()` when one of our class methods only has that name, or for a
|
|
13
|
+
name defined once in the host. A parameter or a variable of the function or of the module hides an import of
|
|
14
|
+
the same name: its calls are `local`. A bare name of ours as a statement (`onclick={fermer}`) is a `references`.
|
|
15
|
+
|
|
16
|
+
The ids carry the extension (`src_zones_mjs`, `src_tableau_svelte`): `zones.py` is the Python reader's `src_zones`.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import posixpath
|
|
22
|
+
import re
|
|
23
|
+
from collections import defaultdict
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import NamedTuple
|
|
26
|
+
|
|
27
|
+
import tree_sitter
|
|
28
|
+
import tree_sitter_javascript
|
|
29
|
+
import tree_sitter_typescript
|
|
30
|
+
|
|
31
|
+
JS = tree_sitter.Parser(tree_sitter.Language(tree_sitter_javascript.language()))
|
|
32
|
+
TS = tree_sitter.Parser(tree_sitter.Language(tree_sitter_typescript.language_typescript()))
|
|
33
|
+
PARSERS = {".js": JS, ".mjs": JS, ".ts": TS, ".svelte": TS}
|
|
34
|
+
# The suffixes a relative specifier may leave out (`./lib/eau` is `./lib/eau.ts`); a component is imported with its
|
|
35
|
+
# `.svelte`. shortcut: neither `.tsx` nor NodeNext's `./x.js` for `x.ts`; to add when a host has some.
|
|
36
|
+
SUFFIXES = (".js", ".mjs", ".ts")
|
|
37
|
+
# shortcut: by a pattern, so a `</script>` in a string of the script ends it; to parse the markup if a host trips on it.
|
|
38
|
+
SCRIPT = re.compile(rb"<script\b[^>]*>(.*?)</script>", re.S)
|
|
39
|
+
# T-0022: what the markup's expressions are not read in: the script, the style, the comments.
|
|
40
|
+
NOT_MARKUP = re.compile(rb"<(script|style)\b[^>]*>.*?</\1>|<!--.*?-->", re.S)
|
|
41
|
+
# The keyword of a block or a tag, cut before its expression is kept (`{#if x}`: `x`; `{@const c = f()}`:
|
|
42
|
+
# `const c = f()`); `{#each xs as x}` and `{#await p then v}` keep `xs` and `p`. Any other `{#`, `{:`, `{/`, `{@`
|
|
43
|
+
# (`{:else}`, `{/if}`, `{#snippet ...}`) keeps nothing.
|
|
44
|
+
KEYWORD = re.compile(rb"(#if|#each|#await|#key|:else\s+if|@html|@render|@attach|@debug)\b\s*|@(?=const\b)")
|
|
45
|
+
CUT = re.compile(rb"\s(?:as|then|catch)\s")
|
|
46
|
+
FUNCTIONS = {"function_declaration", "generator_function_declaration"}
|
|
47
|
+
FUNCTION_VALUES = {"arrow_function", "function_expression", "generator_function", "function"}
|
|
48
|
+
CLASSES = {"class_declaration", "abstract_class_declaration", "class"}
|
|
49
|
+
SCOPES = FUNCTIONS | FUNCTION_VALUES | {"method_definition"}
|
|
50
|
+
PATTERNS = {"formal_parameters", "object_pattern", "array_pattern", "rest_pattern"}
|
|
51
|
+
# shortcut: a hand-kept list of the language's and the platform's names, called without being ours (a verdict, not
|
|
52
|
+
# an alert); to extend when `check` shows one under `unknown`.
|
|
53
|
+
GLOBALS = {"Array", "Boolean", "Date", "Error", "Map", "Number", "Object", "Promise", "RegExp", "Set", "String",
|
|
54
|
+
"Symbol", "TypeError", "URL", "WeakMap", "parseFloat", "parseInt", "isNaN", "isFinite", "fetch", "require",
|
|
55
|
+
"setTimeout", "setInterval", "clearTimeout", "clearInterval", "structuredClone", "queueMicrotask",
|
|
56
|
+
"encodeURIComponent", "decodeURIComponent", "Intl", "Blob", "TextEncoder", "TextDecoder", "Uint8Array",
|
|
57
|
+
"requestAnimationFrame", "alert", "confirm", "console", "Math", "JSON", "Reflect", "document", "window",
|
|
58
|
+
"process", "localStorage", "navigator", "crypto", "performance", "Buffer", "Float32Array",
|
|
59
|
+
"addEventListener", "scrollTo", "matchMedia",
|
|
60
|
+
"$state", "$derived", "$effect", "$props", "$bindable", "$inspect", "$host"} # Svelte's runes
|
|
61
|
+
# T-0021: the functions of node:test, vitest and jest whose callback is a test, named by its title. shortcut: neither
|
|
62
|
+
# `test.only` nor `describe.each`; to add when a host has some.
|
|
63
|
+
TESTS = {"test", "it", "describe"}
|
|
64
|
+
# shortcut: a chain of re-exports longer than this is not followed (and a cycle stops there); to raise if a host
|
|
65
|
+
# re-exports deeper.
|
|
66
|
+
DEPTH = 8
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Def(NamedTuple): # a top-level function or class of the module
|
|
70
|
+
id: str
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Import(NamedTuple): # `name` of `module`: "default", "*" (the namespace) or a name; module None: a package's
|
|
74
|
+
module: str | None
|
|
75
|
+
name: str
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Local(NamedTuple): # an export of a name of the module
|
|
79
|
+
name: str
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class From(NamedTuple): # a re-export: `name` of `module` ("*": `export * as`)
|
|
83
|
+
module: str | None
|
|
84
|
+
name: str
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class Namespace(NamedTuple): # what `import * as x` designates: a module of ours
|
|
88
|
+
module: str
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class Package(NamedTuple): # T-0018: what a name imported from a package designates, re-exported or not
|
|
92
|
+
name: str
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _id(rel: str) -> str:
|
|
96
|
+
return re.sub(r"\W", "_", rel).lower()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _text(node) -> str:
|
|
100
|
+
return node.text.decode("utf-8", "replace")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _names(pattern) -> set[str]:
|
|
104
|
+
"""The names a parameter or a declaration binds (`a`, `{ b, c: d }`, `[e = 1]`, `...f`)."""
|
|
105
|
+
if pattern.type in ("identifier", "shorthand_property_identifier_pattern"):
|
|
106
|
+
return {_text(pattern)}
|
|
107
|
+
if pattern.type in ("required_parameter", "optional_parameter"): # TypeScript's, typed
|
|
108
|
+
return _names(pattern.child_by_field_name("pattern"))
|
|
109
|
+
if pattern.type in ("assignment_pattern", "object_assignment_pattern"):
|
|
110
|
+
return _names(pattern.child_by_field_name("left"))
|
|
111
|
+
if pattern.type == "pair_pattern":
|
|
112
|
+
return _names(pattern.child_by_field_name("value"))
|
|
113
|
+
if pattern.type in PATTERNS:
|
|
114
|
+
return set().union(*map(_names, pattern.named_children))
|
|
115
|
+
return set()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _declared(scope) -> set[str]:
|
|
119
|
+
"""The parameters of a function and the names its body declares, outside its nested functions (whose names it
|
|
120
|
+
declares). shortcut: a block's `let` counts for the whole function; to scope it if a host shadows in a block."""
|
|
121
|
+
found = set()
|
|
122
|
+
for field in ("parameters", "parameter"):
|
|
123
|
+
if (p := scope.child_by_field_name(field)) is not None:
|
|
124
|
+
found |= _names(p)
|
|
125
|
+
stack = [c for c in scope.named_children if c.type not in ("formal_parameters", "identifier")]
|
|
126
|
+
while stack:
|
|
127
|
+
node = stack.pop()
|
|
128
|
+
if node.type == "variable_declarator":
|
|
129
|
+
found |= _names(node.child_by_field_name("name"))
|
|
130
|
+
elif node.type in FUNCTIONS | CLASSES and (name := node.child_by_field_name("name")) is not None:
|
|
131
|
+
found.add(_text(name))
|
|
132
|
+
elif node.type == "catch_clause" and (p := node.child_by_field_name("parameter")) is not None:
|
|
133
|
+
found |= _names(p)
|
|
134
|
+
if node.type not in SCOPES:
|
|
135
|
+
stack.extend(node.named_children)
|
|
136
|
+
return found
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _returned_object(function):
|
|
140
|
+
"""T-0020: the object literal a function returns (`return {...}`, `() => ({...})`), outside its nested
|
|
141
|
+
functions; else None."""
|
|
142
|
+
body = function.child_by_field_name("body")
|
|
143
|
+
stack = [body] if body is not None and body.type == "statement_block" else []
|
|
144
|
+
while body is not None and body.type == "parenthesized_expression" and body.named_children:
|
|
145
|
+
body = body.named_children[0]
|
|
146
|
+
if body is not None and body.type == "object":
|
|
147
|
+
return body
|
|
148
|
+
objects, returned = {}, [] # `const p = {...}; ... return p` (dpe's ui_mode.test.mjs)
|
|
149
|
+
while stack:
|
|
150
|
+
node = stack.pop()
|
|
151
|
+
if node.type == "return_statement" and node.named_children:
|
|
152
|
+
value = node.named_children[0]
|
|
153
|
+
while value.type == "parenthesized_expression" and value.named_children:
|
|
154
|
+
value = value.named_children[0]
|
|
155
|
+
returned.append(value)
|
|
156
|
+
elif node.type == "variable_declarator" and (value := node.child_by_field_name("value")) is not None \
|
|
157
|
+
and value.type == "object" and node.child_by_field_name("name").type == "identifier":
|
|
158
|
+
objects[_text(node.child_by_field_name("name"))] = value
|
|
159
|
+
if node.type not in SCOPES:
|
|
160
|
+
stack.extend(node.named_children)
|
|
161
|
+
for value in sorted(returned, key=lambda v: v.start_byte): # the first return of the source
|
|
162
|
+
if value.type == "object":
|
|
163
|
+
return value
|
|
164
|
+
if value.type == "identifier" and _text(value) in objects:
|
|
165
|
+
return objects[_text(value)]
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _required(root) -> set[str]:
|
|
170
|
+
"""The names a module's top binds by `require(...)` (`const { aider } = require('./x.js')`): names of ours
|
|
171
|
+
perhaps, by the name, that the module's own variables (T-0019) must not hide. shortcut: CommonJS is not followed
|
|
172
|
+
(Reader); to read `require` if a host needs it."""
|
|
173
|
+
return {name for d in root.named_children if d.type in ("lexical_declaration", "variable_declaration")
|
|
174
|
+
for v in d.named_children if v.type == "variable_declarator"
|
|
175
|
+
and (value := v.child_by_field_name("value")) is not None and value.type == "call_expression"
|
|
176
|
+
and _text(_callee(value)) == "require" for name in _names(v.child_by_field_name("name"))}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _callee(call):
|
|
180
|
+
"""What a call or a `new` calls."""
|
|
181
|
+
return call.child_by_field_name("constructor" if call.type == "new_expression" else "function")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _source(path: Path) -> bytes:
|
|
185
|
+
"""A file's code: a `.svelte` component's `<script>` blocks, and the expressions of its markup (T-0022) as
|
|
186
|
+
statements of the module, `{f(x)}` read ` f(x);`; the rest blanked out byte for byte (lines kept)."""
|
|
187
|
+
data = path.read_bytes()
|
|
188
|
+
if path.suffix != ".svelte":
|
|
189
|
+
return data
|
|
190
|
+
kept = bytearray(re.sub(rb"[^\n]", b" ", data))
|
|
191
|
+
for m in SCRIPT.finditer(data):
|
|
192
|
+
kept[m.start(1):m.end(1)] = m.group(1)
|
|
193
|
+
skipped = [m.span() for m in NOT_MARKUP.finditer(data)]
|
|
194
|
+
i = 0
|
|
195
|
+
while (i := data.find(b"{", i)) >= 0:
|
|
196
|
+
if (inside := next((end for start, end in skipped if start <= i < end), None)) is not None:
|
|
197
|
+
i = inside
|
|
198
|
+
continue
|
|
199
|
+
depth, j = 0, i # shortcut: a brace in a string of the expression miscounts; to tokenize if a host has one
|
|
200
|
+
while j < len(data) and not (data[j] == ord("}") and depth == 1):
|
|
201
|
+
depth += {ord("{"): 1, ord("}"): -1}.get(data[j], 0)
|
|
202
|
+
j += 1
|
|
203
|
+
if j == len(data):
|
|
204
|
+
break # an expression never closed: nothing of it, nor of what follows
|
|
205
|
+
start = i + 1
|
|
206
|
+
if keyword := KEYWORD.match(data, start):
|
|
207
|
+
start = keyword.end()
|
|
208
|
+
elif data[start:start + 1] in (b"#", b":", b"/", b"@"):
|
|
209
|
+
start = j
|
|
210
|
+
end = cut.start() if keyword and (cut := CUT.search(data, start, j)) else j
|
|
211
|
+
kept[start:end] = data[start:end]
|
|
212
|
+
kept[j] = ord(";")
|
|
213
|
+
i = j + 1
|
|
214
|
+
return bytes(kept)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def contribute(project) -> dict:
|
|
218
|
+
"""The JS reader's contribution (docs/contribution.md): a site per call."""
|
|
219
|
+
reader = Reader(sorted(p for suffix in PARSERS for p in project.files(suffix)), project.root)
|
|
220
|
+
return {"nodes": reader.nodes, "links": reader.links, "sites": reader.sites}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class Module:
|
|
224
|
+
def __init__(self, rel: str, tree) -> None:
|
|
225
|
+
self.rel, self.id, self.tree = rel, _id(rel), tree
|
|
226
|
+
self.bindings: dict[str, Def | Import] = {}
|
|
227
|
+
self.exports: dict[str, Local | From] = {}
|
|
228
|
+
self.stars: list[str] = [] # export * from
|
|
229
|
+
self.owners: dict[tuple, tuple[str, str | None]] = {} # a body (start, end) -> (its node, its class)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class Reader:
|
|
233
|
+
"""shortcut: ES modules only, neither `require` nor `module.exports`, and relative specifiers only (neither a
|
|
234
|
+
package's `exports` nor aliases); nested functions and the methods of an object literal are not nodes
|
|
235
|
+
(BACKLOG.md). To extend when a host needs it."""
|
|
236
|
+
|
|
237
|
+
def __init__(self, paths: list[Path], root: Path) -> None:
|
|
238
|
+
self.nodes: list[dict] = []
|
|
239
|
+
self.links: list[dict] = []
|
|
240
|
+
self.sites: list[dict] = []
|
|
241
|
+
self.modules: dict[str, Module] = {}
|
|
242
|
+
for path in paths:
|
|
243
|
+
rel = path.relative_to(root).as_posix()
|
|
244
|
+
self.modules[rel] = Module(rel, PARSERS[path.suffix].parse(_source(path)))
|
|
245
|
+
self.ids: set[str] = set()
|
|
246
|
+
self.methods: dict[str, list[str]] = defaultdict(list) # method name -> ids
|
|
247
|
+
self.by_name: dict[str, list[str]] = defaultdict(list) # top-level function or class name -> ids
|
|
248
|
+
self.class_methods: dict[str, dict[str, str]] = {} # class id -> method name -> id
|
|
249
|
+
self.bases: dict[str, tuple[Module, str]] = {} # class id -> (its module, the name it extends)
|
|
250
|
+
self.returning: set[str] = set() # the functions whose methods are those of the object they return
|
|
251
|
+
for m in self.modules.values():
|
|
252
|
+
self._node(m.id, posixpath.basename(m.rel), "file", m.rel, 1, m.rel)
|
|
253
|
+
for top in m.tree.root_node.named_children:
|
|
254
|
+
if top.type == "import_statement":
|
|
255
|
+
self._import(m, top)
|
|
256
|
+
elif top.type == "export_statement":
|
|
257
|
+
self._export_statement(m, top)
|
|
258
|
+
else:
|
|
259
|
+
self._declaration(m, top)
|
|
260
|
+
for m in self.modules.values():
|
|
261
|
+
self._calls(m)
|
|
262
|
+
|
|
263
|
+
# ---------- the definitions, the imports and the exports
|
|
264
|
+
|
|
265
|
+
def _import(self, m: Module, node) -> None:
|
|
266
|
+
target = self._module(m, node.child_by_field_name("source"))
|
|
267
|
+
for clause in (c for c in node.named_children if c.type == "import_clause"):
|
|
268
|
+
for part in clause.named_children:
|
|
269
|
+
if part.type == "identifier":
|
|
270
|
+
m.bindings[_text(part)] = Import(target, "default")
|
|
271
|
+
elif part.type == "namespace_import":
|
|
272
|
+
m.bindings[_text(part.named_children[0])] = Import(target, "*")
|
|
273
|
+
elif part.type == "named_imports":
|
|
274
|
+
for name, alias in map(self._specifier, (c for c in part.named_children if c.type != "comment")):
|
|
275
|
+
m.bindings[alias] = Import(target, name)
|
|
276
|
+
if target:
|
|
277
|
+
self._link(m.id, self.modules[target].id, "imports", m.rel, node)
|
|
278
|
+
|
|
279
|
+
def _export_statement(self, m: Module, node) -> None:
|
|
280
|
+
source = node.child_by_field_name("source")
|
|
281
|
+
target = self._module(m, source) if source else None
|
|
282
|
+
if target:
|
|
283
|
+
self._link(m.id, self.modules[target].id, "imports", m.rel, node)
|
|
284
|
+
declaration = node.child_by_field_name("declaration") or node.child_by_field_name("value")
|
|
285
|
+
clause = next((c for c in node.named_children if c.type in ("export_clause", "namespace_export")), None)
|
|
286
|
+
if clause is not None and clause.type == "namespace_export": # export * as name from
|
|
287
|
+
m.exports[_text(clause.named_children[-1])] = From(target, "*")
|
|
288
|
+
elif clause is not None:
|
|
289
|
+
for name, alias in map(self._specifier, (c for c in clause.named_children if c.type != "comment")):
|
|
290
|
+
m.exports[alias] = From(target, name) if source else Local(name)
|
|
291
|
+
elif source:
|
|
292
|
+
if target:
|
|
293
|
+
m.stars.append(target) # export * from
|
|
294
|
+
elif declaration is not None:
|
|
295
|
+
names = self._declaration(m, declaration)
|
|
296
|
+
if not any(c.type == "default" for c in node.children):
|
|
297
|
+
for name in names:
|
|
298
|
+
m.exports[name] = Local(name)
|
|
299
|
+
return
|
|
300
|
+
if declaration.type == "identifier":
|
|
301
|
+
names = [_text(declaration)]
|
|
302
|
+
elif not names and declaration.type in FUNCTION_VALUES | CLASSES: # anonymous
|
|
303
|
+
names = [self._define(m, "default", declaration)]
|
|
304
|
+
if names:
|
|
305
|
+
m.exports["default"] = Local(names[0])
|
|
306
|
+
|
|
307
|
+
@staticmethod
|
|
308
|
+
def _specifier(s) -> tuple[str, str]:
|
|
309
|
+
"""(the name, the alias) of `name as alias` in an import or an export."""
|
|
310
|
+
name, alias = s.child_by_field_name("name"), s.child_by_field_name("alias")
|
|
311
|
+
return _text(name), _text(alias or name)
|
|
312
|
+
|
|
313
|
+
def _declaration(self, m: Module, node) -> list[str]:
|
|
314
|
+
"""The names a top-level declaration defines: a function, a class, `const f = () =>`."""
|
|
315
|
+
if node.type in FUNCTIONS | CLASSES:
|
|
316
|
+
name = node.child_by_field_name("name")
|
|
317
|
+
return [] if name is None else [self._define(m, _text(name), node)]
|
|
318
|
+
names = []
|
|
319
|
+
if node.type in ("lexical_declaration", "variable_declaration"):
|
|
320
|
+
for d in node.named_children:
|
|
321
|
+
name, value = d.child_by_field_name("name"), d.child_by_field_name("value")
|
|
322
|
+
if d.type == "variable_declarator" and name is not None and name.type == "identifier" \
|
|
323
|
+
and value is not None and value.type in FUNCTION_VALUES | CLASSES:
|
|
324
|
+
names.append(self._define(m, _text(name), value, head=d))
|
|
325
|
+
elif d.type == "variable_declarator" and name is not None and name.type == "identifier" \
|
|
326
|
+
and value is not None and value.type == "object": # T-0020: `const outils = { m() {} }`
|
|
327
|
+
nid = self._node(f"{m.id}_{_text(name).lower()}", _text(name), "object", m.rel,
|
|
328
|
+
d.start_point[0] + 1, _text(name))
|
|
329
|
+
self._link(m.id, nid, "contains", m.rel, d)
|
|
330
|
+
m.bindings[_text(name)] = Def(nid)
|
|
331
|
+
self._members(m, nid, _text(name), value)
|
|
332
|
+
names.append(_text(name))
|
|
333
|
+
return names
|
|
334
|
+
|
|
335
|
+
def _define(self, m: Module, name: str, node, head=None) -> str:
|
|
336
|
+
"""A function or a class at the top of `m` (its methods with it); its name."""
|
|
337
|
+
head = head or node
|
|
338
|
+
is_class = node.type in CLASSES
|
|
339
|
+
nid = self._node(f"{m.id}_{name.lower()}", name if is_class else f"{name}()",
|
|
340
|
+
"class" if is_class else "function", m.rel, head.start_point[0] + 1, name)
|
|
341
|
+
self._link(m.id, nid, "contains", m.rel, head)
|
|
342
|
+
m.bindings[name] = Def(nid)
|
|
343
|
+
self.by_name[name].append(nid)
|
|
344
|
+
m.owners[(node.start_byte, node.end_byte)] = (nid, nid if is_class else None)
|
|
345
|
+
if not is_class:
|
|
346
|
+
if (returned := _returned_object(node)) is not None: # T-0020: dpe's page objects
|
|
347
|
+
self._members(m, nid, name, returned)
|
|
348
|
+
self.returning.add(nid)
|
|
349
|
+
return name
|
|
350
|
+
heritage = next((c for c in node.named_children if c.type == "class_heritage"), None)
|
|
351
|
+
base = heritage.named_children[0] if heritage is not None and heritage.named_children else None
|
|
352
|
+
if base is not None and base.type == "extends_clause": # TypeScript's
|
|
353
|
+
base = base.child_by_field_name("value")
|
|
354
|
+
if base is not None and base.type == "identifier":
|
|
355
|
+
self.bases[nid] = (m, _text(base))
|
|
356
|
+
self._members(m, nid, name, node.child_by_field_name("body"))
|
|
357
|
+
return name
|
|
358
|
+
|
|
359
|
+
def _members(self, m: Module, nid: str, name: str, body) -> None:
|
|
360
|
+
"""The methods of a class body or of an object literal (T-0020: `m() {}`, `m: () => ...`), nodes held by
|
|
361
|
+
`nid`: `this.m()` inside them is `nid`'s. An object's methods are reached by its type only, never by the name
|
|
362
|
+
alone: dpe's fake objects have `click`, `getItem`, which the DOM's would take."""
|
|
363
|
+
methods = self.class_methods.setdefault(nid, {})
|
|
364
|
+
for c in body.named_children:
|
|
365
|
+
if c.type == "method_definition":
|
|
366
|
+
method = _text(c.child_by_field_name("name"))
|
|
367
|
+
elif c.type == "pair" and (value := c.child_by_field_name("value")) is not None \
|
|
368
|
+
and value.type in FUNCTION_VALUES:
|
|
369
|
+
method = _text(c.child_by_field_name("key")).strip("'\"")
|
|
370
|
+
else:
|
|
371
|
+
continue
|
|
372
|
+
mid = self._node(f"{nid}_{method.lower().lstrip('#')}", f"{name}.{method}()", "method", m.rel,
|
|
373
|
+
c.start_point[0] + 1, f"{name}.{method}")
|
|
374
|
+
self._link(nid, mid, "contains", m.rel, c)
|
|
375
|
+
if body.type == "class_body":
|
|
376
|
+
self.methods[method].append(mid)
|
|
377
|
+
methods.setdefault(method, mid) # a getter and its setter: the first
|
|
378
|
+
arrow = c.type == "pair" and c.child_by_field_name("value").type == "arrow_function"
|
|
379
|
+
m.owners[(c.start_byte, c.end_byte)] = (mid, None if arrow else nid) # an arrow's `this` is not nid
|
|
380
|
+
|
|
381
|
+
def _module(self, m: Module, source) -> str | None:
|
|
382
|
+
"""The file of ours that a relative specifier designates (`./zones.mjs`, `../lib`), else None."""
|
|
383
|
+
spec = _text(source).strip("'\"`")
|
|
384
|
+
if not spec.startswith("."):
|
|
385
|
+
return None
|
|
386
|
+
path = posixpath.normpath(posixpath.join(posixpath.dirname(m.rel), spec))
|
|
387
|
+
for candidate in (path, *(path + s for s in SUFFIXES), *(f"{path}/index{s}" for s in SUFFIXES)):
|
|
388
|
+
if candidate in self.modules:
|
|
389
|
+
return candidate
|
|
390
|
+
return None
|
|
391
|
+
|
|
392
|
+
def _export(self, rel: str | None, name: str, depth: int = 0) -> str | Namespace | Package | None:
|
|
393
|
+
"""What the module `rel` exports under `name`: a node, a namespace, a package's name; re-exports followed."""
|
|
394
|
+
m = self.modules.get(rel)
|
|
395
|
+
if m is None or depth > DEPTH:
|
|
396
|
+
return None
|
|
397
|
+
e = m.exports.get(name)
|
|
398
|
+
if isinstance(e, Local):
|
|
399
|
+
return self._binding(m, e.name, depth)
|
|
400
|
+
if isinstance(e, From) and e.module is None:
|
|
401
|
+
return Package(e.name)
|
|
402
|
+
if isinstance(e, From):
|
|
403
|
+
return Namespace(e.module) if e.name == "*" else self._export(e.module, e.name, depth + 1)
|
|
404
|
+
for star in m.stars:
|
|
405
|
+
if found := self._export(star, name, depth + 1):
|
|
406
|
+
return found
|
|
407
|
+
return None
|
|
408
|
+
|
|
409
|
+
def _binding(self, m: Module, name: str, depth: int = 0) -> str | Namespace | Package | None:
|
|
410
|
+
"""What a top-level name of `m` designates: a node of ours, a namespace of ours, a package's name, else
|
|
411
|
+
None."""
|
|
412
|
+
b = m.bindings.get(name)
|
|
413
|
+
if isinstance(b, Def):
|
|
414
|
+
return b.id
|
|
415
|
+
if isinstance(b, Import) and b.module is None:
|
|
416
|
+
return Package(b.name)
|
|
417
|
+
if isinstance(b, Import) and b.module:
|
|
418
|
+
return Namespace(b.module) if b.name == "*" else self._export(b.module, b.name, depth + 1)
|
|
419
|
+
return None
|
|
420
|
+
|
|
421
|
+
def _method(self, cls: str, name: str, depth: int = 0) -> str | None:
|
|
422
|
+
"""The method `name` of the class `cls`, or of the class it extends."""
|
|
423
|
+
if found := self.class_methods.get(cls, {}).get(name):
|
|
424
|
+
return found
|
|
425
|
+
if cls in self.bases and depth < DEPTH:
|
|
426
|
+
base = self._binding(*self.bases[cls])
|
|
427
|
+
if isinstance(base, str):
|
|
428
|
+
return self._method(base, name, depth + 1)
|
|
429
|
+
return None
|
|
430
|
+
|
|
431
|
+
# ---------- the calls
|
|
432
|
+
|
|
433
|
+
def _calls(self, m: Module) -> None:
|
|
434
|
+
# T-0019: the module's own variables (a Svelte prop, `let { onouvrir } = $props()`) hide like a function's;
|
|
435
|
+
# its definitions and imports stay bindings.
|
|
436
|
+
root = m.tree.root_node
|
|
437
|
+
hidden = _declared(root) - m.bindings.keys() - _required(root)
|
|
438
|
+
stack = [(root, m.id, None, frozenset(hidden), self._typed(m, root))]
|
|
439
|
+
while stack:
|
|
440
|
+
node, owner, cls, hidden, types = stack.pop()
|
|
441
|
+
owner, cls = m.owners.get((node.start_byte, node.end_byte), (owner, cls))
|
|
442
|
+
if node.type in SCOPES:
|
|
443
|
+
declared = _declared(node)
|
|
444
|
+
hidden = hidden | declared
|
|
445
|
+
types = {k: v for k, v in types.items() if k not in declared} | self._typed(m, node)
|
|
446
|
+
if node.type in ("call_expression", "new_expression"):
|
|
447
|
+
callee = _callee(node)
|
|
448
|
+
if callee is not None:
|
|
449
|
+
self._call(m, owner, cls, hidden, types, callee, node)
|
|
450
|
+
if node.type == "call_expression" and callee is not None and callee.type == "identifier" \
|
|
451
|
+
and _text(callee) in TESTS and _text(callee) not in hidden:
|
|
452
|
+
self._test(m, owner, node)
|
|
453
|
+
elif node.type == "expression_statement" and len(node.named_children) == 1 \
|
|
454
|
+
and node.named_children[0].type == "identifier" and _text(node.named_children[0]) not in hidden:
|
|
455
|
+
# T-0022: a bare name, a handler of the markup (`onclick={fermer}`): a reference, not a call
|
|
456
|
+
if isinstance(target := self._binding(m, _text(node.named_children[0])), str) and target != owner:
|
|
457
|
+
self._link(owner, target, "references", m.rel, node)
|
|
458
|
+
stack.extend((c, owner, cls, hidden, types) for c in reversed(node.named_children))
|
|
459
|
+
|
|
460
|
+
def _test(self, m: Module, owner: str, node) -> None:
|
|
461
|
+
"""T-0021: `test('title', () => {...})`: a node named by its title, held by `owner` (its file, its
|
|
462
|
+
`describe`); the calls of the callback are its own."""
|
|
463
|
+
if isinstance(self._binding(m, _text(node.child_by_field_name("function"))), str):
|
|
464
|
+
return # a `test` of ours
|
|
465
|
+
arguments = node.child_by_field_name("arguments")
|
|
466
|
+
title = next((a for a in arguments.named_children if a.type in ("string", "template_string")), None)
|
|
467
|
+
callback = next((a for a in arguments.named_children if a.type in FUNCTION_VALUES), None)
|
|
468
|
+
if title is None or callback is None:
|
|
469
|
+
return
|
|
470
|
+
line = node.start_point[0] + 1
|
|
471
|
+
tid = self._node(f"{m.id}_test_{line}", _text(title)[1:-1], "test", m.rel, line, _text(title)[1:-1])
|
|
472
|
+
self._link(owner, tid, "contains", m.rel, node)
|
|
473
|
+
m.owners[(callback.start_byte, callback.end_byte)] = (tid, None)
|
|
474
|
+
|
|
475
|
+
def _typed(self, m: Module, scope) -> dict[str, str]:
|
|
476
|
+
"""T-0020: the variables of a scope assigned `new C()` or `[await] f()`, C a class of ours or f a function
|
|
477
|
+
of ours that returns an object literal: name -> what holds their methods."""
|
|
478
|
+
found = {}
|
|
479
|
+
stack = list(scope.named_children)
|
|
480
|
+
while stack:
|
|
481
|
+
node = stack.pop()
|
|
482
|
+
if node.type == "variable_declarator" and (value := node.child_by_field_name("value")) is not None:
|
|
483
|
+
if value.type == "await_expression" and value.named_children:
|
|
484
|
+
value = value.named_children[0]
|
|
485
|
+
callee = _callee(value) if value.type in ("new_expression", "call_expression") else None
|
|
486
|
+
name = node.child_by_field_name("name")
|
|
487
|
+
if callee is not None and callee.type == "identifier" and name.type == "identifier":
|
|
488
|
+
holder = self._binding(m, _text(callee))
|
|
489
|
+
if isinstance(holder, str) and holder in self.class_methods:
|
|
490
|
+
found[_text(name)] = holder
|
|
491
|
+
if node.type not in SCOPES:
|
|
492
|
+
stack.extend(node.named_children)
|
|
493
|
+
return found
|
|
494
|
+
|
|
495
|
+
def _call(self, m: Module, owner: str, cls: str | None, hidden: frozenset, types: dict[str, str], callee,
|
|
496
|
+
node) -> None:
|
|
497
|
+
"""A call from `owner`: its link, and its site. `hidden`: the names its functions declare; `types`: the
|
|
498
|
+
variables whose methods are known (T-0020)."""
|
|
499
|
+
target, sure, verdict = None, True, "unknown"
|
|
500
|
+
name = _text(callee)
|
|
501
|
+
if callee.type == "identifier":
|
|
502
|
+
b = m.bindings.get(name)
|
|
503
|
+
if name in hidden:
|
|
504
|
+
verdict = "local"
|
|
505
|
+
elif b is not None:
|
|
506
|
+
target = self._binding(m, name)
|
|
507
|
+
verdict = "ours" if isinstance(target, str) else "external" if isinstance(target, Package) else "absent"
|
|
508
|
+
target = target if isinstance(target, str) else None
|
|
509
|
+
elif name in GLOBALS:
|
|
510
|
+
verdict = "global"
|
|
511
|
+
elif len(ours := self.by_name.get(name, [])) == 1:
|
|
512
|
+
target, sure, verdict = ours[0], False, "ours?"
|
|
513
|
+
elif ours:
|
|
514
|
+
verdict = "ambiguous"
|
|
515
|
+
elif callee.type == "member_expression":
|
|
516
|
+
receiver, name = callee.child_by_field_name("object"), _text(callee.child_by_field_name("property"))
|
|
517
|
+
known = receiver.type == "identifier" and _text(receiver) not in hidden
|
|
518
|
+
b = m.bindings.get(_text(receiver)) if known else None
|
|
519
|
+
if receiver.type == "identifier" and _text(receiver) in types:
|
|
520
|
+
target = self._method(types[_text(receiver)], name)
|
|
521
|
+
elif receiver.type == "this" and cls:
|
|
522
|
+
target = self._method(cls, name)
|
|
523
|
+
elif isinstance(b, Import) and b.module is None:
|
|
524
|
+
verdict = "external"
|
|
525
|
+
elif b is not None:
|
|
526
|
+
holder = self._binding(m, _text(receiver))
|
|
527
|
+
if isinstance(holder, Namespace):
|
|
528
|
+
target = self._export(holder.module, name)
|
|
529
|
+
target = target if isinstance(target, str) else None
|
|
530
|
+
elif isinstance(holder, Package):
|
|
531
|
+
verdict = "external"
|
|
532
|
+
elif holder and holder not in self.returning: # `Class.m()`, `objet.m()`; not `f.m()` (T-0020)
|
|
533
|
+
target = self._method(holder, name)
|
|
534
|
+
elif known and _text(receiver) in GLOBALS:
|
|
535
|
+
verdict = "global"
|
|
536
|
+
if target:
|
|
537
|
+
verdict = "ours"
|
|
538
|
+
elif verdict == "unknown":
|
|
539
|
+
ours = self.methods.get(name, [])
|
|
540
|
+
if len(ours) == 1:
|
|
541
|
+
target, sure, verdict = ours[0], False, "ours?"
|
|
542
|
+
else:
|
|
543
|
+
verdict = "ambiguous" if ours else "member"
|
|
544
|
+
if target and target != owner:
|
|
545
|
+
self._link(owner, target, "calls", m.rel, node, sure)
|
|
546
|
+
self.sites.append({"verdict": verdict, "file": m.rel, "line": node.start_point[0] + 1, "name": name,
|
|
547
|
+
"text": _text(callee)[:60]})
|
|
548
|
+
|
|
549
|
+
# ---------- the graph
|
|
550
|
+
|
|
551
|
+
def _node(self, nid: str, label: str, kind: str, rel: str, line: int, name: str) -> str:
|
|
552
|
+
"""A node; its id, made unique (`get x` and `set x`, `Foo` and `foo`): an id taken would merge them."""
|
|
553
|
+
base, n = nid, 2
|
|
554
|
+
while nid in self.ids:
|
|
555
|
+
nid, n = f"{base}_{n}", n + 1
|
|
556
|
+
self.ids.add(nid)
|
|
557
|
+
self.nodes.append({"id": nid, "label": label, "kind": kind, "source_file": rel,
|
|
558
|
+
"source_location": f"L{line}", "name": name})
|
|
559
|
+
return nid
|
|
560
|
+
|
|
561
|
+
def _link(self, source: str, target: str, relation: str, rel: str, node, sure: bool = True) -> None:
|
|
562
|
+
self.links.append({"source": source, "target": target, "relation": relation,
|
|
563
|
+
"confidence": "EXTRACTED" if sure else "INFERRED", "source_file": rel,
|
|
564
|
+
"source_location": f"L{node.start_point[0] + 1}", "context": ""})
|