@skillstech/thunderlang 0.5.8 → 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) {
@@ -242,11 +273,70 @@ function httpErrorOf(head) {
242
273
  return { kind: 'fail', says: `Fails with ${status} ${name}${msg ? `: "${msg}"` : ''}`, error: `${status} ${name}`, ...(msg ? { message: msg } : {}), status };
243
274
  }
244
275
 
276
+ /** Where a redirect goes, in words: '/login' stays a path, `${GOOGLE_AUTH_URL}?…` -> "the Google auth URL", url_for('home') -> "the home page". */
277
+ function redirectTarget(arg) {
278
+ const a = String(arg || '').trim().replace(/^(?:url|to|location|redirect_to)\s*=\s*/, '');
279
+ let m;
280
+ if ((m = a.match(/^(?:new\s+URL\(\s*)?["'`](\/[^"'`$?#]*|https?:\/\/[^"'`$/?#]+[^"'`$?#]*)/))) return m[1];
281
+ if ((m = a.match(/^`\$\{\s*([A-Za-z_][\w.]*)\s*\}/))) return `the ${words(m[1].split('.').pop()).replace(/\burl\b/i, 'URL')}`;
282
+ if ((m = a.match(/\b(?:url_for|reverse|route|url)\(\s*["']([\w.:-]+)["']/))) return `the ${words(m[1].split(/[.:]/).pop())} page`;
283
+ if ((m = a.match(/^([A-Za-z_][\w.]*)$/))) return `the ${words(m[1].split('.').pop()).replace(/\burl\b/i, 'URL')}`;
284
+ return 'another page';
285
+ }
286
+
287
+ /**
288
+ * A redirect: Fastify/Express `reply.redirect(url)` / `res.redirect(302, url)`, `Response.redirect(url)`,
289
+ * `NextResponse.redirect(...)`, Flask/Django/Next `redirect(url)`, `HttpResponseRedirect(url)`,
290
+ * FastAPI `RedirectResponse(url)`, Laravel `redirect()->route('home')`. Gives a step that says where the person goes.
291
+ */
292
+ function redirectOf(head) {
293
+ const isReturn = /^return\b/.test(head);
294
+ const expr = head.replace(/^return\s+/, '').replace(/^await\s+/, '').replace(/;\s*$/, '').trim();
295
+ let m = expr.match(/^(?:reply|res|response|resp|ctx|c)\s*\.\s*redirect\s*\(\s*(?:\d{3}\s*,\s*)?(.*)\)\s*$/)
296
+ || expr.match(/^(?:Response|NextResponse)\s*\.\s*redirect\s*\(\s*(.*?)\s*(?:,\s*\d{3}\s*)?\)\s*$/)
297
+ || expr.match(/^(?:HttpResponseRedirect|HttpResponsePermanentRedirect|RedirectResponse|redirect)\s*\(\s*(.*?)\s*(?:,\s*(?:\d{3}|status(?:_code)?\s*=\s*\d{3}|permanent\s*=\s*\w+)\s*)?\)\s*$/)
298
+ || expr.match(/^redirect\(\s*\)\s*->\s*(route\(.*\))\s*$/);
299
+ if (!m) return null;
300
+ const to = redirectTarget(m[1]);
301
+ return { kind: isReturn ? 'return' : 'call', says: `Sends the person to ${to}`, redirect: to };
302
+ }
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
+
245
329
  export function classifyStatement(raw, { inner = 0 } = {}) {
246
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
+ }
247
337
  // TypeScript-only syntax that changes nothing for a reader: casts, non-null assertions, optional calls.
248
- const head = text.split('\n')[0].trim()
249
- .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.')
250
340
  // Java/C# casts: ((JsonTreeReader) reader).promote() -> reader.promote(); (int) x -> x
251
341
  .replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, '$1').replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, '$1');
252
342
  const code = clip(head, 90);
@@ -254,10 +344,10 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
254
344
  const innerNote = inner ? ` (${inner} step${inner === 1 ? '' : 's'} inside)` : '';
255
345
  // One-line ifs: `if (x) return y;` and Ruby/Perl modifiers `return unless running?`, `notify if late`.
256
346
  let inl;
257
- 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])) {
258
348
  return { kind: 'branch', says: `If ${sayCodeCondition(inl[2])}`, cond: inl[2], code, inline: inl[3] };
259
349
  }
260
- 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])) {
261
351
  const cond = sayCodeCondition(inl[3]);
262
352
  return { kind: 'branch', says: inl[2] === 'unless' ? `If not: ${cond}` : `If ${cond}`, cond: inl[3], negate: inl[2] === 'unless', code, inline: inl[1] };
263
353
  }
@@ -265,7 +355,25 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
265
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 };
266
356
  // A function stored under a name: `ky.create = (opts) => ...` -> "Defines how ky's create works".
267
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 };
268
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 };
269
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 };
270
378
  if (/^default\s*(?::|->)/.test(head)) return { kind: 'check', says: 'Otherwise', code, caseLabel: true };
271
379
  // Failures
@@ -278,6 +386,9 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
278
386
  // An HTTP error response (4xx/5xx) is a Stop: the request is refused, with a status and a message.
279
387
  const httpFail = httpErrorOf(head);
280
388
  if (httpFail) return { ...httpFail, code };
389
+ // A redirect sends the person somewhere else: "Sends the person to the Google auth URL".
390
+ const redirect = redirectOf(head);
391
+ if (redirect) return { ...redirect, code };
281
392
  // Returns (Go/Rust error returns read as failures)
282
393
  if ((m = head.match(/^return\b\s*(.*)$/))) {
283
394
  const expr = stripTail(m[1]);
@@ -293,7 +404,11 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
293
404
  }
294
405
  const chain = sayChain(expr);
295
406
  if (chain) return { kind: 'return', says: `Returns ${chain}`, code };
296
- 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
+ }
297
412
  if (/^\(?\s*</.test(expr)) return { kind: 'return', says: 'Returns what to show on screen', code };
298
413
  const v = sayValue(expr) || sayWhether(expr);
299
414
  return { kind: 'return', says: v ? `Returns ${v}` : 'Returns a computed value', code, ...(v ? {} : { value: clip(expr, 60) }) };
@@ -303,6 +418,8 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
303
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*$/))) {
304
419
  return { kind: 'loop', says: `Counts ${words(m[1])} from ${clip(m[2], 20)}${m[3] ? ` while ${sayCodeCondition(m[3])}` : ''}${innerNote}`, code };
305
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 };
306
423
  // Pairs unpacked in a loop: for (const [key, value] of entries) / for key, value in items.items() / foreach ($a as $k => $v)
307
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*$/))) {
308
425
  const src = stripTail(m[3]).replace(/\($/, '()').replace(/^Object\.entries\((.+)\)$/, '$1').replace(/\.(?:items|entries)\(\)$/, '');
@@ -322,12 +439,13 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
322
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 };
323
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 }; }
324
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 };
325
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 };
326
444
  if (/^(?:try|begin)\b/.test(head)) return { kind: 'try', says: `Tries the next steps and handles any error${innerNote}`, code };
327
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 };
328
446
  if ((m = head.match(/^assert(?:_\w+|That|Equals|True|False|NotNull|Null)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
329
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 };
330
- 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 }; }
331
449
  if ((m = head.match(/^(?:using|lock|synchronized)\s*\((.+?)\)/))) return { kind: 'set', says: `Uses ${clip(m[1], 50)}`, code };
332
450
  if (/^defer\b/.test(head)) return { kind: 'call', says: `At the end, ${clip(head.replace(/^defer\s+/, ''), 60)}`, code };
333
451
  if (/^super\b/.test(head)) return { kind: 'call', says: 'Runs the parent version first', code };
@@ -372,7 +490,7 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
372
490
  const target = m[1].split(/\s*,\s*/).filter((t) => t !== '_').map(targetWords).join(', ') || targetWords(m[1]);
373
491
  const value = stripTail(m[3]);
374
492
  // A yes/no value: `ok = proxy and scheme != "https"` -> "Works out ok: whether proxy and scheme is not https".
375
- 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 };
376
494
  // self.max_books = max_books: the Thing keeps what it was given.
377
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 };
378
496
  const chain = value ? (sayPython(value) || sayChain(value)) : null;
@@ -425,6 +543,7 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
425
543
  const spanOf = (s) => ({ startLine: s.line, endLine: s.endLine ?? s.line, ...(s.start != null && s.end != null ? { start: s.start, end: s.end } : {}) });
426
544
 
427
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; };
428
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; };
429
548
  function asCall(list, i) {
430
549
  const st = list[i];
@@ -460,6 +579,184 @@ function attachClause(step, clause) {
460
579
  }
461
580
  }
462
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
+
463
760
  export function stepsFrom(statements) {
464
761
  const steps = [];
465
762
  const skipped = [];
@@ -468,6 +765,14 @@ export function stepsFrom(statements) {
468
765
  let into = null, intoAlways = false;
469
766
  for (const s of statements) {
470
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
+ }
471
776
  if (into && !CLAUSE.test(t0) && t0 && !/^(?:end\b|#)/.test(t0)) {
472
777
  const st = stepsFrom([s]).steps;
473
778
  into.push(...st);
@@ -488,7 +793,9 @@ export function stepsFrom(statements) {
488
793
  if (prev2 && (prev2.kind === 'branch' || prev2.kind === 'try')) {
489
794
  const prev = prev2;
490
795
  const kw = /^(?:elif|elsif|else\s+if)\b/.test(t0) ? 'elif' : /^else\b/.test(t0) ? 'else' : /^(?:finally|ensure)\b/.test(t0) ? 'finally' : 'catch';
491
- 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 });
492
799
  intoAlways = kw === 'finally';
493
800
  into = s.children?.length ? null : kw === 'catch' ? prev.handlers?.[prev.handlers.length - 1]?.steps ?? null : kw === 'finally' ? prev.always?.steps ?? null : null;
494
801
  prev.span = { ...prev.span, endLine: Math.max(prev.span.endLine, s.endLine ?? s.line) };
@@ -497,24 +804,68 @@ export function stepsFrom(statements) {
497
804
  skipped.push(spanOf(s));
498
805
  continue;
499
806
  }
500
- 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; }
501
808
  if (/^(?:"""|'''|r"""|\/\*\*|\*)/.test(t0)) { skipped.push(spanOf(s)); continue; } // docstrings and doc comments
502
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; }
503
- 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
+ }
504
847
  // A one-line `if (x) return reply.code(400).send({ error: 'bad' })` is one statement: its braces belong to the
505
848
  // object being sent, not to a block, so read the statement after the condition instead of the braces' inside.
506
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; }
507
- 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))) {
508
851
  const kids = stepsFrom(s.children).steps;
509
- 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
+ }
510
858
  }
511
859
  if (step.inline && !step.children) { const kid = classifyStatement(step.inline); step.children = [{ ...kid, line: s.line, span: spanOf(s) }]; delete step.inline; }
512
860
  else delete step.inline;
513
- 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);
514
863
  steps.push(step);
515
864
  }
516
865
  // A bare word is only a returned value when it is the last statement; before that it is a call (Ruby: `rollback`).
517
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); }
518
869
  // Every step is kept (anchoring needs all of them); `more` tells a view how many to fold away.
519
870
  const more = Math.max(0, steps.length - MAX_STEPS);
520
871
  for (const st of steps) if (restates(st)) st.restates = true;
@@ -529,7 +880,7 @@ const GENERIC_CALLS = /^(?:get|set|run|do|call|apply|handle|process|execute|exec
529
880
  function restates(st) {
530
881
  const s = st.says || '';
531
882
  if (st.kind === 'other') return false;
532
- if (/^Works out [^:]+$/.test(s) && !/ from /.test(s)) return true;
883
+ if (/^Works out [^:]+$/.test(s) && !/ from | remembers it/.test(s)) return true;
533
884
  const same = s.match(/^Works out (.+) from (.+)$/);
534
885
  if (same && same[1].trim() === same[2].trim()) return true; // "Works out licence from licence"
535
886
  if (/^(Returns a computed value|Returns a value|Sets .+ to a computed value)$/.test(s)) return true;
@@ -549,26 +900,184 @@ const blockEnd = (text, open) => {
549
900
  return -1;
550
901
  };
551
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
+
552
1025
  /**
553
1026
  * Statements of a brace body, each with its whole block read (every depth), and every clause that follows the first
554
- * 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.
555
1030
  */
556
1031
  export function braceStatements(stmts, split = null) {
557
1032
  return stmts.map((s) => {
558
1033
  const text = s.text;
559
- 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('{');
560
1037
  const lineAtPos = (pos) => s.line + (text.slice(0, pos).match(/\n/g) || []).length;
561
1038
  const read = (o, e) => {
562
- const body = e > o ? text.slice(o + 1, e) : '';
563
- 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;
564
1045
  if (!body || !split) return [];
565
- 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 } : {}) }));
566
1047
  return braceStatements(kids, split);
567
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
+ };
568
1063
  let children = [], inner = 0;
569
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
+ }
570
1075
  if (open >= 0) {
571
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
+ }
572
1081
  const body = end > open ? text.slice(open + 1, end) : '';
573
1082
  inner = body ? body.split(/;|\n/).filter((l) => l.trim() && !/^[{}]$/.test(l.trim())).length : 0;
574
1083
  children = read(open, end);
@@ -587,7 +1096,7 @@ export function braceStatements(stmts, split = null) {
587
1096
  pos = e + 1;
588
1097
  }
589
1098
  }
590
- 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) } } : {}) };
591
1100
  });
592
1101
  }
593
1102