@skillstech/thunderlang 1.1.0 → 1.3.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 +212 -0
- package/README.md +4 -1
- package/dist/core.cjs +2080 -278
- package/dist/index.cjs +12742 -10943
- package/dist/learn.cjs +12976 -3598
- package/package.json +2 -2
- package/src/cli-home.mjs +242 -0
- package/src/cli.mjs +135 -41
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +208 -17
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -0
- package/src/core/engine-core.mjs +855 -0
- package/src/core/engine-values.mjs +1054 -0
- package/src/core/engine-worker.mjs +15 -0
- package/src/core/engine.mjs +63 -0
- package/src/core/format.mjs +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +3 -1
- package/src/core/java/thunder/T.java +6 -0
- package/src/core/java/thunder/ThunderRuntime.java +1374 -0
- package/src/core/java-run.mjs +89 -0
- package/src/core/parser.mjs +331 -5
- package/src/core/project.mjs +43 -8
- package/src/core/react-run.mjs +96 -0
- package/src/core/runtime-go/thunder_runtime.go +3038 -0
- package/src/core/runtime-react.mjs +133 -0
- package/src/core/runtime-typescript.mjs +119 -0
- package/src/core/rust/thunder_runtime.rs +1645 -0
- package/src/core/rust-run.mjs +192 -0
- package/src/core/screen-values.mjs +30 -0
- package/src/core/target-csharp.mjs +484 -0
- package/src/core/target-go.mjs +555 -0
- package/src/core/target-java.mjs +587 -0
- package/src/core/target-python.mjs +2 -1
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +466 -0
- package/src/core/typescript-run.mjs +114 -0
- package/src/core.d.ts +18 -0
- package/src/core.mjs +1 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +30 -0
- package/src/learn-lessons.mjs +245 -1
- package/src/learn.d.mts +8 -0
- package/src/learn.mjs +40 -4
- package/src/libraries.mjs +10 -3
- package/src/model.mjs +50 -8
- package/src/read-level.mjs +192 -0
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +28 -5
- package/src/replay-cli.mjs +123 -0
- package/src/say-less.mjs +152 -11
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +430 -19
- package/src/term.mjs +132 -0
- package/src/try-cli.mjs +225 -0
- package/src/why-cli.mjs +17 -7
- package/src/why.d.mts +17 -7
- package/src/why.mjs +114 -33
|
@@ -0,0 +1,855 @@
|
|
|
1
|
+
// The Thunder engine's core: runs Thunder Core directly, with no Python and no Node APIs, so it also runs in a
|
|
2
|
+
// browser (the tutorial runs each lesson's program with it). engine.mjs adds the Node parts: reading files from
|
|
3
|
+
// disk and a worker thread with a deep stack. (thunder run --engine thunder)
|
|
4
|
+
//
|
|
5
|
+
// It runs the SAME checked program the Python target compiles (compileCore -> program + info), so there is one
|
|
6
|
+
// meaning of Thunder, not two. Its behavior is the Python target's behavior: every statement does what the line
|
|
7
|
+
// target-python.mjs writes for it does, and every helper does what thunder_runtime.py does (engine-values.mjs).
|
|
8
|
+
// compiler/test/core-engine.test.mjs runs every Core test program on both engines and compares the output,
|
|
9
|
+
// errors included. A difference is a bug in one of them.
|
|
10
|
+
//
|
|
11
|
+
// A program that uses a Python module ("Use csv as csv") is not run here: Thunder never imitates a library.
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
Dec, Money, PyDate, PyDict, RecordVal, Tuple, NOT_GIVEN, ThunderErr, PyErr, TypeErr,
|
|
15
|
+
Stop, RuleBroken, ExpectationFailed, KindMismatch, ConversionFailed, MissingValue,
|
|
16
|
+
explain, codeOf, asPyErr, describe, show, pyStr, truthy, yesNo, toDec,
|
|
17
|
+
pyLen, pyIter, pyList, add, sub, mul, neg, intMod, divide, modulo, roundTo, eq, compare, contains, pySort,
|
|
18
|
+
attrErr, strMethod, splitLines, pySplit, pyStrip, jsonParse, jsonText, isInt, isNumber,
|
|
19
|
+
} from './engine-values.mjs';
|
|
20
|
+
import * as V from './engine-values.mjs';
|
|
21
|
+
import { shownText, copyValue, typedNumber, problemText } from './screen-values.mjs';
|
|
22
|
+
import { percentDecimal } from './target-python.mjs';
|
|
23
|
+
import { firstLine } from './target-typescript.mjs';
|
|
24
|
+
|
|
25
|
+
export const ENGINES = ['python', 'thunder'];
|
|
26
|
+
|
|
27
|
+
/** Thrown by Give: carries the value back to the call. */
|
|
28
|
+
class Return { constructor(v) { this.v = v; } }
|
|
29
|
+
|
|
30
|
+
/** JavaScript ran out of stack before Thunder's own limit: the run is retried on a thread with a deeper stack. */
|
|
31
|
+
// Kept cheap on purpose: near the limit even a regular expression can run out of stack. A false alarm only means the
|
|
32
|
+
// run is repeated on the deep-stack thread, so any RangeError (or a regular expression's "Stack overflow") counts.
|
|
33
|
+
const nativeOverflow = (e) => { try { return e instanceof RangeError || (e instanceof SyntaxError && e.message.endsWith('Stack overflow')); } catch { return true; } };
|
|
34
|
+
class NeedsDeeperStack extends Error {}
|
|
35
|
+
|
|
36
|
+
const MAX_FRAMES = V.MAX_FRAMES;
|
|
37
|
+
const CONTAINER_KINDS = new Set(['if', 'each', 'range', 'times', 'while', 'tryFail']); // statements with steps inside
|
|
38
|
+
const MAX_RECORDED = 20000; // a recording stops growing here (and says so); the program still runs to the end
|
|
39
|
+
|
|
40
|
+
/** The Python modules a program uses (Use), which this engine does not run. */
|
|
41
|
+
export function pythonModulesUsed(results) {
|
|
42
|
+
const out = [];
|
|
43
|
+
for (const r of results) for (const m of r.info.modules) if (!r.info.imported?.has(m)) out.push({ file: r.file, module: m.module, name: m.text ?? m.name, line: m.line });
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The message for a program the engine will not run. */
|
|
48
|
+
export function refusalText(uses) {
|
|
49
|
+
const u = uses[0];
|
|
50
|
+
const more = uses.length > 1 ? ` (and ${uses.length - 1} more)` : '';
|
|
51
|
+
return `This program uses the Python module "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it with Python: leave out --engine thunder.`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
class Module {
|
|
55
|
+
constructor(result) { this.r = result; this.file = result.file; this.globals = new Map(); }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
class Engine {
|
|
59
|
+
// readText(path, cwd): the text of a file the program reads, or throws with .code 'ENOENT' / 'EISDIR'. Without it
|
|
60
|
+
// (a browser), reading a file is reported as a missing file.
|
|
61
|
+
// record: keep a step-by-step recording of the run (the Thunder Time Machine; see recordedRun below).
|
|
62
|
+
constructor({ cwd = '.', deeper = false, readText = null, record = false } = {}) {
|
|
63
|
+
this.cwd = cwd;
|
|
64
|
+
this.rec = record ? { steps: [], truncated: false } : null;
|
|
65
|
+
this.readText = readText;
|
|
66
|
+
// deeper: if JavaScript's own stack runs out, stop and say so (NeedsDeeperStack) instead of reporting it as the
|
|
67
|
+
// program's error, so the caller can run it again where the stack is deep enough.
|
|
68
|
+
this.deeper = deeper;
|
|
69
|
+
this.frames = [];
|
|
70
|
+
this.out = [];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ── loading ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
74
|
+
load(result, imports = []) {
|
|
75
|
+
const mod = new Module(result);
|
|
76
|
+
const own = (s) => !result.info.imported?.has(s);
|
|
77
|
+
// from <src module> import *: everything the src module defines (functions, records, kept values).
|
|
78
|
+
for (const m of imports) for (const [k, v] of m.globals) mod.globals.set(k, v);
|
|
79
|
+
for (const r of result.info.records.filter(own)) mod.globals.set(r.py, this.recordClass(r, mod));
|
|
80
|
+
for (const f of result.info.funcs.filter(own)) mod.globals.set(f.py, { isFunc: true, f, mod });
|
|
81
|
+
const consts = result.info.consts.filter(own);
|
|
82
|
+
if (consts.length) {
|
|
83
|
+
const frame = { file: mod.file, line: 0 };
|
|
84
|
+
this.withFrame(frame, () => {
|
|
85
|
+
const env = { mod, locals: mod.globals, frame };
|
|
86
|
+
for (const k of consts) { frame.line = k.line; mod.globals.set(k.py, this.x(k.e, env)); }
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
return mod;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
recordClass(r, mod) {
|
|
93
|
+
const rules = new Map();
|
|
94
|
+
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); }
|
|
95
|
+
return { isRecord: true, py: r.py, fields: r.fields.map((f) => ({ py: f.py, type: f.type })), rules, mod };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ── frames, lines, errors ───────────────────────────────────────────────────────────────────────────────────
|
|
99
|
+
withFrame(frame, fn) {
|
|
100
|
+
if (this.frames.length >= MAX_FRAMES) throw new PyErr('RecursionError', 'maximum recursion depth exceeded');
|
|
101
|
+
this.frames.push(frame);
|
|
102
|
+
try { return fn(); }
|
|
103
|
+
catch (e) {
|
|
104
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
105
|
+
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
106
|
+
const err = asPyErr(e);
|
|
107
|
+
if (!err.where) err.where = this.frames.map((f) => ({ file: f.file, line: f.line }));
|
|
108
|
+
throw err;
|
|
109
|
+
} finally { this.frames.pop(); }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
describeError(e) { return V.describeError(e); }
|
|
113
|
+
|
|
114
|
+
// ── calls ───────────────────────────────────────────────────────────────────────────────────────────────────
|
|
115
|
+
call(fn, args) {
|
|
116
|
+
if (!fn?.isFunc) throw TypeErr(`'${fn === null ? 'NoneType' : typeof fn}' object is not callable`);
|
|
117
|
+
const { f, mod } = fn;
|
|
118
|
+
const frame = { file: mod.file, line: f.line, fn: f.name ?? f.py };
|
|
119
|
+
if (this.frames.length >= MAX_FRAMES) {
|
|
120
|
+
// Python makes the new call's frame, then stops at its first line (a line with no Thunder mark, like the
|
|
121
|
+
// check for a default, leaves the error at the caller's line).
|
|
122
|
+
const err = new PyErr('RecursionError', 'maximum recursion depth exceeded');
|
|
123
|
+
const first = firstLine(f);
|
|
124
|
+
if (first != null) err.where = [...this.frames.map((x) => ({ file: x.file, line: x.line })), { file: mod.file, line: first }];
|
|
125
|
+
throw err;
|
|
126
|
+
}
|
|
127
|
+
return this.withFrame(frame, () => {
|
|
128
|
+
const locals = new Map();
|
|
129
|
+
const env = { mod, locals, frame };
|
|
130
|
+
f.params.forEach((p, i) => {
|
|
131
|
+
let v = i < args.length ? args[i] : (p.dflt ? (p.dflt.k === 'name' ? NOT_GIVEN : this.x(p.dflt, env)) : undefined);
|
|
132
|
+
if (v === undefined) throw TypeErr(`${f.py}() missing 1 required positional argument: '${p.py}'`);
|
|
133
|
+
locals.set(p.py, v);
|
|
134
|
+
});
|
|
135
|
+
for (const p of f.params) if (p.dflt?.k === 'name' && locals.get(p.py) === NOT_GIVEN) { frame.line = p.line; locals.set(p.py, this.x(p.dflt, env)); }
|
|
136
|
+
for (const p of f.params) for (const rule of p.rules ?? []) { frame.line = p.line; this.never(rule, locals.get(p.py), env); }
|
|
137
|
+
try { this.block(f.body, env); }
|
|
138
|
+
catch (e) { if (e instanceof Return) return e.v; throw e; }
|
|
139
|
+
return null;
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
never(rule, value, env) { V.never(this.x(rule.rule.cond, env, { subject: value }), rule.text, rule.line, value); }
|
|
144
|
+
|
|
145
|
+
newRecord(cls, given) { return V.newRecordWith((o, k, v) => this.setAttr(o, k, v), cls, given); }
|
|
146
|
+
|
|
147
|
+
/** obj.name = value (a record checks its Never rules first, as its __setattr__ does). */
|
|
148
|
+
setAttr(obj, name, value) {
|
|
149
|
+
V.setAttrWith((rec) => {
|
|
150
|
+
const env = { mod: rec.cls.mod, locals: new Map(), frame: this.frames[this.frames.length - 1] };
|
|
151
|
+
for (const rule of rec.cls.rules.get(name) ?? []) this.never(rule, value, env);
|
|
152
|
+
}, obj, name, value);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
getAttr(obj, name) { return V.getAttr(obj, name); }
|
|
156
|
+
|
|
157
|
+
// ── statements ──────────────────────────────────────────────────────────────────────────────────────────────
|
|
158
|
+
block(body, env) { for (const s of body) this.stmt(s, env); }
|
|
159
|
+
|
|
160
|
+
lookup(env, py) {
|
|
161
|
+
if (env.locals.has(py)) return env.locals.get(py);
|
|
162
|
+
if (env.mod.globals.has(py)) return env.mod.globals.get(py);
|
|
163
|
+
throw new PyErr('NameError', `name '${py}' is not defined`);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** A name watched by a Never rule: the new value is checked before it is stored. */
|
|
167
|
+
assign(s, py, v, env) {
|
|
168
|
+
for (const rule of s.rules ?? []) this.never(rule, v, env);
|
|
169
|
+
env.locals.set(py, v);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
rulesAfter(s, v, env) { for (const rule of s.rules ?? []) this.never(rule, v, env); }
|
|
173
|
+
|
|
174
|
+
/** Store into a name, a field, or an entry (a list position from 1, or a map key). */
|
|
175
|
+
store(t, v, env) {
|
|
176
|
+
if (t.k === 'name') { env.locals.set(t.ref?.py ?? 'unknown', v); return; }
|
|
177
|
+
if (t.k === 'field') {
|
|
178
|
+
const obj = this.x(t.obj, env);
|
|
179
|
+
if (t.static) this.setAttr(obj, t.py, v); else this.setField(obj, t.text, v);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (t.k === 'at') {
|
|
183
|
+
const obj = this.x(t.obj, env), key = this.x(t.key, env);
|
|
184
|
+
if (t.objKind === 'list') this.setItem(obj, key, v);
|
|
185
|
+
else if (t.objKind === 'map') this.mapSet(obj, key, v);
|
|
186
|
+
else this.setEntry(obj, key, v);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
stmt(s, env) {
|
|
191
|
+
if (this.rec) return this.recordStep(s, env);
|
|
192
|
+
return this.runStmt(s, env);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The Time Machine: one step per statement, in the order they run. A step keeps the line, how deep in calls it
|
|
197
|
+
* is, the values it changed (before -> after, as the program would show them), and what it printed. A statement
|
|
198
|
+
* with steps inside (a choice, a loop) keeps only where it went next; the steps inside are recorded on their own.
|
|
199
|
+
*/
|
|
200
|
+
recordStep(s, env) {
|
|
201
|
+
const rec = this.rec;
|
|
202
|
+
if (rec.steps.length >= MAX_RECORDED) { rec.truncated = true; return this.runStmt(s, env); }
|
|
203
|
+
const names = () => { const m = new Map(); for (const [k, v] of env.locals) if (!v?.isFunc) m.set(k, v); return m; };
|
|
204
|
+
const view = (v) => { try { return typeof v === 'string' ? pyStr(v) : show(v); } catch { return '…'; } };
|
|
205
|
+
const before = new Map([...names()].map(([k, v]) => [k, view(v)]));
|
|
206
|
+
const step = { n: rec.steps.length + 1, file: env.frame.file, line: s.line, depth: this.frames.length, fn: env.frame.fn ?? null, kind: s.k };
|
|
207
|
+
const outFrom = this.out.length;
|
|
208
|
+
rec.steps.push(step);
|
|
209
|
+
const inner = rec.steps.length;
|
|
210
|
+
const container = CONTAINER_KINDS.has(s.k);
|
|
211
|
+
const finish = (failed, gave) => {
|
|
212
|
+
const nested = rec.steps.length > inner;
|
|
213
|
+
if (container && nested) { step.next = rec.steps[inner].line; if (failed) step.failed = true; return; }
|
|
214
|
+
if (container) step.next = null; // a choice or loop whose steps did not run (a condition that was false)
|
|
215
|
+
const said = nested ? '' : this.out.slice(outFrom).join(''); // (output from a call is on the call's own steps)
|
|
216
|
+
if (gave !== undefined) step.gives = view(gave);
|
|
217
|
+
const changes = [];
|
|
218
|
+
for (const [k, v] of names()) { const after = view(v); if (before.get(k) !== after) changes.push({ name: k.replace(/_/g, ' '), ...(before.has(k) ? { before: before.get(k) } : {}), after }); }
|
|
219
|
+
if (changes.length) step.changes = changes;
|
|
220
|
+
if (said) step.said = said;
|
|
221
|
+
if (failed) step.failed = true;
|
|
222
|
+
};
|
|
223
|
+
try { const r = this.runStmt(s, env); finish(false); return r; }
|
|
224
|
+
catch (e) { if (e instanceof Return) finish(false, e.v); else finish(true); throw e; }
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
runStmt(s, env) {
|
|
228
|
+
const L = s.line;
|
|
229
|
+
const fr = env.frame;
|
|
230
|
+
fr.line = L;
|
|
231
|
+
switch (s.k) {
|
|
232
|
+
case 'say': {
|
|
233
|
+
const v = this.x(s.e, env);
|
|
234
|
+
this.out.push(`${s.e.type?.k === 'text' ? pyStr(v) : show(v)}\n`);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
case 'set': {
|
|
238
|
+
const t = s.target;
|
|
239
|
+
const v = this.x(s.e, env);
|
|
240
|
+
if (t.k === 'name') { this.assign(s, t.ref.py, v, env); return; }
|
|
241
|
+
if (t.k === 'field') {
|
|
242
|
+
const obj = this.x(t.obj, env);
|
|
243
|
+
if (t.static) this.setAttr(obj, t.py, v); else this.setField(obj, t.text, v);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
this.storeAt(t, v, env);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
case 'give': throw new Return(s.e.k === 'nothing' ? null : this.x(s.e, env));
|
|
250
|
+
case 'stop': { const v = this.x(s.e, env); throw Stop(s.e.type?.k === 'text' ? pyStr(v) : show(v)); }
|
|
251
|
+
case 'if':
|
|
252
|
+
for (const b of s.branches) {
|
|
253
|
+
fr.line = b.line;
|
|
254
|
+
if (this.yn(b.cond, env)) { this.block(b.body, env); return; }
|
|
255
|
+
}
|
|
256
|
+
if (s.otherwise) this.block(s.otherwise, env);
|
|
257
|
+
return;
|
|
258
|
+
case 'each': {
|
|
259
|
+
const it = this.x(s.iter, env);
|
|
260
|
+
const [a, b] = s.vars;
|
|
261
|
+
let seq;
|
|
262
|
+
if (b) seq = s.iterKind === 'map' ? this.mapItems(it) : s.iterKind === 'pairs' ? pyIter(it) : this.pairsOf(it);
|
|
263
|
+
else seq = pyIter(it);
|
|
264
|
+
for (let i = 0; i < seq.length; i++) {
|
|
265
|
+
fr.line = L;
|
|
266
|
+
const el = seq[i];
|
|
267
|
+
if (b) { const [x, y] = this.unpack2(el); env.locals.set(a.py, x); env.locals.set(b.py, y); }
|
|
268
|
+
else env.locals.set(a.py, el);
|
|
269
|
+
this.block(s.body, env);
|
|
270
|
+
}
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
case 'range': {
|
|
274
|
+
const from = this.x(s.from, env);
|
|
275
|
+
const to = s.to.k === 'num' && s.to.whole ? BigInt(s.to.text.replace(/_/g, '')) + 1n : add(this.x(s.to, env), 1n);
|
|
276
|
+
const lo = this.rangeInt(from), hi = this.rangeInt(to);
|
|
277
|
+
for (let i = lo; i < hi; i++) { fr.line = L; env.locals.set(s.v.py, i); this.block(s.body, env); }
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
case 'while':
|
|
281
|
+
for (;;) {
|
|
282
|
+
fr.line = L;
|
|
283
|
+
const c = this.yn(s.cond, env);
|
|
284
|
+
if (s.until ? c : !c) return;
|
|
285
|
+
this.block(s.body, env);
|
|
286
|
+
}
|
|
287
|
+
case 'times': {
|
|
288
|
+
const n = this.rangeInt(this.x(s.count, env));
|
|
289
|
+
for (let i = 0n; i < n; i++) { fr.line = L; this.block(s.body, env); }
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
case 'expect': return this.expect(s, env);
|
|
293
|
+
case 'add': case 'remove': return this.addRemove(s, env);
|
|
294
|
+
case 'increase': case 'decrease': {
|
|
295
|
+
const op = s.k === 'increase' ? add : sub;
|
|
296
|
+
if (s.target.k === 'name') {
|
|
297
|
+
const py = s.target.ref?.py ?? 'unknown';
|
|
298
|
+
const cur = this.lookup(env, py);
|
|
299
|
+
const v = op(cur, this.x(s.e, env));
|
|
300
|
+
if (s.rules?.length) { this.assign(s, py, v, env); return; }
|
|
301
|
+
env.locals.set(py, v);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const cur = this.x(s.target, env);
|
|
305
|
+
this.store(s.target, op(cur, this.x(s.e, env)), env);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
case 'sort': {
|
|
309
|
+
const target = this.x(s.target, env);
|
|
310
|
+
if (!Array.isArray(target)) throw attrErr(target, 'sort');
|
|
311
|
+
const key = s.field ? this.keyFn(s.field, env) : null;
|
|
312
|
+
const sorted = pySort(target, key, !!s.desc);
|
|
313
|
+
target.splice(0, target.length, ...sorted);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
case 'reverse': {
|
|
317
|
+
const target = this.x(s.target, env);
|
|
318
|
+
if (!Array.isArray(target)) throw attrErr(target, 'reverse');
|
|
319
|
+
target.reverse();
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
case 'do': this.x(s.e, env); return;
|
|
323
|
+
case 'open': env.opens = s.name; return;
|
|
324
|
+
case 'tryFail':
|
|
325
|
+
try { this.stmt(s.stmt, env); }
|
|
326
|
+
catch (e) {
|
|
327
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
328
|
+
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
329
|
+
const err = asPyErr(e);
|
|
330
|
+
fr.line = L;
|
|
331
|
+
env.locals.set(s.errPy, explain(err));
|
|
332
|
+
this.block(s.handler, env);
|
|
333
|
+
}
|
|
334
|
+
return;
|
|
335
|
+
default: return;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
storeAt(t, v, env) { this.store(t, v, env); }
|
|
340
|
+
|
|
341
|
+
addRemove(s, env) {
|
|
342
|
+
const v = this.x(s.e, env);
|
|
343
|
+
const isName = s.target.k === 'name';
|
|
344
|
+
const target = this.x(s.target, env);
|
|
345
|
+
const py = isName ? s.target.ref?.py ?? 'unknown' : null;
|
|
346
|
+
if (s.targetKind === 'list') { if (s.k === 'add') { if (!Array.isArray(target)) throw attrErr(target, 'append'); target.push(v); } else this.removeFrom(target, v); }
|
|
347
|
+
else if (s.targetKind === 'map') this.removeFrom(target, v);
|
|
348
|
+
else if (s.targetKind === 'number') {
|
|
349
|
+
const nv = (s.k === 'add' ? add : sub)(target, v);
|
|
350
|
+
if (isName && s.rules?.length) { this.assign(s, py, nv, env); return; }
|
|
351
|
+
if (isName) env.locals.set(py, nv); else this.store(s.target, nv, env);
|
|
352
|
+
} else if (s.k === 'add') {
|
|
353
|
+
const nv = this.addTo(target, v);
|
|
354
|
+
if (isName) env.locals.set(py, nv); else this.store(s.target, nv, env);
|
|
355
|
+
} else this.removeFrom(target, v);
|
|
356
|
+
if (isName) this.rulesAfter(s, this.lookup(env, py), env);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
expect(s, env) {
|
|
360
|
+
const text = (s.raw ?? 'Expect').trim();
|
|
361
|
+
if (s.mode === 'true') { V.expectTrue(this.x(s.e, env), text); return; }
|
|
362
|
+
if (s.mode === 'fail') {
|
|
363
|
+
const msg = s.msg ? this.x(s.msg, env) : null;
|
|
364
|
+
// A JavaScript stack overflow is not the program failing: let it reach the deeper-stack retry.
|
|
365
|
+
V.expectFailure(() => {
|
|
366
|
+
try { this.x(s.e, env); }
|
|
367
|
+
catch (e) {
|
|
368
|
+
if (e instanceof Return) return;
|
|
369
|
+
if (e instanceof NeedsDeeperStack) throw e;
|
|
370
|
+
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
371
|
+
throw e;
|
|
372
|
+
}
|
|
373
|
+
}, text, msg);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const actual = this.x(s.e, env);
|
|
377
|
+
if (s.mode === 'cmp') { V.expectValue(actual, 'contains', 'contains', this.x(s.want, env), text); return; }
|
|
378
|
+
let c = s.check, negate = false;
|
|
379
|
+
if (c.k === 'not') { negate = true; c = c.e; }
|
|
380
|
+
let op, want = null;
|
|
381
|
+
const OPS = { '==': 'is', '!=': 'is not', '>=': 'at least', '<=': 'at most', '>': 'more than', '<': 'less than' };
|
|
382
|
+
if (c.k === 'cmp') { op = OPS[c.op]; want = this.x(c.r, env); }
|
|
383
|
+
else if (c.k === 'adj') op = c.adj;
|
|
384
|
+
else if (c.k === 'isNothing') op = c.neg ? 'not nothing' : 'nothing';
|
|
385
|
+
else if (c.k === 'between') { op = 'between'; want = [this.x(c.lo, env), this.x(c.hi, env)]; }
|
|
386
|
+
else if (c.k === 'contains') { op = 'in'; want = this.x(c.l, env); }
|
|
387
|
+
else op = 'is';
|
|
388
|
+
V.expectValue(actual, negate ? `not ${op}` : op, op, want, text);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// ── runtime helpers (shared with compiled TypeScript: engine-values.mjs) ────────────────────────────────────
|
|
392
|
+
yn(e, env, ctx) {
|
|
393
|
+
const v = this.x(e, env, ctx);
|
|
394
|
+
const known = e.type?.k === 'bool' || ['cmp', 'contains', 'between', 'adj', 'isNothing', 'not', 'bool'].includes(e.k) || (e.k === 'bin' && (e.op === 'and' || e.op === 'or'));
|
|
395
|
+
return known ? v : yesNo(v);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
rangeInt(v) { return V.rangeInt(v); }
|
|
399
|
+
unpack2(el) { return V.unpack2(el); }
|
|
400
|
+
mapItems(m) { return V.mapItems(m); }
|
|
401
|
+
pairsOf(c) { return V.pairsOf(c); }
|
|
402
|
+
|
|
403
|
+
keyFn(field, env) {
|
|
404
|
+
const frame = { file: env.frame.file, line: env.frame.line };
|
|
405
|
+
return (item) => this.withFrame(frame, () => (field.dynamic ? this.getField(item, field.key) : this.getAttr(item, field.py)));
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
itemAt(items, position, dflt) { return V.itemAt(items, position, dflt); }
|
|
409
|
+
setItem(items, position, value) { V.setItem(items, position, value); }
|
|
410
|
+
mapSet(m, k, v) { V.mapSet(m, k, v); }
|
|
411
|
+
setEntry(c, k, v) { V.setEntry(c, k, v); }
|
|
412
|
+
entry(c, k, dflt) { return V.entry(c, k, dflt); }
|
|
413
|
+
mapGet(m, k, dflt) { return V.mapGet(m, k, dflt); }
|
|
414
|
+
getField(obj, key) { return V.getField(obj, key); }
|
|
415
|
+
setField(obj, key, value) { V.setFieldWith((o, k, v) => this.setAttr(o, k, v), obj, key, value); }
|
|
416
|
+
addTo(target, value) { return V.addTo(target, value); }
|
|
417
|
+
removeFrom(target, value) { V.removeFrom(target, value); }
|
|
418
|
+
|
|
419
|
+
// ── expressions ─────────────────────────────────────────────────────────────────────────────────────────────
|
|
420
|
+
x(e, env, ctx = {}) {
|
|
421
|
+
const sub2 = (k) => this.x(k, env, ctx);
|
|
422
|
+
switch (e.k) {
|
|
423
|
+
case 'num': return e.whole ? BigInt(e.text.replace(/_/g, '')) : Dec.parse(e.text);
|
|
424
|
+
case 'money': return Money.of(e.text);
|
|
425
|
+
case 'percent': return Dec.parse(percentDecimal(e.text));
|
|
426
|
+
case 'bool': return !!e.v;
|
|
427
|
+
case 'nothing': case 'hole': return null;
|
|
428
|
+
case 'paren': return sub2(e.e);
|
|
429
|
+
case 'today': return PyDate.today();
|
|
430
|
+
case 'date': { const d = PyDate.parse(e.text); if (!d) throw new PyErr('ValueError', `Invalid isoformat string: '${e.text}'`); return d; }
|
|
431
|
+
case 'str': return this.str(e, env, ctx);
|
|
432
|
+
case 'list': return e.items ? e.items.map(sub2) : new PyDict();
|
|
433
|
+
case 'map': return new PyDict();
|
|
434
|
+
case 'name': {
|
|
435
|
+
const r = e.ref ?? {};
|
|
436
|
+
if (r.kind === 'subject') return ctx.subject ?? null;
|
|
437
|
+
if (r.kind === 'elemField') return this.getAttr(ctx.item, r.py);
|
|
438
|
+
if (r.kind === 'elemKey') return this.getField(ctx.item, r.key);
|
|
439
|
+
if (r.kind === 'elem') return ctx.item;
|
|
440
|
+
return this.lookup(env, r.py ?? e.name.replace(/ /g, '_'));
|
|
441
|
+
}
|
|
442
|
+
case 'call': { const fn = this.lookup(env, e.py); return this.call(fn, e.args.map(sub2)); }
|
|
443
|
+
case 'new': {
|
|
444
|
+
const cls = this.lookup(env, e.py);
|
|
445
|
+
const given = new Map();
|
|
446
|
+
for (const f of e.fields) given.set(f.py, sub2(f.e));
|
|
447
|
+
return this.newRecord(cls, given);
|
|
448
|
+
}
|
|
449
|
+
case 'field': { const obj = sub2(e.obj); return e.static ? this.getAttr(obj, e.py) : this.getField(obj, e.text); }
|
|
450
|
+
case 'at': {
|
|
451
|
+
const o = sub2(e.obj), k = sub2(e.key);
|
|
452
|
+
const d = e.dflt ? sub2(e.dflt) : undefined;
|
|
453
|
+
if (e.objKind === 'map') return this.mapGet(o, k, d);
|
|
454
|
+
if (e.objKind === 'list') return this.itemAt(o, k, d);
|
|
455
|
+
return this.entry(o, k, d);
|
|
456
|
+
}
|
|
457
|
+
case 'conv': {
|
|
458
|
+
const v = sub2(e.e);
|
|
459
|
+
switch (e.to) {
|
|
460
|
+
case 'list': return pyList(v);
|
|
461
|
+
case 'number': return V.toNumber(v);
|
|
462
|
+
case 'whole': return V.toWhole(v);
|
|
463
|
+
case 'money': return V.toMoney(v);
|
|
464
|
+
case 'text': return show(v);
|
|
465
|
+
case 'bool': return V.toYesNo(v);
|
|
466
|
+
case 'date': return V.toDate(v);
|
|
467
|
+
default: return v;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
case 'where': {
|
|
471
|
+
const list = sub2(e.list);
|
|
472
|
+
return pyIter(list).filter((item) => truthy(this.x(e.cond, env, { ...ctx, item })));
|
|
473
|
+
}
|
|
474
|
+
case 'from': {
|
|
475
|
+
const inner = e.list.k === 'where' ? e.list : null;
|
|
476
|
+
const list = sub2(inner ? inner.list : e.list);
|
|
477
|
+
const pick = (item) => (e.field.dynamic ? this.getField(item, e.field.key) : this.getAttr(item, e.field.py));
|
|
478
|
+
return pyIter(list).filter((item) => !inner || truthy(this.x(inner.cond, env, { ...ctx, item }))).map(pick);
|
|
479
|
+
}
|
|
480
|
+
case 'sorted': {
|
|
481
|
+
const list = sub2(e.list);
|
|
482
|
+
if (e.mapSort) {
|
|
483
|
+
if (!(list instanceof PyDict)) throw attrErr(list, 'items');
|
|
484
|
+
const frame = { file: env.frame.file, line: env.frame.line };
|
|
485
|
+
return pySort(list.items(), (t) => this.withFrame(frame, () => t.items[e.by === 'key' ? 0 : 1]), !!e.desc);
|
|
486
|
+
}
|
|
487
|
+
return pySort(pyList(list), this.keyFn(e.field, env), !!e.desc);
|
|
488
|
+
}
|
|
489
|
+
case 'op': return this.op(e.op, sub2(e.arg));
|
|
490
|
+
case 'round': { const v = sub2(e.e); return e.places ? roundTo(v, sub2(e.places)) : roundTo(v); }
|
|
491
|
+
case 'readFile': return this.readFile(sub2(e.path));
|
|
492
|
+
case 'neg': return neg(sub2(e.e));
|
|
493
|
+
case 'not': return !this.yn(e.e, env, ctx);
|
|
494
|
+
case 'bin': {
|
|
495
|
+
if (e.op === 'and') return this.yn(e.l, env, ctx) && this.yn(e.r, env, ctx);
|
|
496
|
+
if (e.op === 'or') return this.yn(e.l, env, ctx) || this.yn(e.r, env, ctx);
|
|
497
|
+
const l = sub2(e.l), r = sub2(e.r);
|
|
498
|
+
if (e.op === '+') return add(l, r);
|
|
499
|
+
if (e.op === '-') return sub(l, r);
|
|
500
|
+
if (e.op === '*') return mul(l, r);
|
|
501
|
+
if (e.op === '/') return divide(l, r);
|
|
502
|
+
if (e.op === 'mod') return e.l.type?.k === 'whole' && e.r.type?.k === 'whole' ? intMod(l, r) : modulo(l, r);
|
|
503
|
+
throw new PyErr('NameError', `name '${e.op}' is not defined`);
|
|
504
|
+
}
|
|
505
|
+
case 'cmp': {
|
|
506
|
+
if (e.r.k === 'bool' && (e.op === '==' || e.op === '!=')) { const a = this.yn(e.l, env, ctx); const b = sub2(e.r); return e.op === '==' ? a === b : a !== b; }
|
|
507
|
+
return compare(e.op, sub2(e.l), sub2(e.r));
|
|
508
|
+
}
|
|
509
|
+
case 'between': { const lo = sub2(e.lo), v = sub2(e.e); if (!compare('<=', lo, v)) return false; return compare('<=', v, sub2(e.hi)); }
|
|
510
|
+
case 'contains': { const item = sub2(e.r); return contains(sub2(e.l), item); }
|
|
511
|
+
case 'affix': return V.affix(sub2(e.l), sub2(e.r), e.end);
|
|
512
|
+
case 'sortedValues': return pySort(pyList(sub2(e.list)), null, !!e.desc);
|
|
513
|
+
case 'joined': return V.joined(sub2(e.list), sub2(e.sep));
|
|
514
|
+
case 'splitAt': return V.splitAt(sub2(e.text), sub2(e.sep));
|
|
515
|
+
case 'replacing': return V.replacing(sub2(e.text), sub2(e.from), sub2(e.to));
|
|
516
|
+
case 'adj': {
|
|
517
|
+
const v = sub2(e.e);
|
|
518
|
+
if (e.adj === 'empty') return eq(pyLen(v), 0n);
|
|
519
|
+
return compare({ positive: '>', negative: '<', zero: '==' }[e.adj], v, 0n);
|
|
520
|
+
}
|
|
521
|
+
case 'isNothing': { const v = sub2(e.e); return e.neg ? v !== null : v === null; }
|
|
522
|
+
default: return null;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
op(op, a) { return V.applyOp(op, a); }
|
|
527
|
+
|
|
528
|
+
readFile(path) { return V.readTextVia(this.readText, this.cwd, path); }
|
|
529
|
+
|
|
530
|
+
/** Text with {holes}: text and whole numbers as they are, anything else shown the Thunder way. */
|
|
531
|
+
str(e, env, ctx) {
|
|
532
|
+
return e.parts.map((p) => {
|
|
533
|
+
if (typeof p === 'string') return p;
|
|
534
|
+
const v = this.x(p.e, env, ctx);
|
|
535
|
+
const t = p.e.type?.k;
|
|
536
|
+
return t === 'text' || t === 'whole' ? pyStr(v) : show(v);
|
|
537
|
+
}).join('');
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// ── running a program or its tests ──────────────────────────────────────────────────────────────────────────
|
|
541
|
+
runMain(mod) {
|
|
542
|
+
const main = mod.r.program.main ?? [];
|
|
543
|
+
if (!main.length) return;
|
|
544
|
+
const frame = { file: mod.file, line: 0 };
|
|
545
|
+
this.withFrame(frame, () => {
|
|
546
|
+
const env = { mod, locals: new Map(), frame };
|
|
547
|
+
try { this.block(main, env); } catch (e) { if (e instanceof Return) return; throw e; }
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
runTest(mod, t) {
|
|
552
|
+
const frame = { file: mod.file, line: t.line };
|
|
553
|
+
this.withFrame(frame, () => {
|
|
554
|
+
const env = { mod, locals: new Map(), frame };
|
|
555
|
+
try { this.block(t.body, env); } catch (e) { if (e instanceof Return) return; throw e; }
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
// ── public API ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
562
|
+
|
|
563
|
+
/** The same, on the calling thread (its stack allows only a few hundred nested calls). */
|
|
564
|
+
export function runInProcess({ entry, cwd, deeper = false, readText = null } = {}) {
|
|
565
|
+
const uses = pythonModulesUsed([entry]);
|
|
566
|
+
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
567
|
+
const eng = new Engine({ cwd, deeper, readText });
|
|
568
|
+
let stderr = '', status = 0;
|
|
569
|
+
try {
|
|
570
|
+
const mod = eng.load(entry);
|
|
571
|
+
eng.runMain(mod);
|
|
572
|
+
} catch (e) {
|
|
573
|
+
if (e instanceof Return) { /* a Give outside a function ends the program */ }
|
|
574
|
+
else if (e instanceof NeedsDeeperStack || (deeper && nativeOverflow(e))) return { needsDeeperStack: true };
|
|
575
|
+
else { stderr = `${eng.describeError(asPyErr(e))}\n`; status = 1; }
|
|
576
|
+
}
|
|
577
|
+
return { status, stdout: eng.out.join(''), stderr };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Run a program and keep a step-by-step recording of it (the Thunder Time Machine, `thunder run --record`).
|
|
582
|
+
* Gives back { status, stdout, stderr, steps, truncated }. Like runInProcess, on the calling thread.
|
|
583
|
+
*/
|
|
584
|
+
export function recordedRun({ entry, cwd, readText = null } = {}) {
|
|
585
|
+
const uses = pythonModulesUsed([entry]);
|
|
586
|
+
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses, steps: [] };
|
|
587
|
+
const eng = new Engine({ cwd, readText, record: true });
|
|
588
|
+
let stderr = '', status = 0;
|
|
589
|
+
try {
|
|
590
|
+
const mod = eng.load(entry);
|
|
591
|
+
eng.runMain(mod);
|
|
592
|
+
} catch (e) {
|
|
593
|
+
if (!(e instanceof Return)) { stderr = `${eng.describeError(asPyErr(e))}\n`; status = 1; }
|
|
594
|
+
}
|
|
595
|
+
return { status, stdout: eng.out.join(''), stderr, steps: eng.rec.steps, truncated: eng.rec.truncated };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** The same, on the calling thread. */
|
|
599
|
+
export function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
|
|
600
|
+
const uses = pythonModulesUsed(results);
|
|
601
|
+
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
602
|
+
const eng = new Engine({ cwd, deeper, readText });
|
|
603
|
+
const mods = [];
|
|
604
|
+
const srcMods = [];
|
|
605
|
+
for (const r of results) {
|
|
606
|
+
const mod = eng.load(r, r.kind === 'test' ? srcMods : []);
|
|
607
|
+
if (r.kind !== 'test') srcMods.push(mod);
|
|
608
|
+
mods.push(mod);
|
|
609
|
+
}
|
|
610
|
+
let passed = 0, failed = 0;
|
|
611
|
+
for (const mod of mods) {
|
|
612
|
+
for (const t of mod.r.info.tests) {
|
|
613
|
+
try {
|
|
614
|
+
eng.runTest(mod, t);
|
|
615
|
+
passed++;
|
|
616
|
+
eng.out.push(`PASS ${t.title} (${mod.file}, line ${t.line})\n`);
|
|
617
|
+
} catch (e) {
|
|
618
|
+
if (e instanceof NeedsDeeperStack || (deeper && nativeOverflow(e))) return { needsDeeperStack: true };
|
|
619
|
+
failed++;
|
|
620
|
+
eng.out.push(`FAIL ${t.title} (${mod.file}, line ${t.line})\n`, ` ${eng.describeError(asPyErr(e))}\n`);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
const total = passed + failed;
|
|
625
|
+
eng.out.push(`${total} test${total === 1 ? '' : 's'}: ${passed} passed, ${failed} failed\n`);
|
|
626
|
+
return { status: failed ? 1 : 0, stdout: eng.out.join(''), stderr: '' };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// ── screens ────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
630
|
+
//
|
|
631
|
+
// A screen is shown as a tree of plain values (the same tree compiled React's HTML is read back into by the
|
|
632
|
+
// conformance tests), and changed one event at a time: a press runs its steps on copies of the remembered values
|
|
633
|
+
// and keeps them only if every step works; typing sets the box's value. Each shown screen remembers its own values,
|
|
634
|
+
// by its place on the screen (as React keeps a component's state by its place), and forgets them when it goes away.
|
|
635
|
+
//
|
|
636
|
+
// { k: 'screen', name, children: [...] } a screen (the app's, or one shown inside another)
|
|
637
|
+
// { k: 'heading', text } { k: 'text', text } { k: 'row', children } { k: 'list', items: [[...], ...] }
|
|
638
|
+
// { k: 'textbox' | 'numberbox', label, value } { k: 'button', label, off }
|
|
639
|
+
// { k: 'problem', text } what the last press or typing on this screen said, when it failed
|
|
640
|
+
// { k: 'failed', text } the app could not be shown (the same message thunder run gives)
|
|
641
|
+
|
|
642
|
+
class ScreenApp {
|
|
643
|
+
constructor(eng, entry) {
|
|
644
|
+
this.eng = eng;
|
|
645
|
+
this.entry = entry;
|
|
646
|
+
this.screens = new Map(entry.info.screens.map((s) => [s.name, s]));
|
|
647
|
+
this.current = entry.info.screens[0] ?? null;
|
|
648
|
+
this.places = new Map(); // place -> { values: Map(py -> value), problem }
|
|
649
|
+
this.handlers = [];
|
|
650
|
+
try { this.mod = eng.load(entry); } catch (e) { this.loadFailed = e; }
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** The app as it is now, as a tree. */
|
|
654
|
+
render() {
|
|
655
|
+
this.handlers = [];
|
|
656
|
+
if (this.loadFailed) return { k: 'failed', text: this.eng.describeError(asPyErr(this.loadFailed)) };
|
|
657
|
+
if (!this.current) return { k: 'failed', text: 'This program has no Screen to show.' };
|
|
658
|
+
const seen = new Set();
|
|
659
|
+
try {
|
|
660
|
+
const tree = this.screen(this.current, new Map(), this.current.name, seen);
|
|
661
|
+
for (const k of [...this.places.keys()]) if (!seen.has(k)) this.places.delete(k); // gone: forgotten
|
|
662
|
+
return tree;
|
|
663
|
+
} catch (e) {
|
|
664
|
+
if (e instanceof NeedsDeeperStack) throw e;
|
|
665
|
+
this.places.clear();
|
|
666
|
+
return { k: 'failed', text: this.eng.describeError(asPyErr(e)) };
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/** One screen at a place: its inputs (given, or their defaults), its remembered values, and what it shows. */
|
|
671
|
+
screen(s, given, place, seen) {
|
|
672
|
+
seen.add(place);
|
|
673
|
+
const eng = this.eng;
|
|
674
|
+
const frame = { file: this.mod.file, line: s.line };
|
|
675
|
+
// A screen shown inside another is shown on its own (as React renders each component by itself).
|
|
676
|
+
const saved = eng.frames;
|
|
677
|
+
eng.frames = [];
|
|
678
|
+
try {
|
|
679
|
+
return eng.withFrame(frame, () => {
|
|
680
|
+
const env = { mod: this.mod, locals: new Map(), frame };
|
|
681
|
+
for (const p of s.params) {
|
|
682
|
+
if (given.has(p.py)) env.locals.set(p.py, given.get(p.py));
|
|
683
|
+
else { frame.line = p.line; env.locals.set(p.py, p.dflt ? eng.x(p.dflt, env) : null); }
|
|
684
|
+
}
|
|
685
|
+
let st = this.places.get(place);
|
|
686
|
+
if (!st) {
|
|
687
|
+
const values = new Map();
|
|
688
|
+
st = { values, problem: null };
|
|
689
|
+
for (const r of s.remember) { frame.line = r.line; const v = eng.x(r.e, env); values.set(r.py, v); env.locals.set(r.py, v); }
|
|
690
|
+
this.places.set(place, st);
|
|
691
|
+
}
|
|
692
|
+
for (const [k, v] of st.values) env.locals.set(k, v);
|
|
693
|
+
const children = this.elements(s.body, env, s, place, st, seen);
|
|
694
|
+
if (st.problem !== null) children.push({ k: 'problem', text: st.problem });
|
|
695
|
+
return { k: 'screen', name: s.text, children };
|
|
696
|
+
});
|
|
697
|
+
} finally { eng.frames = saved; }
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
elements(els, env, s, place, st, seen) {
|
|
701
|
+
const eng = this.eng;
|
|
702
|
+
const fr = env.frame;
|
|
703
|
+
const out = [];
|
|
704
|
+
els.forEach((el, i) => {
|
|
705
|
+
const at = `${place}/${i}`;
|
|
706
|
+
fr.line = el.line;
|
|
707
|
+
switch (el.k) {
|
|
708
|
+
case 'heading': out.push({ k: 'heading', text: shownText(eng.x(el.e, env), el.e.type?.k) }); return;
|
|
709
|
+
case 'text': out.push({ k: 'text', text: shownText(eng.x(el.e, env), el.e.type?.k) }); return;
|
|
710
|
+
case 'when': {
|
|
711
|
+
for (let b = 0; b < el.branches.length; b++) {
|
|
712
|
+
fr.line = el.branches[b].line;
|
|
713
|
+
if (eng.yn(el.branches[b].cond, env)) { out.push(...this.elements(el.branches[b].body, env, s, `${at}.${b}`, st, seen)); return; }
|
|
714
|
+
}
|
|
715
|
+
if (el.otherwise) out.push(...this.elements(el.otherwise, env, s, `${at}.else`, st, seen));
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
case 'list': {
|
|
719
|
+
const items = pyIter(eng.x(el.iter, env));
|
|
720
|
+
out.push({ k: 'list', items: items.map((item, n) => {
|
|
721
|
+
const inner = { ...env, locals: new Map(env.locals) };
|
|
722
|
+
inner.locals.set(el.v.py, item);
|
|
723
|
+
return this.elements(el.body, inner, s, `${at}#${n}`, st, seen);
|
|
724
|
+
}) });
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
case 'row': out.push({ k: 'row', children: this.elements(el.body, env, s, at, st, seen) }); return;
|
|
728
|
+
case 'textbox': case 'numberbox': {
|
|
729
|
+
const label = pyStr(eng.x(el.label, env));
|
|
730
|
+
const v = env.locals.get(el.target.ref.py);
|
|
731
|
+
out.push({ k: el.k, label, value: el.k === 'textbox' ? pyStr(v) : show(v) });
|
|
732
|
+
this.handlers.push({ kind: 'box', label, type: (text) => {
|
|
733
|
+
try { st.values.set(el.target.ref.py, el.k === 'textbox' ? String(text) : typedNumber(text, el.boxKind)); st.problem = null; }
|
|
734
|
+
catch (e) { st.problem = problemText(e); }
|
|
735
|
+
} });
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
case 'button': {
|
|
739
|
+
const label = pyStr(eng.x(el.label, env));
|
|
740
|
+
fr.line = el.line;
|
|
741
|
+
const off = el.off ? eng.yn(el.off, env) : false;
|
|
742
|
+
out.push({ k: 'button', label, off });
|
|
743
|
+
const locals = new Map(env.locals);
|
|
744
|
+
this.handlers.push({ kind: 'button', label, off, press: () => this.press(el, locals, st) });
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
case 'child': {
|
|
748
|
+
const target = this.screens.get(el.screen.name);
|
|
749
|
+
const given = new Map();
|
|
750
|
+
for (const g of el.given) { fr.line = g.line; given.set(g.py, eng.x(g.e, env)); }
|
|
751
|
+
out.push(this.screen(target, given, `${at}:${target.name}`, seen));
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
default: return;
|
|
755
|
+
}
|
|
756
|
+
});
|
|
757
|
+
return out;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** A press: its steps run on copies of the screen's remembered values; they are kept only if every step works. */
|
|
761
|
+
press(el, locals, st) {
|
|
762
|
+
let opens = el.opens?.name ?? null;
|
|
763
|
+
if (el.press) {
|
|
764
|
+
const eng = this.eng;
|
|
765
|
+
const frame = { file: this.mod.file, line: el.press.line };
|
|
766
|
+
const env = { mod: this.mod, locals: new Map(locals), frame, opens: null };
|
|
767
|
+
for (const [k, v] of st.values) env.locals.set(k, copyValue(v));
|
|
768
|
+
try {
|
|
769
|
+
eng.withFrame(frame, () => eng.block(el.press.body, env));
|
|
770
|
+
} catch (e) {
|
|
771
|
+
if (e instanceof NeedsDeeperStack) throw e;
|
|
772
|
+
st.problem = problemText(e);
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
for (const k of st.values.keys()) st.values.set(k, env.locals.get(k));
|
|
776
|
+
st.problem = null;
|
|
777
|
+
opens = env.opens ?? opens;
|
|
778
|
+
}
|
|
779
|
+
if (opens && opens !== this.current.name) { this.current = this.screens.get(opens); this.places.clear(); }
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/** The button or box with this label (the nth one, from 1, when several have it). */
|
|
783
|
+
find(kind, label, nth = 1) {
|
|
784
|
+
const all = this.handlers.filter((h) => h.kind === kind && h.label === label);
|
|
785
|
+
const h = all[nth - 1];
|
|
786
|
+
if (!h) {
|
|
787
|
+
const labels = [...new Set(this.handlers.filter((x) => x.kind === kind).map((x) => `"${x.label}"`))];
|
|
788
|
+
throw new Error(`There is no ${kind === 'box' ? 'box' : 'button'} "${label}" on the screen${all.length ? ` (only ${all.length})` : ''}.${labels.length ? ` There is ${labels.join(', ')}.` : ''}`);
|
|
789
|
+
}
|
|
790
|
+
return h;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* Show a program's screens and change them one event at a time, on the Thunder engine:
|
|
796
|
+
* const app = screenApp({ entry }); app.render() -> tree; app.press("Add"); app.type("Name", "Ada"); app.render()
|
|
797
|
+
* A press on a button that is off does nothing (and says so). Each event is followed by a render, as in React.
|
|
798
|
+
*/
|
|
799
|
+
export function screenApp({ entry, cwd = '.', readText = null } = {}) {
|
|
800
|
+
const app = new ScreenApp(new Engine({ cwd, readText }), entry);
|
|
801
|
+
let tree = app.render();
|
|
802
|
+
return {
|
|
803
|
+
render: () => tree,
|
|
804
|
+
get screen() { return app.current?.text ?? null; },
|
|
805
|
+
press(label, nth = 1) {
|
|
806
|
+
const h = app.find('button', label, nth);
|
|
807
|
+
if (h.off) return { off: true, tree };
|
|
808
|
+
h.press();
|
|
809
|
+
tree = app.render();
|
|
810
|
+
return { off: false, tree };
|
|
811
|
+
},
|
|
812
|
+
type(label, text, nth = 1) {
|
|
813
|
+
app.find('box', label, nth).type(text);
|
|
814
|
+
tree = app.render();
|
|
815
|
+
return { tree };
|
|
816
|
+
},
|
|
817
|
+
};
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/** A screen tree as an outline people read (thunder run). */
|
|
821
|
+
export function screenOutline(tree, indent = '') {
|
|
822
|
+
const L = [];
|
|
823
|
+
const q = (t) => JSON.stringify(t);
|
|
824
|
+
const walk = (n, ind) => {
|
|
825
|
+
switch (n.k) {
|
|
826
|
+
case 'failed': L.push(`${ind}✗ The screen could not be shown: ${n.text}`); return;
|
|
827
|
+
case 'screen': L.push(`${ind}Screen ${q(n.name)}`); for (const c of n.children) walk(c, `${ind} `); return;
|
|
828
|
+
case 'heading': L.push(`${ind}Heading: ${n.text}`); return;
|
|
829
|
+
case 'text': L.push(`${ind}${n.text}`); return;
|
|
830
|
+
case 'row': L.push(`${ind}Row:`); for (const c of n.children) walk(c, `${ind} `); return;
|
|
831
|
+
case 'list':
|
|
832
|
+
if (!n.items.length) { L.push(`${ind}List: (no items)`); return; }
|
|
833
|
+
L.push(`${ind}List:`);
|
|
834
|
+
for (const item of n.items) {
|
|
835
|
+
const start = L.length;
|
|
836
|
+
for (const c of item) walk(c, `${ind} `);
|
|
837
|
+
if (L.length > start) L[start] = `${ind} • ${L[start].slice(ind.length + 4)}`; else L.push(`${ind} •`);
|
|
838
|
+
}
|
|
839
|
+
return;
|
|
840
|
+
case 'textbox': L.push(`${ind}Text box ${q(n.label)}: ${q(n.value)}`); return;
|
|
841
|
+
case 'numberbox': L.push(`${ind}Number box ${q(n.label)}: ${n.value}`); return;
|
|
842
|
+
case 'button': L.push(`${ind}Button ${q(n.label)}${n.off ? ' (off)' : ''}`); return;
|
|
843
|
+
case 'problem': L.push(`${ind}! ${n.text}`); return;
|
|
844
|
+
default: return;
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
walk(tree, indent);
|
|
848
|
+
return L.join('\n');
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* Run a job on a worker thread with a large stack and wait for it: the program's results are copied to the
|
|
853
|
+
* worker (structured clone keeps the shared references the checker made), and the answer comes back the same way.
|
|
854
|
+
*/
|
|
855
|
+
export { ThunderErr, PyErr };
|