@skillstech/thunderlang 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +212 -0
  2. package/README.md +4 -1
  3. package/dist/core.cjs +2080 -278
  4. package/dist/index.cjs +12742 -10943
  5. package/dist/learn.cjs +12976 -3598
  6. package/package.json +2 -2
  7. package/src/cli-home.mjs +242 -0
  8. package/src/cli.mjs +135 -41
  9. package/src/core/ThunderRuntime.cs +1367 -0
  10. package/src/core/check.mjs +158 -2
  11. package/src/core/cli.mjs +208 -17
  12. package/src/core/csharp-run.mjs +184 -0
  13. package/src/core/diagnostics.mjs +13 -0
  14. package/src/core/engine-core.mjs +855 -0
  15. package/src/core/engine-values.mjs +1054 -0
  16. package/src/core/engine-worker.mjs +15 -0
  17. package/src/core/engine.mjs +63 -0
  18. package/src/core/format.mjs +191 -3
  19. package/src/core/go-run.mjs +106 -0
  20. package/src/core/index.mjs +3 -1
  21. package/src/core/java/thunder/T.java +6 -0
  22. package/src/core/java/thunder/ThunderRuntime.java +1374 -0
  23. package/src/core/java-run.mjs +89 -0
  24. package/src/core/parser.mjs +331 -5
  25. package/src/core/project.mjs +43 -8
  26. package/src/core/react-run.mjs +96 -0
  27. package/src/core/runtime-go/thunder_runtime.go +3038 -0
  28. package/src/core/runtime-react.mjs +133 -0
  29. package/src/core/runtime-typescript.mjs +119 -0
  30. package/src/core/rust/thunder_runtime.rs +1645 -0
  31. package/src/core/rust-run.mjs +192 -0
  32. package/src/core/screen-values.mjs +30 -0
  33. package/src/core/target-csharp.mjs +484 -0
  34. package/src/core/target-go.mjs +555 -0
  35. package/src/core/target-java.mjs +587 -0
  36. package/src/core/target-python.mjs +2 -1
  37. package/src/core/target-react.mjs +270 -0
  38. package/src/core/target-rust.mjs +534 -0
  39. package/src/core/target-typescript.mjs +466 -0
  40. package/src/core/typescript-run.mjs +114 -0
  41. package/src/core.d.ts +18 -0
  42. package/src/core.mjs +1 -0
  43. package/src/emit.mjs +1 -1
  44. package/src/faithful.mjs +30 -0
  45. package/src/learn-lessons.mjs +245 -1
  46. package/src/learn.d.mts +8 -0
  47. package/src/learn.mjs +40 -4
  48. package/src/libraries.mjs +10 -3
  49. package/src/model.mjs +50 -8
  50. package/src/read-level.mjs +192 -0
  51. package/src/read-repo-fs.mjs +3 -1
  52. package/src/read.mjs +28 -5
  53. package/src/replay-cli.mjs +123 -0
  54. package/src/say-less.mjs +152 -11
  55. package/src/screens.mjs +833 -0
  56. package/src/steps.mjs +430 -19
  57. package/src/term.mjs +132 -0
  58. package/src/try-cli.mjs +225 -0
  59. package/src/why-cli.mjs +17 -7
  60. package/src/why.d.mts +17 -7
  61. package/src/why.mjs +114 -33
package/src/steps.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { sayLibraryCall } from './libraries.mjs';
2
- import { splitLogic, wrapped, accountsFor, asCodeWords, isCodeWords, closeOf, balancedText } from './faithful.mjs';
2
+ import { splitLogic, wrapped, accountsFor, asCodeWords, isCodeWords, closeOf, balancedText, pythonImportSays, sliceWords } from './faithful.mjs';
3
3
  import { parseStatement, parseExpr } from './meaning.mjs';
4
4
  // Steps: read any function as a short list of plain steps (check, branch, loop, set, call, return, fail).
5
5
  // Decisions become rules; everything else becomes steps. Deterministic and pattern-based, like the rest of
@@ -120,6 +120,40 @@ const KNOWN_CALLS = [
120
120
  { re: /^(?:log|logger|console|logging|fmt|Log|System\.out|println|print|puts|echo|printf|fprintf|fputs|perror|NSLog|os_log|debugPrint|syslog|std\.(?:cout|cerr|print|println))\b/i, say: () => 'Writes a log or message' },
121
121
  ];
122
122
 
123
+ /**
124
+ * Python `range(…)` in a loop, in words: `range(3)` "Counts i from 0 to 2", `range(n)` "Counts i from 0 up to n (not n
125
+ * itself)", `range(a, b)` "from a up to b (not b itself)", `range(len(xs))` "For each position i in xs", `_` "Repeats n
126
+ * times". Null for a step, or for anything but numbers and plain names.
127
+ */
128
+ function pythonRangeWords(v, argText) {
129
+ const args = splitTopArgs(argText).map((x) => x.trim());
130
+ const plainPath = (x) => /^[A-Za-z_][\w.]*$/.test(x);
131
+ const num = (x) => /^\d+$/.test(x);
132
+ if (args.length === 1) {
133
+ const n = args[0];
134
+ if (v === '_') return /^\w+$/.test(n) ? `Repeats ${n} times` : null;
135
+ const len = /^len\(\s*([A-Za-z_][\w.]*)\s*\)$/.exec(n);
136
+ if (len) return `For each position ${words(v)} in ${possessiveWords(len[1])}`;
137
+ if (num(n)) return Number(n) > 0 ? `Counts ${words(v)} from 0 to ${Number(n) - 1}` : null;
138
+ if (plainPath(n)) return `Counts ${words(v)} from 0 up to ${possessiveWords(n)} (not ${possessiveWords(n)} itself)`;
139
+ return null;
140
+ }
141
+ // `range(1, n + 1)`: 1 to n, n included.
142
+ if (args.length === 2 && v !== '_' && /^(?:\d+|[A-Za-z_][\w.]*)$/.test(args[0]) && /^[A-Za-z_][\w.]*\s*\+\s*1$/.test(args[1])) {
143
+ const end = args[1].replace(/\s*\+\s*1$/, '');
144
+ return `Counts ${words(v)} from ${num(args[0]) ? args[0] : possessiveWords(args[0])} to ${possessiveWords(end)}`;
145
+ }
146
+ if (args.length === 2 && v !== '_') {
147
+ const [a, b] = args;
148
+ if (num(a) && num(b)) return Number(b) > Number(a) ? `Counts ${words(v)} from ${a} to ${Number(b) - 1}` : null;
149
+ if ((num(a) || plainPath(a)) && (num(b) || plainPath(b))) {
150
+ const say = (x) => (num(x) ? x : possessiveWords(x));
151
+ return `Counts ${words(v)} from ${say(a)} up to ${say(b)} (not ${say(b)} itself)`;
152
+ }
153
+ }
154
+ return null;
155
+ }
156
+
123
157
  /** entry['easy'] -> "the entry's easy"; $x->y -> "the x's y"; plain names as words. */
124
158
  const possessiveWords = (path) => {
125
159
  if ((C_FAMILY.has(LANG) || LANG === 'swift') && /\[/.test(String(path)) && !/\[\s*['"]/.test(String(path))) return indexedWords(String(path).replace(/->/g, '.'));
@@ -249,11 +283,11 @@ function sayCodeConditionInner(cond) {
249
283
  if ((ty = c.match(/^typeof\s+([\w$.]+)\s*(===?|!==?)\s*["'](\w+)["']$/)) && TYPEOF_WORDS[ty[3]]) return `${possessiveWords(ty[1])} is ${/^!/.test(ty[2]) ? 'not ' : ''}${TYPEOF_WORDS[ty[3]]}`;
250
284
  if ((ty = c.match(/^(!|not\s+)?\\?(is_\w+)\(\s*\$?([\w$.\[\]'">-]+)\s*\)$/)) && PHP_IS[ty[2]]) return `${possessiveWords(ty[3])} is ${ty[1] ? 'not ' : ''}${PHP_IS[ty[2]]}`;
251
285
  // `x instanceof Foo` / `x is Foo` (Kotlin, C#) / isinstance(x, Foo): "x is a Foo".
252
- if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.]+)\s+instanceof\s+([\w$.\\]+)\s*\)?$/))) return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}a ${ty[3].split(/[.\\]/).pop()}`;
253
- if ((ty = c.match(/^([\w$.]+)\s+(is|!is)\s+([A-Z][\w.<>?]*)$/)) && !/^(?:True|False|None|Null|Nil|NULL)$/.test(ty[3])) return `${possessiveWords(ty[1])} is ${ty[2] === '!is' ? 'not ' : ''}a ${ty[3].split('.').pop()}`;
286
+ if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.]+)\s+instanceof\s+([\w$.\\]+)\s*\)?$/))) return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}${aWord(ty[3].split(/[.\\]/).pop())}`;
287
+ if ((ty = c.match(/^([\w$.]+)\s+(is|!is)\s+([A-Z][\w.<>?]*)$/)) && !/^(?:True|False|None|Null|Nil|NULL)$/.test(ty[3])) return `${possessiveWords(ty[1])} is ${ty[2] === '!is' ? 'not ' : ''}${aWord(ty[3].split('.').pop())}`;
254
288
  // Ruby `x.is_a?(String)` / `kind_of?` / `instance_of?`: "x is a String".
255
- if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.@]+)\.(?:is_a|kind_of|instance_of)\?\s*\(?\s*([A-Z][\w:]*)\s*\)?\s*\)?$/))) return `${possessiveWords(ty[2].replace(/^@/, ''))} is ${ty[1] ? 'not ' : ''}a ${ty[3].split('::').pop()}`;
256
- if ((ty = c.match(/^(not\s+)?isinstance\(\s*([\w.]+)\s*,\s*\(?\s*([\w.]+(?:\s*,\s*[\w.]+)*)\s*\)?\s*\)$/))) { const kinds = ty[3].split(/\s*,\s*/).map((x) => x.split('.').pop()); return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}${kinds.length > 1 ? `one of ${kinds.join(', ')}` : `a ${kinds[0]}`}`; }
289
+ if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.@]+)\.(?:is_a|kind_of|instance_of)\?\s*\(?\s*([A-Z][\w:]*)\s*\)?\s*\)?$/))) return `${possessiveWords(ty[2].replace(/^@/, ''))} is ${ty[1] ? 'not ' : ''}${aWord(ty[3].split('::').pop())}`;
290
+ if ((ty = c.match(/^(not\s+)?isinstance\(\s*([\w.]+)\s*,\s*\(?\s*([\w.]+(?:\s*,\s*[\w.]+)*)\s*\)?\s*\)$/))) { const kinds = ty[3].split(/\s*,\s*/).map((x) => x.split('.').pop()); return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}${kinds.length > 1 ? `one of ${kinds.join(', ')}` : aWord(kinds[0])}`; }
257
291
  // A bare yes/no property reads as a sentence: `order.refunded` -> "order is refunded", `!user.isAdmin` -> "user is not admin".
258
292
  const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
259
293
  const plural = (w, call) => !call && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
@@ -327,6 +361,36 @@ function matchingClose(str, open) {
327
361
  return -1;
328
362
  }
329
363
  const lastWords = (path) => words(String(path).split('.').pop());
364
+ /** "a" or "an" by the sound of a type's name: an Error, an OrderedDict, an HTTPError; a User, a URL. */
365
+ const aWord = (w) => {
366
+ const t = String(w);
367
+ const an = /^(?:[AEIOaeio]|U(?:n|m|nd|tt|pp)|u(?:n|m)|[FHLMNRSX][A-Z0-9]|[fhlmnrsx](?=[A-Z0-9]))/.test(t) && !/^(?:Eu|eu|Uni|uni|Use|use|Usu|One|one|Ur)/.test(t);
368
+ return `${an ? 'an' : 'a'} ${t}`;
369
+ };
370
+ /**
371
+ * A call's name in words, never ending on a dangling preposition: a function named after what it is for
372
+ * (`changeApprovalFor(x, …)`) gets its first argument when that is a plain name ("change approval for x"), and
373
+ * otherwise loses the preposition ("change approval"), instead of "change approval for ".
374
+ */
375
+ const ENDS_ON_PREPOSITION = /\s(?:for|from|to|of|with|by|in|on|at|about|into|as|via)$/;
376
+ function callWords(c, text) {
377
+ const w = lastWords(c);
378
+ if (!ENDS_ON_PREPOSITION.test(w)) return w;
379
+ const args = String(text ?? '');
380
+ const open = args.indexOf('(');
381
+ if (open >= 0) {
382
+ let depth = 0, end = open + 1;
383
+ for (; end < args.length; end++) {
384
+ const ch = args[end];
385
+ if ('([{'.includes(ch)) depth++;
386
+ else if (')]}'.includes(ch)) { if (depth === 0) break; depth--; }
387
+ else if (ch === ',' && depth === 0) break;
388
+ }
389
+ const first = args.slice(open + 1, end).trim();
390
+ if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(first)) return `${w} ${words(first.split('.').pop())}`;
391
+ }
392
+ return w.replace(ENDS_ON_PREPOSITION, '');
393
+ }
330
394
  /** "cmd.commandCalledAs.called" -> "called on command called as"; "this.count" -> "count". */
331
395
  function targetWords(path) {
332
396
  // (C, C++, Swift: an index keeps its place, `events[i].mask` is "the mask of events[i]", never just "events".)
@@ -356,10 +420,71 @@ function sayCall(name, args) {
356
420
  for (const k of KNOWN_CALLS) if (k.re.test(name)) {
357
421
  const target = (args.match(/^\s*["'`]([\w.\-/: ]{1,60})["'`]/) || [])[1];
358
422
  const base = k.say(name);
423
+ // A message says what it writes: `console.log("Saved.")`, `print(f"Total: {t}")`, `console.error(report(x))`.
424
+ if (base === 'Writes a log or message' && (LANG === 'typescript' || LANG === 'javascript' || LANG === 'python')) {
425
+ const what = messageWhat(args);
426
+ if (what) return `${base}: ${what}`;
427
+ }
359
428
  return target ? `${base}: ${target}` : base;
360
429
  }
361
430
  return null;
362
431
  }
432
+ /** Shortened text ends on a whole word ("… the exact…", never "… the exact cr…"); it stays a prefix of the text. */
433
+ const wholeWords = (q) => (q && q.endsWith('…') && q.length > 24 ? `${q.slice(0, -1).replace(/\s+\S*$/, '').replace(/[\s,;:.-]+$/, '')}…` : q);
434
+
435
+ /**
436
+ * JavaScript/TypeScript template text with each value as a «placeholder» (the spec's form, as for Swift and C):
437
+ * `Wrote ${opts.out}.` -> `Wrote «opts.out».`. Null when it is not one whole template. Long text ends in "…".
438
+ */
439
+ function templateWithValues(lit, n = 70) {
440
+ const t = String(lit).trim();
441
+ if (!t.startsWith('`')) return null;
442
+ let out = '';
443
+ for (let i = 1; i < t.length; i++) {
444
+ const c = t[i];
445
+ if (c === '\\') { out += t[i + 1] === '`' ? '`' : t[i + 1] === '$' ? '$' : c + (t[i + 1] ?? ''); i++; continue; }
446
+ if (c === '`') return i === t.length - 1 ? (out.length > n ? wholeWords(`${out.slice(0, n - 1).trimEnd()}…`) : out) : null;
447
+ if (c === '$' && t[i + 1] === '{') {
448
+ let d = 0, j = i + 1;
449
+ for (; j < t.length; j++) { if (t[j] === '{') d++; else if (t[j] === '}' && --d === 0) break; }
450
+ // (A value worked out inside the hole, `${a ? `x` : ''}`, is shown as «…»: only a name or a field is spelled.)
451
+ const hole = t.slice(i + 2, j).trim();
452
+ out += /^[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)*$/.test(hole) ? `«${hole}»` : '«…»'; i = j; continue;
453
+ }
454
+ out += c;
455
+ }
456
+ return null;
457
+ }
458
+
459
+ /** What a message call writes, from its first argument: its text, a named value, or the result of a call. */
460
+ function messageWhat(args) {
461
+ const t = String(args ?? '');
462
+ let depth = 0, end = 0, q = null;
463
+ for (; end < t.length; end++) {
464
+ const c = t[end];
465
+ if (q) { if (c === '\\') { end++; continue; } if (c === q) q = null; continue; }
466
+ if (c === '"' || c === "'" || c === '`') { q = c; continue; }
467
+ if ('([{'.includes(c)) depth++;
468
+ else if (')]}'.includes(c)) { if (depth === 0) break; depth--; }
469
+ else if (c === ',' && depth === 0) break;
470
+ }
471
+ let a = t.slice(0, end).trim();
472
+ if (!a) return null;
473
+ const more = t[end] === ',';
474
+ if (LANG === 'python') a = a.replace(/^[fFrR]{1,2}(?=["'])/, '');
475
+ if (/^["'`]/.test(a)) {
476
+ // (Python f-string holes stay as written, `{name}`; a JavaScript template's values become «placeholders».)
477
+ let text = a.startsWith('`') ? templateWithValues(a, 80) : wholeWords(firstText(a, 80));
478
+ // printf-style holes filled by the values after it (`"Starting job %s", job_id`) are shown as "…".
479
+ if (text && more) text = text.replace(/%[-+ #0-9.]*[sdifrxXeEgGcuo]|\{\}/g, '…');
480
+ return text && /\w/.test(text) ? `"${text}"${more && !/…/.test(text) ? ', and more' : ''}` : null;
481
+ }
482
+ const tail = more ? ', and more' : '';
483
+ if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(a)) return `${possessiveWords(a)}${tail}`;
484
+ const c = callee(a);
485
+ if (c && closeOf(a, a.indexOf('(')) === a.length - 1) return `the result of ${callWords(c, a)}${tail}`;
486
+ return null;
487
+ }
363
488
  function firstArgs(text) {
364
489
  const open = text.indexOf('(');
365
490
  return open >= 0 ? text.slice(open + 1, open + 120) : '';
@@ -405,7 +530,7 @@ function sayValue(expr) {
405
530
  if (/^new\s/.test(e)) return `a new ${c.split('.').pop()}`;
406
531
  // Swift makes a value by calling its type: Loan(title: t) is a new Loan (so does C++: std::string(s)).
407
532
  if ((LANG === 'swift' || LANG === 'cpp') && /^[A-Z]\w*$/.test(c) && !/^[A-Z][A-Z0-9_]+$/.test(c) && !C_STYLE_FUNCTION.test(c)) return `a new ${c}`;
408
- return `the result of ${lastWords(c)}`;
533
+ return `the result of ${callWords(c, e)}`;
409
534
  }
410
535
  if (LANG === 'swift' && /^[A-Za-z_][\w.]*\.count$/.test(e)) return `how many ${possessiveWords(e.replace(/\.count$/, ''))}`;
411
536
  // A path keeps its owner: `callback.call` is "the callback's call", not "call"; `Boolean.TYPE` stays as written.
@@ -495,7 +620,36 @@ function sayCommon(value) {
495
620
  if ((m = e.match(/^new\s*\(\s*(?:[\w]+\.)?([A-Z]\w*)\s*\)$/))) return `a new ${m[1]}`;
496
621
  if ((m = e.match(/^&([A-Z]\w*)$/))) return `a new ${m[1]}`;
497
622
  if ((m = e.match(/^[\w.]+\.(?:get|get_or_404|find|Find|findById|find_by_id)\(\s*([A-Z]\w*)\s*,\s*([\w.]+)\s*\)$/))) return `the ${m[1]} with ${lastSeg(m[2])}`;
498
- if ((m = e.match(/^([\w.]+)\.get\(\s*([A-Za-z_][\w.]*)\s*[,)]/)) || (m = e.match(/^([\w.]+)\[\s*([A-Za-z_][\w.]*)\s*\]$/))) return `the ${lastSeg(m[2])} entry in ${possessiveWords(m[1])}`;
623
+ // (A key that is another value's field keeps its owner: `touched.get(f.id)` is "the entry for f's id in touched".)
624
+ if ((m = e.match(/^([\w.]+)\.get\(\s*([A-Za-z_][\w.]*)\s*[,)]/)) || (m = e.match(/^([\w.]+)\[\s*([A-Za-z_][\w.]*)\s*\]$/))) return /\./.test(m[2]) && !/^(?:self|this)\./.test(m[2]) ? `the entry for ${possessiveWords(m[2])} in ${possessiveWords(m[1])}` : `the ${lastSeg(m[2])} entry in ${possessiveWords(m[1])}`;
625
+ // Everyday Python calls, said by what they give back (only when what they are given is a name).
626
+ if (LANG === 'python') {
627
+ const plain = (x) => (/^[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*$/.test(String(x).trim()) ? possessiveWords(String(x).trim()) : null);
628
+ let mm;
629
+ // A class called like a function makes a new object: `FontDict()` is a new FontDict.
630
+ if ((mm = e.match(/^([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\(\s*\)$/))) return `a new ${mm[1]}`;
631
+ if ((mm = e.match(/^(list|tuple|set|frozenset|sorted|reversed)\(\s*([^(),]+?)\s*\)$/)) && plain(mm[2])) return { list: `${plain(mm[2])}, as a list`, tuple: `${plain(mm[2])}, as a tuple`, set: `the different values in ${plain(mm[2])}`, frozenset: `the different values in ${plain(mm[2])}`, sorted: `${plain(mm[2])}, sorted`, reversed: `${plain(mm[2])}, in reverse order` }[mm[1]];
632
+ if ((mm = e.match(/^([\w.]+)\.index\(\s*([^(),]+?)\s*\)$/)) && plain(mm[1]) && plain(mm[2])) return `the position of ${plain(mm[2])} in ${plain(mm[1])}`;
633
+ }
634
+ // Everyday JavaScript and TypeScript calls, said by what they give back (only when what they are given is a name).
635
+ if (LANG === 'typescript' || LANG === 'javascript') {
636
+ const plain = (x) => (/^[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)*$/.test(String(x).trim()) ? possessiveWords(String(x).trim().replace(/\?\./g, '.')) : null);
637
+ const one = (re) => { const mm = e.match(re); return mm ? plain(mm[1]) : null; };
638
+ let w;
639
+ if ((w = one(/^Object\.keys\(\s*([^(),]+?)\s*\)$/))) return `the keys of ${w}`;
640
+ if ((w = one(/^Object\.values\(\s*([^(),]+?)\s*\)$/))) return `the values in ${w}`;
641
+ if ((w = one(/^Object\.entries\(\s*([^(),]+?)\s*\)$/))) return `each key and value in ${w}`;
642
+ if ((w = one(/^Date\.parse\(\s*([^(),]+?)\s*\)$/))) return `the time written in ${w}`;
643
+ if ((w = one(/^Array\.from\(\s*([^(),]+?)\s*\)$/))) return `a list made from ${w}`;
644
+ if ((m = e.match(/^([A-Z][\w$]*)\.from\(\s*([^(),]+?)\s*\)$/)) && plain(m[2])) return `a ${m[1]} made from ${plain(m[2])}`;
645
+ if ((m = e.match(/^([\w$.]+)\.exec\(\s*([^(),]+?)\s*\)$/)) && plain(m[1]) && plain(m[2])) return `the first match of ${plain(m[1])} in ${plain(m[2])}`;
646
+ if ((m = e.match(/^([A-Z][\w$]*)\.parse\(\s*([^(),]+?)\s*\)$/)) && plain(m[2]) && m[1] !== 'JSON' && m[1] !== 'Date') return `${plain(m[2])}, checked and read by ${m[1]}`;
647
+ if ((m = e.match(/^Math\.(max|min)\(\s*([^()]+?)\s*\)$/))) {
648
+ const xs = splitTopArgs(m[2]).map(plain);
649
+ if (xs.length >= 2 && xs.every(Boolean)) return `the ${m[1] === 'max' ? 'largest' : 'smallest'} of ${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`;
650
+ }
651
+ if ((m = e.match(/^Math\.(round|floor|ceil|abs|trunc)\(\s*([^(),]+?)\s*\)$/)) && plain(m[2])) return { round: `${plain(m[2])} rounded`, floor: `${plain(m[2])} rounded down`, ceil: `${plain(m[2])} rounded up`, abs: `the absolute value of ${plain(m[2])}`, trunc: `${plain(m[2])} without its fraction` }[m[1]];
652
+ }
499
653
  const wholeCall = (() => { const c = e.match(/^(?:new\s+)?[\w$.]+(?:<[^()]*?>)?\s*\(/); return !!c && closeOf(e, c[0].length - 1) === e.length - 1; })();
500
654
  if (/["'`]\s*\+|\+\s*["'`]/.test(e) && !/[<>=!&|]/.test(e) && !wholeCall) return 'text built from its parts';
501
655
  // PHP joins text with ` . ` (spaced when PHP is read): `$a . ':' . $b`.
@@ -503,8 +657,18 @@ function sayCommon(value) {
503
657
  if ((m = e.match(/^[A-Za-z_][\w.]*(\s*,\s*[A-Za-z_][\w.]*)+$/))) return e.split(/\s*,\s*/).map(lastSeg).join(' and ');
504
658
  // (`make([]string, len(m))` has len(m) items, each the empty value; only `make([]T, 0…)` is empty.)
505
659
  if ((m = e.match(/^make\(\s*(\[\]|map\[)/))) { const a = splitTopArgs(e.slice(e.indexOf('(') + 1, -1)); if (m[1] === '[]' && a.length > 1 && !/^0$/.test(a[1].trim())) return null; return m[1] === '[]' ? 'an empty list' : 'an empty lookup table'; }
660
+ // A JavaScript template or a Python f-string whose values are plain names: the text kept exactly, each value a
661
+ // «placeholder» (as for Swift); anything worked out inside a placeholder stays a summary.
662
+ if (/^`/.test(e) || /^f["']/.test(e)) { const tv = templateTextWithValues(e); if (tv) return tv.length > 90 ? `${tv.slice(0, 88)}…"` : tv; }
663
+ // (A value worked out inside a JavaScript template is shown as «…», as in messages: the text around it is exact.)
664
+ if (/^`/.test(e) && /\$\{/.test(e)) { const q = templateWithValues(e, 80); if (q != null && !/"/.test(q)) return `"${q}"`; }
506
665
  if (/^(?:f|rf|fr)["']/.test(e) || /^`[^`]*\$\{/.test(e) || /^\$"/.test(e) || /^(?:fmt\.Sprintf|String\.format|format!)\(/.test(e)) return 'text built from its parts';
507
- if ((m = e.match(/^([\w.]+)\.get\(\s*["'`]([\w.\-: ]{1,40})["'`]/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
666
+ // (`d.get("k", fallback)`: the fallback is said too, never dropped.)
667
+ if ((m = e.match(/^([\w.]+)\.get\(\s*["'`]([\w.\-: ]{1,40})["'`]\s*\)$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
668
+ if (LANG === 'python' && (m = e.match(/^([\w.]+)\.get\(\s*["'`]([\w.\-: ]{1,40})["'`]\s*,\s*(.+?)\s*\)$/)) && balancedText(m[3])) {
669
+ const d = /^[A-Za-z_][\w.]*$/.test(m[3]) && !/^(?:None|True|False)$/.test(m[3]) ? possessiveWords(m[3]) : sayValue(m[3]);
670
+ if (d && d.length < 40) return `the "${m[2]}" value from ${lastSeg(m[1])}, or ${d} if it has none`;
671
+ }
508
672
  if ((m = e.match(/^([\w.]+)\[\s*["'`]([\w.\-: ]{1,40})["'`]\s*\]$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
509
673
  if (FN_CONTEXT?.language === 'ruby' && (m = e.match(/^@?([\w.]+)\[\s*:(\w+)\s*\]$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
510
674
  if ((m = e.match(/^([\w.]+)\.split\(\s*["'`]([^"'`]{0,10})["'`]/))) return `${lastSeg(m[1])} split at "${m[2]}"`;
@@ -517,6 +681,19 @@ function sayCommon(value) {
517
681
  if (/^(?:dict|Map|HashMap|map)\(\s*\)$|^\{\s*\}$|^new (?:Map|HashMap|Dictionary)(?:<[^()]*>)?\s*(?:\(\s*\))?\s*(?:\{\s*\})?$/.test(e)) return 'an empty lookup table';
518
682
  if (/^(?:list|Array|ArrayList|vec!?)\(?\s*\)?$|^\[\s*\]$|^new (?:ArrayList|List)(?:<[^()]*>)?\s*(?:\(\s*\))?\s*(?:\{\s*\})?$/.test(e)) return 'an empty list';
519
683
  if ((m = e.match(/^len\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:length|size\(\)|Count|count\(\)|len\(\))$/))) return `how many ${lastSeg(m[1])}`;
684
+ // Python `set()` / JavaScript `new Set()`: an empty set (of different values).
685
+ if (/^(?:set|frozenset)\(\s*\)$|^new Set(?:<[^()]*>)?\(\s*\)$/.test(e)) return 'an empty set';
686
+ // A list written out of plain names, numbers, and short texts: `[a, b]` "a list of a and b".
687
+ if ((m = e.match(/^\[\s*(.+?)\s*,?\s*\]$/)) && !/\bfor\b/.test(m[1])) {
688
+ const items = splitTopArgs(m[1]).map((x) => x.trim());
689
+ const said = items.map((x) => (/^[A-Za-z_][\w.]*$/.test(x) && !/^(?:None|null|undefined|True|False|true|false|self|this)$/.test(x) ? possessiveWords(x) : /^-?\d+(?:\.\d+)?$/.test(x) ? x : /^(["'])[\w .:/-]{0,24}\1$/.test(x) ? `"${x.slice(1, -1)}"` : null));
690
+ if (items.length && items.length <= 4 && said.every(Boolean)) return items.length === 1 ? `a list with only ${said[0]}` : `a list of ${listWords(said)}`;
691
+ }
692
+ // Python slices and the last item: `xs[1:]` "xs without the first 1", `xs[:3]` "the first 3 of xs", `xs[-1]`.
693
+ if (LANG === 'python' && (m = e.match(/^([A-Za-z_][\w.]*)\[\s*(-?\d+)?\s*(:)?\s*(-?\d+)?\s*\]$/)) && (m[3] || m[2] === '-1')) {
694
+ const t = sliceWords(m[3] ? m[2] : undefined, m[3] ? m[4] : undefined, m[3] ? null : m[2]);
695
+ if (t) return t.replace('{x}', possessiveWords(m[1]));
696
+ }
520
697
  return null;
521
698
  }
522
699
  /** `if (a) b else c` / `if a { b } else { c }` / `if a then b else c end` as { cond, yes, no }; null otherwise. */
@@ -993,7 +1170,8 @@ function responseOf(head) {
993
1170
  // Gin / Echo: c.JSON(http.StatusOK, user), c.String(200, "ok")
994
1171
  if ((m = expr.match(/^c\s*\.\s*(JSON|IndentedJSON|String|XML|YAML)\s*\((.*)\)$/))) { const [st, body] = callArgs(m[2]); const status = statusOf(st); if (status && status >= 300) return null; return sentStep(payloadWords(body), status === 200 ? null : status); }
995
1172
  // ASP.NET: Ok(x), Created(uri, x), CreatedAtAction(name, routeValues, x), Accepted(x), NoContent()
996
- if (/^return\b/.test(head) && (m = expr.match(/^(Ok|Accepted|Created|CreatedAtAction|CreatedAtRoute|NoContent|Json)\s*\((.*)\)$/))) {
1173
+ // (Rust's `Ok(x)` is a result that worked, not an HTTP answer.)
1174
+ if (/^return\b/.test(head) && LANG !== 'rust' && (m = expr.match(/^(Ok|Accepted|Created|CreatedAtAction|CreatedAtRoute|NoContent|Json)\s*\((.*)\)$/))) {
997
1175
  const args = callArgs(m[2]);
998
1176
  const status = { Ok: null, Json: null, Accepted: 202, Created: 201, CreatedAtAction: 201, CreatedAtRoute: 201, NoContent: 204 }[m[1]];
999
1177
  return sentStep(payloadWords(args.at(-1)), status);
@@ -1056,6 +1234,39 @@ function quotedBody(lit) {
1056
1234
  return t.slice(1, -1);
1057
1235
  }
1058
1236
  /** Swift: `"Bearer \(token)"` -> `"Bearer «token»"`. Null when the literal is not one plain "…" text. */
1237
+ const PLAIN_PLACEHOLDER = /^[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*|\[\d+\])*(?:\(\))?$/;
1238
+ /** `` `@scope/x@${version}` `` -> `"@scope/x@«version»"`; f"{n:>3} items" -> `"«n as {:>3}» items"`; null when a value
1239
+ * inside is worked out (an operator, a call with arguments) or the literal is not one whole piece of text. */
1240
+ export function templateTextWithValues(lit) {
1241
+ const t = String(lit).trim();
1242
+ const js = t[0] === '`';
1243
+ if (!js && !/^f(["'])/.test(t)) return null;
1244
+ const q = js ? '`' : t[1];
1245
+ if (!js && t.slice(1, 4) === q.repeat(3)) return null;
1246
+ let out = '', i = js ? 1 : 2, any = false;
1247
+ for (; i < t.length; i++) {
1248
+ const c = t[i];
1249
+ if (c === q) break;
1250
+ if (c === '\\') { out += c + (t[i + 1] ?? ''); i++; continue; }
1251
+ if (js ? c === '$' && t[i + 1] === '{' : c === '{') {
1252
+ if (!js && t[i + 1] === '{') { out += '{'; i++; continue; }
1253
+ const open = js ? i + 1 : i;
1254
+ const close = t.indexOf('}', open);
1255
+ if (close < 0) return null;
1256
+ let inner = t.slice(open + 1, close).trim(), spec = '';
1257
+ if (!js) { const m = /^([^:!]+?)\s*((?:![rsa])?(?::[^{}]*)?)$/.exec(inner); if (!m) return null; inner = m[1].trim(); spec = m[2]; }
1258
+ if (!PLAIN_PLACEHOLDER.test(inner)) return null;
1259
+ out += spec ? `«${inner} as {${spec}}»` : `«${inner}»`;
1260
+ any = true;
1261
+ i = close;
1262
+ continue;
1263
+ }
1264
+ if (!js && c === '}' && t[i + 1] === '}') { out += '}'; i++; continue; }
1265
+ if (c === '"') { out += '\\"'; continue; }
1266
+ out += c;
1267
+ }
1268
+ return any && i === t.length - 1 ? `"${out}"` : null;
1269
+ }
1059
1270
  export function swiftTextWithValues(lit) {
1060
1271
  const t = String(lit).trim();
1061
1272
  if (!/^"/.test(t) || /^"""/.test(t)) return null;
@@ -1215,13 +1426,104 @@ const stripQuotedText = (s) => String(s).replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g
1215
1426
  // Words that start a block or a statement: "Calls unsafe" / "Calls using" / "Calls foreach" would name a function
1216
1427
  // that does not exist, so such a step is shown as its code instead.
1217
1428
  const NOT_CALLED = /^Calls (unsafe|using|foreach|for|while|if|else|return|lock|fixed|checked|unchecked|try|do|switch|match|loop|static|const|let|var|val|mut|typeof|sizeof)$/;
1429
+ /**
1430
+ * TypeScript's types say nothing about what a statement does, so they are set aside before it is read (the step
1431
+ * still shows the original code): `(request.body ?? {}) as { a?: string }` is `request.body ?? {}`, `ctx.repo!` is
1432
+ * `ctx.repo`, and `const reviews: Record<string, 'a' | 'b'> = {}` is `const reviews = {}`.
1433
+ */
1434
+ export function stripTsTypes(text) {
1435
+ let s = String(text);
1436
+ // A type after "as" or a declaration's ":" runs to the first , ; ) ] } = at depth 0 (or the end).
1437
+ const typeEnd = (from, stops) => {
1438
+ let depth = 0, q = null;
1439
+ for (let i = from; i < s.length; i++) {
1440
+ const c = s[i];
1441
+ if (q) { if (c === q && s[i - 1] !== '\\') q = null; continue; }
1442
+ if (c === "'" || c === '"' || c === '`') { q = c; continue; }
1443
+ if (c === '<' || c === '{' || c === '(' || c === '[') depth++;
1444
+ else if ((c === '>' && s[i - 1] !== '=') || c === '}' || c === ')' || c === ']') { if (depth === 0) return i; depth--; }
1445
+ else if (depth === 0 && stops.includes(c)) return i;
1446
+ }
1447
+ return s.length;
1448
+ };
1449
+ // `x as Type` (not inside text).
1450
+ for (let guard = 0; guard < 20; guard++) {
1451
+ const re = /\s+as\s+(?=[A-Za-z_${(\['"])/g;
1452
+ let m;
1453
+ // (Not inside text: an even number of each quote mark before it.)
1454
+ while ((m = re.exec(s)) && ['"', "'", '`'].some((q) => (s.slice(0, m.index).split(q).length - 1) % 2 === 1));
1455
+ if (!m || /\bimport\b|\bexport\b/.test(s.slice(0, m.index))) break;
1456
+ const end = typeEnd(m.index + m[0].length, ',;=');
1457
+ s = s.slice(0, m.index) + s.slice(end);
1458
+ }
1459
+ // `const name: Type = value` -> `const name = value`.
1460
+ const decl = /^(\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_$][\w$]*)\s*:\s*/.exec(s);
1461
+ if (decl) { const end = typeEnd(decl[0].length, '=;'); if (s[end] === '=') s = `${decl[1]} ${s.slice(end)}`; }
1462
+ // A non-null assertion `x!` (never `!=` or `!x`), and parentheses left around a plain name or member.
1463
+ s = s.replace(/([\w$\])])!(?![=\w(])/g, '$1').replace(/\(([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\)(?=\.)/g, '$1');
1464
+ // Parentheses that only held the value for its type (`= (request.body ?? {});`) are not needed once it is gone.
1465
+ const wrapped = /^(\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*|\s*return\s+)\(([\s\S]*)\)(\s*;?\s*)$/.exec(s);
1466
+ if (wrapped) {
1467
+ let depth = 0, whole = true;
1468
+ for (let i = 0; i < wrapped[2].length; i++) { const c = wrapped[2][i]; if (c === '(') depth++; else if (c === ')') { if (depth === 0) { whole = false; break; } depth--; } }
1469
+ if (whole && depth === 0) s = `${wrapped[1]}${wrapped[2]}${wrapped[3]}`;
1470
+ }
1471
+ return s;
1472
+ }
1473
+
1218
1474
  export function classifyStatement(raw, opts) {
1475
+ // An event handler whose body is one expression: `child.on('close', (c) => resolve(c))` -> Whenever "close" happens,
1476
+ // it calls resolve. (A handler with a block body is read with its steps, elsewhere.)
1477
+ if (LANG === 'typescript' || LANG === 'javascript') {
1478
+ const ev = /^\s*[\w$.]+\.(?:on|once|addEventListener|addListener)\(\s*(['"`])([\w:.\-]+)\1\s*,\s*(?:async\s*)?(?:\([^()]*\)|[\w$]+)\s*=>\s*(?!\{)([\s\S]+?)\)\s*;?\s*$/.exec(String(raw));
1479
+ if (ev && balancedText(ev[3])) {
1480
+ const body = ev[3].trim();
1481
+ const c = callee(body);
1482
+ if (c && closeOf(body, body.indexOf('(')) === body.length - 1) return { kind: 'call', says: `Whenever "${ev[2]}" happens, it calls ${callWords(c, body)}`, code: clip(String(raw).replace(/\s+/g, ' ').trim(), 90), callee: c, expr: statementExpr(raw) };
1483
+ }
1484
+ }
1485
+ // Two loops on one line (`for (const r of rows) for (const f of r.files) {`): each, in order, never one mixed loop.
1486
+ if (LANG === 'typescript' || LANG === 'javascript') {
1487
+ const t = String(raw).trim();
1488
+ const m = /^for\s*\(/.exec(t);
1489
+ if (m) {
1490
+ let depth = 0, close = -1;
1491
+ for (let i = t.indexOf('('); i < t.length; i++) { if (t[i] === '(') depth++; else if (t[i] === ')' && --depth === 0) { close = i; break; } }
1492
+ const rest = close > 0 ? t.slice(close + 1).trim() : '';
1493
+ if (/^for\s*\(/.test(rest)) {
1494
+ const outer = classifyStatement(`${t.slice(0, close + 1)} {`, opts);
1495
+ const inner = classifyStatement(rest.replace(/\{?\s*$/, ' {'), opts);
1496
+ if (outer.kind === 'loop' && inner.kind === 'loop') {
1497
+ return { ...outer, says: `${outer.says.replace(/:$/, '')}, and in each, ${inner.says.charAt(0).toLowerCase()}${inner.says.slice(1)}`, code: clip(t.replace(/\s+/g, ' '), 90), nestedLoop: true };
1498
+ }
1499
+ }
1500
+ }
1501
+ }
1502
+ // TypeScript: read the statement without its types; show the code as written.
1503
+ if (LANG === 'typescript' && /\sas\s|[\w$\])]!(?![=\w(])|^\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*:/.test(String(raw))) {
1504
+ const plain = stripTsTypes(raw);
1505
+ if (plain !== String(raw)) {
1506
+ const r = classifyStatement(plain, opts);
1507
+ if (r.kind !== 'other') return { ...r, code: clip(String(raw).replace(/\s+/g, ' ').trim(), 90) };
1508
+ }
1509
+ }
1219
1510
  // Rust `unsafe { f(x) }` (and `return unsafe { … }`) with one expression inside is that expression.
1220
1511
  const un = LANG === 'rust' ? String(raw).trim().match(/^(return\s+)?unsafe\s*\{\s*([^{};]+?)\s*;?\s*\}\s*;?$/s) : null;
1221
1512
  if (un) { const r = classifyStatement(`${un[1] ?? ''}${un[2]}`, opts); return { ...r, code: clip(String(raw).replace(/\s+/g, ' ').trim(), 90) }; }
1222
1513
  let r = classifyWords(raw, opts);
1223
1514
  const nc = r.kind === 'call' && String(r.says || '').match(NOT_CALLED);
1224
1515
  if (nc && new RegExp(`^(?:#\\w+\\s+)?${nc[1]}\\b(?![.(?!])`).test(String(raw).trim().replace(/^#.*\n\s*/, ''))) r = { kind: 'other', says: clip(String(raw).trim(), 70), code: clip(String(raw).replace(/\s+/g, ' ').trim(), 90) };
1516
+ // Rust `let y = f(x)?;`: what `f(x)` would be, and the `?` said: it stops here (passing on the error) if that fails.
1517
+ let rq;
1518
+ if (LANG === 'rust' && r.kind === 'set' && /^Works out [\w ]+$/.test(String(r.says)) && (rq = /^(\s*let\s+(?:mut\s+)?\w+\s*(?::[^=]+)?=\s*)(.+?)\?\s*;?\s*$/.exec(String(raw))) && !/\?/.test(rq[2])) {
1519
+ const inner = classifyWords(`${rq[1]}${rq[2]};`, opts);
1520
+ if (inner.kind === 'set' && /^(?:Works out [\w ]+ from |Sets )/.test(String(inner.says)) && !/, /.test(String(inner.says))) r = { ...r, says: `${inner.says}, and stops here if that fails`, callee: inner.callee };
1521
+ }
1522
+ // `file = self.file` / `const name = this.name`: "Sets file to self.file" (the owner kept, so the two are told apart).
1523
+ let so;
1524
+ if (r.kind === 'set' && (so = /^Sets (.+) to (.+)$/.exec(String(r.says))) && so[1] === so[2] && (so = /^\s*(?:(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*=\s*(self|this)\.([A-Za-z_$][\w$]*)\s*;?\s*$/.exec(String(raw))) && so[1] === so[3]) {
1525
+ r = { ...r, says: `Sets ${words(so[1])} to ${so[2]}.${so[3]}` };
1526
+ }
1225
1527
  if (!r.expr) r.expr = statementExpr(raw);
1226
1528
  return r;
1227
1529
  }
@@ -1384,6 +1686,8 @@ function classifyWords(raw, { inner = 0 } = {}) {
1384
1686
  return { kind: 'fail', says: `Fails${said ? ` with ${said}` : ''}${msg ? `: "${msg}"` : ''}`, code, ...(name ? { error: name } : {}), ...(msg ? { message: msg } : {}) };
1385
1687
  }
1386
1688
  // An HTTP error response (4xx/5xx) is a Stop: the request is refused, with a status and a message.
1689
+ // A Python import inside a function: "Loads the json module", "Loads a and b from the x.y module".
1690
+ if (LANG === 'python' && /^(?:from|import)\s/.test(head)) { const said = pythonImportSays(head); if (said) return { kind: 'set', says: said, code }; }
1387
1691
  // Loading code at run time: const { a } = await import('./x') -> "Loads a from ./x".
1388
1692
  let dyn;
1389
1693
  if ((dyn = head.match(/^(?:const|let|var)\s*(?:\{([^}]*)\}|([A-Za-z_$][\w$]*))\s*=\s*(?:await\s+)?(?:import|require)\(\s*['"`]([^'"`]+)['"`]\s*\)\s*;?$/))) {
@@ -1460,6 +1764,36 @@ function classifyWords(raw, { inner = 0 } = {}) {
1460
1764
  }
1461
1765
  // A C-style loop with no counter of its own: `for (; pos < limit; i++)` / `for (;;)`.
1462
1766
  if ((m = head.match(/^for\s*\(\s*[^;]*;\s*([^;]*?)\s*;[^)]*\)\s*\{?\s*$/))) return { kind: 'loop', says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
1767
+ // Rust `for x in xs.iter() {` / `for (k, v) in map.iter()` / `for i in 0..n` / `for c in s.chars()`.
1768
+ if (LANG === 'rust' && (m = head.match(/^for\s+(\(\s*\w+\s*,\s*\w+\s*\)|\w+)\s+in\s+(.+?)\s*\{?\s*$/))) {
1769
+ const it = m[2].replace(/^&(?:mut\s+)?/, '');
1770
+ const pair = /^\(\s*(\w+)\s*,\s*(\w+)\s*\)$/.exec(m[1]);
1771
+ const who = pair ? `${words(pair[1])} and ${words(pair[2])}` : words(m[1]);
1772
+ let k;
1773
+ const r = !pair && rangeWords(it);
1774
+ if (r && m[1] !== '_') return { kind: 'loop', says: `Counts ${who} ${r.says}${innerNote}`, code };
1775
+ if ((k = it.match(/^([A-Za-z_][\w.]*?)(?:\.(?:iter|iter_mut|into_iter)\(\s*\))?$/)) && m[1] !== '_') return { kind: 'loop', says: `For each ${who} in ${possessiveWords(k[1])}${innerNote}`, code };
1776
+ if ((k = it.match(/^([A-Za-z_][\w.]*)\.(chars|lines|bytes|keys|values)\(\s*\)$/)) && m[1] !== '_') return { kind: 'loop', says: `For each ${who} in the ${{ chars: 'characters', lines: 'lines', bytes: 'bytes', keys: 'keys', values: 'values' }[k[2]]} of ${possessiveWords(k[1])}${innerNote}`, code };
1777
+ }
1778
+ // Python counting loops: `for i in range(n)`, `range(a, b)`, `range(len(xs))`, and `for i, x in enumerate(xs)`.
1779
+ if (LANG === 'python' && (m = head.match(/^for\s+(\w+)\s+in\s+range\((.*)\)\s*:$/))) { const r = pythonRangeWords(m[1], m[2]); if (r) return { kind: 'loop', says: `${r}${innerNote}`, code }; }
1780
+ if (LANG === 'python' && (m = head.match(/^for\s+\(?\s*(\w+)\s*,\s*(\w+)\s*\)?\s+in\s+enumerate\(\s*([A-Za-z_][\w.]*)\s*\)\s*:$/)) && m[1] !== '_') {
1781
+ return { kind: 'loop', says: `For each ${words(m[2])} in ${possessiveWords(m[3])}, with its position ${words(m[1])} (from 0)${innerNote}`, code };
1782
+ }
1783
+ // Python `for x in <collection>:` where the collection is a call: what the call gives, never a cut-off "values(".
1784
+ if (LANG === 'python' && (m = head.match(/^for\s+(\w+)\s+in\s+(.+?)\s*:$/)) && !/^range\(|^enumerate\(/.test(m[2])) {
1785
+ const it = m[2];
1786
+ let w = null, k;
1787
+ if ((k = it.match(/^([A-Za-z_][\w.]*)\.(values|keys)\(\s*\)$/))) w = `the ${k[2]} of ${possessiveWords(k[1])}`;
1788
+ else if ((k = it.match(/^sorted\(\s*([A-Za-z_][\w.]*)\s*\)$/))) w = `${possessiveWords(k[1])}, sorted`;
1789
+ else if ((k = it.match(/^reversed\(\s*([A-Za-z_][\w.]*)\s*\)$/))) w = `${possessiveWords(k[1])}, in reverse order`;
1790
+ else if (/^[A-Za-z_]/.test(it) && /\)$/.test(it)) {
1791
+ // The outermost call: the last `name(` whose bracket closes at the very end (`text.lower().split()` is split).
1792
+ const last = [...it.matchAll(/([A-Za-z_]\w*)\(/g)].reverse().find((x) => closeOf(it, x.index + x[0].length - 1) === it.length - 1);
1793
+ if (last && !/^(?:zip|map|filter|iter|list|tuple|set)$/.test(last[1]) && (last.index === 0 || it[last.index - 1] === '.') && balancedText(it)) w = `the result of ${words(last[1])}`;
1794
+ }
1795
+ if (w) return { kind: 'loop', says: `For each ${words(m[1])} in ${w}${innerNote}`, code };
1796
+ }
1463
1797
  // Pairs unpacked in a loop: for (const [key, value] of entries) / for key, value in items.items() / foreach ($a as $k => $v)
1464
1798
  if ((m = head.match(/^for\b\s*\(?\s*(?:(?:const|let|var|val)\s+)?&?[\[{(]?\s*([\w$]+)\s*,\s*([\w$]+)\s*[\]})]?\s+(?:of|in)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/))) {
1465
1799
  const src = stripTail(m[3]).replace(/\($/, '()').replace(/^Object\.entries\((.+)\)$/, '$1').replace(/\.(?:items|entries|enumerated)\(\)$/, '');
@@ -1477,6 +1811,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
1477
1811
  if ((m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/))) return { kind: 'loop', says: `For each item in ${words(m[1].split('.').pop())}${innerNote}`, code };
1478
1812
  // Go `for {` repeats until something inside leaves the loop (or the function).
1479
1813
  if (/^for\s*\{$/.test(head)) return { kind: 'loop', says: `Repeats until something inside leaves the loop${innerNote}`, code };
1814
+ if (LANG === 'rust' && /^loop\s*\{?\s*$/.test(head)) return { kind: 'loop', says: `Repeats until a step inside stops it${innerNote}`, code };
1480
1815
  if ((m = head.match(/^(?:while|until|loop)\b\s*\(?(.*?)\)?\s*(?:\{|:|do)?\s*$/))) return { kind: 'loop', says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
1481
1816
  // Branches
1482
1817
  // Go: `if err := open(); err != nil` -> "If open fails"; `if v, ok := m[k]; ok` -> "If k is in m".
@@ -1501,7 +1836,8 @@ function classifyWords(raw, { inner = 0 } = {}) {
1501
1836
  }
1502
1837
  if ((m = head.match(/^(?:if|elif|else\s+if|unless|when)\b\s*(.*?)\s*(?:\{|:|then)?\s*$/))) { const cond = sayCodeCondition(m[1]); return { kind: 'branch', says: `If ${/^unless\b/.test(head) ? 'not: ' : ''}${cond}${innerNote}`, cond: m[1].replace(/^\((.*)\)$/, '$1'), code, negate: /^unless\b/.test(head) }; }
1503
1838
  if (/^switch\s*(?:true\s*)?\{$/.test(head)) return { kind: 'branch', says: `Checks these cases in order${innerNote}`, code };
1504
- if ((m = head.match(/^(?:switch|match|case|select)\b\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/))) return { kind: 'branch', says: `Chooses by ${words(clip(m[1], 40)) || 'value'}${innerNote}`, code };
1839
+ // (`match = re.match(x)` / `select.x` use the word as a name: a statement word is never followed by = . , or ).)
1840
+ if ((m = head.match(/^(?:switch|match|case|select)\b(?!\s*(?:=(?!=)|\.|,|\)|\]|[-+*/%]=))\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/))) return { kind: 'branch', says: `Chooses by ${words(clip(m[1], 40)) || 'value'}${innerNote}`, code };
1505
1841
  if (/^(?:try|begin)\b/.test(head)) return { kind: 'try', says: `Tries the next steps and handles any error${innerNote}`, code };
1506
1842
  if ((m = head.match(/^assert\b\s*(.*?)\s*;?$/))) return { kind: 'check', says: `Checks that ${m[1] ? sayCodeCondition(m[1].replace(/,\s*["'].*$/, '')) : 'a condition holds'}`, code };
1507
1843
  if ((m = head.match(/^assert(?:_\w+|That|Equals|True|False|NotNull|Null)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
@@ -1538,6 +1874,9 @@ function classifyWords(raw, { inner = 0 } = {}) {
1538
1874
  if (((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) && !(closeOf(text, text.indexOf("{")) > 0 && text.slice(closeOf(text, text.indexOf("{")) + 1).trim())) return { kind: 'return', says: `Returns a new ${words(m[1])}`, code };
1539
1875
  if ((m = head.match(/^(?:[A-Z]\w*::)+([A-Z]\w*)$/))) return { kind: 'return', says: `Returns ${m[1]}`, code };
1540
1876
  if (/^vec!?\[/.test(head)) return { kind: 'return', says: 'Returns a list', code };
1877
+ // Rust: `loop {` repeats until a step inside stops it; a last `Ok(…)` / `Some(…)` is what the function gives back.
1878
+ if (LANG === 'rust' && /^loop\s*\{?\s*$/.test(head)) return { kind: 'loop', says: `Repeats until a step inside stops it${innerNote}`, code };
1879
+ if (LANG === 'rust' && /^(?:Ok|Some)\s*\(/.test(head) && closeOf(head, head.indexOf('(')) === head.length - 1) { const v = sayValue(head); if (v) return { kind: 'return', says: `Returns ${v}`, code }; }
1541
1880
  // A bare value as a statement is an implicit return (Ruby, Rust, Kotlin/Scala expression bodies).
1542
1881
  // Only where a last value is given back (Ruby, Rust, Kotlin, Scala, Elixir); in Python or JavaScript a bare
1543
1882
  // `self.content` only reads the value.
@@ -1558,7 +1897,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
1558
1897
  if ((m = head.match(/^(?:const|let|var|val)\s+([{[])\s*(.*?)\s*[}\]]\s*(?::\s*[^=]+)?=\s*(.+)$/))) {
1559
1898
  const names = m[2].split(',').map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, '')).filter(Boolean).map(words);
1560
1899
  const value = stripTail(m[3]); const c = callee(value);
1561
- const from = c ? lastWords(c) : (sayValue(value) || words(value.split('.').pop()));
1900
+ const from = c ? callWords(c, value) : (sayValue(value) || words(value.split('.').pop()));
1562
1901
  return { kind: 'set', says: `Takes ${names.slice(0, 4).join(', ')}${names.length > 4 ? ', …' : ''} from ${from}`, code };
1563
1902
  }
1564
1903
  if ((m = head.match(/^(?:var|const)\s*\($/))) return { kind: 'set', says: 'Declares some values', code };
@@ -1575,7 +1914,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
1575
1914
  if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
1576
1915
  // (C++: `Status s = FindTable(…)` calls FindTable; only `Foo f = Foo(…)` makes a new Foo.)
1577
1916
  if (/^new\s/.test(value) || (makesType(c) && (LANG !== 'cpp' || sameType(c, m[1])))) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
1578
- return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
1917
+ return { kind: 'set', says: `Works out ${target} from ${callWords(c, value)}`, code, callee: c };
1579
1918
  }
1580
1919
  const v = value ? sayValue(value) : null;
1581
1920
  return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
@@ -1636,11 +1975,11 @@ function classifyWords(raw, { inner = 0 } = {}) {
1636
1975
  const known = sayCall(c, firstArgs(value));
1637
1976
  if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
1638
1977
  if (/^new\s/.test(value) || (makesType(c) && (LANG !== 'cpp' || sameType(c, declType)))) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
1639
- return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
1978
+ return { kind: 'set', says: `Works out ${target} from ${callWords(c, value)}`, code, callee: c };
1640
1979
  }
1641
1980
  if (!value) return { kind: 'set', says: `Works out ${target}`, code };
1642
1981
  if (m[2] === '+=' || m[2] === '-=') { const what = /^[\w.]+$/.test(value) ? `${value.split('.').filter((p) => !/^(self|this)$/.test(p)).slice(-2).map(words).join(' ')} ` : /^-?\d+(\.\d+)?$/.test(value) ? `${value} ` : ''; return { kind: 'set', says: what ? `${m[2] === '+=' ? 'Adds' : 'Subtracts'} ${what}${m[2] === '+=' ? 'to' : 'from'} ${target}` : `${m[2] === '+=' ? 'Adds to' : 'Subtracts from'} ${target}`, code }; }
1643
- const v = sayValue(value);
1982
+ const v = sayValue(value) ?? sayArithmetic(value);
1644
1983
  return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
1645
1984
  }
1646
1985
  // Calls
@@ -1655,15 +1994,61 @@ function classifyWords(raw, { inner = 0 } = {}) {
1655
1994
  const owner = m[1].split('.').filter((p) => !/^(self|this)$/.test(p));
1656
1995
  const where = owner.length > 1 ? `${words(owner[owner.length - 2])}'s ${words(owner[owner.length - 1])}` : words(owner[0] || m[1]);
1657
1996
  const added = /^new\s+([A-Z]\w*)/.exec(head.slice(head.indexOf('(') + 1))?.[1];
1658
- const open0 = head.indexOf('('), close0 = closeOf(head, open0);
1659
- const argText = close0 > open0 ? head.slice(open0 + 1, close0) : '';
1660
- if (splitTopArgs(argText).length > 1) return { kind: 'call', says: `Adds to ${where}`, code, callee: m[1] };
1661
- return { kind: 'call', says: added ? `Adds a new ${words(added)} to ${where}` : m[2] && /^[A-Za-z_][\w$]*$/.test(m[2]) && m[2] !== 'new' ? `Adds ${words(m[2])} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
1997
+ // The arguments may run over several lines (`out.push({\n kind: …,\n})`): read them from the whole statement.
1998
+ const whole = closeOf(head, head.indexOf('(')) > head.indexOf('(') ? head : text.replace(/\s+/g, ' ');
1999
+ const open0 = whole.indexOf('('), close0 = closeOf(whole, open0);
2000
+ const argText = close0 > open0 ? whole.slice(open0 + 1, close0) : '';
2001
+ const args = argText.trim() ? splitTopArgs(argText) : [];
2002
+ // What is added, in words: an entry and its fields, a text, a value's field, the result of a call, or a name.
2003
+ const addedWhat = (a) => {
2004
+ const t = String(a).trim();
2005
+ if (/^\{[\s\S]*\}$/.test(t)) {
2006
+ // (Its fields are listed only when the statement is short enough for the faithfulness check to see them all.)
2007
+ if (text.split('\n').length > 7) return 'an entry';
2008
+ const parts = splitTopArgs(t.slice(1, -1));
2009
+ const keys = parts.map((p) => (/^\.\.\./.test(p) ? null : (p.match(/^\s*['"]?([A-Za-z_$][\w$]*)['"]?\s*(?::|$|\()/) || [])[1])).filter(Boolean);
2010
+ if (!parts.length) return 'an empty entry';
2011
+ if (!keys.length) return null;
2012
+ return `an entry (${keys.slice(0, 4).map(words).join(', ')}${keys.length > 4 || keys.length < parts.length ? ', …' : ''})`;
2013
+ }
2014
+ if (/^(?:''|""|``)$/.test(t)) return '""';
2015
+ if (t.startsWith('`')) { const q = templateWithValues(t, 60); return q != null ? `"${q}"` : null; }
2016
+ if (/^["']/.test(t)) { const q = wholeWords(firstText(t, 60)); return q ? `"${q}"` : null; }
2017
+ if (/^new\s+[A-Z]\w*/.test(t)) return `a new ${t.match(/^new\s+([A-Z]\w*)/)[1]}`;
2018
+ if (/^[A-Za-z_$][\w$]*$/.test(t)) return words(t);
2019
+ if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(t)) return possessiveWords(t);
2020
+ const c = callee(t);
2021
+ if (c && closeOf(t, t.indexOf('(')) === t.length - 1) return `the result of ${callWords(c, t)}`;
2022
+ return null;
2023
+ };
2024
+ // (Only `push`/`unshift` add every argument: `list.add(index, element)` and `insert(i, x)` put one value at a place.)
2025
+ if (args.length > 1 && !/\.(?:push|unshift)\(/.test(whole)) return { kind: 'call', says: `Adds to ${where}`, code, callee: m[1] };
2026
+ if (args.length > 1) {
2027
+ const ws = args.map(addedWhat);
2028
+ const said = ws.every(Boolean) && args.length <= 3 ? `${ws.slice(0, -1).join(', ')} and ${ws[ws.length - 1]}` : null;
2029
+ return { kind: 'call', says: said ? `Adds ${said} to ${where}` : `Adds several values to ${where}`, code, callee: m[1] };
2030
+ }
2031
+ const one = args.length === 1 ? addedWhat(args[0]) : null;
2032
+ return { kind: 'call', says: added ? `Adds a new ${words(added)} to ${where}` : one ? `Adds ${one} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
1662
2033
  }
1663
2034
  const c = callee(head);
1664
2035
  if (c) {
1665
2036
  const known = sayCall(c, firstArgs(head));
1666
- return { kind: 'call', says: known || `Calls ${lastWords(c)}`, code, callee: c };
2037
+ if (known) return { kind: 'call', says: known, code, callee: c };
2038
+ // One argument that can be named says what the call is given, so two calls to the same function differ:
2039
+ // `cmd.addCommand(rulesCommand())` -> "Calls add command (with the result of rules command)".
2040
+ const o = head.indexOf('('), cl = o >= 0 ? closeOf(head, o) : -1;
2041
+ const only = cl > o && /^\s*;?\s*$/.test(head.slice(cl + 1)) ? splitTopArgs(head.slice(o + 1, cl)) : [];
2042
+ if ((LANG === 'typescript' || LANG === 'javascript' || LANG === 'python') && only.length === 1 && !/^\s*(?:async\s*)?(?:\(|function\b|[A-Za-z_$][\w$]*\s*=>)/.test(only[0]) && !/^(?:exec|eval|compile|__import__|execfile|Function|setTimeout|setInterval)$/.test(c)) {
2043
+ const t = only[0].trim();
2044
+ const w = t.startsWith('`') ? (templateWithValues(t, 60) ? `"${templateWithValues(t, 60)}"` : null)
2045
+ : /^["']/.test(t) ? (wholeWords(firstText(t, 60)) ? `"${wholeWords(firstText(t, 60))}"` : null)
2046
+ : /^[A-Za-z_$][\w$]*$/.test(t) ? words(t)
2047
+ : /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(t) ? possessiveWords(t)
2048
+ : callee(t) && closeOf(t, t.indexOf('(')) === t.length - 1 && !/^new\s/.test(t) ? `the result of ${callWords(callee(t), t)}` : null;
2049
+ if (w && !ENDS_ON_PREPOSITION.test(callWords(c, head))) return { kind: 'call', says: `Calls ${callWords(c, head)} (with ${w})`, code, callee: c };
2050
+ }
2051
+ return { kind: 'call', says: `Calls ${callWords(c, head)}`, code, callee: c };
1667
2052
  }
1668
2053
  if ((m = head.match(/^([a-z_][\w.]*[?!]?)\s+(?![=<>!+\-*/%]|and\b|or\b|if\b|unless\b)(.+)$/)) && !/^(?:if|for|while|return|else|elsif|when|case|def|class|module|end|not|const|let|var|val|new|await|typeof|delete|void|in|of|throw|import|export|from|as|is)$/.test(m[1])) {
1669
2054
  if (/^assert/.test(m[1])) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
@@ -2187,6 +2572,32 @@ export function stepsFrom(statements) {
2187
2572
  for (let i = 0; i < steps.length - 1; i++) asCall(steps, i);
2188
2573
  // A value chosen by if / match / when: each side's last value is what the name is set to (or what is returned).
2189
2574
  for (const st of steps) if (Object.hasOwn(st, 'valueOf')) { const t = st.valueOf; delete st.valueOf; giveValue(st.children, t); giveValue(st.otherwise, t); }
2575
+ // A web route registered in place (`fastify.post('/orders', handle(async (request) => { … }))`) is its own action,
2576
+ // read separately ("When someone calls POST /orders"); here it is one line, not its steps a second time.
2577
+ if (LANG === 'typescript' || LANG === 'javascript') {
2578
+ for (const st of steps) {
2579
+ const r = /^\s*[A-Za-z_$][\w$]*\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,/.exec(String(st.code ?? ''));
2580
+ if (!r || !/^\//.test(r[2])) continue;
2581
+ st.kind = 'call';
2582
+ st.says = `Handles ${r[1] === 'all' ? 'every request to' : r[1].toUpperCase()} ${r[2]} (its steps are in that action)`;
2583
+ delete st.children; delete st.nested; delete st.restates; delete st.value;
2584
+ st.route = { method: r[1].toUpperCase(), path: r[2] };
2585
+ }
2586
+ }
2587
+ // "Calls X with these steps", said by what the call is for (JavaScript, TypeScript): a command-line command
2588
+ // (`program.command('check')…`), a database transaction, progress shown while it works, or the name it registers.
2589
+ if (LANG === 'typescript' || LANG === 'javascript') {
2590
+ for (const st of steps) {
2591
+ const said = /^Calls ([\w ]+) with these steps$/.exec(String(st.says ?? ''));
2592
+ if (!said) continue;
2593
+ const code = String(st.code ?? '');
2594
+ let m;
2595
+ if ((m = /\.command\(\s*(['"`])([\w:.\-]+)(?:\s[^'"`]*)?\1\s*\)/.exec(code))) st.says = `Defines the command "${m[2]}"; when it runs, it does these steps`;
2596
+ else if (/\.transaction\(\s*(?:async\s*)?\(/.test(code)) st.says = 'Does these steps in one database transaction';
2597
+ else if (/\.withProgress\(/.test(code)) st.says = 'Shows progress while it does these steps';
2598
+ else if ((m = /^\s*(?:await\s+)?[\w$.]+\(\s*(['"`])([^'"`$]{1,60})\1\s*,/.exec(code))) st.says = `Calls ${said[1]} ("${m[2]}") with these steps`;
2599
+ }
2600
+ }
2190
2601
  // Every step is kept (anchoring needs all of them); `more` tells a view how many to fold away.
2191
2602
  const more = Math.max(0, steps.length - MAX_STEPS);
2192
2603
  for (const st of steps) if (restates(st)) st.restates = true;