@skillstech/thunderlang 1.2.0 → 1.4.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 (63) hide show
  1. package/CHANGELOG.md +190 -0
  2. package/dist/core.cjs +6718 -1232
  3. package/dist/index.cjs +17490 -12204
  4. package/dist/learn.cjs +5866 -497
  5. package/package.json +6 -2
  6. package/src/cli-home.mjs +1 -1
  7. package/src/cli.mjs +54 -6
  8. package/src/core/ThunderRuntime.cs +1367 -0
  9. package/src/core/check.mjs +158 -2
  10. package/src/core/cli.mjs +148 -8
  11. package/src/core/csharp-run.mjs +184 -0
  12. package/src/core/diagnostics.mjs +13 -1
  13. package/src/core/engine-core.mjs +285 -2
  14. package/src/core/engine-values.mjs +1 -1
  15. package/src/core/format.mjs +191 -3
  16. package/src/core/go-run.mjs +106 -0
  17. package/src/core/index.mjs +2 -1
  18. package/src/core/java/thunder/T.java +6 -0
  19. package/src/core/java/thunder/ThunderRuntime.java +1374 -0
  20. package/src/core/java-run.mjs +89 -0
  21. package/src/core/parser.mjs +331 -5
  22. package/src/core/project.mjs +31 -6
  23. package/src/core/react-run.mjs +96 -0
  24. package/src/core/runtime-go/thunder_runtime.go +3038 -0
  25. package/src/core/runtime-react.mjs +133 -0
  26. package/src/core/rust/thunder_runtime.rs +1645 -0
  27. package/src/core/rust-run.mjs +192 -0
  28. package/src/core/screen-values.mjs +30 -0
  29. package/src/core/target-csharp.mjs +484 -0
  30. package/src/core/target-go.mjs +555 -0
  31. package/src/core/target-java.mjs +587 -0
  32. package/src/core/target-react.mjs +270 -0
  33. package/src/core/target-rust.mjs +534 -0
  34. package/src/core/target-typescript.mjs +2 -2
  35. package/src/core.d.ts +59 -0
  36. package/src/core.mjs +14 -0
  37. package/src/emit.mjs +1 -1
  38. package/src/faithful.mjs +34 -1
  39. package/src/flow/access.mjs +1451 -0
  40. package/src/flow/ts-parse.mjs +772 -0
  41. package/src/index.d.ts +3 -0
  42. package/src/index.mjs +3 -0
  43. package/src/libraries.mjs +32 -4
  44. package/src/model.mjs +72 -9
  45. package/src/passport-cli.mjs +101 -0
  46. package/src/passport-fs.d.mts +9 -0
  47. package/src/passport-fs.mjs +180 -0
  48. package/src/passport.d.mts +46 -0
  49. package/src/passport.mjs +255 -0
  50. package/src/program.d.mts +31 -0
  51. package/src/program.mjs +14 -0
  52. package/src/read-level.mjs +48 -2
  53. package/src/read-repo-fs.mjs +3 -1
  54. package/src/read.mjs +64 -5
  55. package/src/replay-cli.mjs +123 -0
  56. package/src/review.mjs +31 -3
  57. package/src/say-less.mjs +168 -13
  58. package/src/screens.mjs +833 -0
  59. package/src/steps.mjs +443 -20
  60. package/src/term.mjs +43 -0
  61. package/src/things-langs.mjs +20 -3
  62. package/src/write-across-cli.mjs +143 -0
  63. package/src/write-across.mjs +168 -0
@@ -0,0 +1,587 @@
1
+ // Thunder Core -> Java (17 or newer; the JDK only).
2
+ //
3
+ // The same checked program the Python target, the Thunder engine, and the TypeScript target use (compileCore ->
4
+ // program + info), and the same meaning: every statement does what the Thunder engine does for it, and every
5
+ // operation calls thunder.T, the Java runtime (java/thunder/ThunderRuntime.java), which follows the engine's own value
6
+ // code (engine-values.mjs) line for line. compiler/test/core-engines.mjs runs every Core test program on Python, the
7
+ // Thunder engine, compiled TypeScript, and compiled Java, and requires the same output from all of them.
8
+ //
9
+ // Every generated statement sets the frame's line (F.line = N) and ends with `// thunder:N`, the Thunder line it came
10
+ // from, so an error says which Thunder line failed, exactly as the others do.
11
+ //
12
+ // Java asks three things the other targets don't, and the code follows them plainly:
13
+ // - a lambda may use only names that never change, so a name a lambda uses (a "where" condition, an Expect that must
14
+ // fail, the high end of "between") is kept in a T.Box and read as name.v;
15
+ // - a statement after a return or a throw is an error, so such a step is wrapped in `if (true) { … }`;
16
+ // - there are no default inputs, so a function with defaults gets one short overload per number of inputs.
17
+
18
+ import { percentDecimal } from './target-python.mjs';
19
+ import { firstLine } from './target-typescript.mjs';
20
+
21
+ /** A Java string literal for any text (non-ASCII kept; control characters and lone surrogates escaped). */
22
+ export function javaString(s) {
23
+ let out = '"';
24
+ for (let i = 0; i < s.length; i++) {
25
+ const ch = s[i], c = s.charCodeAt(i);
26
+ if (ch === '"') out += '\\"';
27
+ else if (ch === '\\') out += '\\\\';
28
+ else if (ch === '\n') out += '\\n';
29
+ else if (ch === '\r') out += '\\r';
30
+ else if (ch === '\t') out += '\\t';
31
+ else if (c < 0x20 || c === 0x7f || (c >= 0xd800 && c <= 0xdfff)) {
32
+ // A surrogate pair stays a pair; a lone surrogate (or a control character) is written as an octal or \u escape.
33
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length && s.charCodeAt(i + 1) >= 0xdc00 && s.charCodeAt(i + 1) <= 0xdfff) { out += s[i] + s[i + 1]; i++; }
34
+ else out += `\\u${c.toString(16).padStart(4, '0')}`;
35
+ } else out += ch;
36
+ }
37
+ return `${out}"`;
38
+ }
39
+
40
+ const RESERVED = new Set(('abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while true false null var yield record sealed permits non-sealed exports module requires '
41
+ + 'T F FILE main thunderMain THUNDER_TESTS Object String BigInteger Runnable java app thunder').split(' '));
42
+ /** A Java name for a Thunder (Python) name: the same, unless Java or the generated code owns it. */
43
+ export const id = (py) => (RESERVED.has(py) ? `${py}_` : py);
44
+
45
+ /** The Java class for a module: main -> Main, tests_greet -> TestsGreet. */
46
+ export function javaClassName(module) {
47
+ const name = String(module).split(/[^A-Za-z0-9]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join('') || 'Program';
48
+ const safe = /^[0-9]/.test(name) ? `M${name}` : name;
49
+ return ['T', 'ThunderRuntime', 'RunTests'].includes(safe) ? `${safe}Module` : safe;
50
+ }
51
+
52
+ /** Thunder expression kinds the Java code writes as a boolean (a real Java condition). */
53
+ const BOOLEAN_KINDS = new Set(['bool', 'cmp', 'contains', 'between', 'adj', 'isNothing', 'not', 'affix']);
54
+ const isBooleanCode = (e) => BOOLEAN_KINDS.has(e.k) || (e.k === 'bin' && (e.op === 'and' || e.op === 'or'));
55
+
56
+ /** Every expression node under a node (types and name references are not expressions). */
57
+ function* nodesOf(n) {
58
+ if (!n || typeof n !== 'object') return;
59
+ if (Array.isArray(n)) { for (const x of n) yield* nodesOf(x); return; }
60
+ if (typeof n.k === 'string') yield n;
61
+ for (const [key, v] of Object.entries(n)) {
62
+ if (key === 'type' || key === 'ref' || key === 'info' || key === 'of') continue;
63
+ if (v && typeof v === 'object') yield* nodesOf(v);
64
+ }
65
+ }
66
+
67
+ /** The names a lambda in this body uses: the conditions of "where", the high end of "between", an Expect that fails. */
68
+ function capturedNames(body) {
69
+ const out = new Set();
70
+ const take = (e) => { for (const n of nodesOf(e)) if (n.k === 'name' && n.ref?.py && !['subject', 'elem', 'elemField', 'elemKey'].includes(n.ref.kind)) out.add(n.ref.py); };
71
+ const visitExpr = (e) => {
72
+ for (const n of nodesOf(e)) {
73
+ if (n.k === 'where') take(n.cond);
74
+ if (n.k === 'between') take(n.hi);
75
+ }
76
+ };
77
+ const visit = (ss) => {
78
+ for (const s of ss ?? []) {
79
+ for (const [key, v] of Object.entries(s)) {
80
+ if (['body', 'handler', 'otherwise', 'branches', 'stmt', 'rules', 'type', 'ref', 'vars', 'target'].includes(key)) continue;
81
+ if (v && typeof v === 'object') visitExpr(v);
82
+ }
83
+ if (s.target) visitExpr(s.target);
84
+ for (const b of s.branches ?? []) { visitExpr(b.cond); visit(b.body); }
85
+ if (s.k === 'expect' && s.mode === 'fail') take(s.e);
86
+ visit(s.body); visit(s.handler); visit(s.otherwise);
87
+ if (s.stmt) visit([s.stmt]);
88
+ }
89
+ };
90
+ visit(body);
91
+ return out;
92
+ }
93
+
94
+ /** Can this statement finish and let the next one run (Java's "can complete normally")? */
95
+ function completes(s) {
96
+ if (s.k === 'give' || s.k === 'stop') return false;
97
+ if (s.k === 'if') return !s.otherwise || s.branches.some((b) => blockCompletes(b.body)) || blockCompletes(s.otherwise);
98
+ if (s.k === 'tryFail') return completes(s.stmt) || blockCompletes(s.handler);
99
+ return true;
100
+ }
101
+ const blockCompletes = (body) => !body?.length || completes(body[body.length - 1]);
102
+
103
+ /**
104
+ * Compile one checked file to the Java class for `module`. `imports`: [{ module, names }] for a test file (the
105
+ * project's src modules it sees). Gives back the text of <Class>.java.
106
+ */
107
+ export function toJava(program, info, { source = 'main.thunder', module = 'main', imports = [], pkg = 'app' } = {}) {
108
+ return new Gen(program, info, source, module, imports, pkg).module();
109
+ }
110
+
111
+ class Gen {
112
+ constructor(program, info, source, module, imports, pkg) {
113
+ this.p = program; this.info = info; this.source = source; this.pkg = pkg;
114
+ this.cls = javaClassName(module);
115
+ this.out = []; this.ind = 0; this.tmp = 0;
116
+ this.boxed = new Set();
117
+ this.owner = new Map(); // a name a test file sees from a src file -> that file's class
118
+ for (const m of imports) for (const n of m.names) this.owner.set(n, javaClassName(m.module));
119
+ }
120
+ emit(text, line) { this.out.push(`${' '.repeat(this.ind)}${text}${line ? ` // thunder:${line}` : ''}`); }
121
+ blank() { if (this.out.length && this.out[this.out.length - 1] !== '') this.out.push(''); }
122
+ fresh(base) { return `$${base}${++this.tmp}`; }
123
+ /** A record, function, or kept value: this class's own, or a src file's (for a test file). */
124
+ global(py) { const o = this.owner.get(py); return o ? `${o}.${id(py)}` : id(py); }
125
+ /** A local name or input: name, or name.v when a lambda uses it. */
126
+ lv(py) { return this.boxed.has(py) ? `${id(py)}.v` : id(py); }
127
+
128
+ module() {
129
+ const own = (s) => !this.info.imported?.has(s);
130
+ const C = this.cls;
131
+ this.ind = 1;
132
+ for (const r of this.info.records.filter(own)) { this.blank(); this.record(r); }
133
+ const consts = this.info.consts.filter(own);
134
+ if (consts.length) {
135
+ this.blank();
136
+ for (const k of consts) this.emit(`public static Object ${id(k.py)};`, k.line);
137
+ this.emit('static {');
138
+ this.ind++;
139
+ this.emit('T.init(FILE, (T.Frame F) -> {');
140
+ this.ind++;
141
+ for (const k of consts) this.emit(`F.line = ${k.line}; ${id(k.py)} = ${this.x(k.e)};`, k.line);
142
+ this.ind--;
143
+ this.emit('});');
144
+ this.ind--;
145
+ this.emit('}');
146
+ }
147
+ for (const f of this.info.funcs.filter(own)) { this.blank(); this.func(f); }
148
+ const tests = this.info.tests;
149
+ for (const t of tests) {
150
+ this.blank();
151
+ this.emit(`static void ${id(t.py)}() {`, t.line);
152
+ this.ind++;
153
+ this.frameBody(`T.enterFrame(FILE, ${t.line})`, t.body, [], true, [], t.body);
154
+ this.ind--;
155
+ this.emit('}');
156
+ }
157
+ this.blank();
158
+ this.emit('public static final Object[][] THUNDER_TESTS = {');
159
+ for (const t of tests) this.emit(` { ${javaString(t.title)}, (Runnable) ${C}::${id(t.py)}, ${t.line} },`);
160
+ this.emit('};');
161
+ const main = this.p.main ?? [];
162
+ this.blank();
163
+ this.emit('public static void thunderMain() {');
164
+ this.ind++;
165
+ if (main.length) this.frameBody('T.enterFrame(FILE, 0)', main, [], true, [], main);
166
+ this.ind--;
167
+ this.emit('}');
168
+ this.blank();
169
+ this.emit('public static void main(String[] args) {');
170
+ this.emit(` T.run(${C}::thunderMain);`);
171
+ this.emit('}');
172
+ const head = [
173
+ `// Generated by the Thunder compiler from ${this.source}.`,
174
+ `// A build artifact: change ${this.source.split('/').pop()} and build again, or keep this file and edit it as Java.`,
175
+ '// It needs only Java 17+ and the thunder runtime (written next to it). "// thunder:N" marks the Thunder line.',
176
+ '',
177
+ `package ${this.pkg};`,
178
+ '',
179
+ 'import java.math.BigInteger;',
180
+ 'import thunder.T;',
181
+ '',
182
+ `public final class ${C} {`,
183
+ ` static final String FILE = ${javaString(this.source)};`,
184
+ ];
185
+ return `${head.join('\n')}\n${this.out.join('\n').replace(/\n{3,}/g, '\n\n')}\n}\n`;
186
+ }
187
+
188
+ record(r) {
189
+ const fields = r.fields.map((f) => `new T.Field(${javaString(f.py)}, ${javaString(f.type?.k ?? 'any')})`).join(', ');
190
+ const rules = r.rulesToCheck ?? [];
191
+ const head = `public static final T.RecordKind ${id(r.py)} = T.recordKind(${javaString(r.py)}, new T.Field[] { ${fields} }`;
192
+ if (!rules.length) { this.emit(`${head});`, r.line); return; }
193
+ this.emit(`${head}, T.rules(`, r.line);
194
+ this.ind++;
195
+ const bySubject = new Map();
196
+ for (const rule of rules) { const f = r.fieldMap.get(rule.subject); (bySubject.get(f.py) ?? bySubject.set(f.py, []).get(f.py)).push(rule); }
197
+ const entries = [...bySubject];
198
+ entries.forEach(([field, rs], k) => {
199
+ this.emit(`${javaString(field)}, new T.Rule[] {`);
200
+ this.ind++;
201
+ for (const rule of rs) this.emit(`new T.Rule((Object value) -> { final T.Frame F = T.topFrame(); return ${this.x(rule.rule.cond, { subject: 'value' })}; }, ${javaString(rule.text)}, ${rule.line}),`, rule.line);
202
+ this.ind--;
203
+ this.emit(`}${k < entries.length - 1 ? ',' : ''}`);
204
+ });
205
+ this.ind--;
206
+ this.emit('));');
207
+ }
208
+
209
+ func(f) {
210
+ const name = id(f.py);
211
+ // Defaults: a shorter overload for each input that may be left out, passing its fixed value (a kept value is
212
+ // filled in when the function runs: it may be written further down the file).
213
+ const required = f.params.filter((p) => !p.dflt).length;
214
+ for (let n = required; n < f.params.length; n++) {
215
+ const given = f.params.slice(0, n);
216
+ const rest = f.params.slice(n).map((p) => (p.dflt.k === 'name' ? 'T.NOT_GIVEN' : this.x(p.dflt)));
217
+ this.emit(`public static Object ${name}(${given.map((p) => `Object ${id(p.py)}`).join(', ')}) {`, f.line);
218
+ this.emit(` return ${name}(${[...given.map((p) => id(p.py)), ...rest].join(', ')});`);
219
+ this.emit('}');
220
+ }
221
+ const captured = capturedNames(f.body);
222
+ for (const p of f.params) for (const rule of p.rules ?? []) for (const n of nodesOf(rule.rule.cond)) if (n.k === 'between' || n.k === 'where') for (const m of nodesOf(n)) if (m.k === 'name' && m.ref?.py) captured.add(m.ref.py);
223
+ const boxedParams = f.params.filter((p) => captured.has(p.py));
224
+ this.emit(`public static Object ${name}(${f.params.map((p) => `Object ${boxedParams.includes(p) ? `$in_${p.py}` : id(p.py)}`).join(', ')}) {`, f.line);
225
+ this.ind++;
226
+ const pre = [];
227
+ for (const p of boxedParams) pre.push([`final T.Box ${id(p.py)} = new T.Box($in_${p.py});`, null]);
228
+ this.boxed = new Set(captured);
229
+ for (const p of f.params) if (p.dflt?.k === 'name') pre.push([`if (${this.lv(p.py)} == T.NOT_GIVEN) { F.line = ${p.line}; ${this.lv(p.py)} = ${this.x(p.dflt)}; }`, p.line]);
230
+ for (const p of f.params) for (const rule of p.rules ?? []) pre.push([`F.line = ${p.line}; T.never(${this.x(rule.rule.cond, { subject: this.lv(p.py) })}, ${javaString(rule.text)}, ${rule.line}, ${this.lv(p.py)});`, p.line]);
231
+ const first = firstLine(f);
232
+ this.frameBody(`T.enterCall(FILE, ${f.line}, ${first ?? 'null'})`, f.body, pre, false, f.params.map((p) => p.py), f.body, captured);
233
+ this.ind--;
234
+ this.emit('}');
235
+ }
236
+
237
+ /** A body that runs in its own frame: errors leave with the Thunder line they happened on. */
238
+ frameBody(enter, body, pre, isVoid, params = [], scanned = body, captured = capturedNames(scanned)) {
239
+ this.boxed = new Set(captured);
240
+ this.emit(`final T.Frame F = ${enter};`);
241
+ this.emit('try {');
242
+ this.ind++;
243
+ const locals = [...this.localsOf(body)].filter((n) => !params.includes(n));
244
+ const plain = locals.filter((n) => !this.boxed.has(n)), boxes = locals.filter((n) => this.boxed.has(n));
245
+ if (plain.length) this.emit(`Object ${plain.map((n) => `${id(n)} = null`).join(', ')};`);
246
+ for (const n of boxes) this.emit(`final T.Box ${id(n)} = new T.Box(null);`);
247
+ for (const [code, line] of pre) this.emit(code, line);
248
+ this.block(body, isVoid);
249
+ if (!isVoid && blockCompletes(body)) this.emit('return null;');
250
+ this.ind--;
251
+ this.emit('} catch (RuntimeException $e) { throw T.fail($e); } finally { T.leave(); }');
252
+ this.boxed = new Set();
253
+ }
254
+
255
+ /** The names a body assigns (Python's locals): declared once at the top, as a Python function's are. */
256
+ localsOf(body) {
257
+ const names = new Set();
258
+ const visit = (ss) => {
259
+ for (const s of ss ?? []) {
260
+ if (s.k === 'set' && s.target.k === 'name' && s.target.ref?.py) names.add(s.target.ref.py);
261
+ for (const v of s.vars ?? []) if (v?.py) names.add(v.py);
262
+ if (s.k === 'range' && s.v?.py) names.add(s.v.py);
263
+ if (s.errPy) names.add(s.errPy);
264
+ visit(s.body); visit(s.handler); visit(s.otherwise);
265
+ for (const b of s.branches ?? []) visit(b.body);
266
+ if (s.stmt) visit([s.stmt]);
267
+ }
268
+ };
269
+ visit(body);
270
+ const globals = new Set([...this.info.consts, ...this.info.funcs, ...this.info.records].map((x) => x.py));
271
+ return [...names].filter((n) => !globals.has(n));
272
+ }
273
+
274
+ /** Statements in order; one that cannot finish (a Give, a Stop) and has steps after it is wrapped for javac. */
275
+ block(body, isVoid) {
276
+ body.forEach((s, i) => {
277
+ if (i < body.length - 1 && !completes(s)) { this.emit('if (true) {'); this.ind++; this.stmt(s, isVoid); this.ind--; this.emit('}'); }
278
+ else this.stmt(s, isVoid);
279
+ });
280
+ }
281
+
282
+ /** F.line = N; <code> // thunder:N */
283
+ line(L, code) { this.emit(`F.line = ${L}; ${code}`, L); }
284
+
285
+ /** Check a watched name's Never rules on its new value, then store it. */
286
+ assign(s, name, valueCode) {
287
+ if (!s.rules?.length) { this.line(s.line, `${this.lv(name)} = ${valueCode};`); return; }
288
+ const v = this.fresh('new');
289
+ this.line(s.line, `{ Object ${v} = ${valueCode};`);
290
+ this.ind++;
291
+ for (const rule of s.rules) this.emit(`T.never(${this.x(rule.rule.cond, { subject: v })}, ${javaString(rule.text)}, ${rule.line}, ${v});`, s.line);
292
+ this.emit(`${this.lv(name)} = ${v}; }`, s.line);
293
+ this.ind--;
294
+ }
295
+ rulesAfter(s, name) {
296
+ for (const rule of s.rules ?? []) this.emit(`T.never(${this.x(rule.rule.cond, { subject: this.lv(name) })}, ${javaString(rule.text)}, ${rule.line}, ${this.lv(name)});`, s.line);
297
+ }
298
+
299
+ /** Code that stores `v` (a name of generated code) into a name, a field, or an entry. */
300
+ storeCode(t, v) {
301
+ if (t.k === 'name') return `${this.lv(t.ref?.py ?? 'unknown')} = ${v};`;
302
+ if (t.k === 'field') return t.static ? `T.setAttr(${this.x(t.obj)}, ${javaString(t.py)}, ${v});` : `T.setField(${this.x(t.obj)}, ${javaString(t.text)}, ${v});`;
303
+ if (t.k === 'at') {
304
+ const fn = t.objKind === 'list' ? 'T.setItem' : t.objKind === 'map' ? 'T.mapSet' : 'T.setEntry';
305
+ return `${fn}(${this.x(t.obj)}, ${this.x(t.key)}, ${v});`;
306
+ }
307
+ return '';
308
+ }
309
+
310
+ stmt(s, isVoid) {
311
+ const L = s.line;
312
+ switch (s.k) {
313
+ case 'say': this.line(L, `T.say(${s.e.type?.k === 'text' ? `T.pyStr(${this.x(s.e)})` : `T.show(${this.x(s.e)})`});`); return;
314
+ case 'set': {
315
+ const t = s.target;
316
+ if (t.k === 'name') { this.assign(s, t.ref.py, this.x(s.e)); return; }
317
+ const v = this.fresh('v');
318
+ this.line(L, `{ Object ${v} = ${this.x(s.e)}; ${this.storeCode(t, v)} }`);
319
+ return;
320
+ }
321
+ case 'give': this.line(L, isVoid ? 'return;' : `return ${s.e.k === 'nothing' ? 'null' : this.x(s.e)};`); return;
322
+ case 'stop': { const v = this.x(s.e); this.line(L, `throw T.Stop(${s.e.type?.k === 'text' ? `T.pyStr(${v})` : `T.show(${v})`});`); return; }
323
+ case 'if': {
324
+ this.emit(`F.line = ${L};`, L);
325
+ s.branches.forEach((b, k) => {
326
+ this.emit(`${k === 0 ? 'if' : '} else if'} (T.at(F, ${b.line}) && ${this.yn(b.cond)}) {`, b.line);
327
+ this.ind++; this.block(b.body, isVoid); this.ind--;
328
+ });
329
+ if (s.otherwise) { this.emit('} else {'); this.ind++; this.block(s.otherwise, isVoid); this.ind--; }
330
+ this.emit('}');
331
+ return;
332
+ }
333
+ case 'each': {
334
+ const [a, b] = s.vars;
335
+ const it = this.x(s.iter);
336
+ const seq = b ? (s.iterKind === 'map' ? `T.mapItems(${it})` : s.iterKind === 'pairs' ? `T.pyIter(${it})` : `T.pairsOf(${it})`) : `T.pyIter(${it})`;
337
+ const el = this.fresh('el');
338
+ this.line(L, `for (Object ${el} : T.loop(${seq})) {`);
339
+ this.ind++;
340
+ if (b) {
341
+ const pair = this.fresh('pair');
342
+ this.emit(`F.line = ${L}; java.util.List<Object> ${pair} = T.unpack2(${el}); ${this.lv(a.py)} = ${pair}.get(0); ${this.lv(b.py)} = ${pair}.get(1);`, L);
343
+ } else this.emit(`F.line = ${L}; ${this.lv(a.py)} = ${el};`, L);
344
+ this.block(s.body, isVoid);
345
+ this.ind--;
346
+ this.emit('}');
347
+ return;
348
+ }
349
+ case 'range': {
350
+ const lo = this.fresh('from'), hi = this.fresh('to'), n = this.fresh('n');
351
+ const to = s.to.k === 'num' && s.to.whole ? `T.i("${BigInt(s.to.text.replace(/_/g, '')) + 1n}")` : `T.add(${this.x(s.to)}, BigInteger.ONE)`;
352
+ const a = this.fresh('a'), b = this.fresh('b');
353
+ this.line(L, `{ Object ${a} = ${this.x(s.from)}, ${b} = ${to}; BigInteger ${lo} = T.rangeInt(${a}), ${hi} = T.rangeInt(${b});`);
354
+ this.ind++;
355
+ this.emit(`for (BigInteger ${n} = ${lo}; ${n}.compareTo(${hi}) < 0; ${n} = ${n}.add(BigInteger.ONE)) {`);
356
+ this.ind++;
357
+ this.emit(`F.line = ${L}; ${this.lv(s.v.py)} = ${n};`, L);
358
+ this.block(s.body, isVoid);
359
+ this.ind--;
360
+ this.emit('}');
361
+ this.ind--;
362
+ this.emit('}');
363
+ return;
364
+ }
365
+ case 'while':
366
+ this.emit(`while (T.at(F, ${L}) && ${s.until ? `!${this.yn(s.cond)}` : this.yn(s.cond)}) {`, L);
367
+ this.ind++; this.block(s.body, isVoid); this.ind--;
368
+ this.emit('}');
369
+ return;
370
+ case 'times': {
371
+ const count = this.fresh('count'), k = this.fresh('k');
372
+ this.line(L, `{ BigInteger ${count} = T.rangeInt(${this.x(s.count)});`);
373
+ this.ind++;
374
+ this.emit(`for (BigInteger ${k} = BigInteger.ZERO; ${k}.compareTo(${count}) < 0; ${k} = ${k}.add(BigInteger.ONE)) {`);
375
+ this.ind++;
376
+ this.emit(`F.line = ${L};`, L);
377
+ this.block(s.body, isVoid);
378
+ this.ind--;
379
+ this.emit('}');
380
+ this.ind--;
381
+ this.emit('}');
382
+ return;
383
+ }
384
+ case 'expect': this.expect(s); return;
385
+ case 'add': case 'remove': this.addRemove(s); return;
386
+ case 'increase': case 'decrease': {
387
+ const op = s.k === 'increase' ? 'T.add' : 'T.sub';
388
+ if (s.target.k === 'name') { const py = s.target.ref?.py ?? 'unknown'; this.assign(s, py, `${op}(${this.lv(py)}, ${this.x(s.e)})`); return; }
389
+ const v = this.fresh('v');
390
+ this.line(L, `{ Object ${v} = ${op}(${this.x(s.target)}, ${this.x(s.e)}); ${this.storeCode(s.target, v)} }`);
391
+ return;
392
+ }
393
+ case 'sort': {
394
+ const item = this.fresh('item');
395
+ const key = s.field ? `T.keyAt(F, (Object ${item}) -> ${this.fieldGet(item, s.field)})` : 'null';
396
+ this.line(L, `T.sortInPlace(${this.x(s.target)}, ${key}, ${!!s.desc});`);
397
+ return;
398
+ }
399
+ case 'reverse': this.line(L, `T.reverseInPlace(${this.x(s.target)});`); return;
400
+ case 'do': this.line(L, s.e.k === 'call' ? `${this.x(s.e)};` : `T.discard(${this.x(s.e)});`); return;
401
+ case 'tryFail': {
402
+ this.emit('try {', L);
403
+ this.ind++; this.stmt(s.stmt, isVoid); this.ind--;
404
+ const e = this.fresh('failure');
405
+ this.emit(`} catch (RuntimeException ${e}) {`, L);
406
+ this.ind++;
407
+ this.line(L, `${this.lv(s.errPy)} = T.explain(T.asPyErr(${e}));`);
408
+ this.block(s.handler, isVoid);
409
+ this.ind--;
410
+ this.emit('}');
411
+ return;
412
+ }
413
+ default: this.emit(`// not generated: ${s.k}`, L);
414
+ }
415
+ }
416
+
417
+ addRemove(s) {
418
+ const L = s.line;
419
+ const isName = s.target.k === 'name';
420
+ const py = isName ? s.target.ref?.py ?? 'unknown' : null;
421
+ const v = this.fresh('v'), t = this.fresh('t');
422
+ const head = `Object ${v} = ${this.x(s.e)}, ${t} = ${this.x(s.target)};`;
423
+ let body;
424
+ if (s.targetKind === 'list') body = s.k === 'add' ? `T.appendTo(${t}, ${v});` : `T.removeFrom(${t}, ${v});`;
425
+ else if (s.targetKind === 'map') body = `T.removeFrom(${t}, ${v});`;
426
+ else if (s.targetKind === 'number') {
427
+ const nv = `${s.k === 'add' ? 'T.add' : 'T.sub'}(${t}, ${v})`;
428
+ if (isName && s.rules?.length) {
429
+ const n = this.fresh('new');
430
+ this.line(L, `{ ${head} Object ${n} = ${nv};`);
431
+ this.ind++;
432
+ for (const rule of s.rules) this.emit(`T.never(${this.x(rule.rule.cond, { subject: n })}, ${javaString(rule.text)}, ${rule.line}, ${n});`, L);
433
+ this.emit(`${this.lv(py)} = ${n}; }`, L);
434
+ this.ind--;
435
+ this.rulesAfter(s, py);
436
+ return;
437
+ }
438
+ body = isName ? `${this.lv(py)} = ${nv};` : this.storeCode(s.target, nv);
439
+ } else if (s.k === 'add') body = isName ? `${this.lv(py)} = T.addTo(${t}, ${v});` : this.storeCode(s.target, `T.addTo(${t}, ${v})`);
440
+ else body = `T.removeFrom(${t}, ${v});`;
441
+ this.line(L, `{ ${head} ${body} }`);
442
+ if (isName) this.rulesAfter(s, py);
443
+ }
444
+
445
+ expect(s) {
446
+ const L = s.line;
447
+ const text = javaString((s.raw ?? 'Expect').trim());
448
+ if (s.mode === 'true') { this.line(L, `T.expectTrue(${this.x(s.e)}, ${text});`); return; }
449
+ if (s.mode === 'fail') {
450
+ const m = this.fresh('msg');
451
+ this.line(L, `{ Object ${m} = ${s.msg ? this.x(s.msg) : 'null'}; T.expectFailure(() -> T.discard(${this.x(s.e)}), ${text}, ${m}); }`);
452
+ return;
453
+ }
454
+ if (s.mode === 'cmp') { this.line(L, `T.expectValue(${this.x(s.e)}, "contains", "contains", ${this.x(s.want)}, ${text});`); return; }
455
+ let c = s.check, negate = false;
456
+ if (c.k === 'not') { negate = true; c = c.e; }
457
+ const OPS = { '==': 'is', '!=': 'is not', '>=': 'at least', '<=': 'at most', '>': 'more than', '<': 'less than' };
458
+ let op, want = 'null';
459
+ if (c.k === 'cmp') { op = OPS[c.op]; want = this.x(c.r); }
460
+ else if (c.k === 'adj') op = c.adj;
461
+ else if (c.k === 'isNothing') op = c.neg ? 'not nothing' : 'nothing';
462
+ else if (c.k === 'between') { op = 'between'; want = `T.list(${this.x(c.lo)}, ${this.x(c.hi)})`; }
463
+ else if (c.k === 'contains') { op = 'in'; want = this.x(c.l); }
464
+ else op = 'is';
465
+ this.line(L, `T.expectValue(${this.x(s.e)}, ${javaString(negate ? `not ${op}` : op)}, ${javaString(op)}, ${want}, ${text});`);
466
+ }
467
+
468
+ fieldGet(v, field) { return field.dynamic ? `T.getField(${v}, ${javaString(field.key)})` : `T.getAttr(${v}, ${javaString(field.py)})`; }
469
+
470
+ /** A value used as yes/no: a Java condition, checked to be yes/no when the program runs unless it is one already. */
471
+ yn(e, ctx = {}) {
472
+ const c = this.x(e, ctx);
473
+ return isBooleanCode(e) ? c : `T.yesNo(${c})`;
474
+ }
475
+
476
+ x(e, ctx = {}) {
477
+ const sub = (k) => this.x(k, ctx);
478
+ switch (e.k) {
479
+ case 'num': return e.whole ? `T.i("${BigInt(e.text.replace(/_/g, ''))}")` : `T.dec(${javaString(e.text)})`;
480
+ case 'money': return `T.money(${javaString(e.text)})`;
481
+ case 'percent': return `T.dec(${javaString(percentDecimal(e.text))})`;
482
+ case 'bool': return e.v ? 'true' : 'false';
483
+ case 'nothing': case 'hole': return 'null';
484
+ case 'paren': return sub(e.e);
485
+ case 'today': return 'T.today()';
486
+ case 'date': return `T.date(${javaString(e.text)})`;
487
+ case 'str': return this.str(e, ctx);
488
+ case 'list': return e.items ? `T.list(${e.items.map(sub).join(', ')})` : 'T.newMap()';
489
+ case 'map': return 'T.newMap()';
490
+ case 'name': {
491
+ const r = e.ref ?? {};
492
+ if (r.kind === 'subject') return ctx.subject ?? 'null';
493
+ if (r.kind === 'elemField') return `T.getAttr(${ctx.item}, ${javaString(r.py)})`;
494
+ if (r.kind === 'elemKey') return `T.getField(${ctx.item}, ${javaString(r.key)})`;
495
+ if (r.kind === 'elem') return ctx.item;
496
+ const py = r.py ?? e.name.replace(/ /g, '_');
497
+ if (this.boxed.has(py)) return `${id(py)}.v`;
498
+ return this.global(py);
499
+ }
500
+ case 'call': return `${this.global(e.py)}(${e.args.map(sub).join(', ')})`;
501
+ case 'new': return `T.newRecord(${[this.global(e.py), ...e.fields.flatMap((f) => [javaString(f.py), sub(f.e)])].join(', ')})`;
502
+ case 'field': return e.static ? `T.getAttr(${sub(e.obj)}, ${javaString(e.py)})` : `T.getField(${sub(e.obj)}, ${javaString(e.text)})`;
503
+ case 'at': {
504
+ const fn = e.objKind === 'map' ? 'T.mapGet' : e.objKind === 'list' ? 'T.itemAt' : 'T.entry';
505
+ return `${fn}(${sub(e.obj)}, ${sub(e.key)}${e.dflt ? `, ${sub(e.dflt)}` : ''})`;
506
+ }
507
+ case 'conv': {
508
+ const fn = { list: 'T.pyList', number: 'T.toNumber', whole: 'T.toWhole', money: 'T.toMoney', text: 'T.show', bool: 'T.toYesNo', date: 'T.toDate' }[e.to];
509
+ return fn ? `${fn}(${sub(e.e)})` : sub(e.e);
510
+ }
511
+ case 'where': {
512
+ const v = this.fresh('item');
513
+ return `T.filter(T.pyIter(${sub(e.list)}), (Object ${v}) -> T.truthy(${this.x(e.cond, { ...ctx, item: v })}))`;
514
+ }
515
+ case 'from': {
516
+ const inner = e.list.k === 'where' ? e.list : null;
517
+ const v = this.fresh('item'), w = this.fresh('item');
518
+ const list = `T.pyIter(${sub(inner ? inner.list : e.list)})`;
519
+ const filtered = inner ? `T.filter(${list}, (Object ${w}) -> T.truthy(${this.x(inner.cond, { ...ctx, item: w })}))` : list;
520
+ return `T.map(${filtered}, (Object ${v}) -> ${this.fieldGet(v, e.field)})`;
521
+ }
522
+ case 'sorted': {
523
+ const v = this.fresh('item');
524
+ if (e.mapSort) return `T.pySort(T.mapItems(${sub(e.list)}), T.keyAt(F, (Object ${v}) -> T.pairPart(${v}, ${e.by === 'key' ? 0 : 1})), ${!!e.desc})`;
525
+ return `T.pySort(T.pyList(${sub(e.list)}), T.keyAt(F, (Object ${v}) -> ${this.fieldGet(v, e.field)}), ${!!e.desc})`;
526
+ }
527
+ case 'op': return `T.applyOp(${javaString(e.op)}, ${sub(e.arg)})`;
528
+ case 'round': return `T.roundTo(${sub(e.e)}${e.places ? `, ${sub(e.places)}` : ''})`;
529
+ case 'readFile': return `T.readText(${sub(e.path)})`;
530
+ case 'neg': return `T.neg(${sub(e.e)})`;
531
+ case 'not': return `!${this.yn(e.e, ctx)}`;
532
+ case 'bin': {
533
+ if (e.op === 'and') return `(${this.yn(e.l, ctx)} && ${this.yn(e.r, ctx)})`;
534
+ if (e.op === 'or') return `(${this.yn(e.l, ctx)} || ${this.yn(e.r, ctx)})`;
535
+ const fn = { '+': 'T.add', '-': 'T.sub', '*': 'T.mul', '/': 'T.divide' }[e.op]
536
+ ?? (e.op === 'mod' ? (e.l.type?.k === 'whole' && e.r.type?.k === 'whole' ? 'T.intMod' : 'T.modulo') : null);
537
+ return fn ? `${fn}(${sub(e.l)}, ${sub(e.r)})` : 'null';
538
+ }
539
+ case 'cmp': {
540
+ if (e.r.k === 'bool' && (e.op === '==' || e.op === '!=')) return `(${this.yn(e.l, ctx)} ${e.op} ${sub(e.r)})`;
541
+ return `T.compare(${javaString(e.op)}, ${sub(e.l)}, ${sub(e.r)})`;
542
+ }
543
+ case 'between': return `T.between(${sub(e.lo)}, ${sub(e.e)}, () -> ${sub(e.hi)})`;
544
+ case 'contains': return `T.isIn(${sub(e.r)}, ${sub(e.l)})`;
545
+ case 'affix': return `T.affix(${sub(e.l)}, ${sub(e.r)}, ${!!e.end})`;
546
+ case 'sortedValues': return `T.pySort(T.pyList(${sub(e.list)}), null, ${!!e.desc})`;
547
+ case 'joined': return `T.joined(${sub(e.list)}, ${sub(e.sep)})`;
548
+ case 'splitAt': return `T.splitAt(${sub(e.text)}, ${sub(e.sep)})`;
549
+ case 'replacing': return `T.replacing(${sub(e.text)}, ${sub(e.from)}, ${sub(e.to)})`;
550
+ case 'adj': {
551
+ if (e.adj === 'empty') return `T.eq(T.pyLen(${sub(e.e)}), BigInteger.ZERO)`;
552
+ return `T.compare(${javaString({ positive: '>', negative: '<', zero: '==' }[e.adj])}, ${sub(e.e)}, BigInteger.ZERO)`;
553
+ }
554
+ case 'isNothing': return `(${sub(e.e)} ${e.neg ? '!=' : '=='} null)`;
555
+ default: return `null /* not generated: ${e.k} */`;
556
+ }
557
+ }
558
+
559
+ /** Text with {holes}: text and whole numbers as they are, anything else shown the Thunder way. */
560
+ str(e, ctx) {
561
+ const parts = e.parts.filter((p) => p !== '').map((p) => {
562
+ if (typeof p === 'string') return javaString(p);
563
+ const t = p.e.type?.k;
564
+ return t === 'text' || t === 'whole' ? `T.pyStr(${this.x(p.e, ctx)})` : `T.show(${this.x(p.e, ctx)})`;
565
+ });
566
+ if (!parts.length) return '""';
567
+ if (parts.length === 1) return parts[0];
568
+ return `(${parts.join(' + ')})`;
569
+ }
570
+ }
571
+
572
+ /** A module's runner for its project's tests: RunTests.java. */
573
+ export function javaTestRunner(results, pkg = 'app') {
574
+ return [
575
+ '// Generated by the Thunder compiler: runs every Test block in this project.',
576
+ `package ${pkg};`,
577
+ '',
578
+ 'import thunder.T;',
579
+ '',
580
+ 'public final class RunTests {',
581
+ ' public static void main(String[] args) {',
582
+ ` T.runTests(new Object[][] { ${results.map((r) => `{ ${javaString(r.file)}, ${javaClassName(r.module)}.THUNDER_TESTS }`).join(', ')} });`,
583
+ ' }',
584
+ '}',
585
+ '',
586
+ ].join('\n');
587
+ }