@skillstech/thunderlang 1.1.0 → 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.
@@ -0,0 +1,466 @@
1
+ // Thunder Core -> TypeScript (ES modules; only erasable syntax, so Node can strip the types and run it).
2
+ //
3
+ // The same checked program the Python target and the Thunder engine use (compileCore -> program + info), and the
4
+ // same meaning: every statement does what the Thunder engine does for it (engine.mjs), and every operation calls
5
+ // thunder_runtime.mjs, which is the engine's own value code (runtime-typescript.mjs). compiler/test/core-engines.mjs
6
+ // runs every Core test program on Python, the Thunder engine, and compiled TypeScript, and requires the same output.
7
+ //
8
+ // Every generated statement sets the frame's line (F.line = N) and ends with `// thunder:N`, the Thunder line it came
9
+ // from, so an error says which Thunder line failed, exactly as the other two do.
10
+
11
+ import { percentDecimal } from './target-python.mjs';
12
+
13
+ /** The Thunder line of the first generated line of a function, or null when that line carries no mark. */
14
+ export function firstLine(f) {
15
+ if (f.params.some((p) => p.dflt?.k === 'name')) return null;
16
+ const ruled = f.params.find((p) => p.rules?.length);
17
+ if (ruled) return ruled.line;
18
+ const s = f.body[0];
19
+ if (!s) return null;
20
+ return s.k === 'if' ? s.branches[0].line : s.line;
21
+ }
22
+
23
+ const js = (s) => JSON.stringify(s); // a valid JS string literal for any text
24
+
25
+ const RESERVED = new Set(('break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval undefined NaN Infinity T F FILE main').split(' '));
26
+ /** A JavaScript name for a Thunder (Python) name: the same, unless JavaScript or the generated code owns it. */
27
+ export const id = (py) => (RESERVED.has(py) ? `${py}_` : py);
28
+
29
+ /** The TypeScript type of a value whose Thunder kind is known (others are checked when the program runs). */
30
+ const tsType = (t) => {
31
+ if (!t) return 'any';
32
+ if (t.k === 'whole') return 'bigint';
33
+ if (t.k === 'text') return 'string';
34
+ if (t.k === 'bool') return 'boolean';
35
+ if (t.k === 'optional') { const inner = tsType(t.of); return inner === 'any' ? 'any' : `${inner} | null`; }
36
+ return 'any';
37
+ };
38
+
39
+ const KNOWN_BOOL = new Set(['cmp', 'contains', 'between', 'adj', 'isNothing', 'not', 'bool']);
40
+
41
+ /**
42
+ * Compile one checked file. `imports`: [{ module, names }] for a test file (the project's src modules it sees).
43
+ * Gives back the text of <module>.ts.
44
+ */
45
+ export function toTypeScript(program, info, { source = 'main.thunder', imports = [] } = {}) {
46
+ return new Gen(program, info, source).module(imports);
47
+ }
48
+
49
+ /** Thunder modules a program uses that only Python has (Use): compiled TypeScript cannot call them. */
50
+ export function pythonOnlyUses(info) {
51
+ return (info.modules ?? []).filter((m) => !info.imported?.has(m)).map((m) => ({ module: m.module, line: m.line }));
52
+ }
53
+
54
+ class Gen {
55
+ constructor(program, info, source) {
56
+ this.p = program; this.info = info; this.source = source;
57
+ this.out = []; this.ind = 0; this.tmp = 0;
58
+ }
59
+ emit(text, line) { this.out.push(`${' '.repeat(this.ind)}${text}${line ? ` // thunder:${line}` : ''}`); }
60
+ blank() { if (this.out.length && this.out[this.out.length - 1] !== '') this.out.push(''); }
61
+ fresh(base) { return `$${base}${++this.tmp}`; }
62
+
63
+ module(imports) {
64
+ const own = (s) => !this.info.imported?.has(s);
65
+ const head = [
66
+ `// Generated by the Thunder compiler from ${this.source}.`,
67
+ `// A build artifact: change ${this.source.split('/').pop()} and build again, or keep this file and edit it as TypeScript.`,
68
+ '// It needs only Node.js and thunder_runtime.mjs (written next to it). "// thunder:N" marks the Thunder line.',
69
+ '',
70
+ "import * as T from './thunder_runtime.mjs';",
71
+ ...imports.filter((m) => m.names.length).map((m) => `import { ${m.names.map(id).join(', ')} } from './${m.module}.ts';`),
72
+ '',
73
+ `const FILE = ${js(this.source)};`,
74
+ ];
75
+ for (const r of this.info.records.filter(own)) { this.blank(); this.record(r); }
76
+ for (const f of this.info.funcs.filter(own)) { this.blank(); this.func(f); }
77
+ const consts = this.info.consts.filter(own);
78
+ if (consts.length) {
79
+ this.blank();
80
+ for (const k of consts) this.emit(`export let ${id(k.py)}: any;`, k.line);
81
+ this.emit('T.init(FILE, (F: any) => {');
82
+ this.ind++;
83
+ for (const k of consts) this.emit(`F.line = ${k.line}; ${id(k.py)} = ${this.x(k.e)};`, k.line);
84
+ this.ind--;
85
+ this.emit('});');
86
+ }
87
+ const tests = this.info.tests;
88
+ for (const t of tests) {
89
+ this.blank();
90
+ this.emit(`function ${id(t.py)}(): void {`, t.line);
91
+ this.ind++;
92
+ this.frameBody(`T.enterFrame(FILE, ${t.line})`, t.body, [], true);
93
+ this.ind--;
94
+ this.emit('}');
95
+ }
96
+ this.blank();
97
+ this.emit('export const THUNDER_TESTS: [string, () => void, number][] = [');
98
+ for (const t of tests) this.emit(` [${js(t.title)}, ${id(t.py)}, ${t.line}],`);
99
+ this.emit('];');
100
+ const main = this.p.main ?? [];
101
+ if (main.length) {
102
+ this.blank();
103
+ this.emit('export function main(): void {');
104
+ this.ind++;
105
+ this.frameBody('T.enterFrame(FILE, 0)', main, [], true);
106
+ this.ind--;
107
+ this.emit('}');
108
+ this.blank();
109
+ this.emit('if (T.isEntry(import.meta.url)) T.run(main);');
110
+ }
111
+ return `${head.join('\n')}\n${this.out.join('\n').replace(/\n{3,}/g, '\n\n')}\n`;
112
+ }
113
+
114
+ record(r) {
115
+ const fields = r.fields.map((f) => `{ py: ${js(f.py)}, type: { k: ${js(f.type?.k ?? 'any')} } }`).join(', ');
116
+ const rules = r.rulesToCheck ?? [];
117
+ if (!rules.length) { this.emit(`export const ${id(r.py)} = T.recordKind(${js(r.py)}, [${fields}]);`, r.line); return; }
118
+ this.emit(`export const ${id(r.py)} = T.recordKind(${js(r.py)}, [${fields}], {`, r.line);
119
+ this.ind++;
120
+ const bySubject = new Map();
121
+ 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); }
122
+ for (const [field, rs] of bySubject) {
123
+ this.emit(`${js(field)}: [`);
124
+ this.ind++;
125
+ for (const rule of rs) this.emit(`{ cond: (value: any) => { const F = T.topFrame(); return ${this.x(rule.rule.cond, { subject: 'value' })}; }, text: ${js(rule.text)}, line: ${rule.line} },`, rule.line);
126
+ this.ind--;
127
+ this.emit('],');
128
+ }
129
+ this.ind--;
130
+ this.emit('});');
131
+ }
132
+
133
+ func(f) {
134
+ const params = f.params.map((p) => {
135
+ const name = id(p.py);
136
+ if (!p.dflt) return `${name}: ${tsType(p.type)}`;
137
+ return `${name}: any = ${p.dflt.k === 'name' ? 'T.NOT_GIVEN' : this.x(p.dflt)}`;
138
+ });
139
+ this.emit(`export function ${id(f.py)}(${params.join(', ')}): any {`, f.line);
140
+ this.ind++;
141
+ const pre = [];
142
+ for (const p of f.params) if (p.dflt?.k === 'name') pre.push([`if (${id(p.py)} === T.NOT_GIVEN) { F.line = ${p.line}; ${id(p.py)} = ${this.x(p.dflt)}; }`, p.line]);
143
+ 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) })}, ${js(rule.text)}, ${rule.line}, ${id(p.py)});`, p.line]);
144
+ const first = firstLine(f);
145
+ this.frameBody(`T.enterCall(FILE, ${f.line}, ${first ?? 'null'})`, f.body, pre, false, f.params.map((p) => p.py));
146
+ this.ind--;
147
+ this.emit('}');
148
+ }
149
+
150
+ /** A body that runs in its own frame: errors leave with the Thunder line they happened on. */
151
+ frameBody(enter, body, pre, isVoid, params = []) {
152
+ this.emit(`const F = ${enter};`);
153
+ this.emit('try {');
154
+ this.ind++;
155
+ const locals = [...this.localsOf(body)].filter((n) => !params.includes(n));
156
+ if (locals.length) this.emit(`let ${locals.map((n) => `${id(n)}: any`).join(', ')};`);
157
+ for (const [code, line] of pre) this.emit(code, line);
158
+ this.block(body, isVoid);
159
+ if (!isVoid) this.emit('return null;');
160
+ this.ind--;
161
+ this.emit('} catch (e) { throw T.fail(e); } finally { T.leave(); }');
162
+ }
163
+
164
+ /** The names a body assigns (Python's locals): declared once at the top, as a Python function's are. */
165
+ localsOf(body) {
166
+ const names = new Set();
167
+ const visit = (ss) => {
168
+ for (const s of ss ?? []) {
169
+ if (s.k === 'set' && s.target.k === 'name' && s.target.ref?.py) names.add(s.target.ref.py);
170
+ for (const v of s.vars ?? []) if (v?.py) names.add(v.py);
171
+ if (s.k === 'range' && s.v?.py) names.add(s.v.py);
172
+ if (s.errPy) names.add(s.errPy);
173
+ visit(s.body); visit(s.handler); visit(s.otherwise);
174
+ for (const b of s.branches ?? []) visit(b.body);
175
+ if (s.stmt) visit([s.stmt]);
176
+ }
177
+ };
178
+ visit(body);
179
+ const globals = new Set([...this.info.consts, ...this.info.funcs, ...this.info.records].map((x) => x.py));
180
+ return [...names].filter((n) => !globals.has(n));
181
+ }
182
+
183
+ block(body, isVoid) { for (const s of body) this.stmt(s, isVoid); }
184
+
185
+ /** F.line = N; <code> // thunder:N */
186
+ line(L, code) { this.emit(`F.line = ${L}; ${code}`, L); }
187
+
188
+ /** Check a watched name's Never rules on its new value (in `v`), then store it. */
189
+ assign(s, name, valueCode) {
190
+ if (!s.rules?.length) { this.line(s.line, `${id(name)} = ${valueCode};`); return; }
191
+ const v = this.fresh('new');
192
+ this.line(s.line, `{ const ${v} = ${valueCode};`);
193
+ this.ind++;
194
+ for (const rule of s.rules) this.emit(`T.never(${this.x(rule.rule.cond, { subject: v })}, ${js(rule.text)}, ${rule.line}, ${v});`, s.line);
195
+ this.emit(`${id(name)} = ${v}; }`, s.line);
196
+ this.ind--;
197
+ }
198
+ rulesAfter(s, name) {
199
+ for (const rule of s.rules ?? []) this.emit(`T.never(${this.x(rule.rule.cond, { subject: id(name) })}, ${js(rule.text)}, ${rule.line}, ${id(name)});`, s.line);
200
+ }
201
+
202
+ /** Code that stores `v` (a name of generated code) into a name, a field, or an entry. */
203
+ storeCode(t, v) {
204
+ if (t.k === 'name') return `${id(t.ref?.py ?? 'unknown')} = ${v};`;
205
+ if (t.k === 'field') return t.static ? `T.setAttr(${this.x(t.obj)}, ${js(t.py)}, ${v});` : `T.setField(${this.x(t.obj)}, ${js(t.text)}, ${v});`;
206
+ if (t.k === 'at') {
207
+ const fn = t.objKind === 'list' ? 'T.setItem' : t.objKind === 'map' ? 'T.mapSet' : 'T.setEntry';
208
+ return `${fn}(${this.x(t.obj)}, ${this.x(t.key)}, ${v});`;
209
+ }
210
+ return '';
211
+ }
212
+
213
+ stmt(s, isVoid) {
214
+ const L = s.line;
215
+ switch (s.k) {
216
+ 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;
217
+ case 'set': {
218
+ const t = s.target;
219
+ if (t.k === 'name') { this.assign(s, t.ref.py, this.x(s.e)); return; }
220
+ const v = this.fresh('v');
221
+ this.line(L, `{ const ${v} = ${this.x(s.e)}; ${this.storeCode(t, v)} }`);
222
+ return;
223
+ }
224
+ case 'give': this.line(L, isVoid ? 'return;' : `return ${s.e.k === 'nothing' ? 'null' : this.x(s.e)};`); return;
225
+ 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; }
226
+ case 'if': {
227
+ this.emit(`F.line = ${L};`, L);
228
+ s.branches.forEach((b, k) => {
229
+ this.emit(`${k === 0 ? 'if' : '} else if'} ((F.line = ${b.line}, ${this.yn(b.cond)})) {`, b.line);
230
+ this.ind++; this.block(b.body, isVoid); this.ind--;
231
+ });
232
+ if (s.otherwise) { this.emit('} else {'); this.ind++; this.block(s.otherwise, isVoid); this.ind--; }
233
+ this.emit('}');
234
+ return;
235
+ }
236
+ case 'each': {
237
+ const [a, b] = s.vars;
238
+ const it = this.x(s.iter);
239
+ const seq = b ? (s.iterKind === 'map' ? `T.mapItems(${it})` : s.iterKind === 'pairs' ? `T.pyIter(${it})` : `T.pairsOf(${it})`) : `T.pyIter(${it})`;
240
+ const el = this.fresh('el');
241
+ this.line(L, `for (const ${el} of ${seq}) {`);
242
+ this.ind++;
243
+ this.emit(b ? `F.line = ${L}; [${id(a.py)}, ${id(b.py)}] = T.unpack2(${el});` : `F.line = ${L}; ${id(a.py)} = ${el};`, L);
244
+ this.block(s.body, isVoid);
245
+ this.ind--;
246
+ this.emit('}');
247
+ return;
248
+ }
249
+ case 'range': {
250
+ const lo = this.fresh('from'), hi = this.fresh('to'), n = this.fresh('n');
251
+ const to = s.to.k === 'num' && s.to.whole ? `${BigInt(s.to.text.replace(/_/g, '')) + 1n}n` : `T.add(${this.x(s.to)}, 1n)`;
252
+ const a = this.fresh('a'), b = this.fresh('b');
253
+ this.line(L, `{ const ${a} = ${this.x(s.from)}, ${b} = ${to}, ${lo} = T.rangeInt(${a}), ${hi} = T.rangeInt(${b});`);
254
+ this.ind++;
255
+ this.emit(`for (let ${n} = ${lo}; ${n} < ${hi}; ${n}++) {`);
256
+ this.ind++;
257
+ this.emit(`F.line = ${L}; ${id(s.v.py)} = ${n};`, L);
258
+ this.block(s.body, isVoid);
259
+ this.ind--;
260
+ this.emit('}');
261
+ this.ind--;
262
+ this.emit('}');
263
+ return;
264
+ }
265
+ case 'while':
266
+ this.emit(`while ((F.line = ${L}, ${s.until ? `!(${this.yn(s.cond)})` : this.yn(s.cond)})) {`, L);
267
+ this.ind++; this.block(s.body, isVoid); this.ind--;
268
+ this.emit('}');
269
+ return;
270
+ case 'times': {
271
+ const count = this.fresh('count'), k = this.fresh('k');
272
+ this.line(L, `{ const ${count} = T.rangeInt(${this.x(s.count)});`);
273
+ this.ind++;
274
+ this.emit(`for (let ${k} = 0n; ${k} < ${count}; ${k}++) {`);
275
+ this.ind++;
276
+ this.emit(`F.line = ${L};`, L);
277
+ this.block(s.body, isVoid);
278
+ this.ind--;
279
+ this.emit('}');
280
+ this.ind--;
281
+ this.emit('}');
282
+ return;
283
+ }
284
+ case 'expect': this.expect(s); return;
285
+ case 'add': case 'remove': this.addRemove(s); return;
286
+ case 'increase': case 'decrease': {
287
+ const op = s.k === 'increase' ? 'T.add' : 'T.sub';
288
+ if (s.target.k === 'name') { const py = s.target.ref?.py ?? 'unknown'; this.assign(s, py, `${op}(${id(py)}, ${this.x(s.e)})`); return; }
289
+ const v = this.fresh('v');
290
+ this.line(L, `{ const ${v} = ${op}(${this.x(s.target)}, ${this.x(s.e)}); ${this.storeCode(s.target, v)} }`);
291
+ return;
292
+ }
293
+ case 'sort': {
294
+ const key = s.field ? `T.keyAt(F, (item: any) => ${this.fieldGet('item', s.field)})` : 'null';
295
+ this.line(L, `T.sortInPlace(${this.x(s.target)}, ${key}, ${!!s.desc});`);
296
+ return;
297
+ }
298
+ case 'reverse': this.line(L, `T.reverseInPlace(${this.x(s.target)});`); return;
299
+ case 'do': this.line(L, `${this.x(s.e)};`); return;
300
+ case 'tryFail': {
301
+ this.emit('try {', L);
302
+ this.ind++; this.stmt(s.stmt, isVoid); this.ind--;
303
+ const e = this.fresh('failure');
304
+ this.emit(`} catch (${e}) {`, L);
305
+ this.ind++;
306
+ this.line(L, `${id(s.errPy)} = T.explain(T.asPyErr(${e}));`);
307
+ this.block(s.handler, isVoid);
308
+ this.ind--;
309
+ this.emit('}');
310
+ return;
311
+ }
312
+ default: this.emit(`// not generated: ${s.k}`, L);
313
+ }
314
+ }
315
+
316
+ addRemove(s) {
317
+ const L = s.line;
318
+ const isName = s.target.k === 'name';
319
+ const py = isName ? s.target.ref?.py ?? 'unknown' : null;
320
+ const v = this.fresh('v'), t = this.fresh('t');
321
+ const head = `const ${v} = ${this.x(s.e)}, ${t} = ${this.x(s.target)};`;
322
+ let body;
323
+ if (s.targetKind === 'list') body = s.k === 'add' ? `T.appendTo(${t}, ${v});` : `T.removeFrom(${t}, ${v});`;
324
+ else if (s.targetKind === 'map') body = `T.removeFrom(${t}, ${v});`;
325
+ else if (s.targetKind === 'number') {
326
+ const nv = `${s.k === 'add' ? 'T.add' : 'T.sub'}(${t}, ${v})`;
327
+ if (isName && s.rules?.length) {
328
+ const n = this.fresh('new');
329
+ this.line(L, `{ ${head} const ${n} = ${nv};`);
330
+ this.ind++;
331
+ for (const rule of s.rules) this.emit(`T.never(${this.x(rule.rule.cond, { subject: n })}, ${js(rule.text)}, ${rule.line}, ${n});`, L);
332
+ this.emit(`${id(py)} = ${n}; }`, L);
333
+ this.ind--;
334
+ this.rulesAfter(s, py);
335
+ return;
336
+ }
337
+ body = isName ? `${id(py)} = ${nv};` : this.storeCode(s.target, nv);
338
+ } else if (s.k === 'add') body = isName ? `${id(py)} = T.addTo(${t}, ${v});` : this.storeCode(s.target, `T.addTo(${t}, ${v})`);
339
+ else body = `T.removeFrom(${t}, ${v});`;
340
+ this.line(L, `{ ${head} ${body} }`);
341
+ if (isName) this.rulesAfter(s, py);
342
+ }
343
+
344
+ expect(s) {
345
+ const L = s.line;
346
+ const text = js((s.raw ?? 'Expect').trim());
347
+ if (s.mode === 'true') { this.line(L, `T.expectTrue(${this.x(s.e)}, ${text});`); return; }
348
+ if (s.mode === 'fail') {
349
+ const m = this.fresh('msg');
350
+ this.line(L, `{ const ${m} = ${s.msg ? this.x(s.msg) : 'null'}; T.expectFailure(() => { ${this.x(s.e)}; }, ${text}, ${m}); }`);
351
+ return;
352
+ }
353
+ if (s.mode === 'cmp') { this.line(L, `T.expectValue(${this.x(s.e)}, "contains", "contains", ${this.x(s.want)}, ${text});`); return; }
354
+ let c = s.check, negate = false;
355
+ if (c.k === 'not') { negate = true; c = c.e; }
356
+ const OPS = { '==': 'is', '!=': 'is not', '>=': 'at least', '<=': 'at most', '>': 'more than', '<': 'less than' };
357
+ let op, want = 'null';
358
+ if (c.k === 'cmp') { op = OPS[c.op]; want = this.x(c.r); }
359
+ else if (c.k === 'adj') op = c.adj;
360
+ else if (c.k === 'isNothing') op = c.neg ? 'not nothing' : 'nothing';
361
+ else if (c.k === 'between') { op = 'between'; want = `[${this.x(c.lo)}, ${this.x(c.hi)}]`; }
362
+ else if (c.k === 'contains') { op = 'in'; want = this.x(c.l); }
363
+ else op = 'is';
364
+ this.line(L, `T.expectValue(${this.x(s.e)}, ${js(negate ? `not ${op}` : op)}, ${js(op)}, ${want}, ${text});`);
365
+ }
366
+
367
+ fieldGet(v, field) { return field.dynamic ? `T.getField(${v}, ${js(field.key)})` : `T.getAttr(${v}, ${js(field.py)})`; }
368
+
369
+ /** A value used as yes/no: checked when the program runs unless it is known to be yes/no. */
370
+ yn(e, ctx = {}) {
371
+ const c = this.x(e, ctx);
372
+ const known = e.type?.k === 'bool' || KNOWN_BOOL.has(e.k) || (e.k === 'bin' && (e.op === 'and' || e.op === 'or'));
373
+ return known ? c : `T.yesNo(${c})`;
374
+ }
375
+
376
+ x(e, ctx = {}) {
377
+ const sub = (k) => this.x(k, ctx);
378
+ switch (e.k) {
379
+ case 'num': return e.whole ? `${BigInt(e.text.replace(/_/g, ''))}n` : `T.dec(${js(e.text)})`;
380
+ case 'money': return `T.money(${js(e.text)})`;
381
+ case 'percent': return `T.dec(${js(percentDecimal(e.text))})`;
382
+ case 'bool': return e.v ? 'true' : 'false';
383
+ case 'nothing': case 'hole': return 'null';
384
+ case 'paren': return sub(e.e);
385
+ case 'today': return 'T.today()';
386
+ case 'date': return `T.date(${js(e.text)})`;
387
+ case 'str': return this.str(e, ctx);
388
+ case 'list': return e.items ? `[${e.items.map(sub).join(', ')}]` : 'T.newMap()';
389
+ case 'map': return 'T.newMap()';
390
+ case 'name': {
391
+ const r = e.ref ?? {};
392
+ if (r.kind === 'subject') return ctx.subject ?? 'null';
393
+ if (r.kind === 'elemField') return `T.getAttr(${ctx.item}, ${js(r.py)})`;
394
+ if (r.kind === 'elemKey') return `T.getField(${ctx.item}, ${js(r.key)})`;
395
+ if (r.kind === 'elem') return ctx.item;
396
+ return id(r.py ?? e.name.replace(/ /g, '_'));
397
+ }
398
+ case 'call': return `${id(e.py)}(${e.args.map(sub).join(', ')})`;
399
+ case 'new': return `T.newRecord(${id(e.py)}, [${e.fields.map((f) => `[${js(f.py)}, ${sub(f.e)}]`).join(', ')}])`;
400
+ case 'field': return e.static ? `T.getAttr(${sub(e.obj)}, ${js(e.py)})` : `T.getField(${sub(e.obj)}, ${js(e.text)})`;
401
+ case 'at': {
402
+ const fn = e.objKind === 'map' ? 'T.mapGet' : e.objKind === 'list' ? 'T.itemAt' : 'T.entry';
403
+ return `${fn}(${sub(e.obj)}, ${sub(e.key)}${e.dflt ? `, ${sub(e.dflt)}` : ''})`;
404
+ }
405
+ case 'conv': {
406
+ 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];
407
+ return fn ? `${fn}(${sub(e.e)})` : sub(e.e);
408
+ }
409
+ case 'where': {
410
+ const v = this.fresh('item');
411
+ return `T.pyIter(${sub(e.list)}).filter((${v}: any) => T.truthy(${this.x(e.cond, { ...ctx, item: v })}))`;
412
+ }
413
+ case 'from': {
414
+ const inner = e.list.k === 'where' ? e.list : null;
415
+ const v = this.fresh('item');
416
+ const list = `T.pyIter(${sub(inner ? inner.list : e.list)})`;
417
+ const filtered = inner ? `${list}.filter((${v}: any) => T.truthy(${this.x(inner.cond, { ...ctx, item: v })}))` : list;
418
+ return `${filtered}.map((${v}: any) => ${this.fieldGet(v, e.field)})`;
419
+ }
420
+ case 'sorted': {
421
+ if (e.mapSort) return `T.pySort(T.mapItems(${sub(e.list)}), T.keyAt(F, (entry: any) => entry.items[${e.by === 'key' ? 0 : 1}]), ${!!e.desc})`;
422
+ return `T.pySort(T.pyList(${sub(e.list)}), T.keyAt(F, (item: any) => ${this.fieldGet('item', e.field)}), ${!!e.desc})`;
423
+ }
424
+ case 'op': return `T.applyOp(${js(e.op)}, ${sub(e.arg)})`;
425
+ case 'round': return `T.roundTo(${sub(e.e)}${e.places ? `, ${sub(e.places)}` : ''})`;
426
+ case 'readFile': return `T.readText(${sub(e.path)})`;
427
+ case 'neg': return `T.neg(${sub(e.e)})`;
428
+ case 'not': return `!${this.yn(e.e, ctx)}`;
429
+ case 'bin': {
430
+ if (e.op === 'and') return `(${this.yn(e.l, ctx)} && ${this.yn(e.r, ctx)})`;
431
+ if (e.op === 'or') return `(${this.yn(e.l, ctx)} || ${this.yn(e.r, ctx)})`;
432
+ const fn = { '+': 'T.add', '-': 'T.sub', '*': 'T.mul', '/': 'T.divide' }[e.op]
433
+ ?? (e.op === 'mod' ? (e.l.type?.k === 'whole' && e.r.type?.k === 'whole' ? 'T.intMod' : 'T.modulo') : null);
434
+ return fn ? `${fn}(${sub(e.l)}, ${sub(e.r)})` : 'null';
435
+ }
436
+ case 'cmp': {
437
+ if (e.r.k === 'bool' && (e.op === '==' || e.op === '!=')) return `(${this.yn(e.l, ctx)} ${e.op === '==' ? '===' : '!=='} ${sub(e.r)})`;
438
+ return `T.compare(${js(e.op)}, ${sub(e.l)}, ${sub(e.r)})`;
439
+ }
440
+ case 'between': return `T.between(${sub(e.lo)}, ${sub(e.e)}, () => ${sub(e.hi)})`;
441
+ case 'contains': return `T.isIn(${sub(e.r)}, ${sub(e.l)})`;
442
+ case 'affix': return `T.affix(${sub(e.l)}, ${sub(e.r)}, ${!!e.end})`;
443
+ case 'sortedValues': return `T.pySort(T.pyList(${sub(e.list)}), null, ${!!e.desc})`;
444
+ case 'joined': return `T.joined(${sub(e.list)}, ${sub(e.sep)})`;
445
+ case 'splitAt': return `T.splitAt(${sub(e.text)}, ${sub(e.sep)})`;
446
+ case 'replacing': return `T.replacing(${sub(e.text)}, ${sub(e.from)}, ${sub(e.to)})`;
447
+ case 'adj': {
448
+ if (e.adj === 'empty') return `T.eq(T.pyLen(${sub(e.e)}), 0n)`;
449
+ return `T.compare(${js({ positive: '>', negative: '<', zero: '==' }[e.adj])}, ${sub(e.e)}, 0n)`;
450
+ }
451
+ case 'isNothing': return `(${sub(e.e)} ${e.neg ? '!==' : '==='} null)`;
452
+ default: return `null /* not generated: ${e.k} */`;
453
+ }
454
+ }
455
+
456
+ /** Text with {holes}: text and whole numbers as they are, anything else shown the Thunder way. */
457
+ str(e, ctx) {
458
+ const parts = e.parts.filter((p) => p !== '').map((p) => {
459
+ if (typeof p === 'string') return js(p);
460
+ const t = p.e.type?.k;
461
+ return t === 'text' || t === 'whole' ? `T.pyStr(${this.x(p.e, ctx)})` : `T.show(${this.x(p.e, ctx)})`;
462
+ });
463
+ if (!parts.length) return '""';
464
+ return parts.length === 1 ? parts[0] : `(${parts.join(' + ')})`;
465
+ }
466
+ }
@@ -0,0 +1,114 @@
1
+ // Writing compiled TypeScript to disk, and running it.
2
+ //
3
+ // Running: Node strips the types itself from version 23.6 (22.6 with --experimental-strip-types). On an older Node,
4
+ // Thunder uses the `typescript` package when it can find it (in the project, or next to Thunder) to remove the types
5
+ // first. Otherwise it says plainly what is needed. The generated code uses only types Node can strip.
6
+ import { writeFileSync, mkdirSync, readFileSync, rmSync, readdirSync } from 'node:fs';
7
+ import { join, dirname } from 'node:path';
8
+ import { spawnSync } from 'node:child_process';
9
+ import { createRequire } from 'node:module';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { toTypeScript, pythonOnlyUses } from './target-typescript.mjs';
12
+ import { TS_RUNTIME, TS_RUNTIME_DTS } from './runtime-typescript.mjs';
13
+ import { diag } from './diagnostics.mjs';
14
+
15
+ /** The names a src file gives a test file (its records, functions, and kept values). */
16
+ const exportedNames = (r) => [...r.info.records, ...r.info.funcs, ...r.info.consts].filter((s) => !r.info.imported?.has(s)).map((s) => s.py);
17
+
18
+ /** TC405 for every Use in a file: Python modules exist only for the Python target. */
19
+ export function typescriptDiagnostics(result) {
20
+ return pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
21
+ `"${u.module}" is a Python module, and this program is compiled to TypeScript, which cannot use it.`,
22
+ 'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'));
23
+ }
24
+
25
+ /**
26
+ * Compile checked results to TypeScript: { [module]: text }. Test files import every src file's names, as the
27
+ * Python target's `from <module> import *` does.
28
+ */
29
+ export function compileTypeScript(results) {
30
+ const src = results.filter((r) => r.kind !== 'test');
31
+ const out = {};
32
+ for (const r of results) {
33
+ const imports = r.kind === 'test' ? src.map((s) => ({ module: s.module, names: exportedNames(s) })) : [];
34
+ out[r.module] = toTypeScript(r.program, r.info, { source: r.file, imports });
35
+ }
36
+ return out;
37
+ }
38
+
39
+ export const TSCONFIG = `${JSON.stringify({
40
+ compilerOptions: { strict: true, noEmit: true, target: 'es2022', module: 'nodenext', moduleResolution: 'nodenext', allowImportingTsExtensions: true, skipLibCheck: true, types: [] },
41
+ include: ['*.ts'],
42
+ }, null, 2)}\n`;
43
+
44
+ /** Write <module>.ts for every result, run_tests.ts, the runtime and its types, package.json, and tsconfig.json. */
45
+ export function writeTypeScript(results, outDir) {
46
+ mkdirSync(outDir, { recursive: true });
47
+ const files = compileTypeScript(results);
48
+ for (const [m, text] of Object.entries(files)) writeFileSync(join(outDir, `${m}.ts`), text);
49
+ writeFileSync(join(outDir, 'thunder_runtime.mjs'), TS_RUNTIME);
50
+ writeFileSync(join(outDir, 'thunder_runtime.d.mts'), TS_RUNTIME_DTS);
51
+ writeFileSync(join(outDir, 'package.json'), `${JSON.stringify({ type: 'module', private: true }, null, 2)}\n`);
52
+ writeFileSync(join(outDir, 'tsconfig.json'), TSCONFIG);
53
+ writeFileSync(join(outDir, 'run_tests.ts'), [
54
+ '// Generated by the Thunder compiler: runs every Test block in this project.',
55
+ "import * as T from './thunder_runtime.mjs';",
56
+ ...results.map((r, i) => `import { THUNDER_TESTS as tests${i} } from './${r.module}.ts';`),
57
+ '',
58
+ `T.runTests([${results.map((r, i) => `[${JSON.stringify(r.file)}, tests${i}]`).join(', ')}]);`,
59
+ '',
60
+ ].join('\n'));
61
+ return Object.keys(files);
62
+ }
63
+
64
+ /** How this Node runs TypeScript: { args } for Node itself, { ts } for the typescript package, or { error }. */
65
+ export function typescriptRunner({ nodeVersion = process.versions.node, searchFrom = [], searchDefaults = true } = {}) {
66
+ const [maj, min] = nodeVersion.split('.').map(Number);
67
+ if (maj > 23 || (maj === 23 && min >= 6)) return { args: [] };
68
+ if ((maj === 22 && min >= 6) || maj === 23) return { args: ['--experimental-strip-types'] };
69
+ const here = dirname(fileURLToPath(import.meta.url));
70
+ for (const from of [...searchFrom, ...(searchDefaults ? [process.cwd(), here] : [])]) {
71
+ try { const req = createRequire(join(from, 'x.js')); return { ts: req(req.resolve('typescript')) }; } catch { /* not there */ }
72
+ }
73
+ return { error: `Running TypeScript needs Node.js 22.6 or newer (this is Node ${nodeVersion}), or the typescript package (npm install typescript). "thunder build --target typescript" works without either.` };
74
+ }
75
+
76
+ /**
77
+ * Run a compiled module (`entry`, e.g. "main.ts" or "run_tests.ts") in `outDir`, in the folder `cwd`.
78
+ * Returns spawnSync's result ({ status, stdout, stderr }), or { status: 2, stderr } when TypeScript cannot run here.
79
+ */
80
+ export function runTypeScript(outDir, entry, { cwd = outDir, stdio = 'pipe', searchFrom = [] } = {}) {
81
+ const runner = typescriptRunner({ searchFrom: [outDir, cwd, ...searchFrom] });
82
+ if (runner.error) return { status: 2, stdout: '', stderr: `${runner.error}\n`, error: runner.error };
83
+ const env = { ...process.env, NODE_NO_WARNINGS: '1' };
84
+ if (runner.args) return spawnSync(process.execPath, [...runner.args, join(outDir, entry)], { cwd, stdio, encoding: 'utf8', env });
85
+ // Older Node: remove the types with the typescript package, into .run/ next to the TypeScript.
86
+ const ts = runner.ts;
87
+ const runDir = join(outDir, '.run');
88
+ rmSync(runDir, { recursive: true, force: true });
89
+ mkdirSync(runDir, { recursive: true });
90
+ for (const f of readdirTs(outDir)) {
91
+ const js = ts.transpileModule(readFileSync(join(outDir, f), 'utf8'), { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText;
92
+ writeFileSync(join(runDir, f.replace(/\.ts$/, '.mjs')), js.replace(/(from\s+['"]\.\/[^'"]+)\.ts(['"])/g, '$1.mjs$2'));
93
+ }
94
+ writeFileSync(join(runDir, 'thunder_runtime.mjs'), readFileSync(join(outDir, 'thunder_runtime.mjs'), 'utf8'));
95
+ return spawnSync(process.execPath, [join(runDir, entry.replace(/\.ts$/, '.mjs'))], { cwd, stdio, encoding: 'utf8', env });
96
+ }
97
+
98
+ function readdirTs(dir) {
99
+ let all = [];
100
+ try { all = readdirSync(dir); } catch { /* no folder */ }
101
+ return all.filter((f) => f.endsWith('.ts') && !f.endsWith('.d.ts'));
102
+ }
103
+
104
+ /** Typecheck compiled TypeScript with tsc --strict, when tsc can be found. { ok, output } or { skipped }. */
105
+ export function typecheckTypeScript(outDir, { searchFrom = [] } = {}) {
106
+ const here = dirname(fileURLToPath(import.meta.url));
107
+ for (const from of [outDir, ...searchFrom, process.cwd(), here]) {
108
+ let tsc;
109
+ try { tsc = createRequire(join(from, 'x.js')).resolve('typescript/bin/tsc'); } catch { continue; }
110
+ const r = spawnSync(process.execPath, [tsc, '-p', join(outDir, 'tsconfig.json')], { encoding: 'utf8' });
111
+ return { ok: r.status === 0, output: `${r.stdout}${r.stderr}`.trim() };
112
+ }
113
+ return { skipped: 'tsc was not found (install typescript to check the generated types)' };
114
+ }
package/src/emit.mjs CHANGED
@@ -30,7 +30,7 @@ export function notesSummary(ast) {
30
30
  };
31
31
  }
32
32
 
33
- export const COMPILER_VERSION = '1.1.0';
33
+ export const COMPILER_VERSION = '1.2.0';
34
34
  export const PROOF_SCHEMA_VERSION = '0.1.0';
35
35
  // Identifies which ecosystem product emitted this proof. Consumed by SkillsTech
36
36
  // Certified to key cert proofs to the compiler. Stable slug per the coordination bus.