codefactory-cli 0.20.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. codefactory/__init__.py +3 -0
  2. codefactory/__main__.py +5 -0
  3. codefactory/accept.py +68 -0
  4. codefactory/analyzers/__init__.py +55 -0
  5. codefactory/analyzers/generic.py +392 -0
  6. codefactory/analyzers/parallel.py +113 -0
  7. codefactory/analyzers/python.py +279 -0
  8. codefactory/analyzers/python_parse.py +402 -0
  9. codefactory/analyzers/treewalk.py +299 -0
  10. codefactory/analyzers/ts_helper.js +483 -0
  11. codefactory/analyzers/typescript.py +118 -0
  12. codefactory/apple.py +80 -0
  13. codefactory/audit.py +227 -0
  14. codefactory/baseline.py +58 -0
  15. codefactory/brief.py +330 -0
  16. codefactory/cache.py +93 -0
  17. codefactory/checks.py +608 -0
  18. codefactory/cli.py +782 -0
  19. codefactory/config.py +157 -0
  20. codefactory/coverage.py +104 -0
  21. codefactory/deps.py +182 -0
  22. codefactory/diff.py +197 -0
  23. codefactory/efficiency.py +250 -0
  24. codefactory/flags.py +263 -0
  25. codefactory/graph.py +95 -0
  26. codefactory/hotspots.py +344 -0
  27. codefactory/infra.py +242 -0
  28. codefactory/intent.py +106 -0
  29. codefactory/layers.py +143 -0
  30. codefactory/org.py +131 -0
  31. codefactory/owners.py +72 -0
  32. codefactory/patch.py +81 -0
  33. codefactory/paths.py +93 -0
  34. codefactory/plan.py +476 -0
  35. codefactory/privacy.py +221 -0
  36. codefactory/profile.py +667 -0
  37. codefactory/rerank.py +161 -0
  38. codefactory/review.py +1504 -0
  39. codefactory/rules.py +50 -0
  40. codefactory/sarif.py +661 -0
  41. codefactory/sbom.py +78 -0
  42. codefactory/security.py +537 -0
  43. codefactory/similar.py +199 -0
  44. codefactory/skill.py +144 -0
  45. codefactory/skill_template/SKILL.md +68 -0
  46. codefactory/skill_template/__init__.py +0 -0
  47. codefactory/sqlgraph.py +109 -0
  48. codefactory/suppress.py +92 -0
  49. codefactory/taint.py +439 -0
  50. codefactory/trace.py +72 -0
  51. codefactory/viewer/__init__.py +19 -0
  52. codefactory/viewer/dashboard.html +43 -0
  53. codefactory/viewer/factory.css +61 -0
  54. codefactory/viewer/factory.js +665 -0
  55. codefactory/viewer/template.html +47 -0
  56. codefactory_cli-0.20.1.dist-info/METADATA +250 -0
  57. codefactory_cli-0.20.1.dist-info/RECORD +61 -0
  58. codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
  59. codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
  60. codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
  61. codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,279 @@
1
+ """Python analyzer: files, functions, imports and calls from the standard library's ast module (nothing is run).
2
+
3
+ Calls are resolved statically, so the graph is an approximation: plain names, imported names, module.attr,
4
+ self.method / cls.method and ClassName() (to __init__) resolve; calls through variables, getattr or dynamic
5
+ dispatch don't. A function passed by name (a callback, a decorator argument) is kept as a "ref" edge so it
6
+ doesn't look dead.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ from collections import Counter
13
+ from pathlib import Path
14
+
15
+ from ..graph import Edge, File, Function, Graph, Site
16
+ from ..paths import walk
17
+ from . import parallel
18
+ from .python_parse import parse_module
19
+
20
+
21
+ def iter_files(root: Path, ignore: list[str]) -> list[Path]:
22
+ skip = set(ignore)
23
+ out = []
24
+ # hidden folders (.claude, .github, .venv…) hold tooling and environments, not the product's code; pruned before
25
+ # descending, so a virtualenv or node_modules isn't walked at all
26
+ for rel in walk(root, suffixes=(".py",), skip=skip, hidden=False):
27
+ if not any(part.endswith(".egg-info") for part in rel.split("/")[:-1]):
28
+ out.append(root / rel)
29
+ return sorted(out)
30
+
31
+
32
+ def module_name(rel: Path) -> str:
33
+ parts = list(rel.with_suffix("").parts)
34
+ if parts and parts[0] == "src" and len(parts) > 1:
35
+ parts = parts[1:]
36
+ if parts[-1] == "__init__":
37
+ parts = parts[:-1]
38
+ return ".".join(parts)
39
+
40
+
41
+ class _Module:
42
+ def __init__(self, rel: str, name: str, data: dict, is_pkg: bool):
43
+ self.rel, self.name, self.data, self.is_pkg = rel, name, data, is_pkg
44
+ self.funcs: dict[str, Function] = {} # qualname -> function
45
+ self.classes: set[str] = set(data["classes"])
46
+ self.aliases: dict[str, str] = {} # local name -> module name
47
+ self.symbols: dict[str, tuple[str, str]] = {} # local name -> (module name, symbol)
48
+ self.exports: set[str] = set(data["exports"])
49
+ self.load_imports: set[str] = set() # modules imported when this one loads (not inside functions or TYPE_CHECKING)
50
+ self.consts: set[str] = set(data["consts"]) # module-level names bound to a literal list / tuple / set / dict
51
+ self.tables: dict[str, list] = data["tables"] # their references: COMMANDS = {"run": (cmd_run, …)}
52
+
53
+
54
+ def _resolve_relative(mod: _Module, level: int, target: str | None) -> str:
55
+ base = mod.name.split(".") if mod.is_pkg else mod.name.split(".")[:-1]
56
+ if level > 1:
57
+ base = base[: len(base) - (level - 1)]
58
+ return ".".join([*base, target] if target else base)
59
+
60
+
61
+ def _scoped(mod: _Module, imports: list, known: set[str]) -> _Module:
62
+ """The module as one function sees it: its own imports on top of the module's."""
63
+ if not imports:
64
+ return mod
65
+ view = copy.copy(mod)
66
+ view.aliases, view.symbols, view.load_imports = dict(mod.aliases), dict(mod.symbols), set()
67
+ _apply_imports(view, imports, known)
68
+ return view
69
+
70
+
71
+ def _collect(mod: _Module, known: set[str]) -> None:
72
+ _apply_imports(mod, mod.data["imports"], known)
73
+
74
+
75
+ def _apply_imports(mod: _Module, imports: list, known: set[str]) -> None:
76
+ for imp in imports:
77
+ if imp[0] == "import":
78
+ _, name, asname, at_load = imp
79
+ if asname:
80
+ mod.aliases[asname] = name
81
+ else:
82
+ mod.aliases[name.split(".")[0]] = name.split(".")[0]
83
+ mod.aliases[name] = name
84
+ if at_load:
85
+ mod.load_imports.add(name)
86
+ else:
87
+ _, module, level, name, asname, at_load = imp
88
+ src = _resolve_relative(mod, level, module) if level else (module or "")
89
+ local = asname or name
90
+ full = f"{src}.{name}" if src else name
91
+ if full in known:
92
+ mod.aliases[local] = full
93
+ else:
94
+ mod.symbols[local] = (src, name)
95
+ if at_load:
96
+ mod.load_imports.add(full if full in known else src)
97
+
98
+
99
+ def _functions(mod: _Module) -> list[tuple[Function, dict]]:
100
+ """Top-level functions and class methods. Nested functions belong to the function that holds them. The same name
101
+ defined twice (a property's getter and setter) gets its line in the id; name lookups keep finding the first."""
102
+ out = []
103
+ for d in mod.data["defs"]:
104
+ q = d["qualname"]
105
+ fid = f"{mod.rel}::{q}" if q not in mod.funcs else f"{mod.rel}::{q}@{d['line']}"
106
+ f = Function(
107
+ id=fid, file=mod.rel, name=d["name"], qualname=q, line=d["line"], end=d["end"], loc=d["end"] - d["line"] + 1,
108
+ kind=d["kind"], decorated=d["decorated"], exported=d["exported"], shape=d["shape"], tokens=d["tokens"],
109
+ doc=d.get("doc", 0), branches=d.get("branches", 0),
110
+ ) # fmt: skip
111
+ mod.funcs.setdefault(q, f)
112
+ out.append((f, d))
113
+ return out
114
+
115
+
116
+ class _Resolver:
117
+ def __init__(self, modules: dict[str, _Module]):
118
+ self.modules = modules
119
+ # Method names defined exactly once in the codebase: obj.name(...) on an unknown obj probably means it.
120
+ # Only used to keep such methods from looking unused (a "ref"), never drawn as a definite call.
121
+ seen: Counter = Counter()
122
+ owner: dict[str, str] = {}
123
+ for m in modules.values():
124
+ for f in m.funcs.values():
125
+ if f.kind == "method" and not f.name.startswith("__"):
126
+ seen[f.name] += 1
127
+ owner[f.name] = f.id
128
+ self.unique_methods = {n: owner[n] for n, c in seen.items() if c == 1}
129
+
130
+ def in_module(self, modname: str, symbol: str, depth: int = 0) -> str | None:
131
+ m = self.modules.get(modname)
132
+ if not m or depth > 4:
133
+ return None
134
+ if symbol in m.funcs:
135
+ return m.funcs[symbol].id
136
+ if symbol in m.classes:
137
+ init = m.funcs.get(f"{symbol}.__init__")
138
+ return init.id if init else None
139
+ if symbol in m.symbols: # re-exported (from .x import f in a package __init__)
140
+ src, name = m.symbols[symbol]
141
+ return self.in_module(src, name, depth + 1)
142
+ return None
143
+
144
+ def name(self, mod: _Module, name: str) -> str | None:
145
+ if name in mod.funcs:
146
+ return mod.funcs[name].id
147
+ if name in mod.classes:
148
+ init = mod.funcs.get(f"{name}.__init__")
149
+ return init.id if init else None
150
+ if name in mod.symbols:
151
+ return self.in_module(*mod.symbols[name])
152
+ return None
153
+
154
+ def attr(self, mod: _Module, base: str | None, attr: str, dotted: str | None, cls: str | None) -> str | None:
155
+ if base is not None:
156
+ if base in ("self", "cls") and cls:
157
+ f = mod.funcs.get(f"{cls}.{attr}")
158
+ return f.id if f else None
159
+ if base in mod.aliases:
160
+ return self.in_module(mod.aliases[base], attr)
161
+ if base in mod.classes:
162
+ f = mod.funcs.get(f"{base}.{attr}")
163
+ return f.id if f else None
164
+ if base in mod.symbols: # an imported class: Class.method
165
+ src, cname = mod.symbols[base]
166
+ m = self.modules.get(src)
167
+ f = m.funcs.get(f"{cname}.{attr}") if m else None
168
+ return f.id if f else None
169
+ if dotted: # package.module.func
170
+ modname, _, sym = dotted.rpartition(".")
171
+ if modname.split(".")[0] in mod.aliases:
172
+ return self.in_module(modname, sym)
173
+ return None
174
+
175
+ def expr(self, mod: _Module, e: list | None, cls: str | None) -> str | None:
176
+ if not e:
177
+ return None
178
+ if e[0] == "n":
179
+ return self.name(mod, e[1])
180
+ if e[0] == "a":
181
+ return self.attr(mod, e[1], e[2], e[3], cls)
182
+ return None
183
+
184
+
185
+ def _link(
186
+ evs: list, mod: _Module, cls: str | None, src_id: str, res: _Resolver, calls: Counter, refs: Counter,
187
+ consts: set[str], sites: list | None = None, io: set | None = None,
188
+ ) -> None: # fmt: skip
189
+ """Resolves one body's events (see python_parse) into call and ref edges, loop sites and I/O."""
190
+ for ev in evs:
191
+ kind = ev[0]
192
+ if kind == "w":
193
+ if sites is not None:
194
+ sites.append(Site(src_id, "loop_await", ev[1], bounded=ev[2] is not None and all(d in consts for d in ev[2])))
195
+ elif kind == "c":
196
+ _, line, loop, deps, e, sink, attr, tx = ev
197
+ bounded = deps is not None and all(d in consts for d in deps)
198
+ target = res.expr(mod, e, cls)
199
+ if target:
200
+ if target != src_id:
201
+ calls[(src_id, target)] += 1
202
+ if loop and sites is not None:
203
+ sites.append(Site(src_id, "loop_call", line, target=target, bounded=bounded, tx=tx))
204
+ elif tx and sites is not None: # called inside a transaction block
205
+ sites.append(Site(src_id, "tx_call", line, target=target, tx=True))
206
+ elif e and e[0] == "s": # TABLE[key](…): one of the table's functions runs; link to all of them
207
+ for ref in mod.tables.get(e[1], ()):
208
+ fid = res.expr(mod, ref, cls)
209
+ if fid and fid != src_id:
210
+ refs[(src_id, fid)] += 1
211
+ else:
212
+ if sink and io is not None:
213
+ io.add(sink)
214
+ if loop and sites is not None:
215
+ sites.append(Site(src_id, "loop_io", line, detail=sink, bounded=bounded, tx=tx))
216
+ if attr in res.unique_methods:
217
+ guess = res.unique_methods[attr]
218
+ if guess != src_id:
219
+ refs[(src_id, guess)] += 1
220
+ else:
221
+ target = res.expr(mod, ev[1], cls)
222
+ if target and target != src_id:
223
+ refs[(src_id, target)] += 1
224
+
225
+
226
+ def analyze_python(root: Path, ignore: list[str], cache: bool = True) -> Graph:
227
+ g = Graph(root=str(root), language="python")
228
+ paths = [p.relative_to(root) for p in iter_files(root, ignore)]
229
+ parsed = parallel.run(root, "python", [(rel.as_posix(), (str(root / rel), rel.as_posix())) for rel in paths], parse_module,
230
+ tool="python-ir-6", cache=cache) # fmt: skip
231
+ modules: dict[str, _Module] = {}
232
+ for rel in paths:
233
+ data = parsed.get(rel.as_posix())
234
+ if data is None:
235
+ continue
236
+ m = _Module(rel.as_posix(), module_name(rel), data, rel.name == "__init__.py")
237
+ modules[m.name] = m
238
+ g.files.append(File(id=m.rel, module=m.name, loc=data["loc"]))
239
+ known = set(modules)
240
+ for m in modules.values():
241
+ _collect(m, known)
242
+ defs = {name: _functions(m) for name, m in modules.items()}
243
+ res = _Resolver(modules)
244
+ calls: Counter = Counter()
245
+ refs: Counter = Counter()
246
+ imports: Counter = Counter()
247
+ for name, m in modules.items():
248
+ # constants defined here, or imported by name from another module of the codebase
249
+ consts = m.consts | {local for local, (src, sym) in m.symbols.items() if src in modules and sym in modules[src].consts}
250
+ top = Function(
251
+ id=f"{m.rel}::<module>", file=m.rel, name="<module>", qualname="<module>", line=1, end=1, loc=0, kind="module"
252
+ )
253
+ g.functions.append(top)
254
+ top_io: set[str] = set()
255
+ for cls, evs in m.data["top"]: # class bodies' own statements, decorators and module code
256
+ _link(evs, m, cls, top.id, res, calls, refs, consts, g.sites, top_io)
257
+ for fn, d in defs[name]:
258
+ g.functions.append(fn)
259
+ fn_io: set[str] = set()
260
+ _link(d["deco"], m, d["cls"], top.id, res, calls, refs, consts)
261
+ _link(d["body"], _scoped(m, d.get("imports", []), known), d["cls"], fn.id, res, calls, refs, consts, g.sites, fn_io)
262
+ fn.io = sorted(fn_io)
263
+ top.io = sorted(top_io)
264
+ for t in m.load_imports:
265
+ dst = modules.get(t)
266
+ while dst is None and "." in t: # "pkg.mod.attr" style: the closest known module
267
+ t = t.rpartition(".")[0]
268
+ dst = modules.get(t)
269
+ if dst and dst.rel != m.rel:
270
+ imports[(m.rel, dst.rel)] += 1
271
+ # obj.name anywhere (obj unknown): a method of that name may be what runs, so it isn't reported as unused.
272
+ attr_names = {a for m in modules.values() for a in m.data["attrs"]}
273
+ for fn in g.functions:
274
+ if fn.kind == "method" and fn.name in attr_names:
275
+ fn.dynamic = True
276
+ g.edges += [Edge(s, d, "call", c) for (s, d), c in calls.items()]
277
+ g.edges += [Edge(s, d, "ref", c) for (s, d), c in refs.items() if (s, d) not in calls]
278
+ g.edges += [Edge(s, d, "import", 1) for (s, d) in imports]
279
+ return g
@@ -0,0 +1,402 @@
1
+ """The per-file half of the Python analyzer: one file's ast reduced to plain data (runs in a worker, cached per file).
2
+
3
+ What a call or name refers to can depend on other modules, so nothing is resolved here. Each reference is kept as a
4
+ small expression that python.py resolves once every module is known:
5
+ ["n", name] a plain name
6
+ ["a", base or None, attr, dotted] obj.attr (base: the name at its root, when it's a plain name)
7
+ ["s", table] TABLE[key](…): a call through a dispatch table
8
+ Events, in source order: ["c", line, in_loop, bounded, expr, io_sink, attr] for calls, ["w", line, bounded] for
9
+ awaits in a for/while loop, then ["r", expr] for names used without being called. `bounded` is None (the loop's
10
+ length depends on data) or the imported names that must be constants for it to be fixed in the code.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ast
16
+ import hashlib
17
+ import re
18
+ from pathlib import Path
19
+
20
+ DB_METHODS = {
21
+ "execute", "executemany", "executescript", "fetchone", "fetchall", "fetchmany", "commit", "rollback", "scalars",
22
+ "scalar", "query", "bulk_create", "bulk_update", "get_or_create", "update_or_create",
23
+ } # fmt: skip
24
+ IO_MODULES = {
25
+ "requests", "httpx", "urllib", "aiohttp", "subprocess", "socket", "boto3", "redis", "shutil", "smtplib", "ftplib",
26
+ "sqlite3", "psycopg", "psycopg2", "pymongo", "asyncpg",
27
+ } # fmt: skip
28
+ FILE_METHODS = {"read_text", "write_text", "read_bytes", "write_bytes", "urlopen", "iterdir", "glob", "rglob"}
29
+ COMPREHENSIONS = (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
30
+ SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
31
+ FUNCS = (ast.FunctionDef, ast.AsyncFunctionDef)
32
+ SMALL = 50
33
+ LITERALS = (ast.List, ast.Tuple, ast.Set, ast.Dict)
34
+ NONE: frozenset = frozenset()
35
+
36
+
37
+ def _preorder(node):
38
+ stack = [node]
39
+ while stack:
40
+ n = stack.pop()
41
+ yield n
42
+ stack.extend(reversed(list(ast.iter_child_nodes(n))))
43
+
44
+
45
+ def shape_of(node) -> tuple[str, str]:
46
+ """(hash, tokens) of a function's structure, in source order. Local names (arguments, variables) and the
47
+ docstring are blanked out, so a copy with renamed variables still matches; names it uses from outside (calls,
48
+ attributes) are kept, so two small functions that merely look alike don't. The tokens feed near-duplicate
49
+ detection; the hash, exact duplicates."""
50
+ body = list(node.body)
51
+ if (
52
+ body
53
+ and isinstance(body[0], ast.Expr)
54
+ and isinstance(body[0].value, ast.Constant)
55
+ and isinstance(body[0].value.value, str)
56
+ ):
57
+ body = body[1:]
58
+ nodes = [n for stmt in body for n in _preorder(stmt)]
59
+ local = {a.arg for a in ast.walk(node.args) if isinstance(a, ast.arg)}
60
+ local |= {n.id for n in nodes if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store)}
61
+ if len(nodes) < 15: # a line or two (raise NotImplementedError, return self.x): alike by nature, not copies
62
+ return "", ""
63
+ parts = []
64
+ for n in nodes:
65
+ parts.append(type(n).__name__)
66
+ if hasattr(n, "op"):
67
+ parts.append(type(n.op).__name__)
68
+ elif isinstance(n, ast.Compare):
69
+ parts += [type(o).__name__ for o in n.ops]
70
+ elif isinstance(n, ast.Attribute):
71
+ parts.append(n.attr)
72
+ elif isinstance(n, ast.Name) and n.id not in local:
73
+ parts.append(n.id)
74
+ elif isinstance(n, ast.Constant) and isinstance(n.value, str):
75
+ # a string's words count: two functions differing only in their SQL or messages aren't copies
76
+ parts += [f"S:{w}" for w in n.value.split()[:24]]
77
+ elif isinstance(n, ast.Constant) and isinstance(n.value, (int, float)) and not isinstance(n.value, bool):
78
+ parts.append(f"N:{n.value}")
79
+ text = " ".join(parts)
80
+ return hashlib.sha1(text.encode("utf-8", "surrogatepass")).hexdigest()[:16], text
81
+
82
+
83
+ def dotted(node: ast.AST) -> str | None:
84
+ parts = []
85
+ while isinstance(node, ast.Attribute):
86
+ parts.append(node.attr)
87
+ node = node.value
88
+ if isinstance(node, ast.Name):
89
+ parts.append(node.id)
90
+ return ".".join(reversed(parts))
91
+ return None
92
+
93
+
94
+ def io_call(func: ast.AST, call: ast.Call | None = None) -> str | None:
95
+ """The I/O call's name ("cursor.execute"), or None. A SQL string starting with SELECT marks a read."""
96
+ full = dotted(func) or ""
97
+ last = func.attr if isinstance(func, ast.Attribute) else func.id if isinstance(func, ast.Name) else ""
98
+ head = full.split(".")[0]
99
+ sink = None
100
+ if isinstance(func, ast.Name) and last in ("open", "urlopen"):
101
+ sink = last
102
+ elif head in IO_MODULES or ".objects." in f".{full}." or full in ("time.sleep", "asyncio.sleep"):
103
+ sink = full
104
+ elif isinstance(func, ast.Attribute) and (last in DB_METHODS or last in FILE_METHODS):
105
+ sink = full or last
106
+ first = call.args[0] if call is not None and call.args else None
107
+ if isinstance(first, ast.JoinedStr) and first.values and isinstance(first.values[0], ast.Constant):
108
+ first = first.values[0] # f"SELECT … {table}": the leading text says what kind of statement it is
109
+ is_text = isinstance(first, ast.Constant) and isinstance(first.value, str)
110
+ word = re.match(r"\s*(\w+)", first.value) if is_text else None # (triple-quoted SQL starts on a new line)
111
+ verb = word.group(1).upper() if word else ""
112
+ if sink and verb in ("SELECT", "WITH"):
113
+ sink += '("SELECT …")'
114
+ elif sink and verb in ("INSERT", "UPDATE", "DELETE", "REPLACE", "UPSERT", "MERGE"):
115
+ sink += f'("{verb} …")' # what it changes is visible: a write, for the security checks
116
+ return sink
117
+
118
+
119
+ def const_deps(e: ast.AST, local: set[str], maybe: set[str]) -> frozenset | None:
120
+ """A sequence whose length is fixed in the code (a literal, a module-level constant holding one, range(N) or
121
+ x[:N] with a small N, or one of those through .items()/sorted()/enumerate()…): the imported names that must turn
122
+ out to be constants for that to hold, or None if it isn't one."""
123
+ if isinstance(e, LITERALS):
124
+ return NONE
125
+ if isinstance(e, ast.Name):
126
+ return NONE if e.id in local else frozenset([e.id]) if e.id in maybe else None
127
+ if isinstance(e, ast.Attribute):
128
+ d = dotted(e) or ""
129
+ if e.attr in local or d in local:
130
+ return NONE
131
+ return frozenset([e.attr]) if e.attr in maybe else None
132
+ if isinstance(e, ast.Subscript) and isinstance(e.slice, ast.Slice):
133
+ up = e.slice.upper
134
+ return NONE if isinstance(up, ast.Constant) and isinstance(up.value, int) and up.value <= SMALL else None
135
+ if isinstance(e, ast.Call):
136
+ f = e.func
137
+ if isinstance(f, ast.Name) and f.id == "range" and e.args:
138
+ last = e.args[1] if len(e.args) > 1 else e.args[0]
139
+ return NONE if isinstance(last, ast.Constant) and isinstance(last.value, int) and last.value <= SMALL else None
140
+ if isinstance(f, ast.Name) and f.id in ("sorted", "reversed", "enumerate", "list", "tuple", "set", "zip") and e.args:
141
+ out = NONE
142
+ for a in e.args[:2]:
143
+ d = const_deps(a, local, maybe)
144
+ if d is None:
145
+ return None
146
+ out |= d
147
+ return out
148
+ if isinstance(f, ast.Attribute) and f.attr in ("items", "keys", "values"):
149
+ return const_deps(f.value, local, maybe)
150
+ return None
151
+
152
+
153
+ def _and(bounded: frozenset | None, d: frozenset | None) -> frozenset | None:
154
+ return None if bounded is None or d is None else bounded | d
155
+
156
+
157
+ def walk_loops(nodes, local: set[str], maybe: set[str]):
158
+ """Every node under `nodes`, with whether it runs once per iteration of a loop (for/while/comprehension), whether
159
+ that's a for/while statement (where an await waits on each round in turn), its boundedness (see the module
160
+ docstring; None outside loops), and whether it's inside a transaction block. A nested def starts afresh."""
161
+ stack = [(n, False, False, NONE, False) for n in reversed(list(nodes))]
162
+ while stack:
163
+ n, loop, stmt, bounded, tx = stack.pop()
164
+ yield n, loop, stmt, (bounded if loop else None), tx
165
+ if isinstance(n, (ast.With, ast.AsyncWith)) and any(_is_tx(i.context_expr) for i in n.items):
166
+ kids = [(c, loop, stmt, bounded, True) for c in ast.iter_child_nodes(n)]
167
+ elif isinstance(n, (ast.For, ast.AsyncFor)):
168
+ inner = _and(bounded, const_deps(n.iter, local, maybe))
169
+ kids = [(n.target, loop, stmt, bounded, tx), (n.iter, loop, stmt, bounded, tx)]
170
+ kids += [(c, True, True, inner, tx) for c in n.body + n.orelse]
171
+ elif isinstance(n, ast.While):
172
+ kids = [(n.test, True, True, None, tx)] + [(c, True, True, None, tx) for c in n.body + n.orelse]
173
+ elif isinstance(n, COMPREHENSIONS):
174
+ gens = n.generators
175
+ inner = bounded
176
+ for g in gens:
177
+ inner = _and(inner, const_deps(g.iter, local, maybe))
178
+ kids = [(gens[0].iter, loop, stmt, bounded, tx)]
179
+ kids += [(c, True, stmt, inner, tx) for c in ast.iter_child_nodes(n) if c is not gens[0]]
180
+ kids += [(c, True, stmt, inner, tx) for c in ast.iter_child_nodes(gens[0]) if c is not gens[0].iter]
181
+ elif isinstance(n, SCOPES):
182
+ kids = [(c, False, False, NONE, False) for c in ast.iter_child_nodes(n)]
183
+ else:
184
+ kids = [(c, loop, stmt, bounded, tx) for c in ast.iter_child_nodes(n)]
185
+ stack.extend(reversed(kids))
186
+
187
+
188
+ TX = re.compile(
189
+ r"(?:^|\.)(?:session|transaction|atomic|begin|begin_nested|connect|savepoint|batch|bulk_writer|cursor)$"
190
+ r"|^(?:conn|connection|db|tx|txn)$",
191
+ re.I,
192
+ )
193
+
194
+
195
+ def _is_tx(expr: ast.AST) -> bool:
196
+ """`with db.session(…):`, `with transaction.atomic():`, `with conn:` (a sqlite3 connection commits once at the end)."""
197
+ target = expr.func if isinstance(expr, ast.Call) else expr
198
+ return bool(TX.search(dotted(target) or ""))
199
+
200
+
201
+ def branches(fn) -> int:
202
+ """Decision points in the function (if, loops, except, case, conditional expressions, and/or)."""
203
+ n = 0
204
+ for x in ast.walk(fn):
205
+ if isinstance(x, (ast.If, ast.For, ast.AsyncFor, ast.While, ast.ExceptHandler, ast.IfExp, ast.match_case)):
206
+ n += 1
207
+ elif isinstance(x, ast.BoolOp):
208
+ n += len(x.values) - 1
209
+ elif isinstance(x, ast.comprehension):
210
+ n += 1 + len(x.ifs)
211
+ return n
212
+
213
+
214
+ def _type_checking(test: ast.AST) -> bool:
215
+ return (isinstance(test, ast.Name) and test.id == "TYPE_CHECKING") or (
216
+ isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING"
217
+ )
218
+
219
+
220
+ def _imports(tree: ast.Module):
221
+ """Every import, with whether it runs when the module loads. Imports inside functions (often placed there to
222
+ avoid an import loop) and under `if TYPE_CHECKING:` don't: they can't make a loop at load time."""
223
+ stack = [(n, True) for n in reversed(tree.body)]
224
+ while stack:
225
+ n, at_load = stack.pop()
226
+ if isinstance(n, (ast.Import, ast.ImportFrom)):
227
+ yield n, at_load
228
+ continue
229
+ if isinstance(n, ast.If) and _type_checking(n.test):
230
+ kids = [(c, False) for c in n.body] + [(c, at_load) for c in n.orelse]
231
+ elif isinstance(n, SCOPES):
232
+ kids = [(c, False) for c in ast.iter_child_nodes(n)]
233
+ else:
234
+ kids = [(c, at_load) for c in ast.iter_child_nodes(n)]
235
+ stack.extend(reversed(kids))
236
+
237
+
238
+ class _Ctx:
239
+ """What one module can tell about its own names, to keep only references that could resolve."""
240
+
241
+ def __init__(self, tree: ast.Module, imports: list):
242
+ self.funcs = {n.name for n in tree.body if isinstance(n, FUNCS)}
243
+ self.classes = {n.name for n in tree.body if isinstance(n, ast.ClassDef)}
244
+ self.from_locals = {i[3] or i[2] for i in imports if i[0] == "from"}
245
+ self.import_heads = {(i[2] or i[1].split(".")[0]) for i in imports if i[0] == "import"} | {
246
+ i[1] for i in imports if i[0] == "import"
247
+ }
248
+ self.bases = {"self", "cls"} | self.classes | self.from_locals | self.import_heads
249
+ self.local_consts: set[str] = set()
250
+
251
+ def expr(self, node: ast.AST) -> list | None:
252
+ if isinstance(node, ast.Name):
253
+ return ["n", node.id] if node.id in self.funcs or node.id in self.classes or node.id in self.from_locals else None
254
+ if isinstance(node, ast.Attribute):
255
+ base = node.value.id if isinstance(node.value, ast.Name) else None
256
+ d = dotted(node)
257
+ head = d.split(".")[0] if d else None
258
+ if (base and base in self.bases) or (head and head in self.import_heads | self.from_locals):
259
+ return ["a", base, node.attr, d]
260
+ return None
261
+
262
+
263
+ BY_NAME = {"getattr", "hasattr", "setattr", "delattr"}
264
+
265
+
266
+ def by_name(call: ast.Call) -> str | None:
267
+ """The attribute a getattr/hasattr/setattr call names with a literal string, if it does."""
268
+ if isinstance(call.func, ast.Name) and call.func.id in BY_NAME and len(call.args) >= 2:
269
+ arg = call.args[1]
270
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str) and arg.value.isidentifier():
271
+ return arg.value
272
+ return None
273
+
274
+
275
+ def events(nodes, ctx: _Ctx, sites: bool = True) -> list:
276
+ out: list = []
277
+ refs: list = []
278
+ call_funcs = set()
279
+ walked = list(walk_loops(nodes, ctx.local_consts, ctx.from_locals))
280
+ for n, loop, stmt, bounded, tx in walked:
281
+ b = sorted(bounded) if bounded is not None else None
282
+ if isinstance(n, ast.Await) and stmt and sites:
283
+ out.append(["w", n.lineno, b])
284
+ if isinstance(n, ast.Call):
285
+ call_funcs.add(id(n.func))
286
+ f = n.func
287
+ if isinstance(f, (ast.Name, ast.Attribute)):
288
+ expr = ctx.expr(f)
289
+ elif isinstance(f, ast.Subscript):
290
+ root = f
291
+ while isinstance(root, ast.Subscript):
292
+ root = root.value
293
+ expr = ["s", root.id] if isinstance(root, ast.Name) else None
294
+ else:
295
+ expr = None
296
+ attr = f.attr if isinstance(f, ast.Attribute) else None
297
+ out.append(["c", n.lineno, bool(loop), b, expr, io_call(f, n), attr, tx])
298
+ # getattr(obj, "save"): the same as obj.save, written as a string
299
+ name = by_name(n)
300
+ target = n.args[0] if name and isinstance(n.args[0], (ast.Name, ast.Attribute)) else None
301
+ if target is not None and (e := ctx.expr(ast.Attribute(value=target, attr=name, ctx=ast.Load()))):
302
+ refs.append(["r", e])
303
+ for n, *_ in walked:
304
+ if id(n) in call_funcs:
305
+ continue
306
+ if isinstance(n, (ast.Name, ast.Attribute)) and isinstance(n.ctx, ast.Load) and (e := ctx.expr(n)):
307
+ refs.append(["r", e])
308
+ return out + refs
309
+
310
+
311
+ def _local_imports(fn) -> list:
312
+ """Imports inside a function: they name things for that function only (two functions may import different
313
+ `summarize`s), so they're resolved per function as well as for the module."""
314
+ out = []
315
+ for n in ast.walk(fn):
316
+ if isinstance(n, ast.Import):
317
+ out += [["import", a.name, a.asname, False] for a in n.names]
318
+ elif isinstance(n, ast.ImportFrom):
319
+ out += [["from", n.module, n.level, a.name, a.asname, False] for a in n.names]
320
+ return out
321
+
322
+
323
+ def parse_module(path: str, rel: str) -> dict | None:
324
+ """The per-file step: everything python.py needs from one file, or None if it isn't valid Python."""
325
+ try:
326
+ text = Path(path).read_text(encoding="utf-8", errors="replace")
327
+ tree = ast.parse(text, filename=rel)
328
+ except (SyntaxError, ValueError, OSError, RecursionError):
329
+ return None # not valid for this Python: skip rather than fail the whole map
330
+ imports = [] # ["import", name, asname, at_load] / ["from", module, level, name, asname, at_load]
331
+ for node, at_load in _imports(tree):
332
+ if isinstance(node, ast.Import):
333
+ imports += [["import", a.name, a.asname, at_load] for a in node.names]
334
+ else:
335
+ imports += [["from", node.module, node.level, a.name, a.asname, at_load] for a in node.names]
336
+ # the ctx wants (kind, name, asname) shapes: normalise "from" entries to (kind, module, name, asname)
337
+ ctx = _Ctx(tree, [["import", i[1], i[2]] if i[0] == "import" else ["from", i[1], i[3], i[4]] for i in imports])
338
+ tables, consts = {}, []
339
+ for node in tree.body:
340
+ value = node.value if isinstance(node, (ast.Assign, ast.AnnAssign)) else None
341
+ if isinstance(value, LITERALS):
342
+ for t in node.targets if isinstance(node, ast.Assign) else [node.target]:
343
+ if isinstance(t, ast.Name):
344
+ consts.append(t.id)
345
+ tables[t.id] = [e for x in ast.walk(value) if isinstance(x, (ast.Name, ast.Attribute)) and (e := ctx.expr(x))]
346
+ ctx.local_consts = set(consts)
347
+ exports = []
348
+ for node in tree.body:
349
+ if (
350
+ isinstance(node, ast.Assign)
351
+ and any(isinstance(t, ast.Name) and t.id == "__all__" for t in node.targets)
352
+ and isinstance(node.value, (ast.List, ast.Tuple))
353
+ ):
354
+ exports += [e.value for e in node.value.elts if isinstance(e, ast.Constant)]
355
+ defs = []
356
+
357
+ def add(node, qualname: str, kind: str, cls: str | None) -> None:
358
+ shape, tokens = shape_of(node)
359
+ first = node.body[0] if node.body else None
360
+ doc = (
361
+ first.end_lineno - first.lineno + 1
362
+ if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant) and isinstance(first.value.value, str)
363
+ else 0
364
+ )
365
+ defs.append({
366
+ "qualname": qualname, "name": node.name, "line": node.lineno, "end": getattr(node, "end_lineno", node.lineno),
367
+ "kind": kind, "decorated": bool(node.decorator_list), "exported": node.name in exports or node.name == "main",
368
+ "shape": shape, "tokens": tokens, "cls": cls,
369
+ "deco": events(node.decorator_list, ctx, sites=False), "body": events(node.body, ctx), "doc": doc,
370
+ "branches": branches(node),
371
+ "imports": _local_imports(node),
372
+ }) # fmt: skip
373
+
374
+ top = []
375
+ for node in tree.body:
376
+ if isinstance(node, FUNCS):
377
+ add(node, node.name, "function", None)
378
+ elif isinstance(node, ast.ClassDef):
379
+ for item in node.body:
380
+ if isinstance(item, FUNCS):
381
+ add(item, f"{node.name}.{item.name}", "method", node.name)
382
+ # the class body's own statements, its methods' decorators and its own decorators
383
+ stmts = [s for s in node.body if not isinstance(s, FUNCS)]
384
+ stmts += [d for s in node.body if isinstance(s, FUNCS) for d in s.decorator_list]
385
+ top.append([node.name, events(stmts + node.decorator_list, ctx)])
386
+ else:
387
+ top.append([None, events([node], ctx)])
388
+ return {
389
+ "loc": len(text.splitlines()),
390
+ "imports": imports,
391
+ "consts": consts,
392
+ "tables": tables,
393
+ "exports": exports,
394
+ "classes": sorted(ctx.classes),
395
+ "defs": defs,
396
+ "top": top,
397
+ # names used as obj.name, or as getattr(obj, "name"): a method of that name may be what runs
398
+ "attrs": sorted(
399
+ {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)}
400
+ | {s for n in ast.walk(tree) if isinstance(n, ast.Call) and (s := by_name(n))}
401
+ ),
402
+ }