@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
@@ -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,23 +8,45 @@
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 } 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
+ 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';
14
20
  import { formatDiagnostic } from './diagnostics.mjs';
15
21
  import { formatCore } from './format.mjs';
22
+ import { paint, paintThunder, useColor } from '../term.mjs';
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';
16
30
 
17
31
  const CORE_COMMANDS = new Set(['new', 'run', 'build', 'test', 'check', 'format', 'fmt']);
18
32
 
19
33
  function parse(argv) {
20
- const a = { _: [], core: false, json: false, write: false, check: false, force: false, mission: false };
21
- for (const x of argv) {
22
- if (x === '--core') a.core = true;
34
+ const a = { _: [], core: false, json: false, write: false, check: false, force: false, mission: false, engine: null, target: null };
35
+ for (let i = 0; i < argv.length; i++) {
36
+ const x = argv[i];
37
+ if (x === '--target') a.target = argv[++i] ?? '';
38
+ else if (x.startsWith('--target=')) a.target = x.slice('--target='.length);
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);
42
+ else if (x.startsWith('--engine=')) a.engine = x.slice('--engine='.length);
43
+ else if (x === '--core') a.core = true;
23
44
  else if (x === '--json') a.json = true;
24
45
  else if (x === '--write' || x === '-w') a.write = true;
25
46
  else if (x === '--check') a.check = true;
26
47
  else if (x === '--force') a.force = true;
27
48
  else if (x === '--mission') a.mission = true;
49
+ else if (x === '--run') a.run = true;
28
50
  else if (x.startsWith('--')) a.other = true;
29
51
  else a._.push(x);
30
52
  }
@@ -39,6 +61,11 @@ export function coreTarget(cmd, argv, cwd = process.cwd()) {
39
61
  const file = a._[0];
40
62
  if (!file) { const root = findProjectRoot(cwd); return root && !a.other ? { root, file: null } : null; }
41
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
+ }
42
69
  if (existsSync(p) && statSync(p).isDirectory()) { const root = existsSync(join(p, 'thunder.toml')) ? p : null; return root ? { root, file: null } : null; }
43
70
  if (!file.endsWith('.thunder')) return null;
44
71
  const root = findProjectRoot(p);
@@ -46,7 +73,7 @@ export function coreTarget(cmd, argv, cwd = process.cwd()) {
46
73
  return null;
47
74
  }
48
75
 
49
- const say = (s = '') => process.stdout.write(`${s}\n`);
76
+ const say = (s = '') => process.stdout.write(`${paint(s)}\n`);
50
77
  const warn = (s = '') => process.stderr.write(`${s}\n`);
51
78
 
52
79
  function report(build, cwd) {
@@ -64,16 +91,29 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
64
91
  if (cmd === 'new') {
65
92
  const root = newProject(resolve(cwd, t.new), { force: a.force });
66
93
  const rel = relative(cwd, root) || '.';
67
- say(`thunder new: created a Thunder project in ${rel}`);
68
- say(` ${rel}/thunder.toml the project: name, and build target = "python"`);
69
- say(` ${rel}/src/main.thunder your program`);
70
- say(` ${rel}/tests/greet.thunder a test`);
71
- say(` next: cd ${rel} then thunder run (and thunder test)`);
72
- say(` (wanted a mission file instead? thunder init ${t.new})`);
73
- return 0;
94
+ say(`Created ${rel}, a new Thunder program.`);
95
+ say('');
96
+ say('Run it:');
97
+ say(` thunder run ${rel}`);
98
+ say('');
99
+ say(`Then change ${join(rel, 'src', 'main.thunder')} and run it again. Check it works with: thunder test ${rel}`);
100
+ say(`(Wanted a mission file instead? thunder init ${t.new})`);
101
+ if (!a.run) return 0;
102
+ say('');
103
+ return coreMain('run', [root], cwd);
74
104
  }
75
105
  if (cmd === 'format' || cmd === 'fmt') return format(t, a, cwd);
76
- const build = buildProject({ root: t.root, single: t.file, includeTests: cmd === 'test' || cmd === 'check', write: cmd !== 'check' });
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; }
107
+ if (a.engine !== null && cmd !== 'run' && cmd !== 'test') { warn(`thunder ${cmd}: --engine is for thunder run and thunder test.`); return 2; }
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' });
77
117
  if (cmd === 'check') {
78
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; }
79
119
  const n = report(build, cwd);
@@ -83,6 +123,50 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
83
123
  }
84
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; }
85
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
+ }
142
+ if (cmd === 'build' && build.target === 'typescript') {
143
+ say(`thunder build: ${build.results.length} file${build.results.length === 1 ? '' : 's'} -> ${out}/ (TypeScript)`);
144
+ for (const r of build.results) say(` ${relative(cwd, r.path)} -> ${out}/${r.module}.ts`);
145
+ say(` ${out}/thunder_runtime.mjs (the small runtime the generated code uses), with its types and a tsconfig.json`);
146
+ say(` run it without Thunder: node ${out}/${build.entryModule}.ts (Node 22.6 or newer; check the types with: tsc -p ${out})`);
147
+ return 0;
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
+ }
86
170
  if (cmd === 'build') {
87
171
  say(`thunder build: ${build.results.length} file${build.results.length === 1 ? '' : 's'} -> ${out}/ (Python 3.10+)`);
88
172
  for (const r of build.results) say(` ${relative(cwd, r.path)} -> ${out}/${r.module}.py`);
@@ -90,8 +174,15 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
90
174
  say(` run it without Thunder: cd ${build.base === cwd ? '.' : relative(cwd, build.base)} && python3 ${relative(build.base, build.outDir)}/${build.entryModule}.py`);
91
175
  return 0;
92
176
  }
177
+ if (a.record != null) return recordRun(build, a.record, cwd, warn);
178
+ if (a.engine === 'thunder') return runOnEngine(cmd, build, warn, say);
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);
93
184
  const python = findPython();
94
- if (python.error) { warn(`thunder ${cmd}: ${python.error}`); return 2; }
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; }
95
186
  if (cmd === 'run') {
96
187
  if (!build.entryModule) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
97
188
  const r = runPython(python, build.outDir, `${build.entryModule}.py`, build.base);
@@ -110,6 +201,106 @@ export function coreMain(cmd, argv, cwd = process.cwd()) {
110
201
  return null;
111
202
  }
112
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
+
224
+ /** thunder run / test with the TypeScript target: the compiled TypeScript runs on Node. */
225
+ function runCompiledTypeScript(cmd, build, warn, say) {
226
+ if (cmd === 'run' && !build.entryModule) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
227
+ 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; }
228
+ const r = runTypeScript(build.outDir, cmd === 'run' ? `${build.entryModule}.ts` : 'run_tests.ts', { cwd: build.base, stdio: 'inherit' });
229
+ if (r.error && typeof r.error === 'string') { warn(`thunder ${cmd}: ${r.error}`); return 2; }
230
+ return r.status ?? 1;
231
+ }
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
+
287
+ /** thunder run / test --engine thunder: the program runs on the Thunder engine, with no Python. */
288
+ function runOnEngine(cmd, build, warn, say) {
289
+ if (cmd === 'run') {
290
+ if (!build.entry) { warn('thunder run: there is no program to run (no .thunder files in src/).'); return 1; }
291
+ const r = runWithEngine({ entry: build.entry, cwd: build.base });
292
+ if (r.stdout) process.stdout.write(r.stdout);
293
+ if (r.stderr) process.stderr.write(r.stderr.startsWith('This program uses') ? `thunder run: ${r.stderr}` : r.stderr);
294
+ return r.status;
295
+ }
296
+ const tests = build.results.reduce((n, r) => n + r.info.tests.length, 0);
297
+ if (!tests) { say('thunder test: no Test blocks found. Write one: Test "what it checks": then Expect … lines.'); return 0; }
298
+ const r = testWithEngine({ results: build.results, cwd: build.base });
299
+ if (r.stdout) process.stdout.write(r.stdout);
300
+ if (r.stderr) process.stderr.write(`thunder test: ${r.stderr}`);
301
+ return r.status;
302
+ }
303
+
113
304
  function format(t, a, cwd) {
114
305
  let files = [];
115
306
  if (t.file) files = [t.file];
@@ -125,7 +316,7 @@ function format(t, a, cwd) {
125
316
  changed++;
126
317
  if (a.write) { writeFileSync(f, out); say(`formatted ${relative(cwd, f)}`); }
127
318
  else if (a.check) warn(`would format ${relative(cwd, f)}`);
128
- else process.stdout.write(out);
319
+ else process.stdout.write(paintThunder(out));
129
320
  }
130
321
  if (a.check) return changed ? 1 : 0;
131
322
  if (a.write && !changed) say('thunder format: nothing to change.');