@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
@@ -10,6 +10,7 @@
10
10
  #pragma warning disable CS0162, CS0168, CS0219, CS8321
11
11
  using System;
12
12
  using System.Collections.Generic;
13
+ using System.Globalization;
13
14
  using System.IO;
14
15
  using System.Linq;
15
16
  using System.Numerics;
@@ -425,7 +426,26 @@ namespace Thunder
425
426
  for (int i = 0; i < ip.Length; i++) { if (i > 0 && (ip.Length - i) % 3 == 0) sb.Append(','); sb.Append(ip[i]); }
426
427
  return sb.ToString();
427
428
  }
428
- static string jsLower(string s) => s.ToLowerInvariant();
429
+ // Lowercase as Python and JavaScript do, including Unicode's Final_Sigma rule (.NET's ToLowerInvariant has no
430
+ // context, so a word-final Σ would become σ instead of ς).
431
+ static string jsLower(string s)
432
+ {
433
+ // ToLowerInvariant maps one UTF-16 unit to one, so positions line up for the Σ pass. It leaves İ as it is;
434
+ // Python and JavaScript give i followed by a combining dot, so that is done last.
435
+ var sb = new StringBuilder(s.ToLowerInvariant());
436
+ if (s.IndexOf('Σ') >= 0) for (int i = 0; i < s.Length; i++) if (s[i] == 'Σ' && finalSigma(s, i)) sb[i] = 'ς';
437
+ return sb.ToString().Replace("İ", "i\u0307");
438
+ }
439
+ static bool finalSigma(string s, int i)
440
+ {
441
+ static bool cased(char c) => char.IsUpper(c) || char.IsLower(c) || CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.TitlecaseLetter;
442
+ static bool ignorable(char c) { var k = CharUnicodeInfo.GetUnicodeCategory(c); return k == UnicodeCategory.NonSpacingMark || k == UnicodeCategory.EnclosingMark || k == UnicodeCategory.Format || k == UnicodeCategory.ModifierLetter || k == UnicodeCategory.ModifierSymbol || c == '\'' || c == '.' || c == ':' || c == '’' || c == '·'; }
443
+ bool before = false;
444
+ for (int j = i - 1; j >= 0; j--) { if (ignorable(s[j])) continue; before = cased(s[j]); break; }
445
+ if (!before) return false;
446
+ for (int j = i + 1; j < s.Length; j++) { if (ignorable(s[j])) continue; return !cased(s[j]); }
447
+ return true;
448
+ }
429
449
  static string jsUpper(string s) => s.ToUpperInvariant().Replace("ß", "SS");
430
450
 
431
451
  // ── Kinds ───────────────────────────────────────────────────────────────────────────────────────────────
@@ -1054,6 +1074,7 @@ namespace Thunder
1054
1074
  }
1055
1075
 
1056
1076
  public static object addTo(object target, object value) { if (target is List<object> l) { l.Add(value); return l; } return add(target, value); }
1077
+ public static List<object> copyList(object target) { if (!(target is List<object> l)) throw attrErr(target, "append"); return new List<object>(l); }
1057
1078
  public static void appendTo(object target, object value) { if (!(target is List<object> l)) throw attrErr(target, "append"); l.Add(value); }
1058
1079
  public static void removeFrom(object target, object value)
1059
1080
  {
@@ -74,8 +74,9 @@ class Checker {
74
74
  this.rules = []; // top-level and record Never rules
75
75
  this.mainNames = new Map(); // key -> first line it is set in the main program
76
76
  this.elem = []; // stack of { type } for where / from / sorted
77
- this.info = { records: [], funcs: [], consts: [], modules: [], tests: [], rules: [], screens: [], usesDecimal: false };
77
+ this.info = { records: [], funcs: [], consts: [], stores: [], endpoints: [], usesHttp: false, modules: [], tests: [], rules: [], screens: [], usesDecimal: false };
78
78
  this.screens = new Map(); // key -> screen stmt
79
+ this.narrow = []; // { name, alt } while checking a case of "Depending on" or "If x is <alternative>"
79
80
  }
80
81
  err(code, line, msg, hint) { this.d.push(diag(code, line, msg, hint)); }
81
82
 
@@ -101,6 +102,8 @@ class Checker {
101
102
  }
102
103
  }
103
104
  for (const s of top) if (s.k === 'record') this.checkRecordShape(s);
105
+ // Endpoints this file can call in a test: its own, and those of the files it sees (a project's tests see src/).
106
+ this.info.endpointsAll = [...top.filter((s) => s.k === 'func' && s.endpoint), ...(this.imported ?? []).flatMap((inf) => inf.endpoints ?? [])];
104
107
  collectMainNames(top, this.mainNames);
105
108
  // 2. Kept values, in order (they may use each other and functions).
106
109
  for (const s of top) {
@@ -109,6 +112,20 @@ class Checker {
109
112
  this.declare(s, 'const', s.line, { py: pyName(s.name, 'upper'), type: t });
110
113
  this.info.consts.push(s);
111
114
  }
115
+ // 2b. Stored lists (Store habits as a list of Habit): names every function can see, whose items change and are
116
+ // saved between runs. A record's fields must be plain values so the file says exactly what they are.
117
+ for (const s of top) {
118
+ if (s.k !== 'store') continue;
119
+ const t = s.type;
120
+ const rec = t?.k === 'list' && t.of?.k === 'record' ? this.records.get(t.of.name) : null;
121
+ if (!rec) { this.err('TC306', s.line, `A store holds a list of records, for example: Store habits as a list of Habit.`, 'Describe the record with "A Habit has:", then store a list of it.'); continue; }
122
+ const plain = (ft) => ft && (['whole', 'number', 'money', 'text', 'bool', 'date'].includes(ft.k) || (ft.k === 'optional' && plain(ft.of)));
123
+ const bad = rec.fields.find((f) => !plain(f.type));
124
+ if (bad) { this.err('TC306', s.line, `"${rec.text ?? rec.name}" can't be stored yet: its field "${bad.text ?? bad.name}" is not a plain value.`, 'A stored record\'s fields are whole numbers, numbers, money, text, yes/no, dates, or one of those or nothing.'); continue; }
125
+ s.record = rec;
126
+ this.declare(s, 'store', s.line, { py: pyName(s.name, 'upper'), type: { k: 'list', of: { k: 'record', name: rec.name, text: rec.text } } });
127
+ this.info.stores.push(s);
128
+ }
112
129
  // 3. Never rules written at the top level or inside records.
113
130
  for (const s of top) if (s.k === 'never') this.addRule(s, null);
114
131
  for (const r of this.records.values()) for (const rule of r.rules) this.addRule(rule, r);
@@ -122,7 +139,7 @@ class Checker {
122
139
  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).`);
123
140
  const main = new Scope(this.global, 'main');
124
141
  this.mainScope = main;
125
- const mainBody = top.filter((s) => !['record', 'func', 'use', 'keep', 'never', 'test', 'screen'].includes(s.k));
142
+ const mainBody = top.filter((s) => !['record', 'func', 'use', 'keep', 'store', 'never', 'test', 'screen'].includes(s.k));
126
143
  this.block(mainBody, main, {});
127
144
  this.p.main = mainBody;
128
145
  this.info.records = [...this.records.values()];
@@ -158,6 +175,78 @@ class Checker {
158
175
  this.resolveType(f.type, f.line);
159
176
  r.fieldMap.set(f.name, f);
160
177
  }
178
+ if (r.alts) this.checkAlternatives(r);
179
+ }
180
+ /** A data type with alternatives: each alternative's fields, one kind per field name, and no field called "which". */
181
+ /**
182
+ * Depending on payment: one case per alternative (or Otherwise). A missing alternative is reported at this line.
183
+ * Then it runs as If payment is successful … Otherwise if payment is declined …, with the value read once per test.
184
+ */
185
+ depending(s, sc, ctx) {
186
+ const line = s.line;
187
+ const t = this.ex(s.subject, sc);
188
+ const r = t.k === 'record' ? this.records.get(t.name) : null;
189
+ const name = s.subject.k === 'name' ? s.subject.name : null;
190
+ const bodies = () => { for (const c of s.cases) this.block(c.body, sc, ctx); if (s.otherwise) this.block(s.otherwise, sc, ctx); };
191
+ if (!r?.altMap) {
192
+ if (known(t)) this.err('TC305', line, `"Depending on" chooses by the alternative a value is, but this is ${typeWords(t)}, not a data type with alternatives.`, 'For other values, use When … / Otherwise when ….');
193
+ bodies(); s.k = 'if'; s.branches = []; return;
194
+ }
195
+ if (!['name', 'field'].includes(s.subject.k)) this.err('TC305', line, `"Depending on" reads its value once for each case, so give it a name first.`, `Set result to …, then write: Depending on result:`);
196
+ const seen = new Set();
197
+ for (const c of s.cases) {
198
+ if (!r.altMap.has(c.alt)) { this.err('TC217', c.line, `A ${r.text} is ${this.altList(r)}; "${c.text}" isn't one of them.`); this.block(c.body, sc, ctx); continue; }
199
+ if (seen.has(c.alt)) this.err('TC203', c.line, `"${c.text}" already has a case above.`);
200
+ seen.add(c.alt);
201
+ if (name) this.narrow.push({ name, alt: c.alt });
202
+ try { this.block(c.body, sc, ctx); } finally { if (name) this.narrow.pop(); }
203
+ }
204
+ if (s.otherwise) this.block(s.otherwise, sc, ctx);
205
+ const missing = [...r.altMap.values()].filter((a) => !seen.has(a.name));
206
+ if (missing.length && !s.otherwise) {
207
+ const ws = missing.map((a) => a.text.toLowerCase());
208
+ this.err('TC215', line, `"Depending on ${s.subject.text ?? 'this'}" doesn't say what to do when it is ${ws.length <= 2 ? ws.join(' or ') : `${ws.slice(0, -1).join(', ')}, or ${ws[ws.length - 1]}`}.`,
209
+ `Add ${missing.map((a) => `"${a.text}:"`).join(' and ')} with what to do, or "Otherwise:" for every case not listed.`);
210
+ }
211
+ const cases = s.cases.filter((c) => r.altMap.has(c.alt));
212
+ Object.assign(s, { k: 'if', branches: cases.map((c) => ({ cond: this.altTest(s.subject, r, c.alt, false, c.line), body: c.body, line: c.line })), otherwise: s.otherwise });
213
+ }
214
+
215
+ checkAlternatives(r) {
216
+ r.altMap = new Map();
217
+ for (const a of r.alts) {
218
+ if (r.altMap.has(a.name)) this.err('TC203', a.line, `${r.text} already has an alternative "${a.text}".`);
219
+ a.fieldMap = new Map();
220
+ for (const f of a.fields) {
221
+ if (f.name === 'which') { this.err('TC203', f.line, `"which" is the name Thunder gives to the alternative a ${r.text} is, so a field can't be called that.`, 'Give the field another name.'); continue; }
222
+ if (a.fieldMap.has(f.name)) this.err('TC203', f.line, `${a.text} already has a field "${f.text}".`);
223
+ f.py = pyName(f.name);
224
+ this.resolveType(f.type, f.line);
225
+ const shared = r.fieldMap.get(f.name);
226
+ const plain = (t) => (t.k === 'optional' ? t.of : t);
227
+ if (shared && known(f.type) && known(shared.type) && !sameKind(plain(shared.type), plain(f.type))) {
228
+ this.err('TC303', f.line, `"${f.text}" is ${typeWords(plain(shared.type))} in another alternative of ${r.text}, so here it can't be ${typeWords(plain(f.type))}.`, 'Use one kind for a field name in every alternative, or give the fields different names.');
229
+ }
230
+ a.fieldMap.set(f.name, f);
231
+ }
232
+ r.altMap.set(a.name, a);
233
+ }
234
+ }
235
+ /** The alternatives of a data type, as a person reads them: successful, declined, or pending. */
236
+ altList(r, joiner = 'or') {
237
+ const ws = [...r.altMap.values()].map((a) => a.text.toLowerCase());
238
+ return ws.length <= 2 ? ws.join(` ${joiner} `) : `${ws.slice(0, -1).join(', ')}, ${joiner} ${ws[ws.length - 1]}`;
239
+ }
240
+ /** The alternative a name is known to be here (inside its case, or after "If x is …"), or null. */
241
+ narrowed(e) {
242
+ if (e.k !== 'name') return null;
243
+ for (let i = this.narrow.length - 1; i >= 0; i--) if (this.narrow[i].name === e.name) return this.narrow[i].alt;
244
+ return null;
245
+ }
246
+ /** "x is successful", as the program runs it: x's which equals "successful". */
247
+ altTest(subject, r, alt, neg, line) {
248
+ const which = { k: 'field', obj: subject, name: 'which', text: 'which', py: 'which', static: true, line, type: { k: 'text' } };
249
+ return { k: 'cmp', op: neg ? '!=' : '==', l: which, r: { k: 'str', parts: [alt], line, type: { k: 'text' } }, line, type: { k: 'bool' } };
161
250
  }
162
251
  resolveType(t, line) {
163
252
  if (!t) return;
@@ -202,7 +291,79 @@ class Checker {
202
291
  }
203
292
  rulesFor(key) { return this.rules.filter((r) => r.watchesVar && r.subject === key); }
204
293
 
294
+ /**
295
+ * An endpoint (When someone calls GET /habits/{name}:): a known method, one per method and path, every {part} of
296
+ * the path received, and inputs of kinds a request can carry (an input with no kind is text).
297
+ */
298
+ checkEndpoint(f) {
299
+ const ep = f.endpoint;
300
+ const line = ep.line;
301
+ if (!['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(ep.method)) this.err('TC108', line, `"${ep.method}" isn't an HTTP method Thunder answers.`, 'Use GET, POST, PUT, PATCH, or DELETE.');
302
+ this.routes ??= new Map();
303
+ const key = `${ep.method} /${ep.segments.map((g) => (g.param ? '{}' : g.lit)).join('/')}`;
304
+ // The same method and path twice is already reported as a name defined twice ("GET /x" is already defined); a
305
+ // different spelling of one route (/x/{a} and /x/{b}) is caught here.
306
+ if (this.routes.has(key) && this.routes.get(key).path !== ep.path) this.err('TC203', line, `${ep.method} ${ep.path} is answered already, by ${ep.method} ${this.routes.get(key).path} (line ${this.routes.get(key).line}).`, 'Each method and path is answered by one endpoint.');
307
+ else if (!this.routes.has(key)) this.routes.set(key, ep);
308
+ const plain = (t) => t && (['whole', 'number', 'money', 'text', 'bool', 'date'].includes(t.k) || (t.k === 'optional' && plain(t.of)));
309
+ for (const p of f.params) {
310
+ if (!p.type) p.type = { k: 'text' };
311
+ if (!plain(p.type)) this.err('TC306', p.line, `"${p.text}" can't come from a request: it is ${typeWords(p.type)}.`, 'An endpoint receives whole numbers, numbers, money, text, yes/no, dates, or optional ones of those. Receive a record\'s fields one by one.');
312
+ }
313
+ for (const g of ep.segments.filter((x) => x.param)) {
314
+ const p = f.params.find((x) => x.name === g.param);
315
+ if (!p) this.err('TC207', line, `The path has {${g.text}}, but the endpoint doesn't receive "${g.text}".`, `Add: Receive ${g.text} as text (or the kind it is).`);
316
+ else g.py = pyName(p.name);
317
+ }
318
+ this.info.endpoints.push(f);
319
+ }
320
+
321
+ /** calling GET /habits/walk with name "run": the endpoint that answers it, called directly with those inputs. */
322
+ callEndpoint(e, sc, o) {
323
+ const segs = e.path.split('/').filter(Boolean);
324
+ const f = this.info.endpointsAll?.find((x) => x.endpoint.method === e.method && x.endpoint.segments.length === segs.length && x.endpoint.segments.every((g, i) => g.param || g.lit === segs[i]));
325
+ if (!f) {
326
+ const known = (this.info.endpointsAll ?? []).map((x) => `${x.endpoint.method} ${x.endpoint.path}`);
327
+ this.err('TC207', e.line, `Nothing in this program answers ${e.method} ${e.path}.`, known.length ? `Endpoints: ${known.join(', ')}.` : 'Write one: When someone calls GET /habits:');
328
+ for (const fl of e.fields) this.ex(fl.e, sc, o);
329
+ return UNKNOWN;
330
+ }
331
+ const given = new Map();
332
+ f.endpoint.segments.forEach((g, i) => { if (g.param) given.set(g.param, this.pathValue(segs[i], f.params.find((p) => p.name === g.param), e.line)); });
333
+ for (const fl of e.fields) {
334
+ if (!f.params.some((p) => p.name === fl.name)) { this.err('TC207', e.line, `${f.endpoint.method} ${f.endpoint.path} doesn't receive "${fl.text}".`, `It receives: ${f.params.map((p) => p.text).join(', ') || 'nothing'}.`); continue; }
335
+ if (given.has(fl.name)) { this.err('TC203', e.line, `"${fl.text}" is already given by the path.`); continue; }
336
+ given.set(fl.name, fl.e);
337
+ }
338
+ // Inputs in order, up to the last one given: a default fills a gap, an optional one is nothing, others are needed.
339
+ const args = [];
340
+ const last = f.params.reduce((k, p, i) => (given.has(p.name) ? i : k), -1);
341
+ f.params.forEach((p, i) => {
342
+ if (given.has(p.name)) { args.push(given.get(p.name)); return; }
343
+ if (p.dflt) { if (i < last) args.push(JSON.parse(JSON.stringify(p.dflt))); return; }
344
+ if (p.type?.k === 'optional') { if (i < last) args.push({ k: 'nothing', line: e.line }); return; }
345
+ this.err('TC207', e.line, `${f.endpoint.method} ${f.endpoint.path} needs "${p.text}".`, `Give it: calling ${e.method} ${e.path} with ${p.text} ….`);
346
+ });
347
+ Object.assign(e, { k: 'call', name: f.name, text: f.text, args });
348
+ return this.call(e, sc, o);
349
+ }
350
+ /** A part of a path written in a test (walk, 3) as the value its input receives. */
351
+ pathValue(text, p, line) {
352
+ const k = p?.type?.k === 'optional' ? p.type.of.k : p?.type?.k;
353
+ if ((k === 'whole' || k === 'number') && /^-?\d+(\.\d+)?$/.test(text)) return { k: 'num', text, whole: !text.includes('.'), line };
354
+ if (k === 'money' && /^\d+(\.\d+)?$/.test(text)) return { k: 'money', text, line };
355
+ if (k === 'bool' && /^(yes|no|true|false)$/i.test(text)) return { k: 'bool', v: /^(yes|true)$/i.test(text), line };
356
+ if (k === 'date' && /^\d{4}-\d{2}-\d{2}$/.test(text)) return { k: 'date', text, line };
357
+ if (k && k !== 'text') this.err('TC303', line, `"${text}" in the path isn't ${typeWords(p.type)}, which "${p.text}" is.`);
358
+ return { k: 'str', parts: [decodeURIComponent(text)], line };
359
+ }
360
+
361
+ checkStatus(n, line, [lo, hi], what) {
362
+ if (!(n >= lo && n <= hi)) this.err('TC303', line, `${what} ${n}: ${what.startsWith('Give') ? 'an answer that worked' : 'a request that could not be done'} has a status from ${lo} to ${hi}.`, what.startsWith('Give') ? 'For example 200 (done) or 201 (created). To say no, use Stop with "…" and status 404.' : 'For example 400 (bad request), 404 (not found), or 409 (conflict).');
363
+ }
364
+
205
365
  checkFunc(f) {
366
+ if (f.endpoint) this.checkEndpoint(f);
206
367
  const sc = new Scope(this.global, 'func');
207
368
  sc.func = f;
208
369
  f.gives = [];
@@ -255,11 +416,19 @@ class Checker {
255
416
  if (!ctx.inFunc || ctx.inTest) { this.err('TC208', line, '"Give" can only be used inside a "To" block, to give back a result.'); return; }
256
417
  const t = this.ex(s.e, sc);
257
418
  sc.func ? sc.func.gives.push(t) : (findFunc(sc)?.gives.push(t));
419
+ if (s.status != null) this.checkStatus(s.status, line, [200, 299], 'Give … with status');
258
420
  return;
259
421
  }
260
- case 'stop': this.ex(s.e, sc); return;
422
+ case 'stop': this.ex(s.e, sc); if (s.status != null) this.checkStatus(s.status, line, [400, 599], 'Stop … and status'); return;
423
+ case 'depending': return this.depending(s, sc, ctx);
261
424
  case 'if':
262
- for (const b of s.branches) { this.cond(b.cond, sc); this.block(b.body, sc, ctx); }
425
+ for (const b of s.branches) {
426
+ // If payment is successful: inside, payment is known to be successful.
427
+ const c = b.cond.k === 'isAlt' && b.cond.e.k === 'name' ? { name: b.cond.e.name, alt: b.cond.alt } : null;
428
+ this.cond(b.cond, sc);
429
+ if (c && b.cond.k === 'cmp') this.narrow.push(c);
430
+ try { this.block(b.body, sc, ctx); } finally { if (c && b.cond.k === 'cmp') this.narrow.pop(); }
431
+ }
263
432
  if (s.otherwise) this.block(s.otherwise, sc, ctx);
264
433
  return;
265
434
  case 'each': {
@@ -301,6 +470,13 @@ class Checker {
301
470
  // An empty list learns what it holds from the first thing added to it.
302
471
  if (s.k === 'add' && s.targetKind === 'list' && !known(tt.of) && known(te) && s.target.k === 'name' && s.target.ref?.type?.k === 'list') s.target.ref.type = T('list', { of: te });
303
472
  this.afterAssign(s, s.target, sc);
473
+ // A list a Never rule watches (a name, or a record's field) is changed on a copy, checked, then kept: a change
474
+ // that breaks the rule is refused and the old list stays, like any other value. Every target does the same.
475
+ if (s.targetKind === 'list' || (s.targetKind === 'map' && s.k === 'remove')) {
476
+ const watched = s.target.k === 'name' ? s.rules?.length > 0
477
+ : s.target.k === 'field' && (this.records.get(s.target.record)?.rulesToCheck ?? []).some((r) => r.subject === s.target.name);
478
+ if (watched && s.targetKind === 'list') s.guard = true;
479
+ }
304
480
  return;
305
481
  }
306
482
  case 'increase': case 'decrease': {
@@ -464,6 +640,7 @@ class Checker {
464
640
  const tgt = s.target;
465
641
  if (tgt.k === 'name') {
466
642
  const g = this.global.vars.get(tgt.name);
643
+ if (g && g.kind === 'store') { this.err('TC205', line, `"${tgt.text}" is a stored list (line ${g.line}): change its items, don't replace it.`, `Use Add … to ${tgt.text}, Remove … from ${tgt.text}, or Set ${tgt.text} at <position> to ….`); return; }
467
644
  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; }
468
645
  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; }
469
646
  const cur = sc.get(tgt.name);
@@ -484,6 +661,7 @@ class Checker {
484
661
  }
485
662
  } else {
486
663
  const tt = this.ex(tgt, sc);
664
+ if (tgt.k === 'field' && tgt.name === 'which' && tgt.obj.type?.k === 'record' && this.records.get(tgt.obj.type.name)?.altMap) this.err('TC205', line, `Which alternative a ${tgt.obj.type.text ?? 'value'} is can't be changed.`, 'Build a new one instead: Set payment to a declined Payment with ….');
487
665
  this.lvalue(tgt, sc, line);
488
666
  if (known(tt) && known(tv) && !compatible(tt, tv)) this.err('TC303', line, `${tgt.k === 'field' ? `The field "${tgt.text}"` : 'This entry'} holds ${typeWords(tt)}, so it can't be set to ${typeWords(tv)}.`);
489
667
  }
@@ -547,6 +725,32 @@ class Checker {
547
725
  case 'bool': return T('bool');
548
726
  case 'nothing': return T('nothing');
549
727
  case 'hole': return e.type ?? UNKNOWN;
728
+ case 'draftHole': return this.draftHole(e, sc);
729
+ case 'callEndpoint': return this.callEndpoint(e, sc, o);
730
+ case 'httpCall': {
731
+ this.info.usesHttp = true;
732
+ const ut = this.ex(e.url, sc, o);
733
+ if (known(ut) && ut.k !== 'text') this.err('TC305', line, `The address to call is text ("https://…"), but this is ${typeWords(ut)}.`);
734
+ if (e.body) this.ex(e.body, sc, o);
735
+ if (!e.as) return T('text');
736
+ this.resolveType(e.as, line);
737
+ const rec = e.as.k === 'record' ? this.records.get(e.as.name) : e.as.k === 'list' && e.as.of?.k === 'record' ? this.records.get(e.as.of.name) : null;
738
+ const plain = (t) => t && (['whole', 'number', 'money', 'text', 'bool', 'date'].includes(t.k) || (t.k === 'optional' && plain(t.of)));
739
+ if (!rec) { this.err('TC306', line, `An answer is read as a record or a list of records, for example: as Rate, as list of Rate.`, 'Without "as", the answer is its text.'); return UNKNOWN; }
740
+ const bad = rec.fields.find((f) => !plain(f.type));
741
+ if (bad) { this.err('TC306', line, `An answer can't be read as ${rec.text} yet: its field "${bad.text}" is not a plain value.`); return UNKNOWN; }
742
+ e.record = rec;
743
+ return e.as;
744
+ }
745
+ case 'isAlt': {
746
+ const t = this.ex(e.e, sc, o);
747
+ const r = t.k === 'record' ? this.records.get(t.name) : null;
748
+ if (!r?.altMap) { if (known(t)) this.err('TC305', line, `"is ${e.text}" asks which alternative a value is, but this is ${typeWords(t)}, not a data type with alternatives.`); return T('bool'); }
749
+ if (!r.altMap.has(e.alt)) { this.err('TC217', line, `A ${r.text} is ${this.altList(r)}; "${e.text}" isn't one of them.`); return T('bool'); }
750
+ const neg = e.neg;
751
+ Object.assign(e, this.altTest(e.e, r, e.alt, false, line));
752
+ return T('bool');
753
+ }
550
754
  case 'today': case 'date': return T('date');
551
755
  case 'paren': return this.ex(e.e, sc, o);
552
756
  case 'list': {
@@ -564,6 +768,22 @@ class Checker {
564
768
  case 'field': {
565
769
  const ot = this.ex(e.obj, sc, o);
566
770
  const r = ot.k === 'record' ? this.records.get(ot.name) : null;
771
+ if (r) e.record = r.name;
772
+ if (r?.altMap && e.name !== 'which' && r.fieldMap.has(e.name)) {
773
+ // A field one alternative has: only where that alternative is known.
774
+ const alt = this.narrowed(e.obj);
775
+ const a = alt ? r.altMap.get(alt) : null;
776
+ const owners = [...r.altMap.values()].filter((x) => x.fieldMap.has(e.name));
777
+ const f = a?.fieldMap.get(e.name);
778
+ e.py = r.fieldMap.get(e.name).py; e.static = true;
779
+ if (f) return f.type;
780
+ const who = owners.map((x) => x.text.toLowerCase()).join(' or ');
781
+ if (a) this.err('TC216', line, `A ${a.text.toLowerCase()} ${r.text} has no ${e.text}; only a ${who} one does.`, `Fields of a ${a.text.toLowerCase()} ${r.text}: ${[...a.fieldMap.keys()].join(', ') || 'none'}.`);
782
+ else this.err('TC216', line, `Only a ${who} ${r.text} has ${/^[aeiou]/i.test(e.text) ? 'an' : 'a'} ${e.text}, and here it could be any of them.`, e.obj.k === 'name'
783
+ ? `Check which it is first: put this under "Depending on ${e.obj.text}:" in the ${owners[0]?.text ?? ''} case, or under "If ${e.obj.text} is ${owners[0]?.text.toLowerCase() ?? ''}:".`
784
+ : `Set it to a name first, then check which it is with "Depending on …:".`);
785
+ return UNKNOWN;
786
+ }
567
787
  if (r) {
568
788
  const f = r.fieldMap.get(e.name);
569
789
  if (!f) { const g = closest(e.name, [...r.fieldMap.keys()]); this.err('TC206', line, `A ${r.text} has no field "${e.text}".`, g ? `Did you mean "${g}"? Fields: ${[...r.fieldMap.keys()].join(', ')}.` : `Fields: ${[...r.fieldMap.keys()].join(', ')}.`); return UNKNOWN; }
@@ -666,7 +886,11 @@ class Checker {
666
886
  return this.arith(e.op, l, r, line);
667
887
  }
668
888
  case 'cmp': {
669
- const l = this.ex(e.l, sc, o), r = this.ex(e.r, sc, o);
889
+ const l = this.ex(e.l, sc, o);
890
+ // paid is refunded: a word that is neither a value here nor an alternative of the data type.
891
+ const lr = l.k === 'record' ? this.records.get(l.name) : null;
892
+ if (lr?.altMap && e.r.k === 'name' && !sc.get(e.r.name) && !this.global.vars.get(e.r.name)) { this.err('TC217', line, `A ${lr.text} is ${this.altList(lr)}; "${e.r.text}" isn't one of them.`); return T('bool'); }
893
+ const r = this.ex(e.r, sc, o);
670
894
  this.comparable(l, r, line, e.op);
671
895
  return T('bool');
672
896
  }
@@ -694,7 +918,16 @@ class Checker {
694
918
  const el = this.elem[this.elem.length - 1];
695
919
  if (el) {
696
920
  const r = el.type.k === 'record' ? this.records.get(el.type.name) : null;
697
- if (r && r.fieldMap.has(e.name)) { const f = r.fieldMap.get(e.name); e.ref = { kind: 'elemField', py: f.py }; return f.type; }
921
+ if (r && r.fieldMap.has(e.name)) {
922
+ // The item's field wins, so a value of the same name is hidden here: "orders where number is number" would
923
+ // compare each order's number with itself and keep every order. Almost always a mistake, so it is a problem.
924
+ const shadowed = sc.get(e.name);
925
+ if (shadowed && ['param', 'input', 'var', 'item', 'state'].includes(shadowed.kind) && !el.reported?.has(e.name)) {
926
+ (el.reported ??= new Set()).add(e.name);
927
+ this.err('TC219', e.line, `Here "${e.text}" means each ${r.text}'s ${e.text}, so your own "${e.text}"${shadowed.line ? ` (line ${shadowed.line})` : ''} isn't used.`, `Give your value another name, for example "wanted ${e.text}", and write: where ${e.text} is wanted ${e.text}.`);
928
+ }
929
+ const f = r.fieldMap.get(e.name); e.ref = { kind: 'elemField', py: f.py }; return f.type;
930
+ }
698
931
  if (!r && !sc.get(e.name) && !el.type.k.match(/^(whole|number|money|text|bool|date)$/)) { e.ref = { kind: 'elemKey', key: e.text }; return UNKNOWN; }
699
932
  if (!r && !sc.get(e.name) && e.name === 'it') { e.ref = { kind: 'elem' }; return el.type; }
700
933
  }
@@ -728,6 +961,7 @@ class Checker {
728
961
  const entry = this.global.vars.get(e.name);
729
962
  if (!f) { this.err('TC201', e.line, `I don't know a function called "${e.text}".`); return UNKNOWN; }
730
963
  e.py = f.py;
964
+ e.args.forEach((a, k) => { if (a.k === 'draftHole' && !a.want && f.params[k]?.type) a.expected = f.params[k].type; });
731
965
  const ts = e.args.map((a) => this.ex(a, sc, o));
732
966
  const required = f.params.filter((p) => !p.dflt).length;
733
967
  if (ts.length < required || ts.length > f.params.length) {
@@ -738,13 +972,93 @@ class Checker {
738
972
  return entry?.ret ?? UNKNOWN;
739
973
  }
740
974
 
975
+ /**
976
+ * A hole in a draft (TC120): what kind of value it needs (written, or expected where it stands) and what is
977
+ * available here with that kind. Thunder asks; it never chooses a value. The hole has its kind, so nothing else on
978
+ * the line is reported because of it.
979
+ */
980
+ /** a successful Payment with amount $5: the alternative's own fields, all it needs, and "which" set for it. */
981
+ newAlternative(e, r, sc, o) {
982
+ const ty = T('record', { name: r.name, text: r.text });
983
+ const a = e.alt ? r.altMap.get(e.alt) : null;
984
+ if (!a) {
985
+ for (const f of e.fields) this.ex(f.e, sc, o);
986
+ const kinds = [...r.altMap.values()].map((x) => `a ${x.text.toLowerCase()} ${r.text}`);
987
+ if (e.alt) this.err('TC217', e.line, `A ${r.text} is ${this.altList(r)}; "${e.altText}" isn't one of them.`);
988
+ else this.err('TC217', e.line, `Say which ${r.text} it is: ${kinds.length <= 2 ? kinds.join(' or ') : `${kinds.slice(0, -1).join(', ')}, or ${kinds[kinds.length - 1]}`}.`, `For example: ${kinds[0]}${r.alts[0]?.fields.length ? ' with …' : ''}.`);
989
+ return ty;
990
+ }
991
+ const given = new Set();
992
+ for (const f of e.fields) {
993
+ const def = a.fieldMap.get(f.name);
994
+ if (def && f.e.k === 'draftHole' && !f.e.want) f.e.expected = def.type;
995
+ const t = this.ex(f.e, sc, o);
996
+ if (!def) { const others = [...r.altMap.values()].filter((x) => x.fieldMap.has(f.name)).map((x) => x.text.toLowerCase()); this.err('TC206', e.line, `A ${a.text.toLowerCase()} ${r.text} has no field "${f.text}"${others.length ? ` (a ${others.join(' or ')} one does)` : ''}.`, `Fields of a ${a.text.toLowerCase()} ${r.text}: ${[...a.fieldMap.keys()].join(', ') || 'none'}.`); continue; }
997
+ f.py = def.py;
998
+ if (given.has(f.name)) this.err('TC203', e.line, `The field "${f.text}" is given twice.`);
999
+ given.add(f.name);
1000
+ if (known(def.type) && known(t) && !compatible(def.type, t)) this.err('TC303', e.line, `A ${a.text.toLowerCase()} ${r.text}'s ${def.text} is ${typeWords(def.type)}, but ${typeWords(t)} was given.`);
1001
+ }
1002
+ const missing = a.fields.filter((f) => !given.has(f.name) && f.type.k !== 'optional' && f.type.k !== 'list' && f.type.k !== 'map');
1003
+ if (missing.length) this.err('TC210', e.line, `A ${a.text.toLowerCase()} ${r.text} needs ${missing.map((f) => f.text).join(', ')}.`, `Write: a ${a.text.toLowerCase()} ${r.text} with ${a.fields.map((f) => `${f.text} …`).join(' and ')}.`);
1004
+ e.fields.unshift({ name: 'which', text: 'which', py: 'which', e: { k: 'str', parts: [a.name], line: e.line, type: T('text') }, line: e.line });
1005
+ return ty;
1006
+ }
1007
+
1008
+ draftHole(e, sc) {
1009
+ // A record's kind as written in its "A … has:" line (a Line, not a line).
1010
+ const named = (t) => (!t ? t : t.k === 'record' ? { ...t, text: this.records.get(t.name)?.text ?? t.text } : t.of ? { ...t, of: named(t.of) } : t);
1011
+ const want = named(e.want ?? e.expected ?? null);
1012
+ // Stricter than compatible(): only what really is that kind (a whole number can stand for a number, not the
1013
+ // other way round, and money is not a number).
1014
+ const same = (w, t) => {
1015
+ if (!known(w) || !known(t)) return false;
1016
+ if (w.k === 'optional') return t.k === 'optional' ? same(w.of, t.of) : same(w.of, t);
1017
+ if (w.k === 'number') return t.k === 'number' || t.k === 'whole';
1018
+ if (w.k !== t.k) return false;
1019
+ if (w.k === 'record') return w.name === t.name;
1020
+ if (w.k === 'list') return !known(w.of) || same(w.of, t.of);
1021
+ return true;
1022
+ };
1023
+ const fits = (t) => !want || !known(want) || same(want, t);
1024
+ const what = { param: 'input', input: 'input', var: 'value', state: 'remembered value', item: 'item', const: 'kept value', store: 'stored list' };
1025
+ const seen = new Set();
1026
+ const available = [];
1027
+ for (let at = sc; at; at = at.parent) {
1028
+ for (const [name, v] of at.vars) {
1029
+ if (seen.has(name) || !what[v.kind]) continue;
1030
+ seen.add(name);
1031
+ if (fits(v.type)) available.push({ name: v.text ?? name, what: what[v.kind], kind: known(v.type) ? typeWords(v.type) : null });
1032
+ }
1033
+ }
1034
+ if (want && known(want)) {
1035
+ for (const f of this.funcs.values()) {
1036
+ const ret = this.global.vars.get(f.name)?.ret;
1037
+ if (same(want, ret)) available.push({ name: f.text, what: 'function', kind: typeWords(ret), call: f.params.length ? `${f.text} with ${f.params.map((p) => p.text).join(' and ')}` : f.text });
1038
+ }
1039
+ }
1040
+ const needs = want ? typeWords(want) : 'a value';
1041
+ const typed = want && known(want);
1042
+ const shown = available.slice(0, 8).map((a) => (a.what === 'function' ? `${a.call} (a function)` : `${a.name} (${a.what}${!typed && a.kind ? `, ${a.kind}` : ''})`));
1043
+ const more = available.length > 8 ? `, and ${available.length - 8} more` : '';
1044
+ const hint = !available.length ? `Nothing here is ${needs} yet. Write the value, or receive it as an input.`
1045
+ : typed ? `Here, ${needs} could come from: ${shown.join(', ')}${more}.`
1046
+ : `Values here: ${shown.join(', ')}${more}. Write the kind after the ? (?number) to see only what fits.`;
1047
+ const d = diag('TC120', e.line, `This is a hole: it needs ${needs}, and Thunder won't choose it for you. Fill it in before the program can run.`, hint);
1048
+ d.hole = { col: e.col ?? null, needs: want ? needs : null, written: !!e.want, available };
1049
+ this.d.push(d);
1050
+ return want ?? UNKNOWN;
1051
+ }
1052
+
741
1053
  newRecord(e, sc, o) {
742
1054
  const r = this.records.get(e.record);
743
1055
  if (!r) { this.err('TC209', e.line, `I don't know a record called "${e.record}".`); return UNKNOWN; }
744
1056
  e.py = r.py;
1057
+ if (r.altMap) return this.newAlternative(e, r, sc, o);
745
1058
  const given = new Set();
746
1059
  for (const f of e.fields) {
747
1060
  const def = r.fieldMap.get(f.name);
1061
+ if (f.e.k === 'draftHole' && !f.e.want && def?.type) f.e.expected = def.type;
748
1062
  const t = this.ex(f.e, sc, o);
749
1063
  if (!def) { const g = closest(f.name, [...r.fieldMap.keys()]); this.err('TC206', e.line, `A ${r.text} has no field "${f.text}".`, g ? `Did you mean "${g}"?` : `Fields: ${[...r.fieldMap.keys()].join(', ')}.`); continue; }
750
1064
  f.py = def.py;