@skillstech/thunderlang 1.0.4 → 1.2.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +221 -0
  2. package/README.md +4 -1
  3. package/dist/core.cjs +2568 -462
  4. package/dist/index.cjs +7562 -5084
  5. package/dist/learn.cjs +16994 -8339
  6. package/intent-graph.schema.json +11 -0
  7. package/package.json +6 -2
  8. package/src/cli-home.mjs +242 -0
  9. package/src/cli.mjs +241 -89
  10. package/src/codegen.mjs +145 -55
  11. package/src/conformance.mjs +15 -6
  12. package/src/core/check.mjs +725 -0
  13. package/src/core/cli.mjs +184 -0
  14. package/src/core/diagnostics.mjs +82 -0
  15. package/src/core/engine-core.mjs +572 -0
  16. package/src/core/engine-values.mjs +1054 -0
  17. package/src/core/engine-worker.mjs +15 -0
  18. package/src/core/engine.mjs +63 -0
  19. package/src/core/format.mjs +20 -0
  20. package/src/core/from-python.mjs +645 -0
  21. package/src/core/index.mjs +39 -0
  22. package/src/core/lexer.mjs +115 -0
  23. package/src/core/parser.mjs +742 -0
  24. package/src/core/project.mjs +177 -0
  25. package/src/core/round-trip.mjs +150 -0
  26. package/src/core/runtime-python.mjs +801 -0
  27. package/src/core/runtime-typescript.mjs +119 -0
  28. package/src/core/target-python.mjs +487 -0
  29. package/src/core/target-typescript.mjs +466 -0
  30. package/src/core/typescript-run.mjs +114 -0
  31. package/src/core.d.ts +5 -2
  32. package/src/core.mjs +5 -2
  33. package/src/data-schema.mjs +8 -1
  34. package/src/emit.mjs +1 -1
  35. package/src/evidence.mjs +1 -1
  36. package/src/expr.mjs +81 -4
  37. package/src/form-words.mjs +2 -0
  38. package/src/index.d.ts +8 -1
  39. package/src/index.mjs +5 -1
  40. package/src/intent-schema.mjs +1 -0
  41. package/src/learn-lessons.mjs +245 -1
  42. package/src/learn.d.mts +8 -0
  43. package/src/learn.mjs +40 -4
  44. package/src/mcp.mjs +23 -0
  45. package/src/meaning.mjs +45 -6
  46. package/src/model.d.mts +7 -3
  47. package/src/model.mjs +19 -6
  48. package/src/money.d.mts +18 -0
  49. package/src/money.mjs +124 -0
  50. package/src/plain-contract.mjs +18 -2
  51. package/src/read-level.mjs +146 -0
  52. package/src/read.d.mts +11 -0
  53. package/src/read.mjs +40 -6
  54. package/src/review-comment.d.mts +16 -0
  55. package/src/review-comment.mjs +145 -0
  56. package/src/say-less.mjs +1432 -0
  57. package/src/system.mjs +153 -44
  58. package/src/target-cs.mjs +39 -34
  59. package/src/target-elixir.mjs +40 -30
  60. package/src/target-go.mjs +41 -36
  61. package/src/target-java.mjs +34 -27
  62. package/src/target-kotlin.mjs +43 -35
  63. package/src/target-py.mjs +57 -55
  64. package/src/target-result.d.mts +48 -0
  65. package/src/target-result.mjs +112 -0
  66. package/src/target-rust.mjs +42 -38
  67. package/src/target-scala.mjs +45 -35
  68. package/src/target-ts.mjs +37 -45
  69. package/src/target-types.mjs +41 -5
  70. package/src/target-util.mjs +55 -2
  71. package/src/term.mjs +89 -0
  72. package/src/trace-cli.mjs +58 -0
  73. package/src/trace-fs.mjs +76 -0
  74. package/src/trace.mjs +261 -0
  75. package/src/translate.d.mts +3 -0
  76. package/src/translate.mjs +62 -32
  77. package/src/try-cli.mjs +225 -0
  78. package/src/why-cli.mjs +41 -0
  79. package/src/why.d.mts +38 -0
  80. package/src/why.mjs +613 -0
  81. package/src/write-steps.mjs +22 -5
@@ -0,0 +1,572 @@
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 { percentDecimal } from './target-python.mjs';
22
+ import { firstLine } from './target-typescript.mjs';
23
+
24
+ export const ENGINES = ['python', 'thunder'];
25
+
26
+ /** Thrown by Give: carries the value back to the call. */
27
+ class Return { constructor(v) { this.v = v; } }
28
+
29
+ /** JavaScript ran out of stack before Thunder's own limit: the run is retried on a thread with a deeper stack. */
30
+ // Kept cheap on purpose: near the limit even a regular expression can run out of stack. A false alarm only means the
31
+ // run is repeated on the deep-stack thread, so any RangeError (or a regular expression's "Stack overflow") counts.
32
+ const nativeOverflow = (e) => { try { return e instanceof RangeError || (e instanceof SyntaxError && e.message.endsWith('Stack overflow')); } catch { return true; } };
33
+ class NeedsDeeperStack extends Error {}
34
+
35
+ const MAX_FRAMES = V.MAX_FRAMES;
36
+
37
+ /** The Python modules a program uses (Use), which this engine does not run. */
38
+ export function pythonModulesUsed(results) {
39
+ const out = [];
40
+ 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 });
41
+ return out;
42
+ }
43
+
44
+ /** The message for a program the engine will not run. */
45
+ export function refusalText(uses) {
46
+ const u = uses[0];
47
+ const more = uses.length > 1 ? ` (and ${uses.length - 1} more)` : '';
48
+ 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.`;
49
+ }
50
+
51
+ class Module {
52
+ constructor(result) { this.r = result; this.file = result.file; this.globals = new Map(); }
53
+ }
54
+
55
+ class Engine {
56
+ // readText(path, cwd): the text of a file the program reads, or throws with .code 'ENOENT' / 'EISDIR'. Without it
57
+ // (a browser), reading a file is reported as a missing file.
58
+ constructor({ cwd = '.', deeper = false, readText = null } = {}) {
59
+ this.cwd = cwd;
60
+ this.readText = readText;
61
+ // deeper: if JavaScript's own stack runs out, stop and say so (NeedsDeeperStack) instead of reporting it as the
62
+ // program's error, so the caller can run it again where the stack is deep enough.
63
+ this.deeper = deeper;
64
+ this.frames = [];
65
+ this.out = [];
66
+ }
67
+
68
+ // ── loading ─────────────────────────────────────────────────────────────────────────────────────────────────
69
+ load(result, imports = []) {
70
+ const mod = new Module(result);
71
+ const own = (s) => !result.info.imported?.has(s);
72
+ // from <src module> import *: everything the src module defines (functions, records, kept values).
73
+ for (const m of imports) for (const [k, v] of m.globals) mod.globals.set(k, v);
74
+ for (const r of result.info.records.filter(own)) mod.globals.set(r.py, this.recordClass(r, mod));
75
+ for (const f of result.info.funcs.filter(own)) mod.globals.set(f.py, { isFunc: true, f, mod });
76
+ const consts = result.info.consts.filter(own);
77
+ if (consts.length) {
78
+ const frame = { file: mod.file, line: 0 };
79
+ this.withFrame(frame, () => {
80
+ const env = { mod, locals: mod.globals, frame };
81
+ for (const k of consts) { frame.line = k.line; mod.globals.set(k.py, this.x(k.e, env)); }
82
+ });
83
+ }
84
+ return mod;
85
+ }
86
+
87
+ recordClass(r, mod) {
88
+ const rules = new Map();
89
+ 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); }
90
+ return { isRecord: true, py: r.py, fields: r.fields.map((f) => ({ py: f.py, type: f.type })), rules, mod };
91
+ }
92
+
93
+ // ── frames, lines, errors ───────────────────────────────────────────────────────────────────────────────────
94
+ withFrame(frame, fn) {
95
+ if (this.frames.length >= MAX_FRAMES) throw new PyErr('RecursionError', 'maximum recursion depth exceeded');
96
+ this.frames.push(frame);
97
+ try { return fn(); }
98
+ catch (e) {
99
+ if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
100
+ if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
101
+ const err = asPyErr(e);
102
+ if (!err.where) err.where = this.frames.map((f) => ({ file: f.file, line: f.line }));
103
+ throw err;
104
+ } finally { this.frames.pop(); }
105
+ }
106
+
107
+ describeError(e) { return V.describeError(e); }
108
+
109
+ // ── calls ───────────────────────────────────────────────────────────────────────────────────────────────────
110
+ call(fn, args) {
111
+ if (!fn?.isFunc) throw TypeErr(`'${fn === null ? 'NoneType' : typeof fn}' object is not callable`);
112
+ const { f, mod } = fn;
113
+ const frame = { file: mod.file, line: f.line };
114
+ if (this.frames.length >= MAX_FRAMES) {
115
+ // Python makes the new call's frame, then stops at its first line (a line with no Thunder mark, like the
116
+ // check for a default, leaves the error at the caller's line).
117
+ const err = new PyErr('RecursionError', 'maximum recursion depth exceeded');
118
+ const first = firstLine(f);
119
+ if (first != null) err.where = [...this.frames.map((x) => ({ file: x.file, line: x.line })), { file: mod.file, line: first }];
120
+ throw err;
121
+ }
122
+ return this.withFrame(frame, () => {
123
+ const locals = new Map();
124
+ const env = { mod, locals, frame };
125
+ f.params.forEach((p, i) => {
126
+ let v = i < args.length ? args[i] : (p.dflt ? (p.dflt.k === 'name' ? NOT_GIVEN : this.x(p.dflt, env)) : undefined);
127
+ if (v === undefined) throw TypeErr(`${f.py}() missing 1 required positional argument: '${p.py}'`);
128
+ locals.set(p.py, v);
129
+ });
130
+ 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)); }
131
+ for (const p of f.params) for (const rule of p.rules ?? []) { frame.line = p.line; this.never(rule, locals.get(p.py), env); }
132
+ try { this.block(f.body, env); }
133
+ catch (e) { if (e instanceof Return) return e.v; throw e; }
134
+ return null;
135
+ });
136
+ }
137
+
138
+ never(rule, value, env) { V.never(this.x(rule.rule.cond, env, { subject: value }), rule.text, rule.line, value); }
139
+
140
+ newRecord(cls, given) { return V.newRecordWith((o, k, v) => this.setAttr(o, k, v), cls, given); }
141
+
142
+ /** obj.name = value (a record checks its Never rules first, as its __setattr__ does). */
143
+ setAttr(obj, name, value) {
144
+ V.setAttrWith((rec) => {
145
+ const env = { mod: rec.cls.mod, locals: new Map(), frame: this.frames[this.frames.length - 1] };
146
+ for (const rule of rec.cls.rules.get(name) ?? []) this.never(rule, value, env);
147
+ }, obj, name, value);
148
+ }
149
+
150
+ getAttr(obj, name) { return V.getAttr(obj, name); }
151
+
152
+ // ── statements ──────────────────────────────────────────────────────────────────────────────────────────────
153
+ block(body, env) { for (const s of body) this.stmt(s, env); }
154
+
155
+ lookup(env, py) {
156
+ if (env.locals.has(py)) return env.locals.get(py);
157
+ if (env.mod.globals.has(py)) return env.mod.globals.get(py);
158
+ throw new PyErr('NameError', `name '${py}' is not defined`);
159
+ }
160
+
161
+ /** A name watched by a Never rule: the new value is checked before it is stored. */
162
+ assign(s, py, v, env) {
163
+ for (const rule of s.rules ?? []) this.never(rule, v, env);
164
+ env.locals.set(py, v);
165
+ }
166
+
167
+ rulesAfter(s, v, env) { for (const rule of s.rules ?? []) this.never(rule, v, env); }
168
+
169
+ /** Store into a name, a field, or an entry (a list position from 1, or a map key). */
170
+ store(t, v, env) {
171
+ if (t.k === 'name') { env.locals.set(t.ref?.py ?? 'unknown', v); return; }
172
+ if (t.k === 'field') {
173
+ const obj = this.x(t.obj, env);
174
+ if (t.static) this.setAttr(obj, t.py, v); else this.setField(obj, t.text, v);
175
+ return;
176
+ }
177
+ if (t.k === 'at') {
178
+ const obj = this.x(t.obj, env), key = this.x(t.key, env);
179
+ if (t.objKind === 'list') this.setItem(obj, key, v);
180
+ else if (t.objKind === 'map') this.mapSet(obj, key, v);
181
+ else this.setEntry(obj, key, v);
182
+ }
183
+ }
184
+
185
+ stmt(s, env) {
186
+ const L = s.line;
187
+ const fr = env.frame;
188
+ fr.line = L;
189
+ switch (s.k) {
190
+ case 'say': {
191
+ const v = this.x(s.e, env);
192
+ this.out.push(`${s.e.type?.k === 'text' ? pyStr(v) : show(v)}\n`);
193
+ return;
194
+ }
195
+ case 'set': {
196
+ const t = s.target;
197
+ const v = this.x(s.e, env);
198
+ if (t.k === 'name') { this.assign(s, t.ref.py, v, env); return; }
199
+ if (t.k === 'field') {
200
+ const obj = this.x(t.obj, env);
201
+ if (t.static) this.setAttr(obj, t.py, v); else this.setField(obj, t.text, v);
202
+ return;
203
+ }
204
+ this.storeAt(t, v, env);
205
+ return;
206
+ }
207
+ case 'give': throw new Return(s.e.k === 'nothing' ? null : this.x(s.e, env));
208
+ case 'stop': { const v = this.x(s.e, env); throw Stop(s.e.type?.k === 'text' ? pyStr(v) : show(v)); }
209
+ case 'if':
210
+ for (const b of s.branches) {
211
+ fr.line = b.line;
212
+ if (this.yn(b.cond, env)) { this.block(b.body, env); return; }
213
+ }
214
+ if (s.otherwise) this.block(s.otherwise, env);
215
+ return;
216
+ case 'each': {
217
+ const it = this.x(s.iter, env);
218
+ const [a, b] = s.vars;
219
+ let seq;
220
+ if (b) seq = s.iterKind === 'map' ? this.mapItems(it) : s.iterKind === 'pairs' ? pyIter(it) : this.pairsOf(it);
221
+ else seq = pyIter(it);
222
+ for (let i = 0; i < seq.length; i++) {
223
+ fr.line = L;
224
+ const el = seq[i];
225
+ if (b) { const [x, y] = this.unpack2(el); env.locals.set(a.py, x); env.locals.set(b.py, y); }
226
+ else env.locals.set(a.py, el);
227
+ this.block(s.body, env);
228
+ }
229
+ return;
230
+ }
231
+ case 'range': {
232
+ const from = this.x(s.from, env);
233
+ const to = s.to.k === 'num' && s.to.whole ? BigInt(s.to.text.replace(/_/g, '')) + 1n : add(this.x(s.to, env), 1n);
234
+ const lo = this.rangeInt(from), hi = this.rangeInt(to);
235
+ for (let i = lo; i < hi; i++) { fr.line = L; env.locals.set(s.v.py, i); this.block(s.body, env); }
236
+ return;
237
+ }
238
+ case 'while':
239
+ for (;;) {
240
+ fr.line = L;
241
+ const c = this.yn(s.cond, env);
242
+ if (s.until ? c : !c) return;
243
+ this.block(s.body, env);
244
+ }
245
+ case 'times': {
246
+ const n = this.rangeInt(this.x(s.count, env));
247
+ for (let i = 0n; i < n; i++) { fr.line = L; this.block(s.body, env); }
248
+ return;
249
+ }
250
+ case 'expect': return this.expect(s, env);
251
+ case 'add': case 'remove': return this.addRemove(s, env);
252
+ case 'increase': case 'decrease': {
253
+ const op = s.k === 'increase' ? add : sub;
254
+ if (s.target.k === 'name') {
255
+ const py = s.target.ref?.py ?? 'unknown';
256
+ const cur = this.lookup(env, py);
257
+ const v = op(cur, this.x(s.e, env));
258
+ if (s.rules?.length) { this.assign(s, py, v, env); return; }
259
+ env.locals.set(py, v);
260
+ return;
261
+ }
262
+ const cur = this.x(s.target, env);
263
+ this.store(s.target, op(cur, this.x(s.e, env)), env);
264
+ return;
265
+ }
266
+ case 'sort': {
267
+ const target = this.x(s.target, env);
268
+ if (!Array.isArray(target)) throw attrErr(target, 'sort');
269
+ const key = s.field ? this.keyFn(s.field, env) : null;
270
+ const sorted = pySort(target, key, !!s.desc);
271
+ target.splice(0, target.length, ...sorted);
272
+ return;
273
+ }
274
+ case 'reverse': {
275
+ const target = this.x(s.target, env);
276
+ if (!Array.isArray(target)) throw attrErr(target, 'reverse');
277
+ target.reverse();
278
+ return;
279
+ }
280
+ case 'do': this.x(s.e, env); return;
281
+ case 'tryFail':
282
+ try { this.stmt(s.stmt, env); }
283
+ catch (e) {
284
+ if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
285
+ if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
286
+ const err = asPyErr(e);
287
+ fr.line = L;
288
+ env.locals.set(s.errPy, explain(err));
289
+ this.block(s.handler, env);
290
+ }
291
+ return;
292
+ default: return;
293
+ }
294
+ }
295
+
296
+ storeAt(t, v, env) { this.store(t, v, env); }
297
+
298
+ addRemove(s, env) {
299
+ const v = this.x(s.e, env);
300
+ const isName = s.target.k === 'name';
301
+ const target = this.x(s.target, env);
302
+ const py = isName ? s.target.ref?.py ?? 'unknown' : null;
303
+ if (s.targetKind === 'list') { if (s.k === 'add') { if (!Array.isArray(target)) throw attrErr(target, 'append'); target.push(v); } else this.removeFrom(target, v); }
304
+ else if (s.targetKind === 'map') this.removeFrom(target, v);
305
+ else if (s.targetKind === 'number') {
306
+ const nv = (s.k === 'add' ? add : sub)(target, v);
307
+ if (isName && s.rules?.length) { this.assign(s, py, nv, env); return; }
308
+ if (isName) env.locals.set(py, nv); else this.store(s.target, nv, env);
309
+ } else if (s.k === 'add') {
310
+ const nv = this.addTo(target, v);
311
+ if (isName) env.locals.set(py, nv); else this.store(s.target, nv, env);
312
+ } else this.removeFrom(target, v);
313
+ if (isName) this.rulesAfter(s, this.lookup(env, py), env);
314
+ }
315
+
316
+ expect(s, env) {
317
+ const text = (s.raw ?? 'Expect').trim();
318
+ if (s.mode === 'true') { V.expectTrue(this.x(s.e, env), text); return; }
319
+ if (s.mode === 'fail') {
320
+ const msg = s.msg ? this.x(s.msg, env) : null;
321
+ // A JavaScript stack overflow is not the program failing: let it reach the deeper-stack retry.
322
+ V.expectFailure(() => {
323
+ try { this.x(s.e, env); }
324
+ catch (e) {
325
+ if (e instanceof Return) return;
326
+ if (e instanceof NeedsDeeperStack) throw e;
327
+ if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
328
+ throw e;
329
+ }
330
+ }, text, msg);
331
+ return;
332
+ }
333
+ const actual = this.x(s.e, env);
334
+ if (s.mode === 'cmp') { V.expectValue(actual, 'contains', 'contains', this.x(s.want, env), text); return; }
335
+ let c = s.check, negate = false;
336
+ if (c.k === 'not') { negate = true; c = c.e; }
337
+ let op, want = null;
338
+ const OPS = { '==': 'is', '!=': 'is not', '>=': 'at least', '<=': 'at most', '>': 'more than', '<': 'less than' };
339
+ if (c.k === 'cmp') { op = OPS[c.op]; want = this.x(c.r, env); }
340
+ else if (c.k === 'adj') op = c.adj;
341
+ else if (c.k === 'isNothing') op = c.neg ? 'not nothing' : 'nothing';
342
+ else if (c.k === 'between') { op = 'between'; want = [this.x(c.lo, env), this.x(c.hi, env)]; }
343
+ else if (c.k === 'contains') { op = 'in'; want = this.x(c.l, env); }
344
+ else op = 'is';
345
+ V.expectValue(actual, negate ? `not ${op}` : op, op, want, text);
346
+ }
347
+
348
+ // ── runtime helpers (shared with compiled TypeScript: engine-values.mjs) ────────────────────────────────────
349
+ yn(e, env, ctx) {
350
+ const v = this.x(e, env, ctx);
351
+ 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'));
352
+ return known ? v : yesNo(v);
353
+ }
354
+
355
+ rangeInt(v) { return V.rangeInt(v); }
356
+ unpack2(el) { return V.unpack2(el); }
357
+ mapItems(m) { return V.mapItems(m); }
358
+ pairsOf(c) { return V.pairsOf(c); }
359
+
360
+ keyFn(field, env) {
361
+ const frame = { file: env.frame.file, line: env.frame.line };
362
+ return (item) => this.withFrame(frame, () => (field.dynamic ? this.getField(item, field.key) : this.getAttr(item, field.py)));
363
+ }
364
+
365
+ itemAt(items, position, dflt) { return V.itemAt(items, position, dflt); }
366
+ setItem(items, position, value) { V.setItem(items, position, value); }
367
+ mapSet(m, k, v) { V.mapSet(m, k, v); }
368
+ setEntry(c, k, v) { V.setEntry(c, k, v); }
369
+ entry(c, k, dflt) { return V.entry(c, k, dflt); }
370
+ mapGet(m, k, dflt) { return V.mapGet(m, k, dflt); }
371
+ getField(obj, key) { return V.getField(obj, key); }
372
+ setField(obj, key, value) { V.setFieldWith((o, k, v) => this.setAttr(o, k, v), obj, key, value); }
373
+ addTo(target, value) { return V.addTo(target, value); }
374
+ removeFrom(target, value) { V.removeFrom(target, value); }
375
+
376
+ // ── expressions ─────────────────────────────────────────────────────────────────────────────────────────────
377
+ x(e, env, ctx = {}) {
378
+ const sub2 = (k) => this.x(k, env, ctx);
379
+ switch (e.k) {
380
+ case 'num': return e.whole ? BigInt(e.text.replace(/_/g, '')) : Dec.parse(e.text);
381
+ case 'money': return Money.of(e.text);
382
+ case 'percent': return Dec.parse(percentDecimal(e.text));
383
+ case 'bool': return !!e.v;
384
+ case 'nothing': case 'hole': return null;
385
+ case 'paren': return sub2(e.e);
386
+ case 'today': return PyDate.today();
387
+ case 'date': { const d = PyDate.parse(e.text); if (!d) throw new PyErr('ValueError', `Invalid isoformat string: '${e.text}'`); return d; }
388
+ case 'str': return this.str(e, env, ctx);
389
+ case 'list': return e.items ? e.items.map(sub2) : new PyDict();
390
+ case 'map': return new PyDict();
391
+ case 'name': {
392
+ const r = e.ref ?? {};
393
+ if (r.kind === 'subject') return ctx.subject ?? null;
394
+ if (r.kind === 'elemField') return this.getAttr(ctx.item, r.py);
395
+ if (r.kind === 'elemKey') return this.getField(ctx.item, r.key);
396
+ if (r.kind === 'elem') return ctx.item;
397
+ return this.lookup(env, r.py ?? e.name.replace(/ /g, '_'));
398
+ }
399
+ case 'call': { const fn = this.lookup(env, e.py); return this.call(fn, e.args.map(sub2)); }
400
+ case 'new': {
401
+ const cls = this.lookup(env, e.py);
402
+ const given = new Map();
403
+ for (const f of e.fields) given.set(f.py, sub2(f.e));
404
+ return this.newRecord(cls, given);
405
+ }
406
+ case 'field': { const obj = sub2(e.obj); return e.static ? this.getAttr(obj, e.py) : this.getField(obj, e.text); }
407
+ case 'at': {
408
+ const o = sub2(e.obj), k = sub2(e.key);
409
+ const d = e.dflt ? sub2(e.dflt) : undefined;
410
+ if (e.objKind === 'map') return this.mapGet(o, k, d);
411
+ if (e.objKind === 'list') return this.itemAt(o, k, d);
412
+ return this.entry(o, k, d);
413
+ }
414
+ case 'conv': {
415
+ const v = sub2(e.e);
416
+ switch (e.to) {
417
+ case 'list': return pyList(v);
418
+ case 'number': return V.toNumber(v);
419
+ case 'whole': return V.toWhole(v);
420
+ case 'money': return V.toMoney(v);
421
+ case 'text': return show(v);
422
+ case 'bool': return V.toYesNo(v);
423
+ case 'date': return V.toDate(v);
424
+ default: return v;
425
+ }
426
+ }
427
+ case 'where': {
428
+ const list = sub2(e.list);
429
+ return pyIter(list).filter((item) => truthy(this.x(e.cond, env, { ...ctx, item })));
430
+ }
431
+ case 'from': {
432
+ const inner = e.list.k === 'where' ? e.list : null;
433
+ const list = sub2(inner ? inner.list : e.list);
434
+ const pick = (item) => (e.field.dynamic ? this.getField(item, e.field.key) : this.getAttr(item, e.field.py));
435
+ return pyIter(list).filter((item) => !inner || truthy(this.x(inner.cond, env, { ...ctx, item }))).map(pick);
436
+ }
437
+ case 'sorted': {
438
+ const list = sub2(e.list);
439
+ if (e.mapSort) {
440
+ if (!(list instanceof PyDict)) throw attrErr(list, 'items');
441
+ const frame = { file: env.frame.file, line: env.frame.line };
442
+ return pySort(list.items(), (t) => this.withFrame(frame, () => t.items[e.by === 'key' ? 0 : 1]), !!e.desc);
443
+ }
444
+ return pySort(pyList(list), this.keyFn(e.field, env), !!e.desc);
445
+ }
446
+ case 'op': return this.op(e.op, sub2(e.arg));
447
+ case 'round': { const v = sub2(e.e); return e.places ? roundTo(v, sub2(e.places)) : roundTo(v); }
448
+ case 'readFile': return this.readFile(sub2(e.path));
449
+ case 'neg': return neg(sub2(e.e));
450
+ case 'not': return !this.yn(e.e, env, ctx);
451
+ case 'bin': {
452
+ if (e.op === 'and') return this.yn(e.l, env, ctx) && this.yn(e.r, env, ctx);
453
+ if (e.op === 'or') return this.yn(e.l, env, ctx) || this.yn(e.r, env, ctx);
454
+ const l = sub2(e.l), r = sub2(e.r);
455
+ if (e.op === '+') return add(l, r);
456
+ if (e.op === '-') return sub(l, r);
457
+ if (e.op === '*') return mul(l, r);
458
+ if (e.op === '/') return divide(l, r);
459
+ if (e.op === 'mod') return e.l.type?.k === 'whole' && e.r.type?.k === 'whole' ? intMod(l, r) : modulo(l, r);
460
+ throw new PyErr('NameError', `name '${e.op}' is not defined`);
461
+ }
462
+ case 'cmp': {
463
+ 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; }
464
+ return compare(e.op, sub2(e.l), sub2(e.r));
465
+ }
466
+ case 'between': { const lo = sub2(e.lo), v = sub2(e.e); if (!compare('<=', lo, v)) return false; return compare('<=', v, sub2(e.hi)); }
467
+ case 'contains': { const item = sub2(e.r); return contains(sub2(e.l), item); }
468
+ case 'affix': return V.affix(sub2(e.l), sub2(e.r), e.end);
469
+ case 'sortedValues': return pySort(pyList(sub2(e.list)), null, !!e.desc);
470
+ case 'joined': return V.joined(sub2(e.list), sub2(e.sep));
471
+ case 'splitAt': return V.splitAt(sub2(e.text), sub2(e.sep));
472
+ case 'replacing': return V.replacing(sub2(e.text), sub2(e.from), sub2(e.to));
473
+ case 'adj': {
474
+ const v = sub2(e.e);
475
+ if (e.adj === 'empty') return eq(pyLen(v), 0n);
476
+ return compare({ positive: '>', negative: '<', zero: '==' }[e.adj], v, 0n);
477
+ }
478
+ case 'isNothing': { const v = sub2(e.e); return e.neg ? v !== null : v === null; }
479
+ default: return null;
480
+ }
481
+ }
482
+
483
+ op(op, a) { return V.applyOp(op, a); }
484
+
485
+ readFile(path) { return V.readTextVia(this.readText, this.cwd, path); }
486
+
487
+ /** Text with {holes}: text and whole numbers as they are, anything else shown the Thunder way. */
488
+ str(e, env, ctx) {
489
+ return e.parts.map((p) => {
490
+ if (typeof p === 'string') return p;
491
+ const v = this.x(p.e, env, ctx);
492
+ const t = p.e.type?.k;
493
+ return t === 'text' || t === 'whole' ? pyStr(v) : show(v);
494
+ }).join('');
495
+ }
496
+
497
+ // ── running a program or its tests ──────────────────────────────────────────────────────────────────────────
498
+ runMain(mod) {
499
+ const main = mod.r.program.main ?? [];
500
+ if (!main.length) return;
501
+ const frame = { file: mod.file, line: 0 };
502
+ this.withFrame(frame, () => {
503
+ const env = { mod, locals: new Map(), frame };
504
+ try { this.block(main, env); } catch (e) { if (e instanceof Return) return; throw e; }
505
+ });
506
+ }
507
+
508
+ runTest(mod, t) {
509
+ const frame = { file: mod.file, line: t.line };
510
+ this.withFrame(frame, () => {
511
+ const env = { mod, locals: new Map(), frame };
512
+ try { this.block(t.body, env); } catch (e) { if (e instanceof Return) return; throw e; }
513
+ });
514
+ }
515
+ }
516
+
517
+
518
+ // ── public API ─────────────────────────────────────────────────────────────────────────────────────────────────
519
+
520
+ /** The same, on the calling thread (its stack allows only a few hundred nested calls). */
521
+ export function runInProcess({ entry, cwd, deeper = false, readText = null } = {}) {
522
+ const uses = pythonModulesUsed([entry]);
523
+ if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
524
+ const eng = new Engine({ cwd, deeper, readText });
525
+ let stderr = '', status = 0;
526
+ try {
527
+ const mod = eng.load(entry);
528
+ eng.runMain(mod);
529
+ } catch (e) {
530
+ if (e instanceof Return) { /* a Give outside a function ends the program */ }
531
+ else if (e instanceof NeedsDeeperStack || (deeper && nativeOverflow(e))) return { needsDeeperStack: true };
532
+ else { stderr = `${eng.describeError(asPyErr(e))}\n`; status = 1; }
533
+ }
534
+ return { status, stdout: eng.out.join(''), stderr };
535
+ }
536
+
537
+ /** The same, on the calling thread. */
538
+ export function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
539
+ const uses = pythonModulesUsed(results);
540
+ if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
541
+ const eng = new Engine({ cwd, deeper, readText });
542
+ const mods = [];
543
+ const srcMods = [];
544
+ for (const r of results) {
545
+ const mod = eng.load(r, r.kind === 'test' ? srcMods : []);
546
+ if (r.kind !== 'test') srcMods.push(mod);
547
+ mods.push(mod);
548
+ }
549
+ let passed = 0, failed = 0;
550
+ for (const mod of mods) {
551
+ for (const t of mod.r.info.tests) {
552
+ try {
553
+ eng.runTest(mod, t);
554
+ passed++;
555
+ eng.out.push(`PASS ${t.title} (${mod.file}, line ${t.line})\n`);
556
+ } catch (e) {
557
+ if (e instanceof NeedsDeeperStack || (deeper && nativeOverflow(e))) return { needsDeeperStack: true };
558
+ failed++;
559
+ eng.out.push(`FAIL ${t.title} (${mod.file}, line ${t.line})\n`, ` ${eng.describeError(asPyErr(e))}\n`);
560
+ }
561
+ }
562
+ }
563
+ const total = passed + failed;
564
+ eng.out.push(`${total} test${total === 1 ? '' : 's'}: ${passed} passed, ${failed} failed\n`);
565
+ return { status: failed ? 1 : 0, stdout: eng.out.join(''), stderr: '' };
566
+ }
567
+
568
+ /**
569
+ * Run a job on a worker thread with a large stack and wait for it: the program's results are copied to the
570
+ * worker (structured clone keeps the shared references the checker made), and the answer comes back the same way.
571
+ */
572
+ export { ThunderErr, PyErr };