@skillstech/thunderlang 0.5.9 → 0.5.10

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.
package/src/steps.mjs CHANGED
@@ -126,6 +126,17 @@ function sayValue(expr) {
126
126
  return null;
127
127
  }
128
128
 
129
+ /**
130
+ * Simple arithmetic between two names or numbers, used for each side of a choice: `order.total - discount` -> "the
131
+ * order's total minus discount". `+` only with a number (two names joined by `+` may be text put together).
132
+ */
133
+ function sayArithmetic(expr) {
134
+ const ar = String(expr).trim().match(/^([A-Za-z_$][\w$.]*|\d+(?:\.\d+)?)\s*([-+*/])\s*([A-Za-z_$][\w$.]*|\d+(?:\.\d+)?)$/);
135
+ if (!ar || (ar[2] === '+' && !/^\d/.test(ar[1]) && !/^\d/.test(ar[3]))) return null;
136
+ const side = (x) => (/^\d/.test(x) ? x : possessiveWords(x));
137
+ return `${side(ar[1])} ${{ '+': 'plus', '-': 'minus', '*': 'times', '/': 'divided by' }[ar[2]]} ${side(ar[3])}`;
138
+ }
139
+
129
140
  /** Python comprehensions and the builtins that summarize a collection, said as what they produce. */
130
141
  const PY_SUMMARY = [
131
142
  { re: /^any$/, say: (src, cond) => `whether any item in ${src}${cond ? ` where ${cond}` : ''} matches` },
@@ -170,9 +181,13 @@ function sayCommon(value) {
170
181
  const e = String(value).trim().replace(/\s+as\s+[\w.<>\[\]|, ]+$/, '');
171
182
  let m;
172
183
  // cond ? a : b -> "a if cond, otherwise b" (not TypeScript optional types or labels).
173
- const side = (x) => sayValue(x) ?? possessiveWords(x.trim());
184
+ const side = (x) => sayValue(x) ?? sayArithmetic(x) ?? possessiveWords(x.trim());
174
185
  if ((m = e.match(/^(.+?)\s+\?\s+([^:?]+?)\s+:\s+([^:?]+)$/)) && !/^(?:[\w$]+\??\s*:)/.test(e)) return `${side(m[2])} if ${sayCodeCondition(m[1])}, otherwise ${side(m[3])}`;
175
- if ((m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/))) return `${side(m[1])} if ${sayCodeCondition(m[2])}, otherwise ${side(m[3])}`;
186
+ if ((m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/)) && !/^(?:if|unless)\b/.test(e)) return `${side(m[1])} if ${sayCodeCondition(m[2])}, otherwise ${side(m[3])}`;
187
+ // An `if` used as a value, said like a ternary: Kotlin `if (a) b else c`, Rust `if a { b } else { c }`,
188
+ // Ruby `if a then b else c end`.
189
+ const ifValue = ifAsValue(e);
190
+ if (ifValue) return `${side(ifValue.yes)} if ${sayCodeCondition(ifValue.cond)}, otherwise ${side(ifValue.no)}`;
176
191
  if ((m = e.match(/^&?([A-Z]\w*)(?:::new\s*\(|\s*\{)/)) || (m = e.match(/^(?:[\w.]+\.)?([A-Z]\w*)\{/))) return `a new ${m[1]}`;
177
192
  if ((m = e.match(/^new\s*\(\s*(?:[\w]+\.)?([A-Z]\w*)\s*\)$/))) return `a new ${m[1]}`;
178
193
  if ((m = e.match(/^&([A-Z]\w*)$/))) return `a new ${m[1]}`;
@@ -195,6 +210,22 @@ function sayCommon(value) {
195
210
  if ((m = e.match(/^len\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:length|size\(\)|Count|count\(\)|len\(\))$/))) return `how many ${lastSeg(m[1])}`;
196
211
  return null;
197
212
  }
213
+ /** `if (a) b else c` / `if a { b } else { c }` / `if a then b else c end` as { cond, yes, no }; null otherwise. */
214
+ function ifAsValue(e) {
215
+ let m;
216
+ if ((m = e.match(/^if\s*\(/))) {
217
+ const close = matchingClose(e, e.indexOf('('));
218
+ if (close < 0) return null;
219
+ const rest = e.slice(close + 1).match(/^\s*(?:\{\s*([^{};]+?)\s*\}|([^{};]+?))\s+else\s+(?:\{\s*([^{};]+?)\s*\}|([^{};]+))$/);
220
+ if (rest) return { cond: e.slice(e.indexOf('(') + 1, close), yes: rest[1] ?? rest[2], no: rest[3] ?? rest[4] };
221
+ return null;
222
+ }
223
+ if ((m = e.match(/^if\s+([^{}]+?)\s*\{\s*([^{};]+?)\s*\}\s*else\s*\{\s*([^{};]+?)\s*\}$/))) return { cond: m[1], yes: m[2], no: m[3] };
224
+ if ((m = e.match(/^if\s+(.+?)\s+then\s+(.+?)\s+else\s+(.+?)\s+end$/))) return { cond: m[1], yes: m[2], no: m[3] };
225
+ if ((m = e.match(/^unless\s+(.+?)\s+then\s+(.+?)\s+else\s+(.+?)\s+end$/))) return { cond: m[1], yes: m[3], no: m[2] };
226
+ return null;
227
+ }
228
+
198
229
  /** A boolean expression (comparison or logic), said as a yes/no question. */
199
230
  const LOGIC = /(&&|\|\||[<>]=?|[!=]==?|\band\b|\bor\b|\bnot\b|\bis\b|^\s*!)/;
200
231
  function sayWhether(expr) {
@@ -270,11 +301,42 @@ function redirectOf(head) {
270
301
  return { kind: isReturn ? 'return' : 'call', says: `Sends the person to ${to}`, redirect: to };
271
302
  }
272
303
 
304
+ /** The top-level keys of an object literal: `{ org, repos: list, ...rest, 'avg': x }` -> ['org', 'repos', 'avg']. */
305
+ function objectKeys(expr) {
306
+ const open = expr.indexOf('{');
307
+ if (open < 0) return [];
308
+ let close = -1;
309
+ for (let i = open, d = 0; i < expr.length; i++) {
310
+ const c = expr[i];
311
+ if (c === '"' || c === "'" || c === '`') { for (i++; i < expr.length && expr[i] !== c; i++) if (expr[i] === '\\') i++; continue; }
312
+ if (c === '{') d++; else if (c === '}' && --d === 0) { close = i; break; }
313
+ }
314
+ if (close < 0) return [];
315
+ const inner = expr.slice(open + 1, close);
316
+ const keys = [];
317
+ let depth = 0, cur = '';
318
+ const take = (part) => { const m = part.trim().match(/^(?:["'](\w+)["']|(\w+))\s*(?::|$|\()/); if (m && !part.trim().startsWith('...')) keys.push(m[1] || m[2]); };
319
+ for (const c of inner) {
320
+ if ('([{'.includes(c)) depth++;
321
+ if (')]}'.includes(c)) depth--;
322
+ if (c === ',' && depth === 0) { take(cur); cur = ''; } else cur += c;
323
+ }
324
+ if (cur.trim()) take(cur);
325
+ return keys.length > 8 ? [...keys.slice(0, 7), 'more'] : keys;
326
+ }
327
+ const listWords = (xs) => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')}${xs.length > 2 ? ',' : ''} and ${xs.at(-1)}`);
328
+
273
329
  export function classifyStatement(raw, { inner = 0 } = {}) {
274
330
  const text = String(raw).trim();
331
+ // A condition written over several lines (`if (\n a &&\n b\n) {`) is read whole.
332
+ let first = text.split('\n')[0].trim();
333
+ if (/^(?:if|else\s+if|while|for|switch)\s*\($/.test(first.replace(/\s*\{$/, '')) || (/^(?:if|else\s+if|while)\s*\(/.test(first) && !bracketsClosed(first.replace(/\{\s*$/, '')))) {
334
+ const o = text.indexOf('('), c = matchingClose(text, o);
335
+ if (c > 0 && c < 2000) first = `${text.slice(0, c + 1)}${text.slice(c + 1).split('\n')[0]}`.replace(/\s+/g, ' ').replace(/\(\s+/g, '(').replace(/\s+\)/g, ')').trim();
336
+ }
275
337
  // TypeScript-only syntax that changes nothing for a reader: casts, non-null assertions, optional calls.
276
- const head = text.split('\n')[0].trim()
277
- .replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, '$1').replace(/([\w$\])])!(?=[.(\[])/g, '$1').replace(/\?\.(?=[\w(\[])/g, '.').replace(/\.\(/g, '(').replace(/^\(\*+(self|this)\)\./, '$1.')
338
+ const head = first
339
+ .replace(/(^|[^\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, '$1$2').replace(/([\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, '$1($2)').replace(/([\w$\])])!(?=[.(\[])/g, '$1').replace(/\?\.(?=[\w(\[])/g, '.').replace(/\.\(/g, '(').replace(/^\(\*+(self|this)\)\./, '$1.')
278
340
  // Java/C# casts: ((JsonTreeReader) reader).promote() -> reader.promote(); (int) x -> x
279
341
  .replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, '$1').replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, '$1');
280
342
  const code = clip(head, 90);
@@ -282,10 +344,10 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
282
344
  const innerNote = inner ? ` (${inner} step${inner === 1 ? '' : 's'} inside)` : '';
283
345
  // One-line ifs: `if (x) return y;` and Ruby/Perl modifiers `return unless running?`, `notify if late`.
284
346
  let inl;
285
- if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?)$/)) && balanced(inl[2])) {
347
+ if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?|[\w$.]+(?:\+\+|--);?|(?:\+\+|--)[\w$.]+;?)$/)) && balanced(inl[2])) {
286
348
  return { kind: 'branch', says: `If ${sayCodeCondition(inl[2])}`, cond: inl[2], code, inline: inl[3] };
287
349
  }
288
- if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/^(?:[\w$.\[\]]+\s*=)/.test(inl[1])) {
350
+ if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && bracketsClosed(inl[1]) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/^(?:[\w$.\[\]]+\s*=)/.test(inl[1])) {
289
351
  const cond = sayCodeCondition(inl[3]);
290
352
  return { kind: 'branch', says: inl[2] === 'unless' ? `If not: ${cond}` : `If ${cond}`, cond: inl[3], negate: inl[2] === 'unless', code, inline: inl[1] };
291
353
  }
@@ -293,7 +355,25 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
293
355
  if ((inl = head.match(/^(?:let|var|const)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?;?$/))) return { kind: 'set', says: `Starts with no ${words(inl[1])} yet`, code };
294
356
  // A function stored under a name: `ky.create = (opts) => ...` -> "Defines how ky's create works".
295
357
  if ((inl = head.match(/^([\w$.]+)\s*=\s*(?:async\s+)?(?:function\b|\([^()]*\)\s*(?::\s*[^=]+)?=>|[\w$]+\s*=>)/))) return { kind: 'set', says: `Defines how ${targetWords(inl[1])} works`, code };
358
+ if ((inl = head.match(/^([\w$.]+)\s*:?=\s*func\s*\(/))) return { kind: 'set', says: `Defines how ${targetWords(inl[1])} works`, code };
359
+ // JavaScript `delete registry[name]`: "Removes name from registry".
360
+ if ((inl = head.match(/^delete\s+([\w$.]+)(?:\[\s*([^\]]+?)\s*\]|\.([\w$]+));?$/))) return { kind: 'call', says: `Removes ${words(String(inl[2] ?? inl[3]).replace(/["'`]/g, ''))} from ${targetWords(inl[1])}`, code };
361
+ // Go `fallthrough` / C# `goto case`: this case carries on into the next one.
362
+ if (/^fallthrough\b/.test(head)) return { kind: 'call', says: 'Carries on into the next case too', code };
363
+ if ((inl = head.match(/^goto\s+case\s+(.+?);?$/))) return { kind: 'call', says: `Carries on into the case for ${words(plainEnums(inl[1]))}`, code };
364
+ // do { … } while (cond): the steps run once, then again while the condition holds.
365
+ if (/^do\s*\{?$/.test(head)) {
366
+ const dw = text.match(/\}\s*while\s*\(([\s\S]*)\)\s*;?\s*$/);
367
+ if (dw) return { kind: 'loop', says: `Runs once, then repeats while ${sayCodeCondition(dw[1].replace(/\s+/g, ' '))}${innerNote}`, code };
368
+ }
369
+ // Ruby `when x then y` inside a case: "When it is x".
370
+ if ((inl = head.match(/^when\s+(.+?)(?:\s+then\s+(.+))?$/)) && !/[{]\s*$/.test(head) && !/^when\s*\(/.test(head)) {
371
+ return { kind: 'check', says: armSays(inl[1]), code, caseLabel: true, ...(inl[2] ? { inline: inl[2] } : {}) };
372
+ }
373
+ // Kotlin `when (x) {` / `when {` read like a switch.
374
+ if ((inl = head.match(/^when\s*(?:\((.+)\))?\s*\{$/))) return { kind: 'branch', says: inl[1] ? `Chooses by ${words(clip(inl[1], 40))}${innerNote}` : `Checks these cases in order${innerNote}`, code };
296
375
  // switch cases: `case X:` / `case X ->` read as "When it is X"; `default:` as "Otherwise".
376
+ if ((m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/)) && /(?:[<>]=?|[!=]==?|&&|\|\|)/.test(m[1].replace(/<-|->/g, '')) && !/^["']/.test(m[1])) return { kind: 'check', says: `When ${sayCodeCondition(m[1])}`, code, caseLabel: true };
297
377
  if ((m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/))) return { kind: 'check', says: `When it is ${/^[A-Z][A-Z0-9_]+$/.test(m[1].replace(/^[A-Z]\w*\./, '')) ? words(m[1].replace(/^[A-Z]\w*\./, '')) : sayCodeCondition(plainEnums(m[1]))}`, code, caseLabel: true };
298
378
  if (/^default\s*(?::|->)/.test(head)) return { kind: 'check', says: 'Otherwise', code, caseLabel: true };
299
379
  // Failures
@@ -324,7 +404,11 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
324
404
  }
325
405
  const chain = sayChain(expr);
326
406
  if (chain) return { kind: 'return', says: `Returns ${chain}`, code };
327
- if (/^\(?\s*\{/.test(expr)) return { kind: 'return', says: 'Returns an object', code };
407
+ if (/^\(?\s*\{/.test(expr)) {
408
+ // Name what is in it: { org, repos, avg: x } -> "Returns org, repos, and avg".
409
+ const keys = objectKeys(expr);
410
+ return { kind: 'return', says: keys.length ? `Returns ${listWords(keys.map(words))}` : 'Returns an object', code, ...(keys.length ? { keys } : {}) };
411
+ }
328
412
  if (/^\(?\s*</.test(expr)) return { kind: 'return', says: 'Returns what to show on screen', code };
329
413
  const v = sayValue(expr) || sayWhether(expr);
330
414
  return { kind: 'return', says: v ? `Returns ${v}` : 'Returns a computed value', code, ...(v ? {} : { value: clip(expr, 60) }) };
@@ -334,6 +418,8 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
334
418
  if ((m = head.match(/^for\b\s*\(?\s*(?:(?:var|let|const|int|long|size_t|auto|\$)\s*)?\$?(\w+)\s*:?=\s*([^;]+?)\s*;\s*([^;]*?)\s*;\s*[^)]*?\)?\s*\{?\s*$/))) {
335
419
  return { kind: 'loop', says: `Counts ${words(m[1])} from ${clip(m[2], 20)}${m[3] ? ` while ${sayCodeCondition(m[3])}` : ''}${innerNote}`, code };
336
420
  }
421
+ // A C-style loop with no counter of its own: `for (; pos < limit; i++)` / `for (;;)`.
422
+ 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 };
337
423
  // Pairs unpacked in a loop: for (const [key, value] of entries) / for key, value in items.items() / foreach ($a as $k => $v)
338
424
  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*$/))) {
339
425
  const src = stripTail(m[3]).replace(/\($/, '()').replace(/^Object\.entries\((.+)\)$/, '$1').replace(/\.(?:items|entries)\(\)$/, '');
@@ -353,12 +439,13 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
353
439
  if ((m = head.match(/^(?:if|else\s+if)\s+(?:[\w]+\s*,\s*)?err\s*:?=\s*([\w.]+)\(.*\);\s*err\s*!=\s*nil\s*\{?\s*$/))) return { kind: 'branch', says: `If ${lastWords(m[1])} fails${innerNote}`, code };
354
440
  if ((m = head.match(/^(?:if|else\s+if)\s+[^;{]*:=[^;{]*;\s*(.+?)\s*\{?\s*$/))) { const cond = sayCodeCondition(m[1]); return { kind: 'branch', says: `If ${cond}${innerNote}`, cond: m[1], code }; }
355
441
  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) }; }
442
+ if (/^switch\s*(?:true\s*)?\{$/.test(head)) return { kind: 'branch', says: `Checks these cases in order${innerNote}`, code };
356
443
  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 };
357
444
  if (/^(?:try|begin)\b/.test(head)) return { kind: 'try', says: `Tries the next steps and handles any error${innerNote}`, code };
358
445
  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 };
359
446
  if ((m = head.match(/^assert(?:_\w+|That|Equals|True|False|NotNull|Null)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
360
447
  if ((m = head.match(/^(?:expect|t\.(?:Error|Fatal|Errorf|Fatalf|Run)|require\.\w+|assert\.\w+)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
361
- if ((m = head.match(/^with\s+(.+?)\s+as\s+(.+?):\s*$/))) { const what = /^open\s*\(/.test(m[1]) ? 'a file' : words(clip(stripTail(m[1]).replace(/\(.*$/, ''), 40)); return { kind: 'set', says: `Opens ${what} as ${words(m[2].replace(/[()]/g, ''))}`, code }; }
448
+ if ((m = head.match(/^(?:async\s+)?with\s+(.+?)\s+as\s+(.+?):\s*$/))) { const what = /^open\s*\(/.test(m[1]) ? 'a file' : words(clip(stripTail(m[1]).replace(/\(.*$/, ''), 40)); return { kind: 'set', says: `Opens ${what} as ${words(m[2].replace(/[()]/g, ''))}`, code }; }
362
449
  if ((m = head.match(/^(?:using|lock|synchronized)\s*\((.+?)\)/))) return { kind: 'set', says: `Uses ${clip(m[1], 50)}`, code };
363
450
  if (/^defer\b/.test(head)) return { kind: 'call', says: `At the end, ${clip(head.replace(/^defer\s+/, ''), 60)}`, code };
364
451
  if (/^super\b/.test(head)) return { kind: 'call', says: 'Runs the parent version first', code };
@@ -403,7 +490,7 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
403
490
  const target = m[1].split(/\s*,\s*/).filter((t) => t !== '_').map(targetWords).join(', ') || targetWords(m[1]);
404
491
  const value = stripTail(m[3]);
405
492
  // A yes/no value: `ok = proxy and scheme != "https"` -> "Works out ok: whether proxy and scheme is not https".
406
- if (m[2] === '=' && !/[(?]/.test(value.replace(/^\(|\)$/g, '')) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(value.replace(/->|=>/g, '.')) && !/=>/.test(value)) return { kind: 'set', says: `Works out ${target}: whether ${sayCodeCondition(value)}`, code };
493
+ if (m[2] === '=' && !/^(?:if|unless|match|when|case)\b/.test(value) && !/[(?]/.test(value.replace(/^\(|\)$/g, '')) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(value.replace(/->|=>/g, '.')) && !/=>/.test(value)) return { kind: 'set', says: `Works out ${target}: whether ${sayCodeCondition(value)}`, code };
407
494
  // self.max_books = max_books: the Thing keeps what it was given.
408
495
  if (m[2] === '=' && /^[A-Za-z_]\w*$/.test(value) && m[1].split('.').pop() === value && /^(self|this)\./.test(m[1])) return { kind: 'set', says: `Keeps the ${words(value)} it is given`, code };
409
496
  const chain = value ? (sayPython(value) || sayChain(value)) : null;
@@ -456,6 +543,7 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
456
543
  const spanOf = (s) => ({ startLine: s.line, endLine: s.endLine ?? s.line, ...(s.start != null && s.end != null ? { start: s.start, end: s.end } : {}) });
457
544
 
458
545
  const BARE_CALL = /^[a-z_][\w.]*[?!]?$/;
546
+ const bracketsClosed = (x) => { let d = 0; for (const ch of x) { if ('([{'.includes(ch)) d++; else if (')]}'.includes(ch)) d--; } return d === 0; };
459
547
  const balanced = (x) => { let d = 0; for (const ch of x) { if (ch === '(') d++; else if (ch === ')' && --d < 0) return false; } return d === 0; };
460
548
  function asCall(list, i) {
461
549
  const st = list[i];
@@ -491,6 +579,184 @@ function attachClause(step, clause) {
491
579
  }
492
580
  }
493
581
 
582
+ // ── Functions inside functions, values chosen by if / match / when, Go select ──────────────────────────────────
583
+
584
+ /** "a", "a or b", "a, b or c", "a, b, c or 2 other values" — names a reader can follow. */
585
+ function orList(names) {
586
+ const n = [...new Set(names)];
587
+ if (n.length <= 3) return n.length > 1 ? `${n.slice(0, -1).join(', ')} or ${n[n.length - 1]}` : n[0] || '';
588
+ return `${n.slice(0, 3).join(', ')} or ${n.length - 3} other value${n.length - 3 === 1 ? '' : 's'}`;
589
+ }
590
+ /** The watched values after a hook's function: ", [a, b])" -> ['a', 'b']; ")" -> null (none); anything else -> 'unknown'. */
591
+ function depsOf(after) {
592
+ const a = String(after || '');
593
+ if (/^\s*\)/.test(a)) return null;
594
+ const m = a.match(/^\s*,\s*\[([^\]]*)\]/);
595
+ if (!m) return 'unknown';
596
+ return m[1].split(',').map((x) => x.trim().replace(/\?\./g, '.').replace(/\(\)$/, '')).filter(Boolean).map((x) => words(x.split('.').pop()));
597
+ }
598
+ const changesWords = (deps) => `${orList(deps)} ${deps.length > 3 ? 'change' : 'changes'}`;
599
+ function effectSays(deps) {
600
+ if (deps === null) return 'Every time this is drawn on screen';
601
+ if (deps === 'unknown') return 'When this first shows on screen, and whenever what it watches changes';
602
+ if (!deps.length) return 'When this first shows on screen';
603
+ return `When this first shows on screen, and whenever ${changesWords(deps)}`;
604
+ }
605
+ const HOOK = /^(?:(?:const|let|var)\s+([\w$]+)(?:\s*:[^=]+?)?\s*=\s*)?(?:React\.)?(use[A-Z]\w*)\s*(?:<[^(]*?>)?\(/;
606
+ const TRAILING_LAMBDA = /^(?:(?:val|var)\s+[\w$]+(?:\s*:[^=]+)?\s*=\s*)?([a-z_$][\w$]*(?:\??\.[\w$]+)*)\s*(\([^{}]*\))?\s*\{\s*(?:\(?[\w$, ]+\)?\s*->)?\s*$/;
607
+ const RUBY_DO = /^(?:[@$]?[\w]+\s*=\s*)?([a-z_][\w.?!]*)(?:\(.*\)|\s+[^|]*?)?\s+do\s*(?:\|[^|]*\|)?\s*$/;
608
+ const NOT_A_CALL = /^(?:if|else|for|while|when|return|object|init|companion|class|interface|fun|try|catch|finally|do|loop|unsafe|match|switch|select|synchronized|lock|using|get|set)$/;
609
+
610
+ /** A promise's callback: `load(x).then((r) => {` -> "When load is done"; `.catch(` -> "If load goes wrong". */
611
+ function thenSays(text) {
612
+ const m = String(text).match(/^(?:await\s+)?([^{};\n]*?)\.(then|catch)\(\s*(?:async\s+)?(?:function\b|\(|[\w$]+\s*=>)/);
613
+ if (!m) return null;
614
+ const recvText = m[1].trim().replace(/^\(\s*([\w$.]+)\s+as\s+[^()]*\)$/, '$1');
615
+ const recv = recvText.match(/^([\w$.]+)\(.*\)$/s) || recvText.match(/^([\w$.]+)$/);
616
+ const what = recv ? lastWords(recv[1]) : 'that';
617
+ return m[2] === 'then' ? `When ${what} is done` : `If ${what} goes wrong`;
618
+ }
619
+
620
+ /** A function inside a function, read with its own steps. Null when the statement is not one. */
621
+ function nestedStep(s, base) {
622
+ const text = String(s.text || '').trim();
623
+ const head = text.split('\n')[0].trim();
624
+ const kids = () => stepsFrom(s.children || []).steps;
625
+ const own = (step, children) => (children.length ? { ...step, children, nested: true } : step);
626
+ let m;
627
+ // React hooks: what the function is for, and when it runs.
628
+ if (s.fn && s.fn.depth === 1 && (m = text.match(HOOK))) {
629
+ const [, name, hook] = m;
630
+ const deps = depsOf(s.fn.after);
631
+ if (/^use\w*Effect$/.test(hook)) {
632
+ for (const c of s.children || []) if (c.fn && /^return\b/.test(c.text.trim())) c.cleanup = deps && deps !== 'unknown' && !deps.length ? 'When this is taken off the screen, cleans up' : 'Cleans up before it runs again, and when this is taken off the screen';
633
+ return own({ kind: 'call', says: effectSays(deps), code: base.code, callee: hook }, kids());
634
+ }
635
+ if (hook === 'useMemo' && name) {
636
+ let children = kids();
637
+ if (s.fn.expr && children.length === 1) { const v = classifyStatement(`return ${s.children[0].text}`); children = [{ ...children[0], kind: v.kind, says: v.says }]; }
638
+ const says = deps === null ? `Works out ${words(name)}` : Array.isArray(deps) && !deps.length ? `Works out ${words(name)} once and remembers it` : Array.isArray(deps) ? `Works out ${words(name)} and remembers it until ${changesWords(deps)}` : `Works out ${words(name)} and remembers it until what it watches changes`;
639
+ return own({ kind: 'set', says, code: base.code, callee: hook }, children);
640
+ }
641
+ if (/^use\w*Callback$/.test(hook) && name) return own({ kind: 'set', says: `Defines how ${words(name)} works`, code: base.code, callee: hook }, kids());
642
+ }
643
+ // The function an effect gives back is what cleans up after it.
644
+ if (s.cleanup) return own({ kind: 'call', says: s.cleanup, code: base.code }, kids());
645
+ if (s.fn && !s.fn.expr) {
646
+ if (s.fn.depth === 0 && /^go\s+func\b/.test(head)) return own({ kind: 'call', says: 'Starts these steps running alongside, without waiting for them', code: base.code }, kids());
647
+ if (s.fn.depth === 0 && /^defer\s+func\b/.test(head)) return own({ kind: 'call', says: 'At the end, runs these steps', code: base.code }, kids());
648
+ if (/^return\b/.test(head) || base.kind === 'return' || base.kind === 'other' || base.kind === 'branch' || base.kind === 'fail') return null;
649
+ if (base.kind === 'loop') return null; // forEach and friends already read their body as a loop
650
+ let said = base.says;
651
+ if (base.kind !== 'call') { /* a value worked out with a function's help keeps its own wording */ }
652
+ else if ((m = text.match(/^(?:window\.|globalThis\.)?(setTimeout|setInterval)\(/))) {
653
+ const ms = (s.fn.after.match(/^\s*,\s*(\d+)\s*\)/) || [])[1];
654
+ said = m[1] === 'setTimeout' ? (ms ? `After ${ms} milliseconds` : 'After a wait') : (ms ? `Every ${ms} milliseconds` : 'Again and again, with a wait in between');
655
+ } else if ((m = text.match(/\.(addEventListener|on|once)\(\s*['"`]([\w:.-]+)['"`]\s*,/))) {
656
+ said = m[1] === 'once' ? `The first time "${m[2]}" happens` : `Whenever "${m[2]}" happens`;
657
+ } else if (thenSays(text)) {
658
+ said = thenSays(text);
659
+ } else if (/^Calls [\w ]+$/.test(said)) said = `${said} with these steps`;
660
+ return own({ ...base, kind: base.kind === 'set' ? 'set' : 'call', says: said }, kids());
661
+ }
662
+ if (!s.children?.length) return null;
663
+ // Kotlin trailing lambdas: `user?.let { … }` runs only when user is set; `scope.launch { … }` hands over steps.
664
+ const raw = String(s.text || '').split('\n')[0].trim();
665
+ if (!s.fn && !BLOCK_HEAD.test(raw) && (m = raw.match(TRAILING_LAMBDA)) && !NOT_A_CALL.test(m[1])) {
666
+ const safe = m[1].match(/^(.+?)\?\.(?:let|also|run|apply)$/);
667
+ if (safe) return own({ kind: 'branch', says: `If ${words(safe[1].split(/\??\./).pop())} is set`, code: clip(raw, 90) }, kids());
668
+ if ((m = raw.match(/^repeat\s*\(\s*(.+?)\s*\)\s*\{/))) return own({ kind: 'loop', says: `Repeats ${/^\d+$/.test(m[1]) ? m[1] : words(m[1])} times`, code: base.code }, kids());
669
+ if (base.kind === 'loop') return null;
670
+ if (base.kind === 'call' && /^Calls [\w ]+$/.test(base.says)) return own({ ...base, says: `${base.says} with these steps` }, kids());
671
+ if (base.kind === 'set' || base.kind === 'call') return own(base, kids());
672
+ return null;
673
+ }
674
+ // Ruby blocks: `transaction do … end`.
675
+ if ((m = raw.match(RUBY_DO)) && base.kind !== 'loop' && !/^(?:if|unless|while|until|for|case|begin)\b/.test(raw)) {
676
+ if (base.kind === 'call' && /^Calls [\w ]+$/.test(base.says)) return own({ ...base, says: `${base.says.replace(/: .*$/, '')} with these steps` }, kids());
677
+ if (base.kind === 'call' || base.kind === 'set') return own(base, kids());
678
+ }
679
+ return null;
680
+ }
681
+
682
+ /** "if", "match", "when", "case" or "switch" giving a value to a name (or to the caller): [target | null, rest]. */
683
+ function valueChoice(s) {
684
+ const head = headLine(s.text || '');
685
+ let m = head.match(/^(?:(?:const|let|var|val|my)\s+(?:mut\s+)?)?([@$]?[\w$.]+)(?:\s*:\s*[^=]+?)?\s*=\s*((?:if|unless|match|when|case)\b.*|[\w.]+\s+switch\s*\{\s*)$/);
686
+ if (m && !/^(?:if|for|while|return)$/.test(m[1])) return { target: targetWords(m[1]), rest: m[2] };
687
+ if ((m = head.match(/^return\s+((?:if|match|when)\b.*|[\w.]+\s+switch\s*\{\s*)$/))) return { target: null, rest: m[1] };
688
+ return null;
689
+ }
690
+ /** The subject of a match / when / switch: "match cmd {" -> "cmd"; "when {" -> null. */
691
+ function armsSubject(rest) {
692
+ const r = rest.replace(/\{\s*$/, '').trim();
693
+ const m = (r.match(/^match\s*\((.+)\)$/) || r.match(/^match\s+(.+)$/)) || r.match(/^when\s*\((.+)\)$/) || r.match(/^([\w.]+)\s+switch$/);
694
+ return m ? m[1].trim() : null;
695
+ }
696
+ /** One arm's pattern in words: `0..=49` -> "from 0 to 49", `Cmd::Start | Cmd::Go` -> "start or go", `_` -> otherwise. */
697
+ function armSays(pattern) {
698
+ let p = String(pattern).trim();
699
+ if (/^(?:_|else|default)$/.test(p)) return 'Otherwise';
700
+ let guard = null;
701
+ const g = p.match(/^(.+?)\s+(?:if|when)\s+(.+)$/);
702
+ if (g) { p = g[1]; guard = g[2]; }
703
+ if (LOGIC.test(p) && !/^(?:!?in|!?is)\s/.test(p) && !/\.\./.test(p) && !/\|/.test(p.replace(/\|\|/g, ''))) return `When ${sayCodeCondition(p)}`;
704
+ const parts = [];
705
+ let depth = 0, from = 0;
706
+ for (let i = 0; i <= p.length; i++) {
707
+ const c = p[i];
708
+ if (c === '(' || c === '[' || c === '{') depth++; else if (c === ')' || c === ']' || c === '}') depth--;
709
+ if (i === p.length || (depth === 0 && ((c === '|' && p[i + 1] !== '|' && p[i - 1] !== '|') || c === ','))) { parts.push(p.slice(from, i).trim()); from = i + 1; }
710
+ }
711
+ const one = (x) => {
712
+ let m;
713
+ if ((m = x.match(/^(!?)in\s+(.+?)\.\.(=?)(.+)$/)) || (m = x.match(/^()(-?[\w.]+)\.\.(=)(-?[\w.]+)$/))) return `${m[1] ? 'not ' : ''}from ${m[2].trim()} to ${m[4].trim()}`;
714
+ if ((m = x.match(/^(!?)is\s+([\w.<>?]+)$/))) return `${m[1] ? 'not ' : ''}a ${m[2].split('.').pop()}`;
715
+ if ((m = x.match(/^(?:[A-Z]\w*(?:::|\.))+([A-Z]\w*)$/))) return words(m[1]);
716
+ if (/^[A-Z][A-Z0-9_]+$/.test(x)) return words(x);
717
+ return x;
718
+ };
719
+ return `When it is ${orList(parts.filter(Boolean).map(one))}${guard ? `, and ${sayCodeCondition(guard)}` : ''}`;
720
+ }
721
+ /** The last thing each side of a value choice works out becomes "Sets <target> to …" (or "Returns …" for a return). */
722
+ function giveValue(list, target) {
723
+ if (!list?.length) return;
724
+ if (list.some((x) => x.caseLabel)) { for (const x of list) if (x.caseLabel) giveValue(x.children, target); return; }
725
+ const i = list.length - 1;
726
+ const last = list[i];
727
+ if (last.kind === 'branch' && !Object.hasOwn(last, 'valueOf')) { giveValue(last.children, target); giveValue(last.otherwise, target); return; }
728
+ if (last.kind === 'fail' || /^(?:return|break|continue|throw|raise)\b/.test(last.code || '')) return;
729
+ const v = classifyStatement(`return ${String(last.code || '').replace(/,$/, '')}`);
730
+ if (v.kind !== 'return') return;
731
+ const said = v.says.replace(/^Returns /, '');
732
+ list[i] = target ? { ...last, kind: 'set', says: v.value ? `Sets ${target} to a computed value` : `Sets ${target} to ${said}` } : { ...last, kind: 'return', says: v.says };
733
+ delete list[i].callee;
734
+ if (list[i].says && restates(list[i])) list[i].restates = true; else delete list[i].restates;
735
+ }
736
+
737
+ /** Go `select`: which channel is ready first. "case msg := <-ch:" -> "When msg arrives from ch". */
738
+ function selectCaseSays(code) {
739
+ const c = String(code).trim();
740
+ if (/^default\s*:/.test(c)) return 'If none is ready yet';
741
+ let m = c.match(/^case\s+(?:([\w$]+)(?:\s*,\s*([\w$]+))?\s*:?=\s*)?<-\s*(.+?)\s*:\s*$/);
742
+ if (m) {
743
+ const [, name, ok, ch] = m;
744
+ let d;
745
+ if (/\.Done\(\)$/.test(ch)) return `When ${lastWords(ch.replace(/\.Done\(\)$/, ''))} is cancelled or times out`;
746
+ if ((d = ch.match(/^time\.After\((.+)\)$/))) {
747
+ const t = d[1].trim();
748
+ const u = t.match(/^(\d+)\s*\*\s*time\.(Millisecond|Second|Minute|Hour)$/) || t.match(/^time\.(Millisecond|Second|Minute|Hour)$/);
749
+ const dur = u ? (u.length === 3 ? `${u[1]} ${u[2].toLowerCase()}${u[1] === '1' ? '' : 's'}` : `1 ${u[1].toLowerCase()}`) : words(t.split('.').pop());
750
+ return `When ${dur} ${/s$/.test(dur) && !/^1 /.test(dur) ? 'have' : 'has'} passed`;
751
+ }
752
+ if (/\.C$/.test(ch)) return `When ${lastWords(ch.replace(/\.C$/, ''))} ticks`;
753
+ const from = lastWords(ch.replace(/\(\)$/, ''));
754
+ return name && name !== '_' ? `When ${words(name)} arrives from ${from}${ok ? ` (or ${from} is closed)` : ''}` : `When something arrives from ${from}`;
755
+ }
756
+ if ((m = c.match(/^case\s+(.+?)\s*<-\s*(.+?)\s*:\s*$/))) return `When ${words(m[2].split('.').pop())} can be sent to ${lastWords(m[1])}`;
757
+ return null;
758
+ }
759
+
494
760
  export function stepsFrom(statements) {
495
761
  const steps = [];
496
762
  const skipped = [];
@@ -499,6 +765,14 @@ export function stepsFrom(statements) {
499
765
  let into = null, intoAlways = false;
500
766
  for (const s of statements) {
501
767
  const t0 = (s.text || '').trim();
768
+ // An arm of a match / when: "When it is …", with what that arm does inside it (`else ->` is an arm, not a clause).
769
+ if (s.arm != null) {
770
+ const arm = { kind: 'check', says: armSays(s.arm), code: clip(t0.split('\n')[0].trim(), 90), caseLabel: true, line: s.line, span: spanOf(s) };
771
+ const kids = stepsFrom(s.children || []).steps;
772
+ if (kids.length) arm.children = kids;
773
+ steps.push(arm);
774
+ continue;
775
+ }
502
776
  if (into && !CLAUSE.test(t0) && t0 && !/^(?:end\b|#)/.test(t0)) {
503
777
  const st = stepsFrom([s]).steps;
504
778
  into.push(...st);
@@ -519,7 +793,9 @@ export function stepsFrom(statements) {
519
793
  if (prev2 && (prev2.kind === 'branch' || prev2.kind === 'try')) {
520
794
  const prev = prev2;
521
795
  const kw = /^(?:elif|elsif|else\s+if)\b/.test(t0) ? 'elif' : /^else\b/.test(t0) ? 'else' : /^(?:finally|ensure)\b/.test(t0) ? 'finally' : 'catch';
522
- attachClause(prev, { kind: kw, head: t0.replace(/:\s*$/, ''), line: s.line, endLine: s.endLine, children: s.children || [] });
796
+ const inlineElse = kw === 'else' && t0.match(/^else\s+(?!if\b)([^{:\s].*)$/);
797
+ const clauseKids = inlineElse ? [{ text: inlineElse[1], line: s.line, endLine: s.line }, ...(s.children || [])] : s.children || [];
798
+ attachClause(prev, { kind: kw, head: t0.replace(/:\s*$/, ''), line: s.line, endLine: s.endLine, children: clauseKids });
523
799
  intoAlways = kw === 'finally';
524
800
  into = s.children?.length ? null : kw === 'catch' ? prev.handlers?.[prev.handlers.length - 1]?.steps ?? null : kw === 'finally' ? prev.always?.steps ?? null : null;
525
801
  prev.span = { ...prev.span, endLine: Math.max(prev.span.endLine, s.endLine ?? s.line) };
@@ -528,24 +804,68 @@ export function stepsFrom(statements) {
528
804
  skipped.push(spanOf(s));
529
805
  continue;
530
806
  }
531
- if (!t0 || /^(?:end\b|\}|pass$|break$|continue$|#)/.test(t0)) { if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s)); continue; }
807
+ if (!t0 || /^(?:end\b|\}|pass$|break;?$|continue;?$|#)/.test(t0)) { if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s)); continue; }
532
808
  if (/^(?:"""|'''|r"""|\/\*\*|\*)/.test(t0)) { skipped.push(spanOf(s)); continue; } // docstrings and doc comments
533
809
  if (/^[)\]}]+[):;,]*$/.test(t0) || /^\.\.\.$/.test(t0) || /^\.[A-Za-z_]/.test(t0) || /^@\w+(?:\(.*\))?$/.test(t0) || /^#?\[[\w:]+(?:\(.*\))?\]$/.test(t0) || /^:(?:param|rtype|return|raises|type)\b/.test(t0)) { skipped.push(spanOf(s)); continue; }
534
- const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
810
+ const head0 = headLine(s.text);
811
+ // A bare block `{ … }` (a case's own scope) adds nothing to read: its statements are read in its place.
812
+ if (/^\{/.test(t0) && s.children?.length) { steps.push(...stepsFrom(s.children).steps); continue; }
813
+ const choice = s.children?.length || s.clauses || s.arms ? valueChoice(s) : null;
814
+ if (s.arms) {
815
+ const subject = armsSubject(choice ? choice.rest : head0);
816
+ const kids = stepsFrom(s.children || []).steps;
817
+ const chooser = { kind: 'branch', says: subject ? `Chooses by ${words(clip(subject, 40))}` : 'Checks these cases in order', code: clip(head0, 90), line: s.line, span: spanOf(s), ...(kids.length ? { children: kids } : {}), ...(choice ? { valueOf: choice.target } : {}) };
818
+ steps.push(chooser);
819
+ continue;
820
+ }
821
+ let step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
822
+ // `val label = if (user == null) { … } else { … }` over several lines reads as the question it asks, each side
823
+ // ending in "Sets label to …".
824
+ if (choice && /^(?:if|unless|case)\b/.test(choice.rest) && (s.endLine ?? s.line) > s.line) {
825
+ step = { ...classifyStatement(choice.rest, { inner: s.inner || 0 }), code: step.code, line: s.line, span: spanOf(s), valueOf: choice.target };
826
+ } else {
827
+ const nest = nestedStep(s, step);
828
+ // `return new Promise((resolve) => { … })`, `return load().then((x) => { … })`: the function's steps, then the return.
829
+ if (!nest && step.kind === 'return' && s.fn && !s.fn.expr && s.fn.depth >= 1 && s.children?.length) {
830
+ const kids = stepsFrom(s.children).steps;
831
+ if (kids.length) {
832
+ let m;
833
+ const body = s.text.trim().replace(/^return\s+/, '');
834
+ const said = (m = body.match(/^new\s+([A-Z]\w*)/)) ? `Makes a new ${m[1]} with these steps`
835
+ : thenSays(body) ? thenSays(body)
836
+ : callee(body) ? `Calls ${lastWords(callee(body))} with these steps` : null;
837
+ if (said) steps.push({ kind: 'call', says: said, code: step.code, line: s.line, span: spanOf(s), children: kids, nested: true });
838
+ }
839
+ }
840
+ if (nest) {
841
+ step = { ...nest, line: s.line, span: spanOf(s) };
842
+ for (const c of s.clauses || []) attachClause(step, c);
843
+ steps.push(step);
844
+ continue;
845
+ }
846
+ }
535
847
  // A one-line `if (x) return reply.code(400).send({ error: 'bad' })` is one statement: its braces belong to the
536
848
  // object being sent, not to a block, so read the statement after the condition instead of the braces' inside.
537
849
  if (step.inline && !/^\{/.test(step.inline.trim())) { const kid = classifyStatement(step.inline); step.children = [{ ...kid, line: s.line, span: spanOf(s) }]; delete step.inline; }
538
- else if (s.children?.length && ['branch', 'loop', 'try'].includes(step.kind)) {
850
+ else if (s.children?.length && (['branch', 'loop', 'try'].includes(step.kind) || (step.kind === 'check' && step.caseLabel) || /^(?:Defines a helper|Defines how|Opens |Uses )/.test(step.says))) {
539
851
  const kids = stepsFrom(s.children).steps;
540
- if (kids.length) { step.children = kids; step.says = step.says.replace(/ \(\d+ steps? inside\)$/, ''); }
852
+ if (kids.length) { step.children = kids; step.says = step.says.replace(/ \(\d+ steps? inside\)$/, ''); if (/^Defines/.test(step.says)) step.nested = true; }
853
+ // Go select: whichever channel is ready first (or, with a default, whichever is ready now).
854
+ if (/^select\s*\{/.test(head0) && step.children) {
855
+ for (const k of step.children) if (k.caseLabel) k.says = selectCaseSays(k.code) ?? k.says;
856
+ step.says = step.children.some((k) => /^default\b/.test(k.code || '')) ? 'Checks which of these is ready, without waiting' : 'Waits for whichever of these is ready first';
857
+ }
541
858
  }
542
859
  if (step.inline && !step.children) { const kid = classifyStatement(step.inline); step.children = [{ ...kid, line: s.line, span: spanOf(s) }]; delete step.inline; }
543
860
  else delete step.inline;
544
- for (const c of s.clauses || []) attachClause(step, c);
861
+ // An else belongs to a question; on a value already said in one line (`let x = if a { 1 } else { 2 }`) it is part of it.
862
+ if (step.kind === 'branch' || step.kind === 'try') for (const c of s.clauses || []) attachClause(step, c);
545
863
  steps.push(step);
546
864
  }
547
865
  // A bare word is only a returned value when it is the last statement; before that it is a call (Ruby: `rollback`).
548
866
  for (let i = 0; i < steps.length - 1; i++) asCall(steps, i);
867
+ // A value chosen by if / match / when: each side's last value is what the name is set to (or what is returned).
868
+ 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); }
549
869
  // Every step is kept (anchoring needs all of them); `more` tells a view how many to fold away.
550
870
  const more = Math.max(0, steps.length - MAX_STEPS);
551
871
  for (const st of steps) if (restates(st)) st.restates = true;
@@ -560,7 +880,7 @@ const GENERIC_CALLS = /^(?:get|set|run|do|call|apply|handle|process|execute|exec
560
880
  function restates(st) {
561
881
  const s = st.says || '';
562
882
  if (st.kind === 'other') return false;
563
- if (/^Works out [^:]+$/.test(s) && !/ from /.test(s)) return true;
883
+ if (/^Works out [^:]+$/.test(s) && !/ from | remembers it/.test(s)) return true;
564
884
  const same = s.match(/^Works out (.+) from (.+)$/);
565
885
  if (same && same[1].trim() === same[2].trim()) return true; // "Works out licence from licence"
566
886
  if (/^(Returns a computed value|Returns a value|Sets .+ to a computed value)$/.test(s)) return true;
@@ -580,26 +900,184 @@ const blockEnd = (text, open) => {
580
900
  return -1;
581
901
  };
582
902
 
903
+ /** A statement's first line, joined with the next when it ends in a dangling `=` (`valid =\n when (x) {`). */
904
+ const headLine = (text) => String(text).trim().replace(/^([^\n]*?=)[ \t]*\r?\n\s*/, '$1 ').split('\n')[0].trim();
905
+ const skipQuoted = (text, i) => { const q = text[i]; for (i++; i < text.length && text[i] !== q; i++) if (text[i] === '\\') i++; return i; };
906
+ /** Statements whose first brace is their own block (never a function written inside them). */
907
+ const BLOCK_HEAD = /^(?:if|else|for|foreach|while|until|switch|try|catch|finally|do|match|loop|unsafe|select|using|lock|synchronized|when|case|default|elif|with|class|struct|interface|enum|impl|fn|fun|func|def)\b/;
908
+
909
+ /**
910
+ * The first function written inside a statement, outside any object literal: an arrow `(x) => {` or `x => expr`, a
911
+ * `function (x) {`, a Go `func(x) T {`, a Java lambda in a call `x -> {`, a Rust closure `|x| {`.
912
+ * Gives { open, close, depth } for a body in braces or { expr: [from, to], depth } for an expression body, where
913
+ * depth is how many brackets it sits inside (0: the statement itself is the function, `go func() {…}()`). Null when
914
+ * there is none. Linear in the statement's length.
915
+ */
916
+ export function fnLiteral(text) {
917
+ let depth = 0;
918
+ const bodyAt = (j, d) => {
919
+ while (j < text.length && /\s/.test(text[j])) j++;
920
+ if (text[j] !== '{') return null;
921
+ const close = blockEnd(text, j);
922
+ return close < 0 ? null : { open: j, close, depth: d };
923
+ };
924
+ for (let i = 0; i < text.length; i++) {
925
+ const c = text[i];
926
+ if (c === '"' || c === "'" || c === '`') { i = skipQuoted(text, i); continue; }
927
+ if (c === '(' || c === '[') { depth++; continue; }
928
+ if (c === ')' || c === ']') { depth--; continue; }
929
+ // Object literals, destructured parameters, struct literals: not functions; read past them.
930
+ if (c === '{') { const e = blockEnd(text, i); if (e < 0) return null; i = e; continue; }
931
+ if (c === '=' && text[i + 1] === '>') {
932
+ const before = text.slice(Math.max(0, i - 80), i).trimEnd();
933
+ // A lambda's parameters come right before its arrow: `(a, b) =>`, `x =>`, `async () =>` (not PHP `'key' =>`).
934
+ if (!/(?:\)|[A-Za-z_$][\w$]*)(?:\s*:\s*[^=()]+)?$/.test(before) || /["']$/.test(before)) { i++; continue; }
935
+ const body = bodyAt(i + 2, depth);
936
+ if (body) return body;
937
+ if (depth < 1) { i++; continue; }
938
+ // Expression body: up to the next comma or closing bracket at the arrow's own depth.
939
+ let j = i + 2, d = 0;
940
+ for (; j < text.length; j++) {
941
+ const ch = text[j];
942
+ if (ch === '"' || ch === "'" || ch === '`') { j = skipQuoted(text, j); continue; }
943
+ if (ch === '(' || ch === '[' || ch === '{') d++;
944
+ else if (ch === ')' || ch === ']' || ch === '}') { if (--d < 0) break; }
945
+ else if (ch === ',' && d === 0) break;
946
+ }
947
+ return { expr: [i + 2, j], depth };
948
+ }
949
+ if (c === '-' && text[i + 1] === '>' && depth >= 1) { const body = bodyAt(i + 2, depth); if (body) return body; i++; continue; }
950
+ if ((c === 'f' && /\b(?:function|func)\b/y.test(text.slice(i, i + 9)) && !/[\w$.]/.test(text[i - 1] || ''))) {
951
+ const m = text.slice(i, i + 120).match(/^(?:function\s*\*?\s*[\w$]*|func)\s*\(/);
952
+ if (!m) continue;
953
+ let p = i + m[0].length - 1, pd = 0;
954
+ for (; p < text.length; p++) { if (text[p] === '(') pd++; else if (text[p] === ')' && --pd === 0) break; }
955
+ // PHP `use (...)`, a return type (`: string`, Go `(int, error)` or `bool`), skipping Go `interface{}`/`struct{}`.
956
+ let j = p + 1;
957
+ const use = text.slice(j, j + 24).match(/^\s*use\s*\(/);
958
+ if (use) { j += use[0].length - 1; for (let ud = 0; j < text.length; j++) { if (text[j] === '(') ud++; else if (text[j] === ')' && --ud === 0) { j++; break; } } }
959
+ for (; j < text.length && j < p + 200; j++) {
960
+ if (text[j] === '{') { if (/(?:interface|struct)\s*$/.test(text.slice(Math.max(0, j - 12), j))) { j = blockEnd(text, j); continue; } break; }
961
+ if (text[j] === '\n' && /^\s*$/.test(text.slice(p + 1, j))) break;
962
+ }
963
+ const body = text[j] === '{' ? bodyAt(j, depth) : null;
964
+ if (body) return body;
965
+ continue;
966
+ }
967
+ if (c === '|' && depth >= 1 && /[(,]\s*(?:move\s+)?$/.test(text.slice(Math.max(0, i - 8), i))) {
968
+ const m = text.slice(i, i + 200).match(/^\|[^|]*\|\s*(?:->\s*[\w<>&' ]+?\s*)?(?=\{)/);
969
+ if (m) { const body = bodyAt(i + m[0].length, depth); if (body) return body; }
970
+ }
971
+ }
972
+ return null;
973
+ }
974
+
975
+ /** The text of a statement's own lambda parameters at the start of a Kotlin block: `{ item ->` gives "item ->". */
976
+ const LAMBDA_PARAMS = /^\s*(?:\(?[\w$]+(?:\s*:\s*[\w<>?.]+)?(?:\s*,\s*[\w$]+(?:\s*:\s*[\w<>?.]+)?)*\)?|_)\s*->(?![^\n]*->)/;
977
+
978
+ /**
979
+ * The arms of a Rust `match`, a Kotlin `when` or a C# `switch` expression: `pattern => value,` / `pattern -> value`.
980
+ * Gives [{ pattern, body, bodyAt, at, end }] (offsets into `body`), or null when the block is not a list of arms.
981
+ */
982
+ export function armsOf(body) {
983
+ const arms = [];
984
+ let i = 0;
985
+ while (i < body.length) {
986
+ while (i < body.length && /[\s,;]/.test(body[i])) i++;
987
+ if (i >= body.length) break;
988
+ const at = i;
989
+ let depth = 0, arrow = -1, end = -1;
990
+ for (; i < body.length; i++) {
991
+ const c = body[i];
992
+ if (c === '"' || c === "'" || c === '`') { i = skipQuoted(body, i); continue; }
993
+ if (c === '(' || c === '[' || c === '{') { depth++; continue; }
994
+ if (c === ')' || c === ']' || c === '}') {
995
+ depth--;
996
+ // A block arm `X => { ... }` may end without a comma.
997
+ if (depth === 0 && c === '}' && arrow >= 0 && /^\{/.test(body.slice(arrow + 2).trimStart())) { i++; end = i; break; }
998
+ continue;
999
+ }
1000
+ if (depth !== 0) continue;
1001
+ if (arrow < 0 && (c === '=' || c === '-') && body[i + 1] === '>') { arrow = i; i++; continue; }
1002
+ if (arrow >= 0 && (c === ',' || c === ';')) { end = i; break; }
1003
+ if (arrow >= 0 && c === '\n') {
1004
+ const before = body.slice(arrow + 2, i).trim();
1005
+ let j = i + 1;
1006
+ while (j < body.length && /\s/.test(body[j])) j++;
1007
+ const after = body.slice(j, j + 12);
1008
+ if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) && !/^[.)\]}+\-*/%&|^=<>?:,]/.test(after) && !/^else\b(?!\s*->)/.test(after)) { end = i; break; }
1009
+ }
1010
+ }
1011
+ if (end < 0) end = i;
1012
+ if (arrow < 0) return null;
1013
+ const pattern = body.slice(at, arrow).trim();
1014
+ let bodyAt = arrow + 2;
1015
+ while (bodyAt < end && /\s/.test(body[bodyAt])) bodyAt++;
1016
+ if (!pattern) return null;
1017
+ arms.push({ pattern, at, end, bodyAt, body: body.slice(bodyAt, end).trim() });
1018
+ i = end + 1;
1019
+ }
1020
+ return arms.length ? arms : null;
1021
+ }
1022
+ /** A match/when/switch-expression header: `match x {`, `when (x) {`, `when {`, `let y = match x {`, `x switch {`. */
1023
+ const ARMS_HEAD = /(?:^|=\s*|return\s+)(?:[\w.]+\s+(?=switch))?(?:match\b\s*[^{\s][^{]*|when\s*(?:\([^{]*\))?|switch)\s*\{\s*$/;
1024
+
583
1025
  /**
584
1026
  * Statements of a brace body, each with its whole block read (every depth), and every clause that follows the first
585
- * block: else if, else, catch, finally. Nothing is summarized away.
1027
+ * block: else if, else, catch, finally. Nothing is summarized away. A function written inside a statement
1028
+ * (`useEffect(() => { … })`, `go func() { … }()`) has its own body read as the statement's children, and the arms of
1029
+ * a match/when are read one by one.
586
1030
  */
587
1031
  export function braceStatements(stmts, split = null) {
588
1032
  return stmts.map((s) => {
589
1033
  const text = s.text;
590
- const open = text.indexOf('{');
1034
+ const head0 = headLine(text);
1035
+ const lit = BLOCK_HEAD.test(head0) && !/^func\s*\(/.test(head0) ? null : fnLiteral(text);
1036
+ let open = lit?.open ?? text.indexOf('{');
591
1037
  const lineAtPos = (pos) => s.line + (text.slice(0, pos).match(/\n/g) || []).length;
592
1038
  const read = (o, e) => {
593
- const body = e > o ? text.slice(o + 1, e) : '';
594
- const base = s.start != null ? s.start + o + 1 : null;
1039
+ let from = o + 1;
1040
+ // Kotlin lambda parameters (`{ item ->`) name the item; they are not a step.
1041
+ const params = text.slice(from, e).match(LAMBDA_PARAMS);
1042
+ if (params && !ARMS_HEAD.test(head0)) from += params[0].length;
1043
+ const body = e > from ? text.slice(from, e) : '';
1044
+ const base = s.start != null ? s.start + from : null;
595
1045
  if (!body || !split) return [];
596
- const kids = split(body, lineAtPos(o + 1)).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...(base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {}) }));
1046
+ const kids = split(body, lineAtPos(from)).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...(base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {}) }));
597
1047
  return braceStatements(kids, split);
598
1048
  };
1049
+ // The arms of a match / when: each its own statement, with its value or block read inside it.
1050
+ const readArms = (o, e) => {
1051
+ const body = e > o ? text.slice(o + 1, e) : '';
1052
+ const arms = body ? armsOf(body) : null;
1053
+ if (!arms || !split) return null;
1054
+ return arms.map((a) => {
1055
+ const at = o + 1 + a.at, bodyAt = o + 1 + a.bodyAt, end = o + 1 + a.end;
1056
+ const pos = (p) => (s.start != null ? { start: s.start + p } : {});
1057
+ let kids = [];
1058
+ if (a.body.startsWith('{')) kids = read(bodyAt, blockEnd(text, bodyAt));
1059
+ else if (a.body) kids = braceStatements([{ text: a.body.replace(/,$/, ''), line: lineAtPos(bodyAt), endLine: lineAtPos(Math.max(bodyAt, end - 1)), ...(s.start != null ? { start: s.start + bodyAt, end: s.start + bodyAt + a.body.replace(/,$/, '').length } : {}) }], split);
1060
+ return { text: text.slice(at, end).trim(), arm: a.pattern, line: lineAtPos(at), endLine: lineAtPos(Math.max(at, end - 1)), ...pos(at), ...(s.start != null ? { end: s.start + end } : {}), inner: kids.length, children: kids };
1061
+ });
1062
+ };
599
1063
  let children = [], inner = 0;
600
1064
  const clauses = [];
1065
+ if (lit?.expr) {
1066
+ // An expression body (`useMemo(() => a * b, [a, b])`): the expression is the one thing it does.
1067
+ const [f, t] = lit.expr;
1068
+ const raw = text.slice(f, t);
1069
+ const lead = raw.length - raw.trimStart().length;
1070
+ const expr = raw.trim();
1071
+ if (expr) children = braceStatements([{ text: expr, line: lineAtPos(f + lead), endLine: lineAtPos(f + lead + expr.length - 1), ...(s.start != null ? { start: s.start + f + lead, end: s.start + f + lead + expr.length } : {}) }], split);
1072
+ inner = children.length;
1073
+ return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, fn: { depth: lit.depth, expr: true, after: text.slice(t) } };
1074
+ }
601
1075
  if (open >= 0) {
602
1076
  const end = blockEnd(text, open);
1077
+ if (!lit && ARMS_HEAD.test(head0)) {
1078
+ const arms = readArms(open, end);
1079
+ if (arms) return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner: arms.length, children: arms, arms: true };
1080
+ }
603
1081
  const body = end > open ? text.slice(open + 1, end) : '';
604
1082
  inner = body ? body.split(/;|\n/).filter((l) => l.trim() && !/^[{}]$/.test(l.trim())).length : 0;
605
1083
  children = read(open, end);
@@ -618,7 +1096,7 @@ export function braceStatements(stmts, split = null) {
618
1096
  pos = e + 1;
619
1097
  }
620
1098
  }
621
- return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...(clauses.length ? { clauses } : {}) };
1099
+ return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...(clauses.length ? { clauses } : {}), ...(lit ? { fn: { depth: lit.depth, after: text.slice(lit.close + 1) } } : {}) };
622
1100
  });
623
1101
  }
624
1102