@skillstech/thunderlang 1.6.1 → 1.8.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 (81) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/README.md +10 -3
  3. package/dist/core.cjs +264 -47
  4. package/dist/index.cjs +9118 -1077
  5. package/dist/learn.cjs +1419 -90
  6. package/package.json +1 -1
  7. package/src/ai.mjs +2 -1
  8. package/src/atlas.mjs +2 -1
  9. package/src/behaviour.mjs +246 -0
  10. package/src/cli-main.mjs +3015 -0
  11. package/src/cli.mjs +9 -2799
  12. package/src/conflict.mjs +0 -0
  13. package/src/core/ThunderDotnet.cs +195 -0
  14. package/src/core/check.mjs +316 -10
  15. package/src/core/cli.mjs +67 -10
  16. package/src/core/csharp-run.mjs +29 -8
  17. package/src/core/diagnostics.mjs +12 -1
  18. package/src/core/engine-core.mjs +161 -20
  19. package/src/core/engine-values.mjs +1 -0
  20. package/src/core/engine.mjs +131 -7
  21. package/src/core/go-run.mjs +3 -2
  22. package/src/core/index.mjs +6 -2
  23. package/src/core/java-run.mjs +3 -3
  24. package/src/core/kind.mjs +45 -0
  25. package/src/core/lexer.mjs +16 -2
  26. package/src/core/parser.mjs +254 -22
  27. package/src/core/project-root.mjs +18 -0
  28. package/src/core/project.mjs +18 -18
  29. package/src/core/react-run.mjs +3 -3
  30. package/src/core/runtime-go/thunder_runtime.go +269 -1
  31. package/src/core/runtime-npm.mjs +79 -0
  32. package/src/core/runtime-python.mjs +365 -3
  33. package/src/core/runtime-react.mjs +2 -1
  34. package/src/core/runtime-typescript.mjs +155 -6
  35. package/src/core/rust-run.mjs +3 -2
  36. package/src/core/serving.mjs +12 -0
  37. package/src/core/store-format.mjs +110 -0
  38. package/src/core/target-csharp.mjs +5 -1
  39. package/src/core/target-go.mjs +11 -4
  40. package/src/core/target-python.mjs +39 -6
  41. package/src/core/target-rust.mjs +1 -1
  42. package/src/core/target-typescript.mjs +95 -7
  43. package/src/core/typescript-run.mjs +14 -7
  44. package/src/core-changes-fs.mjs +28 -0
  45. package/src/core-changes.d.mts +67 -0
  46. package/src/core-changes.mjs +603 -0
  47. package/src/core-rules.mjs +146 -0
  48. package/src/core-services.d.mts +4 -0
  49. package/src/core-services.mjs +49 -0
  50. package/src/decision.mjs +2 -1
  51. package/src/distributed.mjs +2 -1
  52. package/src/emit.mjs +2 -2
  53. package/src/evidence.mjs +28 -0
  54. package/src/examples.d.mts +21 -0
  55. package/src/examples.mjs +175 -0
  56. package/src/focus.mjs +2 -1
  57. package/src/index.d.ts +4 -0
  58. package/src/index.mjs +4 -0
  59. package/src/intent-atlas.mjs +4 -3
  60. package/src/mcp.mjs +52 -6
  61. package/src/passport-fs.mjs +2 -1
  62. package/src/passport.mjs +2 -1
  63. package/src/privacy.mjs +2 -1
  64. package/src/program.d.mts +4 -0
  65. package/src/program.mjs +4 -0
  66. package/src/read-repo-fs.mjs +2 -1
  67. package/src/read-repo.mjs +3 -2
  68. package/src/report.mjs +3 -2
  69. package/src/review.mjs +71 -4
  70. package/src/select.mjs +2 -1
  71. package/src/semantic-diff.mjs +7 -6
  72. package/src/system.mjs +3 -2
  73. package/src/text-order.mjs +6 -0
  74. package/src/thunderize.mjs +2 -1
  75. package/src/trace-cli.mjs +8 -3
  76. package/src/trace-data.mjs +3 -2
  77. package/src/trace-fs.mjs +29 -3
  78. package/src/trace.mjs +27 -10
  79. package/src/write-across-cli.mjs +22 -4
  80. package/src/write-across.mjs +2 -1
  81. package/syntaxes/thunder.tmLanguage.json +196 -0
@@ -27,7 +27,7 @@ export const typeWords = (t) => {
27
27
  case 'map': return 'a map';
28
28
  case 'record': return `a ${t.text ?? t.name}`;
29
29
  case 'optional': return `${typeWords(t.of)} or nothing`;
30
- case 'module': return 'a Python module';
30
+ case 'module': return 'a library';
31
31
  default: return 'a value';
32
32
  }
33
33
  };
@@ -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
 
@@ -87,13 +88,13 @@ class Checker {
87
88
  for (const r of inf.records) { this.records.set(r.name, r); this.info.imported.add(r); }
88
89
  for (const f of inf.funcs) { this.global.vars.set(f.name, { kind: 'func', line: f.line, name: f.name, text: f.text, py: f.py, stmt: f, ret: f.ret ?? UNKNOWN }); this.funcs.set(f.name, f); this.info.imported.add(f); }
89
90
  for (const k of inf.consts) { this.global.vars.set(k.name, { kind: 'const', line: k.line, name: k.name, text: k.text, py: k.py, type: k.e.type ?? UNKNOWN }); this.info.imported.add(k); }
90
- for (const m of inf.modules) { this.global.vars.set(m.name, { kind: 'module', line: m.line, name: m.name, text: m.text, py: m.py, type: T('module') }); this.info.imported.add(m); }
91
+ for (const m of inf.modules) { this.global.vars.set(m.name, { kind: 'module', line: m.line, name: m.name, text: m.text, py: m.py, ecosystem: m.ecosystem, type: T('module') }); this.info.imported.add(m); }
91
92
  }
92
93
  // 1. Global declarations, hoisted: records, functions, modules, kept values.
93
94
  for (const s of top) {
94
95
  if (s.k === 'record') this.declare(s, 'record', s.line, { py: pyName(s.name, 'pascal'), stmt: s });
95
96
  else if (s.k === 'func') this.declare(s, 'func', s.line, { py: pyName(s.name), stmt: s, ret: UNKNOWN });
96
- else if (s.k === 'use') this.declare(s, 'module', s.line, { py: pyName(s.name), module: s.module, type: T('module') });
97
+ else if (s.k === 'use') this.declare(s, 'module', s.line, { py: pyName(s.name), module: s.module, ecosystem: s.ecosystem, type: T('module') });
97
98
  else if (s.k === 'screen') {
98
99
  const prev = this.screens.get(s.name);
99
100
  if (prev) this.err('TC203', s.line, `There is already a screen called "${s.text}" (line ${prev.line}).`, 'Give one of them a different name.');
@@ -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': {
@@ -464,6 +633,7 @@ class Checker {
464
633
  const tgt = s.target;
465
634
  if (tgt.k === 'name') {
466
635
  const g = this.global.vars.get(tgt.name);
636
+ 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
637
  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
638
  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
639
  const cur = sc.get(tgt.name);
@@ -484,6 +654,7 @@ class Checker {
484
654
  }
485
655
  } else {
486
656
  const tt = this.ex(tgt, sc);
657
+ 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
658
  this.lvalue(tgt, sc, line);
488
659
  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
660
  }
@@ -547,6 +718,32 @@ class Checker {
547
718
  case 'bool': return T('bool');
548
719
  case 'nothing': return T('nothing');
549
720
  case 'hole': return e.type ?? UNKNOWN;
721
+ case 'draftHole': return this.draftHole(e, sc);
722
+ case 'callEndpoint': return this.callEndpoint(e, sc, o);
723
+ case 'httpCall': {
724
+ this.info.usesHttp = true;
725
+ const ut = this.ex(e.url, sc, o);
726
+ if (known(ut) && ut.k !== 'text') this.err('TC305', line, `The address to call is text ("https://…"), but this is ${typeWords(ut)}.`);
727
+ if (e.body) this.ex(e.body, sc, o);
728
+ if (!e.as) return T('text');
729
+ this.resolveType(e.as, line);
730
+ 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;
731
+ const plain = (t) => t && (['whole', 'number', 'money', 'text', 'bool', 'date'].includes(t.k) || (t.k === 'optional' && plain(t.of)));
732
+ 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; }
733
+ const bad = rec.fields.find((f) => !plain(f.type));
734
+ 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; }
735
+ e.record = rec;
736
+ return e.as;
737
+ }
738
+ case 'isAlt': {
739
+ const t = this.ex(e.e, sc, o);
740
+ const r = t.k === 'record' ? this.records.get(t.name) : null;
741
+ 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'); }
742
+ 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'); }
743
+ const neg = e.neg;
744
+ Object.assign(e, this.altTest(e.e, r, e.alt, false, line));
745
+ return T('bool');
746
+ }
550
747
  case 'today': case 'date': return T('date');
551
748
  case 'paren': return this.ex(e.e, sc, o);
552
749
  case 'list': {
@@ -564,6 +761,21 @@ class Checker {
564
761
  case 'field': {
565
762
  const ot = this.ex(e.obj, sc, o);
566
763
  const r = ot.k === 'record' ? this.records.get(ot.name) : null;
764
+ if (r?.altMap && e.name !== 'which' && r.fieldMap.has(e.name)) {
765
+ // A field one alternative has: only where that alternative is known.
766
+ const alt = this.narrowed(e.obj);
767
+ const a = alt ? r.altMap.get(alt) : null;
768
+ const owners = [...r.altMap.values()].filter((x) => x.fieldMap.has(e.name));
769
+ const f = a?.fieldMap.get(e.name);
770
+ e.py = r.fieldMap.get(e.name).py; e.static = true;
771
+ if (f) return f.type;
772
+ const who = owners.map((x) => x.text.toLowerCase()).join(' or ');
773
+ 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'}.`);
774
+ 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'
775
+ ? `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() ?? ''}:".`
776
+ : `Set it to a name first, then check which it is with "Depending on …:".`);
777
+ return UNKNOWN;
778
+ }
567
779
  if (r) {
568
780
  const f = r.fieldMap.get(e.name);
569
781
  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; }
@@ -621,7 +833,7 @@ class Checker {
621
833
  }
622
834
  case 'dot': {
623
835
  const ot = this.ex(e.obj, sc, o);
624
- if (ot.k !== 'module') this.err('TC402', line, `"${e.attr}" with a dot reaches into a Python module brought in with "Use". ${e.obj.k === 'name' ? `"${e.obj.text}"` : 'This'} is not one.`, 'Write "Use <module> as <name>" at the top of the file first.');
836
+ if (ot.k !== 'module') this.err('TC402', line, `"${e.attr}" with a dot reaches into a library brought in with "Use". ${e.obj.k === 'name' ? `"${e.obj.text}"` : 'This'} is not one.`, 'Write "Use <module> as <name>" (Python) or Use "<package>" from npm as <name> at the top of the file first.');
625
837
  for (const a of e.args ?? []) this.ex(a, sc, o);
626
838
  return UNKNOWN;
627
839
  }
@@ -666,7 +878,11 @@ class Checker {
666
878
  return this.arith(e.op, l, r, line);
667
879
  }
668
880
  case 'cmp': {
669
- const l = this.ex(e.l, sc, o), r = this.ex(e.r, sc, o);
881
+ const l = this.ex(e.l, sc, o);
882
+ // paid is refunded: a word that is neither a value here nor an alternative of the data type.
883
+ const lr = l.k === 'record' ? this.records.get(l.name) : null;
884
+ 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'); }
885
+ const r = this.ex(e.r, sc, o);
670
886
  this.comparable(l, r, line, e.op);
671
887
  return T('bool');
672
888
  }
@@ -694,7 +910,16 @@ class Checker {
694
910
  const el = this.elem[this.elem.length - 1];
695
911
  if (el) {
696
912
  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; }
913
+ if (r && r.fieldMap.has(e.name)) {
914
+ // The item's field wins, so a value of the same name is hidden here: "orders where number is number" would
915
+ // compare each order's number with itself and keep every order. Almost always a mistake, so it is a problem.
916
+ const shadowed = sc.get(e.name);
917
+ if (shadowed && ['param', 'input', 'var', 'item', 'state'].includes(shadowed.kind) && !el.reported?.has(e.name)) {
918
+ (el.reported ??= new Set()).add(e.name);
919
+ 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}.`);
920
+ }
921
+ const f = r.fieldMap.get(e.name); e.ref = { kind: 'elemField', py: f.py }; return f.type;
922
+ }
698
923
  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
924
  if (!r && !sc.get(e.name) && e.name === 'it') { e.ref = { kind: 'elem' }; return el.type; }
700
925
  }
@@ -728,6 +953,7 @@ class Checker {
728
953
  const entry = this.global.vars.get(e.name);
729
954
  if (!f) { this.err('TC201', e.line, `I don't know a function called "${e.text}".`); return UNKNOWN; }
730
955
  e.py = f.py;
956
+ e.args.forEach((a, k) => { if (a.k === 'draftHole' && !a.want && f.params[k]?.type) a.expected = f.params[k].type; });
731
957
  const ts = e.args.map((a) => this.ex(a, sc, o));
732
958
  const required = f.params.filter((p) => !p.dflt).length;
733
959
  if (ts.length < required || ts.length > f.params.length) {
@@ -738,13 +964,93 @@ class Checker {
738
964
  return entry?.ret ?? UNKNOWN;
739
965
  }
740
966
 
967
+ /**
968
+ * A hole in a draft (TC120): what kind of value it needs (written, or expected where it stands) and what is
969
+ * available here with that kind. Thunder asks; it never chooses a value. The hole has its kind, so nothing else on
970
+ * the line is reported because of it.
971
+ */
972
+ /** a successful Payment with amount $5: the alternative's own fields, all it needs, and "which" set for it. */
973
+ newAlternative(e, r, sc, o) {
974
+ const ty = T('record', { name: r.name, text: r.text });
975
+ const a = e.alt ? r.altMap.get(e.alt) : null;
976
+ if (!a) {
977
+ for (const f of e.fields) this.ex(f.e, sc, o);
978
+ const kinds = [...r.altMap.values()].map((x) => `a ${x.text.toLowerCase()} ${r.text}`);
979
+ if (e.alt) this.err('TC217', e.line, `A ${r.text} is ${this.altList(r)}; "${e.altText}" isn't one of them.`);
980
+ 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 …' : ''}.`);
981
+ return ty;
982
+ }
983
+ const given = new Set();
984
+ for (const f of e.fields) {
985
+ const def = a.fieldMap.get(f.name);
986
+ if (def && f.e.k === 'draftHole' && !f.e.want) f.e.expected = def.type;
987
+ const t = this.ex(f.e, sc, o);
988
+ 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; }
989
+ f.py = def.py;
990
+ if (given.has(f.name)) this.err('TC203', e.line, `The field "${f.text}" is given twice.`);
991
+ given.add(f.name);
992
+ 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.`);
993
+ }
994
+ const missing = a.fields.filter((f) => !given.has(f.name) && f.type.k !== 'optional' && f.type.k !== 'list' && f.type.k !== 'map');
995
+ 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 ')}.`);
996
+ e.fields.unshift({ name: 'which', text: 'which', py: 'which', e: { k: 'str', parts: [a.name], line: e.line, type: T('text') }, line: e.line });
997
+ return ty;
998
+ }
999
+
1000
+ draftHole(e, sc) {
1001
+ // A record's kind as written in its "A … has:" line (a Line, not a line).
1002
+ 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);
1003
+ const want = named(e.want ?? e.expected ?? null);
1004
+ // Stricter than compatible(): only what really is that kind (a whole number can stand for a number, not the
1005
+ // other way round, and money is not a number).
1006
+ const same = (w, t) => {
1007
+ if (!known(w) || !known(t)) return false;
1008
+ if (w.k === 'optional') return t.k === 'optional' ? same(w.of, t.of) : same(w.of, t);
1009
+ if (w.k === 'number') return t.k === 'number' || t.k === 'whole';
1010
+ if (w.k !== t.k) return false;
1011
+ if (w.k === 'record') return w.name === t.name;
1012
+ if (w.k === 'list') return !known(w.of) || same(w.of, t.of);
1013
+ return true;
1014
+ };
1015
+ const fits = (t) => !want || !known(want) || same(want, t);
1016
+ const what = { param: 'input', input: 'input', var: 'value', state: 'remembered value', item: 'item', const: 'kept value', store: 'stored list' };
1017
+ const seen = new Set();
1018
+ const available = [];
1019
+ for (let at = sc; at; at = at.parent) {
1020
+ for (const [name, v] of at.vars) {
1021
+ if (seen.has(name) || !what[v.kind]) continue;
1022
+ seen.add(name);
1023
+ if (fits(v.type)) available.push({ name: v.text ?? name, what: what[v.kind], kind: known(v.type) ? typeWords(v.type) : null });
1024
+ }
1025
+ }
1026
+ if (want && known(want)) {
1027
+ for (const f of this.funcs.values()) {
1028
+ const ret = this.global.vars.get(f.name)?.ret;
1029
+ 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 });
1030
+ }
1031
+ }
1032
+ const needs = want ? typeWords(want) : 'a value';
1033
+ const typed = want && known(want);
1034
+ const shown = available.slice(0, 8).map((a) => (a.what === 'function' ? `${a.call} (a function)` : `${a.name} (${a.what}${!typed && a.kind ? `, ${a.kind}` : ''})`));
1035
+ const more = available.length > 8 ? `, and ${available.length - 8} more` : '';
1036
+ const hint = !available.length ? `Nothing here is ${needs} yet. Write the value, or receive it as an input.`
1037
+ : typed ? `Here, ${needs} could come from: ${shown.join(', ')}${more}.`
1038
+ : `Values here: ${shown.join(', ')}${more}. Write the kind after the ? (?number) to see only what fits.`;
1039
+ 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);
1040
+ d.hole = { col: e.col ?? null, needs: want ? needs : null, written: !!e.want, available };
1041
+ this.d.push(d);
1042
+ return want ?? UNKNOWN;
1043
+ }
1044
+
741
1045
  newRecord(e, sc, o) {
742
1046
  const r = this.records.get(e.record);
743
1047
  if (!r) { this.err('TC209', e.line, `I don't know a record called "${e.record}".`); return UNKNOWN; }
744
1048
  e.py = r.py;
1049
+ if (r.altMap) return this.newAlternative(e, r, sc, o);
745
1050
  const given = new Set();
746
1051
  for (const f of e.fields) {
747
1052
  const def = r.fieldMap.get(f.name);
1053
+ if (f.e.k === 'draftHole' && !f.e.want && def?.type) f.e.expected = def.type;
748
1054
  const t = this.ex(f.e, sc, o);
749
1055
  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
1056
  f.py = def.py;