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/godot.py ADDED
@@ -0,0 +1,386 @@
1
+ """The code graph, client side: the host's GDScript scripts (res://: godot/).
2
+
3
+ Each .gd script of the host becomes nodes and links, which cli.py merges
4
+ with those of the other readers.
5
+
6
+ What the reader reads, by patterns and not by a grammar:
7
+ - a file, its functions (`func`), its signals;
8
+ - `const X = preload("res://...")`: X designates that file;
9
+ - a variable typed by X or made by `X.new()`: its calls go to X;
10
+ - `X.f(...)`, `f(...)`, `self.f(...)`; a function passed as a value (a
11
+ signal handler); `call_deferred("f")`;
12
+
13
+ `graphe check` recounts the calls with another reader (Python's tokenize,
14
+ `contribute`) and classifies each: our code, the engine (from the API Godot
15
+ exports), an anonymous function, ambiguous or unknown. An unlinked call that
16
+ bears the name of one of our functions is a miss of the reader.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import bisect
22
+ import io
23
+ import json
24
+ import re
25
+ import subprocess
26
+ import sys
27
+ import tempfile
28
+ import tokenize
29
+ from collections import Counter, defaultdict
30
+ from pathlib import Path
31
+
32
+ from graphe import root
33
+ from graphe.root import OUTPUT, ROOT
34
+
35
+ # shortcut: res:// starts at godot/, as in the first host; a .gd elsewhere breaks - look for project.godot if
36
+ # needed.
37
+ GODOT = ROOT / "godot"
38
+
39
+ KEYWORDS = {"if", "elif", "while", "for", "match", "return", "and", "or", "not", "in", "is", "as", "func",
40
+ "await", "var", "const", "signal", "static", "class", "extends", "breakpoint", "pass", "else"}
41
+ # The language's functions, outside the API the engine exports.
42
+ LANGUAGE_BUILTINS = {"preload", "load", "assert", "char", "len", "range", "print_debug", "print_stack", "get_stack",
43
+ "inst_to_dict", "dict_to_inst", "is_instance_of", "type_exists", "convert", "Color8", "ord",
44
+ "super", "_init"}
45
+ CALLS_BY_NAME = re.compile(r"""\b(?:call_deferred|callv?|has_method|Callable\(\s*self\s*,)\s*\(?\s*"(\w+)\"""")
46
+
47
+
48
+ def scripts() -> list[Path]:
49
+ return root.files(".gd")
50
+
51
+
52
+ def _id(path: Path) -> str:
53
+ return re.sub(r"\W", "_", str(path.relative_to(ROOT).with_suffix("")).replace("\\", "/")).lower()
54
+
55
+
56
+ def _rel(path: Path) -> str:
57
+ return path.relative_to(ROOT).as_posix()
58
+
59
+
60
+ def res(target: str) -> str:
61
+ """The host's file behind `res://target` (`menu/outils.gd` -> `godot/menu/outils.gd`)."""
62
+ return _rel(GODOT / target)
63
+
64
+
65
+ def mask(text: str) -> tuple[str, list[tuple[int, str]]]:
66
+ """The text, strings and comments blanked (quotes and line breaks
67
+ kept), and each string: (start, value)."""
68
+ out = list(text)
69
+ strings = []
70
+ i, n = 0, len(text)
71
+ while i < n:
72
+ c = text[i]
73
+ if c == "#":
74
+ j = text.find("\n", i)
75
+ j = n if j < 0 else j
76
+ out[i:j] = " " * (j - i)
77
+ i = j
78
+ elif c in "\"'":
79
+ end = c * 3 if text.startswith(c * 3, i) else c
80
+ start = j = i + len(end)
81
+ # A plain GDScript string can run over a line break (lectures.gd).
82
+ while j < n and not text.startswith(end, j):
83
+ j += 2 if text[j] == "\\" else 1
84
+ strings.append((i, text[start:j]))
85
+ for k in range(start, min(j, n)):
86
+ if out[k] != "\n":
87
+ out[k] = " "
88
+ i = j + len(end)
89
+ else:
90
+ i += 1
91
+ return "".join(out), strings
92
+
93
+
94
+ class Script:
95
+ """A script read: its functions, its preload aliases, its typed
96
+ variables, its signals - and, line by line, the function that encloses
97
+ it."""
98
+
99
+ def __init__(self, path: Path) -> None:
100
+ self.path = path
101
+ self.id = _id(path)
102
+ self.text = path.read_bytes().decode("utf-8")
103
+ self.masked, self.strings = mask(self.text)
104
+ self.lines = self.masked.split("\n")
105
+ self.starts = [0]
106
+ for m in re.finditer("\n", self.masked):
107
+ self.starts.append(m.end())
108
+ self.functions: dict[str, int] = {}
109
+ self.enclosing: list[str | None] = [None] * len(self.lines)
110
+ self.alias: dict[str, str] = {}
111
+ self.types: dict[str, str] = {}
112
+ self.anonymous: set[str] = set()
113
+ self.signals: dict[str, int] = {}
114
+ self._read()
115
+
116
+ def line_of(self, position: int) -> int:
117
+ return bisect.bisect_right(self.starts, position)
118
+
119
+ def string_at(self, position: int) -> str | None:
120
+ i = bisect.bisect_left(self.strings, (position, ""))
121
+ return self.strings[i][1] if i < len(self.strings) and self.strings[i][0] == position else None
122
+
123
+ def _read(self) -> None:
124
+ current, indent = None, -1
125
+ for number, line in enumerate(self.lines):
126
+ content = line.strip()
127
+ shift = len(line) - len(line.lstrip())
128
+ if current and content and shift <= indent:
129
+ current = None
130
+ m = re.match(r"\s*(?:static\s+)?func\s+([A-Za-z_]\w*)\s*\(", line)
131
+ if m:
132
+ current, indent = m.group(1), shift
133
+ self.functions[current] = number + 1
134
+ for name, type_ in re.findall(r"(\w+)\s*:\s*([A-Za-z_]\w*)", line[m.end():]):
135
+ self.types[name] = type_
136
+ self.enclosing[number] = current
137
+ m = re.match(r"\s*signal\s+(\w+)", line)
138
+ if m:
139
+ self.signals[m.group(1)] = number + 1
140
+ line_start = 0
141
+ for line in self.lines:
142
+ m = re.match(r"\s*(?:@\w+(?:\([^)]*\))?\s+)*(?:static\s+)?(?:const|var)\s+(\w+)\s*(?::\s*([A-Za-z_]\w*))?"
143
+ r"[^=\n]*?(?::?=\s*(.*))?$", line)
144
+ if m:
145
+ name, type_, value = m.group(1), m.group(2), m.group(3) or ""
146
+ p = re.match(r"(?:pre)?load\(\s*\"", value)
147
+ if p:
148
+ path = self.string_at(line_start + m.start(3) + p.end() - 1)
149
+ if path and path.endswith(".gd"):
150
+ self.alias[name] = path
151
+ else:
152
+ n = re.match(r"([A-Za-z_]\w*)\.new\(", value)
153
+ if n:
154
+ self.types[name] = n.group(1)
155
+ elif type_:
156
+ self.types[name] = type_
157
+ if re.match(r"func\s*\(", value):
158
+ self.anonymous.add(name)
159
+ line_start += len(line) + 1
160
+ # A variable declared Node, made further down by one of our scripts:
161
+ # that script receives its calls.
162
+ for name, type_ in re.findall(r"(?<![\w.])(\w+)[ \t]*=[ \t]*([A-Za-z_]\w*)\.new\(", self.masked):
163
+ if type_ in self.alias or name not in self.types:
164
+ self.types[name] = type_
165
+
166
+
167
+ class Reader:
168
+ def __init__(self, api: dict | None = None, paths: list[Path] | None = None) -> None:
169
+ self.scripts = {f"res://{s.relative_to(GODOT).as_posix()}": Script(s)
170
+ for s in (scripts() if paths is None else paths)}
171
+ self.by_name: dict[str, list[Script]] = defaultdict(list)
172
+ for s in self.scripts.values():
173
+ for name in s.functions:
174
+ self.by_name[name].append(s)
175
+ # Without GDScript, no Godot to run.
176
+ self.engine_methods, self.engine_names = _engine_api(api) if self.scripts else (set(), set())
177
+ self.nodes: list[dict] = []
178
+ self.links: list[dict] = []
179
+ self.sites: list[dict] = []
180
+ for s in self.scripts.values():
181
+ self._nodes(s)
182
+ for s in self.scripts.values():
183
+ self._calls(s)
184
+
185
+ def _node(self, s: Script, id_: str, label: str, line: int, kind: str, name: str) -> None:
186
+ self.nodes.append({"id": id_, "label": label, "kind": kind, "source_file": _rel(s.path),
187
+ "source_location": f"L{line}", "name": name})
188
+
189
+ def _link(self, s: Script, source: str, target: str, relation: str, line: int, sure: bool = True,
190
+ context: str = "") -> None:
191
+ self.links.append({"source": source, "target": target, "relation": relation,
192
+ "confidence": "EXTRACTED" if sure else "INFERRED", "context": context,
193
+ "source_file": _rel(s.path), "source_location": f"L{line}"})
194
+
195
+ def _nodes(self, s: Script) -> None:
196
+ self._node(s, s.id, s.path.name, 1, "file", _rel(s.path))
197
+ for name, line in s.functions.items():
198
+ self._node(s, f"{s.id}_{name.lower()}", f"{name}()", line, "function", name)
199
+ self._link(s, s.id, f"{s.id}_{name.lower()}", "contains", line)
200
+ for name, line in s.signals.items():
201
+ self._node(s, f"{s.id}_signal_{name.lower()}", f"{name} (signal)", line, "signal", name)
202
+ self._link(s, s.id, f"{s.id}_signal_{name.lower()}", "contains", line)
203
+ for alias, path in s.alias.items():
204
+ if path in self.scripts:
205
+ self._link(s, s.id, self.scripts[path].id, "imports", 1, context=alias)
206
+
207
+ def _context(self, s: Script, line: int) -> str:
208
+ name = s.enclosing[line - 1]
209
+ return f"{s.id}_{name.lower()}" if name else s.id
210
+
211
+ def _script_of(self, s: Script, receiver: str) -> Script | None:
212
+ """The script a receiver designates: an alias, or a variable typed
213
+ by an alias."""
214
+ bearer = s
215
+ for i, segment in enumerate(receiver.split(".")):
216
+ if i == 0 and segment in bearer.alias:
217
+ target = bearer.alias[segment]
218
+ elif bearer.types.get(segment) in bearer.alias:
219
+ target = bearer.alias[bearer.types[segment]]
220
+ else:
221
+ return None
222
+ bearer = self.scripts.get(target)
223
+ if bearer is None:
224
+ return None
225
+ return bearer
226
+
227
+ def _calls(self, s: Script) -> None:
228
+ for m in re.finditer(r"\b([A-Za-z_]\w*)[ \t]*\(", s.masked):
229
+ name = m.group(1)
230
+ before = s.masked[max(0, m.start() - 200):m.start()].rstrip() # a window: the whole prefix made reading quadratic
231
+ if name in KEYWORDS or re.search(r"\b(?:func|signal)$", before):
232
+ continue
233
+ receiver = ""
234
+ if before.endswith("."):
235
+ r = re.search(r"([A-Za-z_][\w.]*)\s*\.$", before)
236
+ receiver = r.group(1) if r and not before[:r.start()].rstrip().endswith(".") else "<expr>"
237
+ receiver = receiver.removeprefix("self.")
238
+ if receiver == "self":
239
+ receiver = ""
240
+ line = s.line_of(m.start())
241
+ self.sites.append({"script": s, "line": line, "name": name, "receiver": receiver,
242
+ **self._resolve(s, name, receiver, line, m.end())})
243
+ for m in re.finditer(r"(?<![.\w])([A-Za-z_]\w*)(?:\.([A-Za-z_]\w*))?\b(?!\s*\()", s.masked):
244
+ head, member = m.group(1), m.group(2)
245
+ line = s.line_of(m.start())
246
+ before = s.masked[max(0, m.start() - 20):m.start()].rstrip()
247
+ if re.search(r"\bfunc$", before):
248
+ continue
249
+ if member is None and head in s.functions:
250
+ self._link(s, self._context(s, line), f"{s.id}_{head.lower()}", "references", line)
251
+ elif member and head in s.alias and s.alias[head] in self.scripts:
252
+ target = self.scripts[s.alias[head]]
253
+ if member in target.functions:
254
+ self._link(s, self._context(s, line), f"{target.id}_{member.lower()}", "references", line)
255
+ for m in CALLS_BY_NAME.finditer(s.text):
256
+ if s.masked[m.start()] == s.text[m.start()] and m.group(1) in s.functions:
257
+ line = s.line_of(m.start())
258
+ self._link(s, self._context(s, line), f"{s.id}_{m.group(1).lower()}", "indirect_call", line)
259
+
260
+ def _resolve(self, s: Script, name: str, receiver: str, line: int, after: int) -> dict:
261
+ source = self._context(s, line)
262
+ if not receiver:
263
+ if name in s.functions:
264
+ self._link(s, source, f"{s.id}_{name.lower()}", "calls", line)
265
+ return {"verdict": "ours"}
266
+ if name in LANGUAGE_BUILTINS or name in self.engine_names or name in self.engine_methods:
267
+ return {"verdict": "engine"}
268
+ return {"verdict": "unknown"}
269
+ target = self._script_of(s, receiver)
270
+ if target is not None:
271
+ if name in target.functions:
272
+ self._link(s, source, f"{target.id}_{name.lower()}", "calls", line)
273
+ return {"verdict": "ours"}
274
+ if name == "new":
275
+ self._link(s, source, target.id, "uses", line, context="new")
276
+ return {"verdict": "ours"}
277
+ return {"verdict": "engine" if name in self.engine_methods else "unknown"}
278
+ last = receiver.split(".")[-1]
279
+ if name in ("connect", "emit", "disconnect", "is_connected"):
280
+ bearer = s if last == receiver else self._script_of(s, receiver.rsplit(".", 1)[0])
281
+ if bearer is not None and last in bearer.signals:
282
+ relation = "emits" if name == "emit" else "connects"
283
+ self._link(s, source, f"{bearer.id}_signal_{last.lower()}", relation, line)
284
+ return {"verdict": "ours"}
285
+ return {"verdict": "engine"}
286
+ if name == "call" and last in s.anonymous:
287
+ return {"verdict": "anonymous"}
288
+ head = receiver.split(".")[0]
289
+ if (head in self.engine_names or (receiver == head and s.types.get(head) in self.engine_names)) \
290
+ and (name in self.engine_methods or name not in self.by_name):
291
+ return {"verdict": "engine"}
292
+ ours = self.by_name.get(name, [])
293
+ if ours and name not in self.engine_methods:
294
+ for other in ours:
295
+ self._link(s, source, f"{other.id}_{name.lower()}", "calls", line, sure=False)
296
+ return {"verdict": "ours?" if len(ours) == 1 else "ambiguous"}
297
+ if name in self.engine_methods:
298
+ return {"verdict": "ambiguous" if ours else "engine"}
299
+ return {"verdict": "unknown"}
300
+
301
+
302
+ def _engine_api(api: dict | None) -> tuple[set[str], set[str]]:
303
+ """The methods and the names (classes, global functions) of the API
304
+ Godot exports (--dump-extension-api)."""
305
+ cached = OUTPUT / "extension_api.json"
306
+ if api is None and not cached.exists():
307
+ # Looked for after the cache: a frozen tree can receive the API without Godot.
308
+ godot = root.executable("godot", "godot")
309
+ if godot is None:
310
+ return set(), set() # nothing in cache: the key, once set, serves at the next build
311
+ with tempfile.TemporaryDirectory() as folder:
312
+ try:
313
+ subprocess.run([str(godot), "--headless", "--dump-extension-api"], cwd=folder,
314
+ capture_output=True, timeout=180, check=False)
315
+ raw = (Path(folder) / "extension_api.json").read_bytes()
316
+ api = json.loads(raw) # a broken JSON stays out of the cache: it would break every build
317
+ except (OSError, ValueError, subprocess.SubprocessError) as e:
318
+ print(f"graphe: {godot} ([godot] executable) did not give the engine API ({e}):"
319
+ " its calls stay unresolved", file=sys.stderr)
320
+ return set(), set()
321
+ OUTPUT.mkdir(exist_ok=True)
322
+ cached.write_bytes(raw)
323
+ if api is None:
324
+ api = json.loads(cached.read_bytes())
325
+ methods, names = set(), set()
326
+ for class_ in api["classes"] + api["builtin_classes"]:
327
+ names.add(class_["name"])
328
+ methods |= {m["name"] for m in class_.get("methods", [])}
329
+ methods |= {s["name"] for s in class_.get("signals", [])}
330
+ names |= {f["name"] for f in api["utility_functions"]}
331
+ names |= {s["name"] for s in api["singletons"]}
332
+ return methods, names
333
+
334
+
335
+ # ---------- check
336
+
337
+ def _calls_by_tokenize(path: Path) -> Counter:
338
+ """A script's calls, read by another reader: Python's tokenize (GDScript
339
+ looks enough like it: strings, comments, indentation). A name followed
340
+ by a parenthesis, outside a definition. A plain string that runs over a
341
+ line break, which Python refuses, gets a continuation backslash where it
342
+ stops: the line numbers stay."""
343
+ lines = path.read_bytes().decode("utf-8").split("\n")
344
+ while True:
345
+ try:
346
+ tokens = list(tokenize.generate_tokens(io.StringIO("\n".join(lines)).readline))
347
+ break
348
+ except tokenize.TokenError as e:
349
+ if "unterminated string" not in e.args[0]:
350
+ raise
351
+ lines[e.args[1][0] - 1] += "\\"
352
+ sites = Counter()
353
+ for i, token in enumerate(tokens[:-1]):
354
+ following = tokens[i + 1]
355
+ preceding = tokens[i - 1] if i else None
356
+ if token.type == tokenize.NAME and following.string == "(" and token.string not in KEYWORDS \
357
+ and not (preceding and preceding.string in ("func", "signal")):
358
+ sites[(token.start[0], token.string)] += 1
359
+ return sites
360
+
361
+
362
+ def contribute(project) -> dict:
363
+ """The GDScript reader's contribution (docs/contribution.md): a site per call, and its alerts.
364
+
365
+ Under `graphe check`, the calls are recounted by another reader (Python's tokenize): a missed call is an
366
+ alert.
367
+ """
368
+ reader = Reader(paths=project.files(".gd"))
369
+ ids = {n["id"] for n in reader.nodes}
370
+ sites = []
371
+ for s in reader.sites:
372
+ site = {"verdict": s["verdict"], "file": _rel(s["script"].path), "line": s["line"], "name": s["name"],
373
+ "text": f"{s['receiver'] or '-'}.{s['name']}"}
374
+ if s["verdict"] == "unknown" and s["name"] in reader.by_name:
375
+ site["alert"] = "not linked to the name of one of our functions"
376
+ sites.append(site)
377
+ if project.checking:
378
+ read_calls = Counter((_rel(site["script"].path), site["line"], site["name"]) for site in reader.sites)
379
+ recounted = Counter()
380
+ for s in reader.scripts.values():
381
+ for (line, name), n in _calls_by_tokenize(s.path).items():
382
+ recounted[(_rel(s.path), line, name)] += n
383
+ # A call too many never made check fail: only the misses are alerts.
384
+ for (file, line, name), n in sorted((recounted - read_calls).items()):
385
+ sites += [{"file": file, "line": line, "name": name, "text": name, "alert": "missed by the reader"}] * n
386
+ return {"nodes": reader.nodes, "sites": sites, "links": [e for e in reader.links if e["target"] in ids]}