@skillstech/thunderlang 1.2.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.
- package/CHANGELOG.md +131 -0
- package/dist/core.cjs +2080 -278
- package/dist/index.cjs +12742 -10943
- package/dist/learn.cjs +2716 -345
- package/package.json +1 -1
- package/src/cli.mjs +31 -6
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +148 -8
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -1
- package/src/core/engine-core.mjs +285 -2
- package/src/core/engine-values.mjs +1 -1
- package/src/core/format.mjs +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +2 -1
- package/src/core/java/thunder/T.java +6 -0
- package/src/core/java/thunder/ThunderRuntime.java +1374 -0
- package/src/core/java-run.mjs +89 -0
- package/src/core/parser.mjs +331 -5
- package/src/core/project.mjs +31 -6
- package/src/core/react-run.mjs +96 -0
- package/src/core/runtime-go/thunder_runtime.go +3038 -0
- package/src/core/runtime-react.mjs +133 -0
- package/src/core/rust/thunder_runtime.rs +1645 -0
- package/src/core/rust-run.mjs +192 -0
- package/src/core/screen-values.mjs +30 -0
- package/src/core/target-csharp.mjs +484 -0
- package/src/core/target-go.mjs +555 -0
- package/src/core/target-java.mjs +587 -0
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +2 -2
- package/src/core.d.ts +18 -0
- package/src/core.mjs +1 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +30 -0
- package/src/libraries.mjs +10 -3
- package/src/model.mjs +50 -8
- package/src/read-level.mjs +48 -2
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +28 -5
- package/src/replay-cli.mjs +123 -0
- package/src/say-less.mjs +152 -11
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +430 -19
- package/src/term.mjs +43 -0
package/src/core/check.mjs
CHANGED
|
@@ -46,6 +46,12 @@ export function pyName(key, style = 'snake') {
|
|
|
46
46
|
return n;
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
/** The closest name, also when two letters are swapped ("cuont" for "count"). */
|
|
50
|
+
function nearName(word, options) {
|
|
51
|
+
const sorted = (w) => [...w].sort().join('');
|
|
52
|
+
return closest(word, options) ?? options.find((o) => o.length === word.length && sorted(o) === sorted(word)) ?? null;
|
|
53
|
+
}
|
|
54
|
+
|
|
49
55
|
class Scope {
|
|
50
56
|
constructor(parent, kind) { this.parent = parent; this.kind = kind; this.vars = new Map(); }
|
|
51
57
|
get(key) { return this.vars.get(key) ?? this.parent?.get(key); }
|
|
@@ -68,7 +74,8 @@ class Checker {
|
|
|
68
74
|
this.rules = []; // top-level and record Never rules
|
|
69
75
|
this.mainNames = new Map(); // key -> first line it is set in the main program
|
|
70
76
|
this.elem = []; // stack of { type } for where / from / sorted
|
|
71
|
-
this.info = { records: [], funcs: [], consts: [], modules: [], tests: [], rules: [], usesDecimal: false };
|
|
77
|
+
this.info = { records: [], funcs: [], consts: [], modules: [], tests: [], rules: [], screens: [], usesDecimal: false };
|
|
78
|
+
this.screens = new Map(); // key -> screen stmt
|
|
72
79
|
}
|
|
73
80
|
err(code, line, msg, hint) { this.d.push(diag(code, line, msg, hint)); }
|
|
74
81
|
|
|
@@ -87,6 +94,11 @@ class Checker {
|
|
|
87
94
|
if (s.k === 'record') this.declare(s, 'record', s.line, { py: pyName(s.name, 'pascal'), stmt: s });
|
|
88
95
|
else if (s.k === 'func') this.declare(s, 'func', s.line, { py: pyName(s.name), stmt: s, ret: UNKNOWN });
|
|
89
96
|
else if (s.k === 'use') this.declare(s, 'module', s.line, { py: pyName(s.name), module: s.module, type: T('module') });
|
|
97
|
+
else if (s.k === 'screen') {
|
|
98
|
+
const prev = this.screens.get(s.name);
|
|
99
|
+
if (prev) this.err('TC203', s.line, `There is already a screen called "${s.text}" (line ${prev.line}).`, 'Give one of them a different name.');
|
|
100
|
+
else { this.screens.set(s.name, s); s.py = pyName(s.name, 'pascal'); for (const p of s.params) p.py = pyName(p.name); }
|
|
101
|
+
}
|
|
90
102
|
}
|
|
91
103
|
for (const s of top) if (s.k === 'record') this.checkRecordShape(s);
|
|
92
104
|
collectMainNames(top, this.mainNames);
|
|
@@ -103,9 +115,14 @@ class Checker {
|
|
|
103
115
|
// 4. Functions, then tests, then the main program.
|
|
104
116
|
for (const s of top) if (s.k === 'func') this.checkFunc(s);
|
|
105
117
|
for (const s of top) if (s.k === 'test') { s.py = `test_${pyName(s.title.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim() || 'unnamed')}`.replace(/_+$/, ''); this.uniqueTestName(s); const sc = new Scope(this.global, 'test'); this.block(s.body, sc, { inTest: true }); this.info.tests.push(s); }
|
|
118
|
+
for (const s of this.screens.values()) this.checkScreen(s);
|
|
119
|
+
this.info.screens = [...this.screens.values()];
|
|
120
|
+
const first = this.info.screens[0];
|
|
121
|
+
const needs = first ? first.params.filter((p) => !p.dflt) : [];
|
|
122
|
+
if (needs.length) this.err('TC214', first.line, `"${first.text}" is the first screen, where the app starts, so nothing gives it ${needs.map((p) => p.text).join(', ')}.`, `Put the screen the app starts on first, or give ${needs.length === 1 ? 'the input' : 'each input'} a value for when it isn't given: Receive ${needs[0].text} (… if not given).`);
|
|
106
123
|
const main = new Scope(this.global, 'main');
|
|
107
124
|
this.mainScope = main;
|
|
108
|
-
const mainBody = top.filter((s) => !['record', 'func', 'use', 'keep', 'never', 'test'].includes(s.k));
|
|
125
|
+
const mainBody = top.filter((s) => !['record', 'func', 'use', 'keep', 'never', 'test', 'screen'].includes(s.k));
|
|
109
126
|
this.block(mainBody, main, {});
|
|
110
127
|
this.p.main = mainBody;
|
|
111
128
|
this.info.records = [...this.records.values()];
|
|
@@ -219,7 +236,18 @@ class Checker {
|
|
|
219
236
|
|
|
220
237
|
stmt(s, sc, ctx) {
|
|
221
238
|
const line = s.line;
|
|
239
|
+
if (ctx.inPress && (s.k === 'say' || s.k === 'give' || s.k === 'expect')) {
|
|
240
|
+
const word = { say: 'Say', give: 'Give', expect: 'Expect' }[s.k];
|
|
241
|
+
this.err('TC407', line, `"${word}" can't run when a button is pressed.`, s.k === 'say' ? 'A screen shows things instead: Remember a value, set it here, and Show it on the screen.' : s.k === 'give' ? 'A button gives nothing back. Set a remembered value instead.' : 'Expect lines go in a "Test" block.');
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
222
244
|
switch (s.k) {
|
|
245
|
+
case 'open': {
|
|
246
|
+
if (!ctx.inPress) { this.err('TC402', line, '"Open" is a step for a button: under "When pressed:".'); return; }
|
|
247
|
+
this.screenRef(s, line);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
case 'screen': this.err('TC402', line, 'A "Screen" must be written at the left edge of the file.'); return;
|
|
223
251
|
case 'say': this.ex(s.e, sc); return;
|
|
224
252
|
case 'set': return this.checkSet(s, sc, ctx);
|
|
225
253
|
case 'keep': this.err('TC402', line, '"Keep" is written at the left edge of the file, not inside a block.', 'Keep values are fixed for the whole program.'); return;
|
|
@@ -304,6 +332,130 @@ class Checker {
|
|
|
304
332
|
}
|
|
305
333
|
}
|
|
306
334
|
|
|
335
|
+
// ------------------------------------------------------------ screens
|
|
336
|
+
|
|
337
|
+
inputChanged(e, entry, line) {
|
|
338
|
+
if (entry.kind === 'item') {
|
|
339
|
+
this.err('TC213', line, `"${e.text}" is an item of the list shown on line ${entry.line}, so it can't be changed here.`, 'Change the remembered list it comes from instead (for example: Remove it from the list, then Add the changed one).');
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
this.err('TC213', line, `"${e.text}" is an input of the screen (line ${entry.line}): the screen that shows it gives it, so it can't be changed here.`,
|
|
343
|
+
`To change it on this screen, remember a copy: Remember ${e.text} now starting at ${e.text}, and change that.`);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** "opens Home" / "Open Home": the screen must exist, and it must not need inputs (nothing gives them). */
|
|
347
|
+
screenRef(s, line) {
|
|
348
|
+
const target = this.screens.get(s.name);
|
|
349
|
+
if (!target) {
|
|
350
|
+
const near = nearName(s.name, [...this.screens.keys()]);
|
|
351
|
+
this.err('TC212', line, `I don't know a screen called "${s.text}".`, near ? `Did you mean "${this.screens.get(near).text}"?` : this.screens.size ? `The screens: ${[...this.screens.values()].map((x) => x.text).join(', ')}.` : 'Write it: Screen <name>: and what it shows.');
|
|
352
|
+
return null;
|
|
353
|
+
}
|
|
354
|
+
s.py = target.py;
|
|
355
|
+
const needs = target.params.filter((p) => !p.dflt);
|
|
356
|
+
if (needs.length) this.err('TC214', line, `"${target.text}" needs ${needs.map((p) => p.text).join(', ')}, and a screen that is opened is given no inputs.`, `Give ${needs.length === 1 ? 'it' : 'each'} a value to use when it isn't given: Receive ${needs[0].text} (… if not given). Or show it inside this screen: Show ${target.text}: with the inputs under it.`);
|
|
357
|
+
return target;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
checkScreen(s) {
|
|
361
|
+
const sc = new Scope(this.global, 'screen');
|
|
362
|
+
sc.screen = s;
|
|
363
|
+
for (const p of s.params) {
|
|
364
|
+
if (p.dflt) this.ex(p.dflt, this.global, {});
|
|
365
|
+
if (sc.vars.has(p.name)) this.err('TC203', p.line, `"${p.text}" is received twice.`);
|
|
366
|
+
if (this.global.vars.has(p.name)) this.err('TC203', p.line, `"${p.text}" is already the name of ${this.global.vars.get(p.name).kind === 'func' ? 'a function' : 'something else'} (line ${this.global.vars.get(p.name).line}).`, 'Receive it under a different name.');
|
|
367
|
+
this.resolveType(p.type, p.line);
|
|
368
|
+
if (p.type && p.dflt && known(p.type) && known(p.dflt.type) && !compatible(p.type, p.dflt.type) && p.dflt.type.k !== 'nothing') this.err('TC303', p.line, `"${p.text}" is ${typeWords(p.type)}, but its default is ${typeWords(p.dflt.type)}.`);
|
|
369
|
+
p.py = pyName(p.name);
|
|
370
|
+
sc.vars.set(p.name, { kind: 'input', py: p.py, type: p.type ?? (p.dflt && known(p.dflt.type) ? p.dflt.type : UNKNOWN), line: p.line });
|
|
371
|
+
}
|
|
372
|
+
for (const r of s.remember) {
|
|
373
|
+
const t = this.ex(r.e, sc);
|
|
374
|
+
this.resolveType(r.type, r.line);
|
|
375
|
+
if (r.type && known(r.type) && known(t) && !compatible(r.type, t) && !(t.k === 'list' && r.type.k === 'list' && !known(t.of))) this.err('TC303', r.line, `"${r.text}" is ${typeWords(r.type)}, but it starts at ${typeWords(t)}.`);
|
|
376
|
+
if (sc.vars.has(r.name)) { this.err('TC203', r.line, `"${r.text}" is already ${sc.vars.get(r.name).kind === 'input' ? 'an input' : 'remembered'} on line ${sc.vars.get(r.name).line}.`, 'Give one of them a different name.'); continue; }
|
|
377
|
+
if (this.global.vars.has(r.name)) { this.err('TC203', r.line, `"${r.text}" is already the name of ${this.global.vars.get(r.name).kind === 'func' ? 'a function' : 'something else'} (line ${this.global.vars.get(r.name).line}).`); continue; }
|
|
378
|
+
r.py = pyName(r.name);
|
|
379
|
+
sc.vars.set(r.name, { kind: 'state', py: r.py, type: r.type ?? t, line: r.line });
|
|
380
|
+
}
|
|
381
|
+
this.elements(s.body, sc, s);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
elements(els, sc, screen) {
|
|
385
|
+
for (const el of els) {
|
|
386
|
+
const line = el.line;
|
|
387
|
+
switch (el.k) {
|
|
388
|
+
case 'heading': case 'text': this.ex(el.e, sc); break;
|
|
389
|
+
case 'when':
|
|
390
|
+
for (const b of el.branches) { this.cond(b.cond, sc); this.elements(b.body, sc, screen); }
|
|
391
|
+
if (el.otherwise) this.elements(el.otherwise, sc, screen);
|
|
392
|
+
break;
|
|
393
|
+
case 'list': {
|
|
394
|
+
const it = this.ex(el.iter, sc);
|
|
395
|
+
if (known(it) && it.k !== 'list' && it.k !== 'optional') this.err('TC305', line, `"Show a list" goes through a list, but this is ${typeWords(it)}.`);
|
|
396
|
+
const inner = new Scope(sc, 'loop');
|
|
397
|
+
el.v.py = pyName(el.v.name);
|
|
398
|
+
inner.vars.set(el.v.name, { kind: 'item', py: el.v.py, type: it.k === 'list' ? it.of ?? UNKNOWN : UNKNOWN, line });
|
|
399
|
+
this.elements(el.body, inner, screen);
|
|
400
|
+
break;
|
|
401
|
+
}
|
|
402
|
+
case 'row': this.elements(el.body, sc, screen); break;
|
|
403
|
+
case 'textbox': case 'numberbox': {
|
|
404
|
+
this.ex(el.label, sc);
|
|
405
|
+
const v = sc.get(el.target.name);
|
|
406
|
+
if (!v || (v.kind !== 'state' && v.kind !== 'input')) {
|
|
407
|
+
const near = nearName(el.target.name, [...sc.vars.keys()].filter((k) => sc.vars.get(k).kind === 'state'));
|
|
408
|
+
this.err('TC201', line, `A box changes a remembered value, and this screen remembers nothing called "${el.target.text}".`, near ? `Did you mean "${near}"?` : `Add it at the top of the screen: Remember ${el.target.text} starting at ${el.k === 'textbox' ? '""' : '0'}.`);
|
|
409
|
+
break;
|
|
410
|
+
}
|
|
411
|
+
if (v.kind === 'input') { this.inputChanged(el.target, v, line); break; }
|
|
412
|
+
el.target.ref = v;
|
|
413
|
+
if (el.k === 'textbox' && known(v.type) && v.type.k !== 'text') this.err('TC305', line, `A text box holds text, but "${el.target.text}" is ${typeWords(v.type)}.`, numeric(v.type) ? `Use a number box: Show a number box … for ${el.target.text}.` : null);
|
|
414
|
+
if (el.k === 'numberbox' && known(v.type) && !numeric(v.type)) this.err('TC305', line, `A number box holds a number, but "${el.target.text}" is ${typeWords(v.type)}.`, v.type.k === 'text' ? `Use a text box: Show a text box … for ${el.target.text}.` : 'Money in a box is not supported yet: remember a number.');
|
|
415
|
+
if (!known(v.type)) v.type = el.k === 'textbox' ? T('text') : T('number');
|
|
416
|
+
el.boxKind = v.type.k;
|
|
417
|
+
break;
|
|
418
|
+
}
|
|
419
|
+
case 'button': {
|
|
420
|
+
this.ex(el.label, sc);
|
|
421
|
+
if (el.off) this.cond(el.off, sc);
|
|
422
|
+
if (el.opens) this.screenRef(el.opens, line);
|
|
423
|
+
if (el.press) {
|
|
424
|
+
const ps = new Scope(sc, 'press');
|
|
425
|
+
this.block(el.press.body, ps, { inPress: true });
|
|
426
|
+
el.press.locals = [...ps.vars.values()].map((v) => v.py);
|
|
427
|
+
}
|
|
428
|
+
break;
|
|
429
|
+
}
|
|
430
|
+
case 'child': {
|
|
431
|
+
const target = this.screens.get(el.screen.name);
|
|
432
|
+
if (!target) break; // (the parser knew it)
|
|
433
|
+
el.screen.py = target.py;
|
|
434
|
+
if (target === screen) { this.err('TC402', line, `"${screen.text}" can't show itself: it would never finish showing.`); break; }
|
|
435
|
+
const keys = target.params.map((p) => p.name);
|
|
436
|
+
const given = new Map();
|
|
437
|
+
for (const g of el.given) {
|
|
438
|
+
const t = this.ex(g.e, sc);
|
|
439
|
+
const p = target.params.find((x) => x.name === g.name);
|
|
440
|
+
if (!p) {
|
|
441
|
+
const near = nearName(g.name, keys);
|
|
442
|
+
this.err('TC214', g.line, `"${target.text}" has no input called "${g.text}".${near ? ` Did you mean "${near}"?` : ''}`, keys.length ? `Its inputs: ${keys.join(', ')}.` : `"${target.text}" receives no inputs.`);
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
if (given.has(g.name)) { this.err('TC114', g.line, `"${g.text}" is given twice (also on line ${given.get(g.name).line}).`, 'Give each input once.'); continue; }
|
|
446
|
+
given.set(g.name, g);
|
|
447
|
+
g.py = p.py;
|
|
448
|
+
if (p.type && known(p.type) && known(t) && !compatible(p.type, t)) this.err('TC303', g.line, `"${target.text}" receives ${p.text} as ${typeWords(p.type)}, but ${typeWords(t)} was given.`);
|
|
449
|
+
}
|
|
450
|
+
const missing = target.params.filter((p) => !p.dflt && !given.has(p.name));
|
|
451
|
+
if (missing.length) this.err('TC214', line, `"${target.text}" needs ${missing.map((p) => p.text).join(', ')}, but ${missing.length === 1 ? 'it is' : 'they are'} not given.`, `Write it as a block:\n Show ${target.text}:\n ${missing.map((p) => `${p.text}: …`).join('\n ')}`);
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
default: this.err('TC402', line, `A screen can't show "${el.k}" yet.`);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
307
459
|
localPy(key, sc) { return pyName(key); }
|
|
308
460
|
|
|
309
461
|
checkSet(s, sc, ctx) {
|
|
@@ -315,6 +467,7 @@ class Checker {
|
|
|
315
467
|
if (g && g.kind === 'const') { this.err('TC205', line, `"${tgt.text}" is kept at a fixed value (line ${g.line}), so it can't be set.`, 'Use a different name for a value that changes, or change the Keep line.'); return; }
|
|
316
468
|
if (g && g.kind !== 'const') { this.err('TC203', line, `"${tgt.text}" is already the name of ${g.kind === 'func' ? 'a function' : g.kind === 'record' ? 'a record' : 'a module'} (line ${g.line}).`, 'Give this value a different name.'); return; }
|
|
317
469
|
const cur = sc.get(tgt.name);
|
|
470
|
+
if (cur && (cur.kind === 'input' || cur.kind === 'item')) { this.inputChanged(tgt, cur, line); return; }
|
|
318
471
|
if (cur && cur.kind !== 'subject') {
|
|
319
472
|
if (cur.kind === 'param' && cur.type && known(cur.type) && known(tv) && !compatible(cur.type, tv)) this.err('TC303', line, `"${tgt.text}" is ${typeWords(cur.type)}, so it can't be set to ${typeWords(tv)}.`);
|
|
320
473
|
else if (known(cur.type) && known(tv) && !compatible(cur.type, tv)) this.err('TC303', line, `"${tgt.text}" was ${typeWords(cur.type)} (line ${cur.line}); now it is set to ${typeWords(tv)}. A name keeps one kind of value.`, 'Use a new name for the new kind of value.');
|
|
@@ -337,6 +490,9 @@ class Checker {
|
|
|
337
490
|
this.afterAssign(s, tgt, sc);
|
|
338
491
|
}
|
|
339
492
|
lvalue(e, sc, line) {
|
|
493
|
+
let root = e;
|
|
494
|
+
while (root.k === 'field' || root.k === 'at') root = root.obj;
|
|
495
|
+
if (root.k === 'name' && (root.ref?.kind === 'input' || root.ref?.kind === 'item')) { this.inputChanged(root, root.ref, line); return; }
|
|
340
496
|
if (e.k === 'name') {
|
|
341
497
|
if (e.ref?.kind === 'const') this.err('TC205', line, `"${e.text}" is kept at a fixed value, so it can't be changed.`);
|
|
342
498
|
} else if (e.k === 'field' || e.k === 'at') {
|
package/src/core/cli.mjs
CHANGED
|
@@ -8,14 +8,25 @@
|
|
|
8
8
|
// - --core is given (a single file with no project)
|
|
9
9
|
// Everything else falls through to the mission commands, unchanged.
|
|
10
10
|
|
|
11
|
-
import { readFileSync, writeFileSync, existsSync, statSync } from 'node:fs';
|
|
12
|
-
import { resolve, relative, join } from 'node:path';
|
|
13
|
-
import { findProjectRoot, buildProject, findPython, runPython, newProject, TARGETS } from './project.mjs';
|
|
11
|
+
import { readFileSync, writeFileSync, existsSync, statSync, readdirSync } from 'node:fs';
|
|
12
|
+
import { resolve, relative, join, basename } from 'node:path';
|
|
13
|
+
import { findProjectRoot, buildProject, findPython, runPython, newProject, TARGETS, TARGET_NAMES } from './project.mjs';
|
|
14
14
|
import { runTypeScript } from './typescript-run.mjs';
|
|
15
|
+
import { runCSharp } from './csharp-run.mjs';
|
|
16
|
+
import { runRust, rustModule } from './rust-run.mjs';
|
|
17
|
+
import { runGo } from './go-run.mjs';
|
|
18
|
+
import { runJava } from './java-run.mjs';
|
|
19
|
+
import { javaClassName } from './target-java.mjs';
|
|
15
20
|
import { formatDiagnostic } from './diagnostics.mjs';
|
|
16
21
|
import { formatCore } from './format.mjs';
|
|
17
|
-
import { paint } from '../term.mjs';
|
|
22
|
+
import { paint, paintThunder, useColor } from '../term.mjs';
|
|
18
23
|
import { runWithEngine, testWithEngine, ENGINES } from './engine.mjs';
|
|
24
|
+
import { recordedRun, screenApp, screenOutline, runInProcess } from './engine-core.mjs';
|
|
25
|
+
import { hasScreens } from './target-react.mjs';
|
|
26
|
+
import { COMPILER_VERSION } from '../emit.mjs';
|
|
27
|
+
|
|
28
|
+
/** The format of a Time Machine recording (thunder run --record, thunder replay). */
|
|
29
|
+
export const TIME_MACHINE_SCHEMA = 'thunder-time-machine-v1';
|
|
19
30
|
|
|
20
31
|
const CORE_COMMANDS = new Set(['new', 'run', 'build', 'test', 'check', 'format', 'fmt']);
|
|
21
32
|
|
|
@@ -26,6 +37,8 @@ function parse(argv) {
|
|
|
26
37
|
if (x === '--target') a.target = argv[++i] ?? '';
|
|
27
38
|
else if (x.startsWith('--target=')) a.target = x.slice('--target='.length);
|
|
28
39
|
else if (x === '--engine') a.engine = argv[++i] ?? '';
|
|
40
|
+
else if (x === '--record') a.record = argv[++i] ?? '';
|
|
41
|
+
else if (x.startsWith('--record=')) a.record = x.slice('--record='.length);
|
|
29
42
|
else if (x.startsWith('--engine=')) a.engine = x.slice('--engine='.length);
|
|
30
43
|
else if (x === '--core') a.core = true;
|
|
31
44
|
else if (x === '--json') a.json = true;
|
|
@@ -48,6 +61,11 @@ export function coreTarget(cmd, argv, cwd = process.cwd()) {
|
|
|
48
61
|
const file = a._[0];
|
|
49
62
|
if (!file) { const root = findProjectRoot(cwd); return root && !a.other ? { root, file: null } : null; }
|
|
50
63
|
const p = resolve(cwd, file);
|
|
64
|
+
// Inside a project, its own name means the project: in hello/, `thunder run hello` runs hello.
|
|
65
|
+
if (!existsSync(p)) {
|
|
66
|
+
const here = findProjectRoot(cwd);
|
|
67
|
+
if (here && !a.other && (file === basename(here) || file === '.')) return { root: here, file: null };
|
|
68
|
+
}
|
|
51
69
|
if (existsSync(p) && statSync(p).isDirectory()) { const root = existsSync(join(p, 'thunder.toml')) ? p : null; return root ? { root, file: null } : null; }
|
|
52
70
|
if (!file.endsWith('.thunder')) return null;
|
|
53
71
|
const root = findProjectRoot(p);
|
|
@@ -87,9 +105,15 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
|
|
|
87
105
|
if (cmd === 'format' || cmd === 'fmt') return format(t, a, cwd);
|
|
88
106
|
if (a.engine !== null && !ENGINES.includes(a.engine)) { warn(`thunder ${cmd}: there is no engine "${a.engine}". Use --engine python (the default) or --engine thunder.`); return 2; }
|
|
89
107
|
if (a.engine !== null && cmd !== 'run' && cmd !== 'test') { warn(`thunder ${cmd}: --engine is for thunder run and thunder test.`); return 2; }
|
|
90
|
-
if (a.target !== null && !TARGETS.includes(a.target)) { warn(`thunder ${cmd}: there is no target "${a.target}". Use --target python (the default)
|
|
91
|
-
if (a.
|
|
92
|
-
|
|
108
|
+
if (a.target !== null && !TARGETS.includes(a.target)) { warn(`thunder ${cmd}: there is no target "${a.target}". Use --target python (the default)${TARGETS.filter((x) => x !== 'python').map((x) => `, --target ${x}`).join('')}.`); return 2; }
|
|
109
|
+
if (a.record != null) {
|
|
110
|
+
if (cmd !== 'run') { warn(`thunder ${cmd}: --record is for thunder run.`); return 2; }
|
|
111
|
+
if (!a.record) { warn('thunder run: --record needs a file to save the recording in, like --record run.trace.json'); return 2; }
|
|
112
|
+
if ((a.engine && a.engine !== 'thunder') || (a.target && a.target !== 'python')) { warn('thunder run: a recording is made on the Thunder engine; leave out --engine and --target.'); return 2; }
|
|
113
|
+
}
|
|
114
|
+
if (a.target !== null && a.target !== 'python' && a.engine === 'thunder') { warn(`thunder ${cmd}: choose one: --target ${a.target} runs compiled ${TARGET_NAMES[a.target] ?? a.target}, --engine thunder runs Thunder directly.`); return 2; }
|
|
115
|
+
if (a.target === 'react' && cmd === 'test') { warn('thunder test: tests run on Python (the default) or on the Thunder engine (--engine thunder). --target react builds the app: thunder build --target react.'); return 2; }
|
|
116
|
+
const build = buildProject({ root: t.root, single: t.file, includeTests: cmd === 'test' || cmd === 'check', write: cmd !== 'check' && !(cmd === 'run' && a.target === 'react'), target: a.target, refuseScreens: cmd === 'build' });
|
|
93
117
|
if (cmd === 'check') {
|
|
94
118
|
if (a.json) { say(JSON.stringify({ ok: build.ok, files: build.results.map((r) => ({ file: relative(cwd, r.path), diagnostics: r.diagnostics })) }, null, 2)); return build.ok ? 0 : 1; }
|
|
95
119
|
const n = report(build, cwd);
|
|
@@ -99,6 +123,22 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
|
|
|
99
123
|
}
|
|
100
124
|
if (!build.ok) { const n = report(build, cwd); warn(`thunder ${cmd}: ${n} problem${n === 1 ? '' : 's'}; nothing was ${cmd === 'build' ? 'built' : 'run'}.`); return 1; }
|
|
101
125
|
const out = relative(cwd, build.outDir) || '.';
|
|
126
|
+
if (cmd === 'run' && a.record == null && build.entry && hasScreens(build.entry.info)) return showScreens(build, warn);
|
|
127
|
+
if (cmd === 'build' && build.target === 'react') {
|
|
128
|
+
const shown = build.results.filter((r) => r.kind !== 'test' && hasScreens(r.info));
|
|
129
|
+
say(`thunder build: ${shown.length} file${shown.length === 1 ? '' : 's'} with screens -> ${out}/ (React)`);
|
|
130
|
+
for (const r of shown) say(` ${relative(cwd, r.path)} -> ${out}/${r.module}.tsx`);
|
|
131
|
+
say(` ${out}/main.tsx and index.html (the app starts on "${build.entry.info.screens[0].text}"), thunder_runtime.mjs (the small runtime it uses), thunder.css, package.json`);
|
|
132
|
+
say(` run it: cd ${out} && npm install && npm run dev (Node 18 or newer; check the types with: npm run typecheck)`);
|
|
133
|
+
return 0;
|
|
134
|
+
}
|
|
135
|
+
if (cmd === 'build' && build.target === 'rust') {
|
|
136
|
+
say(`thunder build: ${build.results.length} file${build.results.length === 1 ? '' : 's'} -> ${out}/ (Rust)`);
|
|
137
|
+
for (const r of build.results) say(` ${relative(cwd, r.path)} -> ${out}/${rustModule(r.module)}.rs`);
|
|
138
|
+
say(` ${out}/thunder_runtime.rs (the small runtime the generated code uses, standard library only), main.rs, and Cargo.toml`);
|
|
139
|
+
say(` run it without Thunder: cd ${build.base === cwd ? '.' : relative(cwd, build.base)} && cargo run --offline --manifest-path ${relative(build.base, build.outDir) || '.'}/Cargo.toml (add -- --tests for the tests)`);
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
102
142
|
if (cmd === 'build' && build.target === 'typescript') {
|
|
103
143
|
say(`thunder build: ${build.results.length} file${build.results.length === 1 ? '' : 's'} -> ${out}/ (TypeScript)`);
|
|
104
144
|
for (const r of build.results) say(` ${relative(cwd, r.path)} -> ${out}/${r.module}.ts`);
|
|
@@ -106,6 +146,27 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
|
|
|
106
146
|
say(` run it without Thunder: node ${out}/${build.entryModule}.ts (Node 22.6 or newer; check the types with: tsc -p ${out})`);
|
|
107
147
|
return 0;
|
|
108
148
|
}
|
|
149
|
+
if (cmd === 'build' && build.target === 'csharp') {
|
|
150
|
+
say(`thunder build: ${build.results.length} file${build.results.length === 1 ? '' : 's'} -> ${out}/ (C#)`);
|
|
151
|
+
for (const r of build.results) say(` ${relative(cwd, r.path)} -> ${out}/${r.module}.cs`);
|
|
152
|
+
say(` ${out}/ThunderRuntime.cs (the small runtime the generated code uses), Program.cs, and ThunderProgram.csproj`);
|
|
153
|
+
say(` run it without Thunder: dotnet run --project ${out} (.NET 8 or newer; add -- test to run the tests)`);
|
|
154
|
+
return 0;
|
|
155
|
+
}
|
|
156
|
+
if (cmd === 'build' && build.target === 'go') {
|
|
157
|
+
say(`thunder build: ${build.results.length} file${build.results.length === 1 ? '' : 's'} -> ${out}/ (Go)`);
|
|
158
|
+
for (const r of build.results) say(` ${relative(cwd, r.path)} -> ${out}/${r.module}.go`);
|
|
159
|
+
say(` ${out}/thunder/thunder_runtime.go (the small runtime the generated code uses), with go.mod`);
|
|
160
|
+
say(` run it without Thunder: cd ${out} && go run . (Go 1.21 or newer; its tests: go run -tags thundertests .)`);
|
|
161
|
+
return 0;
|
|
162
|
+
}
|
|
163
|
+
if (cmd === 'build' && build.target === 'java') {
|
|
164
|
+
say(`thunder build: ${build.results.length} file${build.results.length === 1 ? '' : 's'} -> ${out}/ (Java 17+)`);
|
|
165
|
+
for (const r of build.results) say(` ${relative(cwd, r.path)} -> ${out}/app/${javaClassName(r.module)}.java`);
|
|
166
|
+
say(` ${out}/thunder/ThunderRuntime.java and T.java (the small runtime the generated code uses)`);
|
|
167
|
+
say(` run it without Thunder: javac -d ${out}/classes $(find ${out}/app ${out}/thunder -name '*.java') && java -cp ${out}/classes app.${javaClassName(build.entryModule ?? 'main')}`);
|
|
168
|
+
return 0;
|
|
169
|
+
}
|
|
109
170
|
if (cmd === 'build') {
|
|
110
171
|
say(`thunder build: ${build.results.length} file${build.results.length === 1 ? '' : 's'} -> ${out}/ (Python 3.10+)`);
|
|
111
172
|
for (const r of build.results) say(` ${relative(cwd, r.path)} -> ${out}/${r.module}.py`);
|
|
@@ -113,8 +174,13 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
|
|
|
113
174
|
say(` run it without Thunder: cd ${build.base === cwd ? '.' : relative(cwd, build.base)} && python3 ${relative(build.base, build.outDir)}/${build.entryModule}.py`);
|
|
114
175
|
return 0;
|
|
115
176
|
}
|
|
177
|
+
if (a.record != null) return recordRun(build, a.record, cwd, warn);
|
|
116
178
|
if (a.engine === 'thunder') return runOnEngine(cmd, build, warn, say);
|
|
117
179
|
if (build.target === 'typescript') return runCompiledTypeScript(cmd, build, warn, say);
|
|
180
|
+
if (build.target === 'csharp') return runCompiledCSharp(cmd, build, warn, say);
|
|
181
|
+
if (build.target === 'rust') return runCompiledRust(cmd, build, warn, say);
|
|
182
|
+
if (build.target === 'go') return runCompiledGo(cmd, build, warn, say);
|
|
183
|
+
if (build.target === 'java') return runCompiledJava(cmd, build, warn, say);
|
|
118
184
|
const python = findPython();
|
|
119
185
|
if (python.error) { warn(`thunder ${cmd}: ${python.error}${['run', 'test'].includes(cmd) ? `\nOr run it without Python, on the Thunder engine: thunder ${cmd} ${argv.filter((x) => !x.startsWith('--engine')).join(' ')}${argv.length ? ' ' : ''}--engine thunder`.replace(/ +/g, ' ') : ''}`); return 2; }
|
|
120
186
|
if (cmd === 'run') {
|
|
@@ -135,6 +201,26 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
|
|
|
135
201
|
return null;
|
|
136
202
|
}
|
|
137
203
|
|
|
204
|
+
/**
|
|
205
|
+
* thunder run on a program with screens: its steps (if any) run on the Thunder engine, then its first screen is shown
|
|
206
|
+
* as an outline. A screen needs someone to press its buttons, so the outline is the screen as it first appears.
|
|
207
|
+
*/
|
|
208
|
+
function showScreens(build, warn) {
|
|
209
|
+
const main = build.entry.program.main ?? [];
|
|
210
|
+
if (main.length) {
|
|
211
|
+
const r = runInProcess({ entry: build.entry, cwd: build.base, readText: (p, dir) => readFileSync(resolve(dir, p), 'utf8') });
|
|
212
|
+
if (r.refused) { warn(`thunder run: ${r.stderr.trim()}`); return 2; }
|
|
213
|
+
if (r.stdout) process.stdout.write(r.stdout);
|
|
214
|
+
if (r.stderr) { process.stderr.write(r.stderr); return r.status; }
|
|
215
|
+
}
|
|
216
|
+
const app = screenApp({ entry: build.entry, cwd: build.base, readText: (p, dir) => readFileSync(resolve(dir, p), 'utf8') });
|
|
217
|
+
const tree = app.render();
|
|
218
|
+
process.stdout.write(`${screenOutline(tree)}\n`);
|
|
219
|
+
if (tree.k === 'failed') return 1;
|
|
220
|
+
warn(paint(`(The app starts on this screen. Build it as a React app: thunder build --target react)`, useColor(process.stderr)));
|
|
221
|
+
return 0;
|
|
222
|
+
}
|
|
223
|
+
|
|
138
224
|
/** thunder run / test with the TypeScript target: the compiled TypeScript runs on Node. */
|
|
139
225
|
function runCompiledTypeScript(cmd, build, warn, say) {
|
|
140
226
|
if (cmd === 'run' && !build.entryModule) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
|
|
@@ -144,6 +230,60 @@ function runCompiledTypeScript(cmd, build, warn, say) {
|
|
|
144
230
|
return r.status ?? 1;
|
|
145
231
|
}
|
|
146
232
|
|
|
233
|
+
/** thunder run --record <file>: run on the Thunder engine and save a step-by-step recording (the Time Machine). */
|
|
234
|
+
function recordRun(build, file, cwd, warn) {
|
|
235
|
+
if (!build.entry) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
|
|
236
|
+
const r = recordedRun({ entry: build.entry, cwd: build.base, readText: (p, dir) => readFileSync(resolve(dir, p), 'utf8') });
|
|
237
|
+
if (r.refused) { warn(`thunder run: ${r.stderr.trim()}`); return 2; }
|
|
238
|
+
if (r.stdout) process.stdout.write(r.stdout);
|
|
239
|
+
if (r.stderr) process.stderr.write(r.stderr);
|
|
240
|
+
const files = {};
|
|
241
|
+
for (const x of build.results) { try { files[x.rel ?? relative(build.base, x.path)] = readFileSync(x.path, 'utf8'); } catch { /* not readable */ } }
|
|
242
|
+
const trace = { schema: TIME_MACHINE_SCHEMA, thunder: COMPILER_VERSION, engine: 'thunder', program: build.entry.file, status: r.status, stdout: r.stdout, stderr: r.stderr, truncated: r.truncated, files, steps: r.steps };
|
|
243
|
+
writeFileSync(resolve(cwd, file), `${JSON.stringify(trace, null, 1)}\n`);
|
|
244
|
+
warn(paint(`Recorded ${r.steps.length} step${r.steps.length === 1 ? '' : 's'}${r.truncated ? ' (the recording stopped at its limit; the program ran to the end)' : ''} in ${file}.\nStep through it: thunder replay ${file}`, useColor(process.stderr)));
|
|
245
|
+
return r.status;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** thunder run / test with the C# target: the compiled C# is built with the .NET SDK and run. */
|
|
249
|
+
function runCompiledCSharp(cmd, build, warn, say) {
|
|
250
|
+
if (cmd === 'run' && !build.entryModule) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
|
|
251
|
+
if (cmd === 'test' && !build.results.reduce((n, r) => n + r.info.tests.length, 0)) { say('thunder test: no Test blocks found. Write one: Test "what it checks": then Expect … lines.'); return 0; }
|
|
252
|
+
const r = runCSharp(build.outDir, { tests: cmd === 'test', cwd: build.base, stdio: 'inherit' });
|
|
253
|
+
if (r.error && typeof r.error === 'string') { warn(`thunder ${cmd}: ${r.error}`); return 2; }
|
|
254
|
+
return r.status ?? 1;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** thunder run / test with the Rust target: cargo builds the compiled Rust (offline), then it runs. */
|
|
258
|
+
function runCompiledRust(cmd, build, warn, say) {
|
|
259
|
+
if (cmd === 'run' && !build.entryModule) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
|
|
260
|
+
if (cmd === 'test' && !build.results.reduce((n, r) => n + r.info.tests.length, 0)) { say('thunder test: no Test blocks found. Write one: Test "what it checks": then Expect … lines.'); return 0; }
|
|
261
|
+
const r = runRust(build.outDir, { tests: cmd === 'test', cwd: build.base, stdio: 'inherit' });
|
|
262
|
+
if (r.error && typeof r.error === 'string') { warn(`thunder ${cmd}: ${r.stderr.trimEnd()}`); return 2; }
|
|
263
|
+
return r.status ?? 1;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** thunder run / test with the Go target: the compiled Go is built and run with the go toolchain. */
|
|
267
|
+
function runCompiledGo(cmd, build, warn, say) {
|
|
268
|
+
if (cmd === 'run' && !build.entryModule) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
|
|
269
|
+
if (cmd === 'test' && !build.results.reduce((n, r) => n + r.info.tests.length, 0)) { say('thunder test: no Test blocks found. Write one: Test "what it checks": then Expect … lines.'); return 0; }
|
|
270
|
+
const r = runGo(build.outDir, { tests: cmd === 'test', cwd: build.base, stdio: 'inherit' });
|
|
271
|
+
if (r.error && typeof r.error === 'string') { warn(`thunder ${cmd}: ${r.error}`); return 2; }
|
|
272
|
+
if (r.buildFailed) { warn(`thunder ${cmd}: ${r.stderr}`); return 2; }
|
|
273
|
+
return r.status ?? 1;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** thunder run / test with the Java target: javac compiles the generated Java, and java runs it. */
|
|
277
|
+
function runCompiledJava(cmd, build, warn, say) {
|
|
278
|
+
if (cmd === 'run' && !build.entryModule) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
|
|
279
|
+
if (cmd === 'test' && !build.results.reduce((n, r) => n + r.info.tests.length, 0)) { say('thunder test: no Test blocks found. Write one: Test "what it checks": then Expect … lines.'); return 0; }
|
|
280
|
+
const files = [...readdirDeep(build.outDir, 'app'), ...readdirDeep(build.outDir, 'thunder')];
|
|
281
|
+
const r = runJava(build.outDir, files, cmd === 'run' ? build.entryModule : 'RunTests', { cwd: build.base, stdio: 'inherit' });
|
|
282
|
+
if (r.error && typeof r.error === 'string') { warn(`thunder ${cmd}: ${r.stderr.trimEnd()}`); return 2; }
|
|
283
|
+
return r.status ?? 1;
|
|
284
|
+
}
|
|
285
|
+
const readdirDeep = (root, dir) => { try { return readdirSync(join(root, dir)).filter((f) => f.endsWith('.java')).map((f) => `${dir}/${f}`); } catch { return []; } };
|
|
286
|
+
|
|
147
287
|
/** thunder run / test --engine thunder: the program runs on the Thunder engine, with no Python. */
|
|
148
288
|
function runOnEngine(cmd, build, warn, say) {
|
|
149
289
|
if (cmd === 'run') {
|
|
@@ -176,7 +316,7 @@ function format(t, a, cwd) {
|
|
|
176
316
|
changed++;
|
|
177
317
|
if (a.write) { writeFileSync(f, out); say(`formatted ${relative(cwd, f)}`); }
|
|
178
318
|
else if (a.check) warn(`would format ${relative(cwd, f)}`);
|
|
179
|
-
else process.stdout.write(out);
|
|
319
|
+
else process.stdout.write(paintThunder(out));
|
|
180
320
|
}
|
|
181
321
|
if (a.check) return changed ? 1 : 0;
|
|
182
322
|
if (a.write && !changed) say('thunder format: nothing to change.');
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// Writing compiled C# to disk, building it with the .NET SDK, and running it.
|
|
2
|
+
//
|
|
3
|
+
// A build is an ordinary console project: one <module>.cs per Thunder file (a static class), ThunderRuntime.cs, and a
|
|
4
|
+
// Program.cs that runs the program (`dotnet ThunderProgram.dll`) or its tests (`dotnet ThunderProgram.dll test`).
|
|
5
|
+
// Several programs can share one build (one namespace each, picked by number), which is how the conformance tests
|
|
6
|
+
// keep .NET's build time down.
|
|
7
|
+
import { writeFileSync, mkdirSync, readFileSync, existsSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
import { toCSharp, pythonOnlyUses, classOf, cs } from './target-csharp.mjs';
|
|
11
|
+
import { diag } from './diagnostics.mjs';
|
|
12
|
+
|
|
13
|
+
export const CS_RUNTIME = readFileSync(new URL('./ThunderRuntime.cs', import.meta.url), 'utf8');
|
|
14
|
+
export const ASSEMBLY = 'ThunderProgram';
|
|
15
|
+
|
|
16
|
+
/** TC405 for every Use in a file: Python modules exist only for the Python target. */
|
|
17
|
+
export function csharpDiagnostics(result) {
|
|
18
|
+
return pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
19
|
+
`"${u.module}" is a Python module, and this program is compiled to C#, which cannot use it.`,
|
|
20
|
+
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The .NET SDK here: { cmd, version, major } or { error }. */
|
|
24
|
+
export function findDotnet() {
|
|
25
|
+
const cmd = process.env.THUNDER_DOTNET || 'dotnet';
|
|
26
|
+
const r = spawnSync(cmd, ['--version'], { encoding: 'utf8' });
|
|
27
|
+
if (r.status !== 0 || !r.stdout) return { error: 'Building C# needs the .NET SDK (dotnet), version 8 or newer, and I could not find it. Install it from https://dotnet.microsoft.com/download or set THUNDER_DOTNET to its path. "thunder build --target csharp" still writes the C# without it.' };
|
|
28
|
+
const version = r.stdout.trim();
|
|
29
|
+
const major = Number(version.split('.')[0]);
|
|
30
|
+
if (!(major >= 8)) return { error: `Building C# needs the .NET SDK version 8 or newer, but "${cmd}" is ${version}. Install a newer one from https://dotnet.microsoft.com/download.` };
|
|
31
|
+
return { cmd, version, major };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const csproj = (major) => `<Project Sdk="Microsoft.NET.Sdk">
|
|
35
|
+
<!-- Generated by the Thunder compiler. Build: dotnet build; run: dotnet bin/${ASSEMBLY}.dll (add "test" to run the tests). -->
|
|
36
|
+
<PropertyGroup>
|
|
37
|
+
<OutputType>Exe</OutputType>
|
|
38
|
+
<TargetFramework>net${major}.0</TargetFramework>
|
|
39
|
+
<AssemblyName>${ASSEMBLY}</AssemblyName>
|
|
40
|
+
<RootNamespace>${ASSEMBLY}</RootNamespace>
|
|
41
|
+
<Nullable>disable</Nullable>
|
|
42
|
+
<ImplicitUsings>disable</ImplicitUsings>
|
|
43
|
+
<InvariantGlobalization>true</InvariantGlobalization>
|
|
44
|
+
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
|
45
|
+
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
|
46
|
+
<NoWarn>CS0162;CS0168;CS0219;CS0472;CS1717;CS8321;CS0414</NoWarn>
|
|
47
|
+
<EnableDefaultCompileItems>true</EnableDefaultCompileItems>
|
|
48
|
+
</PropertyGroup>
|
|
49
|
+
<ItemGroup>
|
|
50
|
+
<Compile Remove="bin/**;obj/**" />
|
|
51
|
+
</ItemGroup>
|
|
52
|
+
</Project>
|
|
53
|
+
`;
|
|
54
|
+
|
|
55
|
+
/** The C# for one program's results (src files, then test files) in `namespace`: { [module]: text }. */
|
|
56
|
+
export function compileCSharp(results, namespace = ASSEMBLY) {
|
|
57
|
+
const src = results.filter((r) => r.kind !== 'test');
|
|
58
|
+
const out = {};
|
|
59
|
+
for (const r of results) {
|
|
60
|
+
const imports = r.kind === 'test' ? src.map((s) => s.module) : [];
|
|
61
|
+
out[r.module] = toCSharp(r.program, r.info, { source: r.file, module: r.module, namespace, imports });
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The statements that run one program (`entry`) or its tests, the way the other targets load and run them. */
|
|
67
|
+
function runCode(results, entry, namespace, indent) {
|
|
68
|
+
const pad = ' '.repeat(indent);
|
|
69
|
+
const q = (m) => `${namespace}.${classOf(m)}`;
|
|
70
|
+
const tests = [
|
|
71
|
+
...results.map((r) => `${q(r.module)}.Init();`),
|
|
72
|
+
`T.runTests(new (string, (string, System.Action, int)[])[] { ${results.map((r) => `(${cs(r.file)}, ${q(r.module)}.THUNDER_TESTS)`).join(', ')} });`,
|
|
73
|
+
];
|
|
74
|
+
const run = entry ? [`${q(entry.module)}.Init();`, `T.run(${q(entry.module)}.main);`] : [];
|
|
75
|
+
return { tests: tests.map((l) => pad + l).join('\n'), run: run.map((l) => pad + l).join('\n') };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Write a project for `results` into `outDir`: <module>.cs, ThunderRuntime.cs, Program.cs, ThunderProgram.csproj.
|
|
80
|
+
* `entry` is the result `thunder run` runs.
|
|
81
|
+
*/
|
|
82
|
+
export function writeCSharp(results, outDir, { entry = results.find((r) => r.kind !== 'test') ?? null, major = findDotnet().major ?? 8 } = {}) {
|
|
83
|
+
mkdirSync(outDir, { recursive: true });
|
|
84
|
+
const files = compileCSharp(results);
|
|
85
|
+
for (const [m, text] of Object.entries(files)) writeFileSync(join(outDir, `${m}.cs`), text);
|
|
86
|
+
writeFileSync(join(outDir, 'ThunderRuntime.cs'), CS_RUNTIME);
|
|
87
|
+
const code = runCode(results, entry, ASSEMBLY, 16);
|
|
88
|
+
writeFileSync(join(outDir, 'Program.cs'), `// Generated by the Thunder compiler: runs the program, or every Test block with "test".
|
|
89
|
+
using Thunder;
|
|
90
|
+
|
|
91
|
+
namespace ${ASSEMBLY}
|
|
92
|
+
{
|
|
93
|
+
public static class Program
|
|
94
|
+
{
|
|
95
|
+
public static int Main(string[] args)
|
|
96
|
+
{
|
|
97
|
+
bool tests = args.Length > 0 && args[0] == "test";
|
|
98
|
+
return T.Start(() =>
|
|
99
|
+
{
|
|
100
|
+
if (tests)
|
|
101
|
+
{
|
|
102
|
+
${code.tests}
|
|
103
|
+
}
|
|
104
|
+
else
|
|
105
|
+
{
|
|
106
|
+
${code.run}
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
`);
|
|
113
|
+
writeFileSync(join(outDir, `${ASSEMBLY}.csproj`), csproj(major));
|
|
114
|
+
return Object.keys(files);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Write one build holding many programs, each in its own namespace (P0, P1, …), chosen when it runs:
|
|
119
|
+
* `dotnet ThunderProgram.dll <n> [test]`. `programs`: [{ results, entry }].
|
|
120
|
+
*/
|
|
121
|
+
export function writeCSharpBatch(programs, outDir, { major = findDotnet().major ?? 8 } = {}) {
|
|
122
|
+
mkdirSync(outDir, { recursive: true });
|
|
123
|
+
const cases = [];
|
|
124
|
+
programs.forEach((p, i) => {
|
|
125
|
+
const ns = `P${i}`;
|
|
126
|
+
for (const [m, text] of Object.entries(compileCSharp(p.results, ns))) writeFileSync(join(outDir, `${ns}_${m}.cs`), text);
|
|
127
|
+
const code = runCode(p.results, p.entry, ns, 24);
|
|
128
|
+
cases.push(` case ${i}:\n if (tests)\n {\n${code.tests}\n }\n else\n {\n${code.run}\n }\n break;`);
|
|
129
|
+
});
|
|
130
|
+
writeFileSync(join(outDir, 'ThunderRuntime.cs'), CS_RUNTIME);
|
|
131
|
+
writeFileSync(join(outDir, 'Program.cs'), `// Generated by the Thunder compiler: many programs in one build, chosen by number.
|
|
132
|
+
using Thunder;
|
|
133
|
+
|
|
134
|
+
namespace ${ASSEMBLY}
|
|
135
|
+
{
|
|
136
|
+
public static class Program
|
|
137
|
+
{
|
|
138
|
+
public static int Main(string[] args)
|
|
139
|
+
{
|
|
140
|
+
int which = int.Parse(args[0]);
|
|
141
|
+
bool tests = args.Length > 1 && args[1] == "test";
|
|
142
|
+
return T.Start(() =>
|
|
143
|
+
{
|
|
144
|
+
switch (which)
|
|
145
|
+
{
|
|
146
|
+
${cases.join('\n')}
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
`);
|
|
153
|
+
writeFileSync(join(outDir, `${ASSEMBLY}.csproj`), csproj(major));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** dotnet build the project in `outDir` into outDir/bin. { ok, output } or { error } when there is no .NET SDK. */
|
|
157
|
+
export function buildCSharp(outDir, { dotnet = findDotnet() } = {}) {
|
|
158
|
+
if (dotnet.error) return { ok: false, error: dotnet.error };
|
|
159
|
+
const r = spawnSync(dotnet.cmd, ['build', join(outDir, `${ASSEMBLY}.csproj`), '-nologo', '-v', 'q', '-clp:NoSummary;ErrorsOnly', '-o', join(outDir, 'bin')], {
|
|
160
|
+
encoding: 'utf8', env: { ...process.env, DOTNET_CLI_TELEMETRY_OPTOUT: '1', DOTNET_NOLOGO: '1', DOTNET_SKIP_FIRST_TIME_EXPERIENCE: '1' }, maxBuffer: 64 * 1024 * 1024,
|
|
161
|
+
});
|
|
162
|
+
return { ok: r.status === 0, output: `${r.stdout ?? ''}${r.stderr ?? ''}`.trim() };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Run a built project: `dotnet bin/ThunderProgram.dll …args` in the folder `cwd`. spawnSync's result. */
|
|
166
|
+
export function runBuiltCSharp(outDir, args = [], { cwd = outDir, stdio = 'pipe', dotnet = findDotnet() } = {}) {
|
|
167
|
+
return spawnSync(dotnet.cmd, [join(outDir, 'bin', `${ASSEMBLY}.dll`), ...args], {
|
|
168
|
+
cwd, stdio, encoding: 'utf8', env: { ...process.env, DOTNET_CLI_TELEMETRY_OPTOUT: '1', DOTNET_NOLOGO: '1' }, maxBuffer: 64 * 1024 * 1024,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Build (if needed) and run the project in `outDir`: the program, or its tests when `tests`. Returns spawnSync's
|
|
174
|
+
* result, or { status: 2, stderr, error } when C# cannot be built or run here.
|
|
175
|
+
*/
|
|
176
|
+
export function runCSharp(outDir, { tests = false, cwd = outDir, stdio = 'pipe' } = {}) {
|
|
177
|
+
const dotnet = findDotnet();
|
|
178
|
+
if (dotnet.error) return { status: 2, stdout: '', stderr: `${dotnet.error}\n`, error: dotnet.error };
|
|
179
|
+
const b = buildCSharp(outDir, { dotnet });
|
|
180
|
+
if (!b.ok) return { status: 2, stdout: '', stderr: `The C# did not build:\n${b.output}\n`, error: `The C# did not build:\n${b.output}` };
|
|
181
|
+
return runBuiltCSharp(outDir, tests ? ['test'] : [], { cwd, stdio, dotnet });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export const csharpBuilt = (outDir) => existsSync(join(outDir, 'bin', `${ASSEMBLY}.dll`));
|