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/python.py ADDED
@@ -0,0 +1,917 @@
1
+ """The code graph, Python side: modules, classes, functions and calls.
2
+
3
+ Read by Python's ast. A call is linked to its target when its receiver has
4
+ a known type: an annotation (parameter, variable, attribute, dataclass
5
+ field, return), a construction (`x = Class(...)`, `self.x = Class(...)`),
6
+ an iteration over a typed container, an inferred return
7
+ (`return Class(...)`). Failing that, a name borne by a single one of our
8
+ functions is linked by the name alone (INFERRED); borne by several, it stays
9
+ unlinked and counts as `ambiguous`.
10
+
11
+ `graphe check` reads the classification of each call in the sites of its
12
+ contribution (`contribute`).
13
+
14
+ T-0026: each file's parse and definitions are kept in graphe/cache, keyed by
15
+ this file, the Python version, the path and the content; the resolution
16
+ across modules is redone at each build.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import ast
22
+ import builtins
23
+ import hashlib
24
+ import os
25
+ import pickle
26
+ import re
27
+ import sys
28
+ from collections import defaultdict
29
+ from dataclasses import dataclass, field
30
+ from pathlib import Path
31
+
32
+ from graphe import root
33
+ from graphe.root import ROOT
34
+
35
+ BUILTINS = set(dir(builtins))
36
+ # The methods of the containers we know how to type: what they return.
37
+ TO_ELEMENT = {"get", "pop", "setdefault", "__getitem__"}
38
+ TO_CONTAINER = {"values", "copy", "keys"}
39
+
40
+
41
+ def files() -> list[Path]:
42
+ return root.files(".py")
43
+
44
+
45
+ def _id(text: str) -> str:
46
+ return re.sub(r"\W", "_", text).lower()
47
+
48
+
49
+ @dataclass(eq=False)
50
+ class Function:
51
+ id: str
52
+ name: str
53
+ qualname: str
54
+ module: Module
55
+ cls: Class | None
56
+ parent: Function | None
57
+ node: ast.FunctionDef | ast.AsyncFunctionDef
58
+ locals: dict[str, list] = field(default_factory=lambda: defaultdict(list))
59
+
60
+ @property
61
+ def decorators(self) -> set[str]:
62
+ return {d.id if isinstance(d, ast.Name) else d.attr for d in self.node.decorator_list
63
+ if isinstance(d, (ast.Name, ast.Attribute))}
64
+
65
+
66
+ @dataclass(eq=False)
67
+ class Class:
68
+ id: str
69
+ name: str
70
+ qualname: str
71
+ module: Module
72
+ node: ast.ClassDef
73
+ methods: dict[str, Function] = field(default_factory=dict)
74
+ # name -> [(expression, "annotation" | "value", the function where it is written)]
75
+ attributes: dict[str, list] = field(default_factory=lambda: defaultdict(list))
76
+ # The fields annotated in the class body (a dataclass): name -> line.
77
+ fields: dict[str, int] = field(default_factory=dict)
78
+
79
+
80
+ @dataclass(eq=False)
81
+ class Module:
82
+ id: str
83
+ name: str
84
+ rel: str
85
+ tree: ast.Module
86
+ functions: dict[str, Function] = field(default_factory=dict)
87
+ classes: dict[str, Class] = field(default_factory=dict)
88
+ imports: dict[str, tuple] = field(default_factory=dict)
89
+ variables: dict[str, list] = field(default_factory=lambda: defaultdict(list))
90
+
91
+
92
+ def _store(entry: Path, value: tuple) -> None:
93
+ """Writes alongside then replaces: a build that reads at the same time never sees half an entry."""
94
+ temporary = entry.with_suffix(f".{os.getpid()}.tmp")
95
+ try:
96
+ data = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL)
97
+ if not entry.parent.is_dir(): # outside git even in a host without `graphe install` (pytest's way)
98
+ entry.parent.mkdir(parents=True)
99
+ (entry.parent / ".gitignore").write_text("*\n", encoding="utf-8")
100
+ temporary.write_bytes(data)
101
+ os.replace(temporary, entry)
102
+ # shortcut: a tree too deep for pickle is read again at each build; raise the recursion limit if one is slow.
103
+ except RecursionError:
104
+ pass
105
+ except OSError: # the entry open by another build (Windows), a full disk: the cache is only a gain
106
+ temporary.unlink(missing_ok=True)
107
+
108
+
109
+ def _load(entry: Path | None) -> tuple | None:
110
+ """A module's definitions from the cache, or None. The cache is the host's (graphe/), like its extensions,
111
+ which graphe runs too."""
112
+ if entry is None:
113
+ return None
114
+ try:
115
+ return pickle.loads(entry.read_bytes())
116
+ except Exception: # absent, unreadable, or written by another build at this instant
117
+ return None
118
+
119
+
120
+ def _module_name(rel: str) -> str:
121
+ name = rel.removesuffix(".py").replace("/", ".")
122
+ return name.removesuffix(".__init__")
123
+
124
+
125
+ class Reader:
126
+ """All our modules read, and each call classified."""
127
+
128
+ def __init__(self, paths: list[Path] | None = None, root: Path = ROOT, cache: Path | None = None) -> None:
129
+ self.root = root
130
+ self.modules: dict[str, Module] = {}
131
+ # T-0026: a module's definitions, read from its file alone: module name -> (module, its classes and
132
+ # functions in reading order, or None if to read, the cache file)
133
+ read: dict[str, tuple] = {}
134
+ tool = hashlib.sha256(Path(__file__).read_bytes() + sys.version.encode()).digest()
135
+ for path in paths if paths is not None else files():
136
+ rel = path.relative_to(root).as_posix()
137
+ content = path.read_bytes()
138
+ entry = cache / f"{hashlib.sha256(tool + rel.encode() + b'\0' + content).hexdigest()[:32]}.pickle" \
139
+ if cache else None
140
+ if cached := _load(entry):
141
+ m, classes, functions = cached
142
+ else:
143
+ try:
144
+ tree = ast.parse(content, filename=rel)
145
+ except (SyntaxError, ValueError) as e: # ValueError: a null byte
146
+ print(f"graphe: {rel} does not parse, skipped ({e})", file=sys.stderr)
147
+ continue
148
+ m, classes, functions = Module(_id(rel.removesuffix(".py")), _module_name(rel), rel, tree), None, None
149
+ self.modules[m.name] = m
150
+ read[m.name] = (m, classes, functions, entry)
151
+ self.functions: list[Function] = []
152
+ self.classes: list[Class] = []
153
+ for m in self.modules.values():
154
+ _, classes, functions, entry = read[m.name]
155
+ if classes is None:
156
+ first_class, first_function = len(self.classes), len(self.functions)
157
+ self._read_module(m)
158
+ classes, functions = self.classes[first_class:], self.functions[first_function:]
159
+ if entry is not None:
160
+ _store(entry, (m, classes, functions))
161
+ else:
162
+ self.classes += classes
163
+ self.functions += functions
164
+ if cache is not None and cache.is_dir(): # the entries of files gone or changed
165
+ used = {e.name for *_, e in read.values()}
166
+ for p in cache.glob("*.pickle"):
167
+ if p.name not in used:
168
+ try:
169
+ p.unlink(missing_ok=True)
170
+ except OSError: # open by another build (Windows)
171
+ pass
172
+ self.by_name: dict[str, list[Function]] = defaultdict(list)
173
+ for f in self.functions:
174
+ self.by_name[f.name].append(f)
175
+ self.class_names = {c.name for c in self.classes}
176
+ # T-0026: what holds a nested class, a table rather than a scan of every class per class (Django: 1.7 s)
177
+ self._holders: dict[tuple, str] = {}
178
+ for holder in [*self.classes, *self.functions]:
179
+ self._holders.setdefault((id(holder.module), holder.qualname), holder.id)
180
+ self.nodes: list[dict] = []
181
+ self.links: list[dict] = []
182
+ self.sites: list[dict] = []
183
+ self._memo: dict = {}
184
+ self._in_progress: set = set()
185
+ self._emit()
186
+
187
+ # ---------- reading the definitions
188
+
189
+ def _read_module(self, m: Module) -> None:
190
+ for node in m.tree.body:
191
+ self._read_import(m, node)
192
+ for node in self._statements(m.tree.body):
193
+ if isinstance(node, (ast.Assign, ast.AnnAssign)):
194
+ self._note_assignment(m.variables, node, None)
195
+ self._read_body(m, m.tree.body, m.id, "", None, None)
196
+
197
+ @staticmethod
198
+ def _import_entries(m: Module, node: ast.stmt) -> dict[str, tuple]:
199
+ if isinstance(node, ast.Import):
200
+ return {a.asname or a.name.split(".")[0]: ("module", a.name if a.asname else a.name.split(".")[0])
201
+ for a in node.names}
202
+ if isinstance(node, ast.ImportFrom):
203
+ base = node.module or ""
204
+ if node.level:
205
+ package = m.name.split(".") if m.rel.endswith("__init__.py") else m.name.split(".")[:-1]
206
+ package = package[:len(package) - node.level + 1]
207
+ base = ".".join(package + ([base] if base else []))
208
+ return {a.asname or a.name: ("symbol", base, a.name) for a in node.names}
209
+ return {}
210
+
211
+ def _read_import(self, m: Module, node: ast.stmt) -> None:
212
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
213
+ m.imports.update(self._import_entries(m, node))
214
+ elif isinstance(node, (ast.If, ast.Try)):
215
+ for sub in [*node.body, *getattr(node, "orelse", []), *getattr(node, "finalbody", []),
216
+ *[s for h in getattr(node, "handlers", []) for s in h.body]]:
217
+ self._read_import(m, sub)
218
+
219
+ def _read_body(self, m: Module, body: list, parent_id: str, prefix: str, cls: Class | None,
220
+ function: Function | None) -> None:
221
+ for node in self._definitions(body):
222
+ if isinstance(node, ast.ClassDef):
223
+ qual = prefix + node.name
224
+ c = Class(f"{m.id}_{_id(qual)}", node.name, qual, m, node)
225
+ self.classes.append(c)
226
+ if function is None and cls is None:
227
+ m.classes[node.name] = c
228
+ elif function is not None:
229
+ function.locals[node.name].append((c, "class", function, (node.lineno, None)))
230
+ elif cls is not None:
231
+ cls.attributes[node.name].append((node, "class", None))
232
+ for sub in node.body:
233
+ if isinstance(sub, (ast.Assign, ast.AnnAssign)):
234
+ self._note_assignment(c.attributes, sub, None)
235
+ if isinstance(sub, ast.AnnAssign) and isinstance(sub.target, ast.Name):
236
+ c.fields[sub.target.id] = sub.lineno
237
+ self._read_body(m, node.body, c.id, qual + ".", c, None)
238
+ else:
239
+ qual = prefix + node.name
240
+ f = Function(f"{m.id}_{_id(qual)}", node.name, qual, m, cls, function, node)
241
+ self.functions.append(f)
242
+ if function is not None:
243
+ function.locals[node.name].append((f, "def", function, (node.lineno, None)))
244
+ if function is None:
245
+ if cls is not None:
246
+ cls.methods[node.name] = f
247
+ else:
248
+ m.functions[node.name] = f
249
+ self._read_locals(f)
250
+ self._read_body(m, node.body, f.id, qual + ".", None, f)
251
+
252
+ @staticmethod
253
+ def _statements(body: list):
254
+ """The statements of a body, including under an if or a try, without
255
+ entering the defs and classes."""
256
+ stack = list(body)
257
+ while stack:
258
+ node = stack.pop(0)
259
+ yield node
260
+ if isinstance(node, (ast.If, ast.Try, ast.With, ast.For, ast.While)):
261
+ stack[0:0] = [*node.body, *getattr(node, "orelse", []), *getattr(node, "finalbody", []),
262
+ *[s for h in getattr(node, "handlers", []) for s in h.body]]
263
+
264
+ @staticmethod
265
+ def _definitions(body: list):
266
+ """The defs and classes of a body, including under an if or a try."""
267
+ stack = list(body)
268
+ while stack:
269
+ node = stack.pop(0)
270
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
271
+ yield node
272
+ elif isinstance(node, (ast.If, ast.Try, ast.With, ast.For, ast.While)):
273
+ stack[0:0] = [*node.body, *getattr(node, "orelse", []), *getattr(node, "finalbody", []),
274
+ *[s for h in getattr(node, "handlers", []) for s in h.body]]
275
+
276
+ @staticmethod
277
+ def _note_assignment(table: dict, node: ast.stmt, function: Function | None, location: tuple = ()) -> None:
278
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
279
+ table[node.target.id].append((node.annotation, "annotation", function, *location))
280
+ elif isinstance(node, ast.Assign):
281
+ for target in node.targets:
282
+ if isinstance(target, ast.Name):
283
+ table[target.id].append((node.value, "value", function, *location))
284
+
285
+ def _read_locals(self, f: Function) -> None:
286
+ # Each source of a local variable bears its location: (line, None)
287
+ # for an assignment, (start, end) for a comprehension variable.
288
+ a = f.node.args
289
+ params = [*a.posonlyargs, *a.args, *a.kwonlyargs]
290
+ start = (f.node.lineno, None)
291
+ for i, p in enumerate(params):
292
+ if p.annotation is not None:
293
+ f.locals[p.arg].append((p.annotation, "annotation", f, start))
294
+ elif i == 0 and f.cls is not None and f.parent is None and "staticmethod" not in f.decorators:
295
+ f.locals[p.arg].append(
296
+ (f.cls, "class" if "classmethod" in f.decorators else "instance", f, start))
297
+ own = list(self._own_nodes(f.node)) # T-0026: walked once, not twice (Django: 4.4 million nodes)
298
+ globals_ = {name for n in own if isinstance(n, ast.Global) for name in n.names}
299
+ for node in own:
300
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
301
+ for local, imp in self._import_entries(f.module, node).items():
302
+ f.locals[local].append((imp, "import", f, (node.lineno, None)))
303
+ if local in globals_: # a module loaded later, by `global` in a function
304
+ f.module.imports[local] = imp
305
+ elif isinstance(node, (ast.Assign, ast.AnnAssign)):
306
+ location = (node.lineno, None)
307
+ self._note_assignment(f.locals, node, f, (location,))
308
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
309
+ for target in targets:
310
+ if isinstance(target, ast.Tuple):
311
+ for i, el in enumerate(target.elts):
312
+ if isinstance(el, ast.Name):
313
+ f.locals[el.id].append(((node.value, i), "unpacked", f, location))
314
+ self._note_attribute(f, target, node)
315
+ elif isinstance(node, (ast.For, ast.AsyncFor)):
316
+ self._note_iteration(f, node.target, node.iter, (node.lineno, None))
317
+ elif isinstance(node, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)):
318
+ for g in node.generators:
319
+ self._note_iteration(f, g.target, g.iter, (node.lineno, node.end_lineno))
320
+ elif isinstance(node, (ast.With, ast.AsyncWith)):
321
+ for item in node.items:
322
+ if isinstance(item.optional_vars, ast.Name):
323
+ f.locals[item.optional_vars.id].append(
324
+ (item.context_expr, "value", f, (node.lineno, None)))
325
+ elif isinstance(node, ast.NamedExpr):
326
+ f.locals[node.target.id].append((node.value, "value", f, (node.lineno, None)))
327
+
328
+ def _note_attribute(self, f: Function, target: ast.expr, node: ast.stmt) -> None:
329
+ """`self.x = ...` or `self.x: T = ...` in a method: an attribute of
330
+ the class."""
331
+ if not (isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name)):
332
+ return
333
+ method = f
334
+ while method.parent is not None:
335
+ method = method.parent
336
+ if method.cls is None:
337
+ return
338
+ first = (method.node.args.posonlyargs + method.node.args.args)[:1]
339
+ if not first or first[0].arg != target.value.id:
340
+ return
341
+ if isinstance(node, ast.AnnAssign):
342
+ method.cls.attributes[target.attr].append((node.annotation, "annotation", f))
343
+ else:
344
+ method.cls.attributes[target.attr].append((node.value, "value", f))
345
+
346
+ @staticmethod
347
+ def _note_iteration(f: Function, target: ast.expr, iterable: ast.expr, location: tuple) -> None:
348
+ if isinstance(target, ast.Name):
349
+ f.locals[target.id].append((iterable, "element", f, location))
350
+ elif isinstance(target, ast.Tuple):
351
+ for i, el in enumerate(target.elts):
352
+ if isinstance(el, ast.Name):
353
+ f.locals[el.id].append(((iterable, i), "unpacked_element", f, location))
354
+
355
+ @staticmethod
356
+ def _own_nodes(node: ast.AST):
357
+ """The nodes of a function, without those of its nested functions and
358
+ classes (lambdas belong to it)."""
359
+ stack = list(ast.iter_child_nodes(node))
360
+ while stack:
361
+ n = stack.pop()
362
+ yield n
363
+ if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
364
+ stack.extend(ast.iter_child_nodes(n))
365
+
366
+ # ---------- the types
367
+
368
+ def _module(self, name: str) -> Module | None:
369
+ if name in self.modules:
370
+ return self.modules[name]
371
+ # shortcut: the scripts of tools/ import each other without a package, as in the first host; a graphe.toml
372
+ # key (import roots) if another host arranges its modules otherwise.
373
+ return self.modules.get(f"tools.{name}")
374
+
375
+ def _from_module(self, m: Module, name: str):
376
+ if name in m.functions:
377
+ return ("function", m.functions[name])
378
+ if name in m.classes:
379
+ return ("class", m.classes[name])
380
+ if name in m.imports:
381
+ return self._import(m, m.imports[name], name)
382
+ if name in m.variables: # guarded like a local: `l = l[1:]` at the top of a module
383
+ return self._guard(("variable", m.id, name), lambda: self._from_sources(m.variables[name], None, m))
384
+ if name in BUILTINS:
385
+ return ("external", name)
386
+ return None
387
+
388
+ def _import(self, m: Module, imp: tuple, name: str):
389
+ if imp[0] == "module":
390
+ target = self._module(imp[1])
391
+ return ("module", target) if target else ("external", imp[1])
392
+ target = self._module(imp[1])
393
+ if target is None:
394
+ sub = self._module(f"{imp[1]}.{imp[2]}")
395
+ return ("module", sub) if sub else ("external", f"{imp[1]}.{imp[2]}")
396
+ sub = self._module(f"{imp[1]}.{imp[2]}")
397
+ if sub is not None and imp[2] not in target.functions and imp[2] not in target.classes:
398
+ return ("module", sub)
399
+ return self._guard(("import", imp), lambda: self._from_module(target, imp[2]))
400
+
401
+ def _guard(self, key, compute):
402
+ if key in self._memo:
403
+ return self._memo[key]
404
+ if key in self._in_progress:
405
+ return None
406
+ self._in_progress.add(key)
407
+ try:
408
+ result = compute()
409
+ finally:
410
+ self._in_progress.discard(key)
411
+ self._memo[key] = result
412
+ return result
413
+
414
+ @staticmethod
415
+ def _at_line(sources: list, line: int | None) -> list:
416
+ """The sources of a variable seen from the line where it serves: that
417
+ of the comprehension that encloses it, then the assignments that
418
+ precede, the closest first, then the following ones (a loop)."""
419
+ if line is None:
420
+ return [s for s in sources if len(s) <= 3 or s[3][1] is None]
421
+ inside = [s for s in sources if len(s) > 3 and s[3][1] is not None and s[3][0] <= line <= s[3][1]]
422
+ before = sorted((s for s in sources if len(s) > 3 and s[3][1] is None and s[3][0] <= line),
423
+ key=lambda s: -s[3][0])
424
+ after = [s for s in sources if len(s) > 3 and s[3][1] is None and s[3][0] > line]
425
+ return inside[::-1] + before + after + [s for s in sources if len(s) <= 3]
426
+
427
+ def _from_sources(self, sources: list, f: Function | None, m: Module):
428
+ for source, kind, where, *_ in sources:
429
+ scope = where if where is not None else f
430
+ t = self._source(source, kind, scope, m)
431
+ if t is not None:
432
+ return t
433
+ return None
434
+
435
+ def _source(self, source, kind: str, f: Function | None, m: Module):
436
+ if kind == "annotation":
437
+ return self._annotation(source, f, m)
438
+ if kind in ("instance", "class"):
439
+ return (kind, source)
440
+ if kind == "def":
441
+ return ("function", source)
442
+ if kind == "import":
443
+ return self._import(m, source, "")
444
+ if kind == "value":
445
+ return self.type_of(source, f, m)
446
+ if kind == "element":
447
+ return self._element(self.type_of(source, f, m))
448
+ if kind == "unpacked_element":
449
+ iterable, i = source
450
+ t = self.type_of(iterable, f, m)
451
+ if t and t[0] == "external":
452
+ return t
453
+ if t and t[0] == "pairs":
454
+ return t[1][i] if i < len(t[1]) else None
455
+ if t and t[0] == "container" and t[2]:
456
+ return t[2][i] if i < len(t[2]) else None
457
+ return None
458
+ if kind == "unpacked":
459
+ value, i = source
460
+ t = self.type_of(value, f, m)
461
+ if t and t[0] == "external":
462
+ return t
463
+ if t and t[0] == "container" and t[2]:
464
+ return t[2][i] if i < len(t[2]) else None
465
+ return None
466
+ return None
467
+
468
+ @staticmethod
469
+ def _element(t):
470
+ if t and t[0] == "container":
471
+ return t[1]
472
+ if t and t[0] == "pairs":
473
+ return ("container", None, list(t[1]))
474
+ if t and t[0] == "external":
475
+ return ("external", "element") # what comes out of an object outside the repository is not ours
476
+ return None
477
+
478
+ def _annotation(self, a, f: Function | None, m: Module):
479
+ """The type an annotation designates, as an instance."""
480
+ if isinstance(a, ast.Constant) and isinstance(a.value, str):
481
+ try:
482
+ a = ast.parse(a.value, mode="eval").body
483
+ except SyntaxError:
484
+ return None
485
+ if isinstance(a, ast.BinOp) and isinstance(a.op, ast.BitOr):
486
+ return self._annotation(a.left, f, m) or self._annotation(a.right, f, m)
487
+ if isinstance(a, ast.Subscript):
488
+ head = self._final_name(a.value)
489
+ args = a.slice.elts if isinstance(a.slice, ast.Tuple) else [a.slice]
490
+ if head in ("Optional", "ClassVar", "Final", "Annotated"):
491
+ return self._annotation(args[0], f, m)
492
+ if head == "Union":
493
+ return next((t for t in (self._annotation(x, f, m) for x in args) if t), None)
494
+ if head in ("list", "List", "set", "Set", "frozenset", "Sequence", "Iterable", "Iterator", "deque",
495
+ "Generator", "Collection", "MutableSequence"):
496
+ return ("container", self._annotation(args[0], f, m), None)
497
+ if head in ("dict", "Dict", "Mapping", "MutableMapping", "defaultdict", "OrderedDict") and len(args) == 2:
498
+ return ("dict", self._annotation(args[0], f, m), self._annotation(args[1], f, m))
499
+ if head in ("tuple", "Tuple"):
500
+ return ("container", None, [self._annotation(x, f, m) for x in args])
501
+ if head in ("type", "Type"):
502
+ t = self._annotation(args[0], f, m)
503
+ return ("class", t[1]) if t and t[0] == "instance" else None
504
+ return self._annotation(a.value, f, m)
505
+ if isinstance(a, (ast.Name, ast.Attribute)):
506
+ t = self.type_of(a, f, m)
507
+ if t and t[0] == "class":
508
+ return ("instance", t[1])
509
+ return ("external", self._final_name(a)) if t is None or t[0] == "external" else None
510
+ return None
511
+
512
+ @staticmethod
513
+ def _final_name(e: ast.expr) -> str:
514
+ if isinstance(e, ast.Name):
515
+ return e.id
516
+ if isinstance(e, ast.Attribute):
517
+ return e.attr
518
+ return ""
519
+
520
+ def _local_name(self, name: str, f: Function | None, m: Module, line: int | None = None):
521
+ scope = f
522
+ while scope is not None:
523
+ if name in scope.locals:
524
+ here = line if scope is f else None
525
+ sources = self._at_line(scope.locals[name], here)
526
+ if sources:
527
+ return self._guard(("local", scope.id, name, here),
528
+ lambda p=scope, s=sources: self._from_sources(s, p, m))
529
+ scope = scope.parent
530
+ return self._from_module(m, name)
531
+
532
+ def type_of(self, e: ast.expr, f: Function | None, m: Module):
533
+ """What an expression is: ("module" | "class" | "instance" |
534
+ "function", object), a container, ("external", name), or None."""
535
+ if isinstance(e, ast.Name):
536
+ return self._local_name(e.id, f, m, e.lineno)
537
+ if isinstance(e, ast.Attribute):
538
+ if isinstance(e.value, ast.Call) and isinstance(e.value.func, ast.Name) and e.value.func.id == "super":
539
+ cls = self._enclosing_class(f)
540
+ return self._from_class(cls, e.attr, skip=True) if cls else None
541
+ return self.attribute(self.type_of(e.value, f, m), e.attr)
542
+ if isinstance(e, ast.Call):
543
+ return self._result(e, f, m)
544
+ if isinstance(e, ast.Subscript):
545
+ t = self.type_of(e.value, f, m)
546
+ if t and t[0] == "external":
547
+ return ("external", "element")
548
+ if t and t[0] == "dict":
549
+ return t[2]
550
+ if t and t[0] == "container":
551
+ if t[2] and isinstance(e.slice, ast.Constant) and isinstance(e.slice.value, int):
552
+ return t[2][e.slice.value] if e.slice.value < len(t[2]) else None
553
+ return t[1]
554
+ return None
555
+ if isinstance(e, (ast.List, ast.Set)):
556
+ types = [self.type_of(x, f, m) for x in e.elts if not isinstance(x, ast.Starred)]
557
+ return ("container", next((t for t in types if t), None), None)
558
+ if isinstance(e, ast.Tuple):
559
+ return ("container", None, [self.type_of(x, f, m) for x in e.elts])
560
+ if isinstance(e, ast.Dict):
561
+ values = [self.type_of(v, f, m) for v in e.values if v is not None]
562
+ return ("dict", None, next((t for t in values if t), None))
563
+ if isinstance(e, (ast.ListComp, ast.SetComp, ast.GeneratorExp)):
564
+ return ("container", self.type_of(e.elt, f, m), None)
565
+ if isinstance(e, ast.DictComp):
566
+ return ("dict", None, self.type_of(e.value, f, m))
567
+ if isinstance(e, ast.IfExp):
568
+ return self.type_of(e.body, f, m) or self.type_of(e.orelse, f, m)
569
+ if isinstance(e, ast.BoolOp):
570
+ return next((t for t in (self.type_of(v, f, m) for v in e.values) if t and t[0] != "external"), None)
571
+ if isinstance(e, ast.NamedExpr):
572
+ return self.type_of(e.value, f, m)
573
+ if isinstance(e, ast.Await):
574
+ return self.type_of(e.value, f, m)
575
+ if isinstance(e, (ast.Constant, ast.JoinedStr, ast.BinOp, ast.Compare, ast.UnaryOp)):
576
+ return ("external", type(e).__name__)
577
+ return None
578
+
579
+ @staticmethod
580
+ def _enclosing_class(f: Function | None) -> Class | None:
581
+ while f is not None and f.parent is not None:
582
+ f = f.parent
583
+ return f.cls if f else None
584
+
585
+ def _mro(self, c: Class, seen: set | None = None) -> list:
586
+ """The class and its bases (ours); a base outside the repository is
587
+ given as ("external", name)."""
588
+ seen = seen if seen is not None else set()
589
+ if c.id in seen:
590
+ return []
591
+ seen.add(c.id)
592
+ order = [c]
593
+ for base in c.node.bases:
594
+ t = self.type_of(base, None, c.module)
595
+ if t and t[0] == "class":
596
+ order += self._mro(t[1], seen)
597
+ else:
598
+ order.append(("external", self._final_name(base)))
599
+ return order
600
+
601
+ def _from_class(self, c: Class, name: str, instance: bool = True, skip: bool = False):
602
+ external = False
603
+ for bearer in self._mro(c)[1 if skip else 0:]:
604
+ if isinstance(bearer, tuple):
605
+ external = True
606
+ continue
607
+ if name in bearer.methods:
608
+ method = bearer.methods[name]
609
+ if "property" in method.decorators or "cached_property" in method.decorators:
610
+ return self._return(method) if instance else ("function", method)
611
+ return ("function", method)
612
+ if name in bearer.attributes:
613
+ sources = bearer.attributes[name]
614
+ if sources and sources[0][1] == "class":
615
+ nested = next((k for k in self.classes if k.node is sources[0][0]), None)
616
+ return ("class", nested) if nested else None
617
+ t = self._guard(("attribute", bearer.id, name),
618
+ lambda p=bearer: self._from_sources(p.attributes[name], None, p.module))
619
+ return t if t is not None else ("attribute", bearer, name)
620
+ if external or name.startswith("__"):
621
+ return ("external", name)
622
+ return ("absent", c, name)
623
+
624
+ def attribute(self, t, name: str):
625
+ if t is None:
626
+ return None
627
+ kind = t[0]
628
+ if kind == "module":
629
+ return self._from_module(t[1], name) or ("absent", t[1], name)
630
+ if kind in ("instance", "class"):
631
+ return self._from_class(t[1], name, instance=kind == "instance")
632
+ if kind == "dict":
633
+ if name in TO_ELEMENT:
634
+ return ("returns", t[2])
635
+ if name == "values":
636
+ return ("returns", ("container", t[2], None))
637
+ if name == "items":
638
+ return ("returns", ("pairs", (t[1], t[2])))
639
+ return ("external", name)
640
+ if kind == "container":
641
+ if name in TO_ELEMENT:
642
+ return ("returns", t[1])
643
+ if name in TO_CONTAINER:
644
+ return ("returns", t)
645
+ return ("external", name)
646
+ if kind in ("external", "pairs"):
647
+ return ("external", name)
648
+ return None
649
+
650
+ def _return(self, f: Function):
651
+ def compute():
652
+ if f.node.returns is not None:
653
+ return self._annotation(f.node.returns, f, f.module)
654
+ for n in self._own_nodes(f.node):
655
+ if isinstance(n, ast.Return) and n.value is not None:
656
+ t = self.type_of(n.value, f, f.module)
657
+ if t is not None:
658
+ return t
659
+ return None
660
+ return self._guard(("return", f.id), compute)
661
+
662
+ def _result(self, call: ast.Call, f: Function | None, m: Module):
663
+ if isinstance(call.func, ast.Name) and call.func.id == "super":
664
+ return None
665
+ target = self.type_of(call.func, f, m)
666
+ if target is None:
667
+ return None
668
+ if target[0] == "class":
669
+ return ("instance", target[1])
670
+ if target[0] == "function":
671
+ if target[1].name == "__new__" or target[1].name == "__init__":
672
+ return None
673
+ return self._return(target[1])
674
+ if target[0] == "returns":
675
+ return target[1]
676
+ if target[0] == "external":
677
+ if target[1] in ("replace", "deepcopy", "copy") and call.args:
678
+ return self.type_of(call.args[0], f, m)
679
+ if target[1] in ("sorted", "list", "reversed", "tuple", "set", "frozenset") and call.args:
680
+ t = self.type_of(call.args[0], f, m)
681
+ return ("container", self._element(t), None) if t and t[0] in ("container", "dict") else t
682
+ if target[1] in ("enumerate",) and call.args:
683
+ return ("container", ("container", None, [("external", "int"), self._element(
684
+ self.type_of(call.args[0], f, m))]), None)
685
+ if target[1] in ("zip",) and call.args:
686
+ return ("container", ("container", None, [self._element(self.type_of(a, f, m))
687
+ for a in call.args]), None)
688
+ if target[1] in ("min", "max", "next") and call.args:
689
+ return self._element(self.type_of(call.args[0], f, m))
690
+ if target[1] in ("cast",) and call.args:
691
+ return self._annotation(call.args[0], f, m)
692
+ return ("external", target[1])
693
+ return None
694
+
695
+ # ---------- the graph
696
+
697
+ def _node(self, id_: str, label: str, kind: str, rel: str, line: int, name: str) -> None:
698
+ self.nodes.append({"id": id_, "label": label, "kind": kind, "source_file": rel,
699
+ "source_location": f"L{line}", "name": name})
700
+
701
+ def _link(self, source: str, target: str, relation: str, rel: str, line: int, sure: bool = True,
702
+ context: str = "") -> None:
703
+ self.links.append({"source": source, "target": target, "relation": relation,
704
+ "confidence": "EXTRACTED" if sure else "INFERRED", "context": context,
705
+ "source_file": rel, "source_location": f"L{line}"})
706
+
707
+ def _emit(self) -> None:
708
+ for m in self.modules.values():
709
+ self._node(m.id, Path(m.rel).name, "file", m.rel, 1, m.name)
710
+ for local, imp in m.imports.items():
711
+ target = self._module(imp[1])
712
+ if imp[0] == "symbol" and self._module(f"{imp[1]}.{imp[2]}") is not None:
713
+ target = self._module(f"{imp[1]}.{imp[2]}")
714
+ if target is not None and target is not m:
715
+ self._link(m.id, target.id, "imports", m.rel, 1, context=local)
716
+ if imp[0] == "symbol" and target is not None:
717
+ t = self._import(m, imp, local)
718
+ if t and t[0] in ("function", "class"):
719
+ self._link(m.id, t[1].id, "imports", m.rel, 1, context=local)
720
+ for c in self.classes:
721
+ self._node(c.id, c.name, "class", c.module.rel, c.node.lineno, c.qualname)
722
+ self._link(c.module.id if "." not in c.qualname else self._parent_id(c), c.id, "contains",
723
+ c.module.rel, c.node.lineno)
724
+ for base in c.node.bases:
725
+ t = self.type_of(base, None, c.module)
726
+ if t and t[0] == "class":
727
+ self._link(c.id, t[1].id, "inherits", c.module.rel, c.node.lineno)
728
+ for name, line in c.fields.items():
729
+ self._node(self.field_id(c, name), f"{c.name}.{name}", "field", c.module.rel, line,
730
+ f"{c.qualname}.{name}")
731
+ self._link(c.id, self.field_id(c, name), "contains", c.module.rel, line)
732
+ for f in self.functions:
733
+ label = f"{'.' if f.cls else ''}{f.name}()"
734
+ self._node(f.id, label, "method" if f.cls else "function", f.module.rel, f.node.lineno, f.qualname)
735
+ if f.cls is not None:
736
+ self._link(f.cls.id, f.id, "method", f.module.rel, f.node.lineno)
737
+ else:
738
+ self._link(f.parent.id if f.parent else f.module.id, f.id, "contains", f.module.rel, f.node.lineno)
739
+ for m in self.modules.values():
740
+ body = [n for n in m.tree.body if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef,
741
+ ast.ClassDef))]
742
+ self._walk(body, m.id, None, m)
743
+ for c in self.classes:
744
+ body = [n for n in c.node.body if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef,
745
+ ast.ClassDef))]
746
+ self._walk(body + c.node.bases + c.node.decorator_list, c.id, None, c.module)
747
+ for f in self.functions:
748
+ a = f.node.args
749
+ headers = [*f.node.decorator_list, *a.defaults, *[d for d in a.kw_defaults if d is not None]]
750
+ self._walk(headers, f.parent.id if f.parent else (f.cls.id if f.cls else f.module.id),
751
+ f.parent, f.module)
752
+ self._walk(f.node.body, f.id, f, f.module)
753
+ for p in [*a.posonlyargs, *a.args, *a.kwonlyargs, a.vararg, a.kwarg]:
754
+ if p is not None:
755
+ self._types(p.annotation, f.id, f, f.module)
756
+ self._types(f.node.returns, f.id, f, f.module)
757
+
758
+ def _parent_id(self, c: Class) -> str:
759
+ """The class, else the function, that holds a nested class (the first of the same qualname)."""
760
+ return self._holders.get((id(c.module), c.qualname.rsplit(".", 1)[0]), c.module.id)
761
+
762
+ def _walk(self, nodes: list, owner: str, f: Function | None, m: Module) -> None:
763
+ stack = [(n, owner) for n in reversed(nodes)]
764
+ called = set()
765
+ while stack:
766
+ n, who = stack.pop()
767
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
768
+ continue
769
+ if isinstance(n, ast.AnnAssign):
770
+ self._types(n.annotation, who, f, m)
771
+ stack.extend((x, who) for x in (n.value, n.target) if x is not None)
772
+ continue
773
+ if isinstance(n, ast.Call):
774
+ called.add(id(n.func))
775
+ self._call(n, who, f, m)
776
+ elif isinstance(n, (ast.Name, ast.Attribute)) and isinstance(n.ctx, ast.Load) \
777
+ and id(n) not in called:
778
+ if isinstance(n, ast.Attribute):
779
+ self._property(n, who, f, m)
780
+ self._field(n, who, f, m, "reads")
781
+ self._reference(n, who, f, m)
782
+ elif isinstance(n, ast.Attribute) and isinstance(n.ctx, ast.Store):
783
+ self._field(n, who, f, m, "writes")
784
+ elif isinstance(n, (ast.Import, ast.ImportFrom)) and f is not None:
785
+ for local, imp in self._import_entries(m, n).items():
786
+ target = self._import(m, imp, local)
787
+ if target and target[0] in ("function", "class", "module") and target[1] is not m:
788
+ self._link(who, target[1].id, "imports", m.rel, n.lineno, context=local)
789
+ stack.extend((x, who) for x in reversed(list(ast.iter_child_nodes(n))))
790
+
791
+ def _reference(self, n: ast.expr, who: str, f: Function | None, m: Module, context: str = "") -> None:
792
+ """One of our functions passed as a value (a callback, a sort key, a
793
+ pool task), or one of our classes named without being called
794
+ (isinstance, an annotation: context « type »)."""
795
+ t = self.type_of(n, f, m)
796
+ if t and t[0] == "function" and t[1].id != who and "property" not in t[1].decorators:
797
+ self._link(who, t[1].id, "references", m.rel, n.lineno, context=context)
798
+ elif t and t[0] == "class" and t[1].id != who:
799
+ self._link(who, t[1].id, "references", m.rel, n.lineno, context=context)
800
+
801
+ def _property(self, n: ast.Attribute, who: str, f: Function | None, m: Module) -> None:
802
+ """Reading a property is calling its function."""
803
+ receiver = self.type_of(n.value, f, m)
804
+ if not receiver or receiver[0] != "instance":
805
+ return
806
+ for bearer in self._mro(receiver[1]):
807
+ if isinstance(bearer, tuple):
808
+ continue
809
+ method = bearer.methods.get(n.attr)
810
+ if method is not None:
811
+ if {"property", "cached_property"} & method.decorators and method.id != who:
812
+ self._link(who, method.id, "calls", m.rel, n.lineno, context="property")
813
+ return
814
+
815
+ def field_id(self, c: Class, name: str) -> str:
816
+ id_ = f"{c.id}_{_id(name)}"
817
+ return id_ + "_field" if name in c.methods or name in self.class_names else id_
818
+
819
+ def _field(self, n: ast.Attribute, who: str, f: Function | None, m: Module, relation: str) -> None:
820
+ """`etat.demande`: reading or writing a field of one of our classes,
821
+ when the receiver's type is known - the first bearer in the order of
822
+ the bases."""
823
+ receiver = self.type_of(n.value, f, m)
824
+ if not receiver or receiver[0] != "instance":
825
+ return
826
+ for bearer in self._mro(receiver[1]):
827
+ if isinstance(bearer, tuple):
828
+ return
829
+ if n.attr in bearer.fields:
830
+ self._link(who, self.field_id(bearer, n.attr), relation, m.rel, n.lineno)
831
+ return
832
+ if n.attr in bearer.methods:
833
+ return
834
+
835
+ def _types(self, annotation: ast.expr | None, who: str, f: Function | None, m: Module) -> None:
836
+ """The classes an annotation names, strings included."""
837
+ if annotation is None:
838
+ return
839
+ for n in ast.walk(annotation):
840
+ if isinstance(n, ast.Constant) and isinstance(n.value, str):
841
+ try:
842
+ self._types(ast.parse(n.value, mode="eval").body, who, f, m)
843
+ except SyntaxError:
844
+ pass
845
+ elif isinstance(n, ast.Name) or (isinstance(n, ast.Attribute) and isinstance(n.value, ast.Name)):
846
+ if isinstance(n, ast.Name) and any(isinstance(a, ast.Attribute) and a.value is n
847
+ for a in ast.walk(annotation)):
848
+ continue
849
+ self._reference(n, who, f, m, context="type")
850
+
851
+ def _call(self, call: ast.Call, who: str, f: Function | None, m: Module) -> None:
852
+ func = call.func
853
+ name = self._final_name(func)
854
+ site = {"rel": m.rel, "line": call.lineno, "name": name, "expr": ast.unparse(func)[:80]}
855
+ t = self.type_of(func, f, m)
856
+ if t and t[0] == "function":
857
+ self._link(who, t[1].id, "calls", m.rel, call.lineno)
858
+ verdict = "ours"
859
+ elif t and t[0] == "class":
860
+ self._link(who, t[1].id, "uses", m.rel, call.lineno, context="instantiates")
861
+ verdict = "ours"
862
+ elif t and t[0] in ("external", "returns"):
863
+ verdict = "external"
864
+ elif t and t[0] == "attribute":
865
+ verdict = "attribute" # an attribute called: a callback stored in the object
866
+ elif t and t[0] == "absent":
867
+ verdict = "absent"
868
+ else:
869
+ receiver = None
870
+ if isinstance(func, ast.Attribute):
871
+ receiver = self.type_of(func.value, f, m)
872
+ if receiver and receiver[0] in ("external", "container", "dict", "pairs"):
873
+ verdict = "external"
874
+ elif not name:
875
+ verdict = "dynamic"
876
+ elif isinstance(func, ast.Name):
877
+ verdict = "local" if self._is_local(name, f) else "unknown"
878
+ else:
879
+ ours = self.by_name.get(name, [])
880
+ if len(ours) == 1:
881
+ self._link(who, ours[0].id, "calls", m.rel, call.lineno, sure=False)
882
+ verdict = "ours?"
883
+ elif ours:
884
+ verdict = "ambiguous"
885
+ site["candidates"] = len(ours)
886
+ else:
887
+ verdict = "external?"
888
+ site["verdict"] = verdict
889
+ self.sites.append(site)
890
+
891
+ @staticmethod
892
+ def _is_local(name: str, f: Function | None) -> bool:
893
+ while f is not None:
894
+ a = f.node.args
895
+ if name in f.locals or name in {p.arg for p in [*a.posonlyargs, *a.args, *a.kwonlyargs]} \
896
+ or (a.vararg and a.vararg.arg == name) or (a.kwarg and a.kwarg.arg == name):
897
+ return True
898
+ f = f.parent
899
+ return False
900
+
901
+
902
+ def contribute(project) -> dict:
903
+ """The Python reader's contribution (docs/contribution.md): a site per call, and its alerts."""
904
+ reader = Reader(project.files(".py"), project.root, project.root / root.OUTPUT.name / "cache")
905
+ our_names = set(reader.by_name) | reader.class_names
906
+ sites = []
907
+ for s in reader.sites:
908
+ site = {"verdict": s["verdict"], "file": s["rel"], "line": s["line"], "name": s["name"], "text": s["expr"]}
909
+ if s["verdict"] in ("unknown", "external?", "absent") and s["name"] in our_names:
910
+ site["alert"] = "not linked to the name of one of our functions"
911
+ sites.append(site)
912
+ if project.checking:
913
+ total = sum(1 for m in reader.modules.values() for n in ast.walk(m.tree) if isinstance(n, ast.Call))
914
+ if total != len(reader.sites):
915
+ sites.append({"file": "", "line": 0, "name": "", "alert": "ast calls left unclassified",
916
+ "text": f"{total} calls in the ast, {len(reader.sites)} classified"})
917
+ return {"nodes": reader.nodes, "links": reader.links, "sites": sites}