@skillstech/thunderlang 0.5.11 → 0.5.12
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.
- package/CHANGELOG.md +437 -0
- package/dist/core.cjs +30431 -7604
- package/dist/index.cjs +28577 -5331
- package/dist/learn.cjs +22676 -3870
- package/package.json +12 -3
- package/src/bicep.mjs +167 -0
- package/src/cli.mjs +169 -3
- package/src/commands.mjs +464 -0
- package/src/core.d.ts +12 -4
- package/src/core.mjs +12 -4
- package/src/emit.mjs +1 -1
- package/src/executed.d.mts +53 -0
- package/src/executed.mjs +465 -0
- package/src/faithful.mjs +137 -0
- package/src/file-formats.mjs +35 -0
- package/src/hcl.mjs +94 -0
- package/src/index.d.ts +7 -1
- package/src/index.mjs +6 -1
- package/src/infra-bicep.mjs +312 -0
- package/src/infra-cloud.mjs +348 -0
- package/src/infra-compose.mjs +315 -0
- package/src/infra-containers.mjs +100 -0
- package/src/infra-docker.mjs +267 -0
- package/src/infra-expr.mjs +509 -0
- package/src/infra-gha.mjs +350 -0
- package/src/infra-k8s.mjs +657 -0
- package/src/infra-terraform.mjs +499 -0
- package/src/infra-words.mjs +811 -0
- package/src/libraries.mjs +202 -0
- package/src/lift.mjs +48 -6
- package/src/meaning.d.mts +89 -0
- package/src/meaning.mjs +2544 -0
- package/src/model.d.mts +59 -12
- package/src/model.mjs +462 -80
- package/src/powershell.mjs +1361 -0
- package/src/read-repo-fs.mjs +29 -7
- package/src/read-repo.d.mts +5 -1
- package/src/read-repo.mjs +33 -7
- package/src/read.d.mts +21 -1
- package/src/read.mjs +1015 -42
- package/src/review.d.mts +35 -0
- package/src/review.mjs +671 -0
- package/src/rlang.mjs +1084 -0
- package/src/round-trip.d.mts +12 -0
- package/src/round-trip.mjs +174 -0
- package/src/runners/thunder-generate.mjs +56 -0
- package/src/runners/thunder-trace.cjs +284 -0
- package/src/runners/thunder_trace.py +599 -0
- package/src/running.d.mts +104 -0
- package/src/running.mjs +787 -0
- package/src/same.d.mts +1 -0
- package/src/same.mjs +24 -3
- package/src/shell.mjs +1212 -0
- package/src/sql.mjs +3 -2
- package/src/steps.d.mts +6 -1
- package/src/steps.mjs +1448 -86
- package/src/system.d.mts +12 -0
- package/src/system.mjs +845 -0
- package/src/things-langs.mjs +275 -0
- package/src/thunderize.mjs +3 -3
- package/src/visual.d.mts +5 -5
- package/src/visual.mjs +24 -3
- package/src/write-steps.d.mts +64 -0
- package/src/write-steps.mjs +1608 -0
- package/src/write.mjs +2 -1
- package/src/yaml.mjs +403 -0
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
"""Proof by running, Python side: run real code and record what actually happened, with no third-party packages.
|
|
2
|
+
|
|
3
|
+
Thunder reads code into flows (questions with Yes and No sides, loops, Stops, endings). This recorder runs the code
|
|
4
|
+
and writes down, for every function under --root:
|
|
5
|
+
|
|
6
|
+
* each decision it reached (if / elif / while / for / match / except), where the code went next, and which part of
|
|
7
|
+
the statement that is according to Python's own parser (`ast`): the body, the else, a case, or past the
|
|
8
|
+
statement altogether;
|
|
9
|
+
* each ending: the `return` line (with the value, when it is a plain number, text, yes/no, or None), the `raise`
|
|
10
|
+
line with the exception type and its base classes, or "reached the end without returning".
|
|
11
|
+
|
|
12
|
+
It never interprets Thunder: the comparison with Thunder's flow is done in compiler/src/executed.mjs. It uses
|
|
13
|
+
sys.monitoring (Python 3.12+), so tracing costs little outside the functions being recorded.
|
|
14
|
+
|
|
15
|
+
Usage (always run with `python -I`, from a scratch directory):
|
|
16
|
+
python -I thunder_trace.py --root DIR --out trace.json [--max-seconds 120]
|
|
17
|
+
(--generate | --discover TESTDIR | --pytest -- PYTEST_ARGS...)
|
|
18
|
+
|
|
19
|
+
--generate call each module-level function that looks free of side effects with inputs made from its parameter
|
|
20
|
+
types and the values its own body mentions (each limit, one either side, 0, empty text, None).
|
|
21
|
+
--discover import test_*.py / *_test.py files under TESTDIR and call every test_* function that takes nothing.
|
|
22
|
+
--pytest run pytest in this process with the given arguments (pytest must be installed where this runs).
|
|
23
|
+
"""
|
|
24
|
+
import ast
|
|
25
|
+
import importlib
|
|
26
|
+
import importlib.util
|
|
27
|
+
import itertools
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import random
|
|
31
|
+
import signal
|
|
32
|
+
import sys
|
|
33
|
+
import time
|
|
34
|
+
|
|
35
|
+
MON = getattr(sys, 'monitoring', None)
|
|
36
|
+
TOOL = 4 # a free tool id (0-5); 0 is the debugger, 1 coverage, 2 profiler, 5 optimizer
|
|
37
|
+
SKIP_DIRS = {'.git', 'node_modules', '__pycache__', 'venv', '.venv', 'env', 'site-packages', 'build', 'dist', '.tox', '.eggs'}
|
|
38
|
+
TEST_FILE = lambda p: os.path.basename(p).startswith('test_') or os.path.basename(p).endswith('_test.py') or os.path.basename(p) == 'conftest.py' or any(part in ('test', 'tests', 'testing') for part in p.split(os.sep))
|
|
39
|
+
DECISIONS = (ast.If, ast.While, ast.For, ast.AsyncFor, ast.Match)
|
|
40
|
+
COMPOUND_EXIT = (ast.With, ast.AsyncWith, ast.Try) + ((ast.TryStar,) if hasattr(ast, 'TryStar') else ())
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# ── What Python's parser says about one file ─────────────────────────────────────────────────────────────
|
|
44
|
+
|
|
45
|
+
class FileInfo:
|
|
46
|
+
def __init__(self, path, rel):
|
|
47
|
+
self.path, self.rel = path, rel
|
|
48
|
+
with open(path, encoding='utf-8') as fh:
|
|
49
|
+
self.tree = ast.parse(fh.read(), path)
|
|
50
|
+
self.parent, self.field, self.depth = {}, {}, {}
|
|
51
|
+
self.starts, self.covers = {}, {}
|
|
52
|
+
self.handler_first = {} # id(first stmt of an except body) -> except line
|
|
53
|
+
self.in_finally = set() # ids of statements inside a finally body
|
|
54
|
+
self.funcs = {} # (first line incl. decorators, name) -> def line
|
|
55
|
+
self.returns = {} # return line -> line of the innermost if / case that holds it
|
|
56
|
+
self.spans = {} # first line of a compound statement -> its last line
|
|
57
|
+
self._walk(self.tree, None, None, 0, None, False)
|
|
58
|
+
|
|
59
|
+
def _walk(self, node, parent, field, depth, encl, fin):
|
|
60
|
+
for name, value in ast.iter_fields(node):
|
|
61
|
+
items = value if isinstance(value, list) else [value]
|
|
62
|
+
for idx, child in enumerate(items):
|
|
63
|
+
if not isinstance(child, ast.AST):
|
|
64
|
+
continue
|
|
65
|
+
if isinstance(child, ast.stmt):
|
|
66
|
+
self.parent[id(child)] = node
|
|
67
|
+
self.field[id(child)] = name
|
|
68
|
+
self.depth[id(child)] = depth
|
|
69
|
+
if fin or (name == 'finalbody'):
|
|
70
|
+
self.in_finally.add(id(child))
|
|
71
|
+
cur = self.starts.get(child.lineno)
|
|
72
|
+
if cur is None or self.depth[id(cur)] > depth:
|
|
73
|
+
self.starts[child.lineno] = child
|
|
74
|
+
for line in range(child.lineno, (child.end_lineno or child.lineno) + 1):
|
|
75
|
+
c = self.covers.setdefault(line, [])
|
|
76
|
+
c.append(child)
|
|
77
|
+
if isinstance(node, ast.ExceptHandler) and name == 'body' and idx == 0:
|
|
78
|
+
self.handler_first[id(child)] = node.lineno
|
|
79
|
+
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
80
|
+
first = min([child.lineno] + [d.lineno for d in child.decorator_list])
|
|
81
|
+
self.funcs[(first, child.name)] = child.lineno
|
|
82
|
+
if isinstance(child, ast.Return):
|
|
83
|
+
self.returns[child.lineno] = encl
|
|
84
|
+
if (child.end_lineno or child.lineno) > child.lineno:
|
|
85
|
+
self.spans[child.lineno] = max(self.spans.get(child.lineno, 0), child.end_lineno)
|
|
86
|
+
inner = encl
|
|
87
|
+
if isinstance(child, ast.If):
|
|
88
|
+
inner = child.lineno
|
|
89
|
+
self._walk(child, child, name, depth + 1, inner, fin or name == 'finalbody')
|
|
90
|
+
elif isinstance(child, ast.match_case):
|
|
91
|
+
self.parent[id(child)] = node
|
|
92
|
+
self.field[id(child)] = 'case'
|
|
93
|
+
self._walk(child, child, name, depth, child.pattern.lineno, fin)
|
|
94
|
+
elif isinstance(child, ast.ExceptHandler):
|
|
95
|
+
self.parent[id(child)] = node
|
|
96
|
+
self.field[id(child)] = 'handlers'
|
|
97
|
+
self._walk(child, child, name, depth, encl, fin)
|
|
98
|
+
elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
|
|
99
|
+
self._walk(child, child, name, depth + 1, encl, fin)
|
|
100
|
+
# expressions hold no statements (except lambdas, which have none either)
|
|
101
|
+
|
|
102
|
+
def at_line(self, line):
|
|
103
|
+
"""The statement a LINE event belongs to: the outermost one starting on the line, else the innermost one
|
|
104
|
+
whose lines include it (a continued expression, or an `except` line, which belongs to its try)."""
|
|
105
|
+
s = self.starts.get(line)
|
|
106
|
+
if s is not None:
|
|
107
|
+
return s
|
|
108
|
+
c = self.covers.get(line)
|
|
109
|
+
return max(c, key=lambda x: self.depth[id(x)]) if c else None
|
|
110
|
+
|
|
111
|
+
def at_pos(self, line, col):
|
|
112
|
+
"""The innermost statement that contains (line, col)."""
|
|
113
|
+
if line is None:
|
|
114
|
+
return None
|
|
115
|
+
best = None
|
|
116
|
+
for s in self.covers.get(line, []):
|
|
117
|
+
if (s.lineno, s.col_offset) <= (line, col if col is not None else 0) <= (s.end_lineno, s.end_col_offset):
|
|
118
|
+
if best is None or self.depth[id(s)] > self.depth[id(best)]:
|
|
119
|
+
best = s
|
|
120
|
+
return best
|
|
121
|
+
|
|
122
|
+
def where(self, d, n):
|
|
123
|
+
"""Where statement n sits relative to decision d: body, orelse, case:<line>, or after."""
|
|
124
|
+
x = n
|
|
125
|
+
while x is not None:
|
|
126
|
+
p = self.parent.get(id(x))
|
|
127
|
+
if p is d:
|
|
128
|
+
return self.field.get(id(x))
|
|
129
|
+
if isinstance(p, ast.match_case) and self.parent.get(id(p)) is d:
|
|
130
|
+
return 'case:%d' % p.pattern.lineno
|
|
131
|
+
x = p
|
|
132
|
+
return 'after'
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ── The recorder ──────────────────────────────────────────────────────────────────────────────────────────
|
|
136
|
+
|
|
137
|
+
class Frame:
|
|
138
|
+
__slots__ = ('cur', 'pending', 'last_return', 'func')
|
|
139
|
+
|
|
140
|
+
def __init__(self, func):
|
|
141
|
+
self.cur = None
|
|
142
|
+
self.pending = None
|
|
143
|
+
self.last_return = None
|
|
144
|
+
self.func = func
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class Recorder:
|
|
148
|
+
def __init__(self, root):
|
|
149
|
+
self.root = os.path.realpath(root)
|
|
150
|
+
self.files = {} # real path -> FileInfo or None
|
|
151
|
+
self.codes = {} # code -> (FileInfo, def line) for recorded functions
|
|
152
|
+
self.frames = {}
|
|
153
|
+
self.out = {} # rel -> {'functions': {}, 'decisions': {}, 'returns': {}}
|
|
154
|
+
self.instrumented = []
|
|
155
|
+
|
|
156
|
+
def info_for(self, filename):
|
|
157
|
+
if filename in self.files:
|
|
158
|
+
return self.files[filename]
|
|
159
|
+
real = os.path.realpath(filename)
|
|
160
|
+
info = None
|
|
161
|
+
if real.endswith('.py') and real.startswith(self.root + os.sep):
|
|
162
|
+
rel = os.path.relpath(real, self.root)
|
|
163
|
+
if not TEST_FILE(rel) and not any(p in SKIP_DIRS for p in rel.split(os.sep)):
|
|
164
|
+
try:
|
|
165
|
+
info = FileInfo(real, rel.replace(os.sep, '/'))
|
|
166
|
+
self.out[info.rel] = {'functions': {}, 'decisions': {}, 'returns': {str(k): v for k, v in info.returns.items()}, 'spans': {str(k): v for k, v in info.spans.items()}}
|
|
167
|
+
except (SyntaxError, UnicodeDecodeError, OSError):
|
|
168
|
+
info = None
|
|
169
|
+
self.files[filename] = info
|
|
170
|
+
return info
|
|
171
|
+
|
|
172
|
+
def fn(self, info, line):
|
|
173
|
+
return self.out[info.rel]['functions'].setdefault(str(line), {'runs': 0, 'returns': {}, 'raises': {}, 'fellOff': 0, 'unwound': 0})
|
|
174
|
+
|
|
175
|
+
# Events ---------------------------------------------------------------------------------------------
|
|
176
|
+
def on_start(self, code, offset):
|
|
177
|
+
hit = self.codes.get(code)
|
|
178
|
+
if hit is None:
|
|
179
|
+
info = self.info_for(code.co_filename)
|
|
180
|
+
line = info.funcs.get((code.co_firstlineno, code.co_name)) if info else None
|
|
181
|
+
if line is None:
|
|
182
|
+
return MON.DISABLE
|
|
183
|
+
hit = self.codes[code] = (info, line)
|
|
184
|
+
MON.set_local_events(TOOL, code, MON.events.LINE | MON.events.PY_RETURN)
|
|
185
|
+
self.instrumented.append(code)
|
|
186
|
+
info, line = hit
|
|
187
|
+
self.fn(info, line)['runs'] += 1
|
|
188
|
+
self.frames[id(sys._getframe(1))] = Frame(line)
|
|
189
|
+
|
|
190
|
+
def state(self, code):
|
|
191
|
+
hit = self.codes.get(code)
|
|
192
|
+
if hit is None:
|
|
193
|
+
return None, None
|
|
194
|
+
f = sys._getframe(2)
|
|
195
|
+
st = self.frames.get(id(f))
|
|
196
|
+
if st is None:
|
|
197
|
+
st = self.frames[id(f)] = Frame(hit[1])
|
|
198
|
+
return hit[0], st
|
|
199
|
+
|
|
200
|
+
def resolve(self, info, st, n):
|
|
201
|
+
d = st.pending
|
|
202
|
+
st.pending = None
|
|
203
|
+
where = info.where(d, n) if n is not None else 'end'
|
|
204
|
+
if where in ('orelse',) and isinstance(d, (ast.For, ast.AsyncFor, ast.While)):
|
|
205
|
+
where = 'after'
|
|
206
|
+
kind = 'if' if isinstance(d, ast.If) else 'while' if isinstance(d, ast.While) else 'match' if isinstance(d, ast.Match) else 'for'
|
|
207
|
+
rec = self.out[info.rel]['decisions'].setdefault(str(d.lineno), {'kind': kind, 'obs': {}})
|
|
208
|
+
key = '%s|%s' % (where, n.lineno if n is not None else '')
|
|
209
|
+
rec['obs'][key] = rec['obs'].get(key, 0) + 1
|
|
210
|
+
|
|
211
|
+
def on_line(self, code, line):
|
|
212
|
+
info, st = self.state(code)
|
|
213
|
+
if info is None:
|
|
214
|
+
return
|
|
215
|
+
s = info.at_line(line)
|
|
216
|
+
if s is None or s is st.cur:
|
|
217
|
+
return
|
|
218
|
+
st.cur = s
|
|
219
|
+
h = info.handler_first.get(id(s))
|
|
220
|
+
if h is not None:
|
|
221
|
+
rec = self.out[info.rel]['decisions'].setdefault(str(h), {'kind': 'handler', 'obs': {}})
|
|
222
|
+
key = 'body|%d' % s.lineno
|
|
223
|
+
rec['obs'][key] = rec['obs'].get(key, 0) + 1
|
|
224
|
+
if st.pending is not None:
|
|
225
|
+
self.resolve(info, st, s)
|
|
226
|
+
if isinstance(s, ast.Return):
|
|
227
|
+
st.last_return = s
|
|
228
|
+
elif st.last_return is not None and not isinstance(s, COMPOUND_EXIT) and id(s) not in info.in_finally:
|
|
229
|
+
st.last_return = None
|
|
230
|
+
if isinstance(s, DECISIONS) and line == s.lineno:
|
|
231
|
+
st.pending = s
|
|
232
|
+
|
|
233
|
+
def position(self, code, offset):
|
|
234
|
+
try:
|
|
235
|
+
p = list(code.co_positions())[offset // 2]
|
|
236
|
+
return p[0], p[2]
|
|
237
|
+
except Exception:
|
|
238
|
+
return None, None
|
|
239
|
+
|
|
240
|
+
def on_return(self, code, offset, value):
|
|
241
|
+
info, st = self.state(code)
|
|
242
|
+
if info is None:
|
|
243
|
+
return
|
|
244
|
+
self.frames.pop(id(sys._getframe(1)), None)
|
|
245
|
+
line, col = self.position(code, offset)
|
|
246
|
+
s = info.at_pos(line, col)
|
|
247
|
+
if st.pending is not None:
|
|
248
|
+
if s is not None and s is not st.pending:
|
|
249
|
+
self.resolve(info, st, s)
|
|
250
|
+
else:
|
|
251
|
+
self.resolve(info, st, None)
|
|
252
|
+
fn = self.fn(info, st.func)
|
|
253
|
+
r = s if isinstance(s, ast.Return) else st.last_return
|
|
254
|
+
if r is not None:
|
|
255
|
+
e = fn['returns'].setdefault(str(r.lineno), {'count': 0, 'values': []})
|
|
256
|
+
e['count'] += 1
|
|
257
|
+
v = plain(value)
|
|
258
|
+
if v is not None and v not in e['values'] and len(e['values']) < 6:
|
|
259
|
+
e['values'].append(v)
|
|
260
|
+
elif code.co_flags & 0x20 or code.co_flags & 0x80 or code.co_flags & 0x200:
|
|
261
|
+
pass # a generator or coroutine finishing is not an ending a person reads
|
|
262
|
+
else:
|
|
263
|
+
fn['fellOff'] += 1
|
|
264
|
+
if st.cur is not None:
|
|
265
|
+
at = fn.setdefault('fellOffAt', {})
|
|
266
|
+
at[str(st.cur.lineno)] = at.get(str(st.cur.lineno), 0) + 1
|
|
267
|
+
|
|
268
|
+
def on_raise(self, code, offset, exc):
|
|
269
|
+
hit = self.codes.get(code)
|
|
270
|
+
if hit is None:
|
|
271
|
+
return
|
|
272
|
+
info = hit[0]
|
|
273
|
+
st = self.frames.get(id(sys._getframe(1)))
|
|
274
|
+
line, col = self.position(code, offset)
|
|
275
|
+
s = info.at_pos(line, col)
|
|
276
|
+
if st is not None and st.pending is not None:
|
|
277
|
+
if s is not None and s is not st.pending and info.where(st.pending, s) != 'after':
|
|
278
|
+
self.resolve(info, st, s)
|
|
279
|
+
else:
|
|
280
|
+
st.pending = None # the condition itself failed
|
|
281
|
+
if isinstance(s, ast.Raise):
|
|
282
|
+
fn = self.fn(info, hit[1])
|
|
283
|
+
e = fn['raises'].setdefault(str(s.lineno), {'count': 0, 'types': {}})
|
|
284
|
+
e['count'] += 1
|
|
285
|
+
t = type(exc)
|
|
286
|
+
e['types'][t.__name__] = [c.__name__ for c in t.__mro__]
|
|
287
|
+
|
|
288
|
+
def on_unwind(self, code, offset, exc):
|
|
289
|
+
hit = self.codes.get(code)
|
|
290
|
+
if hit is None:
|
|
291
|
+
return
|
|
292
|
+
self.frames.pop(id(sys._getframe(1)), None)
|
|
293
|
+
self.fn(hit[0], hit[1])['unwound'] += 1
|
|
294
|
+
|
|
295
|
+
def start(self):
|
|
296
|
+
MON.use_tool_id(TOOL, 'thunder-proof')
|
|
297
|
+
E = MON.events
|
|
298
|
+
MON.register_callback(TOOL, E.PY_START, self.on_start)
|
|
299
|
+
MON.register_callback(TOOL, E.LINE, self.on_line)
|
|
300
|
+
MON.register_callback(TOOL, E.PY_RETURN, self.on_return)
|
|
301
|
+
MON.register_callback(TOOL, E.RAISE, self.on_raise)
|
|
302
|
+
MON.register_callback(TOOL, E.PY_UNWIND, self.on_unwind)
|
|
303
|
+
MON.set_events(TOOL, E.PY_START | E.RAISE | E.PY_UNWIND)
|
|
304
|
+
|
|
305
|
+
def stop(self):
|
|
306
|
+
MON.set_events(TOOL, 0)
|
|
307
|
+
for c in self.instrumented:
|
|
308
|
+
try:
|
|
309
|
+
MON.set_local_events(TOOL, c, 0)
|
|
310
|
+
except Exception:
|
|
311
|
+
pass
|
|
312
|
+
MON.free_tool_id(TOOL)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def plain(v):
|
|
316
|
+
"""A value written so Thunder can compare it: numbers, text, yes/no, nothing. Anything else is not compared."""
|
|
317
|
+
if v is None:
|
|
318
|
+
return 'None'
|
|
319
|
+
if isinstance(v, bool):
|
|
320
|
+
return 'True' if v else 'False'
|
|
321
|
+
if isinstance(v, (int, float)):
|
|
322
|
+
return repr(v)
|
|
323
|
+
if isinstance(v, str) and len(v) <= 80:
|
|
324
|
+
return json.dumps(v)
|
|
325
|
+
return None
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
# ── Inputs ───────────────────────────────────────────────────────────────────────────────────────────────
|
|
329
|
+
|
|
330
|
+
SAFE_CALLS = set('abs all any bool dict divmod enumerate filter float frozenset int isinstance issubclass len list map max min range repr reversed round set sorted str sum tuple zip ValueError TypeError KeyError IndexError ZeroDivisionError ArithmeticError RuntimeError LookupError NotImplementedError Exception'.split())
|
|
331
|
+
SAFE_METHODS = set('lower upper strip lstrip rstrip split rsplit join replace startswith endswith format get items keys values append extend insert pop count index find rfind title capitalize isdigit isalpha isalnum isspace copy add discard update setdefault partition rpartition zfill ljust rjust center casefold encode decode'.split())
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
class Timeout(Exception):
|
|
335
|
+
pass
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def looks_pure(fn, module_names, imported):
|
|
339
|
+
"""True when a function calls only builtins, plain text/list/dict methods, and this module's own functions and
|
|
340
|
+
classes: safe to call with made-up inputs (no files, network, processes, or clocks)."""
|
|
341
|
+
for n in ast.walk(fn):
|
|
342
|
+
if isinstance(n, (ast.Import, ast.ImportFrom, ast.Global, ast.Nonlocal, ast.Await, ast.Yield, ast.YieldFrom)):
|
|
343
|
+
return False
|
|
344
|
+
if isinstance(n, ast.Call):
|
|
345
|
+
f = n.func
|
|
346
|
+
if isinstance(f, ast.Name):
|
|
347
|
+
if f.id not in SAFE_CALLS and f.id not in module_names:
|
|
348
|
+
return False
|
|
349
|
+
elif isinstance(f, ast.Attribute):
|
|
350
|
+
base = f.value
|
|
351
|
+
while isinstance(base, ast.Attribute):
|
|
352
|
+
base = base.value
|
|
353
|
+
if isinstance(base, ast.Name) and base.id in imported:
|
|
354
|
+
return False
|
|
355
|
+
if f.attr not in SAFE_METHODS:
|
|
356
|
+
return False
|
|
357
|
+
else:
|
|
358
|
+
return False
|
|
359
|
+
return True
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def literals(fn):
|
|
363
|
+
nums, texts = set(), set()
|
|
364
|
+
for n in ast.walk(fn):
|
|
365
|
+
if isinstance(n, ast.Constant):
|
|
366
|
+
if isinstance(n.value, bool):
|
|
367
|
+
continue
|
|
368
|
+
if isinstance(n.value, (int, float)):
|
|
369
|
+
for v in (n.value - 1, n.value, n.value + 1):
|
|
370
|
+
nums.add(v)
|
|
371
|
+
if isinstance(n.value, float):
|
|
372
|
+
nums.update((round(n.value - 0.01, 6), round(n.value + 0.01, 6)))
|
|
373
|
+
elif isinstance(n.value, str) and len(n.value) <= 40:
|
|
374
|
+
texts.add(n.value)
|
|
375
|
+
return sorted(nums)[:12], sorted(texts)[:8]
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def values_for(arg, default, nums, texts):
|
|
379
|
+
ann = ast.unparse(arg.annotation) if arg.annotation is not None else ''
|
|
380
|
+
nums = nums or [0]
|
|
381
|
+
ints = sorted({int(x) for x in nums} | {0, 1, -1})
|
|
382
|
+
floats = sorted(set(nums) | {0.0, 1.5, -1.0})
|
|
383
|
+
strs = sorted(set(texts) | {'', 'x'})
|
|
384
|
+
out = []
|
|
385
|
+
if default is not None:
|
|
386
|
+
try:
|
|
387
|
+
out.append(ast.literal_eval(default))
|
|
388
|
+
except Exception:
|
|
389
|
+
pass
|
|
390
|
+
a = ann.replace(' ', '')
|
|
391
|
+
if a in ('int',):
|
|
392
|
+
out += ints
|
|
393
|
+
elif a in ('float',):
|
|
394
|
+
out += floats
|
|
395
|
+
elif a in ('bool',):
|
|
396
|
+
out += [True, False]
|
|
397
|
+
elif a in ('str',):
|
|
398
|
+
out += strs
|
|
399
|
+
elif a.startswith(('list', 'List', 'Sequence', 'Iterable', 'tuple', 'Tuple')):
|
|
400
|
+
out += [[], [0], [1, 20, 3], ['a', ''], ints[:4]]
|
|
401
|
+
elif a.startswith(('dict', 'Dict', 'Mapping')):
|
|
402
|
+
out += [{}, {'a': 1}]
|
|
403
|
+
elif a.startswith(('Optional[', 'None|')) or a.endswith('|None'):
|
|
404
|
+
inner = a.replace('Optional[', '')[:-1] if a.startswith('Optional[') else a.replace('|None', '').replace('None|', '')
|
|
405
|
+
out += [None] + (ints if inner == 'int' else floats if inner == 'float' else strs if inner == 'str' else [0, ''])
|
|
406
|
+
elif not a:
|
|
407
|
+
out += [None, 0, 1, -1, '', 'x', True, False, []] + ints[:6] + list(texts)[:4]
|
|
408
|
+
else:
|
|
409
|
+
return None # a type we cannot make
|
|
410
|
+
seen, uniq = set(), []
|
|
411
|
+
for v in out:
|
|
412
|
+
k = repr(v)
|
|
413
|
+
if k not in seen:
|
|
414
|
+
seen.add(k)
|
|
415
|
+
uniq.append(v)
|
|
416
|
+
return uniq
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def generated_calls(tree, module, cap):
|
|
420
|
+
module_names = {n.name for n in tree.body if isinstance(n, (ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef))}
|
|
421
|
+
imported = set()
|
|
422
|
+
for n in tree.body:
|
|
423
|
+
if isinstance(n, ast.Import):
|
|
424
|
+
imported.update(a.asname or a.name.split('.')[0] for a in n.names)
|
|
425
|
+
elif isinstance(n, ast.ImportFrom):
|
|
426
|
+
imported.update(a.asname or a.name for a in n.names)
|
|
427
|
+
module_names -= imported
|
|
428
|
+
for fn in tree.body:
|
|
429
|
+
if not isinstance(fn, ast.FunctionDef) or fn.decorator_list:
|
|
430
|
+
continue
|
|
431
|
+
target = getattr(module, fn.name, None)
|
|
432
|
+
if not callable(target) or not looks_pure(fn, module_names, imported):
|
|
433
|
+
continue
|
|
434
|
+
a = fn.args
|
|
435
|
+
if a.vararg or a.kwarg or a.posonlyargs or any(d is None for d in a.kw_defaults):
|
|
436
|
+
continue
|
|
437
|
+
nums, texts = literals(fn)
|
|
438
|
+
defaults = [None] * (len(a.args) - len(a.defaults)) + list(a.defaults)
|
|
439
|
+
axes = []
|
|
440
|
+
for arg, d in zip(a.args, defaults):
|
|
441
|
+
vs = values_for(arg, d, nums, texts)
|
|
442
|
+
if vs is None:
|
|
443
|
+
axes = None
|
|
444
|
+
break
|
|
445
|
+
axes.append(vs)
|
|
446
|
+
if axes is None:
|
|
447
|
+
continue
|
|
448
|
+
total = 1
|
|
449
|
+
for ax in axes:
|
|
450
|
+
total *= len(ax)
|
|
451
|
+
if total <= cap:
|
|
452
|
+
combos = itertools.product(*axes)
|
|
453
|
+
else:
|
|
454
|
+
rnd = random.Random(fn.name)
|
|
455
|
+
combos = (tuple(ax[rnd.randrange(len(ax))] for ax in axes) for _ in range(cap))
|
|
456
|
+
combos = [tuple(ax[0] for ax in axes)] + list(combos)
|
|
457
|
+
yield fn.name, target, combos
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def call_with_timeout(f, args, seconds):
|
|
461
|
+
def alarm(signum, frame):
|
|
462
|
+
raise Timeout()
|
|
463
|
+
old = signal.signal(signal.SIGALRM, alarm)
|
|
464
|
+
signal.setitimer(signal.ITIMER_REAL, seconds)
|
|
465
|
+
try:
|
|
466
|
+
f(*[_copy(x) for x in args])
|
|
467
|
+
return 'ok'
|
|
468
|
+
except Timeout:
|
|
469
|
+
return 'timeout'
|
|
470
|
+
except Exception:
|
|
471
|
+
return 'raised'
|
|
472
|
+
finally:
|
|
473
|
+
signal.setitimer(signal.ITIMER_REAL, 0)
|
|
474
|
+
signal.signal(signal.SIGALRM, old)
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _copy(x):
|
|
478
|
+
return list(x) if isinstance(x, list) else dict(x) if isinstance(x, dict) else x
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def module_name(root, path):
|
|
482
|
+
rel = os.path.relpath(path, root)[:-3].split(os.sep)
|
|
483
|
+
if rel[-1] == '__init__':
|
|
484
|
+
rel = rel[:-1]
|
|
485
|
+
return '.'.join(rel)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def py_files(root, tests=False):
|
|
489
|
+
for d, dirs, files in os.walk(root):
|
|
490
|
+
dirs[:] = sorted(x for x in dirs if x not in SKIP_DIRS and not x.startswith('.'))
|
|
491
|
+
for name in sorted(files):
|
|
492
|
+
p = os.path.join(d, name)
|
|
493
|
+
if name.endswith('.py') and TEST_FILE(os.path.relpath(p, root)) == tests:
|
|
494
|
+
yield p
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def main(argv):
|
|
498
|
+
args = {'--root': None, '--out': None, '--max-seconds': '120', '--max-calls': '200', '--discover': None}
|
|
499
|
+
mode, rest, i = None, [], 0
|
|
500
|
+
while i < len(argv):
|
|
501
|
+
a = argv[i]
|
|
502
|
+
if a in ('--generate',):
|
|
503
|
+
mode = 'generate'
|
|
504
|
+
elif a == '--pytest':
|
|
505
|
+
mode = 'pytest'
|
|
506
|
+
elif a == '--':
|
|
507
|
+
rest = argv[i + 1:]
|
|
508
|
+
break
|
|
509
|
+
elif a in args:
|
|
510
|
+
args[a] = argv[i + 1]
|
|
511
|
+
i += 1
|
|
512
|
+
if a == '--discover':
|
|
513
|
+
mode = 'discover'
|
|
514
|
+
i += 1
|
|
515
|
+
root, out = args['--root'], args['--out']
|
|
516
|
+
meta = {'python': sys.version.split()[0], 'mode': mode, 'calls': 0, 'raised': 0, 'timeouts': 0, 'capped': False, 'errors': []}
|
|
517
|
+
if MON is None:
|
|
518
|
+
meta['errors'].append('Python %s has no sys.monitoring (3.12 or newer is needed).' % meta['python'])
|
|
519
|
+
json.dump({'meta': meta, 'files': {}}, open(out, 'w'))
|
|
520
|
+
return 0
|
|
521
|
+
root = os.path.realpath(root)
|
|
522
|
+
rec = Recorder(root)
|
|
523
|
+
limit = float(args['--max-seconds'])
|
|
524
|
+
began = time.time()
|
|
525
|
+
if mode == 'generate':
|
|
526
|
+
sys.path.insert(0, root)
|
|
527
|
+
rec.start()
|
|
528
|
+
try:
|
|
529
|
+
for p in py_files(root):
|
|
530
|
+
if time.time() - began > limit:
|
|
531
|
+
meta['capped'] = True
|
|
532
|
+
break
|
|
533
|
+
try:
|
|
534
|
+
tree = ast.parse(open(p, encoding='utf-8').read())
|
|
535
|
+
mod = importlib.import_module(module_name(root, p))
|
|
536
|
+
except BaseException as e: # a module that cannot be imported is simply not run
|
|
537
|
+
meta['errors'].append('%s: %s' % (os.path.relpath(p, root), str(e)[:160]))
|
|
538
|
+
continue
|
|
539
|
+
for name, target, combos in generated_calls(tree, mod, int(args['--max-calls'])):
|
|
540
|
+
for combo in combos:
|
|
541
|
+
if time.time() - began > limit:
|
|
542
|
+
meta['capped'] = True
|
|
543
|
+
break
|
|
544
|
+
r = call_with_timeout(target, combo, 0.5)
|
|
545
|
+
meta['calls'] += 1
|
|
546
|
+
meta['raised'] += r == 'raised'
|
|
547
|
+
meta['timeouts'] += r == 'timeout'
|
|
548
|
+
finally:
|
|
549
|
+
rec.stop()
|
|
550
|
+
elif mode == 'discover':
|
|
551
|
+
tdir = os.path.realpath(args['--discover'])
|
|
552
|
+
sys.path.insert(0, root)
|
|
553
|
+
sys.path.insert(0, tdir)
|
|
554
|
+
rec.start()
|
|
555
|
+
try:
|
|
556
|
+
for p in py_files(tdir, tests=True):
|
|
557
|
+
if os.path.basename(p) == 'conftest.py':
|
|
558
|
+
continue
|
|
559
|
+
try:
|
|
560
|
+
spec = importlib.util.spec_from_file_location('thunder_test_' + module_name(tdir, p).replace('.', '_'), p)
|
|
561
|
+
mod = importlib.util.module_from_spec(spec)
|
|
562
|
+
spec.loader.exec_module(mod)
|
|
563
|
+
except BaseException as e:
|
|
564
|
+
meta['errors'].append('%s: %s' % (os.path.relpath(p, tdir), str(e)[:160]))
|
|
565
|
+
continue
|
|
566
|
+
for name in sorted(dir(mod)):
|
|
567
|
+
f = getattr(mod, name)
|
|
568
|
+
if name.startswith('test') and callable(f) and getattr(f, '__code__', None) and f.__code__.co_argcount == 0:
|
|
569
|
+
if time.time() - began > limit:
|
|
570
|
+
meta['capped'] = True
|
|
571
|
+
break
|
|
572
|
+
r = call_with_timeout(f, (), 5)
|
|
573
|
+
meta['calls'] += 1
|
|
574
|
+
meta['raised'] += r == 'raised'
|
|
575
|
+
meta['timeouts'] += r == 'timeout'
|
|
576
|
+
finally:
|
|
577
|
+
rec.stop()
|
|
578
|
+
elif mode == 'pytest':
|
|
579
|
+
import pytest
|
|
580
|
+
def alarm(signum, frame):
|
|
581
|
+
meta['capped'] = True
|
|
582
|
+
rec.stop()
|
|
583
|
+
signal.signal(signal.SIGALRM, alarm)
|
|
584
|
+
signal.setitimer(signal.ITIMER_REAL, limit)
|
|
585
|
+
rec.start()
|
|
586
|
+
try:
|
|
587
|
+
meta['exit'] = int(pytest.main(rest))
|
|
588
|
+
finally:
|
|
589
|
+
signal.setitimer(signal.ITIMER_REAL, 0)
|
|
590
|
+
if not meta['capped']:
|
|
591
|
+
rec.stop()
|
|
592
|
+
meta['seconds'] = round(time.time() - began, 2)
|
|
593
|
+
with open(out, 'w') as fh:
|
|
594
|
+
json.dump({'meta': meta, 'files': rec.out}, fh)
|
|
595
|
+
return 0
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
if __name__ == '__main__':
|
|
599
|
+
sys.exit(main(sys.argv[1:]))
|