@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,119 @@
1
+ // thunder_runtime.mjs, the runtime compiled TypeScript uses, and its declarations (thunder_runtime.d.mts).
2
+ //
3
+ // One meaning of Thunder: the runtime is engine-values.mjs, byte for byte (the same values, rules, and messages the
4
+ // Thunder engine uses), followed by a small Node part: call frames for error lines, output, reading files, and
5
+ // running the program or its tests. compiler/test/core-engines.mjs runs every Core test program on Python, the
6
+ // Thunder engine, and compiled TypeScript, and requires the same output from all three.
7
+ import { readFileSync } from 'node:fs';
8
+ import * as VALUES from './engine-values.mjs';
9
+
10
+ const VALUES_SOURCE = readFileSync(new URL('./engine-values.mjs', import.meta.url), 'utf8');
11
+
12
+ /** The Node part: everything here is about running, not about what a value means. */
13
+ const NODE_PART = `
14
+ // ── Running compiled TypeScript: frames (for error lines), output, files, and the program or its tests ───────────
15
+ import { readFileSync as nodeReadFile, realpathSync as nodeRealpath } from 'node:fs';
16
+ import { resolve as nodeResolve } from 'node:path';
17
+
18
+ const frames = [];
19
+ let aborted = false;
20
+ const snapshot = () => frames.map((f) => ({ file: f.file, line: f.line }));
21
+
22
+ /** A frame for a program, a test, or a kept value (as the engine's withFrame). */
23
+ export function enterFrame(file, line) {
24
+ if (frames.length >= MAX_FRAMES) throw new PyErr('RecursionError', 'maximum recursion depth exceeded');
25
+ const f = { file, line };
26
+ frames.push(f);
27
+ return f;
28
+ }
29
+ /** A frame for a call; \`first\` is the Thunder line the function starts on (where Python stops when it is too deep). */
30
+ export function enterCall(file, line, first) {
31
+ if (frames.length >= MAX_FRAMES) {
32
+ const err = new PyErr('RecursionError', 'maximum recursion depth exceeded');
33
+ if (first != null) err.where = [...snapshot(), { file, line: first }];
34
+ throw err;
35
+ }
36
+ const f = { file, line };
37
+ frames.push(f);
38
+ return f;
39
+ }
40
+ export function leave() { frames.pop(); }
41
+ /** The innermost frame (a record's Never rule runs in its caller's frame). */
42
+ export function topFrame() { return frames[frames.length - 1]; }
43
+ /** An error on its way out of a frame: remember where it happened (the innermost frames first seen). */
44
+ export function fail(e) { const err = asPyErr(e); if (!err.where) err.where = snapshot(); return err; }
45
+ function withFrame(frame, fn) {
46
+ if (frames.length >= MAX_FRAMES) throw new PyErr('RecursionError', 'maximum recursion depth exceeded');
47
+ frames.push(frame);
48
+ try { return fn(); } catch (e) { throw fail(e); } finally { frames.pop(); }
49
+ }
50
+ /** A key for sorting by a field: it runs in a frame at the sorting line, as the generated Python's lambda does. */
51
+ export function keyAt(F, get) { const frame = { file: F.file, line: F.line }; return (item) => withFrame(frame, () => get(item)); }
52
+
53
+ export function say(text) { process.stdout.write(\`\${text}\\n\`); }
54
+ export function readText(path) { return readTextVia((p, c) => nodeReadFile(nodeResolve(c, p), 'utf8'), process.cwd(), path); }
55
+
56
+ /** Records: their kind (name, fields, and Never rules), making one, and setting a field. */
57
+ export function recordKind(py, fields, rules = {}) { return { isRecord: true, py, fields, rules }; }
58
+ export function setAttr(obj, name, value) {
59
+ setAttrWith((rec) => { for (const r of rec.cls.rules[name] ?? []) never(r.cond(value), r.text, r.line, value); }, obj, name, value);
60
+ }
61
+ export function setField(obj, key, value) { setFieldWith(setAttr, obj, key, value); }
62
+ export function newRecord(cls, pairs) { return newRecordWith(setAttr, cls, new Map(pairs)); }
63
+
64
+ function report(e) { process.stderr.write(\`\${describeError(asPyErr(e))}\\n\`); process.exitCode = 1; aborted = true; }
65
+ /** Work out a file's kept values; an error stops the program with a Thunder message. */
66
+ export function init(file, fn) {
67
+ if (aborted) return;
68
+ const F = { file, line: 0 };
69
+ try { withFrame(F, () => fn(F)); } catch (e) { report(e); }
70
+ }
71
+ /** Is this module the one Node was asked to run? */
72
+ export function isEntry(url) {
73
+ const arg = process.argv[1];
74
+ if (!arg) return false;
75
+ const real = (p) => { try { return nodeRealpath(p); } catch { return p; } };
76
+ const strip = (p) => real(p).replace(/\\\\/g, '/').replace(/\\.(ts|mts|js|mjs)$/, '');
77
+ return strip(decodeURIComponent(new URL(url).pathname)) === strip(nodeResolve(arg));
78
+ }
79
+ export function run(main) { if (aborted) return; try { main(); } catch (e) { report(e); } }
80
+ /** Every Test block, the way run_tests.py runs them: one line per test, then the totals. */
81
+ export function runTests(modules) {
82
+ if (aborted) return;
83
+ let passed = 0, failed = 0;
84
+ for (const [file, tests] of modules) {
85
+ for (const [title, fn, line] of tests) {
86
+ try { fn(); passed++; say(\`PASS \${title} (\${file}, line \${line})\`); }
87
+ catch (e) { failed++; say(\`FAIL \${title} (\${file}, line \${line})\`); say(\` \${describeError(asPyErr(e))}\`); }
88
+ }
89
+ }
90
+ const total = passed + failed;
91
+ say(\`\${total} test\${total === 1 ? '' : 's'}: \${passed} passed, \${failed} failed\`);
92
+ if (failed) process.exitCode = 1;
93
+ }
94
+ `;
95
+
96
+ const NODE_EXPORTS = { functions: ['enterFrame', 'enterCall', 'leave', 'topFrame', 'fail', 'keyAt', 'say', 'readText', 'recordKind', 'setAttr', 'setField', 'newRecord', 'init', 'isEntry', 'run', 'runTests'] };
97
+
98
+ const HEADER = `// thunder_runtime.mjs: written by the Thunder compiler next to compiled TypeScript. Standard library only.
99
+ // The values and rules here are the Thunder engine's own (engine-values.mjs), so compiled TypeScript, the Thunder
100
+ // engine, and compiled Python say the same thing for the same program.
101
+ `;
102
+
103
+ export const TS_RUNTIME = `${HEADER}\n${VALUES_SOURCE.trimEnd()}\n${NODE_PART}`;
104
+
105
+ const isClass = (v) => typeof v === 'function' && /^class\b/.test(Function.prototype.toString.call(v));
106
+
107
+ /** Declarations for the runtime, made from its exports: every function takes and gives values of any kind. */
108
+ function declarations() {
109
+ const L = ['// thunder_runtime.d.mts: types for thunder_runtime.mjs (written by the Thunder compiler).', '// Thunder values are checked when the program runs; to TypeScript they are of any kind.', ''];
110
+ for (const [name, v] of Object.entries(VALUES).sort(([a], [b]) => a.localeCompare(b))) {
111
+ if (isClass(v)) L.push(`export declare class ${name} { constructor(...args: any[]); [key: string]: any; static [key: string]: any; }`);
112
+ else if (typeof v === 'function') L.push(`export declare function ${name}(...args: any[]): any;`);
113
+ else L.push(`export declare const ${name}: any;`);
114
+ }
115
+ for (const f of NODE_EXPORTS.functions) L.push(`export declare function ${f}(...args: any[]): any;`);
116
+ return `${L.join('\n')}\n`;
117
+ }
118
+
119
+ export const TS_RUNTIME_DTS = declarations();
@@ -0,0 +1,487 @@
1
+ // Thunder Core -> Python 3.10+.
2
+ //
3
+ // The generated code is meant to be read and used without Thunder: plain functions, dataclasses, and a small
4
+ // runtime file (thunder_runtime.py) that is written next to it. Every generated statement ends with
5
+ // `# thunder:N`, the line of the .thunder file it came from; the runtime uses those comments to report errors
6
+ // against Thunder lines.
7
+
8
+ const P = { or: 1, and: 2, not: 3, cmp: 4, add: 5, mul: 6, unary: 7, atom: 9 };
9
+ const wrap = (x, min) => (x.p < min ? `(${x.c})` : x.c);
10
+ const py = (s) => JSON.stringify(s); // a valid Python string literal for any text
11
+
12
+ export function percentDecimal(text) {
13
+ const [i, f = ''] = text.split('.');
14
+ const digits = (i + f).replace(/^0+(?=\d)/, '');
15
+ const pos = digits.length - f.length - 2;
16
+ if (pos <= 0) return `0.${'0'.repeat(-pos)}${digits}`;
17
+ return `${digits.slice(0, pos)}.${digits.slice(pos)}`;
18
+ }
19
+
20
+ const pyType = (t) => {
21
+ if (!t) return 'object';
22
+ switch (t.k) {
23
+ case 'whole': return 'int';
24
+ case 'number': return 'Decimal';
25
+ case 'money': return 'Money';
26
+ case 'text': return 'str';
27
+ case 'bool': return 'bool';
28
+ case 'date': return 'date';
29
+ case 'list': return 'list';
30
+ case 'map': return 'dict';
31
+ case 'record': return py(t.py ?? 'object');
32
+ case 'optional': { const inner = pyType(t.of); return inner.startsWith('"') ? `${inner.slice(0, -1)} | None"` : `${inner} | None`; }
33
+ default: return 'object';
34
+ }
35
+ };
36
+
37
+ const singular = (n) => (n.endsWith('ies') ? `${n.slice(0, -3)}y` : n.endsWith('ses') || n.endsWith('xes') ? n.slice(0, -2) : n.endsWith('s') && !n.endsWith('ss') ? n.slice(0, -1) : null);
38
+
39
+ export function toPython(program, info, { source = 'main.thunder', imports = [] } = {}) {
40
+ const g = new Gen(program, info, source);
41
+ return g.module(imports);
42
+ }
43
+
44
+ class Gen {
45
+ constructor(program, info, source) {
46
+ this.p = program; this.info = info; this.source = source;
47
+ this.out = []; this.ind = 0;
48
+ this.rt = new Set(['run']); this.needDecimal = false; this.needDate = false; this.needDataclass = false;
49
+ this.usedPy = new Set();
50
+ }
51
+ emit(text, line) { this.out.push(`${' '.repeat(this.ind)}${text}${line ? ` # thunder:${line}` : ''}`); }
52
+ blank() { while (this.out.length && this.out.slice(-2).join('|') !== '|') this.out.push(''); }
53
+ R(name) { this.rt.add(name); return name; }
54
+
55
+ module(srcModules) {
56
+ const body = [];
57
+ const top = this.p.body;
58
+ const own = (s) => !this.info.imported?.has(s);
59
+ // Records, functions, kept values, tests, main.
60
+ for (const r of this.info.records.filter(own)) { this.blank(); this.record(r); }
61
+ for (const f of this.info.funcs.filter(own)) { this.blank(); this.func(f); }
62
+ const consts = this.info.consts.filter(own);
63
+ if (consts.length) { this.blank(); for (const k of consts) this.emit(`${k.py} = ${this.x(k.e).c}`, k.line); }
64
+ const tests = this.info.tests;
65
+ for (const t of tests) {
66
+ this.blank();
67
+ this.emit(`def ${t.py}():`, t.line);
68
+ this.ind++; this.block(t.body); this.ind--;
69
+ }
70
+ if (tests.length) {
71
+ this.blank();
72
+ this.emit('THUNDER_TESTS = [');
73
+ for (const t of tests) this.emit(` (${py(t.title)}, ${t.py}, ${t.line}),`);
74
+ this.emit(']');
75
+ }
76
+ const main = this.p.main ?? [];
77
+ this.blank();
78
+ if (main.length) {
79
+ this.emit('def main():');
80
+ this.ind++; this.block(main); this.ind--;
81
+ this.blank();
82
+ this.emit('if __name__ == "__main__":');
83
+ this.emit(` ${this.R('run')}(main, __file__)`);
84
+ }
85
+ body.push(...this.out);
86
+
87
+ const head = [
88
+ `# Generated by the Thunder compiler from ${this.source}.`,
89
+ `# This file is a build artifact: change ${this.source.split('/').pop()} and build again, or keep this file and edit it as Python.`,
90
+ '# It needs only Python 3.10+ and thunder_runtime.py (written next to it). "# thunder:N" marks the Thunder line.',
91
+ '',
92
+ ];
93
+ if (this.needDataclass) head.push('from dataclasses import dataclass, field');
94
+ if (this.needDate) head.push('from datetime import date');
95
+ if (this.needDecimal) head.push('from decimal import Decimal');
96
+ for (const m of this.info.modules.filter(own)) head.push(m.module === m.py || (m.module.split('.')[0] === m.py && !m.module.includes('.')) ? `import ${m.module}` : `import ${m.module} as ${m.py}`);
97
+ head.push(`from thunder_runtime import ${[...this.rt].sort().join(', ')}`);
98
+ for (const m of srcModules) head.push(`from ${m} import *`);
99
+ head.push('', `THUNDER_SOURCE = ${py(this.source)}`, '', '');
100
+ return `${head.join('\n')}\n${body.join('\n').replace(/\n{4,}/g, '\n\n\n')}\n`;
101
+ }
102
+
103
+ record(r) {
104
+ this.needDataclass = true;
105
+ this.emit('@dataclass(kw_only=True)', r.line);
106
+ this.emit(`class ${r.py}:`, r.line);
107
+ this.ind++;
108
+ // Fields that may be left out come with a default (nothing, or an empty list or map).
109
+ for (const f of r.fields) {
110
+ const t = pyType(f.type);
111
+ if (t === 'Decimal') this.needDecimal = true;
112
+ if (t === 'Money') this.R('Money');
113
+ if (t === 'date') this.needDate = true;
114
+ const dflt = f.type.k === 'optional' ? ' = None' : f.type.k === 'list' ? ' = field(default_factory=list)' : f.type.k === 'map' ? ' = field(default_factory=dict)' : '';
115
+ this.emit(`${f.py}: ${t}${dflt}`, f.line);
116
+ }
117
+ if (!r.fields.length) this.emit('pass');
118
+ const rules = r.rulesToCheck ?? [];
119
+ if (rules.length) {
120
+ this.out.push('');
121
+ this.emit('def __setattr__(self, name, value):', rules[0].line);
122
+ this.ind++;
123
+ const bySubject = new Map();
124
+ 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); }
125
+ for (const [field, rs] of bySubject) {
126
+ this.emit(`if name == ${py(field)}:`);
127
+ this.ind++;
128
+ for (const rule of rs) this.emit(`${this.R('never')}(${this.x(rule.rule.cond, { subject: 'value' }).c}, ${py(rule.text)}, rule=${rule.line}, value=value)`, rule.line);
129
+ this.ind--;
130
+ }
131
+ this.emit('super().__setattr__(name, value)');
132
+ this.ind--;
133
+ }
134
+ this.ind--;
135
+ }
136
+
137
+ func(f) {
138
+ // A default: a fixed value in the signature; a kept value is filled in when the function is called (it may be
139
+ // written further down the file, and a kept value never changes, so this means the same).
140
+ const late = f.params.filter((p) => p.dflt?.k === 'name');
141
+ this.emit(`def ${f.py}(${f.params.map((p) => (p.dflt ? `${p.py}=${p.dflt.k === 'name' ? `${this.R('NOT_GIVEN')}` : this.x(p.dflt).c}` : p.py)).join(', ')}):`, f.line);
142
+ for (const p of late) this.emit(` if ${p.py} is ${this.R('NOT_GIVEN')}:\n ${p.py} = ${this.x(p.dflt).c}`, p.line);
143
+ this.ind++;
144
+ for (const p of f.params) for (const rule of p.rules ?? []) this.emit(`${this.R('never')}(${this.x(rule.rule.cond, { subject: p.py }).c}, ${py(rule.text)}, rule=${rule.line}, value=${p.py})`, p.line);
145
+ this.block(f.body);
146
+ this.ind--;
147
+ }
148
+
149
+ block(body) {
150
+ if (!body.length) { this.emit('pass'); return; }
151
+ for (const s of body) this.stmt(s);
152
+ }
153
+
154
+ // A name watched by a Never rule gets its new value checked before it is stored, so a refused change
155
+ // leaves the old value in place.
156
+ assign(s, name, value) {
157
+ if (!s.rules?.length) { this.emit(`${name} = ${value}`, s.line); return; }
158
+ const tmp = `new_${name}`;
159
+ this.emit(`${tmp} = ${value}`, s.line);
160
+ this.rulesAfter(s, tmp);
161
+ this.emit(`${name} = ${tmp}`, s.line);
162
+ }
163
+
164
+ rulesAfter(s, targetPy) {
165
+ for (const rule of s.rules ?? []) this.emit(`${this.R('never')}(${this.x(rule.rule.cond, { subject: targetPy }).c}, ${py(rule.text)}, rule=${rule.line}, value=${targetPy})`, s.line);
166
+ }
167
+
168
+ /** Store a value into a name, a field, or an entry (a list position from 1, or a map key). */
169
+ store(t, v, L) {
170
+ if (t.k === 'name') { this.emit(`${t.ref?.py ?? 'unknown'} = ${v}`, L); return; }
171
+ if (t.k === 'field') {
172
+ if (t.static) this.emit(`${wrap(this.x(t.obj), P.atom)}.${t.py} = ${v}`, L);
173
+ else this.emit(`${this.R('set_field')}(${this.x(t.obj).c}, ${py(t.text)}, ${v})`, L);
174
+ return;
175
+ }
176
+ if (t.k === 'at') {
177
+ if (t.objKind === 'list') this.emit(`${this.R('set_item')}(${this.x(t.obj).c}, ${this.x(t.key).c}, ${v})`, L);
178
+ else if (t.objKind === 'map') this.emit(`${wrap(this.x(t.obj), P.atom)}[${this.x(t.key).c}] = ${v}`, L);
179
+ else this.emit(`${this.R('set_entry')}(${this.x(t.obj).c}, ${this.x(t.key).c}, ${v})`, L);
180
+ }
181
+ }
182
+
183
+ lv(e) {
184
+ if (e.k === 'name') return e.ref?.py ?? 'unknown';
185
+ return this.x(e).c;
186
+ }
187
+
188
+ stmt(s) {
189
+ const L = s.line;
190
+ switch (s.k) {
191
+ case 'say': {
192
+ const v = this.x(s.e);
193
+ this.emit(`print(${s.e.type?.k === 'text' ? v.c : `${this.R('show')}(${v.c})`})`, L);
194
+ return;
195
+ }
196
+ case 'set': {
197
+ const t = s.target;
198
+ const v = this.x(s.e).c;
199
+ if (t.k === 'name') { this.assign(s, t.ref.py, v); return; }
200
+ if (t.k === 'field') {
201
+ if (t.static) this.emit(`${wrap(this.x(t.obj), P.atom)}.${t.py} = ${v}`, L);
202
+ else this.emit(`${this.R('set_field')}(${this.x(t.obj).c}, ${py(t.text)}, ${v})`, L);
203
+ return;
204
+ }
205
+ this.store(t, v, L);
206
+ return;
207
+ }
208
+ case 'give': this.emit(s.e.k === 'nothing' ? 'return None' : `return ${this.x(s.e).c}`, L); return;
209
+ case 'stop': this.emit(`raise ${this.R('Stop')}(${s.e.type?.k === 'text' ? this.x(s.e).c : `${this.R('show')}(${this.x(s.e).c})`})`, L); return;
210
+ case 'if':
211
+ s.branches.forEach((b, k) => {
212
+ this.emit(`${k === 0 ? 'if' : 'elif'} ${this.yn(b.cond).c}:`, b.line);
213
+ this.ind++; this.block(b.body); this.ind--;
214
+ });
215
+ if (s.otherwise) { this.emit('else:'); this.ind++; this.block(s.otherwise); this.ind--; }
216
+ return;
217
+ case 'each': {
218
+ const it = this.x(s.iter).c;
219
+ const [a, b] = s.vars;
220
+ if (b) this.emit(`for ${a.py}, ${b.py} in ${s.iterKind === 'map' ? `${wrap(this.x(s.iter), P.atom)}.items()` : s.iterKind === 'pairs' ? it : `${this.R('pairs_of')}(${it})`}:`, L);
221
+ else this.emit(`for ${a.py} in ${it}:`, L);
222
+ this.ind++; this.block(s.body); this.ind--;
223
+ return;
224
+ }
225
+ case 'range': {
226
+ const to = s.to.k === 'num' && s.to.whole ? String(Number(s.to.text) + 1) : `${wrap(this.x(s.to), P.add)} + 1`;
227
+ this.emit(`for ${s.v.py} in range(${this.x(s.from).c}, ${to}):`, L);
228
+ this.ind++; this.block(s.body); this.ind--;
229
+ return;
230
+ }
231
+ case 'while':
232
+ this.emit(`while ${s.until ? `not ${wrap(this.yn(s.cond), P.not)}` : this.yn(s.cond).c}:`, L);
233
+ this.ind++; this.block(s.body); this.ind--;
234
+ return;
235
+ case 'times':
236
+ this.emit(`for _ in range(${this.x(s.count).c}):`, L);
237
+ this.ind++; this.block(s.body); this.ind--;
238
+ return;
239
+ case 'expect': return this.expect(s);
240
+ case 'add': case 'remove': {
241
+ const v = this.x(s.e).c;
242
+ const target = this.lv(s.target);
243
+ if (s.targetKind === 'list') this.emit(s.k === 'add' ? `${target}.append(${v})` : `${this.R('remove_from')}(${target}, ${v})`, L);
244
+ else if (s.targetKind === 'map') this.emit(`${this.R('remove_from')}(${target}, ${v})`, L);
245
+ else if (s.targetKind === 'number') { if (s.target.k === 'name' && s.rules?.length) { this.assign(s, target, `${target} ${s.k === 'add' ? '+' : '-'} ${v}`); return; } this.emit(`${target} ${s.k === 'add' ? '+' : '-'}= ${v}`, L); }
246
+ else if (s.k === 'add') { if (s.target.k === 'name') this.emit(`${target} = ${this.R('add_to')}(${target}, ${v})`, L); else this.store(s.target, `${this.R('add_to')}(${target}, ${v})`, L); }
247
+ else this.emit(`${this.R('remove_from')}(${target}, ${v})`, L);
248
+ if (s.target.k === 'name') this.rulesAfter(s, target);
249
+ return;
250
+ }
251
+ case 'increase': case 'decrease': {
252
+ const target = this.lv(s.target);
253
+ if (s.target.k === 'name' && s.rules?.length) { this.assign(s, target, `${target} ${s.k === 'increase' ? '+' : '-'} ${wrap(this.x(s.e), P.add + 1)}`); return; }
254
+ if (s.target.k === 'name') { this.emit(`${target} ${s.k === 'increase' ? '+' : '-'}= ${this.x(s.e).c}`, L); return; }
255
+ // A field or an entry: read it, then store the new value (a dynamic field cannot be written with +=).
256
+ this.store(s.target, `${wrap(this.numv(s.target, { c: target, p: P.atom }), P.add)} ${s.k === 'increase' ? '+' : '-'} ${wrap(this.numv(s.e, this.x(s.e)), P.add + 1)}`, L);
257
+ return;
258
+ }
259
+ case 'sort': {
260
+ const target = this.x(s.target);
261
+ const key = s.field ? this.keyLambda(s.field) : null;
262
+ const args = [key ? `key=${key}` : null, s.desc ? 'reverse=True' : null].filter(Boolean).join(', ');
263
+ this.emit(`${wrap(target, P.atom)}.sort(${args})`, L);
264
+ return;
265
+ }
266
+ case 'reverse': this.emit(`${wrap(this.x(s.target), P.atom)}.reverse()`, L); return;
267
+ case 'do': this.emit(this.x(s.e).c, L); return;
268
+ case 'tryFail':
269
+ this.emit('try:', L);
270
+ this.ind++; this.stmt(s.stmt); this.ind--;
271
+ this.emit('except Exception as failure:', L);
272
+ this.ind++;
273
+ this.emit(`${s.errPy} = ${this.R('explain')}(failure)`, L);
274
+ this.block(s.handler);
275
+ this.ind--;
276
+ return;
277
+ default: this.emit(`pass # not generated: ${s.k}`, L);
278
+ }
279
+ }
280
+
281
+ expect(s) {
282
+ const L = s.line;
283
+ const text = py((s.raw ?? 'Expect').trim());
284
+ if (s.mode === 'true') { this.emit(`${this.R('expect_true')}(${this.x(s.e).c}, ${text})`, L); return; }
285
+ if (s.mode === 'fail') {
286
+ this.emit(`with ${this.R('expect_failure')}(${text}${s.msg ? `, ${this.x(s.msg).c}` : ''}):`, L);
287
+ this.ind++; this.emit(this.x(s.e).c, L); this.ind--;
288
+ return;
289
+ }
290
+ const actual = this.x(s.e).c;
291
+ if (s.mode === 'cmp') { this.emit(`${this.R('expect_value')}(${actual}, "contains", ${this.x(s.want).c}, ${text})`, L); return; }
292
+ let c = s.check, neg = '';
293
+ if (c.k === 'not') { neg = 'not '; c = c.e; }
294
+ const OPS = { '==': 'is', '!=': 'is not', '>=': 'at least', '<=': 'at most', '>': 'more than', '<': 'less than' };
295
+ let op, want = 'None';
296
+ if (c.k === 'cmp') { op = OPS[c.op]; want = this.x(c.r).c; }
297
+ else if (c.k === 'adj') op = c.adj;
298
+ else if (c.k === 'isNothing') op = c.neg ? 'not nothing' : 'nothing';
299
+ else if (c.k === 'between') { op = 'between'; want = `(${this.x(c.lo).c}, ${this.x(c.hi).c})`; }
300
+ else if (c.k === 'contains') { op = 'in'; want = this.x(c.l).c; }
301
+ else op = 'is';
302
+ this.emit(`${this.R('expect_value')}(${actual}, ${py(neg + op)}, ${want}, ${text})`, L);
303
+ }
304
+
305
+ // A name for the item in a list comprehension: the singular of the list's name when it is free, else "item".
306
+ itemVar(listExpr) {
307
+ const base = listExpr.k === 'name' && listExpr.ref?.py ? singular(listExpr.ref.py) : null;
308
+ const taken = (n) => !n || this.isTaken(n);
309
+ let n = !taken(base) ? base : 'item';
310
+ let k = 2;
311
+ while (this.isTaken(n)) n = `item${k++}`;
312
+ return n;
313
+ }
314
+ isTaken(n) {
315
+ if (this.stack?.includes(n)) return true;
316
+ if (!this.allPy) {
317
+ this.allPy = new Set();
318
+ const add = (s) => { if (s?.py) this.allPy.add(s.py); };
319
+ const visit = (body) => { for (const s of body ?? []) { if (s.k === 'set' && s.target.ref) this.allPy.add(s.target.ref.py); (s.vars ?? []).forEach(add); add(s.v); if (s.errPy) this.allPy.add(s.errPy); visit(s.body); visit(s.handler); visit(s.otherwise); (s.branches ?? []).forEach((b) => visit(b.body)); if (s.stmt) visit([s.stmt]); } };
320
+ for (const f of this.info.funcs) { add(f); f.params.forEach(add); visit(f.body); }
321
+ for (const r of this.info.records) add(r);
322
+ for (const c of this.info.consts) add(c);
323
+ for (const m of this.info.modules) add(m);
324
+ visit(this.p.main); for (const t of this.info.tests) visit(t.body);
325
+ }
326
+ return this.allPy.has(n);
327
+ }
328
+
329
+ keyLambda(field, v = 'item') {
330
+ if (field.dynamic) return `lambda ${v}: ${this.R('get_field')}(${v}, ${py(field.key)})`;
331
+ return `lambda ${v}: ${v}.${field.py}`;
332
+ }
333
+
334
+ fieldOf(v, field) { return field.dynamic ? `${this.R('get_field')}(${v}, ${py(field.key)})` : `${v}.${field.py}`; }
335
+
336
+ // ------------------------------------------------------------ expressions
337
+ /** A value whose kind is not known in advance, used in arithmetic or a comparison: a Python float becomes exact. */
338
+ numv(e, c) {
339
+ return ['whole', 'number', 'money', 'text', 'bool', 'list', 'map', 'record', 'date'].includes(e.type?.k) ? c : { c: `${this.R('num')}(${c.c})`, p: P.atom };
340
+ }
341
+
342
+ /** A value used as yes/no: checked at run time unless it is known to be yes/no (never Python's "truthy"). */
343
+ yn(e, ctx = {}) {
344
+ const c = this.x(e, ctx);
345
+ 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'));
346
+ return known ? c : { c: `${this.R('yes_no')}(${c.c})`, p: P.atom };
347
+ }
348
+
349
+ x(e, ctx = {}) {
350
+ const A = (c) => ({ c, p: P.atom });
351
+ const sub = (k) => this.x(k, ctx);
352
+ switch (e.k) {
353
+ // A whole number: Python refuses leading zeros (007), and Thunder means 7.
354
+ case 'num': if (e.whole) return A(e.text.replace(/^0+(?=\d)/, '')); this.needDecimal = true; return A(`Decimal(${py(e.text)})`);
355
+ case 'money': return A(`${this.R('Money')}(${py(e.text)})`);
356
+ case 'percent': this.needDecimal = true; return A(`Decimal(${py(percentDecimal(e.text))})`);
357
+ case 'bool': return A(e.v ? 'True' : 'False');
358
+ case 'nothing': return A('None');
359
+ case 'paren': return sub(e.e);
360
+ case 'today': this.needDate = true; return A('date.today()');
361
+ case 'date': this.needDate = true; return A(`date.fromisoformat(${py(e.text)})`);
362
+ case 'str': return A(this.str(e, ctx));
363
+ case 'list': return A(e.items ? `[${e.items.map((i) => sub(i).c).join(', ')}]` : '{}');
364
+ case 'map': return A('{}');
365
+ case 'name': {
366
+ const r = e.ref ?? {};
367
+ if (r.kind === 'subject') return A(ctx.subject ?? 'value');
368
+ if (r.kind === 'elemField') return A(`${ctx.item}.${r.py}`);
369
+ if (r.kind === 'elemKey') return A(`${this.R('get_field')}(${ctx.item}, ${py(r.key)})`);
370
+ if (r.kind === 'elem') return A(ctx.item);
371
+ return A(r.py ?? e.name.replace(/ /g, '_'));
372
+ }
373
+ case 'call': return A(`${e.py}(${e.args.map((a) => sub(a).c).join(', ')})`);
374
+ case 'new': return A(`${e.py}(${e.fields.map((f) => `${f.py}=${sub(f.e).c}`).join(', ')})`);
375
+ case 'field': return e.static ? A(`${wrap(sub(e.obj), P.atom)}.${e.py}`) : A(`${this.R('get_field')}(${sub(e.obj).c}, ${py(e.text)})`);
376
+ case 'at': {
377
+ const o = sub(e.obj), k = sub(e.key);
378
+ if (e.objKind === 'map') return A(e.dflt ? `${wrap(o, P.atom)}.get(${k.c}, ${sub(e.dflt).c})` : `${wrap(o, P.atom)}[${k.c}]`);
379
+ if (e.objKind === 'list') return A(`${this.R('item_at')}(${o.c}, ${k.c}${e.dflt ? `, ${sub(e.dflt).c}` : ''})`);
380
+ return A(`${this.R('entry')}(${o.c}, ${k.c}${e.dflt ? `, ${sub(e.dflt).c}` : ''})`);
381
+ }
382
+ case 'conv': {
383
+ if (e.to === 'list') return A(`list(${sub(e.e).c})`);
384
+ const fn = { number: 'to_number', whole: 'to_whole', money: 'to_money', text: 'to_text', bool: 'to_yes_no', date: 'to_date' }[e.to];
385
+ return A(`${this.R(fn)}(${sub(e.e).c})`);
386
+ }
387
+ case 'where': {
388
+ const v = this.itemVar(e.list);
389
+ return A(`[${v} for ${v} in ${sub(e.list).c} if ${this.withItem(v, () => this.x(e.cond, { ...ctx, item: v }).c)}]`);
390
+ }
391
+ case 'from': {
392
+ const inner = e.list.k === 'where' ? e.list : null;
393
+ const listE = inner ? inner.list : e.list;
394
+ const v = this.itemVar(listE);
395
+ const cond = inner ? ` if ${this.withItem(v, () => this.x(inner.cond, { ...ctx, item: v }).c)}` : '';
396
+ return A(`[${this.fieldOf(v, e.field)} for ${v} in ${sub(listE).c}${cond}]`);
397
+ }
398
+ case 'sorted': {
399
+ const rev = e.desc ? ', reverse=True' : '';
400
+ if (e.mapSort) return A(`sorted(${wrap(sub(e.list), P.atom)}.items(), key=lambda entry: entry[${e.by === 'key' ? 0 : 1}]${rev})`);
401
+ const v = this.itemVar(e.list);
402
+ return A(`sorted(${sub(e.list).c}, key=${this.keyLambda(e.field, v)}${rev})`);
403
+ }
404
+ case 'dot': return A(`${wrap(sub(e.obj), P.atom)}.${e.attr}${e.args ? `(${e.args.map((a) => sub(a).c).join(', ')})` : ''}`);
405
+ case 'op': {
406
+ const a = sub(e.arg);
407
+ switch (e.op) {
408
+ case 'sum': return A(`${this.R('total_of')}(${a.c})`);
409
+ case 'average': return A(`${this.R('average_of')}(${a.c})`);
410
+ case 'count': case 'length': return A(`len(${a.c})`);
411
+ case 'min': return A(`${this.R('smallest_of')}(${a.c})`);
412
+ case 'max': return A(`${this.R('largest_of')}(${a.c})`);
413
+ case 'first': return A(`${this.R('first_of')}(${a.c})`);
414
+ case 'last': return A(`${this.R('last_of')}(${a.c})`);
415
+ case 'words': return A(`${this.R('words_of')}(${a.c})`);
416
+ case 'lines': return A(`${wrap(a, P.atom)}.splitlines()`);
417
+ case 'lowercase': return A(`${wrap(a, P.atom)}.lower()`);
418
+ case 'uppercase': return A(`${wrap(a, P.atom)}.upper()`);
419
+ case 'trimmed': return A(`${wrap(a, P.atom)}.strip()`);
420
+ case 'parts': return A(`${this.R('parts_of')}(${a.c})`);
421
+ case 'abs': return A(`${this.R('absolute')}(${a.c})`);
422
+ case 'jsonText': return A(`${this.R('json_text')}(${a.c})`);
423
+ case 'jsonData': return A(`${this.R('json_data')}(${a.c})`);
424
+ case 'keys': return A(`list(${wrap(a, P.atom)}.keys())`);
425
+ case 'values': return A(`list(${wrap(a, P.atom)}.values())`);
426
+ default: return A(`${e.op}(${a.c})`);
427
+ }
428
+ }
429
+ case 'round': return A(`${this.R('round_to')}(${sub(e.e).c}${e.places ? `, ${sub(e.places).c}` : ''})`);
430
+ case 'readFile': return A(`${this.R('read_file')}(${sub(e.path).c})`);
431
+ case 'neg': return { c: `-${wrap(sub(e.e), P.unary)}`, p: P.unary };
432
+ case 'not': return { c: `not ${wrap(this.yn(e.e, ctx), P.not)}`, p: P.not };
433
+ case 'bin': {
434
+ const l = sub(e.l), r = sub(e.r);
435
+ if (e.op === 'and') { const a = this.yn(e.l, ctx), b = this.yn(e.r, ctx); return { c: `${wrap(a, P.and)} and ${wrap(b, P.and + 1)}`, p: P.and }; }
436
+ if (e.op === 'or') { const a = this.yn(e.l, ctx), b = this.yn(e.r, ctx); return { c: `${wrap(a, P.or)} or ${wrap(b, P.or + 1)}`, p: P.or }; }
437
+ if (e.op === '+' || e.op === '-') { const a = this.numv(e.l, l), b = this.numv(e.r, r); return { c: `${wrap(a, P.add)} ${e.op} ${wrap(b, P.add + 1)}`, p: P.add }; }
438
+ if (e.op === '*') { const a = this.numv(e.l, l), b = this.numv(e.r, r); return { c: `${wrap(a, P.mul)} * ${wrap(b, P.mul + 1)}`, p: P.mul }; }
439
+ if (e.op === '/') return A(`${this.R('divide')}(${l.c}, ${r.c})`);
440
+ if (e.op === 'mod') {
441
+ if (e.l.type?.k === 'whole' && e.r.type?.k === 'whole') return { c: `${wrap(l, P.mul)} % ${wrap(r, P.mul + 1)}`, p: P.mul };
442
+ return A(`${this.R('modulo')}(${l.c}, ${r.c})`);
443
+ }
444
+ return A(`${e.op}(${l.c}, ${r.c})`);
445
+ }
446
+ case 'cmp': {
447
+ const l = sub(e.l), r = sub(e.r);
448
+ if (e.r.k === 'bool' && (e.op === '==' || e.op === '!=')) return { c: `${wrap(this.yn(e.l, ctx), P.cmp + 1)} ${e.op === '==' ? 'is' : 'is not'} ${r.c}`, p: P.cmp };
449
+ return { c: `${wrap(this.numv(e.l, l), P.cmp + 1)} ${e.op} ${wrap(this.numv(e.r, r), P.cmp + 1)}`, p: P.cmp };
450
+ }
451
+ case 'between': return { c: `${wrap(sub(e.lo), P.cmp + 1)} <= ${wrap(sub(e.e), P.cmp + 1)} <= ${wrap(sub(e.hi), P.cmp + 1)}`, p: P.cmp };
452
+ case 'contains': return { c: `${wrap(sub(e.r), P.cmp + 1)} in ${wrap(sub(e.l), P.cmp + 1)}`, p: P.cmp };
453
+ case 'affix': return A(`${this.R(e.end ? 'ends_with' : 'starts_with')}(${sub(e.l).c}, ${sub(e.r).c})`);
454
+ case 'sortedValues': return A(`${this.R('sorted_values')}(${sub(e.list).c}${e.desc ? ', True' : ''})`);
455
+ case 'joined': return A(`${this.R('joined')}(${sub(e.list).c}, ${sub(e.sep).c})`);
456
+ case 'splitAt': return A(`${this.R('split_at')}(${sub(e.text).c}, ${sub(e.sep).c})`);
457
+ case 'replacing': return A(`${this.R('replacing')}(${sub(e.text).c}, ${sub(e.from).c}, ${sub(e.to).c})`);
458
+ case 'adj': {
459
+ const v = sub(e.e);
460
+ if (e.adj === 'empty') return { c: `len(${v.c}) == 0`, p: P.cmp };
461
+ return { c: `${wrap(v, P.cmp + 1)} ${{ positive: '>', negative: '<', zero: '==' }[e.adj]} 0`, p: P.cmp };
462
+ }
463
+ case 'isNothing': return { c: `${wrap(sub(e.e), P.cmp + 1)} ${e.neg ? 'is not' : 'is'} None`, p: P.cmp };
464
+ case 'hole': return A('None');
465
+ default: return A(`None # not generated: ${e.k}`);
466
+ }
467
+ }
468
+ withItem(v, fn) { (this.stack ??= []).push(v); try { return fn(); } finally { this.stack.pop(); } }
469
+
470
+ // Text with {holes} becomes an f-string; a value that is not text is shown the Thunder way (yes/no, $1.00, nothing).
471
+ str(e, ctx) {
472
+ if (e.parts.every((p) => typeof p === 'string')) return py(e.parts.join(''));
473
+ const holes = e.parts.map((p) => {
474
+ if (typeof p === 'string') return null;
475
+ const t = p.e.type?.k;
476
+ const c = this.x(p.e, ctx).c;
477
+ return t === 'text' || t === 'whole' ? c : `${this.R('show')}(${c})`;
478
+ });
479
+ const code = holes.filter(Boolean).join('');
480
+ const q = !code.includes('"') ? '"' : !code.includes("'") ? "'" : null;
481
+ if (q && !code.includes('\\')) {
482
+ const lit = (s) => py(s).slice(1, -1).replace(/\{/g, '{{').replace(/\}/g, '}}').replace(q === "'" ? /'/g : /(?!)/g, "\\'").replace(q === "'" ? /\\"/g : /(?!)/g, '"');
483
+ return `f${q}${e.parts.map((p, k) => (typeof p === 'string' ? lit(p) : `{${holes[k]}}`)).join('')}${q}`;
484
+ }
485
+ return e.parts.map((p, k) => (typeof p === 'string' ? py(p) : holes[k].startsWith('show(') ? holes[k] : `${this.R('show')}(${holes[k]})`)).join(' + ');
486
+ }
487
+ }