@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,12 @@
|
|
|
1
|
+
// Code → Thunder → code for steps (see src/round-trip.mjs). Node only (runs Python for Python behavior).
|
|
2
|
+
import type { Expr } from './meaning.mjs';
|
|
3
|
+
export const ROUND_TRIP_LANGUAGES: string[];
|
|
4
|
+
export type StepTripResult = 'exact' | 'different' | 'code' | 'not-written' | 'not-read-back';
|
|
5
|
+
/** Read code as Thunder reads a file, and give back its first step's tree. */
|
|
6
|
+
export function rereadStatement(code: string, language: string): Expr | null;
|
|
7
|
+
/** Write a step's tree back as code, read it again, and compare the trees. */
|
|
8
|
+
export function stepRoundTrip(step: { expr?: Expr }, language: string): { result: StepTripResult; code?: string; back?: Expr; why?: string | null };
|
|
9
|
+
/** A condition or value of a step that can be run alone: its names, the original code, and the code written back. */
|
|
10
|
+
export function behaviorCase(step: { expr?: Expr }, sourceText: string, language: string): { names: string[]; original: string; written: string } | null;
|
|
11
|
+
/** Run original and written-back code on the same generated inputs. Go is not run (it says so). */
|
|
12
|
+
export function runBehavior(cases: { names: string[]; original: string; written: string }[], language: string): { result: 'same' | 'different' | 'not-run'; why?: string; tried?: number }[];
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// Code → Thunder → code, for steps: is the meaning unchanged?
|
|
2
|
+
//
|
|
3
|
+
// Every step carries its meaning tree (`expr`, see meaning.mjs). Here each tree is written back as code in the
|
|
4
|
+
// language it was read from (TypeScript, JavaScript, Python, Go), that code is read again by the same reader, and the
|
|
5
|
+
// two trees are compared:
|
|
6
|
+
//
|
|
7
|
+
// structural the re-read tree equals the original (after normalizing spelling: quotes, spacing). "exact".
|
|
8
|
+
// behavioral where a condition or value is made only of names, values, and operators, the ORIGINAL code and the
|
|
9
|
+
// code written back are both run on generated inputs (Node for TypeScript/JavaScript, Python for
|
|
10
|
+
// Python) and must give the same answer, or fail the same way, every time.
|
|
11
|
+
//
|
|
12
|
+
// A step Thunder could not read into a tree (`kind: 'code'`) is counted apart: its code is kept, but it is not a
|
|
13
|
+
// round trip of meaning. Nothing is reported as exact that was not compared.
|
|
14
|
+
import { spawnSync } from 'node:child_process';
|
|
15
|
+
import { readCode } from './read.mjs';
|
|
16
|
+
import { renderStatement, renderExpr, parseStatementSpans, sameExpr, normalizeExpr, nodesOf } from './meaning.mjs';
|
|
17
|
+
|
|
18
|
+
export const ROUND_TRIP_LANGUAGES = ['typescript', 'javascript', 'python', 'go'];
|
|
19
|
+
|
|
20
|
+
const WRAP = {
|
|
21
|
+
typescript: (code) => `function thunderRoundTrip() {\n${code}\nthunderEnd();\n}\n`,
|
|
22
|
+
javascript: (code) => `function thunderRoundTrip() {\n${code}\nthunderEnd();\n}\n`,
|
|
23
|
+
python: (code) => `def thunder_round_trip():\n${code.split('\n').map((l) => ` ${l}`).join('\n')}\n thunder_end()\n`,
|
|
24
|
+
go: (code) => `package main\n\nfunc thunderRoundTrip() {\n${code}\nthunderEnd()\n}\n`,
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// A case label is only code inside a switch (match): it is written in one, and its step read from there.
|
|
28
|
+
const IN_SWITCH = {
|
|
29
|
+
typescript: (code) => `switch (thunderSubject) {\n${code}\n thunderCase();\n}`,
|
|
30
|
+
javascript: (code) => `switch (thunderSubject) {\n${code}\n thunderCase();\n}`,
|
|
31
|
+
python: (code) => `match thunder_subject:\n ${code}\n thunder_case()`,
|
|
32
|
+
go: (code) => `switch thunderSubject {\n${code}\n\tthunderCase()\n}`,
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Read code the way Thunder reads a file, and give back the first step's tree (a case label: the case's). */
|
|
36
|
+
export function rereadStatement(code, language, { caseLabel = false } = {}) {
|
|
37
|
+
const wrapped = WRAP[language](caseLabel ? IN_SWITCH[language](code) : code);
|
|
38
|
+
const reading = readCode(wrapped, { language });
|
|
39
|
+
const fn = reading.items.find((i) => i.kind === 'function' && /^thunder_?round_?trip$/i.test(i.name));
|
|
40
|
+
const first = fn?.steps?.[0];
|
|
41
|
+
return (caseLabel ? first?.children?.[0]?.expr : first?.expr) ?? null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* One step's round trip: { result, code?, back?, why? }, result one of 'exact', 'different', 'code' (Thunder kept
|
|
46
|
+
* the code; no tree to compare), 'not-written' (the tree has something the language cannot say this way), or
|
|
47
|
+
* 'not-read-back' (the written code did not read back as a step).
|
|
48
|
+
*/
|
|
49
|
+
export function stepRoundTrip(step, language) {
|
|
50
|
+
const e = step?.expr;
|
|
51
|
+
if (!e || e.kind === 'code') return { result: 'code' };
|
|
52
|
+
let code;
|
|
53
|
+
try { code = renderStatement(e, language); } catch (err) { return { result: 'not-written', why: err.message }; }
|
|
54
|
+
let back;
|
|
55
|
+
try { back = rereadStatement(code, language, { caseLabel: e.kind === 'case' }); } catch (err) { return { result: 'not-read-back', code, why: err.message }; }
|
|
56
|
+
if (!back) return { result: 'not-read-back', code, why: 'no step was read from the written code' };
|
|
57
|
+
return sameExpr(e, back) ? { result: 'exact', code } : { result: 'different', code, back, why: firstDifference(normalizeExpr(e), normalizeExpr(back)) };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function firstDifference(a, b, path = '') {
|
|
61
|
+
if (JSON.stringify(a) === JSON.stringify(b)) return null;
|
|
62
|
+
if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return `${path || 'tree'}: ${JSON.stringify(a)?.slice(0, 80)} became ${JSON.stringify(b)?.slice(0, 80)}`;
|
|
63
|
+
for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
|
64
|
+
const d = firstDifference(a[k], b[k], path ? `${path}.${k}` : k);
|
|
65
|
+
if (d) return d;
|
|
66
|
+
}
|
|
67
|
+
return path;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ── Behavior: run the original and the written-back code on the same inputs ─────────────────────────────────
|
|
71
|
+
|
|
72
|
+
const PURE = new Set(['name', 'literal', 'not', 'unary', 'binary', 'compare', 'chain', 'logic', 'conditional', 'array', 'template']);
|
|
73
|
+
/** The part of a step that can be run on its own: a condition or a value made only of names, values, and operators. */
|
|
74
|
+
function runnablePart(tree) {
|
|
75
|
+
const part = tree.kind === 'if' && !tree.init ? tree.test : tree.kind === 'return' ? tree.value : tree.kind === 'assign' && (tree.op === '=' || tree.op === ':=') ? tree.value : tree.kind === 'loop' && tree.form === 'while' ? tree.test : null;
|
|
76
|
+
if (!part) return null;
|
|
77
|
+
for (const n of nodesOf(part)) {
|
|
78
|
+
if (!PURE.has(n.kind)) return null;
|
|
79
|
+
if (n.kind === 'unary' && !/^[-+~]$/.test(n.op)) return null;
|
|
80
|
+
if (n.kind === 'literal' && !/^(?:number|text|bool|null)$/.test(n.type)) return null;
|
|
81
|
+
if (n.kind === 'array' && n.form === 'set') return null;
|
|
82
|
+
}
|
|
83
|
+
return part;
|
|
84
|
+
}
|
|
85
|
+
const freeNames = (part) => [...new Set([...nodesOf(part)].filter((n) => n.kind === 'name').map((n) => n.name))].filter((n) => !/^(?:undefined|NaN|Infinity|None|True|False|null|true|false|nil)$/.test(n));
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A behavior case for a step, or null when the step has no part that can be run alone: { names, original, written }
|
|
89
|
+
* (`original`: the code as it is in the file; `written`: the code Thunder wrote back from the tree).
|
|
90
|
+
*/
|
|
91
|
+
export function behaviorCase(step, sourceText, language) {
|
|
92
|
+
if (!step?.expr || step.expr.kind === 'code' || !sourceText) return null;
|
|
93
|
+
const read = parseStatementSpans(sourceText, language);
|
|
94
|
+
if (!read) return null;
|
|
95
|
+
const part = runnablePart(read.tree);
|
|
96
|
+
if (!part) return null;
|
|
97
|
+
const original = read.textOf(part);
|
|
98
|
+
if (!original) return null;
|
|
99
|
+
const names = freeNames(part);
|
|
100
|
+
if (names.length > 4) return null;
|
|
101
|
+
let written;
|
|
102
|
+
try { written = renderExpr(part, language); } catch { return null; }
|
|
103
|
+
return { names, original: original.trim(), written };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const JS_POOL = [0, 1, -1, 2, 7, 0.5, '', 'a', 'B', null, undefined, true, false, [], [1]];
|
|
107
|
+
const PY_POOL = ['0', '1', '-1', '2', '7', '0.5', "''", "'a'", "'B'", 'None', 'True', 'False', '[]', '[1]'];
|
|
108
|
+
/** Inputs for k names: every combination when there are few, else a fixed spread of them (deterministic). */
|
|
109
|
+
function inputs(k, n) {
|
|
110
|
+
const total = n ** k;
|
|
111
|
+
const out = [];
|
|
112
|
+
if (total <= 225) { for (let i = 0; i < total; i++) { const c = []; let x = i; for (let j = 0; j < k; j++) { c.push(x % n); x = Math.floor(x / n); } out.push(c); } return out; }
|
|
113
|
+
let seed = 7;
|
|
114
|
+
const rnd = () => { seed = (seed * 1103515245 + 12345) % 2147483648; return seed; };
|
|
115
|
+
for (let i = 0; i < 225; i++) out.push(Array.from({ length: k }, () => rnd() % n));
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function runJs(c) {
|
|
120
|
+
const show = (f, args) => { try { const v = f(...args); return `= ${typeof v} ${JSON.stringify(v, (k, x) => (x === undefined ? '__undefined__' : Number.isNaN(x) ? '__NaN__' : x))}`; } catch (e) { return `! ${e?.constructor?.name}`; } };
|
|
121
|
+
let a, b;
|
|
122
|
+
try { a = new Function(...c.names, `"use strict"; return (${c.original});`); } catch { return { result: 'not-run', why: 'the original is not plain JavaScript' }; }
|
|
123
|
+
try { b = new Function(...c.names, `"use strict"; return (${c.written});`); } catch { return { result: 'different', why: 'the written code does not compile' }; }
|
|
124
|
+
for (const combo of inputs(c.names.length, JS_POOL.length)) {
|
|
125
|
+
const args = combo.map((i) => (Array.isArray(JS_POOL[i]) ? [...JS_POOL[i]] : JS_POOL[i]));
|
|
126
|
+
const x = show(a, args), y = show(b, args);
|
|
127
|
+
if (x !== y) return { result: 'different', why: `with ${c.names.map((n, i) => `${n}=${JSON.stringify(args[i])}`).join(', ')}: ${x} before, ${y} after` };
|
|
128
|
+
}
|
|
129
|
+
return { result: 'same', tried: inputs(c.names.length, JS_POOL.length).length };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const PY_RUNNER = `
|
|
133
|
+
import json, sys
|
|
134
|
+
cases = json.load(sys.stdin)
|
|
135
|
+
pool = ${JSON.stringify(PY_POOL)}
|
|
136
|
+
out = []
|
|
137
|
+
def show(src, env):
|
|
138
|
+
try:
|
|
139
|
+
v = eval(src, {"__builtins__": {}}, env)
|
|
140
|
+
return "= " + type(v).__name__ + " " + repr(v)
|
|
141
|
+
except Exception as e:
|
|
142
|
+
return "! " + type(e).__name__
|
|
143
|
+
for c in cases:
|
|
144
|
+
res = {"result": "same", "tried": 0}
|
|
145
|
+
try:
|
|
146
|
+
compile(c["original"], "<o>", "eval"); compile(c["written"], "<w>", "eval")
|
|
147
|
+
except SyntaxError:
|
|
148
|
+
out.append({"result": "not-run", "why": "does not compile as one Python expression"}); continue
|
|
149
|
+
for combo in c["inputs"]:
|
|
150
|
+
env = {n: eval(pool[i]) for n, i in zip(c["names"], combo)}
|
|
151
|
+
a = show(c["original"], dict(env)); b = show(c["written"], dict(env))
|
|
152
|
+
res["tried"] += 1
|
|
153
|
+
if a != b:
|
|
154
|
+
res = {"result": "different", "why": "with %s: %s before, %s after" % (env, a, b)}; break
|
|
155
|
+
out.append(res)
|
|
156
|
+
print(json.dumps(out))
|
|
157
|
+
`;
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Run behavior cases: [{ names, original, written }] in a language -> [{ result: 'same' | 'different' | 'not-run',
|
|
161
|
+
* why?, tried? }]. TypeScript/JavaScript run in Node; Python in a Python process (when one is installed); Go is not
|
|
162
|
+
* run (its values need declared types), and says so.
|
|
163
|
+
*/
|
|
164
|
+
export function runBehavior(cases, language) {
|
|
165
|
+
if (!cases.length) return [];
|
|
166
|
+
if (language === 'typescript' || language === 'javascript') return cases.map(runJs);
|
|
167
|
+
if (language === 'python') {
|
|
168
|
+
const payload = JSON.stringify(cases.map((c) => ({ ...c, inputs: inputs(c.names.length, PY_POOL.length) })));
|
|
169
|
+
const r = spawnSync('python3', ['-I', '-c', PY_RUNNER], { input: payload, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
|
|
170
|
+
if (r.status !== 0) return cases.map(() => ({ result: 'not-run', why: `Python could not run: ${(r.stderr || r.error?.message || '').split('\n').filter(Boolean).pop() ?? 'unknown'}` }));
|
|
171
|
+
return JSON.parse(r.stdout);
|
|
172
|
+
}
|
|
173
|
+
return cases.map(() => ({ result: 'not-run', why: `${language} values need declared types to run alone` }));
|
|
174
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Proof by running, JavaScript inputs: when code has no tests Thunder can run, call each exported function that looks
|
|
2
|
+
// free of side effects with inputs made from the values its own body mentions (each number, one either side, 0, empty
|
|
3
|
+
// text, null, undefined, true/false). Run under thunder-trace.cjs, which records what happened.
|
|
4
|
+
// node --require thunder-trace.cjs thunder-generate.mjs <root> [maxCalls]
|
|
5
|
+
import { readdirSync, statSync, readFileSync, realpathSync } from 'node:fs';
|
|
6
|
+
import { join, relative, sep } from 'node:path';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
|
|
9
|
+
const root = realpathSync(process.argv[2]);
|
|
10
|
+
const cap = Number(process.argv[3] || 200);
|
|
11
|
+
const SKIP = new Set(['node_modules', '.git', 'dist', 'build', 'coverage']);
|
|
12
|
+
const TEST = /(^|\/)(test|tests|__tests__|spec|specs|fixtures?)\/|\.(test|spec)\.[cm]?js$/;
|
|
13
|
+
// A function is called only when its text names nothing that reaches outside: no modules, files, network, processes,
|
|
14
|
+
// timers, randomness, or evaluation of text as code.
|
|
15
|
+
const UNSAFE = /\b(require|import|fetch|process|globalThis|window|document|fs|child_process|setTimeout|setInterval|setImmediate|Promise|XMLHttpRequest|WebSocket|eval|Function|Math\.random|Date|crypto|console|this|async|await|yield|while)\b/;
|
|
16
|
+
|
|
17
|
+
function files(dir, out = []) {
|
|
18
|
+
for (const name of readdirSync(dir).sort()) {
|
|
19
|
+
if (SKIP.has(name) || name.startsWith('.')) continue;
|
|
20
|
+
const full = join(dir, name);
|
|
21
|
+
if (statSync(full).isDirectory()) files(full, out);
|
|
22
|
+
else if (/\.(m?js|cjs)$/.test(name) && !TEST.test(relative(root, full).split(sep).join('/'))) out.push(full);
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function valuesFor(text) {
|
|
28
|
+
const nums = new Set([0, 1, -1]);
|
|
29
|
+
for (const m of text.matchAll(/(?<![\w.$])(-?\d+(?:\.\d+)?)(?![\w.])/g)) { const n = Number(m[1]); if (Number.isFinite(n) && nums.size < 14) { nums.add(n - 1); nums.add(n); nums.add(n + 1); } }
|
|
30
|
+
const strs = new Set(['', 'x']);
|
|
31
|
+
for (const m of text.matchAll(/(["'])((?:\\.|(?!\1).){0,40})\1/g)) if (strs.size < 10) strs.add(m[2]);
|
|
32
|
+
return [...nums, ...strs, null, undefined, true, false, [], [1, 20, 3]];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let calls = 0;
|
|
36
|
+
for (const file of files(root)) {
|
|
37
|
+
let mod;
|
|
38
|
+
try { mod = await import(pathToFileURL(file).href); } catch { continue; }
|
|
39
|
+
const source = readFileSync(file, 'utf8');
|
|
40
|
+
for (const [name, f] of Object.entries(mod)) {
|
|
41
|
+
if (typeof f !== 'function' || /^class\b/.test(Function.prototype.toString.call(f))) continue;
|
|
42
|
+
const text = Function.prototype.toString.call(f);
|
|
43
|
+
if (UNSAFE.test(text.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, '""')) || !source.includes(text.slice(0, 40))) continue;
|
|
44
|
+
const values = valuesFor(text);
|
|
45
|
+
const arity = Math.max(f.length, 1);
|
|
46
|
+
const total = values.length ** arity;
|
|
47
|
+
let seed = 7;
|
|
48
|
+
const pick = () => { seed = (seed * 48271) % 2147483647; return values[seed % values.length]; };
|
|
49
|
+
const combos = total <= cap ? [...Array(total).keys()].map((i) => Array.from({ length: arity }, (_, k) => values[Math.floor(i / values.length ** k) % values.length])) : Array.from({ length: cap }, () => Array.from({ length: arity }, pick));
|
|
50
|
+
for (const args of combos) {
|
|
51
|
+
calls++;
|
|
52
|
+
try { f(...args.map((a) => (Array.isArray(a) ? [...a] : a))); } catch { /* a Stop is a behavior too */ }
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
process.stdout.write(JSON.stringify({ calls }));
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Proof by running, JavaScript side: record what real code actually did, using V8's own debugger in this process
|
|
3
|
+
// (node:inspector), with no dependencies. Load it with `node --require <this file>`; set
|
|
4
|
+
// THUNDER_TRACE_ROOT the folder whose code is recorded (node_modules and test files are left out)
|
|
5
|
+
// THUNDER_TRACE_OUT a folder; each process writes trace-<pid>.json there when it exits
|
|
6
|
+
// THUNDER_TRACE_MAX_SECONDS stop recording after this many seconds (default 120)
|
|
7
|
+
//
|
|
8
|
+
// V8 stops at every statement of the recorded files (its own statement positions, from getPossibleBreakpoints). At
|
|
9
|
+
// an `if` / `else if` / `while` it works out the condition's value without side effects (evaluateOnCallFrame with
|
|
10
|
+
// throwOnSideEffect; a condition that could change something is left undecided and not recorded), then notes the next
|
|
11
|
+
// statement the same call reached. At a return point it notes the line of the `return` and the value; at the end of
|
|
12
|
+
// a function body, "reached the end without returning"; at a `throw`, the error's class and its parents. It never
|
|
13
|
+
// reads Thunder: compiler/src/executed.mjs compares this record with Thunder's flow.
|
|
14
|
+
const inspector = require('node:inspector');
|
|
15
|
+
const fs = require('node:fs');
|
|
16
|
+
const path = require('node:path');
|
|
17
|
+
const { fileURLToPath } = require('node:url');
|
|
18
|
+
|
|
19
|
+
const ROOT = process.env.THUNDER_TRACE_ROOT ? fs.realpathSync(process.env.THUNDER_TRACE_ROOT) : null;
|
|
20
|
+
const OUT = process.env.THUNDER_TRACE_OUT;
|
|
21
|
+
const MAX_MS = Number(process.env.THUNDER_TRACE_MAX_SECONDS || 120) * 1000;
|
|
22
|
+
const TEST = /(^|\/)(test|tests|__tests__|spec|specs|fixtures?)\//;
|
|
23
|
+
const TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/;
|
|
24
|
+
const CALL_OPENS_CONDITION = /(?:^\s*|[;{}]\s*|\belse\s+)(?:if|while)\s*\(\s*!*\s*(?:await\s+)?[\w$.]*$/;
|
|
25
|
+
|
|
26
|
+
if (ROOT && OUT) start();
|
|
27
|
+
|
|
28
|
+
function start() {
|
|
29
|
+
const began = Date.now();
|
|
30
|
+
const session = new inspector.Session();
|
|
31
|
+
session.connect();
|
|
32
|
+
const post = (method, params) => {
|
|
33
|
+
let out, err;
|
|
34
|
+
session.post(method, params, (e, r) => { err = e; out = r; });
|
|
35
|
+
if (err) throw err;
|
|
36
|
+
return out;
|
|
37
|
+
};
|
|
38
|
+
const scripts = new Map(); // scriptId -> { rel, source, lineStarts, types: Map("line:col" -> type) }
|
|
39
|
+
const files = {};
|
|
40
|
+
const meta = { node: process.version, pid: process.pid, pauses: 0, undecided: 0, capped: false };
|
|
41
|
+
const pending = new Map(); // frame key -> the question waiting for its next step { rel, line, kind, truth }
|
|
42
|
+
const last = new Map(); // frame key -> the last statement it stopped at { at, line }
|
|
43
|
+
let stopped = false;
|
|
44
|
+
|
|
45
|
+
const fileOf = (rel) => (files[rel] ||= { functions: {}, decisions: {}, returns: {} });
|
|
46
|
+
const fn = (rel, line) => (fileOf(rel).functions[line] ||= { runs: 0, returns: {}, raises: {}, fellOff: 0, unwound: 0 });
|
|
47
|
+
const bump = (o, k) => { o[k] = (o[k] || 0) + 1; };
|
|
48
|
+
|
|
49
|
+
session.on('Debugger.scriptParsed', (m) => {
|
|
50
|
+
if (stopped) return;
|
|
51
|
+
const url = m.params.url;
|
|
52
|
+
if (!url || !/\.[cm]?[jt]sx?$/.test(url) || /node_modules/.test(url)) return;
|
|
53
|
+
let file;
|
|
54
|
+
try { file = url.startsWith('file:') ? fileURLToPath(url) : url; file = fs.realpathSync(file); } catch { return; }
|
|
55
|
+
if (!file.startsWith(ROOT + path.sep)) return;
|
|
56
|
+
const rel = path.relative(ROOT, file).split(path.sep).join('/');
|
|
57
|
+
if (TEST.test(rel) || TEST_FILE.test(rel)) return;
|
|
58
|
+
let source;
|
|
59
|
+
try { source = fs.readFileSync(file, 'utf8'); } catch { return; }
|
|
60
|
+
const lineStarts = [0];
|
|
61
|
+
for (let i = 0; i < source.length; i++) if (source[i] === '\n') lineStarts.push(i + 1);
|
|
62
|
+
const types = new Map();
|
|
63
|
+
let locs;
|
|
64
|
+
try { locs = post('Debugger.getPossibleBreakpoints', { start: { scriptId: m.params.scriptId, lineNumber: 0, columnNumber: 0 } }).locations; } catch { return; }
|
|
65
|
+
const lines = source.split('\n');
|
|
66
|
+
const byLine = new Map();
|
|
67
|
+
for (const l of locs) { if (!byLine.has(l.lineNumber)) byLine.set(l.lineNumber, []); byLine.get(l.lineNumber).push(l); }
|
|
68
|
+
for (const [ln, list] of byLine) {
|
|
69
|
+
const text = lines[ln] || '';
|
|
70
|
+
list.sort((a, b) => a.columnNumber - b.columnNumber);
|
|
71
|
+
// An `if (` / `while (` whose condition starts with a call has no stop of its own: V8 stops at the call. That
|
|
72
|
+
// stop is where the question is asked (at = the keyword's column).
|
|
73
|
+
const asks = [...text.matchAll(/(?:^|[^\w$.])((?:if|while)\s*\()/g)].map((x) => x.index + x[0].length - x[1].length);
|
|
74
|
+
const conditionAt = new Map();
|
|
75
|
+
for (const k of asks) {
|
|
76
|
+
if (list.some((l) => l.columnNumber === k && l.type !== 'call')) continue;
|
|
77
|
+
const first = list.find((l) => l.columnNumber > k);
|
|
78
|
+
if (first && first.type === 'call') conditionAt.set(first.columnNumber, k);
|
|
79
|
+
}
|
|
80
|
+
for (const l of list) {
|
|
81
|
+
let type = l.type || 'statement';
|
|
82
|
+
if (l.type === 'call') {
|
|
83
|
+
if (conditionAt.has(l.columnNumber)) type = `condition:${conditionAt.get(l.columnNumber)}`;
|
|
84
|
+
else if (startsStatement(text, l.columnNumber)) {
|
|
85
|
+
// A chain continued from the lines above (`body = body\n .replace(…)`): the statement starts there.
|
|
86
|
+
let from = ln;
|
|
87
|
+
while (from > 0 && (/^\s*[.?]/.test(lines[from]) || /(?:[=(,+\-*/?:]|&&|\|\|)\s*$/.test(lines[from - 1].replace(/\/\/.*$/, ''))) && from > ln - 8) from--;
|
|
88
|
+
type = from === ln ? 'statement' : `statement:${from}`;
|
|
89
|
+
} else continue; // a call inside a statement: not a step of its own
|
|
90
|
+
}
|
|
91
|
+
types.set(`${ln}:${l.columnNumber}`, type);
|
|
92
|
+
try { post('Debugger.setBreakpoint', { location: l }); } catch { /* not every position takes one */ }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
scripts.set(m.params.scriptId, { rel, source, lineStarts, types });
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const keyOf = (frames) => frames.map((f, i) => (i === 0 ? `${f.functionLocation?.scriptId}:${f.functionLocation?.lineNumber}:${f.functionLocation?.columnNumber}` : `${f.location.scriptId}:${f.location.lineNumber}:${f.location.columnNumber}`)).join('|');
|
|
99
|
+
const offsetOf = (s, loc) => s.lineStarts[loc.lineNumber] + loc.columnNumber;
|
|
100
|
+
|
|
101
|
+
session.on('Debugger.paused', (msg) => {
|
|
102
|
+
try { onPause(msg.params); } catch { /* never break the program being run */ }
|
|
103
|
+
session.post('Debugger.resume');
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
function onPause({ callFrames, reason, data }) {
|
|
107
|
+
if (stopped) return;
|
|
108
|
+
if (Date.now() - began > MAX_MS) { meta.capped = true; stop(); return; }
|
|
109
|
+
const top = callFrames[0];
|
|
110
|
+
const s = scripts.get(top.location.scriptId);
|
|
111
|
+
if (!s) return;
|
|
112
|
+
meta.pauses++;
|
|
113
|
+
const loc = top.location;
|
|
114
|
+
const where = s.types.get(`${loc.lineNumber}:${loc.columnNumber}`) || 'statement';
|
|
115
|
+
const line = (where.startsWith('statement:') ? Number(where.slice(10)) : loc.lineNumber) + 1;
|
|
116
|
+
const key = keyOf(callFrames);
|
|
117
|
+
const defLine = (top.functionLocation?.lineNumber ?? loc.lineNumber) + 1;
|
|
118
|
+
let at = offsetOf(s, loc);
|
|
119
|
+
const kind = s.types.get(`${loc.lineNumber}:${loc.columnNumber}`) || 'statement';
|
|
120
|
+
// A stop at a call that opens a condition: the question starts at its `if` / `while`, earlier on the line.
|
|
121
|
+
if (kind.startsWith('condition:')) at = s.lineStarts[loc.lineNumber] + Number(kind.slice(10));
|
|
122
|
+
const text = s.source.slice(at, at + 400);
|
|
123
|
+
// Top-level code (the module itself, not a function) is not a member Thunder draws.
|
|
124
|
+
if (callFrames[0].functionLocation && callFrames[0].functionLocation.lineNumber === 0 && callFrames[0].functionLocation.columnNumber === 0 && !/^\s*(?:async\s+)?function\b/.test(s.source)) return;
|
|
125
|
+
if (at >= s.source.trimEnd().length) return;
|
|
126
|
+
|
|
127
|
+
if (reason === 'exception') {
|
|
128
|
+
// A throw in this function: the line of the `throw`, the error's class and its parents.
|
|
129
|
+
const p = pending.get(key);
|
|
130
|
+
if (p) { pending.delete(key); if (/^throw\b/.test(text)) record(p, line); }
|
|
131
|
+
if (!/^throw\b/.test(text)) return;
|
|
132
|
+
let names = [data?.className || 'Error'];
|
|
133
|
+
if (data?.objectId) {
|
|
134
|
+
try {
|
|
135
|
+
const r = post('Runtime.callFunctionOn', { objectId: data.objectId, returnByValue: true, functionDeclaration: 'function(){const n=[];let p=Object.getPrototypeOf(this);while(p&&p.constructor&&n.length<12){n.push(p.constructor.name);p=Object.getPrototypeOf(p);}return n}' });
|
|
136
|
+
if (Array.isArray(r.result?.value) && r.result.value.length) names = r.result.value;
|
|
137
|
+
} catch { /* keep the class name */ }
|
|
138
|
+
}
|
|
139
|
+
const f = fn(s.rel, defLine);
|
|
140
|
+
const e = (f.raises[line] ||= { count: 0, types: {} });
|
|
141
|
+
e.count++;
|
|
142
|
+
e.types[names[0]] = names;
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
const p = pending.get(key);
|
|
146
|
+
const prev = last.get(key);
|
|
147
|
+
if (kind === 'return') {
|
|
148
|
+
const f = fn(s.rel, defLine);
|
|
149
|
+
f.runs++;
|
|
150
|
+
pending.delete(key);
|
|
151
|
+
last.delete(key);
|
|
152
|
+
// The `return` this return point closes: the statement the call last stopped at, when that is a `return`;
|
|
153
|
+
// otherwise found by reading back from the return point. The end of the body is "reached the end".
|
|
154
|
+
const ret = s.source[at] === '}' ? null : prev && /^return\b/.test(s.source.slice(prev.at, prev.at + 7)) ? prev.line : returnLine(s, at);
|
|
155
|
+
if (ret === 'arrow') return; // an arrow function's expression body: its value is its answer, no `return` line
|
|
156
|
+
if (p) record(p, ret ?? null);
|
|
157
|
+
if (ret == null) { f.fellOff++; if (prev) bump(f.fellOffAt ||= {}, prev.line); return; }
|
|
158
|
+
const e = (f.returns[ret] ||= { count: 0, values: [] });
|
|
159
|
+
e.count++;
|
|
160
|
+
const v = plain(top.returnValue);
|
|
161
|
+
if (v != null && !e.values.includes(v) && e.values.length < 6) e.values.push(v);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (p) { pending.delete(key); record(p, line); }
|
|
165
|
+
last.set(key, { at, line });
|
|
166
|
+
const m = text.match(/^(if|while)\s*\(/);
|
|
167
|
+
if (!m) return;
|
|
168
|
+
const cond = condition(text, m[0].length - 1);
|
|
169
|
+
if (cond == null) { meta.undecided++; return; }
|
|
170
|
+
let truth = null;
|
|
171
|
+
try {
|
|
172
|
+
const r = post('Debugger.evaluateOnCallFrame', { callFrameId: top.callFrameId, expression: `!!(${cond})`, throwOnSideEffect: true, silent: true, returnByValue: true });
|
|
173
|
+
if (!r.exceptionDetails && typeof r.result?.value === 'boolean') truth = r.result.value;
|
|
174
|
+
} catch { truth = null; }
|
|
175
|
+
if (truth == null) { meta.undecided++; return; }
|
|
176
|
+
pending.set(key, { rel: s.rel, line, kind: m[1], truth });
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function record(p, next) {
|
|
180
|
+
const d = (fileOf(p.rel).decisions[p.line] ||= { kind: p.kind, obs: {} });
|
|
181
|
+
bump(d.obs, `${p.truth ? 'body' : next == null ? 'end' : 'after'}|${next ?? ''}`);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The line of the `return` keyword this return point belongs to, or null for the end of a function body. */
|
|
185
|
+
function returnLine(s, at) {
|
|
186
|
+
if (s.source[at] === '}') return null;
|
|
187
|
+
// V8 puts a return point just after the statement (`return x;|`): step back over the `;` and spaces, then walk
|
|
188
|
+
// back to the statement's start, the nearest `return` keyword at bracket depth 0.
|
|
189
|
+
let end = at - 1;
|
|
190
|
+
while (end >= 0 && /\s/.test(s.source[end])) end--;
|
|
191
|
+
if (s.source[end] === ';') end--;
|
|
192
|
+
const before = s.source.slice(Math.max(0, end - 4000), end + 1);
|
|
193
|
+
const base = Math.max(0, end - 4000);
|
|
194
|
+
let depth = 0;
|
|
195
|
+
for (let i = before.length - 1; i >= 0; i--) {
|
|
196
|
+
const c = before[i];
|
|
197
|
+
if (c === '"' || c === "'" || c === '`') { let j = i - 1; while (j >= 0 && (before[j] !== c || before[j - 1] === '\\')) j--; i = j; continue; }
|
|
198
|
+
if (c === ')' || c === ']' || c === '}') depth++;
|
|
199
|
+
else if (c === '(' || c === '[' || c === '{') { if (depth === 0) return null; depth--; }
|
|
200
|
+
else if (depth === 0 && c === 'r' && before.startsWith('return', i) && !/[\w$]/.test(before[i - 1] || ' ') && !/[\w$]/.test(before[i + 6] || ' ')) {
|
|
201
|
+
const abs = base + i;
|
|
202
|
+
let line = 0;
|
|
203
|
+
while (line + 1 < s.lineStarts.length && s.lineStarts[line + 1] <= abs) line++;
|
|
204
|
+
return line + 1;
|
|
205
|
+
}
|
|
206
|
+
else if (depth === 0 && c === '>' && before[i - 1] === '=') return 'arrow';
|
|
207
|
+
else if (depth === 0 && c === ';') return null;
|
|
208
|
+
}
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function stop() {
|
|
213
|
+
if (stopped) return;
|
|
214
|
+
stopped = true;
|
|
215
|
+
try { post('Debugger.disable'); } catch { /* already off */ }
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
post('Debugger.enable');
|
|
219
|
+
post('Debugger.setPauseOnExceptions', { state: 'all' });
|
|
220
|
+
process.on('exit', () => {
|
|
221
|
+
stop();
|
|
222
|
+
try {
|
|
223
|
+
fs.mkdirSync(OUT, { recursive: true });
|
|
224
|
+
fs.writeFileSync(path.join(OUT, `trace-${process.pid}.json`), JSON.stringify({ meta, files }));
|
|
225
|
+
} catch { /* nothing to write to */ }
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* True when the call at `col` begins a statement: nothing before it on the line but an optional `}` / `else` / a
|
|
231
|
+
* closed `if (…)` / `;`, an assignment's left side, `await`, `new`, `void`, and the callee's own path (`res.send`).
|
|
232
|
+
*/
|
|
233
|
+
function startsStatement(text, col) {
|
|
234
|
+
let p = text.slice(0, col).replace(/(?:await\s+|new\s+|void\s+)?[\w$.]*$/, '');
|
|
235
|
+
p = p.replace(/(?:(?:var|let|const)\s+)?[\w$.[\]'"]+\s*(?:[-+*/%]|\|\||&&|\?\?)?=\s*(?:await\s+|new\s+)?$/, '');
|
|
236
|
+
if (/^\s*$/.test(p) || /[;{}]\s*$/.test(p) || /\belse\s*$/.test(p)) return true;
|
|
237
|
+
// A one-line `if (cond) call()`: the call is the statement the question leads to.
|
|
238
|
+
const m = p.match(/^(.*?\b(?:if|while|for)\s*)\(/);
|
|
239
|
+
if (m && /\)\s*$/.test(p)) { const inner = condition(p, m[1].length); return inner != null && m[1].length + inner.length + 2 === p.trimEnd().length; }
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** A returned value written so Thunder can compare it: numbers, text, yes/no, null, undefined. */
|
|
244
|
+
function plain(v) {
|
|
245
|
+
if (!v) return null;
|
|
246
|
+
if (v.type === 'undefined') return 'undefined';
|
|
247
|
+
if (v.subtype === 'null') return 'null';
|
|
248
|
+
if (v.type === 'number' && 'value' in v) return String(v.value);
|
|
249
|
+
if (v.type === 'boolean') return String(v.value);
|
|
250
|
+
if (v.type === 'string' && typeof v.value === 'string' && v.value.length <= 80) return JSON.stringify(v.value);
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* The condition inside `( … )` starting at `open` (the index of the bracket): strings, template literals, comments,
|
|
256
|
+
* and regular expressions are skipped so their brackets do not count. Null when the text does not close.
|
|
257
|
+
*/
|
|
258
|
+
function condition(text, open) {
|
|
259
|
+
let depth = 0, i = open, prev = '(';
|
|
260
|
+
while (i < text.length) {
|
|
261
|
+
const c = text[i];
|
|
262
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
263
|
+
const q = c;
|
|
264
|
+
i++;
|
|
265
|
+
while (i < text.length && text[i] !== q) { if (text[i] === '\\') i++; else if (q === '`' && text[i] === '$' && text[i + 1] === '{') return null; i++; }
|
|
266
|
+
prev = 'a'; i++; continue;
|
|
267
|
+
}
|
|
268
|
+
if (c === '/' && text[i + 1] === '/') return null;
|
|
269
|
+
if (c === '/' && text[i + 1] === '*') { const e = text.indexOf('*/', i + 2); if (e < 0) return null; i = e + 2; continue; }
|
|
270
|
+
if (c === '/' && /[(,=:[!&|?{};+\-*%<>~^]/.test(prev)) {
|
|
271
|
+
i++;
|
|
272
|
+
let cls = false;
|
|
273
|
+
while (i < text.length && (text[i] !== '/' || cls)) { if (text[i] === '\\') i++; else if (text[i] === '[') cls = true; else if (text[i] === ']') cls = false; else if (text[i] === '\n') return null; i++; }
|
|
274
|
+
prev = 'a'; i++; continue;
|
|
275
|
+
}
|
|
276
|
+
if (c === '(') depth++;
|
|
277
|
+
else if (c === ')') { depth--; if (depth === 0) return text.slice(open + 1, i); }
|
|
278
|
+
if (!/\s/.test(c)) prev = c;
|
|
279
|
+
i++;
|
|
280
|
+
}
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
module.exports = { condition, plain, startsStatement };
|