@skillstech/thunderlang 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +212 -0
  2. package/README.md +4 -1
  3. package/dist/core.cjs +2080 -278
  4. package/dist/index.cjs +12742 -10943
  5. package/dist/learn.cjs +12976 -3598
  6. package/package.json +2 -2
  7. package/src/cli-home.mjs +242 -0
  8. package/src/cli.mjs +135 -41
  9. package/src/core/ThunderRuntime.cs +1367 -0
  10. package/src/core/check.mjs +158 -2
  11. package/src/core/cli.mjs +208 -17
  12. package/src/core/csharp-run.mjs +184 -0
  13. package/src/core/diagnostics.mjs +13 -0
  14. package/src/core/engine-core.mjs +855 -0
  15. package/src/core/engine-values.mjs +1054 -0
  16. package/src/core/engine-worker.mjs +15 -0
  17. package/src/core/engine.mjs +63 -0
  18. package/src/core/format.mjs +191 -3
  19. package/src/core/go-run.mjs +106 -0
  20. package/src/core/index.mjs +3 -1
  21. package/src/core/java/thunder/T.java +6 -0
  22. package/src/core/java/thunder/ThunderRuntime.java +1374 -0
  23. package/src/core/java-run.mjs +89 -0
  24. package/src/core/parser.mjs +331 -5
  25. package/src/core/project.mjs +43 -8
  26. package/src/core/react-run.mjs +96 -0
  27. package/src/core/runtime-go/thunder_runtime.go +3038 -0
  28. package/src/core/runtime-react.mjs +133 -0
  29. package/src/core/runtime-typescript.mjs +119 -0
  30. package/src/core/rust/thunder_runtime.rs +1645 -0
  31. package/src/core/rust-run.mjs +192 -0
  32. package/src/core/screen-values.mjs +30 -0
  33. package/src/core/target-csharp.mjs +484 -0
  34. package/src/core/target-go.mjs +555 -0
  35. package/src/core/target-java.mjs +587 -0
  36. package/src/core/target-python.mjs +2 -1
  37. package/src/core/target-react.mjs +270 -0
  38. package/src/core/target-rust.mjs +534 -0
  39. package/src/core/target-typescript.mjs +466 -0
  40. package/src/core/typescript-run.mjs +114 -0
  41. package/src/core.d.ts +18 -0
  42. package/src/core.mjs +1 -0
  43. package/src/emit.mjs +1 -1
  44. package/src/faithful.mjs +30 -0
  45. package/src/learn-lessons.mjs +245 -1
  46. package/src/learn.d.mts +8 -0
  47. package/src/learn.mjs +40 -4
  48. package/src/libraries.mjs +10 -3
  49. package/src/model.mjs +50 -8
  50. package/src/read-level.mjs +192 -0
  51. package/src/read-repo-fs.mjs +3 -1
  52. package/src/read.mjs +28 -5
  53. package/src/replay-cli.mjs +123 -0
  54. package/src/say-less.mjs +152 -11
  55. package/src/screens.mjs +833 -0
  56. package/src/steps.mjs +430 -19
  57. package/src/term.mjs +132 -0
  58. package/src/try-cli.mjs +225 -0
  59. package/src/why-cli.mjs +17 -7
  60. package/src/why.d.mts +17 -7
  61. package/src/why.mjs +114 -33
@@ -0,0 +1,555 @@
1
+ // Thunder Core -> Go (one `main` package; standard library 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 TypeScript target writes for it, and every
5
+ // operation calls thunder/thunder_runtime.go, a Go port of the engine's own value code (engine-values.mjs).
6
+ // compiler/test/core-engines.mjs runs every Core test program on Python, the Thunder engine, TypeScript, and Go, and
7
+ // 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 other targets do. A Thunder error is a Go panic
11
+ // with a *T.Err; each frame records where it happened on the way out (defer T.Exit(recover())).
12
+
13
+ import { percentDecimal } from './target-python.mjs';
14
+ import { firstLine } from './target-typescript.mjs';
15
+
16
+ /** A Go string literal for any text. */
17
+ export function goStr(s) {
18
+ let out = '"';
19
+ for (const ch of String(s)) {
20
+ const cp = ch.codePointAt(0);
21
+ if (ch === '"') out += '\\"';
22
+ else if (ch === '\\') out += '\\\\';
23
+ else if (ch === '\n') out += '\\n';
24
+ else if (ch === '\r') out += '\\r';
25
+ else if (ch === '\t') out += '\\t';
26
+ else if (cp < 0x20 || cp === 0x7f) out += `\\x${cp.toString(16).padStart(2, '0')}`;
27
+ else if (cp >= 0xd800 && cp <= 0xdfff) out += '\\uFFFD';
28
+ else out += ch;
29
+ }
30
+ return `${out}"`;
31
+ }
32
+
33
+ // Go's keywords and the names the generated code or Go itself owns.
34
+ const RESERVED = new Set(('break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var '
35
+ + 'T F main init append cap close complex copy delete imag len make new panic print println real recover bool byte error float32 float64 int int8 int16 int32 int64 rune string uint uint8 uint16 uint32 uint64 uintptr true false nil iota any comparable').split(' '));
36
+ /** A Go name for a Thunder (Python) name: the same, unless Go or the generated code owns it. */
37
+ export const id = (py) => (RESERVED.has(py) || /^_/.test(py) ? `${py}_` : py);
38
+
39
+ const KNOWN_BOOL = new Set(['cmp', 'contains', 'between', 'adj', 'isNothing', 'not', 'bool']);
40
+
41
+ /** Thunder modules a program uses that only Python has (Use): compiled Go cannot call them. */
42
+ export function pythonOnlyUses(info) {
43
+ return (info.modules ?? []).filter((m) => !info.imported?.has(m)).map((m) => ({ module: m.module, line: m.line }));
44
+ }
45
+
46
+ /**
47
+ * Compile one checked file to the text of <module>.go. `ns` names every module-level thing in the program:
48
+ * ns.name(py) -> the Go name (records, functions, kept values this file defines or sees), ns.params(py) -> how many
49
+ * inputs a function takes.
50
+ */
51
+ export function toGo(program, info, { source = 'main.thunder', module = 'main', ns }) {
52
+ return new Gen(program, info, source, module, ns).module();
53
+ }
54
+
55
+ class Gen {
56
+ constructor(program, info, source, module, ns) {
57
+ this.p = program; this.info = info; this.source = source; this.mod = module; this.ns = ns;
58
+ this.out = []; this.ind = 0; this.tmp = 0;
59
+ this.file = `file_${module}`;
60
+ this.scope = new Set(); // the names of the function being written (its inputs and locals)
61
+ this.closures = []; // the "If this fails" closures a Give is inside (innermost last): { ret, flag, isVoid }
62
+ }
63
+ emit(text, line) { this.out.push(`${'\t'.repeat(this.ind)}${text}${line ? ` // thunder:${line}` : ''}`); }
64
+ blank() { if (this.out.length && this.out[this.out.length - 1] !== '') this.out.push(''); }
65
+ fresh(base) { return `_${base}${++this.tmp}`; }
66
+ g(py) { return this.ns.name(py); }
67
+
68
+ module() {
69
+ const own = (s) => !this.info.imported?.has(s);
70
+ const head = [
71
+ `// Generated by the Thunder compiler from ${this.source}.`,
72
+ `// A build artifact: change ${this.source.split('/').pop()} and build again, or keep this file and edit it as Go.`,
73
+ '// It needs only Go and thunder/thunder_runtime.go (written next to it). "// thunder:N" marks the Thunder line.',
74
+ '',
75
+ 'package main',
76
+ '',
77
+ 'import T "thunderprogram/thunder"',
78
+ '',
79
+ `const ${this.file} = ${goStr(this.source)}`,
80
+ ];
81
+ const records = this.info.records.filter(own);
82
+ for (const r of records) { this.blank(); this.record(r); }
83
+ const ruled = records.filter((r) => (r.rulesToCheck ?? []).length);
84
+ if (ruled.length) {
85
+ this.blank();
86
+ this.emit('func init() {');
87
+ this.ind++;
88
+ for (const r of ruled) this.recordRules(r);
89
+ this.ind--;
90
+ this.emit('}');
91
+ }
92
+ for (const f of this.info.funcs.filter(own)) { this.blank(); this.func(f); }
93
+ const consts = this.info.consts.filter(own);
94
+ this.blank();
95
+ for (const k of consts) this.emit(`var ${this.g(k.py)} T.V`, k.line);
96
+ this.emit(`// The kept values of ${this.source}, worked out when the program starts.`);
97
+ this.emit(`func keep_${this.mod}() {`);
98
+ this.ind++;
99
+ if (consts.length) {
100
+ this.emit(`T.Init(${this.file}, func(F *T.Frame) {`);
101
+ this.ind++;
102
+ for (const k of consts) this.emit(`F.Line = ${k.line}; ${this.g(k.py)} = ${this.x(k.e)}`, k.line);
103
+ this.ind--;
104
+ this.emit('})');
105
+ }
106
+ this.ind--;
107
+ this.emit('}');
108
+ const tests = this.info.tests;
109
+ for (const t of tests) {
110
+ this.blank();
111
+ this.emit(`func ${this.testName(t)}() {`, t.line);
112
+ this.ind++;
113
+ this.frameBody(`T.EnterFrame(${this.file}, ${t.line})`, t.body, [], true);
114
+ this.ind--;
115
+ this.emit('}');
116
+ }
117
+ this.blank();
118
+ this.emit(`var tests_${this.mod} = []T.Test{`);
119
+ for (const t of tests) this.emit(`\t{Title: ${goStr(t.title)}, Run: ${this.testName(t)}, Line: ${t.line}},`);
120
+ this.emit('}');
121
+ const main = this.p.main ?? [];
122
+ this.blank();
123
+ this.emit(`func main_${this.mod}() {`);
124
+ this.ind++;
125
+ if (main.length) this.frameBody(`T.EnterFrame(${this.file}, 0)`, main, [], true);
126
+ this.ind--;
127
+ this.emit('}');
128
+ this.blank();
129
+ this.emit('var _ = T.I');
130
+ return `${head.join('\n')}\n${this.out.join('\n').replace(/\n{3,}/g, '\n\n')}\n`;
131
+ }
132
+
133
+ testName(t) { return `test_${this.mod}_${t.py.replace(/^test_/, '')}`; }
134
+
135
+ record(r) {
136
+ const fields = r.fields.map((f) => `{Py: ${goStr(f.py)}, Kind: ${goStr(f.type?.k ?? 'any')}}`).join(', ');
137
+ this.emit(`var ${this.g(r.py)} = T.Kind(${goStr(r.py)}, []T.Field{${fields}}, nil)`, r.line);
138
+ }
139
+
140
+ recordRules(r) {
141
+ const bySubject = new Map();
142
+ for (const rule of r.rulesToCheck) { const f = r.fieldMap.get(rule.subject); (bySubject.get(f.py) ?? bySubject.set(f.py, []).get(f.py)).push(rule); }
143
+ for (const [field, rs] of bySubject) {
144
+ this.emit(`${this.g(r.py)}.Rules[${goStr(field)}] = []T.Rule{`);
145
+ this.ind++;
146
+ for (const rule of rs) this.emit(`{Cond: func(value T.V) T.V { F := T.TopFrame(); _ = F; return ${this.x(rule.rule.cond, { subject: 'value' })} }, Text: ${goStr(rule.text)}, Line: ${rule.line}},`, rule.line);
147
+ this.ind--;
148
+ this.emit('}');
149
+ }
150
+ }
151
+
152
+ func(f) {
153
+ this.emit(`func ${this.g(f.py)}(${f.params.map((p) => `${id(p.py)} T.V`).join(', ')}) T.V {`, f.line);
154
+ this.ind++;
155
+ this.scope = new Set(f.params.map((p) => p.py));
156
+ const pre = [];
157
+ // A default: filled in when a call leaves the input out (T.NotGiven). A kept value is read when the call
158
+ // happens, at its line (it may be written further down the file); a fixed value can't fail.
159
+ for (const p of f.params) {
160
+ if (!p.dflt) continue;
161
+ pre.push(p.dflt.k === 'name'
162
+ ? [`if ${id(p.py)} == T.NotGiven { F.Line = ${p.line}; ${id(p.py)} = ${this.x(p.dflt)} }`, p.line]
163
+ : [`if ${id(p.py)} == T.NotGiven { ${id(p.py)} = ${this.x(p.dflt)} }`, null]);
164
+ }
165
+ 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: id(p.py) })}, ${goStr(rule.text)}, ${rule.line}, ${id(p.py)})`, p.line]);
166
+ const first = firstLine(f);
167
+ this.frameBody(`T.EnterCall(${this.file}, ${f.line}, ${first ?? 0})`, f.body, pre, false, f.params.map((p) => p.py));
168
+ this.ind--;
169
+ this.emit('}');
170
+ }
171
+
172
+ /** A body that runs in its own frame: an error leaves with the Thunder line it happened on. */
173
+ frameBody(enter, body, pre, isVoid, params = []) {
174
+ this.emit(`F := ${enter}`);
175
+ this.emit('defer func() { T.Exit(recover()) }()');
176
+ this.emit('_ = F');
177
+ const locals = [...this.localsOf(body)].filter((n) => !params.includes(n));
178
+ this.scope = new Set([...params, ...locals]);
179
+ if (locals.length) {
180
+ this.emit(`var ${locals.map(id).join(', ')} T.V`);
181
+ this.emit(`${locals.map(() => '_').join(', ')} = ${locals.map(id).join(', ')}`);
182
+ }
183
+ for (const [code, line] of pre) this.emit(code, line);
184
+ this.block(body, isVoid);
185
+ if (!isVoid) this.emit('return nil');
186
+ this.scope = new Set();
187
+ }
188
+
189
+ /** The names a body assigns (Python's locals): declared once at the top, as a Python function's are. */
190
+ localsOf(body) {
191
+ const names = new Set();
192
+ const visit = (ss) => {
193
+ for (const s of ss ?? []) {
194
+ if (s.k === 'set' && s.target.k === 'name' && s.target.ref?.py) names.add(s.target.ref.py);
195
+ for (const v of s.vars ?? []) if (v?.py) names.add(v.py);
196
+ if (s.k === 'range' && s.v?.py) names.add(s.v.py);
197
+ if (s.errPy) names.add(s.errPy);
198
+ visit(s.body); visit(s.handler); visit(s.otherwise);
199
+ for (const b of s.branches ?? []) visit(b.body);
200
+ if (s.stmt) visit([s.stmt]);
201
+ }
202
+ };
203
+ visit(body);
204
+ const globals = new Set([...this.info.consts, ...this.info.funcs, ...this.info.records].map((x) => x.py));
205
+ return [...names].filter((n) => !globals.has(n));
206
+ }
207
+
208
+ /** A local name, or a module-level one (a kept value). */
209
+ nameOf(py) { return !this.scope.has(py) && this.ns.has(py) ? this.g(py) : id(py); }
210
+
211
+ block(body, isVoid) { for (const s of body) this.stmt(s, isVoid); }
212
+
213
+ /** F.Line = N; <code> // thunder:N */
214
+ line(L, code) { this.emit(`F.Line = ${L}; ${code}`, L); }
215
+
216
+ /** Give: return from the function, or (inside an "If this fails" closure) remember the value and leave it. */
217
+ giveCode(valueCode, isVoid) {
218
+ const c = this.closures[this.closures.length - 1];
219
+ if (!c) return isVoid ? 'return' : `return ${valueCode}`;
220
+ return isVoid ? `${c.flag} = true; return` : `${c.ret} = ${valueCode}; ${c.flag} = true; return`;
221
+ }
222
+
223
+ /** Check a watched name's Never rules on its new value, then store it. */
224
+ assign(s, name, valueCode) {
225
+ const target = this.nameOf(name);
226
+ if (!s.rules?.length) { this.line(s.line, `${target} = ${valueCode}`); return; }
227
+ const v = this.fresh('new');
228
+ this.line(s.line, `{ ${v} := ${valueCode}`);
229
+ this.ind++;
230
+ for (const rule of s.rules) this.emit(`T.Never(${this.x(rule.rule.cond, { subject: v })}, ${goStr(rule.text)}, ${rule.line}, ${v})`, s.line);
231
+ this.emit(`${target} = ${v} }`, s.line);
232
+ this.ind--;
233
+ }
234
+ rulesAfter(s, name) {
235
+ for (const rule of s.rules ?? []) this.emit(`T.Never(${this.x(rule.rule.cond, { subject: this.nameOf(name) })}, ${goStr(rule.text)}, ${rule.line}, ${this.nameOf(name)})`, s.line);
236
+ }
237
+
238
+ /** Code that stores `v` (a name of generated code) into a name, a field, or an entry. */
239
+ storeCode(t, v) {
240
+ if (t.k === 'name') return `${this.nameOf(t.ref?.py ?? 'unknown')} = ${v}`;
241
+ if (t.k === 'field') return t.static ? `T.SetAttr(${this.x(t.obj)}, ${goStr(t.py)}, ${v})` : `T.SetField(${this.x(t.obj)}, ${goStr(t.text)}, ${v})`;
242
+ if (t.k === 'at') {
243
+ const fn = t.objKind === 'list' ? 'T.SetItem' : t.objKind === 'map' ? 'T.MapSet' : 'T.SetEntry';
244
+ return `${fn}(${this.x(t.obj)}, ${this.x(t.key)}, ${v})`;
245
+ }
246
+ return '';
247
+ }
248
+
249
+ stmt(s, isVoid) {
250
+ const L = s.line;
251
+ switch (s.k) {
252
+ case 'say': this.line(L, `T.Say(${s.e.type?.k === 'text' ? `T.Str(${this.x(s.e)})` : `T.Shown(${this.x(s.e)})`})`); return;
253
+ case 'set': {
254
+ const t = s.target;
255
+ if (t.k === 'name') { this.assign(s, t.ref.py, this.x(s.e)); return; }
256
+ const v = this.fresh('v');
257
+ this.line(L, `{ ${v} := ${this.x(s.e)}; ${this.storeCode(t, v)} }`);
258
+ return;
259
+ }
260
+ case 'give': this.line(L, this.giveCode(s.e.k === 'nothing' ? 'nil' : this.x(s.e), isVoid)); return;
261
+ case 'stop': { const v = this.x(s.e); this.line(L, `panic(T.Stop(${s.e.type?.k === 'text' ? `T.Str(${v})` : `T.Shown(${v})`}))`); return; }
262
+ case 'if': {
263
+ this.emit(`F.Line = ${L}`, L);
264
+ s.branches.forEach((b, k) => {
265
+ this.emit(`${k === 0 ? 'if' : '} else if'} F.Line = ${b.line}; ${this.yn(b.cond)} {`, b.line);
266
+ this.ind++; this.block(b.body, isVoid); this.ind--;
267
+ });
268
+ if (s.otherwise) { this.emit('} else {'); this.ind++; this.block(s.otherwise, isVoid); this.ind--; }
269
+ this.emit('}');
270
+ return;
271
+ }
272
+ case 'each': {
273
+ const [a, b] = s.vars;
274
+ const it = this.x(s.iter);
275
+ const seq = b ? (s.iterKind === 'map' ? `T.MapItems(${it})` : s.iterKind === 'pairs' ? it : `T.PairsOf(${it})`) : it;
276
+ const iter = this.fresh('it'), k = this.fresh('k'), el = this.fresh('el'), ok = this.fresh('ok');
277
+ this.line(L, `${iter} := T.PyIter(${seq})`);
278
+ this.emit(`for ${k} := 0; ; ${k}++ {`);
279
+ this.ind++;
280
+ this.emit(`${el}, ${ok} := ${iter}.Next(${k})`);
281
+ this.emit(`if !${ok} { break }`);
282
+ this.emit(b ? `F.Line = ${L}; ${this.nameOf(a.py)}, ${this.nameOf(b.py)} = T.Unpack2(${el})` : `F.Line = ${L}; ${this.nameOf(a.py)} = ${el}`, L);
283
+ this.block(s.body, isVoid);
284
+ this.ind--;
285
+ this.emit('}');
286
+ return;
287
+ }
288
+ case 'range': {
289
+ const lo = this.fresh('from'), hi = this.fresh('to'), n = this.fresh('n');
290
+ const to = s.to.k === 'num' && s.to.whole ? this.wholeLit(BigInt(s.to.text.replace(/_/g, '')) + 1n) : `T.Add(${this.x(s.to)}, T.I(1))`;
291
+ const a = this.fresh('a'), b = this.fresh('b');
292
+ this.line(L, `{ ${a} := ${this.x(s.from)}; ${b} := ${to}; ${lo} := T.RangeInt(${a}); ${hi} := T.RangeInt(${b})`);
293
+ this.ind++;
294
+ this.emit(`for ${n} := ${lo}; ${n} < ${hi}; ${n}++ {`);
295
+ this.ind++;
296
+ this.emit(`F.Line = ${L}; ${this.nameOf(s.v.py)} = T.I(${n})`, L);
297
+ this.block(s.body, isVoid);
298
+ this.ind--;
299
+ this.emit('}');
300
+ this.ind--;
301
+ this.emit('}');
302
+ return;
303
+ }
304
+ case 'while':
305
+ this.emit('for {', L);
306
+ this.ind++;
307
+ this.emit(`F.Line = ${L}; if !(${s.until ? `!(${this.yn(s.cond)})` : this.yn(s.cond)}) { break }`, L);
308
+ this.block(s.body, isVoid);
309
+ this.ind--;
310
+ this.emit('}');
311
+ return;
312
+ case 'times': {
313
+ const count = this.fresh('count'), k = this.fresh('k');
314
+ this.line(L, `{ ${count} := T.RangeInt(${this.x(s.count)})`);
315
+ this.ind++;
316
+ this.emit(`for ${k} := int64(0); ${k} < ${count}; ${k}++ {`);
317
+ this.ind++;
318
+ this.emit(`F.Line = ${L}`, L);
319
+ this.block(s.body, isVoid);
320
+ this.ind--;
321
+ this.emit('}');
322
+ this.ind--;
323
+ this.emit('}');
324
+ return;
325
+ }
326
+ case 'expect': this.expect(s); return;
327
+ case 'add': case 'remove': this.addRemove(s); return;
328
+ case 'increase': case 'decrease': {
329
+ const op = s.k === 'increase' ? 'T.Add' : 'T.Sub';
330
+ if (s.target.k === 'name') { const py = s.target.ref?.py ?? 'unknown'; this.assign(s, py, `${op}(${this.nameOf(py)}, ${this.x(s.e)})`); return; }
331
+ const v = this.fresh('v');
332
+ this.line(L, `{ ${v} := ${op}(${this.x(s.target)}, ${this.x(s.e)}); ${this.storeCode(s.target, v)} }`);
333
+ return;
334
+ }
335
+ case 'sort': {
336
+ const key = s.field ? `T.KeyAt(F, func(item T.V) T.V { return ${this.fieldGet('item', s.field)} })` : 'nil';
337
+ this.line(L, `T.SortInPlace(${this.x(s.target)}, ${key}, ${!!s.desc})`);
338
+ return;
339
+ }
340
+ case 'reverse': this.line(L, `T.ReverseInPlace(${this.x(s.target)})`); return;
341
+ case 'do': this.line(L, `_ = ${this.x(s.e)}`); return;
342
+ case 'tryFail': {
343
+ const ret = this.fresh('ret'), flag = this.fresh('gave'), failure = this.fresh('failure');
344
+ this.emit(`{ var ${ret} T.V; ${flag} := false; _ = ${ret}`, L);
345
+ this.ind++;
346
+ this.emit(`${failure} := T.Try(func() {`, L);
347
+ this.ind++;
348
+ this.closures.push({ ret, flag });
349
+ this.stmt(s.stmt, isVoid);
350
+ this.closures.pop();
351
+ this.ind--;
352
+ this.emit('})');
353
+ this.emit(`if ${flag} { ${this.giveCode(ret, isVoid)} }`);
354
+ this.emit(`if ${failure} != nil {`);
355
+ this.ind++;
356
+ this.line(L, `${this.nameOf(s.errPy)} = T.Explain(${failure})`);
357
+ this.block(s.handler, isVoid);
358
+ this.ind--;
359
+ this.emit('}');
360
+ this.ind--;
361
+ this.emit('}');
362
+ return;
363
+ }
364
+ default: this.emit(`// not generated: ${s.k}`, L);
365
+ }
366
+ }
367
+
368
+ addRemove(s) {
369
+ const L = s.line;
370
+ const isName = s.target.k === 'name';
371
+ const py = isName ? s.target.ref?.py ?? 'unknown' : null;
372
+ const v = this.fresh('v'), t = this.fresh('t');
373
+ const head = `${v} := ${this.x(s.e)}; ${t} := ${this.x(s.target)}`;
374
+ let body;
375
+ if (s.targetKind === 'list') body = s.k === 'add' ? `T.AppendTo(${t}, ${v})` : `T.RemoveFrom(${t}, ${v})`;
376
+ else if (s.targetKind === 'map') body = `T.RemoveFrom(${t}, ${v})`;
377
+ else if (s.targetKind === 'number') {
378
+ const nv = `${s.k === 'add' ? 'T.Add' : 'T.Sub'}(${t}, ${v})`;
379
+ if (isName && s.rules?.length) {
380
+ const n = this.fresh('new');
381
+ this.line(L, `{ ${head}; ${n} := ${nv}`);
382
+ this.ind++;
383
+ for (const rule of s.rules) this.emit(`T.Never(${this.x(rule.rule.cond, { subject: n })}, ${goStr(rule.text)}, ${rule.line}, ${n})`, L);
384
+ this.emit(`${this.nameOf(py)} = ${n} }`, L);
385
+ this.ind--;
386
+ this.rulesAfter(s, py);
387
+ return;
388
+ }
389
+ body = isName ? `${this.nameOf(py)} = ${nv}` : this.storeCode(s.target, nv);
390
+ } else if (s.k === 'add') body = isName ? `${this.nameOf(py)} = T.AddTo(${t}, ${v})` : this.storeCode(s.target, `T.AddTo(${t}, ${v})`);
391
+ else body = `T.RemoveFrom(${t}, ${v})`;
392
+ this.line(L, `{ ${head}; ${body} }`);
393
+ if (isName) this.rulesAfter(s, py);
394
+ }
395
+
396
+ expect(s) {
397
+ const L = s.line;
398
+ const text = goStr((s.raw ?? 'Expect').trim());
399
+ if (s.mode === 'true') { this.line(L, `T.ExpectTrue(${this.x(s.e)}, ${text})`); return; }
400
+ if (s.mode === 'fail') {
401
+ const m = this.fresh('msg');
402
+ this.line(L, `{ var ${m} T.V = ${s.msg ? this.x(s.msg) : 'nil'}; T.ExpectFailure(func() { _ = ${this.x(s.e)} }, ${text}, ${m}) }`);
403
+ return;
404
+ }
405
+ if (s.mode === 'cmp') { this.line(L, `T.ExpectValue(${this.x(s.e)}, "contains", "contains", ${this.x(s.want)}, ${text})`); return; }
406
+ let c = s.check, negate = false;
407
+ if (c.k === 'not') { negate = true; c = c.e; }
408
+ const OPS = { '==': 'is', '!=': 'is not', '>=': 'at least', '<=': 'at most', '>': 'more than', '<': 'less than' };
409
+ let op, want = 'nil';
410
+ if (c.k === 'cmp') { op = OPS[c.op]; want = this.x(c.r); }
411
+ else if (c.k === 'adj') op = c.adj;
412
+ else if (c.k === 'isNothing') op = c.neg ? 'not nothing' : 'nothing';
413
+ else if (c.k === 'between') { op = 'between'; want = `T.NewList(${this.x(c.lo)}, ${this.x(c.hi)})`; }
414
+ else if (c.k === 'contains') { op = 'in'; want = this.x(c.l); }
415
+ else op = 'is';
416
+ this.line(L, `T.ExpectValue(${this.x(s.e)}, ${goStr(negate ? `not ${op}` : op)}, ${goStr(op)}, ${want}, ${text})`);
417
+ }
418
+
419
+ fieldGet(v, field) { return field.dynamic ? `T.GetField(${v}, ${goStr(field.key)})` : `T.GetAttr(${v}, ${goStr(field.py)})`; }
420
+
421
+ /** A value used as yes/no: a Go condition. Values that are not known to be yes/no are checked when it runs. */
422
+ yn(e, ctx = {}) {
423
+ const c = this.x(e, ctx);
424
+ const known = KNOWN_BOOL.has(e.k) || (e.k === 'bin' && (e.op === 'and' || e.op === 'or'));
425
+ return known ? c : `T.YesNo(${c})`;
426
+ }
427
+
428
+ wholeLit(n) {
429
+ const big = BigInt(n);
430
+ return big >= -(2n ** 63n) && big < 2n ** 63n ? `T.I(${big})` : `T.Int(${goStr(big.toString())})`;
431
+ }
432
+
433
+ x(e, ctx = {}) {
434
+ const sub = (k) => this.x(k, ctx);
435
+ switch (e.k) {
436
+ case 'num': return e.whole ? this.wholeLit(BigInt(e.text.replace(/_/g, ''))) : `T.D(${goStr(e.text)})`;
437
+ case 'money': return `T.M(${goStr(e.text)})`;
438
+ case 'percent': return `T.D(${goStr(percentDecimal(e.text))})`;
439
+ case 'bool': return e.v ? 'true' : 'false';
440
+ case 'nothing': case 'hole': return 'nil';
441
+ case 'paren': return sub(e.e);
442
+ case 'today': return 'T.Today()';
443
+ case 'date': return `T.DateOf(${goStr(e.text)})`;
444
+ case 'str': return this.str(e, ctx);
445
+ case 'list': return e.items ? `T.NewList(${e.items.map(sub).join(', ')})` : 'T.NewMap()';
446
+ case 'map': return 'T.NewMap()';
447
+ case 'name': {
448
+ const r = e.ref ?? {};
449
+ if (r.kind === 'subject') return ctx.subject ?? 'nil';
450
+ if (r.kind === 'elemField') return `T.GetAttr(${ctx.item}, ${goStr(r.py)})`;
451
+ if (r.kind === 'elemKey') return `T.GetField(${ctx.item}, ${goStr(r.key)})`;
452
+ if (r.kind === 'elem') return ctx.item;
453
+ return this.nameOf(r.py ?? e.name.replace(/ /g, '_'));
454
+ }
455
+ case 'call': {
456
+ const args = e.args.map(sub);
457
+ const n = this.ns.params(e.py);
458
+ while (n != null && args.length < n) args.push('T.NotGiven');
459
+ return `${this.g(e.py)}(${args.join(', ')})`;
460
+ }
461
+ case 'new': return `T.NewRecord(${this.g(e.py)}${e.fields.map((f) => `, T.Pair{Py: ${goStr(f.py)}, V: ${sub(f.e)}}`).join('')})`;
462
+ case 'field': return e.static ? `T.GetAttr(${sub(e.obj)}, ${goStr(e.py)})` : `T.GetField(${sub(e.obj)}, ${goStr(e.text)})`;
463
+ case 'at': {
464
+ const fn = e.objKind === 'map' ? 'T.MapGet' : e.objKind === 'list' ? 'T.ItemAt' : 'T.Entry';
465
+ return `${fn}(${sub(e.obj)}, ${sub(e.key)}${e.dflt ? `, ${sub(e.dflt)}` : ''})`;
466
+ }
467
+ case 'conv': {
468
+ const fn = { list: 'T.PyList', number: 'T.ToNumber', whole: 'T.ToWhole', money: 'T.ToMoney', text: 'T.Shown', bool: 'T.ToYesNo', date: 'T.ToDate' }[e.to];
469
+ return fn ? `${fn}(${sub(e.e)})` : sub(e.e);
470
+ }
471
+ case 'where': {
472
+ const v = this.fresh('item');
473
+ return `T.Filter(${sub(e.list)}, func(${v} T.V) bool { return T.Truthy(${this.x(e.cond, { ...ctx, item: v })}) })`;
474
+ }
475
+ case 'from': {
476
+ const inner = e.list.k === 'where' ? e.list : null;
477
+ const v = this.fresh('item');
478
+ const list = sub(inner ? inner.list : e.list);
479
+ const filtered = inner ? `T.Filter(${list}, func(${v} T.V) bool { return T.Truthy(${this.x(inner.cond, { ...ctx, item: v })}) })` : list;
480
+ const w = this.fresh('item');
481
+ return `T.Pick(${filtered}, func(${w} T.V) T.V { return ${this.fieldGet(w, e.field)} })`;
482
+ }
483
+ case 'sorted': {
484
+ if (e.mapSort) return `T.PySort(T.MapItems(${sub(e.list)}), T.KeyAt(F, func(entry T.V) T.V { return T.EntryAt(entry, ${e.by === 'key' ? 0 : 1}) }), ${!!e.desc})`;
485
+ return `T.PySort(T.PyList(${sub(e.list)}), T.KeyAt(F, func(item T.V) T.V { return ${this.fieldGet('item', e.field)} }), ${!!e.desc})`;
486
+ }
487
+ case 'op': return `T.ApplyOp(${goStr(e.op)}, ${sub(e.arg)})`;
488
+ case 'round': return `T.RoundTo(${sub(e.e)}${e.places ? `, ${sub(e.places)}` : ''})`;
489
+ case 'readFile': return `T.ReadText(${sub(e.path)})`;
490
+ case 'neg': return `T.Neg(${sub(e.e)})`;
491
+ case 'not': return `!${this.yn(e.e, ctx)}`;
492
+ case 'bin': {
493
+ if (e.op === 'and') return `(${this.yn(e.l, ctx)} && ${this.yn(e.r, ctx)})`;
494
+ if (e.op === 'or') return `(${this.yn(e.l, ctx)} || ${this.yn(e.r, ctx)})`;
495
+ const fn = { '+': 'T.Add', '-': 'T.Sub', '*': 'T.Mul', '/': 'T.Divide' }[e.op]
496
+ ?? (e.op === 'mod' ? (e.l.type?.k === 'whole' && e.r.type?.k === 'whole' ? 'T.IntMod' : 'T.Modulo') : null);
497
+ return fn ? `${fn}(${sub(e.l)}, ${sub(e.r)})` : 'nil';
498
+ }
499
+ case 'cmp': {
500
+ if (e.r.k === 'bool' && (e.op === '==' || e.op === '!=')) return `(${this.yn(e.l, ctx)} ${e.op} ${sub(e.r)})`;
501
+ return `T.Compare(${goStr(e.op)}, ${sub(e.l)}, ${sub(e.r)})`;
502
+ }
503
+ case 'between': return `T.Between(${sub(e.lo)}, ${sub(e.e)}, func() T.V { return ${sub(e.hi)} })`;
504
+ case 'contains': return `T.IsIn(${sub(e.r)}, ${sub(e.l)})`;
505
+ case 'affix': return `T.Affix(${sub(e.l)}, ${sub(e.r)}, ${!!e.end})`;
506
+ case 'sortedValues': return `T.PySort(T.PyList(${sub(e.list)}), nil, ${!!e.desc})`;
507
+ case 'joined': return `T.Joined(${sub(e.list)}, ${sub(e.sep)})`;
508
+ case 'splitAt': return `T.SplitAt(${sub(e.text)}, ${sub(e.sep)})`;
509
+ case 'replacing': return `T.Replacing(${sub(e.text)}, ${sub(e.from)}, ${sub(e.to)})`;
510
+ case 'adj': {
511
+ if (e.adj === 'empty') return `T.Eq(T.PyLen(${sub(e.e)}), T.I(0))`;
512
+ return `T.Compare(${goStr({ positive: '>', negative: '<', zero: '==' }[e.adj])}, ${sub(e.e)}, T.I(0))`;
513
+ }
514
+ case 'isNothing': return `${e.neg ? '!' : ''}T.IsNothing(${sub(e.e)})`;
515
+ default: return `nil /* not generated: ${e.k} */`;
516
+ }
517
+ }
518
+
519
+ /** Text with {holes}: text and whole numbers as they are, anything else shown the Thunder way. */
520
+ str(e, ctx) {
521
+ const parts = e.parts.filter((p) => p !== '').map((p) => {
522
+ if (typeof p === 'string') return goStr(p);
523
+ const t = p.e.type?.k;
524
+ return t === 'text' || t === 'whole' ? `T.Str(${this.x(p.e, ctx)})` : `T.Shown(${this.x(p.e, ctx)})`;
525
+ });
526
+ if (!parts.length) return '""';
527
+ return parts.length === 1 ? parts[0] : `(${parts.join(' + ')})`;
528
+ }
529
+ }
530
+
531
+ const own = (r) => (s) => !r.info.imported?.has(s);
532
+
533
+ /**
534
+ * The Go names of every module-level thing (records, functions, kept values), per module. A name two Thunder files
535
+ * both define gets its module in front (orders_total), so the one Go package can hold them all.
536
+ */
537
+ export function goNamespaces(results) {
538
+ const defs = new Map();
539
+ for (const r of results) for (const s of [...r.info.records, ...r.info.funcs, ...r.info.consts].filter(own(r))) (defs.get(s.py) ?? defs.set(s.py, []).get(s.py)).push(r.module);
540
+ const goName = (module, py) => ((defs.get(py)?.length ?? 0) > 1 ? `${module}_${py}` : id(py));
541
+ const out = new Map();
542
+ for (const r of results) {
543
+ const visible = new Map();
544
+ const funcs = new Map();
545
+ const take = (x) => {
546
+ for (const s of [...x.info.records, ...x.info.funcs, ...x.info.consts].filter(own(x))) visible.set(s.py, goName(x.module, s.py));
547
+ for (const f of x.info.funcs.filter(own(x))) funcs.set(f.py, f.params.length);
548
+ };
549
+ // A test file sees every src file's names (as the Python target's `from <module> import *`), later ones winning.
550
+ if (r.kind === 'test') for (const s of results.filter((x) => x.kind !== 'test')) take(s);
551
+ take(r);
552
+ out.set(r.module, { name: (py) => visible.get(py) ?? id(py), has: (py) => visible.has(py), params: (py) => funcs.get(py) ?? null });
553
+ }
554
+ return out;
555
+ }