@skillstech/thunderlang 1.2.0 → 1.4.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 (63) hide show
  1. package/CHANGELOG.md +190 -0
  2. package/dist/core.cjs +6718 -1232
  3. package/dist/index.cjs +17490 -12204
  4. package/dist/learn.cjs +5866 -497
  5. package/package.json +6 -2
  6. package/src/cli-home.mjs +1 -1
  7. package/src/cli.mjs +54 -6
  8. package/src/core/ThunderRuntime.cs +1367 -0
  9. package/src/core/check.mjs +158 -2
  10. package/src/core/cli.mjs +148 -8
  11. package/src/core/csharp-run.mjs +184 -0
  12. package/src/core/diagnostics.mjs +13 -1
  13. package/src/core/engine-core.mjs +285 -2
  14. package/src/core/engine-values.mjs +1 -1
  15. package/src/core/format.mjs +191 -3
  16. package/src/core/go-run.mjs +106 -0
  17. package/src/core/index.mjs +2 -1
  18. package/src/core/java/thunder/T.java +6 -0
  19. package/src/core/java/thunder/ThunderRuntime.java +1374 -0
  20. package/src/core/java-run.mjs +89 -0
  21. package/src/core/parser.mjs +331 -5
  22. package/src/core/project.mjs +31 -6
  23. package/src/core/react-run.mjs +96 -0
  24. package/src/core/runtime-go/thunder_runtime.go +3038 -0
  25. package/src/core/runtime-react.mjs +133 -0
  26. package/src/core/rust/thunder_runtime.rs +1645 -0
  27. package/src/core/rust-run.mjs +192 -0
  28. package/src/core/screen-values.mjs +30 -0
  29. package/src/core/target-csharp.mjs +484 -0
  30. package/src/core/target-go.mjs +555 -0
  31. package/src/core/target-java.mjs +587 -0
  32. package/src/core/target-react.mjs +270 -0
  33. package/src/core/target-rust.mjs +534 -0
  34. package/src/core/target-typescript.mjs +2 -2
  35. package/src/core.d.ts +59 -0
  36. package/src/core.mjs +14 -0
  37. package/src/emit.mjs +1 -1
  38. package/src/faithful.mjs +34 -1
  39. package/src/flow/access.mjs +1451 -0
  40. package/src/flow/ts-parse.mjs +772 -0
  41. package/src/index.d.ts +3 -0
  42. package/src/index.mjs +3 -0
  43. package/src/libraries.mjs +32 -4
  44. package/src/model.mjs +72 -9
  45. package/src/passport-cli.mjs +101 -0
  46. package/src/passport-fs.d.mts +9 -0
  47. package/src/passport-fs.mjs +180 -0
  48. package/src/passport.d.mts +46 -0
  49. package/src/passport.mjs +255 -0
  50. package/src/program.d.mts +31 -0
  51. package/src/program.mjs +14 -0
  52. package/src/read-level.mjs +48 -2
  53. package/src/read-repo-fs.mjs +3 -1
  54. package/src/read.mjs +64 -5
  55. package/src/replay-cli.mjs +123 -0
  56. package/src/review.mjs +31 -3
  57. package/src/say-less.mjs +168 -13
  58. package/src/screens.mjs +833 -0
  59. package/src/steps.mjs +443 -20
  60. package/src/term.mjs +43 -0
  61. package/src/things-langs.mjs +20 -3
  62. package/src/write-across-cli.mjs +143 -0
  63. package/src/write-across.mjs +168 -0
@@ -17,6 +17,13 @@ export const CODES = {
17
17
  TC110: '"If this fails:" without a statement before it',
18
18
  TC111: '"Receive" is not the first line of a "To" block',
19
19
  TC112: 'Something extra at the end of a line',
20
+ TC113: 'A line under a record or call written as a block is not "name: value"',
21
+ TC114: 'A field or an input is given twice',
22
+ TC115: 'A function called with names has no input of that name (or its inputs are not known)',
23
+ TC116: 'A function called with names is missing an input it needs',
24
+ TC117: 'Lines like "name: value" with no record or function call to give them to',
25
+ TC118: 'A line inside a Screen is not something a screen can show',
26
+ TC119: '"Receive" or "Remember" is not at the top of a Screen',
20
27
  TC201: 'Unknown name',
21
28
  TC202: 'A name uses a word that belongs to Thunder',
22
29
  TC203: 'A name is defined twice',
@@ -28,6 +35,9 @@ export const CODES = {
28
35
  TC209: 'Unknown record',
29
36
  TC210: 'A record is missing a field',
30
37
  TC211: 'A name is used before it is set',
38
+ TC212: 'Unknown screen',
39
+ TC213: 'An input of a screen is changed',
40
+ TC214: 'A screen is given an input it does not have, or is missing one it needs',
31
41
  TC301: 'Money and a plain number are mixed',
32
42
  TC302: 'Values of different kinds are compared',
33
43
  TC303: 'A name changes kind',
@@ -38,7 +48,9 @@ export const CODES = {
38
48
  TC402: 'Thunder Core does not support this yet',
39
49
  TC403: 'A "Never" rule names more than one changing value',
40
50
  TC404: 'A default for an input must be a fixed value, after the inputs without one',
41
- TC405: 'A Python module ("Use") cannot be used when compiling to TypeScript',
51
+ TC405: 'A Python module ("Use") can be used only when compiling to Python',
52
+ TC406: 'A Screen is built only for React (--target react)',
53
+ TC407: 'A step that cannot run when a button is pressed',
42
54
  TC501: 'Divided by zero (runtime)',
43
55
  TC502: 'Nothing used where a value was needed (runtime)',
44
56
  TC503: 'A field or entry is missing (runtime)',
@@ -18,6 +18,7 @@ import {
18
18
  attrErr, strMethod, splitLines, pySplit, pyStrip, jsonParse, jsonText, isInt, isNumber,
19
19
  } from './engine-values.mjs';
20
20
  import * as V from './engine-values.mjs';
21
+ import { shownText, copyValue, typedNumber, problemText } from './screen-values.mjs';
21
22
  import { percentDecimal } from './target-python.mjs';
22
23
  import { firstLine } from './target-typescript.mjs';
23
24
 
@@ -33,6 +34,8 @@ const nativeOverflow = (e) => { try { return e instanceof RangeError || (e insta
33
34
  class NeedsDeeperStack extends Error {}
34
35
 
35
36
  const MAX_FRAMES = V.MAX_FRAMES;
37
+ const CONTAINER_KINDS = new Set(['if', 'each', 'range', 'times', 'while', 'tryFail']); // statements with steps inside
38
+ const MAX_RECORDED = 20000; // a recording stops growing here (and says so); the program still runs to the end
36
39
 
37
40
  /** The Python modules a program uses (Use), which this engine does not run. */
38
41
  export function pythonModulesUsed(results) {
@@ -55,8 +58,10 @@ class Module {
55
58
  class Engine {
56
59
  // readText(path, cwd): the text of a file the program reads, or throws with .code 'ENOENT' / 'EISDIR'. Without it
57
60
  // (a browser), reading a file is reported as a missing file.
58
- constructor({ cwd = '.', deeper = false, readText = null } = {}) {
61
+ // record: keep a step-by-step recording of the run (the Thunder Time Machine; see recordedRun below).
62
+ constructor({ cwd = '.', deeper = false, readText = null, record = false } = {}) {
59
63
  this.cwd = cwd;
64
+ this.rec = record ? { steps: [], truncated: false } : null;
60
65
  this.readText = readText;
61
66
  // deeper: if JavaScript's own stack runs out, stop and say so (NeedsDeeperStack) instead of reporting it as the
62
67
  // program's error, so the caller can run it again where the stack is deep enough.
@@ -110,7 +115,7 @@ class Engine {
110
115
  call(fn, args) {
111
116
  if (!fn?.isFunc) throw TypeErr(`'${fn === null ? 'NoneType' : typeof fn}' object is not callable`);
112
117
  const { f, mod } = fn;
113
- const frame = { file: mod.file, line: f.line };
118
+ const frame = { file: mod.file, line: f.line, fn: f.name ?? f.py };
114
119
  if (this.frames.length >= MAX_FRAMES) {
115
120
  // Python makes the new call's frame, then stops at its first line (a line with no Thunder mark, like the
116
121
  // check for a default, leaves the error at the caller's line).
@@ -183,6 +188,43 @@ class Engine {
183
188
  }
184
189
 
185
190
  stmt(s, env) {
191
+ if (this.rec) return this.recordStep(s, env);
192
+ return this.runStmt(s, env);
193
+ }
194
+
195
+ /**
196
+ * The Time Machine: one step per statement, in the order they run. A step keeps the line, how deep in calls it
197
+ * is, the values it changed (before -> after, as the program would show them), and what it printed. A statement
198
+ * with steps inside (a choice, a loop) keeps only where it went next; the steps inside are recorded on their own.
199
+ */
200
+ recordStep(s, env) {
201
+ const rec = this.rec;
202
+ if (rec.steps.length >= MAX_RECORDED) { rec.truncated = true; return this.runStmt(s, env); }
203
+ const names = () => { const m = new Map(); for (const [k, v] of env.locals) if (!v?.isFunc) m.set(k, v); return m; };
204
+ const view = (v) => { try { return typeof v === 'string' ? pyStr(v) : show(v); } catch { return '…'; } };
205
+ const before = new Map([...names()].map(([k, v]) => [k, view(v)]));
206
+ const step = { n: rec.steps.length + 1, file: env.frame.file, line: s.line, depth: this.frames.length, fn: env.frame.fn ?? null, kind: s.k };
207
+ const outFrom = this.out.length;
208
+ rec.steps.push(step);
209
+ const inner = rec.steps.length;
210
+ const container = CONTAINER_KINDS.has(s.k);
211
+ const finish = (failed, gave) => {
212
+ const nested = rec.steps.length > inner;
213
+ if (container && nested) { step.next = rec.steps[inner].line; if (failed) step.failed = true; return; }
214
+ if (container) step.next = null; // a choice or loop whose steps did not run (a condition that was false)
215
+ const said = nested ? '' : this.out.slice(outFrom).join(''); // (output from a call is on the call's own steps)
216
+ if (gave !== undefined) step.gives = view(gave);
217
+ const changes = [];
218
+ for (const [k, v] of names()) { const after = view(v); if (before.get(k) !== after) changes.push({ name: k.replace(/_/g, ' '), ...(before.has(k) ? { before: before.get(k) } : {}), after }); }
219
+ if (changes.length) step.changes = changes;
220
+ if (said) step.said = said;
221
+ if (failed) step.failed = true;
222
+ };
223
+ try { const r = this.runStmt(s, env); finish(false); return r; }
224
+ catch (e) { if (e instanceof Return) finish(false, e.v); else finish(true); throw e; }
225
+ }
226
+
227
+ runStmt(s, env) {
186
228
  const L = s.line;
187
229
  const fr = env.frame;
188
230
  fr.line = L;
@@ -278,6 +320,7 @@ class Engine {
278
320
  return;
279
321
  }
280
322
  case 'do': this.x(s.e, env); return;
323
+ case 'open': env.opens = s.name; return;
281
324
  case 'tryFail':
282
325
  try { this.stmt(s.stmt, env); }
283
326
  catch (e) {
@@ -534,6 +577,24 @@ export function runInProcess({ entry, cwd, deeper = false, readText = null } = {
534
577
  return { status, stdout: eng.out.join(''), stderr };
535
578
  }
536
579
 
580
+ /**
581
+ * Run a program and keep a step-by-step recording of it (the Thunder Time Machine, `thunder run --record`).
582
+ * Gives back { status, stdout, stderr, steps, truncated }. Like runInProcess, on the calling thread.
583
+ */
584
+ export function recordedRun({ entry, cwd, readText = null } = {}) {
585
+ const uses = pythonModulesUsed([entry]);
586
+ if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses, steps: [] };
587
+ const eng = new Engine({ cwd, readText, record: true });
588
+ let stderr = '', status = 0;
589
+ try {
590
+ const mod = eng.load(entry);
591
+ eng.runMain(mod);
592
+ } catch (e) {
593
+ if (!(e instanceof Return)) { stderr = `${eng.describeError(asPyErr(e))}\n`; status = 1; }
594
+ }
595
+ return { status, stdout: eng.out.join(''), stderr, steps: eng.rec.steps, truncated: eng.rec.truncated };
596
+ }
597
+
537
598
  /** The same, on the calling thread. */
538
599
  export function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
539
600
  const uses = pythonModulesUsed(results);
@@ -565,6 +626,228 @@ export function testInProcess({ results, cwd, deeper = false, readText = null }
565
626
  return { status: failed ? 1 : 0, stdout: eng.out.join(''), stderr: '' };
566
627
  }
567
628
 
629
+ // ── screens ────────────────────────────────────────────────────────────────────────────────────────────────────
630
+ //
631
+ // A screen is shown as a tree of plain values (the same tree compiled React's HTML is read back into by the
632
+ // conformance tests), and changed one event at a time: a press runs its steps on copies of the remembered values
633
+ // and keeps them only if every step works; typing sets the box's value. Each shown screen remembers its own values,
634
+ // by its place on the screen (as React keeps a component's state by its place), and forgets them when it goes away.
635
+ //
636
+ // { k: 'screen', name, children: [...] } a screen (the app's, or one shown inside another)
637
+ // { k: 'heading', text } { k: 'text', text } { k: 'row', children } { k: 'list', items: [[...], ...] }
638
+ // { k: 'textbox' | 'numberbox', label, value } { k: 'button', label, off }
639
+ // { k: 'problem', text } what the last press or typing on this screen said, when it failed
640
+ // { k: 'failed', text } the app could not be shown (the same message thunder run gives)
641
+
642
+ class ScreenApp {
643
+ constructor(eng, entry) {
644
+ this.eng = eng;
645
+ this.entry = entry;
646
+ this.screens = new Map(entry.info.screens.map((s) => [s.name, s]));
647
+ this.current = entry.info.screens[0] ?? null;
648
+ this.places = new Map(); // place -> { values: Map(py -> value), problem }
649
+ this.handlers = [];
650
+ try { this.mod = eng.load(entry); } catch (e) { this.loadFailed = e; }
651
+ }
652
+
653
+ /** The app as it is now, as a tree. */
654
+ render() {
655
+ this.handlers = [];
656
+ if (this.loadFailed) return { k: 'failed', text: this.eng.describeError(asPyErr(this.loadFailed)) };
657
+ if (!this.current) return { k: 'failed', text: 'This program has no Screen to show.' };
658
+ const seen = new Set();
659
+ try {
660
+ const tree = this.screen(this.current, new Map(), this.current.name, seen);
661
+ for (const k of [...this.places.keys()]) if (!seen.has(k)) this.places.delete(k); // gone: forgotten
662
+ return tree;
663
+ } catch (e) {
664
+ if (e instanceof NeedsDeeperStack) throw e;
665
+ this.places.clear();
666
+ return { k: 'failed', text: this.eng.describeError(asPyErr(e)) };
667
+ }
668
+ }
669
+
670
+ /** One screen at a place: its inputs (given, or their defaults), its remembered values, and what it shows. */
671
+ screen(s, given, place, seen) {
672
+ seen.add(place);
673
+ const eng = this.eng;
674
+ const frame = { file: this.mod.file, line: s.line };
675
+ // A screen shown inside another is shown on its own (as React renders each component by itself).
676
+ const saved = eng.frames;
677
+ eng.frames = [];
678
+ try {
679
+ return eng.withFrame(frame, () => {
680
+ const env = { mod: this.mod, locals: new Map(), frame };
681
+ for (const p of s.params) {
682
+ if (given.has(p.py)) env.locals.set(p.py, given.get(p.py));
683
+ else { frame.line = p.line; env.locals.set(p.py, p.dflt ? eng.x(p.dflt, env) : null); }
684
+ }
685
+ let st = this.places.get(place);
686
+ if (!st) {
687
+ const values = new Map();
688
+ st = { values, problem: null };
689
+ for (const r of s.remember) { frame.line = r.line; const v = eng.x(r.e, env); values.set(r.py, v); env.locals.set(r.py, v); }
690
+ this.places.set(place, st);
691
+ }
692
+ for (const [k, v] of st.values) env.locals.set(k, v);
693
+ const children = this.elements(s.body, env, s, place, st, seen);
694
+ if (st.problem !== null) children.push({ k: 'problem', text: st.problem });
695
+ return { k: 'screen', name: s.text, children };
696
+ });
697
+ } finally { eng.frames = saved; }
698
+ }
699
+
700
+ elements(els, env, s, place, st, seen) {
701
+ const eng = this.eng;
702
+ const fr = env.frame;
703
+ const out = [];
704
+ els.forEach((el, i) => {
705
+ const at = `${place}/${i}`;
706
+ fr.line = el.line;
707
+ switch (el.k) {
708
+ case 'heading': out.push({ k: 'heading', text: shownText(eng.x(el.e, env), el.e.type?.k) }); return;
709
+ case 'text': out.push({ k: 'text', text: shownText(eng.x(el.e, env), el.e.type?.k) }); return;
710
+ case 'when': {
711
+ for (let b = 0; b < el.branches.length; b++) {
712
+ fr.line = el.branches[b].line;
713
+ if (eng.yn(el.branches[b].cond, env)) { out.push(...this.elements(el.branches[b].body, env, s, `${at}.${b}`, st, seen)); return; }
714
+ }
715
+ if (el.otherwise) out.push(...this.elements(el.otherwise, env, s, `${at}.else`, st, seen));
716
+ return;
717
+ }
718
+ case 'list': {
719
+ const items = pyIter(eng.x(el.iter, env));
720
+ out.push({ k: 'list', items: items.map((item, n) => {
721
+ const inner = { ...env, locals: new Map(env.locals) };
722
+ inner.locals.set(el.v.py, item);
723
+ return this.elements(el.body, inner, s, `${at}#${n}`, st, seen);
724
+ }) });
725
+ return;
726
+ }
727
+ case 'row': out.push({ k: 'row', children: this.elements(el.body, env, s, at, st, seen) }); return;
728
+ case 'textbox': case 'numberbox': {
729
+ const label = pyStr(eng.x(el.label, env));
730
+ const v = env.locals.get(el.target.ref.py);
731
+ out.push({ k: el.k, label, value: el.k === 'textbox' ? pyStr(v) : show(v) });
732
+ this.handlers.push({ kind: 'box', label, type: (text) => {
733
+ try { st.values.set(el.target.ref.py, el.k === 'textbox' ? String(text) : typedNumber(text, el.boxKind)); st.problem = null; }
734
+ catch (e) { st.problem = problemText(e); }
735
+ } });
736
+ return;
737
+ }
738
+ case 'button': {
739
+ const label = pyStr(eng.x(el.label, env));
740
+ fr.line = el.line;
741
+ const off = el.off ? eng.yn(el.off, env) : false;
742
+ out.push({ k: 'button', label, off });
743
+ const locals = new Map(env.locals);
744
+ this.handlers.push({ kind: 'button', label, off, press: () => this.press(el, locals, st) });
745
+ return;
746
+ }
747
+ case 'child': {
748
+ const target = this.screens.get(el.screen.name);
749
+ const given = new Map();
750
+ for (const g of el.given) { fr.line = g.line; given.set(g.py, eng.x(g.e, env)); }
751
+ out.push(this.screen(target, given, `${at}:${target.name}`, seen));
752
+ return;
753
+ }
754
+ default: return;
755
+ }
756
+ });
757
+ return out;
758
+ }
759
+
760
+ /** A press: its steps run on copies of the screen's remembered values; they are kept only if every step works. */
761
+ press(el, locals, st) {
762
+ let opens = el.opens?.name ?? null;
763
+ if (el.press) {
764
+ const eng = this.eng;
765
+ const frame = { file: this.mod.file, line: el.press.line };
766
+ const env = { mod: this.mod, locals: new Map(locals), frame, opens: null };
767
+ for (const [k, v] of st.values) env.locals.set(k, copyValue(v));
768
+ try {
769
+ eng.withFrame(frame, () => eng.block(el.press.body, env));
770
+ } catch (e) {
771
+ if (e instanceof NeedsDeeperStack) throw e;
772
+ st.problem = problemText(e);
773
+ return;
774
+ }
775
+ for (const k of st.values.keys()) st.values.set(k, env.locals.get(k));
776
+ st.problem = null;
777
+ opens = env.opens ?? opens;
778
+ }
779
+ if (opens && opens !== this.current.name) { this.current = this.screens.get(opens); this.places.clear(); }
780
+ }
781
+
782
+ /** The button or box with this label (the nth one, from 1, when several have it). */
783
+ find(kind, label, nth = 1) {
784
+ const all = this.handlers.filter((h) => h.kind === kind && h.label === label);
785
+ const h = all[nth - 1];
786
+ if (!h) {
787
+ const labels = [...new Set(this.handlers.filter((x) => x.kind === kind).map((x) => `"${x.label}"`))];
788
+ throw new Error(`There is no ${kind === 'box' ? 'box' : 'button'} "${label}" on the screen${all.length ? ` (only ${all.length})` : ''}.${labels.length ? ` There is ${labels.join(', ')}.` : ''}`);
789
+ }
790
+ return h;
791
+ }
792
+ }
793
+
794
+ /**
795
+ * Show a program's screens and change them one event at a time, on the Thunder engine:
796
+ * const app = screenApp({ entry }); app.render() -> tree; app.press("Add"); app.type("Name", "Ada"); app.render()
797
+ * A press on a button that is off does nothing (and says so). Each event is followed by a render, as in React.
798
+ */
799
+ export function screenApp({ entry, cwd = '.', readText = null } = {}) {
800
+ const app = new ScreenApp(new Engine({ cwd, readText }), entry);
801
+ let tree = app.render();
802
+ return {
803
+ render: () => tree,
804
+ get screen() { return app.current?.text ?? null; },
805
+ press(label, nth = 1) {
806
+ const h = app.find('button', label, nth);
807
+ if (h.off) return { off: true, tree };
808
+ h.press();
809
+ tree = app.render();
810
+ return { off: false, tree };
811
+ },
812
+ type(label, text, nth = 1) {
813
+ app.find('box', label, nth).type(text);
814
+ tree = app.render();
815
+ return { tree };
816
+ },
817
+ };
818
+ }
819
+
820
+ /** A screen tree as an outline people read (thunder run). */
821
+ export function screenOutline(tree, indent = '') {
822
+ const L = [];
823
+ const q = (t) => JSON.stringify(t);
824
+ const walk = (n, ind) => {
825
+ switch (n.k) {
826
+ case 'failed': L.push(`${ind}✗ The screen could not be shown: ${n.text}`); return;
827
+ case 'screen': L.push(`${ind}Screen ${q(n.name)}`); for (const c of n.children) walk(c, `${ind} `); return;
828
+ case 'heading': L.push(`${ind}Heading: ${n.text}`); return;
829
+ case 'text': L.push(`${ind}${n.text}`); return;
830
+ case 'row': L.push(`${ind}Row:`); for (const c of n.children) walk(c, `${ind} `); return;
831
+ case 'list':
832
+ if (!n.items.length) { L.push(`${ind}List: (no items)`); return; }
833
+ L.push(`${ind}List:`);
834
+ for (const item of n.items) {
835
+ const start = L.length;
836
+ for (const c of item) walk(c, `${ind} `);
837
+ if (L.length > start) L[start] = `${ind} • ${L[start].slice(ind.length + 4)}`; else L.push(`${ind} •`);
838
+ }
839
+ return;
840
+ case 'textbox': L.push(`${ind}Text box ${q(n.label)}: ${q(n.value)}`); return;
841
+ case 'numberbox': L.push(`${ind}Number box ${q(n.label)}: ${n.value}`); return;
842
+ case 'button': L.push(`${ind}Button ${q(n.label)}${n.off ? ' (off)' : ''}`); return;
843
+ case 'problem': L.push(`${ind}! ${n.text}`); return;
844
+ default: return;
845
+ }
846
+ };
847
+ walk(tree, indent);
848
+ return L.join('\n');
849
+ }
850
+
568
851
  /**
569
852
  * Run a job on a worker thread with a large stack and wait for it: the program's results are copied to the
570
853
  * worker (structured clone keeps the shared references the checker made), and the answer comes back the same way.
@@ -633,7 +633,7 @@ export function jsonParse(text) {
633
633
  if (ch === '[') return arr(i + 1);
634
634
  if (s.startsWith('null', i)) return [null, i + 4];
635
635
  if (s.startsWith('true', i)) return [true, i + 4];
636
- if (s.startsWith('false', i)) return [false, i + 4];
636
+ if (s.startsWith('false', i)) return [false, i + 5];
637
637
  NUM.lastIndex = i;
638
638
  const m = NUM.exec(s);
639
639
  if (m) {
@@ -1,7 +1,33 @@
1
- // thunder format for Thunder Core: two spaces per block level, no trailing spaces, at most one blank line in a
2
- // row, and a newline at the end. It changes only layout, never words, so it cannot change what a program means.
1
+ // thunder format: the one way Thunder Core is written (the "Thunder style", docs/core.md).
2
+ //
3
+ // 1. Layout: two spaces per block level, no trailing spaces, at most one blank line in a row, a newline at the end.
4
+ // 2. Structure, read from the program itself (its records, their fields, its functions):
5
+ // - short stays short: a record built on one line keeps that line while it has 1 to 3 fields and fits in 100
6
+ // columns; with 4 or more fields, or past 100 columns, it becomes a block of "field: value" lines;
7
+ // - a long condition (When, If, Otherwise when, Repeat while/until) wraps before "and" / "or".
8
+ // 3. Spacing: one blank line around each function (To), record (A … has), and Test block.
9
+ //
10
+ // It never changes what a program means: a block record is the same program as the one-line form, and a wrapped
11
+ // condition is joined back into the same line when it is read. Comments stay where they are. Formatting twice gives
12
+ // the same text as formatting once. Lines that are already in the Thunder style are left exactly as they are.
3
13
 
4
- export function formatCore(source) {
14
+ import { tokenizeLine } from './lexer.mjs';
15
+ import { parseCore, RESERVED } from './parser.mjs';
16
+
17
+ export const FORMAT_WIDTH = 100;
18
+ const MAX_INLINE_FIELDS = 3;
19
+
20
+ export function formatCore(source, { width = FORMAT_WIDTH } = {}) {
21
+ let text = layout(source);
22
+ let names = null;
23
+ try { names = parseCore(text).names; } catch { /* a program that cannot be read keeps its layout only */ }
24
+ if (names) text = layout(structure(text, names, width));
25
+ return spacing(text);
26
+ }
27
+
28
+ // ── 1. layout ─────────────────────────────────────────────────────────────────────────────────────────────────
29
+
30
+ function layout(source) {
5
31
  const lines = source.replace(/\r\n?/g, '\n').split('\n');
6
32
  const out = [];
7
33
  const stack = [0]; // original indents of open blocks
@@ -18,3 +44,165 @@ export function formatCore(source) {
18
44
  }
19
45
  return out.length ? `${out.join('\n')}\n` : '';
20
46
  }
47
+
48
+ // ── 2. structure ──────────────────────────────────────────────────────────────────────────────────────────────
49
+
50
+ /** A line's code and its comment ("# …" outside text). */
51
+ function splitComment(line) {
52
+ let q = false;
53
+ for (let i = 0; i < line.length; i++) {
54
+ const c = line[i];
55
+ if (c === '"' || c === '“' || c === '”') q = !q;
56
+ else if (c === '#' && !q) return [line.slice(0, i).replace(/\s+$/, ''), line.slice(i)];
57
+ }
58
+ return [line, ''];
59
+ }
60
+
61
+ const isWord = (t, w) => t && t.t === 'word' && (w === undefined || t.lower === w);
62
+ const isSym = (t, s) => t && t.t === 'sym' && t.text === s;
63
+ const keyOf = (ts) => ts.map((t) => t.lower).join(' ');
64
+
65
+ /** Token indexes at the top level (outside parentheses and brackets) that satisfy pred. */
66
+ function topLevel(ts, pred, from = 0, to = ts.length) {
67
+ const out = [];
68
+ let depth = 0;
69
+ for (let k = from; k < to; k++) {
70
+ const t = ts[k];
71
+ if (isSym(t, '(') || isSym(t, '[')) depth++;
72
+ else if (isSym(t, ')') || isSym(t, ']')) depth--;
73
+ else if (depth === 0 && pred(t, k)) out.push(k);
74
+ }
75
+ return out;
76
+ }
77
+
78
+ /** The longest run of words starting at k whose key satisfies ok: its length, or 0. */
79
+ function longest(ts, k, ok) {
80
+ const run = [];
81
+ for (let j = k; isWord(ts[j]) && !RESERVED.has(ts[j].lower); j++) run.push(ts[j]);
82
+ for (let n = run.length; n > 0; n--) if (ok(keyOf(run.slice(0, n)))) return n;
83
+ return 0;
84
+ }
85
+
86
+ function structure(text, names, width) {
87
+ const out = [];
88
+ for (const line of text.replace(/\n$/, '').split('\n')) {
89
+ const [code, comment] = splitComment(line);
90
+ if (!code.trim()) { out.push(line); continue; }
91
+ const indent = code.match(/^ */)[0];
92
+ let ts;
93
+ try { ts = tokenizeLine(code.slice(indent.length), 1); } catch { out.push(line); continue; }
94
+ const expanded = expandRecord(code, indent, ts, comment, names, width);
95
+ if (expanded) { out.push(...expanded); continue; }
96
+ const wrapped = wrapCondition(code, indent, ts, comment, width);
97
+ if (wrapped) { out.push(...wrapped); continue; }
98
+ out.push(line);
99
+ }
100
+ return `${out.join('\n')}\n`;
101
+ }
102
+
103
+ /**
104
+ * A record built on one line, as the whole value of Set, Give, Add … to, or Expect … to, becomes a block when it is long:
105
+ * Set trade to a Trade with symbol "ACME" and quantity 10 and buy price $20.00 and sell price $40.00
106
+ * ->
107
+ * Set trade to a Trade:
108
+ * symbol: "ACME"
109
+ * …
110
+ * Fields are found exactly as the parser finds them; each value is copied from the line as written.
111
+ */
112
+ function expandRecord(code, indent, ts, comment, names, width) {
113
+ const w0 = ts[0]?.lower;
114
+ let from, to = ts.length;
115
+ if (w0 === 'set') { const k = topLevel(ts, (t) => isWord(t, 'to'))[0]; if (k == null) return null; from = k + 1; }
116
+ else if (w0 === 'give') from = 1;
117
+ else if (w0 === 'add') { const k = topLevel(ts, (t) => isWord(t, 'to')).pop(); if (k == null) return null; from = 1; to = k; }
118
+ else if (w0 === 'expect') {
119
+ // Expect <record> to be / to fail / to contain …: the record is everything before that "to".
120
+ const k = topLevel(ts, (t, j) => isWord(t, 'to') && ['be', 'fail', 'contain'].some((w) => isWord(ts[j + 1], w)))[0];
121
+ if (k == null) return null;
122
+ from = 1; to = k;
123
+ } else return null;
124
+ if (!(isWord(ts[from], 'a') || isWord(ts[from], 'an'))) return null;
125
+ const rn = longest(ts, from + 1, (key) => names.records.has(key));
126
+ if (!rn || !isWord(ts[from + 1 + rn], 'with')) return null;
127
+ const record = keyOf(ts.slice(from + 1, from + 1 + rn));
128
+ const own = names.recordFields?.get(record);
129
+ // The fields, split exactly where the parser splits them: at "and" or "," followed by a field name.
130
+ const fieldAt = (k) => longest(ts, k, (key) => names.fields.has(key));
131
+ const fields = [];
132
+ let k = from + 1 + rn + 1;
133
+ while (k < to) {
134
+ const fn = fieldAt(k);
135
+ if (!fn) return null;
136
+ const valueFrom = k + fn;
137
+ const seps = topLevel(ts, (t, j) => (isWord(t, 'and') || isSym(t, ',')) && fieldAt(j + 1) > 0, valueFrom, to);
138
+ const valueTo = seps.length ? seps[0] : to;
139
+ if (valueTo <= valueFrom) return null;
140
+ fields.push({ key: keyOf(ts.slice(k, k + fn)), text: ts.slice(k, k + fn).map((t) => t.text).join(' '), from: valueFrom, to: valueTo });
141
+ k = valueTo + 1;
142
+ }
143
+ if (!fields.length || (own && fields.some((f) => !own.includes(f.key))) || new Set(fields.map((f) => f.key)).size !== fields.length) return null;
144
+ if (fields.length <= MAX_INLINE_FIELDS && code.length + (comment ? comment.length + 2 : 0) <= width) return null;
145
+ const body = code.slice(indent.length);
146
+ const col = (j) => (j < ts.length ? ts[j].col - 1 : body.length); // where token j starts in the line (or its end)
147
+ const head = `${body.slice(0, col(from + 1 + rn)).replace(/\s+$/, '')}${w0 === 'add' || w0 === 'expect' ? ` ${body.slice(col(to)).trim()}` : ''}:`;
148
+ return [`${indent}${head}${comment ? ` ${comment}` : ''}`, ...fields.map((f) => `${indent} ${f.text}: ${body.slice(col(f.from), col(f.to)).trim()}`)];
149
+ }
150
+
151
+ /**
152
+ * A long condition wraps before each "and" / "or" that joins its parts (not the "and" of "between 1 and 10", nor
153
+ * the ones that separate a call's values):
154
+ * When member is yes
155
+ * and total is at least 100:
156
+ */
157
+ function wrapCondition(code, indent, ts, comment, width) {
158
+ if (code.length + (comment ? comment.length + 2 : 0) <= width) return null;
159
+ const lead = keyOf(ts.slice(0, 2));
160
+ const starts = isWord(ts[0], 'when') || isWord(ts[0], 'if') || lead === 'otherwise when' || lead === 'otherwise if' || lead === 'repeat while' || lead === 'repeat until';
161
+ if (!starts || !isSym(ts[ts.length - 1], ':') || keyOf(ts.slice(0, 3)) === 'if this fails') return null;
162
+ // Split points: a top-level and/or that is not owed to a "between" or to a call's "with" list.
163
+ let owed = 0, inWith = false;
164
+ const splits = [];
165
+ topLevel(ts, (t, j) => {
166
+ if (isWord(t, 'between')) owed++;
167
+ else if (isWord(t, 'with')) inWith = true;
168
+ else if (isWord(t, 'is') || isWord(t, 'are') || ['<', '>', '<=', '>=', '=', '==', '!='].some((s) => isSym(t, s))) inWith = false;
169
+ else if (isWord(t, 'and') && owed) owed--;
170
+ else if ((isWord(t, 'and') && !inWith) || isWord(t, 'or')) { splits.push(j); inWith = false; }
171
+ return false;
172
+ });
173
+ if (!splits.length) return null;
174
+ const body = code.slice(indent.length);
175
+ const parts = [];
176
+ let start = 0;
177
+ for (const j of splits) { parts.push(body.slice(start, ts[j].col - 1).trim()); start = ts[j].col - 1; }
178
+ parts.push(body.slice(start).trim());
179
+ if (parts.some((p) => !p)) return null;
180
+ return parts.map((p, i) => `${indent}${i ? ' ' : ''}${p}${i === parts.length - 1 && comment ? ` ${comment}` : ''}`);
181
+ }
182
+
183
+ // ── 3. spacing ────────────────────────────────────────────────────────────────────────────────────────────────
184
+
185
+ /** One blank line before and after each function, record, and Test block at the top level. */
186
+ function spacing(text) {
187
+ const lines = text.replace(/\n$/, '').split('\n');
188
+ if (lines.length === 1 && !lines[0]) return '';
189
+ const isDefinition = (l) => /^(?:To\b.*:|Test\b.*:|An?\b.*\bhas:)\s*(?:#.*)?$/i.test(l);
190
+ const isComment = (l) => /^\s*#/.test(l);
191
+ const out = [];
192
+ let inDefinition = false;
193
+ for (const l of lines) {
194
+ const top = l && !/^\s/.test(l);
195
+ if (top && isDefinition(l)) {
196
+ // A blank line before it, above any comment written right over it (unless that is the top of the file).
197
+ let k = out.length;
198
+ while (k > 0 && isComment(out[k - 1]) && !/^\s/.test(out[k - 1])) k--;
199
+ if (k > 0 && out[k - 1] !== '') out.splice(k, 0, '');
200
+ inDefinition = true;
201
+ } else if (top && inDefinition && !isComment(l)) {
202
+ if (out[out.length - 1] !== '') out.push('');
203
+ inDefinition = false;
204
+ }
205
+ out.push(l);
206
+ }
207
+ return `${out.join('\n').replace(/\n{3,}/g, '\n\n')}\n`;
208
+ }