@skillstech/thunderlang 1.7.0 → 2.0.0
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 +153 -1
- package/README.md +15 -3
- package/dist/core.cjs +303 -41
- package/dist/index.cjs +9906 -1387
- package/dist/learn.cjs +1420 -93
- package/package.json +17 -15
- package/src/cli-main.mjs +381 -149
- package/src/core/ThunderRuntime.cs +22 -1
- package/src/core/check.mjs +320 -6
- package/src/core/cli.mjs +60 -8
- package/src/core/csharp-run.mjs +2 -2
- package/src/core/diagnostics.mjs +9 -0
- package/src/core/engine-core.mjs +148 -19
- package/src/core/engine-values.mjs +3 -0
- package/src/core/engine.mjs +131 -7
- package/src/core/from-python.mjs +1 -1
- package/src/core/go-run.mjs +5 -3
- package/src/core/index.mjs +12 -3
- package/src/core/java/thunder/ThunderRuntime.java +1 -0
- package/src/core/java-run.mjs +2 -2
- package/src/core/kind.mjs +6 -0
- package/src/core/lexer.mjs +16 -2
- package/src/core/parser.mjs +215 -29
- package/src/core/project-root.mjs +18 -0
- package/src/core/project.mjs +34 -16
- package/src/core/react-run.mjs +2 -2
- package/src/core/runtime-go/thunder_runtime.go +310 -2
- package/src/core/runtime-python.mjs +365 -3
- package/src/core/runtime-typescript.mjs +150 -5
- package/src/core/rust/thunder_runtime.rs +1 -0
- package/src/core/rust-run.mjs +2 -2
- package/src/core/serving.mjs +12 -0
- package/src/core/store-format.mjs +110 -0
- package/src/core/target-csharp.mjs +14 -0
- package/src/core/target-go.mjs +24 -3
- package/src/core/target-java.mjs +14 -0
- package/src/core/target-python.mjs +46 -5
- package/src/core/target-rust.mjs +14 -0
- package/src/core/target-typescript.mjs +76 -6
- package/src/core/typescript-run.mjs +6 -4
- package/src/core-changes-fs.mjs +28 -0
- package/src/core-changes.d.mts +67 -0
- package/src/core-changes.mjs +603 -0
- package/src/core-rules.mjs +146 -0
- package/src/core-services.d.mts +4 -0
- package/src/core-services.mjs +49 -0
- package/src/emit.mjs +3 -3
- package/src/evidence-words.d.mts +6 -0
- package/src/evidence-words.mjs +47 -0
- package/src/evidence.mjs +36 -1
- package/src/examples.d.mts +21 -0
- package/src/examples.mjs +175 -0
- package/src/index.d.ts +19 -0
- package/src/index.mjs +8 -1
- package/src/learn-lessons.mjs +1 -1
- package/src/lsp.mjs +110 -0
- package/src/mcp.mjs +47 -12
- package/src/obligations.d.mts +5 -0
- package/src/obligations.mjs +30 -2
- package/src/program.d.mts +7 -0
- package/src/program.mjs +7 -0
- package/src/read-repo-fs.mjs +2 -1
- package/src/review.mjs +75 -6
- package/src/same.mjs +16 -6
- package/src/scan-queries.mjs +2 -1
- package/src/symbols.d.mts +23 -0
- package/src/symbols.mjs +351 -0
- package/src/system.mjs +1 -1
- package/src/template.d.mts +31 -0
- package/src/template.mjs +189 -0
- package/src/trace-cli.mjs +8 -3
- package/src/trace-fs.mjs +29 -3
- package/src/trace.mjs +23 -7
package/src/core/cli.mjs
CHANGED
|
@@ -21,7 +21,7 @@ import { javaClassName } from './target-java.mjs';
|
|
|
21
21
|
import { formatDiagnostic } from './diagnostics.mjs';
|
|
22
22
|
import { formatCore } from './format.mjs';
|
|
23
23
|
import { paint, paintThunder, useColor } from '../term.mjs';
|
|
24
|
-
import { runWithEngine, testWithEngine, ENGINES } from './engine.mjs';
|
|
24
|
+
import { runWithEngine, testWithEngine, serveWithEngine, ENGINES, nodeStore } from './engine.mjs';
|
|
25
25
|
import { recordedRun, screenApp, screenOutline, runInProcess } from './engine-core.mjs';
|
|
26
26
|
import { hasScreens } from './target-react.mjs';
|
|
27
27
|
import { COMPILER_VERSION } from '../emit.mjs';
|
|
@@ -30,7 +30,7 @@ import { fileKind } from './kind.mjs';
|
|
|
30
30
|
/** The format of a Time Machine recording (thunder run --record, thunder replay). */
|
|
31
31
|
export const TIME_MACHINE_SCHEMA = 'thunder-time-machine-v1';
|
|
32
32
|
|
|
33
|
-
const CORE_COMMANDS = new Set(['new', 'run', 'build', 'test', 'check', 'format', 'fmt']);
|
|
33
|
+
export const CORE_COMMANDS = new Set(['new', 'run', 'build', 'test', 'check', 'format', 'fmt']);
|
|
34
34
|
|
|
35
35
|
function parse(argv) {
|
|
36
36
|
const a = { _: [], core: false, json: false, write: false, check: false, force: false, mission: false, engine: null, target: null };
|
|
@@ -39,6 +39,8 @@ function parse(argv) {
|
|
|
39
39
|
if (x === '--target') a.target = argv[++i] ?? '';
|
|
40
40
|
else if (x.startsWith('--target=')) a.target = x.slice('--target='.length);
|
|
41
41
|
else if (x === '--engine') a.engine = argv[++i] ?? '';
|
|
42
|
+
else if (x === '--port') a.port = argv[++i] ?? '';
|
|
43
|
+
else if (x.startsWith('--port=')) a.port = x.slice('--port='.length);
|
|
42
44
|
else if (x === '--record') a.record = argv[++i] ?? '';
|
|
43
45
|
else if (x.startsWith('--record=')) a.record = x.slice('--record='.length);
|
|
44
46
|
else if (x.startsWith('--engine=')) a.engine = x.slice('--engine='.length);
|
|
@@ -49,12 +51,23 @@ function parse(argv) {
|
|
|
49
51
|
else if (x === '--force') a.force = true;
|
|
50
52
|
else if (x === '--mission') a.mission = true;
|
|
51
53
|
else if (x === '--run') a.run = true;
|
|
52
|
-
else if (x.startsWith('--')) a.other = true;
|
|
54
|
+
else if (x.startsWith('--')) { a.other = true; a.unknown ??= x; }
|
|
53
55
|
else a._.push(x);
|
|
54
56
|
}
|
|
55
57
|
return a;
|
|
56
58
|
}
|
|
57
59
|
|
|
60
|
+
/** Does the program answer requests (When someone calls …)? Then thunder run keeps it running until stopped. */
|
|
61
|
+
const answersRequests = (build) => !!build.entry && (build.entry.info.endpoints ?? []).some((f) => !build.entry.info.imported?.has(f));
|
|
62
|
+
|
|
63
|
+
/** The known option closest to a mistyped one (one or two letters off), or null. */
|
|
64
|
+
function closestOption(said, known) {
|
|
65
|
+
const dist = (x, y) => { const d = Array.from({ length: y.length + 1 }, (_, j) => j); for (let i = 1; i <= x.length; i++) { let prev = d[0]; d[0] = i; for (let j = 1; j <= y.length; j++) { const t = d[j]; d[j] = Math.min(d[j] + 1, d[j - 1] + 1, prev + (x[i - 1] === y[j - 1] ? 0 : 1)); prev = t; } } return d[y.length]; };
|
|
66
|
+
let best = null, bestD = 3;
|
|
67
|
+
for (const k of known) { const dd = dist(said, k); if (dd < bestD) { bestD = dd; best = k; } }
|
|
68
|
+
return best;
|
|
69
|
+
}
|
|
70
|
+
|
|
58
71
|
/** Decide whether this invocation is a Thunder Core one: { root, file } or null. */
|
|
59
72
|
export function coreTarget(cmd, argv, cwd = process.cwd()) {
|
|
60
73
|
if (!CORE_COMMANDS.has(cmd)) return null;
|
|
@@ -81,6 +94,14 @@ export function coreTarget(cmd, argv, cwd = process.cwd()) {
|
|
|
81
94
|
const say = (s = '') => process.stdout.write(`${paint(s)}\n`);
|
|
82
95
|
const warn = (s = '') => process.stderr.write(`${s}\n`);
|
|
83
96
|
|
|
97
|
+
/** Holes (TC120) are not mistakes: a draft is counted and named apart from the problems to fix. */
|
|
98
|
+
const holeCount = (build) => build.results.reduce((k, r) => k + r.diagnostics.filter((d) => d.code === 'TC120').length, 0);
|
|
99
|
+
function problemWords(n, holes) {
|
|
100
|
+
const fix = n - holes;
|
|
101
|
+
const p = `${fix} problem${fix === 1 ? '' : 's'}`;
|
|
102
|
+
return holes ? `${p} and ${holes} hole${holes === 1 ? '' : 's'}` : p;
|
|
103
|
+
}
|
|
104
|
+
|
|
84
105
|
function report(build, cwd) {
|
|
85
106
|
let n = 0;
|
|
86
107
|
for (const r of build.results) for (const d of r.diagnostics) { warn(formatDiagnostic(d, relative(cwd, r.path) || r.rel)); n++; }
|
|
@@ -92,6 +113,21 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
|
|
|
92
113
|
const t = coreTarget(cmd, argv, cwd);
|
|
93
114
|
if (!t) return null;
|
|
94
115
|
const a = parse(argv);
|
|
116
|
+
// An option Thunder doesn't know is refused, never ignored: "--core --target go" written as one word would otherwise
|
|
117
|
+
// run the default target and look like it worked.
|
|
118
|
+
if (a.unknown && cmd !== 'new') {
|
|
119
|
+
const known = ['--core', '--engine', '--target', '--port', '--record', '--json', '--write', '--check', '--force'];
|
|
120
|
+
const said = a.unknown.split(/\s+/)[0].split('=')[0];
|
|
121
|
+
const near = known.find((k) => k === said) ? null : closestOption(said, known);
|
|
122
|
+
warn(`thunder ${cmd}: I don't know the option "${a.unknown}".${a.unknown.includes(' ') ? ' Options are separate words: --core --target go.' : near ? ` Did you mean ${near}?` : ''} Options for Thunder programs: ${known.join(', ')}.`);
|
|
123
|
+
return 2;
|
|
124
|
+
}
|
|
125
|
+
// --port: where a program with endpoints answers (every engine and target reads THUNDER_PORT).
|
|
126
|
+
if (a.port != null) {
|
|
127
|
+
if (cmd !== 'run') { warn(`thunder ${cmd}: --port is for thunder run, for a program that answers requests.`); return 2; }
|
|
128
|
+
if (!/^\d+$/.test(a.port) || Number(a.port) < 1 || Number(a.port) > 65535) { warn(`thunder run: --port takes a number from 1 to 65535, for example --port 8080.`); return 2; }
|
|
129
|
+
process.env.THUNDER_PORT = a.port;
|
|
130
|
+
}
|
|
95
131
|
try {
|
|
96
132
|
if (cmd === 'new') {
|
|
97
133
|
const root = newProject(resolve(cwd, t.new), { force: a.force });
|
|
@@ -122,11 +158,19 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
|
|
|
122
158
|
if (cmd === 'check') {
|
|
123
159
|
if (a.json) { say(JSON.stringify({ ok: build.ok, files: build.results.map((r) => ({ file: relative(cwd, r.path), diagnostics: r.diagnostics })) }, null, 2)); return build.ok ? 0 : 1; }
|
|
124
160
|
const n = report(build, cwd);
|
|
125
|
-
|
|
161
|
+
const holes = holeCount(build);
|
|
162
|
+
if (n && holes === n) { warn(`thunder check: a draft with ${holes} hole${holes === 1 ? '' : 's'} to fill in, and nothing else to fix.`); return 1; }
|
|
163
|
+
if (n) { warn(`thunder check: ${problemWords(n, holes)} in ${build.results.filter((r) => !r.ok).length} of ${build.results.length} file${build.results.length === 1 ? '' : 's'}.`); return 1; }
|
|
126
164
|
say(`thunder check: no problems in ${build.results.length} Thunder Core file${build.results.length === 1 ? '' : 's'}.`);
|
|
127
165
|
return 0;
|
|
128
166
|
}
|
|
129
|
-
if (!build.ok) {
|
|
167
|
+
if (!build.ok) {
|
|
168
|
+
const n = report(build, cwd);
|
|
169
|
+
const holes = holeCount(build);
|
|
170
|
+
const done = `nothing was ${cmd === 'build' ? 'built' : 'run'}`;
|
|
171
|
+
warn(n === holes ? `thunder ${cmd}: this is a draft with ${holes} hole${holes === 1 ? '' : 's'} to fill in; ${done}.` : `thunder ${cmd}: ${problemWords(n, holes)}; ${done}.`);
|
|
172
|
+
return 1;
|
|
173
|
+
}
|
|
130
174
|
const out = relative(cwd, build.outDir) || '.';
|
|
131
175
|
if (cmd === 'run' && a.record == null && build.entry && hasScreens(build.entry.info)) return showScreens(build, warn);
|
|
132
176
|
if (cmd === 'build' && build.target === 'react') {
|
|
@@ -190,7 +234,7 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
|
|
|
190
234
|
if (python.error) { warn(`thunder ${cmd}: ${python.error}${['run', 'test'].includes(cmd) ? `\nOr run it without Python, on the Thunder engine: thunder ${cmd} ${argv.filter((x) => !x.startsWith('--engine')).join(' ')}${argv.length ? ' ' : ''}--engine thunder`.replace(/ +/g, ' ') : ''}`); return 2; }
|
|
191
235
|
if (cmd === 'run') {
|
|
192
236
|
if (!build.entryModule) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
|
|
193
|
-
const r = runPython(python, build.outDir, `${build.entryModule}.py`, build.base);
|
|
237
|
+
const r = runPython(python, build.outDir, `${build.entryModule}.py`, build.base, { serving: answersRequests(build) });
|
|
194
238
|
return r.status ?? 1;
|
|
195
239
|
}
|
|
196
240
|
if (cmd === 'test') {
|
|
@@ -230,7 +274,7 @@ function showScreens(build, warn) {
|
|
|
230
274
|
function runCompiledTypeScript(cmd, build, warn, say) {
|
|
231
275
|
if (cmd === 'run' && !build.entryModule) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
|
|
232
276
|
if (cmd === 'test' && !build.results.reduce((n, r) => n + r.info.tests.length, 0)) { say('thunder test: no Test blocks found. Write one: Test "what it checks": then Expect … lines.'); return 0; }
|
|
233
|
-
const r = runTypeScript(build.outDir, cmd === 'run' ? `${build.entryModule}.ts` : 'run_tests.ts', { cwd: build.base, stdio: 'inherit' });
|
|
277
|
+
const r = runTypeScript(build.outDir, cmd === 'run' ? `${build.entryModule}.ts` : 'run_tests.ts', { cwd: build.base, stdio: 'inherit', serving: cmd === 'run' && answersRequests(build) });
|
|
234
278
|
if (r.error && typeof r.error === 'string') { warn(`thunder ${cmd}: ${r.error}`); return 2; }
|
|
235
279
|
return r.status ?? 1;
|
|
236
280
|
}
|
|
@@ -238,7 +282,7 @@ function runCompiledTypeScript(cmd, build, warn, say) {
|
|
|
238
282
|
/** thunder run --record <file>: run on the Thunder engine and save a step-by-step recording (the Time Machine). */
|
|
239
283
|
function recordRun(build, file, cwd, warn) {
|
|
240
284
|
if (!build.entry) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
|
|
241
|
-
const r = recordedRun({ entry: build.entry, cwd: build.base, readText: (p, dir) => readFileSync(resolve(dir, p), 'utf8') });
|
|
285
|
+
const r = recordedRun({ entry: build.entry, cwd: build.base, readText: (p, dir) => readFileSync(resolve(dir, p), 'utf8'), store: nodeStore(build.base) });
|
|
242
286
|
if (r.refused) { warn(`thunder run: ${r.stderr.trim()}`); return 2; }
|
|
243
287
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
244
288
|
if (r.stderr) process.stderr.write(r.stderr);
|
|
@@ -293,6 +337,14 @@ const readdirDeep = (root, dir) => { try { return readdirSync(join(root, dir)).f
|
|
|
293
337
|
function runOnEngine(cmd, build, warn, say) {
|
|
294
338
|
if (cmd === 'run') {
|
|
295
339
|
if (!build.entry) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
|
|
340
|
+
if (answersRequests(build)) {
|
|
341
|
+
// A program with endpoints keeps answering requests until stopped; it reports here only if it can't start.
|
|
342
|
+
const r = serveWithEngine({ entry: build.entry, cwd: build.base });
|
|
343
|
+
if (!r) return 0; // answering requests now; the process stays alive until Ctrl+C
|
|
344
|
+
if (r.stdout) process.stdout.write(r.stdout);
|
|
345
|
+
if (r.stderr) process.stderr.write(r.stderr);
|
|
346
|
+
return r.status;
|
|
347
|
+
}
|
|
296
348
|
const r = runWithEngine({ entry: build.entry, cwd: build.base });
|
|
297
349
|
if (r.stdout) process.stdout.write(r.stdout);
|
|
298
350
|
if (r.stderr) process.stderr.write(r.stderr.startsWith('This program uses') ? `thunder run: ${r.stderr}` : r.stderr);
|
package/src/core/csharp-run.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import { writeFileSync, mkdirSync, readFileSync, existsSync, rmSync } from 'node
|
|
|
8
8
|
import { join } from 'node:path';
|
|
9
9
|
import { spawnSync } from 'node:child_process';
|
|
10
10
|
import { toCSharp, pythonOnlyUses, classOf, cs } from './target-csharp.mjs';
|
|
11
|
-
import { npmRefusals } from './target-typescript.mjs';
|
|
11
|
+
import { npmRefusals, storeRefusals, httpRefusals } from './target-typescript.mjs';
|
|
12
12
|
import { diag } from './diagnostics.mjs';
|
|
13
13
|
|
|
14
14
|
export const CS_RUNTIME = readFileSync(new URL('./ThunderRuntime.cs', import.meta.url), 'utf8');
|
|
@@ -16,7 +16,7 @@ export const ASSEMBLY = 'ThunderProgram';
|
|
|
16
16
|
|
|
17
17
|
/** TC405 for every Use in a file: Python modules exist only for the Python target. */
|
|
18
18
|
export function csharpDiagnostics(result) {
|
|
19
|
-
return [...npmRefusals(result.info, 'C#', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
19
|
+
return [...npmRefusals(result.info, 'C#', diag), ...storeRefusals(result.info, 'C#', diag), ...httpRefusals(result.info, 'C#', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
20
20
|
`"${u.module}" is a Python module, and this program is compiled to C#, which cannot use it.`,
|
|
21
21
|
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
|
|
22
22
|
}
|
package/src/core/diagnostics.mjs
CHANGED
|
@@ -24,6 +24,7 @@ export const CODES = {
|
|
|
24
24
|
TC117: 'Lines like "name: value" with no record or function call to give them to',
|
|
25
25
|
TC118: 'A line inside a Screen is not something a screen can show',
|
|
26
26
|
TC119: '"Receive" or "Remember" is not at the top of a Screen',
|
|
27
|
+
TC120: 'A hole (?, ?number) in a draft: the program does not run until it is filled in',
|
|
27
28
|
TC201: 'Unknown name',
|
|
28
29
|
TC202: 'A name uses a word that belongs to Thunder',
|
|
29
30
|
TC203: 'A name is defined twice',
|
|
@@ -38,6 +39,11 @@ export const CODES = {
|
|
|
38
39
|
TC212: 'Unknown screen',
|
|
39
40
|
TC213: 'An input of a screen is changed',
|
|
40
41
|
TC214: 'A screen is given an input it does not have, or is missing one it needs',
|
|
42
|
+
TC215: '"Depending on" leaves out an alternative of the data type (and has no "Otherwise")',
|
|
43
|
+
TC216: 'A field only some alternatives have, read where the alternative is not known',
|
|
44
|
+
TC217: 'An alternative a data type does not have, or a value built without saying which alternative it is',
|
|
45
|
+
TC218: 'An HTTP status (Give … with status, Stop … and status) outside an endpoint',
|
|
46
|
+
TC219: 'Inside where or sorted by, a name that is both a field of each item and a value of yours (the field wins, so your value is hidden)',
|
|
41
47
|
TC301: 'Money and a plain number are mixed',
|
|
42
48
|
TC302: 'Values of different kinds are compared',
|
|
43
49
|
TC303: 'A name changes kind',
|
|
@@ -53,6 +59,8 @@ export const CODES = {
|
|
|
53
59
|
TC407: 'A step that cannot run when a button is pressed',
|
|
54
60
|
TC408: 'An npm package ("Use … from npm") can be used only when compiling to TypeScript',
|
|
55
61
|
TC409: 'A .NET library ("Use … from .NET" or "from NuGet") can be used only when compiling to C#',
|
|
62
|
+
TC410: 'A stored list ("Store … as a list of …") runs on Python, TypeScript, Go, and the Thunder engine only, for now',
|
|
63
|
+
TC411: 'An endpoint or a call to another service in a program compiled to a target without HTTP yet',
|
|
56
64
|
TC501: 'Divided by zero (runtime)',
|
|
57
65
|
TC502: 'Nothing used where a value was needed (runtime)',
|
|
58
66
|
TC503: 'A field or entry is missing (runtime)',
|
|
@@ -62,6 +70,7 @@ export const CODES = {
|
|
|
62
70
|
TC507: 'The program stopped with a message (runtime)',
|
|
63
71
|
TC508: 'Library code used through "Use" failed (runtime)',
|
|
64
72
|
TC509: 'A value could not be converted (runtime)',
|
|
73
|
+
TC510: 'A call to another service failed: it could not be reached, or it answered with a problem (runtime)',
|
|
65
74
|
};
|
|
66
75
|
|
|
67
76
|
export class CoreError extends Error {
|
package/src/core/engine-core.mjs
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
attrErr, strMethod, splitLines, pySplit, pyStrip, jsonParse, jsonText, isInt, isNumber,
|
|
19
19
|
} from './engine-values.mjs';
|
|
20
20
|
import * as V from './engine-values.mjs';
|
|
21
|
+
import { storeFromText, storeToText, storeFile, recordFrom, dataJson, unreachableReason } from './store-format.mjs';
|
|
21
22
|
import { shownText, copyValue, typedNumber, problemText } from './screen-values.mjs';
|
|
22
23
|
import { percentDecimal } from './target-python.mjs';
|
|
23
24
|
import { firstLine } from './target-typescript.mjs';
|
|
@@ -32,6 +33,8 @@ class Return { constructor(v) { this.v = v; } }
|
|
|
32
33
|
// run is repeated on the deep-stack thread, so any RangeError (or a regular expression's "Stack overflow") counts.
|
|
33
34
|
const nativeOverflow = (e) => { try { return e instanceof RangeError || (e instanceof SyntaxError && e.message.endsWith('Stack overflow')); } catch { return true; } };
|
|
34
35
|
class NeedsDeeperStack extends Error {}
|
|
36
|
+
/** A call ran out of its steps (engineForCalls): it may never finish, so its answer is unknown, not wrong. */
|
|
37
|
+
export class OutOfSteps extends Error {}
|
|
35
38
|
|
|
36
39
|
const MAX_FRAMES = V.MAX_FRAMES;
|
|
37
40
|
const CONTAINER_KINDS = new Set(['if', 'each', 'range', 'times', 'while', 'tryFail']); // statements with steps inside
|
|
@@ -61,7 +64,14 @@ class Engine {
|
|
|
61
64
|
// readText(path, cwd): the text of a file the program reads, or throws with .code 'ENOENT' / 'EISDIR'. Without it
|
|
62
65
|
// (a browser), reading a file is reported as a missing file.
|
|
63
66
|
// record: keep a step-by-step recording of the run (the Thunder Time Machine; see recordedRun below).
|
|
64
|
-
|
|
67
|
+
// http(method, url, bodyText) -> { status, text } | { error }: calls another service and waits for the answer.
|
|
68
|
+
// Without it (a browser), "the answer from …" says it can't run here.
|
|
69
|
+
constructor({ cwd = '.', deeper = false, readText = null, record = false, store = null, http = null } = {}) {
|
|
70
|
+
this.http = http;
|
|
71
|
+
this.answeredStatus = null; // Give … with status 201, read by the server after an endpoint answers
|
|
72
|
+
// store: { load(file) -> text | null, save(file, text) } for stored lists (Store … as a list of …). Without it,
|
|
73
|
+
// stored lists start empty and are not saved (the browser, and every test).
|
|
74
|
+
this.dataFiles = store;
|
|
65
75
|
this.cwd = cwd;
|
|
66
76
|
this.rec = record ? { steps: [], truncated: false } : null;
|
|
67
77
|
this.readText = readText;
|
|
@@ -70,6 +80,7 @@ class Engine {
|
|
|
70
80
|
this.deeper = deeper;
|
|
71
81
|
this.frames = [];
|
|
72
82
|
this.out = [];
|
|
83
|
+
this.budget = null; // steps left before a call is stopped (engineForCalls); null: no limit
|
|
73
84
|
}
|
|
74
85
|
|
|
75
86
|
// ── loading ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
@@ -80,6 +91,9 @@ class Engine {
|
|
|
80
91
|
for (const m of imports) for (const [k, v] of m.globals) mod.globals.set(k, v);
|
|
81
92
|
for (const r of result.info.records.filter(own)) mod.globals.set(r.py, this.recordClass(r, mod));
|
|
82
93
|
for (const f of result.info.funcs.filter(own)) mod.globals.set(f.py, { isFunc: true, f, mod });
|
|
94
|
+
// Stored lists: empty until the program starts (fillStores), saved when it finishes well (saveStores).
|
|
95
|
+
mod.stores = (result.info.stores ?? []).filter(own).map((s) => { const list = []; mod.globals.set(s.py, list); return { s, list, cls: mod.globals.get(s.record.py) }; });
|
|
96
|
+
for (const m of imports) for (const st of m.stores ?? []) mod.stores.push(st);
|
|
83
97
|
const consts = result.info.consts.filter(own);
|
|
84
98
|
if (consts.length) {
|
|
85
99
|
const frame = { file: mod.file, line: 0 };
|
|
@@ -94,7 +108,8 @@ class Engine {
|
|
|
94
108
|
recordClass(r, mod) {
|
|
95
109
|
const rules = new Map();
|
|
96
110
|
for (const rule of r.rulesToCheck ?? []) { const f = r.fieldMap.get(rule.subject); (rules.get(f.py) ?? rules.set(f.py, []).get(f.py)).push(rule); }
|
|
97
|
-
|
|
111
|
+
const alts = r.alts ? Object.fromEntries(r.alts.map((a) => [a.name, a.fields.map((f) => f.py)])) : null;
|
|
112
|
+
return { isRecord: true, py: r.py, fields: r.fields.map((f) => ({ py: f.py, type: f.type })), rules, mod, alts };
|
|
98
113
|
}
|
|
99
114
|
|
|
100
115
|
// ── frames, lines, errors ───────────────────────────────────────────────────────────────────────────────────
|
|
@@ -103,7 +118,7 @@ class Engine {
|
|
|
103
118
|
this.frames.push(frame);
|
|
104
119
|
try { return fn(); }
|
|
105
120
|
catch (e) {
|
|
106
|
-
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
121
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
|
|
107
122
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
108
123
|
const err = asPyErr(e);
|
|
109
124
|
if (!err.where) err.where = this.frames.map((f) => ({ file: f.file, line: f.line }));
|
|
@@ -130,7 +145,7 @@ class Engine {
|
|
|
130
145
|
const locals = new Map();
|
|
131
146
|
const env = { mod, locals, frame };
|
|
132
147
|
f.params.forEach((p, i) => {
|
|
133
|
-
let v = i < args.length ? args[i] : (p.dflt ? (p.dflt.k === 'name' ? NOT_GIVEN : this.x(p.dflt, env)) : undefined);
|
|
148
|
+
let v = i < args.length && args[i] !== NOT_GIVEN ? args[i] : (p.dflt ? (p.dflt.k === 'name' ? NOT_GIVEN : this.x(p.dflt, env)) : undefined);
|
|
134
149
|
if (v === undefined) throw TypeErr(`${f.py}() missing 1 required positional argument: '${p.py}'`);
|
|
135
150
|
locals.set(p.py, v);
|
|
136
151
|
});
|
|
@@ -142,6 +157,34 @@ class Engine {
|
|
|
142
157
|
});
|
|
143
158
|
}
|
|
144
159
|
|
|
160
|
+
/** the answer from GET "…" [with …] [as Rate]: the answer's text, or records read from it. */
|
|
161
|
+
httpCall(e, env) {
|
|
162
|
+
const url = this.x(e.url, env);
|
|
163
|
+
const body = e.body ? dataJson(this.x(e.body, env)) : null;
|
|
164
|
+
if (!this.http) throw V.CallFailed(`${e.method} ${pyStr(url)} can't be called here: calls to other services run with the thunder command, not in the browser.`);
|
|
165
|
+
const out = this.http(e.method, url, body);
|
|
166
|
+
if (out.error) throw V.CallFailed(`${e.method} ${url} could not be reached (${unreachableReason(out)}).`);
|
|
167
|
+
if (out.status < 200 || out.status > 299) throw V.CallFailed(`${e.method} ${url} answered ${out.status}: ${out.text.trim().slice(0, 300)}`);
|
|
168
|
+
if (!e.record) return out.text;
|
|
169
|
+
const where = `The answer from ${e.method} ${url}`;
|
|
170
|
+
let data;
|
|
171
|
+
try { data = JSON.parse(out.text); } catch { throw V.ConversionFailed(`${where} is not JSON Thunder can read.`); }
|
|
172
|
+
const cls = env.mod.globals.get(e.record.py);
|
|
173
|
+
const make = (given) => this.newRecord(cls, given);
|
|
174
|
+
if (e.as.k === 'list') {
|
|
175
|
+
if (!Array.isArray(data)) throw V.ConversionFailed(`${where} should be a list, written [ … ].`);
|
|
176
|
+
return data.map((row, i) => recordFrom(row, cls, `${where}, item ${i + 1}`, make, 'it has'));
|
|
177
|
+
}
|
|
178
|
+
return recordFrom(data, cls, where, make, 'it has');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** An endpoint answering one request: its value and status, or the error it stopped with. Output so far is kept. */
|
|
182
|
+
answer(mod, f, args) {
|
|
183
|
+
this.answeredStatus = null;
|
|
184
|
+
const value = this.call(mod.globals.get(f.py), args);
|
|
185
|
+
return { value, status: this.answeredStatus ?? 200 };
|
|
186
|
+
}
|
|
187
|
+
|
|
145
188
|
never(rule, value, env) { V.never(this.x(rule.rule.cond, env, { subject: value }), rule.text, rule.line, value); }
|
|
146
189
|
|
|
147
190
|
newRecord(cls, given) { return V.newRecordWith((o, k, v) => this.setAttr(o, k, v), cls, given); }
|
|
@@ -190,6 +233,7 @@ class Engine {
|
|
|
190
233
|
}
|
|
191
234
|
|
|
192
235
|
stmt(s, env) {
|
|
236
|
+
if (this.budget !== null && --this.budget < 0) throw new OutOfSteps();
|
|
193
237
|
if (this.rec) return this.recordStep(s, env);
|
|
194
238
|
return this.runStmt(s, env);
|
|
195
239
|
}
|
|
@@ -248,8 +292,8 @@ class Engine {
|
|
|
248
292
|
this.storeAt(t, v, env);
|
|
249
293
|
return;
|
|
250
294
|
}
|
|
251
|
-
case 'give':
|
|
252
|
-
case 'stop': { const v = this.x(s.e, env);
|
|
295
|
+
case 'give': { const v = s.e.k === 'nothing' ? null : this.x(s.e, env); if (s.status != null) this.answeredStatus = s.status; throw new Return(v); }
|
|
296
|
+
case 'stop': { const v = this.x(s.e, env); const err = Stop(s.e.type?.k === 'text' ? pyStr(v) : show(v)); if (s.status != null) err.status = s.status; throw err; }
|
|
253
297
|
case 'if':
|
|
254
298
|
for (const b of s.branches) {
|
|
255
299
|
fr.line = b.line;
|
|
@@ -326,7 +370,7 @@ class Engine {
|
|
|
326
370
|
case 'tryFail':
|
|
327
371
|
try { this.stmt(s.stmt, env); }
|
|
328
372
|
catch (e) {
|
|
329
|
-
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
373
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
|
|
330
374
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
331
375
|
const err = asPyErr(e);
|
|
332
376
|
fr.line = L;
|
|
@@ -345,6 +389,13 @@ class Engine {
|
|
|
345
389
|
const isName = s.target.k === 'name';
|
|
346
390
|
const target = this.x(s.target, env);
|
|
347
391
|
const py = isName ? s.target.ref?.py ?? 'unknown' : null;
|
|
392
|
+
if (s.guard) {
|
|
393
|
+
// A watched list: change a copy, then keep it through the checked assignment (the old list stays if refused).
|
|
394
|
+
const copy = V.copyList(target);
|
|
395
|
+
if (s.k === 'add') V.appendTo(copy, v); else this.removeFrom(copy, v);
|
|
396
|
+
if (isName) this.assign(s, py, copy, env); else this.store(s.target, copy, env);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
348
399
|
if (s.targetKind === 'list') { if (s.k === 'add') { if (!Array.isArray(target)) throw attrErr(target, 'append'); target.push(v); } else this.removeFrom(target, v); }
|
|
349
400
|
else if (s.targetKind === 'map') this.removeFrom(target, v);
|
|
350
401
|
else if (s.targetKind === 'number') {
|
|
@@ -364,15 +415,18 @@ class Engine {
|
|
|
364
415
|
if (s.mode === 'fail') {
|
|
365
416
|
const msg = s.msg ? this.x(s.msg, env) : null;
|
|
366
417
|
// A JavaScript stack overflow is not the program failing: let it reach the deeper-stack retry.
|
|
418
|
+
let outOfSteps = null; // running out of steps is not the failure the example expects
|
|
367
419
|
V.expectFailure(() => {
|
|
368
420
|
try { this.x(s.e, env); }
|
|
369
421
|
catch (e) {
|
|
370
422
|
if (e instanceof Return) return;
|
|
371
423
|
if (e instanceof NeedsDeeperStack) throw e;
|
|
372
424
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
425
|
+
if (e instanceof OutOfSteps) outOfSteps = e;
|
|
373
426
|
throw e;
|
|
374
427
|
}
|
|
375
428
|
}, text, msg);
|
|
429
|
+
if (outOfSteps) throw outOfSteps;
|
|
376
430
|
return;
|
|
377
431
|
}
|
|
378
432
|
const actual = this.x(s.e, env);
|
|
@@ -428,6 +482,7 @@ class Engine {
|
|
|
428
482
|
case 'bool': return !!e.v;
|
|
429
483
|
case 'nothing': case 'hole': return null;
|
|
430
484
|
case 'paren': return sub2(e.e);
|
|
485
|
+
case 'httpCall': return this.httpCall(e, env);
|
|
431
486
|
case 'today': return PyDate.today();
|
|
432
487
|
case 'date': { const d = PyDate.parse(e.text); if (!d) throw new PyErr('ValueError', `Invalid isoformat string: '${e.text}'`); return d; }
|
|
433
488
|
case 'str': return this.str(e, env, ctx);
|
|
@@ -542,12 +597,33 @@ class Engine {
|
|
|
542
597
|
// ── running a program or its tests ──────────────────────────────────────────────────────────────────────────
|
|
543
598
|
runMain(mod) {
|
|
544
599
|
const main = mod.r.program.main ?? [];
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
600
|
+
this.fillStores(mod);
|
|
601
|
+
if (main.length) {
|
|
602
|
+
const frame = { file: mod.file, line: 0 };
|
|
603
|
+
this.withFrame(frame, () => {
|
|
604
|
+
const env = { mod, locals: new Map(), frame };
|
|
605
|
+
try { this.block(main, env); } catch (e) { if (e instanceof Return) return; throw e; }
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
// Only a program that finished well is saved: one that stopped with a problem changes nothing.
|
|
609
|
+
this.saveStores(mod);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** Each stored list, filled from its file (data/<name>.json); a missing file is an empty list. */
|
|
613
|
+
fillStores(mod) {
|
|
614
|
+
if (!this.dataFiles) return;
|
|
615
|
+
for (const st of mod.stores ?? []) {
|
|
616
|
+
const file = storeFile(st.s);
|
|
617
|
+
const text = this.dataFiles.load(file);
|
|
618
|
+
if (text == null) continue;
|
|
619
|
+
const frame = { file: mod.file, line: st.s.line };
|
|
620
|
+
this.withFrame(frame, () => { st.list.splice(0, st.list.length, ...storeFromText(text, st.cls, file, (given) => this.newRecord(st.cls, given))); });
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
saveStores(mod) {
|
|
625
|
+
if (!this.dataFiles) return;
|
|
626
|
+
for (const st of mod.stores ?? []) this.dataFiles.save(storeFile(st.s), storeToText(st.list, st.cls));
|
|
551
627
|
}
|
|
552
628
|
|
|
553
629
|
runTest(mod, t) {
|
|
@@ -574,12 +650,12 @@ function notCompiled(results) {
|
|
|
574
650
|
}
|
|
575
651
|
|
|
576
652
|
/** The same, on the calling thread (its stack allows only a few hundred nested calls). */
|
|
577
|
-
export function runInProcess({ entry, cwd, deeper = false, readText = null } = {}) {
|
|
653
|
+
export function runInProcess({ entry, cwd, deeper = false, readText = null, store = null, http = null } = {}) {
|
|
578
654
|
const broken = notCompiled([entry]);
|
|
579
655
|
if (broken) return broken;
|
|
580
656
|
const uses = pythonModulesUsed([entry]);
|
|
581
657
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
582
|
-
const eng = new Engine({ cwd, deeper, readText });
|
|
658
|
+
const eng = new Engine({ cwd, deeper, readText, store, http });
|
|
583
659
|
let stderr = '', status = 0;
|
|
584
660
|
try {
|
|
585
661
|
const mod = eng.load(entry);
|
|
@@ -592,16 +668,37 @@ export function runInProcess({ entry, cwd, deeper = false, readText = null } = {
|
|
|
592
668
|
return { status, stdout: eng.out.join(''), stderr };
|
|
593
669
|
}
|
|
594
670
|
|
|
671
|
+
/**
|
|
672
|
+
* A program loaded and its main part run, ready to answer requests (thunder run --engine thunder with endpoints).
|
|
673
|
+
* Gives back { eng, mod, stdout } or, when it can't start, { status, stdout, stderr }.
|
|
674
|
+
*/
|
|
675
|
+
export function engineForServing({ entry, cwd, readText = null, store = null, http = null } = {}) {
|
|
676
|
+
const broken = notCompiled([entry]);
|
|
677
|
+
if (broken) return broken;
|
|
678
|
+
const uses = pythonModulesUsed([entry]);
|
|
679
|
+
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
680
|
+
const eng = new Engine({ cwd, readText, store, http });
|
|
681
|
+
try {
|
|
682
|
+
const mod = eng.load(entry);
|
|
683
|
+
eng.runMain(mod);
|
|
684
|
+
const stdout = eng.out.join('');
|
|
685
|
+
eng.out = [];
|
|
686
|
+
return { eng, mod, stdout };
|
|
687
|
+
} catch (e) {
|
|
688
|
+
return { status: 1, stdout: eng.out.join(''), stderr: `${eng.describeError(asPyErr(e))}\n` };
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
595
692
|
/**
|
|
596
693
|
* Run a program and keep a step-by-step recording of it (the Thunder Time Machine, `thunder run --record`).
|
|
597
694
|
* Gives back { status, stdout, stderr, steps, truncated }. Like runInProcess, on the calling thread.
|
|
598
695
|
*/
|
|
599
|
-
export function recordedRun({ entry, cwd, readText = null } = {}) {
|
|
696
|
+
export function recordedRun({ entry, cwd, readText = null, store = null } = {}) {
|
|
600
697
|
const broken = notCompiled([entry]);
|
|
601
698
|
if (broken) return broken;
|
|
602
699
|
const uses = pythonModulesUsed([entry]);
|
|
603
700
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses, steps: [] };
|
|
604
|
-
const eng = new Engine({ cwd, readText, record: true });
|
|
701
|
+
const eng = new Engine({ cwd, readText, record: true, store });
|
|
605
702
|
let stderr = '', status = 0;
|
|
606
703
|
try {
|
|
607
704
|
const mod = eng.load(entry);
|
|
@@ -612,13 +709,45 @@ export function recordedRun({ entry, cwd, readText = null } = {}) {
|
|
|
612
709
|
return { status, stdout: eng.out.join(''), stderr, steps: eng.rec.steps, truncated: eng.rec.truncated };
|
|
613
710
|
}
|
|
614
711
|
|
|
712
|
+
/**
|
|
713
|
+
* Compiled files loaded together, for a tool that calls one function, endpoint, or test at a time (the behaviour
|
|
714
|
+
* comparison in core-changes.mjs). Tests see the src/ files before them, as in thunder test. Nothing is run at load
|
|
715
|
+
* apart from kept values; stored lists start empty and are never saved; calls to other services and file reads are
|
|
716
|
+
* refused. Each call() gets `steps` statements, then stops with OutOfSteps.
|
|
717
|
+
* Gives back { mods, call(mod, f, args), endpoint(mod, f, args), test(mod, t), record(cls, row) } or { failed }.
|
|
718
|
+
*/
|
|
719
|
+
export function engineForCalls({ results, steps = 20000 } = {}) {
|
|
720
|
+
const broken = notCompiled(results);
|
|
721
|
+
if (broken) return { failed: broken.stderr };
|
|
722
|
+
const uses = pythonModulesUsed(results);
|
|
723
|
+
if (uses.length) return { failed: refusalText(uses) };
|
|
724
|
+
const eng = new Engine({});
|
|
725
|
+
const mods = [], srcMods = [];
|
|
726
|
+
try {
|
|
727
|
+
for (const r of results) {
|
|
728
|
+
const mod = eng.load(r, r.kind === 'test' ? srcMods : []);
|
|
729
|
+
if (r.kind !== 'test') srcMods.push(mod);
|
|
730
|
+
mods.push(mod);
|
|
731
|
+
}
|
|
732
|
+
} catch (e) { return { failed: eng.describeError(asPyErr(e)) }; }
|
|
733
|
+
const fresh = (fn) => { eng.budget = steps; eng.frames = []; eng.out = []; try { return fn(); } finally { eng.budget = null; } };
|
|
734
|
+
return {
|
|
735
|
+
mods,
|
|
736
|
+
eng,
|
|
737
|
+
call: (mod, f, args) => fresh(() => eng.call(mod.globals.get(f.py), args)),
|
|
738
|
+
endpoint: (mod, f, args) => fresh(() => eng.answer(mod, f, args)),
|
|
739
|
+
test: (mod, t) => fresh(() => eng.runTest(mod, t)),
|
|
740
|
+
record: (cls, row) => fresh(() => recordFrom(row, cls, `the ${cls.py}`, (given) => eng.newRecord(cls, given), 'it has')),
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
|
|
615
744
|
/** The same, on the calling thread. */
|
|
616
|
-
export function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
|
|
745
|
+
export function testInProcess({ results, cwd, deeper = false, readText = null, http = null } = {}) {
|
|
617
746
|
const broken = notCompiled(results);
|
|
618
747
|
if (broken) return broken;
|
|
619
748
|
const uses = pythonModulesUsed(results);
|
|
620
749
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
621
|
-
const eng = new Engine({ cwd, deeper, readText });
|
|
750
|
+
const eng = new Engine({ cwd, deeper, readText, http });
|
|
622
751
|
const mods = [];
|
|
623
752
|
const srcMods = [];
|
|
624
753
|
for (const r of results) {
|
|
@@ -23,6 +23,7 @@ export const KindMismatch = (m) => new ThunderErr('TC506', m, 'TypeError'); // a
|
|
|
23
23
|
export const ConversionFailed = (m) => new ThunderErr('TC509', m, 'ValueError');
|
|
24
24
|
export const MissingValue = (m) => new ThunderErr('TC503', m, 'LookupError');
|
|
25
25
|
export const DividedByZero = (m) => new ThunderErr('TC501', m, 'ZeroDivisionError');
|
|
26
|
+
export const CallFailed = (m) => new ThunderErr('TC510', m, 'CallFailed'); // a call to another service (HTTP)
|
|
26
27
|
|
|
27
28
|
/** An error Python itself raises (TypeError, KeyError, ...), with Python's own message. */
|
|
28
29
|
export class PyErr extends Error {
|
|
@@ -825,6 +826,8 @@ export function setFieldWith(setAttr, obj, key, value) {
|
|
|
825
826
|
}
|
|
826
827
|
|
|
827
828
|
export function addTo(target, value) { if (Array.isArray(target)) { target.push(value); return target; } return add(target, value); }
|
|
829
|
+
/** A new list with the same items (a watched list is changed on a copy, so a refused change leaves it as it was). */
|
|
830
|
+
export function copyList(target) { if (!Array.isArray(target)) throw attrErr(target, 'append'); return [...target]; }
|
|
828
831
|
export function appendTo(target, value) { if (!Array.isArray(target)) throw attrErr(target, 'append'); target.push(value); }
|
|
829
832
|
export function removeFrom(target, value) {
|
|
830
833
|
if (target instanceof PyDict) { if (!target.has(value)) throw MissingValue(`There is no entry for ${show(value)} to remove.`); target.delete(value); return; }
|