@skillstech/thunderlang 1.7.0 → 2.0.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 (73) hide show
  1. package/CHANGELOG.md +153 -1
  2. package/README.md +15 -3
  3. package/dist/core.cjs +303 -41
  4. package/dist/index.cjs +9906 -1387
  5. package/dist/learn.cjs +1420 -93
  6. package/package.json +17 -15
  7. package/src/cli-main.mjs +381 -149
  8. package/src/core/ThunderRuntime.cs +22 -1
  9. package/src/core/check.mjs +320 -6
  10. package/src/core/cli.mjs +60 -8
  11. package/src/core/csharp-run.mjs +2 -2
  12. package/src/core/diagnostics.mjs +9 -0
  13. package/src/core/engine-core.mjs +148 -19
  14. package/src/core/engine-values.mjs +3 -0
  15. package/src/core/engine.mjs +131 -7
  16. package/src/core/from-python.mjs +1 -1
  17. package/src/core/go-run.mjs +5 -3
  18. package/src/core/index.mjs +12 -3
  19. package/src/core/java/thunder/ThunderRuntime.java +1 -0
  20. package/src/core/java-run.mjs +2 -2
  21. package/src/core/kind.mjs +6 -0
  22. package/src/core/lexer.mjs +16 -2
  23. package/src/core/parser.mjs +215 -29
  24. package/src/core/project-root.mjs +18 -0
  25. package/src/core/project.mjs +34 -16
  26. package/src/core/react-run.mjs +2 -2
  27. package/src/core/runtime-go/thunder_runtime.go +310 -2
  28. package/src/core/runtime-python.mjs +365 -3
  29. package/src/core/runtime-typescript.mjs +150 -5
  30. package/src/core/rust/thunder_runtime.rs +1 -0
  31. package/src/core/rust-run.mjs +2 -2
  32. package/src/core/serving.mjs +12 -0
  33. package/src/core/store-format.mjs +110 -0
  34. package/src/core/target-csharp.mjs +14 -0
  35. package/src/core/target-go.mjs +24 -3
  36. package/src/core/target-java.mjs +14 -0
  37. package/src/core/target-python.mjs +46 -5
  38. package/src/core/target-rust.mjs +14 -0
  39. package/src/core/target-typescript.mjs +76 -6
  40. package/src/core/typescript-run.mjs +6 -4
  41. package/src/core-changes-fs.mjs +28 -0
  42. package/src/core-changes.d.mts +67 -0
  43. package/src/core-changes.mjs +603 -0
  44. package/src/core-rules.mjs +146 -0
  45. package/src/core-services.d.mts +4 -0
  46. package/src/core-services.mjs +49 -0
  47. package/src/emit.mjs +3 -3
  48. package/src/evidence-words.d.mts +6 -0
  49. package/src/evidence-words.mjs +47 -0
  50. package/src/evidence.mjs +36 -1
  51. package/src/examples.d.mts +21 -0
  52. package/src/examples.mjs +175 -0
  53. package/src/index.d.ts +19 -0
  54. package/src/index.mjs +8 -1
  55. package/src/learn-lessons.mjs +1 -1
  56. package/src/lsp.mjs +110 -0
  57. package/src/mcp.mjs +47 -12
  58. package/src/obligations.d.mts +5 -0
  59. package/src/obligations.mjs +30 -2
  60. package/src/program.d.mts +7 -0
  61. package/src/program.mjs +7 -0
  62. package/src/read-repo-fs.mjs +2 -1
  63. package/src/review.mjs +75 -6
  64. package/src/same.mjs +16 -6
  65. package/src/scan-queries.mjs +2 -1
  66. package/src/symbols.d.mts +23 -0
  67. package/src/symbols.mjs +351 -0
  68. package/src/system.mjs +1 -1
  69. package/src/template.d.mts +31 -0
  70. package/src/template.mjs +189 -0
  71. package/src/trace-cli.mjs +8 -3
  72. package/src/trace-fs.mjs +29 -3
  73. package/src/trace.mjs +23 -7
@@ -123,6 +123,9 @@ function collectNames(nodes, names) {
123
123
  } else if (w0 === 'keep') {
124
124
  const k = splitTop(ts, (t) => isWord(t, 'at'));
125
125
  add('const', stripArticle(ts.slice(1, k < 0 ? ts.length : k)));
126
+ } else if (w0 === 'store' && ts.some((t) => isWord(t, 'as'))) {
127
+ const k = splitTop(ts, (t) => isWord(t, 'as'));
128
+ add('const', stripArticle(ts.slice(1, k)));
126
129
  } else if (w0 === 'receive') {
127
130
  for (const p of paramGroups(ts.slice(1))) add('var', p.words);
128
131
  } else if (w0 === 'for' && isWord(ts[1], 'each')) {
@@ -139,6 +142,22 @@ function collectNames(nodes, names) {
139
142
  for (const p of paramGroups(c.tokens.slice(1))) inputs.push({ key: keyOf(p.words), text: p.words.map((x) => x.text).join(' '), defaultTokens: p.defaultTokens });
140
143
  }
141
144
  names.funcInputs.set(keyOf(ts.slice(1, -1)), inputs);
145
+ } else if ((w0 === 'a' || w0 === 'an') && isOneOf(ts)) {
146
+ // A Payment is one of: its alternatives (Successful with amount as money) and their fields, and "which".
147
+ const words = ts.slice(1, -4);
148
+ add('record', words);
149
+ const own = ['which'];
150
+ const alts = [];
151
+ for (const c of n.children) {
152
+ const at = c.tokens.findIndex((t) => isWord(t, 'with'));
153
+ const altWords = stripArticle(at < 0 ? c.tokens : c.tokens.slice(0, at));
154
+ if (altWords.length) { alts.push(keyOf(altWords)); names.alts.set(keyOf(altWords), [...(names.alts.get(keyOf(altWords)) ?? []), keyOf(words)]); }
155
+ if (at >= 0) for (const g of paramGroups(c.tokens.slice(at + 1))) if (g.words.length) { names.fields.add(keyOf(g.words)); own.push(keyOf(g.words)); }
156
+ }
157
+ names.fields.add('which');
158
+ names.recordFields.set(keyOf(words), [...new Set(own)]);
159
+ names.recordText.set(keyOf(words), words.map((x) => x.text).join(' '));
160
+ names.altsOf.set(keyOf(words), alts);
142
161
  } else if ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has')) {
143
162
  const words = ts.slice(1, -2);
144
163
  add('record', words);
@@ -180,6 +199,12 @@ function rememberName(ts) {
180
199
  }
181
200
 
182
201
  // "total and member", "total as money, member as yes/no", "price and rate (7% if not given)"
202
+ /** "A Payment is one of:": a data type with alternatives. */
203
+ function isOneOf(ts) {
204
+ const n = ts.length;
205
+ return n >= 6 && isSym(ts[n - 1], ':') && isWord(ts[n - 2], 'of') && isWord(ts[n - 3], 'one') && isWord(ts[n - 4], 'is');
206
+ }
207
+
183
208
  function paramGroups(ts) {
184
209
  const groups = [];
185
210
  let cur = [];
@@ -280,6 +305,15 @@ export class ExprParser {
280
305
  }
281
306
  if (s.word('in')) return wrap({ k: 'contains', l: this.add(s, o), r: l, line });
282
307
  if (s.done()) s.fail('Something is missing after "is".', 'For example: is 10, is at least 18, is nothing, is empty.', 'TC108');
308
+ // payment is successful: which alternative of a data type it is (a name of a value comes first).
309
+ if (this.names.alts?.size && s.peek()?.t === 'word') {
310
+ const run = []; for (let j = s.i; s.ts[j]?.t === 'word' && !RESERVED.has(s.ts[j].lower); j++) run.push(s.ts[j]);
311
+ const ak = this.longest(run, (key) => this.names.alts.has(key));
312
+ if (ak && !this.longest(run, (key) => this.names.known.has(key))) {
313
+ s.i += ak;
314
+ return wrap({ k: 'isAlt', e: l, alt: keyOf(run.slice(0, ak)), text: run.slice(0, ak).map((x) => x.text).join(' '), col: run[0].col, line });
315
+ }
316
+ }
283
317
  return { k: 'cmp', op: neg ? '!=' : '==', l, r: this.add(s, o), line };
284
318
  }
285
319
  return l;
@@ -318,7 +352,7 @@ export class ExprParser {
318
352
  if (!run.length) s.fail(`I expected a field name after "'s".`, null, 'TC108');
319
353
  const k = this.longest(run, (key) => this.names.fields.has(key)) || run.length;
320
354
  s.i -= run.length - k;
321
- e = { k: 'field', obj: e, name: keyOf(run.slice(0, k)), text: run.slice(0, k).map((w) => w.text).join(' '), line: s.line };
355
+ e = { k: 'field', obj: e, name: keyOf(run.slice(0, k)), text: run.slice(0, k).map((w) => w.text).join(' '), col: run[0].col, line: s.line };
322
356
  } else if (isWord(t, 'at') && !isWord(s.peek(1), 'least') && !isWord(s.peek(1), 'most')) {
323
357
  s.next();
324
358
  const key = this.unary(s, { ...o, noAnd: true });
@@ -412,12 +446,55 @@ export class ExprParser {
412
446
  if (!k) s.fail(`I don't know the kind of value "${run.map((x) => x.text).join(' ')}".`, 'Kinds: number, whole number, text, yes/no, money, date, list of …, map of … to …, optional …, or a record you defined with "A … has:".', 'TC306');
413
447
  s.i -= run.length - k;
414
448
  const key = keyOf(run.slice(0, k));
415
- return { k: 'record', name: this.names.records.has(key) ? key : key.replace(/s$/, '') };
449
+ return { k: 'record', name: this.names.records.has(key) ? key : key.replace(/s$/, ''), col: run[0].col, line: s.line };
450
+ }
451
+
452
+ /** The fields a record is built with: with name "Ann" and balance $10 (none without "with"). */
453
+ recordFields(s, line) {
454
+ const fields = [];
455
+ if (s.word('with')) {
456
+ do {
457
+ const fr = this.wordRun(s);
458
+ if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, 'TC108');
459
+ const fk = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
460
+ s.i -= fr.length - fk;
461
+ fields.push({ name: keyOf(fr.slice(0, fk)), text: fr.slice(0, fk).map((x) => x.text).join(' '), e: this.expr(s, { noAnd: true }), line });
462
+ } while ((isSym(s.peek(), ',') || isWord(s.peek(), 'and')) && this.fieldAhead(s, 1) && s.next());
463
+ }
464
+ return fields;
416
465
  }
417
466
 
418
467
  primary(s, o) {
419
468
  const t = s.peek();
420
469
  const line = s.line;
470
+ const METHODS = ['get', 'post', 'put', 'patch', 'delete'];
471
+ // the answer from GET "https://…" [with <value>] [as <Kind>]: call another service over HTTP.
472
+ if (isWord(t, 'answer') && isWord(s.peek(1), 'from') && METHODS.includes(s.peek(2)?.lower)) {
473
+ s.i += 2;
474
+ const method = s.next().text.toUpperCase();
475
+ const url = this.primary(s, { ...o, noAnd: true });
476
+ let body = null, as = null;
477
+ if (s.word('with')) {
478
+ body = this.expr(s, { ...o, noAnd: true });
479
+ // "with charge as Receipt": the "as" belongs to the call (what the answer is), not to the value sent.
480
+ if (body.k === 'conv' && body.type) { as = body.type; body = body.e; }
481
+ }
482
+ if (!as && s.word('as')) as = this.typeRef(s);
483
+ return { k: 'httpCall', method, url, body, as, line };
484
+ }
485
+ // calling GET /habits/walk [with name "run" and …]: an endpoint of this program, called directly (in tests).
486
+ if (isWord(t, 'calling') && METHODS.includes(s.peek(1)?.lower) && isSym(s.peek(2), '/')) {
487
+ s.i += 2;
488
+ const method = s.ts[s.i - 1].text.toUpperCase();
489
+ // The path is the tokens written against each other: / habits / walk (a space ends it).
490
+ let path = '';
491
+ let prev = null;
492
+ while (s.peek() && (prev === null ? isSym(s.peek(), '/') : s.peek().col === prev.col + String(prev.text).length && (isSym(s.peek(), '/') || isSym(s.peek(), '-') || s.peek().t === 'word' || s.peek().t === 'num'))) {
493
+ prev = s.next();
494
+ path += prev.text;
495
+ }
496
+ return { k: 'callEndpoint', method, path, fields: this.recordFields(s, line), line };
497
+ }
421
498
  if (!t) s.fail('A value is missing at the end of this line.', null, 'TC108');
422
499
  if (t.t === 'num') { s.next(); return { k: 'num', text: t.text, whole: t.whole, line }; }
423
500
  if (t.t === 'money') { s.next(); return { k: 'money', text: t.text, line }; }
@@ -431,6 +508,16 @@ export class ExprParser {
431
508
  s.next();
432
509
  return { k: 'str', parts: t.parts.map((p) => (typeof p === 'string' ? p : { e: this.parse(p.tokens, line), source: p.source })), line };
433
510
  }
511
+ // A hole in a draft: ? alone, or ?number / ?money / ?Habit with the kind written right after it. It never runs;
512
+ // the checker says what could go here and asks (TC120).
513
+ if (isSym(t, '?')) {
514
+ s.next();
515
+ const next = s.peek();
516
+ let want = null;
517
+ // A word right against the ? is its kind, so a misspelt kind is reported as one.
518
+ if (next && next.t === 'word' && t.col != null && next.col === t.col + 1) want = this.typeRef(s);
519
+ return { k: 'draftHole', want, line, col: t.col };
520
+ }
434
521
  if (isSym(t, '(')) { s.next(); const e = this.expr(s, {}); s.expectSym(')', 'to close the parenthesis'); return { k: 'paren', e, line }; }
435
522
  if (isSym(t, '[')) {
436
523
  s.next();
@@ -476,6 +563,26 @@ export class ExprParser {
476
563
  if (RESERVED.has(w)) s.fail(`"${t.text}" is a Thunder word and can't start a value here.`, null, 'TC105');
477
564
 
478
565
  const run = this.wordRun(s);
566
+ // an alternative of a data type: "a successful Payment with amount $5", "a pending Payment"
567
+ if (o.article && this.names.alts?.size) {
568
+ for (let i = 1; i < run.length; i++) {
569
+ const alt = keyOf(run.slice(0, i));
570
+ const recs = this.names.alts.get(alt);
571
+ if (!recs) continue;
572
+ const rk = this.longest(run.slice(i), (key) => recs.includes(key));
573
+ if (!rk || i + rk !== run.length) continue;
574
+ s.i -= run.length - i - rk;
575
+ const node = { k: 'new', record: keyOf(run.slice(i, i + rk)), alt, altText: run.slice(0, i).map((x) => x.text).join(' '), altCol: run[0].col, recordCol: run[i].col, fields: this.recordFields(s, line), line };
576
+ return node;
577
+ }
578
+ // "a refunded Payment": words before a data type that has alternatives, but not one of them (the checker says so).
579
+ for (let i = 1; i < run.length; i++) {
580
+ const rk = this.longest(run.slice(i), (key) => this.names.altsOf.has(key));
581
+ if (!rk || i + rk !== run.length) continue;
582
+ s.i -= run.length - i - rk;
583
+ return { k: 'new', record: keyOf(run.slice(i, i + rk)), alt: keyOf(run.slice(0, i)), altText: run.slice(0, i).map((x) => x.text).join(' '), altCol: run[0].col, recordCol: run[i].col, fields: this.recordFields(s, line), line };
584
+ }
585
+ }
479
586
  // a record: "a Customer with name "Ann" and balance $10", "a new Customer"
480
587
  let off = run[0]?.lower === 'new' && run.length > 1 ? 1 : 0;
481
588
  const recK = this.longest(run.slice(off), (key) => this.names.records.has(key));
@@ -483,17 +590,8 @@ export class ExprParser {
483
590
  if (recK && wantsRecord && (recK + off === run.length)) {
484
591
  s.i -= run.length - off - recK;
485
592
  const name = keyOf(run.slice(off, off + recK));
486
- const fields = [];
487
- if (s.word('with')) {
488
- do {
489
- const fr = this.wordRun(s);
490
- if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, 'TC108');
491
- const fk = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
492
- s.i -= fr.length - fk;
493
- fields.push({ name: keyOf(fr.slice(0, fk)), text: fr.slice(0, fk).map((x) => x.text).join(' '), e: this.expr(s, { noAnd: true }), line });
494
- } while ((isSym(s.peek(), ',') || isWord(s.peek(), 'and')) && this.fieldAhead(s, 1) && s.next());
495
- }
496
- const node = { k: 'new', record: name, fields, line };
593
+ const fields = this.recordFields(s, line);
594
+ const node = { k: 'new', record: name, recordCol: run[off].col, fields, line };
497
595
  if (!fields.length && this.open) this.open.push(node); // a block of "field: value" lines may fill it
498
596
  return node;
499
597
  }
@@ -509,18 +607,19 @@ export class ExprParser {
509
607
  const key = keyOf(run.slice(0, k));
510
608
  const text = run.slice(0, k).map((x) => x.text).join(' ');
511
609
  if (this.names.known.get(key) === 'func') {
512
- if (isSym(s.peek(), '(')) return { k: 'call', name: key, text, args: this.parenArgs(s), line };
513
- if (s.word('with')) return { k: 'call', name: key, text, args: this.withArgs(s), line };
514
- const node = { k: 'call', name: key, text, args: [], line, bare: true };
610
+ const col = run[0].col;
611
+ if (isSym(s.peek(), '(')) return { k: 'call', name: key, text, col, args: this.parenArgs(s), line };
612
+ if (s.word('with')) return { k: 'call', name: key, text, col, args: this.withArgs(s), line };
613
+ const node = { k: 'call', name: key, text, col, args: [], line, bare: true };
515
614
  if (this.open) this.open.push(node); // a block of "input: value" lines may fill it
516
615
  return node;
517
616
  }
518
- return { k: 'name', name: key, text, line };
617
+ return { k: 'name', name: key, text, col: run[0].col, line };
519
618
  }
520
619
  const fk = this.longest(run, (key) => this.names.fields.has(key));
521
- if (fk) { s.i -= run.length - fk; return { k: 'name', name: keyOf(run.slice(0, fk)), text: run.slice(0, fk).map((x) => x.text).join(' '), line, unknown: true }; }
620
+ if (fk) { s.i -= run.length - fk; return { k: 'name', name: keyOf(run.slice(0, fk)), text: run.slice(0, fk).map((x) => x.text).join(' '), col: run[0].col, line, unknown: true }; }
522
621
  // An unknown name: kept whole, so the checker can say exactly what it did not know.
523
- return { k: 'name', name: keyOf(run), text: run.map((x) => x.text).join(' '), line, unknown: true };
622
+ return { k: 'name', name: keyOf(run), text: run.map((x) => x.text).join(' '), col: run[0]?.col, line, unknown: true };
524
623
  }
525
624
  }
526
625
 
@@ -529,7 +628,7 @@ export class ExprParser {
529
628
  export function parseCore(source, { seed = null } = {}) {
530
629
  const { lines, diagnostics } = lex(source);
531
630
  const tree = buildBlocks(lines, diagnostics);
532
- const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []), recordFields: new Map(seed?.recordFields ?? []), funcInputs: new Map(seed?.funcInputs ?? []), recordText: new Map(), screens: new Map() };
631
+ const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []), recordFields: new Map(seed?.recordFields ?? []), funcInputs: new Map(seed?.funcInputs ?? []), recordText: new Map(), screens: new Map(), alts: new Map(seed?.alts ?? []), altsOf: new Map(seed?.altsOf ?? []) };
533
632
  collectNames(tree, names);
534
633
  const ep = new ExprParser(names);
535
634
  const body = parseBlock(tree, ep, names, diagnostics, { top: true });
@@ -562,14 +661,14 @@ function parseBlock(nodes, ep, names, diagnostics, ctx) {
562
661
  }
563
662
 
564
663
  // Statements whose ":" opens a block of statements (never a block of "name: value" lines).
565
- const BLOCK_STATEMENTS = new Set(['when', 'if', 'otherwise', 'for', 'repeat', 'to', 'test', 'receive', 'never', 'use', 'screen']);
664
+ const BLOCK_STATEMENTS = new Set(['when', 'if', 'otherwise', 'for', 'repeat', 'to', 'test', 'receive', 'never', 'use', 'screen', 'depending']);
566
665
 
567
666
  /** The "name: value" lines under a statement that is not itself a block statement, or null. */
568
667
  function fieldBlock(n, diagnostics = []) {
569
668
  const ts = n.tokens;
570
669
  if (!n.children.length || !isSym(ts[ts.length - 1], ':')) return null;
571
670
  const w0 = ts[0]?.t === 'word' ? ts[0].lower : '';
572
- if (BLOCK_STATEMENTS.has(w0) || ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has'))) return null;
671
+ if (BLOCK_STATEMENTS.has(w0) || ((w0 === 'a' || w0 === 'an') && (isWord(ts[ts.length - 2], 'has') || isOneOf(ts)))) return null;
573
672
  return n.children.map((c) => {
574
673
  const colon = c.tokens.findIndex((t) => isSym(t, ':'));
575
674
  const nameTs = colon > 0 ? c.tokens.slice(0, colon) : [];
@@ -649,7 +748,7 @@ function nameWords(ts, line, what) {
649
748
  if (t.t !== 'word') throw new CoreError(diag('TC105', line, `A name can only use words, but "${show(t)}" is not a word.`));
650
749
  if (RESERVED.has(t.lower)) throw new CoreError(diag('TC202', line, `A name can't contain the word "${t.text}", because it belongs to Thunder.`, `Try a name without "${t.text}".`));
651
750
  }
652
- return { name: keyOf(words), text: words.map((x) => x.text).join(' ') };
751
+ return { name: keyOf(words), text: words.map((x) => x.text).join(' '), col: words[0].col };
653
752
  }
654
753
 
655
754
  function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
@@ -662,6 +761,25 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
662
761
  const w0 = ts[0].t === 'word' ? ts[0].lower : '';
663
762
  const rest = ts.slice(1);
664
763
 
764
+ // When someone calls GET /habits/{name}: an endpoint. Underneath it is a function whose inputs are its Receive
765
+ // lines; the server (and "calling GET /habits/walk" in a test) passes the path parts and the body to them.
766
+ if (w0 === 'when' && isWord(ts[1], 'someone') && isWord(ts[2], 'calls') && ts[4]?.t === 'path') {
767
+ if (!ctx.top) fail('TC402', 'An endpoint ("When someone calls …") must be written at the left edge, not inside another block.');
768
+ const method = ts[3].text.toUpperCase();
769
+ const path = ts[4].text;
770
+ const segments = path.split('/').filter(Boolean).map((seg) => { const m = seg.match(/^\{([^{}]+)\}$/); return m ? { param: m[1].trim().toLowerCase(), text: m[1].trim() } : { lit: seg }; });
771
+ const kids = n.children;
772
+ const params = [];
773
+ let r = 0;
774
+ while (kids[r] && isWord(kids[r].tokens[0], 'receive')) {
775
+ const kid = kids[r];
776
+ params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords(p.raw, kid.line, '"Receive"'), type: p.typeTokens ? typeOf(ep, p.typeTokens, kid.line) : null, dflt: p.defaultTokens ? ep.parse(p.defaultTokens, kid.line) : null, line: kid.line })));
777
+ r++;
778
+ }
779
+ const words = ['answer', method.toLowerCase(), ...segments.map((g) => (g.param ? g.param : g.lit.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim())).filter(Boolean)];
780
+ const name = words.join(' ');
781
+ return { k: 'func', name, text: `${method} ${path}`, params, body: parseBlock(kids.slice(r), ep, names, diagnostics, { inFunc: true, inEndpoint: true }), line, endpoint: { method, path, segments, line } };
782
+ }
665
783
  if (w0 === 'say' || w0 === 'print') return { k: 'say', e: E(rest), line };
666
784
  if (w0 === 'set') {
667
785
  const at = splitTop(rest, (t) => isWord(t, 'to'));
@@ -672,20 +790,41 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
672
790
  if (!['name', 'field', 'at'].includes(target.k)) fail('TC305', 'Only a name, a field (customer\'s balance), or an entry (counts at word) can be set.');
673
791
  return { k: 'set', target, e: E(rest.slice(at + 1)), line };
674
792
  }
793
+ // Store <name> as a list of <Record>: a list that is saved between runs (data/<name>.json).
794
+ if (w0 === 'store' && rest.some((t) => isWord(t, 'as'))) {
795
+ if (!ctx.top) fail('TC402', 'A "Store" line must be written at the left edge of the file.');
796
+ const as = splitTop(rest, (t) => isWord(t, 'as'));
797
+ const typeTokens = stripArticle(rest.slice(as + 1));
798
+ if (!typeTokens.length) fail('TC108', 'Write what the store holds: Store habits as a list of Habit.');
799
+ return { k: 'store', ...nameWords(rest.slice(0, as), line, '"Store"'), type: typeOf(ep, typeTokens, line), line };
800
+ }
675
801
  if (w0 === 'keep') {
676
802
  const at = splitTop(rest, (t) => isWord(t, 'at'));
677
803
  if (at < 0) fail('TC108', '"Keep" needs "at": Keep tax rate at 7%.');
678
804
  return { k: 'keep', ...nameWords(rest.slice(0, at), line, '"Keep"'), e: E(rest.slice(at + 1)), line };
679
805
  }
806
+ // "… with status 201" (Give) and "… and status 404" (Stop): the HTTP status an endpoint answers with.
807
+ // A Stop's status may be set in any function (a helper like "find order" says 404; it matters only when an
808
+ // endpoint answers with it). Give's status only in the endpoint itself, where the answer is made.
809
+ const statusAt = (r, joiner) => {
810
+ const n = r.length;
811
+ if (n >= 3 && isWord(r[n - 3], joiner) && isWord(r[n - 2], 'status') && r[n - 1].t === 'num') {
812
+ if (joiner === 'with' && !ctx.inEndpoint) fail('TC218', `"with status" sets the HTTP status of an endpoint's answer, so it goes inside "When someone calls …".`, 'Outside an endpoint, Give the value; the endpoint that gives it sets the status.');
813
+ return { status: Number(r[n - 1].text), r: r.slice(0, -3) };
814
+ }
815
+ return { status: null, r };
816
+ };
680
817
  if (w0 === 'give') {
681
818
  let r = rest;
682
819
  if (isWord(r[0], 'back')) r = r.slice(1);
683
- return { k: 'give', e: r.length ? E(r) : { k: 'nothing', line }, line };
820
+ const st = statusAt(r, 'with');
821
+ return { k: 'give', e: st.r.length ? E(st.r) : { k: 'nothing', line }, status: st.status, line };
684
822
  }
685
823
  if (w0 === 'stop') {
686
824
  let r = rest;
687
825
  if (isWord(r[0], 'with') || isSym(r[0], ':')) r = r.slice(1);
688
- return { k: 'stop', e: r.length ? E(r) : { k: 'str', parts: ['Stopped'], line }, line };
826
+ const st = statusAt(r, 'and');
827
+ return { k: 'stop', e: st.r.length ? E(st.r) : { k: 'str', parts: ['Stopped'], line }, status: st.status, line };
689
828
  }
690
829
  if (w0 === 'if' && keyOf(ts.slice(0, 3)) === 'if this fails') {
691
830
  header();
@@ -694,6 +833,23 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
694
833
  siblings.pop();
695
834
  return { k: 'tryFail', stmt: prev, handler: children(), line };
696
835
  }
836
+ // Depending on payment: / Successful: … / Declined: … / Otherwise: …
837
+ if (w0 === 'depending' && isWord(ts[1], 'on')) {
838
+ const subject = E(header().slice(2));
839
+ const cases = [];
840
+ let otherwise = null;
841
+ for (const c of n.children) {
842
+ try {
843
+ const ct = c.tokens;
844
+ if (!isSym(ct[ct.length - 1], ':') || ct.length < 2) throw new CoreError(diag('TC108', c.line, 'Under "Depending on", each case is an alternative and a colon, for example: Successful:'));
845
+ const sub = parseBlock(c.children, ep, names, diagnostics, ctx);
846
+ if (ct.length === 2 && isWord(ct[0], 'otherwise')) { otherwise = sub; continue; }
847
+ const { name, text, col } = nameWords(ct.slice(0, -1), c.line, 'A case');
848
+ cases.push({ alt: name, text, col, body: sub, line: c.line });
849
+ } catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
850
+ }
851
+ return { k: 'depending', subject, cases, otherwise, line };
852
+ }
697
853
  if (w0 === 'when' || w0 === 'if') {
698
854
  const cond = E(header().slice(1));
699
855
  return { k: 'if', branches: [{ cond, body: children(), line }], otherwise: null, line };
@@ -733,7 +889,7 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
733
889
  }
734
890
  if (w0 === 'to' && isSym(ts[ts.length - 1], ':')) {
735
891
  if (!ctx.top) fail('TC402', 'A "To" block (a function) must be written at the left edge, not inside another block.');
736
- const { name, text } = nameWords(header().slice(1), line, '"To"');
892
+ const { name, text, col } = nameWords(header().slice(1), line, '"To"');
737
893
  const kids = n.children;
738
894
  let params = [];
739
895
  let bodyNodes = kids;
@@ -745,7 +901,7 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
745
901
  r++;
746
902
  }
747
903
  bodyNodes = kids.slice(r);
748
- return { k: 'func', name, text, params, body: parseBlock(bodyNodes, ep, names, diagnostics, { inFunc: true }), line };
904
+ return { k: 'func', name, text, col, params, body: parseBlock(bodyNodes, ep, names, diagnostics, { inFunc: true }), line };
749
905
  }
750
906
  if (w0 === 'receive') fail('TC111', '"Receive" must be the first line inside a "To" block or a "Screen".');
751
907
  if (w0 === 'screen' && isSym(ts[ts.length - 1], ':')) {
@@ -758,9 +914,39 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
758
914
  }
759
915
  if (w0 === 'remember') fail('TC119', '"Remember" goes at the top of a "Screen", after its "Receive" lines.', 'A function keeps nothing between calls; a screen remembers values while it is shown.');
760
916
  if (w0 === 'show') fail('TC118', '"Show" is used inside a "Screen" (a screen shows things). In a program, write: Say …');
917
+ // A Payment is one of:
918
+ // Successful with amount as money
919
+ // Declined with reason as text
920
+ // Pending
921
+ // A record underneath: "which" (the alternative's name) and every alternative's fields, each optional. The checker
922
+ // makes sure a field is only read where the alternative is known, and that "Depending on" covers every one.
923
+ if ((w0 === 'a' || w0 === 'an') && isOneOf(ts)) {
924
+ if (!ctx.top) fail('TC402', 'A data type ("A … is one of:") must be written at the left edge, not inside another block.');
925
+ const { name, text, col } = nameWords(ts.slice(1, -4), line, 'A data type');
926
+ const alts = [];
927
+ for (const c of n.children) {
928
+ try {
929
+ const at = c.tokens.findIndex((t) => isWord(t, 'with'));
930
+ const alt = nameWords(at < 0 ? c.tokens : c.tokens.slice(0, at), c.line, 'An alternative');
931
+ const fields = [];
932
+ if (at >= 0) {
933
+ for (const g of paramGroups(c.tokens.slice(at + 1))) {
934
+ if (!g.typeTokens) throw new CoreError(diag('TC108', c.line, `Write each field with its kind: ${alt.text} with ${g.words.map((x) => x.text).join(' ') || 'amount'} as money.`));
935
+ fields.push({ ...nameWords(g.raw, c.line, 'A field'), type: typeOf(ep, g.typeTokens, c.line), line: c.line });
936
+ }
937
+ }
938
+ alts.push({ ...alt, fields, line: c.line });
939
+ } catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
940
+ }
941
+ if (!alts.length) fail('TC108', `Write the alternatives under it, one per line, for example: Successful with amount as money.`);
942
+ const opt = (t) => (t.k === 'optional' ? t : { k: 'optional', of: t });
943
+ const fields = [{ name: 'which', text: 'which', type: { k: 'text' }, line, hidden: true }];
944
+ for (const a of alts) for (const f of a.fields) if (!fields.some((x) => x.name === f.name)) fields.push({ ...f, type: opt(f.type) });
945
+ return { k: 'record', name, text, col, fields, rules: [], alts, line };
946
+ }
761
947
  if ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has') && isSym(ts[ts.length - 1], ':')) {
762
948
  if (!ctx.top) fail('TC402', 'A record ("A … has:") must be written at the left edge, not inside another block.');
763
- const { name, text } = nameWords(ts.slice(1, -2), line, 'A record');
949
+ const { name, text, col } = nameWords(ts.slice(1, -2), line, 'A record');
764
950
  const fields = [], rules = [];
765
951
  for (const c of n.children) {
766
952
  try {
@@ -770,7 +956,7 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
770
956
  fields.push({ ...nameWords(c.tokens.slice(0, k), c.line, 'A field'), type: typeOf(ep, c.tokens.slice(k + 1), c.line), line: c.line });
771
957
  } catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
772
958
  }
773
- return { k: 'record', name, text, fields, rules, line };
959
+ return { k: 'record', name, text, col, fields, rules, line };
774
960
  }
775
961
  if (w0 === 'expect') return { ...parseExpect(rest, line, ep), raw: n.raw };
776
962
  if (w0 === 'never') return parseNever(ts, line, ep);
@@ -0,0 +1,18 @@
1
+ // Where a Thunder Core project starts: the nearest thunder.toml. Its own small file so the thunder command can
2
+ // find a project (for example to word a "no such file" message) without loading the whole of Thunder Core.
3
+ import { existsSync, statSync } from 'node:fs';
4
+ import { join, dirname, resolve } from 'node:path';
5
+
6
+ export const PROJECT_FILE = 'thunder.toml';
7
+
8
+ /** The nearest folder at or above `start` that holds a thunder.toml, or null. */
9
+ export function findProjectRoot(start) {
10
+ let dir = resolve(start);
11
+ if (existsSync(dir) && !statSync(dir).isDirectory()) dir = dirname(dir);
12
+ for (;;) {
13
+ if (existsSync(join(dir, PROJECT_FILE))) return dir;
14
+ const up = dirname(dir);
15
+ if (up === dir) return null;
16
+ dir = up;
17
+ }
18
+ }
@@ -3,6 +3,8 @@
3
3
  // Source ownership: in a Thunder project the .thunder files are the source. generated/ is a build artifact,
4
4
  // rewritten by every build; it is never read back.
5
5
 
6
+ import { LANGUAGE_VERSION } from './kind.mjs';
7
+ import { spawnServing } from './serving.mjs';
6
8
  import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync, rmSync } from 'node:fs';
7
9
  import { join, dirname, relative, resolve, basename } from 'node:path';
8
10
  import { spawnSync } from 'node:child_process';
@@ -23,7 +25,9 @@ export const TARGETS = ['python', 'typescript', 'csharp', 'rust', 'go', 'java',
23
25
  /** How a target is named to people. */
24
26
  export const TARGET_NAMES = { python: 'Python', typescript: 'TypeScript', csharp: 'C#', rust: 'Rust', go: 'Go', java: 'Java', react: 'React' };
25
27
 
26
- export const PROJECT_FILE = 'thunder.toml';
28
+ import { PROJECT_FILE, findProjectRoot } from './project-root.mjs';
29
+
30
+ export { PROJECT_FILE, findProjectRoot };
27
31
 
28
32
  /** A tiny TOML subset: [sections], key = "text" | number | true | false, and # comments. */
29
33
  export function parseToml(text) {
@@ -42,20 +46,26 @@ export function parseToml(text) {
42
46
  return out;
43
47
  }
44
48
 
45
- /** The nearest folder at or above `start` that holds a thunder.toml, or null. */
46
- export function findProjectRoot(start) {
47
- let dir = resolve(start);
48
- if (existsSync(dir) && !statSync(dir).isDirectory()) dir = dirname(dir);
49
- for (;;) {
50
- if (existsSync(join(dir, PROJECT_FILE))) return dir;
51
- const up = dirname(dir);
52
- if (up === dir) return null;
53
- dir = up;
54
- }
49
+ export { LANGUAGE_VERSION };
50
+
51
+ /**
52
+ * The language a project is written in, from thunder.toml ([project] language = "2"). A project without it is read as
53
+ * the current language. A newer major version is refused with what to do, never read as something else.
54
+ */
55
+ export function projectLanguage(value, where = 'thunder.toml') {
56
+ if (value == null || value === '') return LANGUAGE_VERSION;
57
+ const text = String(value).trim();
58
+ const m = /^(\d+)(?:\.(\d+))?$/.exec(text);
59
+ if (!m) throw new Error(`${where}: language = "${text}" is not a language version. Write language = "${LANGUAGE_VERSION}".`);
60
+ const major = Number(m[1]);
61
+ if (major > Number(LANGUAGE_VERSION)) throw new Error(`${where}: this project is written in Thunder language ${text}, and this compiler speaks language ${LANGUAGE_VERSION}. Install a newer ThunderLang: npm install -g @skillstech/thunderlang`);
62
+ if (major < Number(LANGUAGE_VERSION)) throw new Error(`${where}: language = "${text}" is older than any version Thunder keeps. Programs written before 2.0 are read as language ${LANGUAGE_VERSION}: write language = "${LANGUAGE_VERSION}".`);
63
+ return text;
55
64
  }
56
65
 
57
66
  export function loadProject(root) {
58
67
  const toml = parseToml(readFileSync(join(root, PROJECT_FILE), 'utf8'));
68
+ const language = projectLanguage(toml.project?.language);
59
69
  const build = toml.build ?? {};
60
70
  const target = String(build.target ?? 'python');
61
71
  if (!TARGETS.includes(target)) throw new Error(`thunder.toml: target "${target}" is not supported yet. Thunder Core builds ${TARGETS.map((t) => `${TARGET_NAMES[t] ?? t} (target = "${t}")`).join(', ')}.`);
@@ -63,6 +73,7 @@ export function loadProject(root) {
63
73
  root,
64
74
  name: toml.project?.name ?? basename(root),
65
75
  version: toml.project?.version ?? '0.1.0',
76
+ language,
66
77
  target,
67
78
  src: build.source ?? 'src',
68
79
  tests: build.tests ?? 'tests',
@@ -93,8 +104,10 @@ export function buildProject({ root, single = null, includeTests = false, write
93
104
  const tgt = target ?? cfg?.target ?? 'python';
94
105
  if (!TARGETS.includes(tgt)) throw new Error(`there is no target "${tgt}". Thunder Core builds ${TARGETS.join(', ')} (python is the default).`);
95
106
  const srcFiles = cfg ? thunderFiles(join(cfg.root, cfg.src)) : [];
96
- if (single && !srcFiles.includes(resolve(single))) srcFiles.unshift(resolve(single));
97
- const testFiles = includeTests && cfg ? thunderFiles(join(cfg.root, cfg.tests)) : [];
107
+ // A single file in the project's tests/ is a test: it is checked against src/, as in a whole-project run.
108
+ const singleTest = single && cfg && thunderFiles(join(cfg.root, cfg.tests)).includes(resolve(single)) ? resolve(single) : null;
109
+ if (single && !singleTest && !srcFiles.includes(resolve(single))) srcFiles.unshift(resolve(single));
110
+ const testFiles = singleTest ? [singleTest] : includeTests && cfg ? thunderFiles(join(cfg.root, cfg.tests)) : [];
98
111
  const outDir = join(base, cfg && (target == null || target === cfg.target) ? cfg.out : `generated/${tgt}`);
99
112
  const results = [];
100
113
  const used = new Set();
@@ -105,7 +118,9 @@ export function buildProject({ root, single = null, includeTests = false, write
105
118
  results.push({ ...r, path: f, rel, module: uniqueModule(f), kind: 'src' });
106
119
  }
107
120
  const srcOk = results.filter((r) => r.ok);
108
- for (const f of testFiles) {
121
+ // Tests are built against src/. While src/ has problems they would only repeat them as names they can't find,
122
+ // so the problems in src/ are reported alone; the tests are checked once src/ is fixed.
123
+ for (const f of srcOk.length === results.length ? testFiles : []) {
109
124
  const rel = relative(base, f).split('\\').join('/');
110
125
  const r = compileCore(readFileSync(f, 'utf8'), { file: rel, imported: srcOk, srcModules: srcOk.map((x) => x.module) });
111
126
  results.push({ ...r, path: f, rel, module: uniqueModule(f, 'tests_'), kind: 'test' });
@@ -163,8 +178,10 @@ export function findPython() {
163
178
  return { error: 'Thunder needs Python 3.10 or newer to run this program, and I could not find it (tried THUNDER_PYTHON, python3, python). Install it from https://www.python.org/downloads/ or set THUNDER_PYTHON to its path. "thunder build" still works without Python.' };
164
179
  }
165
180
 
166
- export function runPython(python, outDir, script, cwd) {
167
- return spawnSync(python.cmd, [join(outDir, script)], { cwd, stdio: 'inherit', env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONIOENCODING: 'utf-8', PYTHONUNBUFFERED: '1' } });
181
+ export function runPython(python, outDir, script, cwd, { serving = false } = {}) {
182
+ const opts = { cwd, stdio: 'inherit', env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', PYTHONIOENCODING: 'utf-8', PYTHONUNBUFFERED: '1' } };
183
+ // A program with endpoints keeps answering until stopped: started without waiting, with stop signals passed on.
184
+ return (serving ? spawnServing : spawnSync)(python.cmd, [join(outDir, script)], opts);
168
185
  }
169
186
 
170
187
  export function newProject(dir, { force = false } = {}) {
@@ -177,6 +194,7 @@ export function newProject(dir, { force = false } = {}) {
177
194
  [project]
178
195
  name = "${name}"
179
196
  version = "0.1.0"
197
+ language = "${LANGUAGE_VERSION}" # the Thunder language version (docs/spec-2.md)
180
198
 
181
199
  [build]
182
200
  target = "python"
@@ -5,13 +5,13 @@
5
5
  import { writeFileSync, mkdirSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
7
  import { toReact, hasScreens } from './target-react.mjs';
8
- import { pythonOnlyUses, npmRefusals, dotnetRefusals } from './target-typescript.mjs';
8
+ import { pythonOnlyUses, npmRefusals, dotnetRefusals, storeRefusals, httpRefusals } from './target-typescript.mjs';
9
9
  import { REACT_RUNTIME, REACT_RUNTIME_DTS } from './runtime-react.mjs';
10
10
  import { diag } from './diagnostics.mjs';
11
11
 
12
12
  /** What stops a file from becoming a React app: a Python module (TC405), or steps outside a screen (TC406). */
13
13
  export function reactDiagnostics(result, { entry = false } = {}) {
14
- const out = [...npmRefusals(result.info, 'a React app', diag), ...dotnetRefusals(result.info, 'a React app', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
14
+ const out = [...npmRefusals(result.info, 'a React app', diag), ...dotnetRefusals(result.info, 'a React app', diag), ...storeRefusals(result.info, 'a React app', diag), ...httpRefusals(result.info, 'a React app', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
15
15
  `"${u.module}" is a Python module, and this program is built as a React app, which cannot use it.`,
16
16
  'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
17
17
  const main = result.program.main ?? [];