@skillstech/thunderlang 0.5.11 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +437 -0
  2. package/dist/core.cjs +30431 -7604
  3. package/dist/index.cjs +28577 -5331
  4. package/dist/learn.cjs +22676 -3870
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +48 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +59 -12
  34. package/src/model.mjs +462 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1015 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
package/src/steps.mjs CHANGED
@@ -1,10 +1,112 @@
1
+ import { sayLibraryCall } from './libraries.mjs';
2
+ import { splitLogic, wrapped, accountsFor, asCodeWords, isCodeWords, closeOf, balancedText } from './faithful.mjs';
3
+ import { parseStatement, parseExpr } from './meaning.mjs';
1
4
  // Steps: read any function as a short list of plain steps (check, branch, loop, set, call, return, fail).
2
5
  // Decisions become rules; everything else becomes steps. Deterministic and pattern-based, like the rest of
3
6
  // the reader: a statement it does not recognize is kept as `other` with its original text, never guessed.
4
7
  export const STEPS_SCHEMA = 'thunder-steps-v1';
5
8
  const MAX_STEPS = 14;
6
9
 
7
- const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
10
+ // The language being read, for the few shapes that mean different things in different languages (C's `p->x` is a
11
+ // field; Java's `x->y` is a lambda). Set only for the length of one reading (see withLanguage); null otherwise.
12
+ let LANG = null;
13
+ const C_FAMILY = new Set(['c', 'cpp']);
14
+ /** Run `fn` with the reader's language set, so C, C++, and Swift shapes are read the way that language means them. */
15
+ export function withLanguage(language, fn) {
16
+ const before = LANG;
17
+ LANG = language || null;
18
+ try { return fn(); } finally { LANG = before; }
19
+ }
20
+
21
+ // Names become words (deliveryFee, delivery_fee -> "delivery fee"); text inside quotes is never changed.
22
+ const wordsPlain = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase();
23
+ const words = (s) => {
24
+ const t = String(s);
25
+ if (!/["'`]/.test(t)) return wordsPlain(t).trim();
26
+ let out = '', last = 0;
27
+ for (const m of t.matchAll(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g)) { out += wordsPlain(t.slice(last, m.index)) + m[0]; last = m.index + m[0].length; }
28
+ return (out + wordsPlain(t.slice(last))).trim();
29
+ };
30
+ /**
31
+ * True unless the value goes on past its first call in a way that changes what it is: `isObject(s) || t ? a : b`
32
+ * is not "worked out from is object". A chain (`a.b().c()`) or a call cut at the end of its line still counts.
33
+ */
34
+ function wholeValueCall(value) {
35
+ const e = String(value).trim().replace(/;$/, '');
36
+ const at = e.search(/[\w$>\]]\s*\(/);
37
+ if (at < 0) return true;
38
+ const close = closeOf(e, e.indexOf('(', at));
39
+ if (close < 0) return true;
40
+ const rest = e.slice(close + 1).trim();
41
+ return !rest || /^(?:\.|\?\.|!\.|\)|\.Error\b)/.test(rest) && !/(?:&&|\|\||\s\?\s|[=!<>]=|\s[<>]\s)/.test(rest.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, 'Q'));
42
+ }
43
+
44
+ /**
45
+ * `a || b` / `a or b` / `a ?? b` as a value: "a, or b when that has no value". Null when the value is not a
46
+ * fallback; false when it is one whose parts cannot all be said (it must then be shown as code, never as just a).
47
+ */
48
+ function fallbackWords(value) {
49
+ const v = String(value).trim();
50
+ if (!/\|\||\bor\b|\?\?/.test(v)) return null;
51
+ const parts = splitFallback(v);
52
+ if (!parts) return null;
53
+ const said = parts.terms.map((t) => sayValue(t) ?? sayArithmetic(t) ?? (/^\$?[\w$]+(?:\.[\w$]+)*$/.test(t) ? possessiveWords(t) : null));
54
+ if (said.some((x) => x == null)) return false;
55
+ return said.reduce((acc, x, i) => (i ? `${acc}, or ${x} when that has no value` : x), '');
56
+ }
57
+ function splitFallback(v) {
58
+ const out = [];
59
+ let d = 0, from = 0, op = null;
60
+ for (let i = 0; i < v.length; i++) {
61
+ const c = v[i];
62
+ if (c === '"' || c === "'" || c === '`') { const q = c; for (i++; i < v.length && v[i] !== q; i++) if (v[i] === '\\') i++; continue; }
63
+ if ('([{'.includes(c)) d++; else if (')]}'.includes(c)) d--;
64
+ if (d) continue;
65
+ let len = 0;
66
+ if ((c === '|' && v[i + 1] === '|') || (c === '?' && v[i + 1] === '?')) len = 2;
67
+ else if (c === ' ' && /^ or (?=\S)/.test(v.slice(i, i + 5))) len = 4;
68
+ else if (c === '&' && v[i + 1] === '&') return null;
69
+ else if (c === ' ' && /^ and /.test(v.slice(i, i + 5))) return null;
70
+ else if (c === '?' && v[i + 1] === ' ') return null;
71
+ else if (/[=!<>]/.test(c) && (v[i + 1] === '=' || /[<>]/.test(c))) return null;
72
+ if (len) { out.push(v.slice(from, i).trim()); from = i + len; i += len - 1; op = true; }
73
+ }
74
+ if (!op) return null;
75
+ out.push(v.slice(from).trim());
76
+ return out.every(Boolean) ? { terms: out } : null;
77
+ }
78
+
79
+ /** Top-level arguments of a call's argument text: "a, f(b, c), d" -> ['a', 'f(b, c)', 'd']. */
80
+ function splitTopArgs(t) {
81
+ const out = [];
82
+ let d = 0, from = 0;
83
+ for (let i = 0; i < t.length; i++) {
84
+ const c = t[i];
85
+ if (c === '"' || c === "'" || c === '`') { const q = c; for (i++; i < t.length && t[i] !== q; i++) if (t[i] === '\\') i++; continue; }
86
+ if ('([{'.includes(c)) d++; else if (')]}'.includes(c)) d--;
87
+ else if (c === ',' && d === 0) { out.push(t.slice(from, i).trim()); from = i + 1; }
88
+ }
89
+ if (t.slice(from).trim()) out.push(t.slice(from).trim());
90
+ return out;
91
+ }
92
+ /**
93
+ * The first quoted text in a statement, whole: a quote of one kind closes only at the same kind, so
94
+ * 'The `ky.retry()` options' is never cut at its inner backtick. Long text is shortened visibly with "…".
95
+ */
96
+ function firstText(text, n = 60) {
97
+ const s = String(text);
98
+ for (let i = 0; i < s.length; i++) {
99
+ const q = s[i];
100
+ if (q !== '"' && q !== "'" && q !== '`') continue;
101
+ let j = i + 1, out = '';
102
+ for (; j < s.length && s[j] !== q; j++) { if (s[j] === '\\' && j + 1 < s.length) { out += s[j + 1] === q ? q : s[j] + s[j + 1]; j++; } else out += s[j]; }
103
+ if (j >= s.length) return null;
104
+ if (!out.trim()) { i = j; continue; }
105
+ if (q === '`') out = out.replace(/\$\{[^}]*\}/g, '…');
106
+ return out.length > n ? `${out.slice(0, n - 1).trimEnd()}…` : out;
107
+ }
108
+ return null;
109
+ }
8
110
  const clip = (s, n = 70) => { const t = String(s).replace(/\s+/g, ' ').trim(); return t.length > n ? `${t.slice(0, n - 1)}…` : t; };
9
111
  const stripTail = (s) => String(s).trim().replace(/[;{]\s*$/, '').replace(/:\s*$/, '').trim();
10
112
 
@@ -15,19 +117,139 @@ const KNOWN_CALLS = [
15
117
  { re: /^(?:send_?email|sendMail|mailer\.\w+|smtp\.\w+)$/i, say: () => 'Sends an email' },
16
118
  { re: /^(?:db|database|repo|repository|session|conn|cursor)\.(?:insert|save|add|create|update|execute|exec|query|delete|remove|commit)\w*$/i, say: (m) => `Writes to the database (${m.split('.').pop()})` },
17
119
  { re: /^(?:events?|bus|publisher|emitter|queue)\.(?:publish|emit|send|enqueue|push)$/i, say: () => 'Announces an event' },
18
- { re: /^(?:log|logger|console|logging|fmt|Log|System\.out|println|print|puts|echo|printf)\b/i, say: () => 'Writes a log or message' },
120
+ { re: /^(?:log|logger|console|logging|fmt|Log|System\.out|println|print|puts|echo|printf|fprintf|fputs|perror|NSLog|os_log|debugPrint|syslog|std\.(?:cout|cerr|print|println))\b/i, say: () => 'Writes a log or message' },
19
121
  ];
20
122
 
21
123
  /** entry['easy'] -> "the entry's easy"; $x->y -> "the x's y"; plain names as words. */
22
- const possessiveWords = (path) => { const parts = String(path).replace(/^\$/, '').replace(/\[\s*['"]?([\w$]+)['"]?\s*\]/g, '.$1').split(/\.|->/).filter((x) => x && !/^(self|this)$/.test(x)); return parts.length > 1 ? `the ${words(parts[parts.length - 2])}'s ${words(parts[parts.length - 1])}` : words(parts[0] || path); };
124
+ const possessiveWords = (path) => {
125
+ if ((C_FAMILY.has(LANG) || LANG === 'swift') && /\[/.test(String(path)) && !/\[\s*['"]/.test(String(path))) return indexedWords(String(path).replace(/->/g, '.'));
126
+ return possessivePlain(path);
127
+ };
128
+ /** A path with an index in it, owners kept: `c.argv[j].ptr` -> "the ptr of c.argv[j]", `c.argv[1]` -> "the 1 entry in c.argv". */
129
+ function indexedWords(p) {
130
+ const t = p.replace(/^(?:self|this)\./, '');
131
+ let m;
132
+ if ((m = t.match(/^(.*\])\.([A-Za-z_]\w*)$/))) return `the ${words(m[2])} of ${m[1]}`;
133
+ if ((m = t.match(/^([\w.]+)\[\s*([^\[\]]+?)\s*\]$/))) return `the ${m[2]} entry in ${m[1].includes('.') ? possessivePlain(m[1]) : words(m[1])}`;
134
+ return possessivePlain(p);
135
+ }
136
+ const possessivePlain = (path) => { const parts = String(path).replace(/^\$/, '').replace(/\[\s*['"]?([\w$]+)['"]?\s*\]/g, '.$1').split(/\.|->/).filter((x) => x && !/^(self|this)$/.test(x)); return parts.length > 1 ? `the ${words(parts[parts.length - 2])}'s ${words(parts[parts.length - 1])}` : words(parts[0] || path); };
23
137
 
24
138
  /** Enum values read as words: Status.ON_SHELF -> "on shelf", Color.RED -> "red". */
25
- export const plainEnums = (text) => String(text).replace(/\b[A-Z][A-Za-z0-9]*\.([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*)\b(?!\s*\()/g, (m, v) => (v.length > 1 && v === v.toUpperCase() ? words(v) : m));
139
+ // (Constants of the number and text classes are not choices: `Integer.TYPE`, `Long.MAX_VALUE` stay as written.)
140
+ export const plainEnums = (text) => String(text).replace(/\b([A-Z][A-Za-z0-9]*)\.([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*)\b(?!\s*\()/g, (m, owner, v) => (v.length > 1 && v === v.toUpperCase() && !/^(?:Integer|Long|Short|Byte|Float|Double|Character|Boolean|Void|Number|Math|BigInteger|BigDecimal|Int|UInt|Char)$/.test(owner) ? words(v) : m));
26
141
 
27
142
  /** A condition as words when it can't be fully translated: c.ctx == nil -> "c.ctx is empty". */
143
+ /**
144
+ * Request and settings idioms in words, before anything else touches them: req.headers['x-admin-secret'] -> "the
145
+ * x-admin-secret header", process.env.ADMIN_SECRET -> "the ADMIN_SECRET setting", req.query.force -> "the force in
146
+ * the address", req.body.email -> "the email it was sent". The names inside are kept exactly as written.
147
+ */
148
+ export function requestIdioms(text) {
149
+ return String(text)
150
+ .replace(/\b(?:req|request|ctx\.request|c\.req|ctx\.req|event)\s*\.\s*headers\s*(?:\[\s*['"`]([^'"`]+)['"`]\s*\]|\.\s*get\(\s*['"`]([^'"`]+)['"`]\s*\)|\.\s*([A-Za-z_][\w]*))/g, (m, a, b, c) => `the ${a || b || c} header`)
151
+ .replace(/\b(?:req|request|c)\s*\.\s*(?:header|get|Header|GetHeader)\(\s*['"`]([^'"`]+)['"`]\s*\)/g, (m, a) => `the ${a} header`)
152
+ .replace(/\b(?:req|request|ctx\.request|ctx|c\.req)\s*\.\s*(?:query|searchParams|params|args)\s*(?:\.\s*get\(\s*['"`]([^'"`]+)['"`]\s*\)|\[\s*['"`]([^'"`]+)['"`]\s*\]|\.\s*([A-Za-z_][\w]*))/g, (m, a, b, c) => `the ${a || b || c} in the address`)
153
+ .replace(/\b(?:req|request|ctx\.request)\s*\.\s*(?:body|json|form)\s*(?:\[\s*['"`]([^'"`]+)['"`]\s*\]|\.\s*([A-Za-z_][\w]*))/g, (m, a, b) => `the ${a || b} it was sent`)
154
+ .replace(/\bprocess\s*\.\s*env\s*(?:\.\s*([A-Za-z_][\w]*)|\[\s*['"`]([^'"`]+)['"`]\s*\])/g, (m, a, b) => `the ${a || b} setting`)
155
+ .replace(/\bos\s*\.\s*(?:environ\s*\[\s*['"]([^'"]+)['"]\s*\]|environ\.get\(\s*['"]([^'"]+)['"][^)]*\)|getenv\(\s*['"]([^'"]+)['"][^)]*\))/g, (m, a, b, c) => `the ${a || b || c} setting`)
156
+ .replace(/\b(?:System\.getenv|Environment\.GetEnvironmentVariable|os\.Getenv|std::env::var|ENV\.fetch)\(\s*["']([^"']+)["'][^)]*\)|\bENV\[\s*["']([^"']+)["']\s*\]/g, (m, a, b) => `the ${a || b} setting`);
157
+ }
158
+
159
+ /**
160
+ * A code condition in words, checked by the faithfulness gate: split at its top-level and / or, each part said on
161
+ * its own, and each part's words must keep that part's negations and comparisons. When they do not, the whole
162
+ * condition is given back as code in backticks (`isCodeWords`), which every view shows as "not explained".
163
+ */
28
164
  export function sayCodeCondition(cond) {
165
+ let raw = String(cond).replace(/\s+/g, ' ').trim().replace(/\s*(\{|:|\bthen|\bdo)\s*$/, '').trim();
166
+ while (wrapped(raw)) raw = raw.slice(1, -1).trim();
167
+ const said = sayLogic(raw, 0);
168
+ if (said == null || said.length > 260) return asCodeWords(raw);
169
+ return said;
170
+ }
171
+
172
+ function sayLogic(text, depth) {
173
+ let t = String(text).trim();
174
+ while (wrapped(t)) t = t.slice(1, -1).trim();
175
+ if (!t || depth > 6) return null;
176
+ const parts = splitLogic(t);
177
+ if (!parts) return null;
178
+ if (parts.terms.length === 1) return sayAtom(t);
179
+ const said = [];
180
+ for (const term of parts.terms) {
181
+ const inner = wrapped(term) && splitLogic(term.slice(1, -1))?.terms.length > 1 ? sayLogic(term, depth + 1) : sayAtom(term);
182
+ if (inner == null) return null;
183
+ said.push(wrapped(term) && splitLogic(term.slice(1, -1))?.terms.length > 1 ? `(${inner})` : inner);
184
+ }
185
+ return said.reduce((acc, s, i) => (i ? `${acc} ${parts.ops[i - 1]} ${s}` : s), '');
186
+ }
187
+
188
+ /** One condition with no top-level and / or, in words, or null when the words would not keep what the code says. */
189
+ function sayAtom(atom) {
190
+ const a = String(atom).trim();
191
+ if (/^(?:!|not\s+)\s*\(/.test(a) && wrapped(a.replace(/^(?:!|not\s+)\s*/, ''))) {
192
+ // not (a or b): the group in words, with "not" in front of it.
193
+ const inner = sayLogic(a.replace(/^(?:!|not\s+)\s*/, ''), 1);
194
+ return inner == null ? null : `not (${inner})`;
195
+ }
196
+ const said = sayAtomWords(a);
197
+ // (C and C++ write the empty pointer as NULL or nullptr: for the gate it is null, so `p != nullptr` is "p is set".)
198
+ // (`!strcmp(a, b)` and `strcmp(a, b) == 0` ask whether a is b; the reader says them that way.)
199
+ const gated = C_FAMILY.has(LANG) ? a.replace(/\b(?:nullptr|NULL)\b/g, 'null').replace(/(!\s*)?\b(?:strcmp|strcasecmp|strncmp|strncasecmp)\(\s*([^,()]+?)\s*,\s*([^,()]+?)\s*(?:,[^()]*)?\)(\s*(==|!=)\s*0\b)?/g, (all, neg, x, y, cmp, op) => (neg || op === '==' ? `${x} == ${y}` : `${x} != ${y}`)) : a;
200
+ // The words are checked against the condition's tree when it parses (exact operators, no strings or comments in
201
+ // the way); otherwise against the text.
202
+ if (said == null || isCodeWords(said) || !accountsFor(gated, said, parseExpr(gated, readingLanguage()))) return null;
203
+ return said;
204
+ }
205
+
206
+ /** True when `request` here is a web framework's request (so `request.body.x` is a field it was sent). */
207
+ function webRequest() {
208
+ const ps = FN_CONTEXT?.params;
209
+ if (!ps) return true;
210
+ if (FN_CONTEXT.route) return true;
211
+ if (!ps.some((p) => /^(?:req|request)$/.test(p.name))) return true;
212
+ return ps.some((p) => /^(?:res|reply|response|ctx|c|next)$/.test(p.name) || /HttpRequest|ServerRequest|FastifyRequest|NextRequest|HttpServletRequest|Express|Koa/.test(String(p.type || '')));
213
+ }
214
+
215
+ function sayAtomWords(cond) {
216
+ if (!webRequest()) return sayCodeConditionInner(cond);
217
+ // Keep request and settings names exactly as written (x-admin-secret, ADMIN_SECRET) while the rest becomes words.
218
+ const kept = [];
219
+ const keep = (t) => `\u0000${kept.push(t) - 1}\u0000`;
220
+ const restore = (t) => String(t).replace(/\u0000(\d+)\u0000/g, (m, i) => kept[Number(i)]);
221
+ const idioms = requestIdioms(String(cond)).replace(/the [^\u0000]*? (?:header|setting|in the address|it was sent)(?=$|[\s)!=<>&|,;])/g, (m) => keep(m));
222
+ if (idioms !== String(cond)) return restore(sayCodeConditionInner(idioms).replace(/'([^']*)'/g, '"$1"'));
223
+ return sayCodeConditionInner(cond);
224
+ }
225
+
226
+ // `typeof x === 'string'` -> "x is text": what a reader means by each JavaScript type name.
227
+ const TYPEOF_WORDS = { string: 'text', number: 'a number', boolean: 'a true/false value', function: 'a function', object: 'an object', undefined: 'undefined', bigint: 'a big number', symbol: 'a symbol' };
228
+ // PHP's type checks: is_string($x) -> "x is text".
229
+ const PHP_IS = { is_string: 'text', is_array: 'an array', is_int: 'a whole number', is_integer: 'a whole number', is_float: 'a decimal number', is_numeric: 'a number', is_bool: 'a true/false value', is_object: 'an object', is_callable: 'callable', is_resource: 'a resource', is_iterable: 'iterable', is_scalar: 'a single value' };
230
+
231
+ function sayCodeConditionInner(cond) {
232
+ let ty0;
29
233
  let c = plainEnums(String(cond)).trim().replace(/\s*(\{|:|then|do)\s*$/, '').trim();
234
+ if (C_FAMILY.has(LANG)) {
235
+ c = cNormalize(c).replace(/'\\0'/g, 'the end of the text');
236
+ // C text comparison: `strcmp(a, b) == 0` and `!strcmp(a, b)` are "a is b"; `strcmp(a, b)` alone is "a is not b".
237
+ c = c.replace(/(!\s*)?\b(?:strcmp|strcasecmp|strncmp|strncasecmp)\(\s*([^,()]+?)\s*,\s*([^,()]+?)\s*(?:,[^()]*)?\)(\s*(==|!=)\s*0\b)?/g, (all, neg, a, b, cmp, op) => (neg || op === '==' ? `${a} == ${b}` : op === '!=' || !cmp ? `${a} != ${b}` : all));
238
+ }
239
+ // Swift `T.self is String.Type` asks whether the type T is String.
240
+ if (LANG === 'swift' && (ty0 = String(c).match(/^([A-Za-z_]\w*)\.self\s+is\s+([A-Za-z_][\w.]*)\.Type$/))) return `${ty0[1]} is the type ${ty0[2]}`;
241
+ if (LANG === 'swift') c = c.replace(/(^|[\s(!=<>])\.([a-z]\w*)\b(?!\s*\()/g, (m0, pre, v) => `${pre}${words(v)}`); // .onShelf -> on shelf
30
242
  while (c.startsWith('(') && matchingClose(c, 0) === c.length - 1) c = c.slice(1, -1).trim();
243
+ let ty;
244
+ // Yoda order (`false === f(x)`, `null != y`): the value being checked first.
245
+ if ((ty = c.match(/^(true|false|null|nil|None|undefined|-?\d+(?:\.\d+)?|"[^"]*"|'[^']*')\s*(===?|!==?)\s*([^=!<>&|?]+)$/)) && !/^(?:true|false|null|nil|None|undefined|-?\d|["'])/.test(ty[3].trim())) c = `${ty[3].trim()} ${ty[2]} ${ty[1]}`;
246
+ if (c === 'super') return 'the parent version says yes';
247
+ if ((ty = c.match(/^typeof\s+([\w$.]+)\s*(===?|!==?)\s*["'](\w+)["']$/)) && TYPEOF_WORDS[ty[3]]) return `${possessiveWords(ty[1])} is ${/^!/.test(ty[2]) ? 'not ' : ''}${TYPEOF_WORDS[ty[3]]}`;
248
+ if ((ty = c.match(/^(!|not\s+)?\\?(is_\w+)\(\s*\$?([\w$.\[\]'">-]+)\s*\)$/)) && PHP_IS[ty[2]]) return `${possessiveWords(ty[3])} is ${ty[1] ? 'not ' : ''}${PHP_IS[ty[2]]}`;
249
+ // `x instanceof Foo` / `x is Foo` (Kotlin, C#) / isinstance(x, Foo): "x is a Foo".
250
+ if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.]+)\s+instanceof\s+([\w$.\\]+)\s*\)?$/))) return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}a ${ty[3].split(/[.\\]/).pop()}`;
251
+ if ((ty = c.match(/^([\w$.]+)\s+(is|!is)\s+([A-Z][\w.<>?]*)$/)) && !/^(?:True|False|None|Null|Nil|NULL)$/.test(ty[3])) return `${possessiveWords(ty[1])} is ${ty[2] === '!is' ? 'not ' : ''}a ${ty[3].split('.').pop()}`;
252
+ if ((ty = c.match(/^(not\s+)?isinstance\(\s*([\w.]+)\s*,\s*\(?\s*([\w.]+(?:\s*,\s*[\w.]+)*)\s*\)?\s*\)$/))) { const kinds = ty[3].split(/\s*,\s*/).map((x) => x.split('.').pop()); return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}${kinds.length > 1 ? `one of ${kinds.join(', ')}` : `a ${kinds[0]}`}`; }
31
253
  // A bare yes/no property reads as a sentence: `order.refunded` -> "order is refunded", `!user.isAdmin` -> "user is not admin".
32
254
  const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
33
255
  const plural = (w, call) => !call && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
@@ -41,7 +263,8 @@ export function sayCodeCondition(cond) {
41
263
  }
42
264
  // Ruby predicates: `running?` -> "it is running", `order.paid?` -> "order is paid".
43
265
  let pred;
44
- if ((pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/))) return `${pred[2] ? words(pred[2]) : 'it'} is ${pred[1] ? 'not ' : ''}${words(pred[3])}`;
266
+ // A name that is itself negative (`not_found?`) keeps its words joined, so "not found" is never flipped into "found".
267
+ if ((pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/))) return `${pred[2] ? words(pred[2]) : 'it'} is ${pred[1] ? 'not ' : ''}${words(pred[3]).replace(/^(not|no|non) /, '$1-')}`;
45
268
  // How many: count($a) / len(a) / a.length / a.Count / a.size() -> "how many a".
46
269
  c = c.replace(/\\?\b(?:count|len|sizeof)\(\s*\$?([\w$.\[\]'">-]+)\s*\)/g, (m0, x) => `how many ${possessiveWords(x)}`)
47
270
  .replace(/\b([\w$]+(?:\.[\w$]+)*)\.(?:length|Length|Count|count\(\)|size\(\)|len\(\))(?![\w(])/g, (m0, x) => `how many ${possessiveWords(x)}`);
@@ -51,11 +274,18 @@ export function sayCodeCondition(cond) {
51
274
  if ((call = c.match(/^(!|not\s+)?(empty|isset|is_null)\(\s*\$?([\w$.\[\]'">-]+)\s*\)$/))) {
52
275
  const neg = !!call[1] !== (call[2] === 'isset');
53
276
  const what = possessiveWords(call[3]);
54
- return call[2] === 'isset' || call[2] === 'is_null' ? `${what} is ${(call[2] === 'isset') === !call[1] ? '' : 'not '}set` : `${what} is ${neg ? 'not ' : ''}empty`;
277
+ if (call[2] === 'is_null') return `${what} is ${call[1] ? 'not ' : ''}null`;
278
+ return call[2] === 'isset' ? `${what} is ${call[1] ? 'not ' : ''}set` : `${what} is ${neg ? 'not ' : ''}empty`;
279
+ }
280
+ // isObject(x) -> "x is object"; !isRequest(options.request) -> "the options's request is not request".
281
+ if ((call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?is_?([A-Z]\w*)\s*\(\s*([\w$.]+)\s*\)$/)) && !/^(?:Empty|Set|Null)$/.test(call[2])) {
282
+ return `${possessiveWords(call[3])} is ${call[1] ? 'not ' : ''}${words(call[2])}`;
55
283
  }
56
284
  if ((call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?((?:is|has|can|should|was|are|does)[A-Z_]\w*)\s*\([^()]*\)$/))) {
57
285
  const w = words(call[2]);
58
- return call[1] ? `not: ${w}` : w;
286
+ // "not: " is kept for `unless` (it flips the whole question); a negated call says its own "not".
287
+ if (!call[1]) return w;
288
+ return w.replace(/^(is|was|are|should|has|can|does) /, (m0, v) => ({ has: 'does not have ', can: 'cannot ', does: 'does not ' }[v] ?? `${v} not `));
59
289
  }
60
290
  // A plain name or property path used as a yes/no: `if proxy` -> "proxy is set"; `not url.host` -> "the url's host is not set".
61
291
  const bare = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
@@ -64,18 +294,26 @@ export function sayCodeCondition(cond) {
64
294
  const what = parts.length > 1 ? `the ${words(parts[0])}'s ${words(parts[1])}` : words(parts[0]);
65
295
  return `${what} is ${bare[1] ? 'not ' : ''}set`;
66
296
  }
67
- return clip(c
68
- .replace(/\s*(===|==)\s*(nil|null|None|undefined|""|'')(?=\s|\)|$)/g, ' is empty')
297
+ // (C, C++, Swift: quoted text is kept exactly while the operators around it become words: "lie in between" stays.)
298
+ const quotes = [];
299
+ if (C_FAMILY.has(LANG) || LANG === 'swift') c = c.replace(/"(?:\\.|[^"\\])*"/g, (q) => `\u0001${quotes.push(q) - 1}\u0001`);
300
+ return conditionOperatorWords(c).replace(/\u0001(\d+)\u0001/g, (m0, i) => quotes[Number(i)]);
301
+ }
302
+ function conditionOperatorWords(c) {
303
+ return c
304
+ // Strict equality keeps null and undefined apart (a reader must be able to tell `=== null` from `=== undefined`).
305
+ .replace(/\s*===\s*(null|undefined)(?=\s|\)|$)/g, ' is $1').replace(/\s*!==\s*(null|undefined)(?=\s|\)|$)/g, ' is not $1')
306
+ .replace(/\s*(?<!!)(===|==)\s*(nil|null|None|undefined|NULL|nullptr|""|'')(?=\s|\)|$)/g, ' is empty')
69
307
  .replace(/\s*(!==|!=)\s*(""|'')(?=\s|\)|$)/g, ' is not empty')
70
- .replace(/\s*(!==|!=)\s*(nil|null|None|undefined)\b/g, ' is set')
308
+ .replace(/\s*(!==|!=)\s*(nil|null|None|undefined|NULL|nullptr)\b/g, ' is set')
71
309
  .replace(/\bis not None\b/g, 'is set').replace(/\bis None\b/g, 'is empty')
72
- .replace(/\s*(===|==)\s*/g, ' is ').replace(/\s*(!==|!=)\s*/g, ' is not ')
310
+ .replace(/\s*(!==|!=)\s*/g, ' is not ').replace(/\s*(===|==)\s*/g, ' is ')
73
311
  .replace(/\s*&&\s*/g, ' and ').replace(/\s*\|\|\s*/g, ' or ')
74
312
  // Membership: `book not in student.books` -> "book is not in student.books".
75
313
  .replace(/\s+not\s+in\s+/g, ' is not in ').replace(/(?<!\bis(?: not)?)\s+in\s+(?=[\w$])/g, ' is in ')
76
314
  // Comparisons as words; `->` and `=>` are never comparisons.
77
315
  .replace(/\s+<=\s+/g, ' is at most ').replace(/\s+>=\s+/g, ' is at least ').replace(/\s+<\s+/g, ' is less than ').replace(/(?<![-=])\s+>\s+/g, ' is more than ')
78
- .replace(/(^|[\s(])!(?=[\w(])/g, '$1not ').replace(/\s+/g, ' '), 70);
316
+ .replace(/(^|[\s(])!(?=[\w(])/g, '$1not ').replace(/\s+/g, ' ').trim();
79
317
  }
80
318
  function matchingClose(str, open) {
81
319
  let depth = 0;
@@ -85,16 +323,27 @@ function matchingClose(str, open) {
85
323
  const lastWords = (path) => words(String(path).split('.').pop());
86
324
  /** "cmd.commandCalledAs.called" -> "called on command called as"; "this.count" -> "count". */
87
325
  function targetWords(path) {
326
+ // (C, C++, Swift: an index keeps its place, `events[i].mask` is "the mask of events[i]", never just "events".)
327
+ if ((C_FAMILY.has(LANG) || LANG === 'swift') && /\[[^\]]*\]\s*(?:\.|->)/.test(String(path))) return indexedWords(String(path).replace(/->/g, '.'));
88
328
  const parts = String(path).replace(/^[@$]+/, '').replace(/#/g, '').replace(/\[.*$/, '').split('.').filter((p) => !/^(this|self)$/.test(p));
89
329
  if (parts.length <= 1) return words(parts[0] || path);
90
330
  return `the ${words(parts[parts.length - 2])}'s ${words(parts[parts.length - 1])}`;
91
331
  }
92
332
 
93
333
  function callee(text) {
94
- const m = String(text).replace(/\[[^\]]*\]/g, '').match(/^(?:await\s+|try\s+|yield\s+|void\s+)?(?:new\s+)?([A-Za-z_$#@][\w$#]*(?:<[^()]*?>)?(?:(?:\.|::|->)[A-Za-z_$#][\w$#]*(?:<[^()]*?>)?(?:\(\))?)*)!?\s*\(/);
95
- return m ? m[1].replace(/<[^()]*?>/g, '').replace(/\(\)/g, '').replace(/::|->/g, '.').replace(/#/g, '') : null;
334
+ const m = String(text).replace(/\[[^\]]*\]/g, '').match(/^(?:(?:await|try[?!]?|yield|void)\s+)*(?:new\s+)?([A-Za-z_$#@][\w$#]*(?:<[^()]*?>)?(?:(?:\.|::|->)[A-Za-z_$#][\w$#]*(?:<[^()]*?>)?(?:\(\))?)*)!?\s*\(/);
335
+ if (!m) return null;
336
+ let name = m[1];
337
+ // Template arguments, innermost first, so `unique_ptr<typed_node<T>>` is `unique_ptr` (not `unique_ptr>`).
338
+ if (C_FAMILY.has(LANG)) for (let k = 0; k < 6 && /<[^<>()]*>/.test(name); k++) name = name.replace(/<[^<>()]*>/g, '');
339
+ return name.replace(/<[^()]*?>/g, '').replace(/\(\)/g, '').replace(/::|->/g, '.').replace(/#/g, '');
96
340
  }
97
341
  function sayCall(name, args) {
342
+ // A bare capitalized Swift call makes a value of that type (`Logger(label: …)` makes a logger; it does not write one).
343
+ if (LANG === 'swift' && /^[A-Z]\w*$/.test(name) && !/^NSLog$/.test(name)) return null;
344
+ // In C and C++ `fmt::` is the {fmt} library (fmt::format makes text, fmt::format_to fills a buffer): only its print
345
+ // functions write a message; std::print likewise.
346
+ if (C_FAMILY.has(LANG) && /^(?:fmt|std)\./.test(name) && !/^(?:fmt|std)\.(?:print|println|cout|cerr)$/.test(name)) return null;
98
347
  for (const k of KNOWN_CALLS) if (k.re.test(name)) {
99
348
  const target = (args.match(/^\s*["'`]([\w.\-/: ]{1,60})["'`]/) || [])[1];
100
349
  const base = k.say(name);
@@ -114,14 +363,40 @@ function sayValue(expr) {
114
363
  if (py) return py;
115
364
  const common = sayCommon(e);
116
365
  if (common) return common;
117
- if (/^["'`].*["'`]$/.test(e)) return `"${clip(e.slice(1, -1), 40)}"`;
366
+ // Swift `SocketAddress.init(…)` makes a new SocketAddress.
367
+ if (LANG === 'swift' && /^[A-Z][\w.]*\.init\(/.test(e) && closeOf(e, e.indexOf('(')) === e.length - 1) return `a new ${e.slice(0, e.indexOf('.init(')).split('.').pop()}`;
368
+ // Swift text with values inside: the literal kept exactly, each value a «placeholder» (docs/spec.md).
369
+ if (LANG === 'swift' && /^"/.test(e) && /\\\(/.test(e)) { const tv = swiftTextWithValues(e); if (tv) return tv.length > 90 ? `${tv.slice(0, 88)}…"` : tv; }
370
+ if (/^(["'`])(?:\\.|(?!\1)[^\\])*\1$/.test(e) && !(/^`/.test(e) && /\$\{/.test(e))) return `"${clip(e.slice(1, -1), 40)}"`;
118
371
  if (/^-?\d+(\.\d+)?$/.test(e) || /^(true|false|True|False|nil|null|None|undefined)$/.test(e)) return e;
372
+ if (C_FAMILY.has(LANG) && /^-?(?:0[xX][\da-fA-F]+|\d+(?:\.\d+)?)[uUlLfF]*$/.test(e)) return e.replace(/(?<=\d|[a-fA-F])[uUlLfF]+$/, '').replace(/^(-?\d+(?:\.\d+)?)[uUlLfF]+$/, '$1');
373
+ if (C_FAMILY.has(LANG) && /^(?:NULL|nullptr)$/.test(e)) return 'nothing';
374
+ if (LANG === 'cpp' && /^\*this$/.test(e)) return 'itself';
375
+ // Swift enum cases: .cancelled -> "cancelled"; .failure(error) -> "failure with error".
376
+ if (LANG === 'swift' && /^\.[a-z]\w*(?:\(.*\))?$/.test(e)) {
377
+ const sm = e.match(/^\.([a-z]\w*)(?:\((.*)\))?$/);
378
+ const arg = sm[2] != null ? sm[2].trim() : '';
379
+ return arg ? (/^[A-Za-z_][\w.]*$/.test(arg) ? `${words(sm[1])} with ${words(arg.split('.').pop())}` : words(sm[1])) : words(sm[1]);
380
+ }
381
+ if (C_FAMILY.has(LANG) && /^(?:[A-Za-z_]\w*::)+([A-Za-z_]\w*)$/.test(e)) return words(e.split('::').pop()); // token_type::parse_error
119
382
  const c = callee(e);
120
383
  if (c) {
384
+ // `search.trim().length > 0` is not "the result of trim": the call must be the whole value.
385
+ const open = e.indexOf('(', e.search(/[\w$]\s*(?:<[^()]*?>)?\s*\(/));
386
+ const close = open < 0 ? -1 : closeOf(e, open);
387
+ if (close >= 0 && close !== e.length - 1) return null;
121
388
  if (/^new\s/.test(e)) return `a new ${c.split('.').pop()}`;
389
+ // Swift makes a value by calling its type: Loan(title: t) is a new Loan (so does C++: std::string(s)).
390
+ if ((LANG === 'swift' || LANG === 'cpp') && /^[A-Z]\w*$/.test(c) && !/^[A-Z][A-Z0-9_]+$/.test(c) && !C_STYLE_FUNCTION.test(c)) return `a new ${c}`;
122
391
  return `the result of ${lastWords(c)}`;
123
392
  }
124
- if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words(e.replace(/^\$/, '').split('.').pop());
393
+ if (LANG === 'swift' && /^[A-Za-z_][\w.]*\.count$/.test(e)) return `how many ${possessiveWords(e.replace(/\.count$/, ''))}`;
394
+ // A path keeps its owner: `callback.call` is "the callback's call", not "call"; `Boolean.TYPE` stays as written.
395
+ if (/^[A-Za-z_$][\w$.]*$/.test(e)) {
396
+ const parts = e.replace(/^\$/, '').split('.').filter((p) => !/^(?:self|this)$/.test(p));
397
+ if (parts.length > 1 && /^[A-Z][A-Z0-9_]+$/.test(parts[parts.length - 1])) return parts.slice(-2).join('.');
398
+ return parts.length > 1 ? possessiveWords(parts.join('.')) : words(parts[0] ?? e);
399
+ }
125
400
  if (/^\$?[A-Za-z_][\w$]*(?:\[\s*['"]?\w+['"]?\s*\]|->\w+|\.\w+)+$/.test(e)) return possessiveWords(e);
126
401
  return null;
127
402
  }
@@ -181,27 +456,38 @@ function sayCommon(value) {
181
456
  const e = String(value).trim().replace(/\s+as\s+[\w.<>\[\]|, ]+$/, '');
182
457
  let m;
183
458
  // cond ? a : b -> "a if cond, otherwise b" (not TypeScript optional types or labels).
184
- const side = (x) => sayValue(x) ?? sayArithmetic(x) ?? possessiveWords(x.trim());
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])}`;
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])}`;
459
+ // Each side must be said in full (a value, simple arithmetic, or a plain name or path); anything else and the
460
+ // whole choice is left unsaid rather than half-said.
461
+ const side = (x) => { const t = x.trim(); return sayValue(t) ?? sayArithmetic(t) ?? (/^\$?[\w$]+(?:\.[\w$]+)*$/.test(t) ? possessiveWords(t) : null); };
462
+ const choice = (yes, cond, no) => {
463
+ if (![yes, cond, no].every((x) => balancedText(x))) return null;
464
+ const a = side(yes), b = side(no), c = sayCodeCondition(cond);
465
+ return a != null && b != null && !isCodeWords(c) ? `${a} if ${c}, otherwise ${b}` : null;
466
+ };
467
+ if ((m = e.match(/^(.+?)\s+\?\s+([^:?]+?)\s+:\s+([^:?]+)$/)) && !/^(?:[\w$]+\??\s*:)/.test(e)) return choice(m[2], m[1], m[3]);
468
+ if ((m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/)) && !/^(?:if|unless)\b/.test(e)) return choice(m[1], m[2], m[3]);
187
469
  // An `if` used as a value, said like a ternary: Kotlin `if (a) b else c`, Rust `if a { b } else { c }`,
188
470
  // Ruby `if a then b else c end`.
189
471
  const ifValue = ifAsValue(e);
190
- if (ifValue) return `${side(ifValue.yes)} if ${sayCodeCondition(ifValue.cond)}, otherwise ${side(ifValue.no)}`;
472
+ if (ifValue) return choice(ifValue.yes, ifValue.cond, ifValue.no);
191
473
  if ((m = e.match(/^&?([A-Z]\w*)(?:::new\s*\(|\s*\{)/)) || (m = e.match(/^(?:[\w.]+\.)?([A-Z]\w*)\{/))) return `a new ${m[1]}`;
192
474
  if ((m = e.match(/^new\s*\(\s*(?:[\w]+\.)?([A-Z]\w*)\s*\)$/))) return `a new ${m[1]}`;
193
475
  if ((m = e.match(/^&([A-Z]\w*)$/))) return `a new ${m[1]}`;
194
476
  if ((m = e.match(/^[\w.]+\.(?:get|get_or_404|find|Find|findById|find_by_id)\(\s*([A-Z]\w*)\s*,\s*([\w.]+)\s*\)$/))) return `the ${m[1]} with ${lastSeg(m[2])}`;
195
- if ((m = e.match(/^([\w.]+)\.get\(\s*([A-Za-z_][\w.]*)\s*[,)]/)) || (m = e.match(/^([\w.]+)\[\s*([A-Za-z_][\w.]*)\s*\]$/))) return `the ${lastSeg(m[2])} entry in ${lastSeg(m[1])}`;
196
- if (/["'`]\s*\+|\+\s*["'`]/.test(e) && !/[<>=!&|]/.test(e)) return 'text built from its parts';
477
+ if ((m = e.match(/^([\w.]+)\.get\(\s*([A-Za-z_][\w.]*)\s*[,)]/)) || (m = e.match(/^([\w.]+)\[\s*([A-Za-z_][\w.]*)\s*\]$/))) return `the ${lastSeg(m[2])} entry in ${possessiveWords(m[1])}`;
478
+ const wholeCall = (() => { const c = e.match(/^(?:new\s+)?[\w$.]+(?:<[^()]*?>)?\s*\(/); return !!c && closeOf(e, c[0].length - 1) === e.length - 1; })();
479
+ if (/["'`]\s*\+|\+\s*["'`]/.test(e) && !/[<>=!&|]/.test(e) && !wholeCall) return 'text built from its parts';
480
+ // PHP joins text with ` . ` (spaced when PHP is read): `$a . ':' . $b`.
481
+ if (/\s\.\s/.test(e.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, 'Q')) && !/[<>=!&|?]/.test(e.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, 'Q'))) return 'text built from its parts';
197
482
  if ((m = e.match(/^[A-Za-z_][\w.]*(\s*,\s*[A-Za-z_][\w.]*)+$/))) return e.split(/\s*,\s*/).map(lastSeg).join(' and ');
198
483
  if ((m = e.match(/^make\(\s*(\[\]|map\[)/))) return m[1] === '[]' ? 'an empty list' : 'an empty lookup table';
199
484
  if (/^(?:f|rf|fr)["']/.test(e) || /^`[^`]*\$\{/.test(e) || /^\$"/.test(e) || /^(?:fmt\.Sprintf|String\.format|format!)\(/.test(e)) return 'text built from its parts';
200
485
  if ((m = e.match(/^([\w.]+)\.get\(\s*["'`]([\w.\-: ]{1,40})["'`]/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
201
486
  if ((m = e.match(/^([\w.]+)\[\s*["'`]([\w.\-: ]{1,40})["'`]\s*\]$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
487
+ if (FN_CONTEXT?.language === 'ruby' && (m = e.match(/^@?([\w.]+)\[\s*:(\w+)\s*\]$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
202
488
  if ((m = e.match(/^([\w.]+)\.split\(\s*["'`]([^"'`]{0,10})["'`]/))) return `${lastSeg(m[1])} split at "${m[2]}"`;
203
489
  if ((m = e.match(/^@?([\w.]+?)(?:\.copy|\.clone|\.Clone|\.dup)(?:\(\))?$/))) return `a copy of ${lastSeg(m[1])}`;
204
- if ((m = e.match(/^(?:str|String|string)\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:toString|to_s|ToString)\(\)$/))) return `${lastSeg(m[1])} as text`;
490
+ if ((m = e.match(/^(?:str|String|string)\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:toString\(\)|to_s(?:\(\))?|ToString\(\))$/))) return `${lastSeg(m[1])} as text`;
205
491
  if ((m = e.match(/^(?:int|float|Number|parseInt|parseFloat|strconv\.Atoi|Integer\.parseInt|int\.Parse)\(\s*([\w.]+)/))) return `${lastSeg(m[1])} as a number`;
206
492
  if ((m = e.match(/^(?:JSON\.parse|json\.loads|json\.load|JsonSerializer\.Deserialize\w*)\(\s*([\w.]+)/))) return `${lastSeg(m[1])} read as JSON`;
207
493
  if ((m = e.match(/^(?:JSON\.stringify|json\.dumps|JsonSerializer\.Serialize)\(\s*([\w.]+)/))) return `${lastSeg(m[1])} written as JSON`;
@@ -230,8 +516,40 @@ function ifAsValue(e) {
230
516
  const LOGIC = /(&&|\|\||[<>]=?|[!=]==?|\band\b|\bor\b|\bnot\b|\bis\b|^\s*!)/;
231
517
  function sayWhether(expr) {
232
518
  const e = String(expr).trim();
233
- if (!LOGIC.test(e) || /=>|\blambda\b|\?.*:/.test(e) || e.length > 90) return null;
234
- return `whether ${sayCodeCondition(e)}`;
519
+ if (!LOGIC.test(e) || /=>|\blambda\b|\s\?\s.*:/.test(e)) return null;
520
+ // (`bin_sig << 4` shifts bits: it is not a comparison.)
521
+ if ((C_FAMILY.has(LANG) || LANG === 'swift') && /<<|>>/.test(e.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, 'Q'))) return null;
522
+ // (A Swift range `a..<b` is not a comparison, and `(a, b)` is two values, not one yes/no.)
523
+ if (LANG === 'swift' && (/\.\.[.<]/.test(e) || splitTopArgs(e.replace(/^\((.*)\)$/, '$1')).length > 1)) return null;
524
+ const said = sayCodeCondition(e);
525
+ return isCodeWords(said) ? null : `whether ${said}`;
526
+ }
527
+
528
+ // ── What the function around a statement is: its inputs, so `next(…)` can be told apart from a local helper ──
529
+ let FN_CONTEXT = null;
530
+ /** Read steps with the function's inputs known ({ params: [{ name, type }], language }). */
531
+ export function withFunctionContext(ctx, fn) {
532
+ const before = FN_CONTEXT;
533
+ FN_CONTEXT = ctx;
534
+ try { return fn(); } finally { FN_CONTEXT = before; }
535
+ }
536
+ /**
537
+ * What `next` is in this function: 'middleware' (Express/Koa/Fastify style `(req, res, next)` or a NextFunction),
538
+ * 'pipeline' (a .NET handler delegate: calling it runs the rest of the pipeline and gives its answer), or null
539
+ * (a local helper named next, or no such input): then `next(x)` is an ordinary call.
540
+ */
541
+ function nextKind() {
542
+ const ps = FN_CONTEXT?.params || [];
543
+ // A route handler's `next` (`app.get('/', function (req, res, next) { … })`).
544
+ if (FN_CONTEXT?.route && !ps.some((x) => x.name === 'next' && /Delegate|Func</.test(String(x.type || '')))) return 'middleware';
545
+ const p = ps.find((x) => x.name === 'next');
546
+ if (!p) return null;
547
+ if (/RequestHandlerDelegate|Delegate\b|Func</.test(String(p.type || ''))) return 'pipeline';
548
+ if (/NextFunction|Next\b/.test(String(p.type || ''))) return 'middleware';
549
+ const names = ps.map((x) => x.name);
550
+ const i = names.indexOf('next');
551
+ if (i >= 1 && /^(?:req|request|res|response|reply|ctx|context|c|err|error|e)$/.test(names[i - 1] || '')) return 'middleware';
552
+ return null;
235
553
  }
236
554
 
237
555
  /** Classify one statement (its first line or header). Returns { kind, says, code } where code is the original text. */
@@ -247,11 +565,17 @@ const CHAIN = [
247
565
  ];
248
566
  /** "items.filter(x => …).map(…)" -> "one for each item in items" (the last collection step wins). */
249
567
  function sayChain(value) {
250
- const src = (value.match(/^(?:await\s+)?([A-Za-z_$#][\w$#.]*?)(?:\.(?:iter|into_iter|stream|asSequence|values|keys|entries)\(\))?\./) || [])[1];
251
- if (!src) return null;
252
- let hit = null;
253
- for (const c of CHAIN) { const m = value.match(c.re); if (m && (!hit || m.index > hit.index)) hit = { index: m.index, c }; }
254
- return hit ? hit.c.say(words(src.split('.').pop().replace(/^#/, ''))) : null;
568
+ // In Rust, `.map` straight on a value (not on `.iter()`) is on an Option or a Result: it changes the value if
569
+ // there is one; it does not go through items.
570
+ if (FN_CONTEXT?.language === 'rust' && !/\.(?:iter|into_iter|iter_mut|chars|bytes|lines|split\w*|keys|values|windows|chunks)\(\)/.test(value) && /\.(?:map|filter|and_then|find)\s*\(/.test(value)) return null;
571
+ let hit = null, first = null;
572
+ for (const c of CHAIN) { const m = value.match(c.re); if (m && (!hit || m.index > hit.index)) hit = { index: m.index, c }; if (m && (first == null || m.index < first)) first = m.index; }
573
+ if (!hit) return null;
574
+ // The items are the source's only when the first collection step comes straight after a plain name or path: in
575
+ // `Orderer.Prioritize(list, r).Select(…)` they are what Prioritize gives back, not the orderer's.
576
+ const src = value.slice(0, first).replace(/^await\s+/, '').replace(/\.(?:iter|into_iter|stream|asSequence|values|keys|entries)\(\)$/, '');
577
+ if (!/^[A-Za-z_$#][\w$#.]*$/.test(src)) return null;
578
+ return hit.c.say(words(src.split('.').pop().replace(/^#/, '')));
255
579
  }
256
580
 
257
581
  const HTTP_STATUS = { 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 409: 'Conflict', 410: 'Gone', 413: 'Payload Too Large', 415: 'Unsupported Media Type', 422: 'Unprocessable Content', 429: 'Too Many Requests', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout' };
@@ -263,7 +587,16 @@ const HTTP_STATUS = { 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Req
263
587
  */
264
588
  function httpErrorOf(head) {
265
589
  const expr = head.replace(/^return\s+/, '').replace(/^await\s+/, '').replace(/;\s*$/, '').trim();
590
+ const named = /^return\b/.test(head) && expr.match(/^(NotFound|BadRequest|Unauthorized|Forbid|Conflict|UnprocessableEntity|ValidationProblem|Problem)\s*\((.*)\)$/);
591
+ if (named) {
592
+ const status = { NotFound: 404, BadRequest: 400, Unauthorized: 401, Forbid: 403, Conflict: 409, UnprocessableEntity: 422, ValidationProblem: 400, Problem: 500 }[named[1]];
593
+ const msg = firstText(named[2], 80);
594
+ return { kind: 'fail', says: `Fails with ${status} ${HTTP_STATUS[status]}${msg ? `: "${msg}"` : ''}`, error: `${status} ${HTTP_STATUS[status]}`, ...(msg ? { message: msg } : {}), status };
595
+ }
266
596
  let m = expr.match(/^(?:reply|res|response|resp|ctx\.response)\s*\.\s*(?:code|status|statusCode)\s*\(\s*([45]\d\d)\s*\)/)
597
+ || expr.match(/^(?:res|response)\s*\.\s*sendStatus\s*\(\s*([45]\d\d)\s*\)/)
598
+ || expr.match(/^c\s*\.\s*(?:JSON|String|AbortWithStatusJSON|AbortWithStatus)\s*\(\s*(?:http\.Status\w+?|([45]\d\d))\b/) && (() => { const g = expr.match(/^c\s*\.\s*\w+\s*\(\s*([^,)]+)/); const st = g && statusOf(g[1]); return st && st >= 400 ? [null, String(st)] : null; })()
599
+ || expr.match(/^ResponseEntity\s*\.\s*(?:status\s*\(\s*(?:HttpStatus\.)?(\w+)\s*\)|(notFound|badRequest|unprocessableEntity)\s*\(\s*\))/) && (() => { const g = expr.match(/ResponseEntity\s*\.\s*(?:status\s*\(\s*([^)]+)\)|(notFound|badRequest|unprocessableEntity))/); const st = g[2] ? { notFound: 404, badRequest: 400, unprocessableEntity: 422 }[g[2]] : statusOf(g[1]); return st && st >= 400 ? [null, String(st)] : null; })()
267
600
  || expr.match(/^(?:new\s+)?(?:Response|NextResponse(?:\.json)?|HttpResponse|JSONResponse|PlainTextResponse|Response\.json)\s*\(.*\bstatus(?:_code)?\s*[:=]\s*([45]\d\d)\b/)
268
601
  || (/^return\b/.test(head) ? expr.match(/^.+,\s*([45]\d\d)\s*$/) : null);
269
602
  if (!m) return null;
@@ -298,7 +631,8 @@ function redirectOf(head) {
298
631
  || expr.match(/^redirect\(\s*\)\s*->\s*(route\(.*\))\s*$/);
299
632
  if (!m) return null;
300
633
  const to = redirectTarget(m[1]);
301
- return { kind: isReturn ? 'return' : 'call', says: `Sends the person to ${to}`, redirect: to };
634
+ // A redirect ends the response whether or not the code writes `return` before it.
635
+ return { kind: 'return', says: `Sends the person to ${to}`, redirect: to, response: true };
302
636
  }
303
637
 
304
638
  /** The top-level keys of an object literal: `{ org, repos: list, ...rest, 'avg': x }` -> ['org', 'repos', 'avg']. */
@@ -326,28 +660,597 @@ function objectKeys(expr) {
326
660
  }
327
661
  const listWords = (xs) => (xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')}${xs.length > 2 ? ',' : ''} and ${xs.at(-1)}`);
328
662
 
329
- export function classifyStatement(raw, { inner = 0 } = {}) {
663
+ // ── C, C++, and Swift statement shapes ──────────────────────────────────────────────────────────────────
664
+
665
+ /** `p->x` as `p.x`, C casts dropped (`(char *)buf` -> `buf`, `(void)f()` -> `f()`), `*out = v` as `out = v`. */
666
+ function cNormalize(head) {
667
+ return String(head)
668
+ .replace(/(\w|\))->(?=[A-Za-z_])/g, '$1.')
669
+ .replace(/\((?:const\s+)?(?:unsigned\s+|signed\s+|struct\s+|enum\s+)?(?:void|char|int|long|short|float|double|size_t|ssize_t|u?int\d+_t|bool|unsigned|[A-Za-z_]\w*\s*\*+)\s*\)\s*(?=[\w(&*"'])/g, '')
670
+ .replace(/^\*+\s*(?=[A-Za-z_][\w.]*\s*(?:[-+*/|&]?=)(?!=))/, '')
671
+ .replace(/\b(?:static|reinterpret|const|dynamic)_cast\s*<[^<>()]*(?:<[^<>()]*>[^<>()]*)*>\s*\(\s*([\w.]+)\s*\)/g, '$1');
672
+ }
673
+
674
+ const NOT_A_TYPE = /^(?:return|throw|yield|await|new|delete|case|goto|else|typeof|let|const|var|val|if|for|while|do|switch|using|namespace|typedef|public|private|protected|def|func|fn|fun|import|export|from|echo|print|puts|go|defer|not|and|or|in|is|as|of|mut|ref|out|static|final|readonly|unless|until|when|guard|try|catch|sizeof|template|operator|class|struct|enum|union|co_return|co_await|raise|assert|super|this|self)$/;
675
+ /**
676
+ * A C/C++ declaration: `char *buf = malloc(n)`, `size_t len = strlen(s)`, `struct node *n;`, `std::vector<int> v(10);`.
677
+ * Gives { type, name, value } (value null when there is none; ctor true for `Type name(args)`). Java-style
678
+ * `String x = …` is left to the typed-declaration reading.
679
+ */
680
+ function cDeclaration(head) {
681
+ const m = String(head).match(/^((?:(?:static|const|constexpr|volatile|register|unsigned|signed|struct|enum|union|thread_local|mutable|inline|long(?=\s+(?:long|int|double|unsigned)\b)|short(?=\s+int\b))\s+)*)((?:[A-Za-z_]\w*::)*[A-Za-z_]\w*(?:<[^=;]*?>)?)(\s*[*&]+\s*|\s+)((?:const\s+)?[a-zA-Z_]\w*)\s*(?:\[[^\]]*\])*\s*(?:=(?!=)\s*(.*?)|(\{[^{}]*\}|\([^()]*\)))?\s*;?\s*$/);
682
+ if (!m || NOT_A_TYPE.test(m[2]) || NOT_A_TYPE.test(m[4].replace(/^const\s+/, ''))) return null;
683
+ const type = m[2], pointer = /[*&]/.test(m[3]), quals = m[1].trim();
684
+ // Leave `String name = …`, `int x = …`, `auto x = …` to the typed reading unless it is plainly C (a pointer, a
685
+ // qualifier, `::`, or a lowercase type such as size_t).
686
+ const array = /\[/.test(String(head).slice(m[1].length + m[2].length + m[3].length).split('=')[0]);
687
+ const cish = pointer || array || /::/.test(type) || /\b(?:struct|enum|union|unsigned|signed|const|static|constexpr|register|volatile)\b/.test(quals) || (/^[a-z_]\w*$/.test(type) && !/^(?:int|long|double|float|boolean|bool|char|byte|short|string|decimal|var|auto|let|val|dynamic|object)$/.test(type)) || /^\s*\{/.test(m[5] ?? '');
688
+ // `int j;` / `RedisModuleIO io;`: in C a type and a name with nothing else is always a declaration.
689
+ if (!cish && (m[5] != null || m[6])) return null;
690
+ if (m[6]) return /^\{\s*\}$|^\(\s*\)$/.test(m[6]) ? { type, name: m[4], value: '{}', ctor: false } : { type, name: m[4], value: m[6], ctor: true };
691
+ return { type, name: m[4].replace(/^const\s+/, ''), value: m[5] == null ? null : m[5], array };
692
+ }
693
+
694
+ const pluralOf = (w) => (/(?:s|x|ch|sh)$/.test(w) ? `${w}es` : /[^aeiou]y$/.test(w) ? `${w.slice(0, -1)}ies` : `${w}s`);
695
+ const CAST = String.raw`(?:\(\s*[\w\s*]+\)\s*)?`;
696
+ const SIZEOF = String.raw`sizeof\s*\(?\s*\*?\s*([\w\s*:]+?)\s*\)?`;
697
+ const ALLOC_ONE = new RegExp(String.raw`^${CAST}(?:z|x|je_|ck_)?malloc\(\s*${SIZEOF}\s*\)$`);
698
+ const ALLOC_N = new RegExp(String.raw`^${CAST}(?:z|x|je_|ck_)?malloc\(\s*([\w.]+)\s*\*\s*${SIZEOF}\s*\)$`);
699
+ const ALLOC_N2 = new RegExp(String.raw`^${CAST}(?:z|x|je_|ck_)?malloc\(\s*${SIZEOF}\s*\*\s*([\w.]+)\s*\)$`);
700
+ const CALLOC = new RegExp(String.raw`^${CAST}(?:z|x|je_|ck_)?calloc\(\s*([\w.]+)\s*,\s*${SIZEOF}\s*\)$`);
701
+ /** How much memory a C allocation asks for, as words: "memory for 10 books", "memory for one node", or "memory". */
702
+ function memoryFor(value) {
703
+ const v = String(value).trim().replace(/;$/, '');
704
+ const ofType = (t) => words(String(t).replace(/\b(?:struct|const|unsigned)\s+/g, '').replace(/\s*\*+$/, '').trim().split('::').pop());
705
+ const count = (n) => (/^\d+$/.test(n.trim()) ? n.trim() : words(n.trim()));
706
+ let m;
707
+ if ((m = v.match(ALLOC_ONE))) return `memory for one ${ofType(m[1])}`;
708
+ if ((m = v.match(ALLOC_N))) return `memory for ${count(m[1])} ${pluralOf(ofType(m[2]))}`;
709
+ if ((m = v.match(ALLOC_N2))) return `memory for ${count(m[2])} ${pluralOf(ofType(m[1]))}`;
710
+ if ((m = v.match(CALLOC))) return m[1].trim() === '1' ? `memory for one ${ofType(m[2])}` : `memory for ${count(m[1])} ${pluralOf(ofType(m[2]))}`;
711
+ if ((m = v.match(/^new\s+([\w:<>]+)\s*\[\s*([^\]]+?)\s*\]$/))) return `memory for ${count(m[2])} ${pluralOf(ofType(m[1]))}`;
712
+ if (new RegExp(String.raw`^${CAST}(?:z|x|je_|ck_)?(?:malloc|calloc|alloca|aligned_alloc)\(`).test(v)) return 'memory';
713
+ return null;
714
+ }
715
+
716
+ /** Calls into the C library that read plainly: free, memcpy, memset, strcpy, printf, exit. */
717
+ function sayCLibrary(head) {
718
+ const h = String(head).trim().replace(/;$/, '').trim();
719
+ let m;
720
+ // Allocations: `buf = malloc(len + 1)`, `nodes = calloc(n, sizeof(Node))`, `p = realloc(p, size)`, `a = new int[n]`.
721
+ if ((m = h.match(/^(?:var\s+)?([A-Za-z_][\w.\[\]]*)\s*=(?!=)\s*(.+)$/))) {
722
+ const target = targetWords(m[1]);
723
+ const mem = memoryFor(m[2]);
724
+ if (mem) return { kind: 'set', says: mem === 'memory' ? `Gets memory for ${target}` : `Gets ${mem} as ${target}` };
725
+ const re = m[2].match(new RegExp(String.raw`^${CAST}(?:z|x)?realloc\(\s*([\w.]+)\s*,`));
726
+ if (re) return { kind: 'set', says: re[1] === m[1] ? `Resizes the memory for ${target}` : `Resizes the memory for ${targetWords(re[1])}, as ${target}` };
727
+ const made = m[2].match(/^(?:std::)?make_(?:unique|shared)\s*<\s*([\w:]+)/);
728
+ if (made) return { kind: 'set', says: `Creates a new ${made[1].split('::').pop()} as ${target}` };
729
+ const dup = m[2].match(/^(?:z|x)?strn?dup\(\s*([\w.]+)/);
730
+ if (dup) return { kind: 'set', says: `Sets ${target} to a copy of ${targetWords(dup[1])}` };
731
+ const len = m[2].match(/^strlen\(\s*([\w.]+)\s*\)$/);
732
+ if (len) return { kind: 'set', says: `Sets ${target} to the length of ${targetWords(len[1])}` };
733
+ return null;
734
+ }
735
+ if ((m = h.match(/^(?:z|x|je_|ck_)?free\(\s*([\w.[\]]+)\s*\)$/)) || (m = h.match(/^delete\s*(?:\[\s*\])?\s*([\w.]+)$/))) return { kind: 'call', says: `Frees ${targetWords(m[1])}`, callee: 'free' };
736
+ if ((m = h.match(/^(?:std::)?(?:memcpy|memmove|strcpy|strncpy|strlcpy)\(\s*&?([\w.[\]]+)\s*,\s*&?([\w.[\]]+)\s*(?:,|\))/))) return { kind: 'call', says: `Copies ${targetWords(m[2])} into ${targetWords(m[1])}`, callee: 'copy' };
737
+ if ((m = h.match(/^(?:std::)?(?:strcat|strncat|strlcat)\(\s*([\w.[\]]+)\s*,\s*([\w.[\]]+|"[^"]*")\s*(?:,|\))/))) return { kind: 'call', says: `Adds ${/^"/.test(m[2]) ? m[2] : targetWords(m[2])} to the end of ${targetWords(m[1])}`, callee: 'append' };
738
+ if ((m = h.match(/^(?:std::)?memset\(\s*&?([\w.[\]]+)\s*,\s*(?:0|'\\0')\s*,/))) return { kind: 'call', says: `Fills ${targetWords(m[1])} with zeros`, callee: 'memset' };
739
+ if ((m = h.match(/^(?:std::)?(?:exit|_exit|quick_exit)\(\s*(.+?)\s*\)$/))) return /^(?:0|EXIT_SUCCESS)$/.test(m[1]) ? { kind: 'return', says: 'Ends the program' } : { kind: 'fail', says: `Stops the program (exit code ${m[1].replace(/^EXIT_FAILURE$/, '1')})`, error: 'exit' };
740
+ if (/^(?:std::)?abort\(\s*\)$/.test(h)) return { kind: 'fail', says: 'Stops the program', error: 'abort' };
741
+ if (/^(?:std::)?(?:cout|cerr|clog)\s*<</.test(h)) return { kind: 'call', says: 'Writes a log or message', callee: 'cout' };
742
+ return null;
743
+ }
744
+
745
+ /** Swift and C++ make a value by calling its type (`Request()`, `Response.Body(…)`, `std::string(s)`). */
746
+ // (Apple's C functions are named like types but are calls: SecPolicyCreateSSL, CFStringCreateCopy, CGRectMake.)
747
+ const C_STYLE_FUNCTION = /[a-z0-9](?:Create|Copy|Get|Make|Set)(?:[A-Z0-9]\w*)?$/;
748
+ const makesType = (c) => (LANG === 'swift' || LANG === 'cpp') && /^(?:[A-Z]\w*\.)*[A-Z]\w*$/.test(String(c || '')) && !/^[A-Z][A-Z0-9_]+$/.test(String(c).split('.').pop()) && !C_STYLE_FUNCTION.test(String(c).split('.').pop());
749
+
750
+ /** Vapor's HTTP status names (`Abort(.notFound)`) and their numbers. */
751
+ export const VAPOR_STATUS = { badRequest: 400, unauthorized: 401, paymentRequired: 402, forbidden: 403, notFound: 404, methodNotAllowed: 405, conflict: 409, gone: 410, payloadTooLarge: 413, unsupportedMediaType: 415, unprocessableEntity: 422, tooManyRequests: 429, internalServerError: 500, notImplemented: 501, badGateway: 502, serviceUnavailable: 503 };
752
+
753
+ /** A Swift condition list (`let user = user, user.isActive, count > 0`) in words: "user is set and …". */
754
+ function swiftCondition(cond) {
755
+ const parts = [];
756
+ let depth = 0, from = 0;
757
+ const c = String(cond);
758
+ for (let i = 0; i <= c.length; i++) {
759
+ const ch = c[i];
760
+ if (ch === '(' || ch === '[' || ch === '{') depth++; else if (ch === ')' || ch === ']' || ch === '}') depth--;
761
+ else if (ch === '"') { for (i++; i < c.length && c[i] !== '"'; i++) if (c[i] === '\\') i++; }
762
+ if (i === c.length || (ch === ',' && depth === 0)) { parts.push(c.slice(from, i).trim()); from = i + 1; }
763
+ }
764
+ return parts.filter(Boolean).map((p) => {
765
+ let m;
766
+ if ((m = p.match(/^(?:let|var)\s+(\w+)(?:\s*:\s*[^=]+)?(?:\s*=\s*(.+))?$/))) return `${words(m[1])} is set`;
767
+ if ((m = p.match(/^case\s+(?:let\s+|var\s+)?\.?(\w+)(?:\s*\([^()]*\))?\s*=\s*(.+)$/)) && /^[\w.]+$/.test(m[2].trim())) return `${possessiveWords(m[2].trim())} is ${words(m[1])}`;
768
+ if ((m = p.match(/^case\s+(?:let\s+|var\s+)?\.?(\w+)/))) return `it is ${words(m[1])}`;
769
+ return sayCodeCondition(p);
770
+ }).join(' and ');
771
+ }
772
+
773
+ /** `a..<b`, `a...b` (Swift) and `a..b`, `a..=b` (Rust) as words: "from 0 up to n (not n itself)", "from 1 to 10". */
774
+ function rangeWords(expr) {
775
+ // Each side is a number or a name path; a dot is only part of a name when a letter follows it (`1...3` is a range).
776
+ const m = String(expr).trim().match(/^\(?\s*(-?\w+(?:\.[A-Za-z_]\w*)*(?:\s*[-+]\s*\d+)?)\s*(\.\.<|\.\.\.|\.\.=|\.\.)\s*(-?\w+(?:\.[A-Za-z_]\w*)*(?:\(\))?(?:\s*[-+]\s*\d+)?)\s*\)?$/);
777
+ if (!m) return null;
778
+ const side = (x) => (/^-?\d+$/.test(x.trim()) ? x.trim() : /\.count$/.test(x.trim()) ? `how many ${possessiveWords(x.trim().replace(/\.count$/, ''))}` : possessiveWords(x.trim().replace(/\(\)$/, '')));
779
+ const inclusive = m[2] === '...' || m[2] === '..=';
780
+ if (!inclusive && /^-?\d+$/.test(m[1].trim()) && /^-?\d+$/.test(m[3].trim())) return { from: m[1].trim(), to: m[3].trim(), says: `from ${m[1].trim()} to ${Number(m[3]) - 1}` };
781
+ return { from: m[1].trim(), to: m[3].trim(), says: inclusive ? `from ${side(m[1])} to ${side(m[3])}` : `from ${side(m[1])} up to ${side(m[3])} (not ${side(m[3])} itself)` };
782
+ }
783
+
784
+ /**
785
+ * Shapes that belong to C, C++, and Swift: labels and goto, do/repeat … while, C++ range-for, Swift ranges, guard,
786
+ * if let, defer blocks, do/catch, throw of an enum case, Vapor's Abort, and functions kept in a name. Null otherwise.
787
+ */
788
+ function sayNativeShape(head, text, innerNote) {
789
+ let m;
790
+ const swift = LANG === 'swift';
791
+ // A label (`cleanup:`) and the goto that jumps to it.
792
+ if ((m = head.match(/^([A-Za-z_]\w*)\s*:$/)) && !/^(?:default|public|private|protected|else|case)$/.test(m[1]) && (C_FAMILY.has(LANG) || LANG === 'go')) return { kind: 'call', says: `The "${m[1]}" part starts here` };
793
+ if ((m = head.match(/^goto\s+([A-Za-z_]\w*)\s*;?$/))) return { kind: 'call', says: `Jumps to the "${m[1]}" part` };
794
+ if (/^\[\[fallthrough\]\]\s*;?$/.test(head)) return { kind: 'call', says: 'Carries on into the next case too' };
795
+ // do { … } while (cond) written on one line; Swift's repeat { … } while cond; Swift's do { try … } catch { … }.
796
+ if (/^(?:do|repeat)\s*\{/.test(head)) {
797
+ const tail = text.slice(text.lastIndexOf('}') + 1).trim();
798
+ const dw = tail.match(/^while\s*\(([\s\S]*)\)\s*;?$/) || tail.match(/^while\s+([\s\S]+?)\s*;?$/);
799
+ if (dw) return { kind: 'loop', says: `Runs once, then repeats while ${sayCodeCondition(dw[1].replace(/\s+/g, ' '))}${innerNote}` };
800
+ if (swift && /^do\b/.test(head)) return { kind: 'try', says: `Tries the next steps and handles any error${innerNote}` };
801
+ }
802
+ // Loops that never end on their own.
803
+ if (/^(?:while\s*\(\s*(?:1|true|TRUE)\s*\)|while\s+true|for\s*\(\s*;\s*;\s*\))\s*\{?\s*$/.test(head)) return { kind: 'loop', says: `Repeats until a step inside stops it${innerNote}` };
804
+ // C++ range-for: for (const auto& item : items) / for (auto [key, value] : map).
805
+ if ((m = head.match(/^for\s*\(\s*(?:const\s+)?(?:auto|[\w:<>, ]+?)\s*[&*]{0,2}\s*(\[[^\]]*\]|\w+)\s*:(?!:)\s*(.+?)\s*\)\s*\{?\s*$/)) && C_FAMILY.has(LANG)) {
806
+ const src = words(stripTail(m[2]).replace(/\(\)$/, '').split(/\.|->/).pop());
807
+ const pair = m[1].match(/^\[\s*(\w+)\s*,\s*(\w+)\s*\]$/);
808
+ return { kind: 'loop', says: pair ? `For each ${words(pair[1])} and ${words(pair[2])} in ${src}${innerNote}` : `For each ${words(m[1].replace(/[[\]]/g, ''))} in ${src}${innerNote}` };
809
+ }
810
+ // Swift ranges: for i in 0..<n / for _ in 1...3.
811
+ if (swift && (m = head.match(/^for\s+(_|\w+)\s+in\s+(.+?)\s*\{?\s*$/))) {
812
+ const r = rangeWords(m[2]);
813
+ if (r) {
814
+ if (m[1] === '_') return { kind: 'loop', says: /^0$/.test(r.from) && /^\d+$/.test(r.to) && !/\.\.\.|\.\.=/.test(m[2]) ? `Repeats ${r.to} times${innerNote}` : `Repeats for each number ${r.says}${innerNote}` };
815
+ return { kind: 'loop', says: `Counts ${words(m[1])} ${r.says}${innerNote}` };
816
+ }
817
+ }
818
+ if (swift && (m = head.match(/^for\s+_\s+in\s+([\w.]+)\s*\{?\s*$/))) return { kind: 'loop', says: `Repeats once for each item in ${possessiveWords(m[1])}${innerNote}` };
819
+ if (swift && (m = head.match(/^while\s+(?:let|var)\s+(\w+)\s*=/))) return { kind: 'loop', says: `Repeats while there is a next ${words(m[1])}${innerNote}` };
820
+ // guard cond else { … }: the else block is the way out; the steps after it run only when the condition holds.
821
+ if (swift && (m = head.match(/^guard\s+(.+?)\s+else\s*(?:\{.*)?$/))) {
822
+ const binds = /(?:^|,)\s*(?:let|var|case)\b/.test(m[1]) || /,/.test(m[1]);
823
+ return { kind: 'branch', says: `If not: ${swiftCondition(m[1])}${innerNote}`, ...(binds ? {} : { cond: m[1], negate: true }) };
824
+ }
825
+ // if let x = … / if let x, y > 0 / if case .a = x
826
+ if (swift && (m = head.match(/^(?:else\s+)?if\s+(.+?)\s*(?:\{.*)?$/)) && (/^(?:let|var|case)\b/.test(m[1]) || /,\s*(?:let|var|case)?\s*\w/.test(m[1].replace(/\([^()]*\)/g, '')))) {
827
+ return { kind: 'branch', says: `If ${swiftCondition(m[1])}${innerNote}` };
828
+ }
829
+ if (swift && /^defer\s*\{/.test(head)) return { kind: 'call', says: 'At the end, runs these steps' };
830
+ // Vapor: throw Abort(.notFound, reason: "…") refuses the request with that HTTP status.
831
+ if ((m = head.match(/^throw\s+Abort\(\s*\.(\w+)(?:\s*,\s*reason:\s*"([^"]{1,80})")?/))) {
832
+ const status = VAPOR_STATUS[m[1]];
833
+ const name = status ? `${status} ${words(m[1]).replace(/\b\w/g, (x) => x.toUpperCase()).replace(/^Unprocessable Entity$/, 'Unprocessable Content')}` : words(m[1]);
834
+ return { kind: 'fail', says: `Fails with ${name}${m[2] ? `: "${m[2]}"` : ''}`, error: name, ...(m[2] ? { message: m[2] } : {}), ...(status ? { status } : {}) };
835
+ }
836
+ // throw LibraryError.full / throw .full (Swift errors are often enum cases).
837
+ if (swift && (m = head.match(/^throw\s+([A-Z]\w*)?\.([a-z]\w*)\b/))) {
838
+ const msg = (head.match(/"([^"]{1,60})"/) || [])[1];
839
+ return { kind: 'fail', says: `Fails with ${m[1] ? `${m[1]} (${words(m[2])})` : words(m[2])}${msg ? `: "${msg}"` : ''}`, error: `${m[1] ? `${m[1]}.` : ''}${m[2]}`, ...(msg ? { message: msg } : {}) };
840
+ }
841
+ // A function kept in a name: C++ `auto cmp = [&](…) { … }`, Swift `let format = { (x: Int) in … }`.
842
+ if ((m = head.match(/^(?:const\s+)?(?:auto|std::function<.*>|let|var)\s+(\w+)\s*(?::\s*[^=]+)?=\s*(?:\[[^\]]*\]\s*(?:\([^)]*\))?\s*(?:mutable\s*)?(?:->\s*[\w:<>]+\s*)?\{|\{)/)) && (C_FAMILY.has(LANG) && /=\s*\[/.test(head) || swift && /=\s*\{/.test(head))) return { kind: 'set', says: `Defines a helper, ${words(m[1])}` };
843
+ if (swift && (m = head.match(/^case\s+(.+?)\s*:\s*(.*)$/))) return { kind: 'check', says: armSays(m[1]), caseLabel: true };
844
+ // Passing a caught error on: Swift `throw error`, C++ `throw;`.
845
+ if ((swift && /^throw\s+(?:error|err|e)\s*$/.test(head)) || (C_FAMILY.has(LANG) && /^throw\s*;?$/.test(head))) return { kind: 'fail', says: 'Passes the error on' };
846
+ // Vapor routes registered in place: app.get("orders", ":id") { req in … } / todos.post(use: create).
847
+ if (swift && (m = head.match(/^(\w+)\.(get|post|put|patch|delete)\(([^(){}]*)\)\s*(\{.*)?$/))) {
848
+ const use = m[3].match(/\buse:\s*(?:self\.)?(\w+)/);
849
+ const pieces = m[3].replace(/\buse:[\s\S]*$/, '').split(',').map((x) => x.trim()).filter(Boolean);
850
+ if ((use || m[4]) && pieces.every((x) => /^"[^"]*"$/.test(x))) {
851
+ const path = pieces.map((x) => x.slice(1, -1).replace(/^\/+|\/+$/g, '')).filter(Boolean).join('/');
852
+ const where = /^(?:app|routes?|router)$/.test(m[1]) ? `/${path}` : `${path ? `${path} ` : ''}under ${words(m[1])}`;
853
+ return { kind: 'call', says: use ? `Handles ${m[2].toUpperCase()} ${where} with ${words(use[1])}` : `Handles ${m[2].toUpperCase()} ${where} with these steps` };
854
+ }
855
+ }
856
+ return null;
857
+ }
858
+
859
+ const STATUS_NAMES = { CONTINUE: 100, OK: 200, CREATED: 201, ACCEPTED: 202, NO_CONTENT: 204, NoContent: 204, MOVED_PERMANENTLY: 301, FOUND: 302, BAD_REQUEST: 400, BadRequest: 400, UNAUTHORIZED: 401, Unauthorized: 401, FORBIDDEN: 403, Forbidden: 403, NOT_FOUND: 404, NotFound: 404, CONFLICT: 409, Conflict: 409, UNPROCESSABLE_ENTITY: 422, UnprocessableEntity: 422, TOO_MANY_REQUESTS: 429, INTERNAL_SERVER_ERROR: 500, InternalServerError: 500, StatusOK: 200, StatusCreated: 201, StatusAccepted: 202, StatusNoContent: 204, StatusBadRequest: 400, StatusUnauthorized: 401, StatusForbidden: 403, StatusNotFound: 404, StatusConflict: 409, StatusUnprocessableEntity: 422, StatusInternalServerError: 500 };
860
+ const SUCCESS_WORDS = { 200: '', 201: '201 Created', 202: '202 Accepted', 204: '204 No Content' };
861
+ /** A status written as a number, http.StatusCreated, HttpStatus.CREATED, status.HTTP_201_CREATED, or StatusCodes.Status201Created. */
862
+ function statusOf(text) {
863
+ const t = String(text || '').trim();
864
+ let m;
865
+ if ((m = t.match(/^(\d{3})$/))) return Number(m[1]);
866
+ if ((m = t.match(/HTTP_(\d{3})/)) || (m = t.match(/Status(\d{3})/))) return Number(m[1]);
867
+ if ((m = t.match(/(?:^|\.)(\w+)$/)) && STATUS_NAMES[m[1]]) return STATUS_NAMES[m[1]];
868
+ return null;
869
+ }
870
+ /** What is sent back, in words: user -> "user"; { ok, user } -> "ok and user"; "Hello" -> "\"Hello\"". */
871
+ function payloadWords(arg) {
872
+ const a = String(arg || '').trim().replace(/^content\s*=\s*/, '');
873
+ if (!a) return null;
874
+ if (/^\{/.test(a)) {
875
+ // Each key, with its value when the code makes it plain: { success: true, data: result } -> "success (yes) and data (result)".
876
+ const inner = a.slice(1, a.lastIndexOf('}'));
877
+ const parts = callArgs(inner).map((p) => {
878
+ const kv = p.match(/^["']?([A-Za-z_$][\w$]*)["']?\s*:\s*(.+)$/s);
879
+ if (!kv) return /^[A-Za-z_$][\w$]*$/.test(p) ? words(p) : null;
880
+ const v = kv[2].trim();
881
+ const plain = /^(true|false)$/i.test(v) ? (v === 'true' ? 'yes' : 'no') : /^-?\d+(\.\d+)?$/.test(v) ? v : /^["'`][^"'`]{0,40}["'`]$/.test(v) ? `"${v.slice(1, -1)}"` : /^[A-Za-z_$][\w$.]*$/.test(v) && words(v) !== words(kv[1]) ? possessiveWords(v) : null;
882
+ return plain ? `${words(kv[1])} (${plain})` : words(kv[1]);
883
+ }).filter(Boolean);
884
+ return parts.length ? listWords(parts.length > 8 ? [...parts.slice(0, 7), 'more'] : parts) : 'an object';
885
+ }
886
+ if (/^\[/.test(a)) return 'a list';
887
+ const made = a.match(/^new\s+([A-Z]\w*)/);
888
+ if (made) return `a new ${words(made[1])}`;
889
+ if (/^(["'`])(?:\\.|(?!\1)[^\\])*\1$/.test(a) && !/^`[^`]*\$\{/.test(a)) return a.length < 50 ? `"${a.replace(/^["'`]|["'`]$/g, '')}"` : 'a message';
890
+ if (/^["'`]/.test(a) || /["'`]\s*\+|\+\s*["'`]/.test(a)) return 'text built from its parts';
891
+ if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(a)) return possessiveWords(a);
892
+ const call = a.match(/^(?:await\s+)?([\w.]+)\s*\(/);
893
+ if (call) return `what ${words(call[1].split('.').pop())} gives back`;
894
+ return 'a value';
895
+ }
896
+ /** Split a call's argument text at top-level commas. */
897
+ function callArgs(text) {
898
+ const out = []; let d = 0, cur = '';
899
+ for (const c of String(text)) { if ('([{'.includes(c)) d++; if (')]}'.includes(c)) d--; if (c === ',' && d === 0) { out.push(cur.trim()); cur = ''; } else cur += c; }
900
+ if (cur.trim()) out.push(cur.trim());
901
+ return out;
902
+ }
903
+ const sentStep = (payload, status, extra = {}) => {
904
+ const st = SUCCESS_WORDS[status] ?? (status ? String(status) : '');
905
+ const what = status === 204 ? 'nothing' : payload || 'a response';
906
+ return { kind: 'return', says: `Returns ${what}${st && status !== 204 ? ` (${st})` : status === 204 ? ' (204 No Content)' : ''}`, response: true, ...(status ? { status } : {}), ...extra };
907
+ };
908
+
909
+ /**
910
+ * A successful response sent back to the caller (an error response is a Stop, see httpErrorOf): Express/Fastify
911
+ * res.json/send/status().json/sendStatus/render, Koa ctx.body =, Gin c.JSON, ASP.NET Ok/Created/NoContent, Spring
912
+ * ResponseEntity, Flask jsonify, FastAPI JSONResponse. Gives a return step that says what the person gets back.
913
+ */
914
+ function responseOf(head) {
915
+ const expr = head.replace(/^return\s+/, '').replace(/^await\s+/, '').replace(/;\s*$/, '').trim();
916
+ let m;
917
+ // res.json(x) / res.status(201).json(x) / reply.code(201).send(x) / res.send(x) / res.end()
918
+ if ((m = expr.match(/^(?:res|reply|response|resp)\s*(?:\.\s*(?:status|code)\s*\(\s*([^)]*)\))?\s*\.\s*(json|send|jsonp|end)\s*\((.*)\)$/))) {
919
+ const status = m[1] ? statusOf(m[1]) : null;
920
+ if (status && status >= 300) return null;
921
+ return sentStep(payloadWords(m[3]), status);
922
+ }
923
+ if ((m = expr.match(/^(?:res|response)\s*\.\s*sendStatus\s*\(\s*([^)]*)\)$/))) { const st = statusOf(m[1]); return st && st < 300 ? sentStep(null, st) : null; }
924
+ if ((m = expr.match(/^(?:res|response)\s*\.\s*render\s*\(\s*["'`]([^"'`]+)["'`]/))) return { kind: 'return', says: `Shows the ${words(m[1].split('/').pop().replace(/\.\w+$/, ''))} page`, response: true };
925
+ if ((m = expr.match(/^ctx\.body\s*=\s*(.+)$/))) return sentStep(payloadWords(m[1]), null);
926
+ // Gin / Echo: c.JSON(http.StatusOK, user), c.String(200, "ok")
927
+ if ((m = expr.match(/^c\s*\.\s*(JSON|IndentedJSON|String|XML|YAML)\s*\((.*)\)$/))) { const [st, body] = callArgs(m[2]); const status = statusOf(st); if (status && status >= 300) return null; return sentStep(payloadWords(body), status === 200 ? null : status); }
928
+ // ASP.NET: Ok(x), Created(uri, x), CreatedAtAction(name, routeValues, x), Accepted(x), NoContent()
929
+ if (/^return\b/.test(head) && (m = expr.match(/^(Ok|Accepted|Created|CreatedAtAction|CreatedAtRoute|NoContent|Json)\s*\((.*)\)$/))) {
930
+ const args = callArgs(m[2]);
931
+ const status = { Ok: null, Json: null, Accepted: 202, Created: 201, CreatedAtAction: 201, CreatedAtRoute: 201, NoContent: 204 }[m[1]];
932
+ return sentStep(payloadWords(args.at(-1)), status);
933
+ }
934
+ // Spring: ResponseEntity.ok(x), ResponseEntity.status(HttpStatus.CREATED).body(x), ResponseEntity.noContent().build()
935
+ if ((m = expr.match(/^ResponseEntity\s*\.\s*(ok|accepted|created|noContent|status)\s*\(([^)]*)\)(?:\s*\.\s*(?:body|build)\s*\((.*)\))?$/))) {
936
+ const status = m[1] === 'status' ? statusOf(m[2]) : { ok: null, accepted: 202, created: 201, noContent: 204 }[m[1]];
937
+ if (status && status >= 300) return null;
938
+ return sentStep(payloadWords(m[1] === 'ok' ? m[2] || m[3] : m[3]), status);
939
+ }
940
+ // Flask jsonify(x) / jsonify(x), 201; FastAPI JSONResponse(content=x, status_code=201)
941
+ if (/^return\b/.test(head) && (m = expr.match(/^jsonify\s*\((.*)\)\s*(?:,\s*(\d{3}))?$/))) { const status = m[2] ? Number(m[2]) : null; if (status && status >= 300) return null; return sentStep(payloadWords(m[1]), status); }
942
+ if (/^return\b/.test(head) && (m = expr.match(/^(?:JSONResponse|ORJSONResponse|HTMLResponse|PlainTextResponse)\s*\((.*)\)$/))) {
943
+ const args = callArgs(m[1]);
944
+ const st = args.find((x) => /^status_code\s*=/.test(x));
945
+ const status = st ? statusOf(st.split('=')[1]) : null;
946
+ if (status && status >= 300) return null;
947
+ return sentStep(payloadWords(args.find((x) => !/^\w+\s*=/.test(x) || /^content\s*=/.test(x))), status);
948
+ }
949
+ return null;
950
+ }
951
+
952
+ /** A step for a library call written alone, stored in a name, or returned. */
953
+ function libraryStep(head) {
954
+ const h = head.replace(/;\s*$/, '').trim();
955
+ let m;
956
+ // Returned: return await prisma.user.findMany(...)
957
+ if ((m = h.match(/^return\s+(.+)$/))) {
958
+ const lib = sayLibraryCall(m[1]);
959
+ if (lib) return { kind: 'return', says: lib.value ? `Returns ${lib.says}` : `${lib.says}, and gives ${/^(Finds the \w+s\b|Finds all|Finds rows|Finds the [\w ]+ (?:whose|marked))/.test(lib.says) && !/^Finds the first/.test(lib.says) && /s\b/.test(lib.says.split(' ')[2] ?? '') ? 'them' : 'it'} back`, library: true };
960
+ return null;
961
+ }
962
+ // Stored: const user = await prisma.user.findUnique(...) / user = session.query(...).first() / err := db.Create(&u).Error
963
+ if ((m = h.match(/^(?:(?:const|let|var|val|final|auto)\s+)?(?:[A-Za-z_$][\w$<>[\],.?]*\s+)?([@$]{0,2}[A-Za-z_][\w$.]*|\{[^}]*\}|\[[^\]]*\])\s*(?::\s*[^=]+?)?\s*:?=(?!=)\s*(.+)$/)) && !/^(if|while|for|return)\b/.test(h)) {
964
+ // (A value that goes on past the library call — `a.get("x") or b`, `f() ? a : b` — is not just that call.)
965
+ const parts = splitLogic(m[2]);
966
+ if (!parts || parts.terms.length > 1 || /\?\?/.test(m[2])) return null;
967
+ const lib = sayLibraryCall(m[2].replace(/\.Error$/, ''));
968
+ if (!lib) return null;
969
+ const target = words(m[1].replace(/^[@$]+/, '').replace(/^[{[]\s*|\s*[}\]]$/g, '').split('.').pop());
970
+ if (lib.value) return { kind: 'set', says: `Sets ${target} to ${lib.says}`, library: true };
971
+ const mentions = new RegExp(`\\b${target.split(' ').pop().replace(/s$/, '')}`, 'i').test(lib.says);
972
+ return { kind: 'set', says: mentions || /^err(or)?$/.test(target) ? lib.says : `${lib.says} (as ${target})`, library: true, does: lib.does };
973
+ }
974
+ // Alone: await prisma.order.create(...) / session.commit()
975
+ const lib = sayLibraryCall(h);
976
+ return lib && !lib.value ? { kind: 'call', says: lib.says, library: true, does: lib.does } : null;
977
+ }
978
+
979
+ // ── Text with values inside (C, C++, Swift) ──────────────────────────────────────────────────────────────
980
+ // Quoted text keeps every literal character exactly as the code writes it; each inserted value is a placeholder in
981
+ // guillemets, holding the code that is inserted (a plain name exactly as spelled). See docs/spec.md, "Text with values
982
+ // inside". Null when the values cannot be paired with their places: the code is then shown as code.
983
+
984
+ /** The literal text between the quotes of `lit` (a C/C++/Swift "…" literal, with its quotes), or null. */
985
+ function quotedBody(lit) {
986
+ const t = String(lit).trim();
987
+ if (!/^"/.test(t) || t.length < 2 || !t.endsWith('"')) return null;
988
+ for (let i = 1; i < t.length - 1; i++) { if (t[i] === '\\') { i++; continue; } if (t[i] === '"') return null; }
989
+ return t.slice(1, -1);
990
+ }
991
+ /** Swift: `"Bearer \(token)"` -> `"Bearer «token»"`. Null when the literal is not one plain "…" text. */
992
+ export function swiftTextWithValues(lit) {
993
+ const t = String(lit).trim();
994
+ if (!/^"/.test(t) || /^"""/.test(t)) return null;
995
+ let out = '', i = 1;
996
+ for (; i < t.length; i++) {
997
+ const c = t[i];
998
+ if (c === '"') break;
999
+ if (c === '\\' && t[i + 1] === '(') {
1000
+ const close = closeOf(t, i + 1);
1001
+ if (close < 0) return null;
1002
+ out += `«${t.slice(i + 2, close).trim()}»`;
1003
+ i = close;
1004
+ continue;
1005
+ }
1006
+ if (c === '\\') { out += c + (t[i + 1] ?? ''); i++; continue; }
1007
+ out += c;
1008
+ }
1009
+ return i === t.length - 1 ? `"${out}"` : null;
1010
+ }
1011
+ const PLAIN_CONVERSION = /^%(?:hh|h|ll|l|j|z|t|L|q)?[diusc@]$/;
1012
+ /** C printf: `"%s/alias %d\n"` with [dir, n] -> `"«dir»/alias «n»\n"`; `%5.2f` with x -> `«x as %5.2f»`. */
1013
+ export function printfTextWithValues(lit, args) {
1014
+ const body = quotedBody(lit);
1015
+ if (body == null) return null;
1016
+ let out = '', k = 0, last = 0;
1017
+ for (const m of body.matchAll(/%(?:%|[-+ #0']*(?:\d+|\*)?(?:\.(?:\d+|\*))?(?:hh|h|ll|l|j|z|t|L|q)?[diouxXeEfFgGaAcspn@])/g)) {
1018
+ if (m[0] === '%%') continue;
1019
+ if (/\*/.test(m[0]) || k >= args.length) return null;
1020
+ const a = String(args[k++]).trim();
1021
+ out += body.slice(last, m.index) + (PLAIN_CONVERSION.test(m[0]) ? `«${a}»` : `«${a} as ${m[0]}»`);
1022
+ last = m.index + m[0].length;
1023
+ }
1024
+ if (k !== args.length) return null;
1025
+ return `"${out}${body.slice(last)}"`;
1026
+ }
1027
+ /** {fmt} / std::format: `"{}/{:>8}"` with [a, b] -> `"«a»/«b as {:>8}»"`; `{0}` is the first argument. */
1028
+ export function braceTextWithValues(lit, args) {
1029
+ const body = quotedBody(lit);
1030
+ if (body == null) return null;
1031
+ let out = '', next = 0, last = 0;
1032
+ const used = new Set();
1033
+ for (const m of body.matchAll(/\{\{|\}\}|\{(\d*)(:[^{}]*)?\}/g)) {
1034
+ if (m[0] === '{{' || m[0] === '}}') continue;
1035
+ const at = m[1] === '' ? next++ : Number(m[1]);
1036
+ if (at >= args.length) return null;
1037
+ used.add(at);
1038
+ const a = String(args[at]).trim();
1039
+ out += body.slice(last, m.index) + (m[2] && m[2] !== ':' ? `«${a} as {${m[2]}}»` : `«${a}»`);
1040
+ last = m.index + m[0].length;
1041
+ }
1042
+ if (used.size !== args.length) return null;
1043
+ return `"${out}${body.slice(last)}"`;
1044
+ }
1045
+ /** `std::cout << "a: " << x << '\n'` -> `"a: «x»\n"` (string and character literals kept, everything else a value). */
1046
+ function streamTextWithValues(parts) {
1047
+ let out = '';
1048
+ for (const p0 of parts) {
1049
+ const p = p0.trim();
1050
+ const q = quotedBody(p);
1051
+ if (q != null) { out += q; continue; }
1052
+ const ch = p.match(/^'((?:\\.|[^'\\])+)'$/);
1053
+ if (ch) { out += ch[1]; continue; }
1054
+ if (/^["']/.test(p) || !p) return null;
1055
+ out += `«${p}»`;
1056
+ }
1057
+ return `"${out}"`;
1058
+ }
1059
+ /** Split at top-level `<<` (strings and brackets skipped). */
1060
+ function splitShift(t) {
1061
+ const out = [];
1062
+ let d = 0, from = 0;
1063
+ for (let i = 0; i < t.length; i++) {
1064
+ const c = t[i];
1065
+ if (c === '"' || c === "'") { const q = c; for (i++; i < t.length && t[i] !== q; i++) if (t[i] === '\\') i++; continue; }
1066
+ if ('([{'.includes(c)) d++; else if (')]}'.includes(c)) d--;
1067
+ else if (d === 0 && c === '<' && t[i + 1] === '<') { out.push(t.slice(from, i)); from = i + 2; i++; }
1068
+ }
1069
+ out.push(t.slice(from));
1070
+ return out;
1071
+ }
1072
+ /** The arguments of the call that starts at `name(` in `t`, or null when its parentheses are not closed at the end. */
1073
+ function wholeCallArgs(t, name) {
1074
+ const at = t.indexOf('(', name.length - 1);
1075
+ const close = at >= 0 ? closeOf(t, at) : -1;
1076
+ if (close < 0 || t.slice(close + 1).trim().replace(/;$/, '').trim()) return null;
1077
+ return splitTopArgs(t.slice(at + 1, close));
1078
+ }
1079
+
1080
+ /**
1081
+ * C, C++, and Swift statements that must be said exactly or shown as code: messages with values inside, a value
1082
+ * written where a pointer points, `+=` / `-=` of a call, other compound operators, a statement that is a ternary, and
1083
+ * compile-time checks. Null for anything else (the usual reading takes over).
1084
+ */
1085
+ function sayExactly(first, head) {
1086
+ const t = String(first).trim().replace(/;\s*$/, '').trim();
1087
+ const c = C_FAMILY.has(LANG);
1088
+ let m, args;
1089
+ // Messages: printf / fprintf / puts / fmt::print / std::print / cout << … / Swift print("…\(x)").
1090
+ if (c && (m = t.match(/^(?:std::)?(printf|fprintf|dprintf|puts|fputs|perror)\s*\(/)) && (args = wholeCallArgs(t, m[0]))) {
1091
+ const fmtAt = m[1] === 'fprintf' || m[1] === 'dprintf' ? 1 : 0;
1092
+ const to = m[1] === 'fputs' ? args[1] : fmtAt ? args[0] : null;
1093
+ const lit = m[1] === 'fputs' ? args[0] : args[fmtAt];
1094
+ const text = /^(?:puts|fputs|perror)$/.test(m[1]) ? (quotedBody(lit) != null ? `"${quotedBody(lit)}"` : null) : lit && printfTextWithValues(lit, args.slice(fmtAt + 1));
1095
+ if (!text) return { kind: 'other', says: clip(t, 70) };
1096
+ return { kind: 'call', says: `Writes a log or message${to && !/^(?:stdout|stderr)$/.test(to.trim()) ? ` to ${words(to.trim())}` : ''}: ${text}`, callee: m[1] };
1097
+ }
1098
+ if (c && (m = t.match(/^(?:std::)?(sn?printf)\s*\(/)) && (args = wholeCallArgs(t, m[0]))) {
1099
+ const fmtAt = m[1] === 'snprintf' ? 2 : 1;
1100
+ const text = args[fmtAt] && printfTextWithValues(args[fmtAt], args.slice(fmtAt + 1));
1101
+ return text ? { kind: 'set', says: `Writes the text ${text} into ${targetWords(args[0].trim().replace(/^&/, ''))}` } : { kind: 'other', says: clip(t, 70) };
1102
+ }
1103
+ if (c && (m = t.match(/^(?:fmt|std)::(print|println)\s*\(/)) && (args = wholeCallArgs(t, m[0]))) {
1104
+ const lit = /^"/.test(args[0] || '') ? 0 : 1;
1105
+ const text = args[lit] && braceTextWithValues(args[lit], args.slice(lit + 1));
1106
+ return text ? { kind: 'call', says: `Writes a log or message${lit ? ` to ${words(args[0].trim())}` : ''}: ${text}`, callee: m[1] } : { kind: 'other', says: clip(t, 70) };
1107
+ }
1108
+ if (c && /^(?:std::)?(?:cout|cerr|clog)\s*<</.test(t)) {
1109
+ const parts = splitShift(t).slice(1);
1110
+ const text = parts.length && parts.length <= 12 ? streamTextWithValues(parts) : null;
1111
+ return text ? { kind: 'call', says: `Writes a log or message: ${text}`, callee: 'cout' } : { kind: 'other', says: clip(t, 70) };
1112
+ }
1113
+ if (LANG === 'swift' && (m = t.match(/^(print|debugPrint|NSLog)\s*\(\s*(".*")\s*\)$/)) && (args = wholeCallArgs(t, m[1] + '('))?.length === 1) {
1114
+ const text = swiftTextWithValues(args[0]);
1115
+ if (text) return { kind: 'call', says: `Writes a log or message: ${text}`, callee: m[1] };
1116
+ }
1117
+ // `eItem newitem, curitem = f(x);` declares two names at once: shown as code (it is not a call to eItem).
1118
+ if (c && /^(?:(?:const|unsigned|signed|struct|static|long|short)\s+)*[A-Za-z_][\w:]*(?:\s*\*+\s*|\s+)\**[A-Za-z_]\w*\s*(?:=|,)/.test(t) && !/^(?:return|else|case|goto|delete|throw|new|sizeof)\b/.test(t) && splitTopArgs(t).length > 1) return { kind: 'other', says: clip(t, 70) };
1119
+ if (c) {
1120
+ // `*out = v` writes v where out points (out itself does not change); `*p++ = v` is shown as code.
1121
+ if ((m = t.match(/^\*\s*([A-Za-z_][\w.]*(?:->[A-Za-z_]\w*)*)\s*=(?!=)\s*(.+)$/))) {
1122
+ const v = sayValue(m[2]) ?? sayArithmetic(m[2]);
1123
+ return v ? { kind: 'set', says: `Writes ${v} where ${targetWords(m[1].replace(/->/g, '.'))} points` } : { kind: 'other', says: clip(t, 70) };
1124
+ }
1125
+ if (/^static_assert\s*\(/.test(t)) return { kind: 'check', says: 'Checks a fact about the types when the code is compiled' };
1126
+ }
1127
+ // Compound assignment: `x += f(y)` adds (it does not replace x); bit and shift operators are shown as code.
1128
+ if ((m = String(head).trim().replace(/;\s*$/, '').match(/^([A-Za-z_][\w.\[\]>-]*)\s*(\+|-|\||&|\^|<<|>>)=\s*(.+)$/)) && !/[-+]$/.test(m[1])) {
1129
+ if (m[2] !== '+' && m[2] !== '-') return { kind: 'other', says: clip(t, 70) };
1130
+ const value = c ? cNormalize(m[3]) : m[3];
1131
+ const v = sayValue(value) ?? sayArithmetic(value);
1132
+ const target = targetWords(m[1].replace(/->/g, '.'));
1133
+ return v ? { kind: 'set', says: `${m[2] === '+' ? 'Adds' : 'Subtracts'} ${v} ${m[2] === '+' ? 'to' : 'from'} ${target}` } : { kind: 'other', says: clip(t, 70) };
1134
+ }
1135
+ // A statement that is a ternary (`locking ? a(x) : b(x);`) does one of two things: shown as code.
1136
+ const bare = stripQuotedText(t);
1137
+ if (!/^(?:return|throw|if|for|while|switch|case|let|var|guard)\b/.test(t) && !/^[\w.\[\]>-]+\s*[-+*/%|&^]?=(?!=)/.test(t) && /\s\?\s.*\s:\s/.test(bare)) return { kind: 'other', says: clip(t, 70) };
1138
+ return null;
1139
+ }
1140
+ const stripQuotedText = (s) => String(s).replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, 'Q');
1141
+
1142
+
1143
+ /**
1144
+ * One statement as a step: its short words (`says`), its kind, and `expr`, the full meaning underneath the words
1145
+ * (thunder-expr-v1, see meaning.mjs): every name, argument, and value, or `{ kind: 'code', text }` when the statement
1146
+ * is not fully understood. The words stay short; `expr` keeps everything one level down.
1147
+ */
1148
+ export function classifyStatement(raw, opts) {
1149
+ const r = classifyWords(raw, opts);
1150
+ if (!r.expr) r.expr = statementExpr(raw);
1151
+ return r;
1152
+ }
1153
+ /** The language of the function being read ('' outside one). */
1154
+ export const readingLanguage = () => FN_CONTEXT?.language || '';
1155
+ /** A statement's meaning tree, read in the language of the function around it. */
1156
+ export function statementExpr(raw) {
1157
+ let text = String(raw ?? '').trim();
1158
+ // An annotation line (`@Override`) belongs to the declaration under it.
1159
+ if (/^@\w+/.test(text) && text.includes('\n')) text = text.replace(/^(?:@\w+(?:\([^)]*\))?[ \t]*\r?\n\s*)+/, '');
1160
+ return parseStatement(text, readingLanguage());
1161
+ }
1162
+ const codeExpr = (text) => ({ kind: 'code', text: String(text ?? '').replace(/\s+/g, ' ').trim() });
1163
+
1164
+ function classifyWords(raw, { inner = 0 } = {}) {
330
1165
  const text = String(raw).trim();
331
1166
  // A condition written over several lines (`if (\n a &&\n b\n) {`) is read whole.
332
1167
  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);
1168
+ if (/^(?:if|else\s+if|while|for|switch)\s*\($/.test(first.replace(/\s*\{$/, '')) || (/^(?:if|else\s+if|while)\s*\(/.test(first) && !balancedText(first.replace(/\{\s*$/, '')))) {
1169
+ const o = text.indexOf('('), c = closeOf(text, o);
335
1170
  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
1171
  }
1172
+ // A brace-less `if (x)` whose one statement is on the next line(s): `if (a)\n throw new E(…);` is one step.
1173
+ if (/^(?:if|else\s+if)\s*\(/.test(text) && text.includes('\n')) {
1174
+ const o = text.indexOf('('), c = closeOf(text, o);
1175
+ const rest = c > 0 ? text.slice(c + 1).trim() : '';
1176
+ if (rest && !rest.startsWith('{') && !text.slice(c + 1).split('\n')[0].trim()) first = `${text.slice(0, c + 1).replace(/\s+/g, ' ').replace(/\(\s+/g, '(').replace(/\s+\)/g, ')')} ${rest.replace(/\s+/g, ' ')}`.trim();
1177
+ }
1178
+ // `return (` with JSX on the next line: what is drawn on screen.
1179
+ if (/^return\s*\(\s*$/.test(first) && /^\s*</.test(text.split('\n')[1] || '')) first = `return (${text.split('\n')[1].trim()}`;
1180
+ // A statement written over several lines (`return a\n && b`, `x =\n cond ? y : z`, `return (\n <div>…`) is read
1181
+ // whole, so a value is never cut to its first line.
1182
+ else if (text.includes('\n') && !/^(?:if|else|elif|elsif|for|foreach|while|until|switch|try|catch|finally|do|match|loop|when|case|default|unless|with|def|fn|fun|func|function|class|struct|interface|enum|impl|object|begin|select|using|lock)\b/.test(first) && (!/[{:]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^(?:const|let|var|val)\s*[{[]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first)) && !/=>\s*\{?\s*$/.test(first) && text.length < 2000 && balancedText(text) && (!/\{\s*$/.test(text.split('\n')[0]) || /^(?:const|let|var|val)\s*[{[]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first))) {
1183
+ const lines = text.split('\n');
1184
+ const joined = lines.map((l) => l.trim()).join(' ');
1185
+ if (!bracketsClosed(first) || /(?:[-+*/%&|^=<>?:.,(\[]|\b(?:and|or|not|in))\s*$/.test(first) || /^\s*(?:[-+*/%&|^=<>?:.)\]]|&&|\|\||\b(?:and|or)\b)/.test(lines[1] || '')) first = joined;
1186
+ }
1187
+ // An annotation line (`@Override`) belongs to the declaration under it.
1188
+ let jmp;
1189
+ if ((jmp = text.match(/^(continue|break)(?:\s+([A-Za-z_]\w*))?;?$/))) return { kind: 'call', says: jmp[1] === 'break' ? `Leaves the loop${jmp[2] ? ` (${jmp[2]})` : ''}` : `Skips to the next one${jmp[2] ? ` (${jmp[2]})` : ''}`, code: text, jump: jmp[1] };
1190
+ if (/^@\w+(?:\([^)]*\))?$/.test(first) && text.includes('\n')) first = text.split('\n').map((l) => l.trim()).find((l) => l && !/^@\w+(?:\([^)]*\))?$/.test(l)) ?? first;
337
1191
  // TypeScript-only syntax that changes nothing for a reader: casts, non-null assertions, optional calls.
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.')
1192
+ // (PHP `foreach ($a as $k => $v)` is a loop, not a cast.)
1193
+ let head = (/^foreach\b/.test(first) ? first : first
1194
+ .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.')
340
1195
  // Java/C# casts: ((JsonTreeReader) reader).promote() -> reader.promote(); (int) x -> x
341
- .replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, '$1').replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, '$1');
342
- const code = clip(head, 90);
1196
+ .replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, '$1').replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, '$1')
1197
+ // .NET: `.ConfigureAwait(false)` only says which thread carries on; it changes nothing a reader needs.
1198
+ .replace(/\.ConfigureAwait\(\s*(?:false|true)\s*\)/g, '');
1199
+ // (C, C++, and Swift show the code exactly as written: `window!.root` stays `window!.root`.)
1200
+ const code = clip(C_FAMILY.has(LANG) || LANG === 'swift' ? first : head, 90);
343
1201
  let m;
344
1202
  const innerNote = inner ? ` (${inner} step${inner === 1 ? '' : 's'} inside)` : '';
1203
+ const exact = C_FAMILY.has(LANG) || LANG === 'swift' ? sayExactly(first, head) : null;
1204
+ if (exact) return { ...exact, code };
1205
+ // A brace-less C loop: `for (…)\n stmt;` is the loop with that one statement inside it (never the header alone).
1206
+ if (C_FAMILY.has(LANG) && /^(?:for|while)\s*\(/.test(text)) {
1207
+ const flat = text.replace(/\s+/g, ' ').trim();
1208
+ const close = closeOf(flat, flat.indexOf('('));
1209
+ const rest = close > 0 ? flat.slice(close + 1).trim() : '';
1210
+ if (rest && !/^[{;]/.test(rest)) {
1211
+ const loop = classifyStatement(flat.slice(0, close + 1));
1212
+ if (loop.kind === 'loop') return { ...loop, says: loop.says.replace(/ \(\d+ steps? inside\)$/, ''), code: clip(flat.slice(0, close + 1), 90), inline: rest };
1213
+ return { kind: 'other', says: clip(flat, 70), code: clip(flat, 90) };
1214
+ }
1215
+ }
1216
+ // C and C++ read like the rest once `p->x` is `p.x`, C casts are dropped, and `Type *name = v` is `var name = v`.
1217
+ if (C_FAMILY.has(LANG)) head = cNormalize(head);
1218
+ // `if (x) [[unlikely]] {`: the attribute is a hint to the compiler, not part of the check or the block.
1219
+ if (C_FAMILY.has(LANG)) head = head.replace(/^((?:else\s+)?(?:if|while|for|switch)\s*\(.*\))\s*\[\[[^\[\]]*\]\]\s*(?=\{)/, '$1 ');
1220
+ // Swift marks a call that can fail with `try` (and one that waits with `await`): the step is the call itself.
1221
+ if (LANG === 'swift' && !/^do\b/.test(head)) head = head.replace(/^(return\s+)?(?:(?:try[?!]?|await)\s+)+/, '$1').replace(/(\w|\))\?(?=\()/g, '$1');
1222
+ if (LANG === 'swift' && /^self\.init\s*\(/.test(head)) return { kind: 'call', says: 'Sets up the way another init does', code };
1223
+ const cdecl = C_FAMILY.has(LANG) ? cDeclaration(head) : null;
1224
+ if (cdecl) {
1225
+ if (cdecl.value == null) return { kind: 'set', says: `Declares ${words(cdecl.name)}`, code };
1226
+ if (cdecl.ctor) return { kind: 'set', says: `Creates a new ${words(cdecl.type.replace(/<.*$/, '').split('::').pop())} as ${words(cdecl.name)}`, code };
1227
+ // A C initializer: `Library lib = { .max_books = 3, .overflow = {0} }` names the facts it sets.
1228
+ if (/^\{/.test(cdecl.value.trim()) && !/^\{\s*\}$/.test(cdecl.value.trim())) {
1229
+ const keys = [...cdecl.value.matchAll(/(?:^|[{,])\s*\.(\w+)\s*=/g)].map((k) => words(k[1]));
1230
+ const what = words(cdecl.type.replace(/<.*$/, '').split('::').pop());
1231
+ return { kind: 'set', says: cdecl.array ? `Sets ${words(cdecl.name)} to a list of values` : keys.length ? `Sets ${words(cdecl.name)} to a new ${what} with ${listWords(keys.length > 4 ? [...keys.slice(0, 4), 'more'] : keys)}` : `Sets ${words(cdecl.name)} to a new ${what}`, code };
1232
+ }
1233
+ head = `var ${cdecl.name} = ${cdecl.value}`;
1234
+ }
1235
+ const cSays = C_FAMILY.has(LANG) ? sayCLibrary(head) : null;
1236
+ if (cSays) return { ...cSays, code };
1237
+ const native = sayNativeShape(head, text, innerNote);
1238
+ if (native) return { ...native, code };
1239
+ // A loop's own exits, written after a check: `if (done) break;`.
1240
+ if (/^break\s*;?$/.test(head)) return { kind: 'call', says: 'Leaves the loop', code };
1241
+ if (/^continue\s*;?$/.test(head)) return { kind: 'call', says: 'Skips to the next round of the loop', code };
345
1242
  // One-line ifs: `if (x) return y;` and Ruby/Perl modifiers `return unless running?`, `notify if late`.
346
1243
  let inl;
347
- if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?|[\w$.]+(?:\+\+|--);?|(?:\+\+|--)[\w$.]+;?)$/)) && balanced(inl[2])) {
348
- return { kind: 'branch', says: `If ${sayCodeCondition(inl[2])}`, cond: inl[2], code, inline: inl[3] };
1244
+ if ((inl = head.match(/^(if|else\s+if)\s*\(/))) {
1245
+ const c = closeOf(head, head.indexOf('('));
1246
+ const body = c > 0 ? head.slice(c + 1).trim() : '';
1247
+ // (`if (x) ++q;` has a statement after its condition: `++q` is not the condition going on.)
1248
+ if (body && !/^[{:]/.test(body) && !/^then\b/.test(body) && !/\belse\b/.test(body) && (!/^(?:&&|\|\||and\b|or\b|is\b|in\b|not\b|instanceof\b|[-+*/%<>=!?.])/.test(body) || /^(?:\+\+|--)[A-Za-z_][\w.]*\s*;?$/.test(body) || (C_FAMILY.has(LANG) && /^\*\s*[A-Za-z_][\w.]*(?:->\w+)*\s*=(?!=)/.test(body))) && !/:\s*$/.test(body)) {
1249
+ const cond = head.slice(head.indexOf('(') + 1, c);
1250
+ return { kind: 'branch', says: `If ${sayCodeCondition(cond)}`, cond, code, inline: body };
1251
+ }
349
1252
  }
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])) {
1253
+ 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]) && !/\[[^\]]*\bfor\b/.test(head)) {
351
1254
  const cond = sayCodeCondition(inl[3]);
352
1255
  return { kind: 'branch', says: inl[2] === 'unless' ? `If not: ${cond}` : `If ${cond}`, cond: inl[3], negate: inl[2] === 'unless', code, inline: inl[1] };
353
1256
  }
@@ -377,15 +1280,44 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
377
1280
  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 };
378
1281
  if (/^default\s*(?::|->)/.test(head)) return { kind: 'check', says: 'Otherwise', code, caseLabel: true };
379
1282
  // Failures
380
- if ((m = head.match(/^(?:throw|raise)\s+(?:new\s+)?([A-Za-z_][\w.]*)?/)) || /^panic!?\s*\(/.test(head)) {
381
- const name = m?.[1] ? m[1].split('.').pop() : null;
382
- const msg = (head.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
1283
+ if ((m = head.match(/^(?:throw|raise)\s+(?:new\s+)?([A-Za-z_][\w.]*(?:::[A-Za-z_]\w*)*)?/)) || /^panic!?\s*\(/.test(head)) {
1284
+ const name = m?.[1] ? m[1].split(/\.|::/).pop() : null;
1285
+ // C++ error types are often lowercase (std::runtime_error): still a type, said in words.
1286
+ if (name && C_FAMILY.has(LANG) && /^[a-z]/.test(name)) {
1287
+ const msg = (head.match(/"([^"]{1,60})"/) || [])[1];
1288
+ return { kind: 'fail', says: `Fails with ${words(name)}${msg ? `: "${msg}"` : ''}`, code, error: name, ...(msg ? { message: msg } : {}) };
1289
+ }
1290
+ const msg = firstText(head);
383
1291
  const said = name && /^[a-z]/.test(name) ? `the error made by ${words(name)}` : name;
384
1292
  return { kind: 'fail', says: `Fails${said ? ` with ${said}` : ''}${msg ? `: "${msg}"` : ''}`, code, ...(name ? { error: name } : {}), ...(msg ? { message: msg } : {}) };
385
1293
  }
386
1294
  // An HTTP error response (4xx/5xx) is a Stop: the request is refused, with a status and a message.
1295
+ // Loading code at run time: const { a } = await import('./x') -> "Loads a from ./x".
1296
+ let dyn;
1297
+ if ((dyn = head.match(/^(?:const|let|var)\s*(?:\{([^}]*)\}|([A-Za-z_$][\w$]*))\s*=\s*(?:await\s+)?(?:import|require)\(\s*['"`]([^'"`]+)['"`]\s*\)\s*;?$/))) {
1298
+ const names = dyn[1] ? dyn[1].split(',').map((x) => x.split(':').pop().trim()).filter(Boolean).map(words) : [words(dyn[2])];
1299
+ return { kind: 'set', says: `Loads ${listWords(names)} from ${dyn[3]}`, code };
1300
+ }
1301
+ // `res.status(500);` on its own only sets the status; what is sent (and the end of the request) comes after.
1302
+ let st0;
1303
+ if ((st0 = head.match(/^(?:res|reply|response|resp)\s*\.\s*(?:status|code)\s*\(\s*(\d{3})\s*\)\s*;?$/))) return { kind: 'set', says: `Sets the response status to ${st0[1]}${HTTP_STATUS[st0[1]] ? ` ${HTTP_STATUS[st0[1]]}` : ''}`, code };
387
1304
  const httpFail = httpErrorOf(head);
388
1305
  if (httpFail) return { ...httpFail, code };
1306
+ // A response sent back to the caller: "Returns user (201 Created)", not "Calls json".
1307
+ const sent = responseOf(head);
1308
+ if (sent) return { ...sent, code };
1309
+ // Common libraries read as what they do (an ORM, an HTTP client, a cache, tokens, payments): see libraries.mjs.
1310
+ const lib = libraryStep(head);
1311
+ if (lib) return { ...lib, code };
1312
+ // Middleware handing on: `next()` lets the request go on to the next step; `next(err)` passes an error on.
1313
+ let nx;
1314
+ const nk = nextKind();
1315
+ if (nk === 'pipeline' && (nx = head.match(/^(return\s+)?(?:await\s+)?next\s*\(\s*(.*?)\s*\)\s*;?$/))) {
1316
+ return nx[1] ? { kind: 'return', says: 'Returns the answer of the next handler in the pipeline', code, passes: true } : { kind: 'call', says: 'Runs the next handler in the pipeline', code };
1317
+ }
1318
+ if (nk === 'middleware' && (nx = head.match(/^(?:return\s+)?(?:await\s+)?next\s*\(\s*(.*?)\s*\)\s*;?$/))) {
1319
+ return nx[1] && !/^(undefined|null)$/.test(nx[1]) ? (/^['"]route['"]$/.test(nx[1]) ? { kind: 'return', says: 'Skips to the next route', code, passes: true } : { kind: 'fail', says: `Fails with ${/^new\s+(\w+)/.exec(nx[1])?.[1] ?? 'the error'}: passes it on`, error: /^new\s+(\w+)/.exec(nx[1])?.[1] ?? 'an error', code }) : { kind: 'return', says: 'Lets the request go on to the next step', code, passes: true };
1320
+ }
389
1321
  // A redirect sends the person somewhere else: "Sends the person to the Google auth URL".
390
1322
  const redirect = redirectOf(head);
391
1323
  if (redirect) return { ...redirect, code };
@@ -394,23 +1326,34 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
394
1326
  const expr = stripTail(m[1]);
395
1327
  if (!expr) return { kind: 'return', says: 'Stops here', code };
396
1328
  const lastVal = expr.split(',').pop().trim();
397
- if (/,/.test(expr) && /^(?:err|error|e)$|^Err[A-Z]\w*$|^\w*Error$|^errors\.New\(|^fmt\.Errorf\(/.test(lastVal)) {
1329
+ // Go `return nil, err` gives an error back; `return output, err` gives both back (err is often nil).
1330
+ const others = expr.split(',').slice(0, -1).map((x) => x.trim());
1331
+ const zero = others.every((x) => /^(?:nil|0|0\.0|""|false|None|\w+\{\}|\[\]\w+\{\}|-1)$/.test(x));
1332
+ if (/,/.test(expr) && zero && /^(?:err|error|e)$|^Err[A-Z]\w*$|^\w*Error$|^errors\.New\(|^fmt\.Errorf\(/.test(lastVal)) {
398
1333
  const named = /^Err[A-Z]\w*$|^\w+Error$/.test(lastVal) ? `: ${lastVal}` : '';
399
1334
  return { kind: 'fail', says: `Returns an error to the caller${named}`, code };
400
1335
  }
401
1336
  if (/^(Err|Error)\s*\(/.test(expr) || /\berrors\.New\(|fmt\.Errorf\(/.test(expr)) {
402
- const msg = (expr.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
1337
+ const msg = firstText(expr);
403
1338
  return { kind: 'fail', says: `Returns an error${msg ? `: "${msg}"` : ''}`, code };
404
1339
  }
1340
+ const terms = splitLogic(expr);
1341
+ if (terms && terms.terms.length > 1) {
1342
+ // `return a && b`: every part is said, or the code is shown; never only the first part.
1343
+ const w = sayWhether(expr);
1344
+ return w ? { kind: 'return', says: `Returns ${w}`, code } : { kind: 'return', says: 'Returns a computed value', code, value: clip(expr, 60) };
1345
+ }
405
1346
  const chain = sayChain(expr);
406
1347
  if (chain) return { kind: 'return', says: `Returns ${chain}`, code };
1348
+ const py = sayPython(expr);
1349
+ if (py) return { kind: 'return', says: `Returns ${py}`, code };
407
1350
  if (/^\(?\s*\{/.test(expr)) {
408
1351
  // Name what is in it: { org, repos, avg: x } -> "Returns org, repos, and avg".
409
1352
  const keys = objectKeys(expr);
410
1353
  return { kind: 'return', says: keys.length ? `Returns ${listWords(keys.map(words))}` : 'Returns an object', code, ...(keys.length ? { keys } : {}) };
411
1354
  }
412
1355
  if (/^\(?\s*</.test(expr)) return { kind: 'return', says: 'Returns what to show on screen', code };
413
- const v = sayValue(expr) || sayWhether(expr);
1356
+ const v = sayValue(expr) || sayWhether(expr) || (C_FAMILY.has(LANG) || LANG === 'swift' ? sayArithmetic(expr) : null);
414
1357
  return { kind: 'return', says: v ? `Returns ${v}` : 'Returns a computed value', code, ...(v ? {} : { value: clip(expr, 60) }) };
415
1358
  }
416
1359
  // Loops
@@ -421,39 +1364,85 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
421
1364
  // A C-style loop with no counter of its own: `for (; pos < limit; i++)` / `for (;;)`.
422
1365
  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 };
423
1366
  // Pairs unpacked in a loop: for (const [key, value] of entries) / for key, value in items.items() / foreach ($a as $k => $v)
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*$/))) {
425
- const src = stripTail(m[3]).replace(/\($/, '()').replace(/^Object\.entries\((.+)\)$/, '$1').replace(/\.(?:items|entries)\(\)$/, '');
1367
+ 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*$/))) {
1368
+ const src = stripTail(m[3]).replace(/\($/, '()').replace(/^Object\.entries\((.+)\)$/, '$1').replace(/\.(?:items|entries|enumerated)\(\)$/, '');
426
1369
  return { kind: 'loop', says: `For each ${words(m[1])} and ${words(m[2])} in ${words(src.split('.').pop())}${innerNote}`, code };
427
1370
  }
428
1371
  if ((m = head.match(/^for\b\s*\(?\s*(?:const|let|var|val|final|auto|[\w<>\[\],? ]+?\s)?\s*\(?([\w$, _]+?)\)?\s+(?:of|in|:)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/))) {
429
1372
  return { kind: 'loop', says: `For each ${words(m[1].split(',').pop().trim())} in ${words(stripTail(m[2]).split('.').pop().replace(/\(\)$/, ''))}${innerNote}`, code };
430
1373
  }
431
1374
  if ((m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/))) return { kind: 'loop', says: `For each item in ${words(stripTail(m[1]).split('.').pop())}${innerNote}`, code };
432
- if ((m = head.match(/^foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/))) return { kind: 'loop', says: `For each ${words(m[1])} in ${words(m[2].split('.').pop())}${innerNote}`, code };
433
- if ((m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:\w+\s*=>\s*)?(\w+)\s*\)\s*\{?$/))) return { kind: 'loop', says: `For each ${words(m[2])} in ${words(m[1].split('.').pop())}${innerNote}`, code };
434
- if ((m = head.match(/^([\w.]+)\.each(?:_with_index)?\s+do\s*\|(\w+)/))) return { kind: 'loop', says: `For each ${words(m[2])} in ${words(m[1].split('.').pop())}${innerNote}`, code };
1375
+ if ((m = head.match(/^(?:await\s+)?foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/))) return { kind: 'loop', says: `For each ${words(m[1])} in ${words(m[2].split('.').pop())}${innerNote}`, code };
1376
+ if ((m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:&?(\w+)\s*=>\s*)?&?(\w+)\s*\)\s*\{?$/))) return { kind: 'loop', says: `For each ${m[2] ? `${words(m[2])} and ` : ''}${words(m[3])} in ${words(m[1].split('.').pop())}${innerNote}`, code };
1377
+ // Ruby one-line blocks: `items.each { |e| e.save if e.dirty? }` is a loop whose step is the block's body.
1378
+ if ((m = head.match(/^([\w.@]+(?:\([^()]*\))?)\.each(?:_with_index)?\s*\{\s*\|([^|]*)\|\s*(.+?)\s*\}$/))) return { kind: 'loop', says: `For each ${m[2].split(',').map((x) => words(x.replace(/^[*&]+/, '').trim())).join(', ')} in ${words(m[1].replace(/\(.*$/, '').replace(/^@/, '').split('.').pop())}`, code, inline: m[3] };
1379
+ if ((m = head.match(/^@?([\w.]+(?:\([^()]*\))?)\.each(?:_with_index)?\s+do\s*\|(\w+)/))) return { kind: 'loop', says: `For each ${words(m[2])} in ${words(m[1].replace(/\(.*$/, '').split('.').pop())}${innerNote}`, code };
435
1380
  if ((m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/))) return { kind: 'loop', says: `For each item in ${words(m[1].split('.').pop())}${innerNote}`, code };
436
1381
  if ((m = head.match(/^(?:while|until|loop)\b\s*\(?(.*?)\)?\s*(?:\{|:|do)?\s*$/))) return { kind: 'loop', says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
437
1382
  // Branches
438
1383
  // Go: `if err := open(); err != nil` -> "If open fails"; `if v, ok := m[k]; ok` -> "If k is in m".
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 };
1384
+ if ((m = head.match(/^(?:if|else\s+if)\s+(?:[\w]+\s*,\s*)?err\s*:?=\s*(.+?)(?:\.Error)?;\s*err\s*!=\s*nil\s*\{?\s*$/))) {
1385
+ const lib = sayLibraryCall(m[1]);
1386
+ const BASE = { Finds: 'find', Saves: 'save', Sends: 'send', Removes: 'remove', Changes: 'change', Reads: 'read', Turns: 'turn', Makes: 'make', Checks: 'check', Keeps: 'keep', Creates: 'create', Adds: 'add', Counts: 'count', Writes: 'write', Starts: 'start' };
1387
+ if (lib && BASE[lib.says.split(' ')[0]]) return { kind: 'branch', says: `If it cannot ${BASE[lib.says.split(' ')[0]]} ${lib.says.split(' ').slice(1).join(' ')}${innerNote}`, code };
1388
+ const fn = (m[1].match(/^([\w.]+)\s*\(/) || [])[1];
1389
+ if (fn) return { kind: 'branch', says: `If ${lastWords(fn)} fails${innerNote}`, code };
1390
+ }
440
1391
  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 }; }
1392
+ // C/C++ `if (x) { y; }` on one line: the condition is what is inside the parentheses, not the block after it.
1393
+ if (C_FAMILY.has(LANG) && (m = head.match(/^(?:else\s+)?if\s*\(/))) {
1394
+ const close = closeOf(head, head.indexOf('('));
1395
+ if (close > 0 && /^\s*(?:\[\[[^\[\]]*\]\]\s*)?\{/.test(head.slice(close + 1))) { const cond = head.slice(head.indexOf('(') + 1, close); return { kind: 'branch', says: `If ${sayCodeCondition(cond)}${innerNote}`, cond, code }; }
1396
+ }
1397
+ // `if (x) { a(); }` on one line: the condition is what is in the brackets; the block is the step's children.
1398
+ if (/^(?:if|else\s+if)\s*\(/.test(head)) {
1399
+ const o = head.indexOf('('), c = closeOf(head, o);
1400
+ const after = c > 0 ? head.slice(c + 1).trim() : '';
1401
+ if (/^\{./.test(after)) { const cond = head.slice(o + 1, c); return { kind: 'branch', says: `If ${sayCodeCondition(cond)}${innerNote}`, cond, code }; }
1402
+ }
441
1403
  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
1404
  if (/^switch\s*(?:true\s*)?\{$/.test(head)) return { kind: 'branch', says: `Checks these cases in order${innerNote}`, code };
443
1405
  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 };
444
1406
  if (/^(?:try|begin)\b/.test(head)) return { kind: 'try', says: `Tries the next steps and handles any error${innerNote}`, code };
445
1407
  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 };
446
1408
  if ((m = head.match(/^assert(?:_\w+|That|Equals|True|False|NotNull|Null)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
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 };
1409
+ // Sinatra / Rack `halt`: the request stops here, with what follows sent back.
1410
+ if (/^halt\b/.test(head) && FN_CONTEXT?.language === 'ruby') return { kind: 'fail', says: `Fails with halt: the request stops here${/^halt\s*$/.test(head) ? '' : ', sending back what follows'}`, error: 'halt', code };
1411
+ // Kotlin `require(x) { "msg" }` / `requireNotNull(x)` / `check(x)`: stops with an error when it does not hold.
1412
+ if (FN_CONTEXT?.language === 'kotlin' && (m = head.match(/^(require|requireNotNull|check|checkNotNull)\s*\((.*)\)\s*(?:\{\s*(["'])(.*)\3\s*\})?\s*;?$/)) && balancedText(m[2])) {
1413
+ const cond = m[1].endsWith('NotNull') ? `${m[2].trim()} != null` : m[2].trim();
1414
+ const c = sayCodeCondition(cond);
1415
+ const err = m[1].startsWith('require') ? 'IllegalArgumentException' : 'IllegalStateException';
1416
+ return { kind: 'check', says: `Checks that ${c}; otherwise stops with ${err}${m[4] ? `: "${clip(m[4], 60)}"` : ''}`, code };
1417
+ }
1418
+ // Go tests: t.Fatal stops the test as failed; t.Error marks it failed and carries on.
1419
+ if ((m = head.match(/^t\.(Fatal|Fatalf|Error|Errorf|FailNow|Fail)\s*\(/))) {
1420
+ const msg = firstText(head);
1421
+ return /^Fa(?:tal|ilNow)/.test(m[1]) ? { kind: 'fail', says: `Fails the test${msg ? `: "${msg}"` : ''}`, error: 'the test fails', code, ...(msg ? { message: msg } : {}) } : { kind: 'call', says: `Marks the test as failed${msg ? `: "${msg}"` : ''}, and goes on`, code };
1422
+ }
1423
+ if ((m = head.match(/^(?:expect|t\.(?:Run)|require\.\w+|assert\.\w+)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
448
1424
  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 }; }
449
1425
  if ((m = head.match(/^(?:using|lock|synchronized)\s*\((.+?)\)/))) return { kind: 'set', says: `Uses ${clip(m[1], 50)}`, code };
1426
+ // Python `with self.lock:` (no `as`): the steps inside run while holding it. (It read "Calls with", and its steps
1427
+ // were dropped.)
1428
+ if ((m = head.match(/^(?:async\s+)?with\s+(.+?):\s*$/))) return { kind: 'set', says: `Uses ${clip(m[1], 50)}`, code };
450
1429
  if (/^defer\b/.test(head)) return { kind: 'call', says: `At the end, ${clip(head.replace(/^defer\s+/, ''), 60)}`, code };
451
1430
  if (/^super\b/.test(head)) return { kind: 'call', says: 'Runs the parent version first', code };
1431
+ // yield: in C# (`yield return x`), Python, and JavaScript generators it hands back one more value; in Ruby, bare
1432
+ // `yield` runs the block the caller gave.
1433
+ let y;
1434
+ if ((y = head.match(/^yield\s+return\s+(.+?);?$/)) || (y = head.match(/^yield\s+(?!break\b)(.+?);?$/)) && !/^\(|^\|/.test(y?.[1] ?? '')) {
1435
+ return { kind: 'return', says: `Gives back, one at a time, ${payloadWords(y[1]) ?? 'a value'}`, code, yields: true };
1436
+ }
1437
+ if (/^yield\s+break\b/.test(head)) return { kind: 'return', says: 'Stops giving back values', code, yields: true };
452
1438
  if (/^yield\b/.test(head)) return { kind: 'call', says: 'Hands control to the given block', code };
453
1439
  if ((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) return { kind: 'return', says: `Returns a new ${words(m[1])}`, code };
454
1440
  if ((m = head.match(/^(?:[A-Z]\w*::)+([A-Z]\w*)$/))) return { kind: 'return', says: `Returns ${m[1]}`, code };
455
1441
  if (/^vec!?\[/.test(head)) return { kind: 'return', says: 'Returns a list', code };
456
1442
  // A bare value as a statement is an implicit return (Ruby, Rust, Kotlin/Scala expression bodies).
1443
+ // Only where a last value is given back (Ruby, Rust, Kotlin, Scala, Elixir); in Python or JavaScript a bare
1444
+ // `self.content` only reads the value.
1445
+ if (FN_CONTEXT && !/^(?:ruby|rust|kotlin|scala|elixir)$/.test(FN_CONTEXT.language || '') && /^(?:self|this|[a-z_][\w]*)\.[\w.]+$/.test(head)) return { kind: 'call', says: `Reads ${targetWords(head)}`, code };
457
1446
  if (/^(?:["'`].*["'`]|-?\d+(?:\.\d+)?|true|false|nil|null|None|self|[a-z_][\w.]*)$/.test(head) && !/^(?:else|end|break|next|redo|retry|pass)$/.test(head)) {
458
1447
  const v = sayValue(head);
459
1448
  return { kind: 'return', says: v ? `Returns ${v}` : 'Returns a value', code };
@@ -461,6 +1450,11 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
461
1450
  if ((m = head.match(/^(?:\+\+|--)?([@A-Za-z_$#][\w$#.]*)(\+\+|--)?;?$/)) && (/^(\+\+|--)/.test(head) || m[2])) return { kind: 'set', says: `${/\+\+/.test(head) ? 'Adds one to' : 'Subtracts one from'} ${targetWords(m[1].replace(/#/g, ''))}`, code };
462
1451
  if ((m = head.match(/^(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface|enum|record|object)\s+([A-Za-z_]\w*)/))) return { kind: 'set', says: `Defines ${words(m[1])}`, code };
463
1452
  if ((m = head.match(/^(?:async\s+)?(?:function|def|fn|fun|func)\s+([A-Za-z_]\w*)/))) return { kind: 'set', says: `Defines a helper, ${words(m[1])}`, code };
1453
+ // Java/C# methods and local functions written inside a body: `public String translateName(Field f) {`,
1454
+ // `static bool IsBase64UrlChar(char c) =>`.
1455
+ if ((m = head.match(/^(?:(?:public|private|protected|internal|static|final|abstract|override|virtual|sealed|async|unsafe|synchronized|open)\s+)*([A-Za-z_][\w.]*(?:<[^()]*>)?(?:\[\])*\??)\s+([A-Za-z_]\w*)\s*\([^()]*\)\s*(?:throws\s+[\w., ]+)?\s*(=>.*|\{|(?=$))\s*$/)) && (m[3] !== '' || /^[^\n]*\n\s*\{/.test(text)) && !/^(?:return|new|await|throw|yield|else|if|for|foreach|while|switch|catch|using|lock|case|when|function|def|fn|func|fun|class|do|try|go|defer|var|let|const|val|in|is|as|not|and|or)$/.test(m[1])) {
1456
+ return { kind: 'set', says: `Defines a helper, ${words(m[2])}`, code };
1457
+ }
464
1458
  if ((m = head.match(/^(?:const|let|var|val)\s+([A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=>/))) return { kind: 'set', says: `Defines a helper, ${words(m[1])}`, code };
465
1459
  if ((m = head.match(/^(?:const|let|var|val)\s+([{[])\s*(.*?)\s*[}\]]\s*(?::\s*[^=]+)?=\s*(.+)$/))) {
466
1460
  const names = m[2].split(',').map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, '')).filter(Boolean).map(words);
@@ -469,6 +1463,7 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
469
1463
  return { kind: 'set', says: `Takes ${names.slice(0, 4).join(', ')}${names.length > 4 ? ', …' : ''} from ${from}`, code };
470
1464
  }
471
1465
  if ((m = head.match(/^(?:var|const)\s*\($/))) return { kind: 'set', says: 'Declares some values', code };
1466
+ if ((m = head.match(/^(?:final\s+)?(?:int|long|double|float|boolean|bool|char|byte|short|string|String|decimal|[A-Z][\w.]*(?:<[^=;()]*>)?(?:\[\])*\??)\s+([a-z_]\w*(?:\s*,\s*[a-z_]\w*)*)\s*;$/))) return { kind: 'set', says: `Declares ${m[1].split(/\s*,\s*/).map(words).join(', ')}`, code };
472
1467
  if ((m = head.match(/^var\s+([\w, ]+?)\s+[\w.*\[\]]+$/))) return { kind: 'set', says: `Declares ${m[1].split(/\s*,\s*/).map(words).join(', ')}`, code };
473
1468
  // Typed declaration: Type name = value (Java, C#, C++); the value may continue on the next line.
474
1469
  if ((m = head.match(/^(?:final\s+|static\s+|readonly\s+)*([A-Z][\w.]*(?:<[^=]*>)?(?:\[\])?|int|long|double|float|boolean|bool|char|byte|short|string|decimal|var|auto)\s+([a-zA-Z_$][\w$]*)\s*=(?!=)\s*(.*)$/))) {
@@ -476,34 +1471,69 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
476
1471
  const c = value ? callee(value) : null;
477
1472
  const everyday = value ? sayPython(value) || sayCommon(value) : null;
478
1473
  if (everyday) return { kind: 'set', says: `Sets ${target} to ${everyday}`, code };
479
- if (c) {
1474
+ if (c && wholeValueCall(value)) {
480
1475
  const known = sayCall(c, firstArgs(value));
481
1476
  if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
482
- if (/^new\s/.test(value)) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
1477
+ if (/^new\s/.test(value) || makesType(c)) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
483
1478
  return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
484
1479
  }
485
1480
  const v = value ? sayValue(value) : null;
486
1481
  return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
487
1482
  }
488
1483
  // Assignment (not comparisons)
489
- if ((m = head.replace(/^(?:final\s+)?(?!return\b|throw\b|yield\b|await\b|new\b)[A-Z][\w.]*(?:<[^=;]*?>)?(?:\[\])*\??\s+(?=[a-z_]\w*\s*=[^=])/, '').match(/^(?:(?:const|let|var|val|final|auto|my|local)\s+)?(?:mut\s+)?([@A-Za-z_$#][\w$#.\[\]'"@]*?(?:\s*,\s*[@A-Za-z_$#][\w$#.@]*)*)(?:\s*:\s*[\w<>\[\]?, .|]+)?\s*(:=|\+=|-=|\*=|\/=|\|\|=|\?\?=|=)(?!=)\s*(.*)$/)) && !/^(?:if|for|while|return)\b/.test(head)) {
1484
+ if ((m = head.replace(/^(?:final\s+)?(?!return\b|throw\b|yield\b|await\b|new\b)[A-Z][\w.]*(?:<[^=;]*?>)?(?:\[\])*\??\s+(?=[a-z_]\w*\s*=[^=])/, '').match(/^(?:(?:const|let|var|val|final|auto|my|local)\s+)?(?:mut\s+)?([@A-Za-z_$#][\w$#.@]*(?:\[[^\]=]*\][\w$#.@]*)*(?:\s*,\s*[@A-Za-z_$#][\w$#.@]*)*)(?:\s*:\s*[\w<>\[\]?, .|]+)?\s*(:=|\+=|-=|\*=|\/=|\|\|=|\?\?=|\.=|%=|&&=|=)(?!=)\s*(.*)$/)) && !/^(?:if|for|while|return)\b/.test(head)) {
490
1485
  const target = m[1].split(/\s*,\s*/).filter((t) => t !== '_').map(targetWords).join(', ') || targetWords(m[1]);
491
- const value = stripTail(m[3]);
1486
+ let value = stripTail(m[3]);
1487
+ // `a = b = x`: both names get x.
1488
+ let also = '';
1489
+ const chained = m[2] === '=' && value.match(/^([@$]?[A-Za-z_][\w$.]*)\s*=(?!=)\s*(.+)$/);
1490
+ if (chained) { also = ` (and as ${targetWords(chained[1])})`; value = chained[2]; }
1491
+ const valueWords = (v) => sayValue(v) ?? sayArithmetic(v);
1492
+ // A value with a fallback (`rel or url`, `options || null`, `a ?? b`): both parts, or the code.
1493
+ const fb = /[=!<>]=|\bnot\b|!(?!=)|\s[<>]\s|\bis\b/.test(value.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, 'Q')) ? null : fallbackWords(value);
1494
+ if (fb === false) return { kind: 'other', says: clip(head, 70), code };
1495
+ if (fb && m[2] === '=' && !/\[/.test(m[1])) return { kind: 'set', says: `Sets ${target} to ${fb}${also}`, code };
1496
+ // A value stored under a key keeps the key: `headers[key] = v` -> "Stores v under key in headers", never
1497
+ // "Sets headers to ..." (that would say the whole container was replaced).
1498
+ // Go `xs = append(xs, v)`: v is added to the end of xs.
1499
+ const app = m[2] !== '+=' && value.match(/^append\(\s*([\w$.]+)\s*,\s*(.+)\)$/);
1500
+ if (app && app[1] === m[1].trim()) { const v = /,/.test(app[2].replace(/\([^()]*\)/g, '')) ? null : valueWords(app[2].trim()); return { kind: 'set', says: `Adds ${v ?? 'to the end of'}${v ? ' to the end of' : ''} ${target}`, code }; }
1501
+ if (/\[\s*\]$/.test(m[1]) && m[2] === '=') { const v = valueWords(value); return { kind: 'set', says: `Adds ${v ?? 'a value'} to the end of ${targetWords(m[1].replace(/\[\s*\]$/, ''))}`, code }; }
1502
+ const keyedAt = m[1].indexOf('[');
1503
+ if (keyedAt > 0 && /\]$/.test(m[1]) && !/,/.test(m[1])) {
1504
+ const container = targetWords(m[1].slice(0, keyedAt));
1505
+ const keys = [...m[1].slice(keyedAt).matchAll(/\[\s*([^\]]*?)\s*\]/g)].map((k) => k[1]);
1506
+ const keyWords = (k) => (/^\$\d/.test(k) ? `\`${k}\`` : /^["'`].*["'`]$/.test(k) ? `"${k.slice(1, -1)}"` : /^:\w+$/.test(k) && FN_CONTEXT?.language === 'ruby' ? `"${k.slice(1)}"` : /^[\w$.]+$/.test(k) ? possessiveWords(k) : `\`${k}\``);
1507
+ const v = value ? valueWords(value) : null;
1508
+ const what = v ?? 'a value';
1509
+ const where = keys.length === 1 ? `under ${keyWords(keys[0])} in ${container}` : `at ${keys.map(keyWords).join(', then ')} in ${container}`;
1510
+ if (m[2] === '=') return { kind: 'set', says: / if .*, otherwise /.test(what) ? `Stores ${where}${also}: ${what}` : `Stores ${what} ${where}${also}`, code };
1511
+ if (m[2] === '||=' || m[2] === '??=') return { kind: 'set', says: `Stores ${what} ${where}, if nothing is there yet`, code };
1512
+ if (m[2] === '+=' || m[2] === '.=') return { kind: 'set', says: `Adds ${what} to what is stored ${where}`, code };
1513
+ return { kind: 'other', says: clip(head, 70), code };
1514
+ }
1515
+ if (m[2] === '*=' || m[2] === '/=') { const v = valueWords(value) ?? null; return v ? { kind: 'set', says: `${m[2] === '*=' ? 'Multiplies' : 'Divides'} ${target} by ${v}`, code } : { kind: 'other', says: clip(head, 70), code }; }
1516
+ if (m[2] === '||=' || m[2] === '??=') { const v = valueWords(value); return { kind: 'set', says: v ? `Sets ${target} to ${v}, if it has no value yet` : `Sets ${target}, if it has no value yet`, code }; }
1517
+ if (m[2] === '.=') { const v = valueWords(value); return { kind: 'set', says: v ? `Adds ${v} to the end of ${target}` : `Adds to the end of ${target}`, code }; }
1518
+ if (m[2] === '%=' || m[2] === '&&=') return { kind: 'other', says: clip(head, 70), code };
492
1519
  // A yes/no value: `ok = proxy and scheme != "https"` -> "Works out ok: whether proxy and scheme is not https".
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 };
1520
+ if (m[2] === '=' && fb == null && !/^(?:if|unless|match|when|case)\b/.test(value) && !/[(?]/.test(value.replace(/^\(|\)$/g, '')) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(value.replace(/->|=>/g, '.').replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, 'Q')) && !/=>/.test(value) && !((C_FAMILY.has(LANG) || LANG === 'swift') && /<<|>>/.test(stripQuotedText(value)))) return { kind: 'set', says: `Works out ${target}: whether ${sayCodeCondition(value)}`, code };
494
1521
  // self.max_books = max_books: the Thing keeps what it was given.
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 };
1522
+ if (m[2] === '=' && /^[A-Za-z_]\w*$/.test(value) && m[1].split('.').pop() === value && /^(self|this)\./.test(m[1])) {
1523
+ // Only an input is "given": a value made in this function is kept, not given (C, C++, Swift check the inputs).
1524
+ const given = !(C_FAMILY.has(LANG) || LANG === 'swift') || !FN_CONTEXT?.params || FN_CONTEXT.params.some((p) => p.name === value);
1525
+ return { kind: 'set', says: given ? `Keeps the ${words(value)} it is given` : `Keeps ${words(value)} as its own ${words(value)}`, code };
1526
+ }
496
1527
  const chain = value ? (sayPython(value) || sayChain(value)) : null;
497
1528
  if (chain) return { kind: 'set', says: `Works out ${target}: ${chain}`, code };
498
1529
  const common = value ? sayCommon(m[3].trim().replace(/;$/, '')) || sayCommon(value) : null;
1530
+ if (common && (m[2] === '+=' || m[2] === '-=') && (C_FAMILY.has(LANG) || LANG === 'swift')) return { kind: 'set', says: `${m[2] === '+=' ? 'Adds' : 'Subtracts'} ${common} ${m[2] === '+=' ? 'to' : 'from'} ${target}`, code };
499
1531
  if (common) return { kind: 'set', says: `Sets ${target} to ${common}`, code };
500
- const keyed = m[2] === '=' && m[1].match(/^([\w$.]+)\[\s*([^\]]+?)\s*\]$/);
501
- if (keyed) return { kind: 'set', says: `Records ${words(keyed[2].replace(/["'`]/g, ''))} in ${targetWords(keyed[1])}`, code };
502
1532
  const c = callee(value);
503
- if (c) {
1533
+ if (c && wholeValueCall(value)) {
504
1534
  const known = sayCall(c, firstArgs(value));
505
1535
  if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
506
- if (/^new\s/.test(value)) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
1536
+ if (/^new\s/.test(value) || makesType(c)) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
507
1537
  return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
508
1538
  }
509
1539
  if (!value) return { kind: 'set', says: `Works out ${target}`, code };
@@ -523,6 +1553,9 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
523
1553
  const owner = m[1].split('.').filter((p) => !/^(self|this)$/.test(p));
524
1554
  const where = owner.length > 1 ? `${words(owner[owner.length - 2])}'s ${words(owner[owner.length - 1])}` : words(owner[0] || m[1]);
525
1555
  const added = /^new\s+([A-Z]\w*)/.exec(head.slice(head.indexOf('(') + 1))?.[1];
1556
+ const open0 = head.indexOf('('), close0 = closeOf(head, open0);
1557
+ const argText = close0 > open0 ? head.slice(open0 + 1, close0) : '';
1558
+ if (splitTopArgs(argText).length > 1) return { kind: 'call', says: `Adds to ${where}`, code, callee: m[1] };
526
1559
  return { kind: 'call', says: added ? `Adds a new ${words(added)} to ${where}` : m[2] && /^[A-Za-z_][\w$]*$/.test(m[2]) && m[2] !== 'new' ? `Adds ${words(m[2])} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
527
1560
  }
528
1561
  const c = callee(head);
@@ -554,6 +1587,30 @@ function asCall(list, i) {
554
1587
 
555
1588
  const CLAUSE = /^(?:elif\b|elsif\b|else\s+if\b|else\b|except\b|catch\b|rescue\b|finally\b|ensure\b)/;
556
1589
 
1590
+ /**
1591
+ * A catch clause as a tree: which errors it handles and the name it gives the error. `catch (e)`, `catch (IOException
1592
+ * | TimeoutException e)`, `except (A, B) as e`, `rescue Foo, Bar => e`. Anything else is kept as code.
1593
+ */
1594
+ function catchExpr(head) {
1595
+ const h = String(head).trim().replace(/\s*[:{]\s*$/, '').replace(/\s+/g, ' ');
1596
+ const m = h.match(/^(?:catch|except|rescue)\b\s*(.*)$/);
1597
+ if (!m) return codeExpr(h);
1598
+ let rest = m[1].trim();
1599
+ if (rest.startsWith('(') && closeOf(rest, 0) === rest.length - 1) rest = rest.slice(1, -1).trim();
1600
+ if (!rest) return { kind: 'catch', errors: [] };
1601
+ let as = null;
1602
+ const named = rest.match(/^(.*?)\s*(?:\bas\b|=>)\s*([A-Za-z_$][\w$]*)$/);
1603
+ if (named) { rest = named[1].replace(/^\(\s*|\s*\)$/g, ''); as = named[2]; }
1604
+ else {
1605
+ const typed = rest.match(/^([\w.$:\\]+(?:\s*\|\s*[\w.$:\\]+)*)\s+([a-z_$][\w$]*)$/);
1606
+ if (typed) { rest = typed[1]; as = typed[2]; }
1607
+ else if (/^[a-z_$][\w$]*$/.test(rest)) return { kind: 'catch', errors: [], as: rest };
1608
+ }
1609
+ const errors = rest ? rest.split(/\s*[,|]\s*/) : [];
1610
+ if (!errors.every((x) => /^[\w.$:\\]+$/.test(x))) return codeExpr(h);
1611
+ return { kind: 'catch', errors, ...(as ? { as } : {}) };
1612
+ }
1613
+
557
1614
  /** Turn a clause (else, elif, except, catch, finally) into what it means for the step it belongs to. */
558
1615
  function attachClause(step, clause) {
559
1616
  const kw = clause.kind;
@@ -570,8 +1627,15 @@ function attachClause(step, clause) {
570
1627
  target.otherwise = kids;
571
1628
  target.otherwiseLine = clause.line;
572
1629
  } else if (kw === 'catch') {
1630
+ // C++ `catch (const std::runtime_error& e)` and Swift `catch let e as DecodingError` / `catch is X` name the error
1631
+ // type in their own way; C++ `catch (...)` catches anything.
1632
+ let native = null, nm;
1633
+ if (C_FAMILY.has(LANG) && (nm = clause.head.match(/^catch\s*\(\s*(?:const\s+)?(?:\w+::)*(\w+)(?:<[^>]*>)?\s*[&*]*\s*\w*\s*\)/))) native = /^[a-z]/.test(nm[1]) ? words(nm[1]) : nm[1];
1634
+ if (LANG === 'swift' && (nm = clause.head.match(/^catch\s+(?:(?:let|var)\s+\w+\s+as\s+|is\s+)([\w.]+)/))) native = nm[1].split('.').pop();
1635
+ if (LANG === 'swift' && (nm = clause.head.match(/^catch\s+([A-Z]\w*)\.(\w+)/))) native = `${nm[1]} (${words(nm[2])})`;
1636
+ if (native) { (step.handlers ||= []).push({ says: `If ${native} goes wrong`, line: clause.line, steps: kids }); return; }
573
1637
  const what = (clause.head.replace(/\\/g, '.').replace(/\(\s*\./, '(').match(/^(?:except|catch|rescue)\s*\(?\s*(?:[\w.]+\s+)?\(?\.?([A-Z][\w.:]*(?:\s*[,|]\s*\.?[A-Z][\w.:]*)*)/) || [])[1]?.replace(/::/g, '.');
574
- (step.handlers ||= []).push({ says: what ? `If ${what.split(/\s*[,|]\s*/).map((x) => x.split('.').pop()).join(' or ')} goes wrong` : 'If anything goes wrong', line: clause.line, steps: kids });
1638
+ (step.handlers ||= []).push({ says: what ? `If ${what.split(/\s*[,|]\s*/).map((x) => x.split('.').pop()).join(' or ')} goes wrong` : 'If anything goes wrong', line: clause.line, steps: kids, expr: catchExpr(clause.head) });
575
1639
  } else if (kw === 'finally') {
576
1640
  // Code that always runs at the end is never the value given back.
577
1641
  for (let i = 0; i < kids.length; i++) asCall(kids, i);
@@ -652,7 +1716,7 @@ function nestedStep(s, base) {
652
1716
  else if ((m = text.match(/^(?:window\.|globalThis\.)?(setTimeout|setInterval)\(/))) {
653
1717
  const ms = (s.fn.after.match(/^\s*,\s*(\d+)\s*\)/) || [])[1];
654
1718
  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*,/))) {
1719
+ } else if ((m = (s.fn.before ?? text).match(/\.(addEventListener|on|once)\(\s*['"`]([\w:.-]+)['"`]\s*,/))) {
656
1720
  said = m[1] === 'once' ? `The first time "${m[2]}" happens` : `Whenever "${m[2]}" happens`;
657
1721
  } else if (thenSays(text)) {
658
1722
  said = thenSays(text);
@@ -661,7 +1725,18 @@ function nestedStep(s, base) {
661
1725
  }
662
1726
  if (!s.children?.length) return null;
663
1727
  // 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();
1728
+ // Swift trailing closures name their parameters with `in`: `queue.async { [weak self] in`, `list.map { item in`.
1729
+ const raw = String(s.text || '').split('\n')[0].trim().replace(LANG === 'swift' ? /\{[^{}]*?(?<![\w$])in\s*$/ : /$^/, '{');
1730
+ // Swift trailing closures anywhere in a statement: `Task { … }`, `return withLogger(l) { _ in … }`,
1731
+ // `let total = items.reduce(0) { … }`. The closure's steps are its own sub-flow under the step.
1732
+ if (LANG === 'swift' && !s.fn && /\{\s*$/.test(raw) && !BLOCK_HEAD.test(raw) && !/^(?:guard|repeat|defer|else|extension|protocol|actor|init|deinit|subscript|get|set|willSet|didSet)\b/.test(raw) && base.kind !== 'loop' && base.kind !== 'branch' && base.kind !== 'try') {
1733
+ const k = kids();
1734
+ if (k.length) {
1735
+ const says = /^Task(?:\.detached)?\s*(?:\(|\{)/.test(raw) ? 'Starts these steps running alongside, without waiting for them'
1736
+ : base.kind === 'call' && /^Calls [\w ]+$/.test(base.says) ? `${base.says} with these steps` : base.says;
1737
+ return own({ ...base, says }, k);
1738
+ }
1739
+ }
665
1740
  if (!s.fn && !BLOCK_HEAD.test(raw) && (m = raw.match(TRAILING_LAMBDA)) && !NOT_A_CALL.test(m[1])) {
666
1741
  const safe = m[1].match(/^(.+?)\?\.(?:let|also|run|apply)$/);
667
1742
  if (safe) return own({ kind: 'branch', says: `If ${words(safe[1].split(/\??\./).pop())} is set`, code: clip(raw, 90) }, kids());
@@ -693,18 +1768,38 @@ function armsSubject(rest) {
693
1768
  const m = (r.match(/^match\s*\((.+)\)$/) || r.match(/^match\s+(.+)$/)) || r.match(/^when\s*\((.+)\)$/) || r.match(/^([\w.]+)\s+switch$/);
694
1769
  return m ? m[1].trim() : null;
695
1770
  }
1771
+ /** One arm's patterns as a tree: `A | B` -> case [A, B]; `_` / `else` -> otherwise; anything not understood -> code. */
1772
+ function armExpr(pattern) {
1773
+ const p = String(pattern).trim();
1774
+ if (/^(?:_|else|default)$/.test(p)) return { kind: 'case', default: true };
1775
+ const lang = readingLanguage();
1776
+ let guard = null, body = p;
1777
+ const g = p.match(/^(.+?)\s+(?:if|when)\s+(.+)$/);
1778
+ if (g) { body = g[1]; guard = parseExpr(g[2], lang); if (!guard) return codeExpr(p); }
1779
+ const parts = [];
1780
+ let depth = 0, from = 0;
1781
+ for (let i = 0; i <= body.length; i++) {
1782
+ const c = body[i];
1783
+ if (c === '(' || c === '[' || c === '{') depth++; else if (c === ')' || c === ']' || c === '}') depth--;
1784
+ if (i === body.length || (depth === 0 && ((c === '|' && body[i + 1] !== '|' && body[i - 1] !== '|') || c === ','))) { parts.push(body.slice(from, i).trim()); from = i + 1; }
1785
+ }
1786
+ const patterns = parts.filter(Boolean).map((x) => parseExpr(x, lang));
1787
+ if (!patterns.length || patterns.some((x) => !x)) return codeExpr(p);
1788
+ return { kind: 'case', patterns, ...(guard ? { guard } : {}) };
1789
+ }
696
1790
  /** One arm's pattern in words: `0..=49` -> "from 0 to 49", `Cmd::Start | Cmd::Go` -> "start or go", `_` -> otherwise. */
697
1791
  function armSays(pattern) {
698
1792
  let p = String(pattern).trim();
699
1793
  if (/^(?:_|else|default)$/.test(p)) return 'Otherwise';
700
1794
  let guard = null;
701
- const g = p.match(/^(.+?)\s+(?:if|when)\s+(.+)$/);
1795
+ const g = p.match(/^(.+?)\s+(?:if|when|where)\s+(.+)$/);
702
1796
  if (g) { p = g[1]; guard = g[2]; }
703
1797
  if (LOGIC.test(p) && !/^(?:!?in|!?is)\s/.test(p) && !/\.\./.test(p) && !/\|/.test(p.replace(/\|\|/g, ''))) return `When ${sayCodeCondition(p)}`;
704
1798
  const parts = [];
705
1799
  let depth = 0, from = 0;
706
1800
  for (let i = 0; i <= p.length; i++) {
707
1801
  const c = p[i];
1802
+ if (c === '"' || c === "'" || c === '`') { i = Math.min(skipQuoted(p, i), p.length - 1); continue; } // `case ',':` is one value
708
1803
  if (c === '(' || c === '[' || c === '{') depth++; else if (c === ')' || c === ']' || c === '}') depth--;
709
1804
  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
1805
  }
@@ -714,6 +1809,9 @@ function armSays(pattern) {
714
1809
  if ((m = x.match(/^(!?)is\s+([\w.<>?]+)$/))) return `${m[1] ? 'not ' : ''}a ${m[2].split('.').pop()}`;
715
1810
  if ((m = x.match(/^(?:[A-Z]\w*(?:::|\.))+([A-Z]\w*)$/))) return words(m[1]);
716
1811
  if (/^[A-Z][A-Z0-9_]+$/.test(x)) return words(x);
1812
+ // Swift enum cases: .onShelf, .failed(let error), let .failed(error), Status.onShelf.
1813
+ if ((m = x.match(/^(?:(?:let|var)\s+)?(?:[A-Z]\w*)?\.([a-z]\w*)(?:\s*\(.*\))?$/))) return words(m[1]);
1814
+ if (/\.\.<|\.\.\./.test(x) && (m = rangeWords(x))) return m.says;
717
1815
  return x;
718
1816
  };
719
1817
  return `When it is ${orList(parts.filter(Boolean).map(one))}${guard ? `, and ${sayCodeCondition(guard)}` : ''}`;
@@ -757,6 +1855,49 @@ function selectCaseSays(code) {
757
1855
  return null;
758
1856
  }
759
1857
 
1858
+ /**
1859
+ * A C-like switch writes each case's steps after its label, not inside it: `case A: case B: x(); break;`. Put each
1860
+ * case's steps under its label (labels with no steps of their own share the next one's: "When it is A or B"), and
1861
+ * drop the `break` that only ends the case. Left as it is when steps come before the first label.
1862
+ */
1863
+ function groupCases(kids) {
1864
+ if (!kids.length || !kids[0].caseLabel || kids.every((k) => k.caseLabel && k.children?.length)) return kids;
1865
+ const out = [];
1866
+ let cur = null;
1867
+ for (const k of kids) {
1868
+ if (k.caseLabel && !k.children?.length) {
1869
+ if (cur && !cur.children.length && !cur.closed) {
1870
+ const a = cur.says, b = k.says;
1871
+ cur.says = /^When it is /.test(a) && /^When it is /.test(b) ? `${a} or ${b.slice(11)}` : b === 'Otherwise' ? 'Otherwise' : `${a}, or ${b.replace(/^When /, '')}`;
1872
+ cur.span = { ...cur.span, endLine: k.span?.endLine ?? cur.span?.endLine };
1873
+ // The tree keeps every label: `case A: case B:` is one case with both patterns (and `default` when it is one).
1874
+ const ea = cur.expr, eb = k.expr;
1875
+ if (ea?.kind === 'case' && eb?.kind === 'case') cur.expr = { kind: 'case', patterns: [...(ea.patterns || []), ...(eb.patterns || [])], ...(ea.default || eb.default ? { default: true } : {}) };
1876
+ else if (ea || eb) cur.expr = { kind: 'code', text: [cur.code, k.code].filter(Boolean).join(' ') };
1877
+ continue;
1878
+ }
1879
+ cur = { ...k, children: [] };
1880
+ out.push(cur);
1881
+ continue;
1882
+ }
1883
+ if (k.caseLabel) { cur = null; out.push(k); continue; }
1884
+ if (!cur) return kids;
1885
+ if (cur.closed) continue; // after a break, nothing in this case runs
1886
+ if (k.jump === 'break') { cur.closed = true; continue; }
1887
+ cur.children.push(k);
1888
+ }
1889
+ for (const c of out) { delete c.closed; if (c.children && !c.children.length) delete c.children; }
1890
+ return out;
1891
+ }
1892
+
1893
+ /** The one statement written after a condition or in a one-line block, read (with its own one-line body, if any). */
1894
+ function inlineKid(text, s, depth = 0) {
1895
+ const kid = { ...classifyStatement(text), line: s.line, span: spanOf(s) };
1896
+ if (kid.inline && depth < 3) kid.children = [inlineKid(kid.inline, s, depth + 1)];
1897
+ delete kid.inline;
1898
+ return kid;
1899
+ }
1900
+
760
1901
  export function stepsFrom(statements) {
761
1902
  const steps = [];
762
1903
  const skipped = [];
@@ -767,7 +1908,7 @@ export function stepsFrom(statements) {
767
1908
  const t0 = (s.text || '').trim();
768
1909
  // An arm of a match / when: "When it is …", with what that arm does inside it (`else ->` is an arm, not a clause).
769
1910
  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) };
1911
+ const arm = { kind: 'check', says: armSays(s.arm) + (s.fallsThrough ? ', then carries on into the next case' : ''), code: clip(t0.split('\n')[0].trim(), 90), expr: armExpr(s.arm), caseLabel: true, line: s.line, span: spanOf(s) };
771
1912
  const kids = stepsFrom(s.children || []).steps;
772
1913
  if (kids.length) arm.children = kids;
773
1914
  steps.push(arm);
@@ -787,10 +1928,18 @@ export function stepsFrom(statements) {
787
1928
  // Ruby: `def x ... rescue ... end` with no `begin`: everything before the rescue is what is tried.
788
1929
  const tried = steps.splice(0, steps.length);
789
1930
  for (let i = 0; i < tried.length - 1; i++) asCall(tried, i);
790
- steps.push({ kind: 'try', says: 'Tries these steps and handles any error', code: '(the whole method)', line: tried[0].line, span: { startLine: tried[0].span.startLine, endLine: tried[tried.length - 1].span.endLine }, children: tried });
1931
+ steps.push({ kind: 'try', says: 'Tries these steps and handles any error', code: '(the whole method)', expr: { kind: 'try' }, line: tried[0].line, span: { startLine: tried[0].span.startLine, endLine: tried[tried.length - 1].span.endLine }, children: tried });
791
1932
  }
792
1933
  const prev2 = steps[steps.length - 1];
793
- if (prev2 && (prev2.kind === 'branch' || prev2.kind === 'try')) {
1934
+ // Inside a Ruby `case`, `else` is the last arm ("Otherwise"), with what it does.
1935
+ if (prev2?.caseLabel && /^else\b/.test(t0)) {
1936
+ const inlineElse = t0.match(/^else\s+(?!if\b)(.+)$/);
1937
+ const kids = inlineElse ? [inlineKid(inlineElse[1], s)] : stepsFrom(s.children || []).steps;
1938
+ steps.push({ kind: 'check', says: 'Otherwise', code: clip(t0, 90), expr: { kind: 'case', default: true }, caseLabel: true, line: s.line, span: spanOf(s), ...(kids.length ? { children: kids } : {}) });
1939
+ continue;
1940
+ }
1941
+ // Python `for … else:` / `while … else:` — steps for when the loop ran to its end without `break`.
1942
+ if (prev2 && (prev2.kind === 'branch' || prev2.kind === 'try' || (prev2.kind === 'loop' && /^else\s*:/.test(t0)))) {
794
1943
  const prev = prev2;
795
1944
  const kw = /^(?:elif|elsif|else\s+if)\b/.test(t0) ? 'elif' : /^else\b/.test(t0) ? 'else' : /^(?:finally|ensure)\b/.test(t0) ? 'finally' : 'catch';
796
1945
  const inlineElse = kw === 'else' && t0.match(/^else\s+(?!if\b)([^{:\s].*)$/);
@@ -804,8 +1953,20 @@ export function stepsFrom(statements) {
804
1953
  skipped.push(spanOf(s));
805
1954
  continue;
806
1955
  }
807
- if (!t0 || /^(?:end\b|\}|pass$|break;?$|continue;?$|#)/.test(t0)) { if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s)); continue; }
808
- if (/^(?:"""|'''|r"""|\/\*\*|\*)/.test(t0)) { skipped.push(spanOf(s)); continue; } // docstrings and doc comments
1956
+ // Leaving a loop early is a step a reader must see: without it, "Yes: continue" would say the loop goes on.
1957
+ let jump;
1958
+ if ((jump = t0.match(/^(continue|break|next)(?:\s+([A-Za-z_]\w*))?;?$/)) && !(jump[1] === 'next' && jump[2])) {
1959
+ const label = jump[2] && jump[2] !== 'if' ? ` (${jump[2]})` : '';
1960
+ steps.push({ kind: 'call', says: jump[1] === 'break' ? `Leaves the loop${label}` : `Skips to the next one${label}`, code: t0, expr: { kind: 'jump', jump: jump[1] === 'break' ? 'break' : 'continue', ...(jump[2] ? { label: jump[2] } : {}) }, line: s.line, span: spanOf(s), jump: jump[1] === 'break' ? 'break' : 'continue' });
1961
+ continue;
1962
+ }
1963
+ if (!C_FAMILY.has(LANG) && /^[A-Za-z_]\w*:$/.test(t0) && !/^(?:default|else|try|finally|begin|ensure|rescue)$/.test(t0.slice(0, -1))) { skipped.push(spanOf(s)); continue; }
1964
+ if (!t0 || /^(?:end\b|\}|pass$|#)/.test(t0)) { if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s)); continue; }
1965
+ if (/^(?:"""|'''|r"""|\/\*\*|\*(?![\w(*]))/.test(t0)) { skipped.push(spanOf(s)); continue; } // docstrings and doc comments (not C's `*out = n`)
1966
+ // C/C++ `(void)x;` and `static_cast<void>(x);` only tell the compiler x is unused on purpose: nothing happens.
1967
+ if (C_FAMILY.has(LANG) && /^(?:\(\s*void\s*\)|static_cast\s*<\s*void\s*>)\s*\(?\s*[\w.]+\s*\)?\s*;?$/.test(t0)) { skipped.push(spanOf(s)); continue; }
1968
+ // C++ `using traits = …;`, `using namespace detail;`, `using std::get;` only name things for the code below: no step.
1969
+ if (LANG === 'cpp' && /^using\s+(?:namespace\s+)?[\w:]+(?:\s*=[^;{]*)?;?$/.test(t0.replace(/<[^;{}]*>/g, ''))) { skipped.push(spanOf(s)); continue; }
809
1970
  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; }
810
1971
  const head0 = headLine(s.text);
811
1972
  // A bare block `{ … }` (a case's own scope) adds nothing to read: its statements are read in its place.
@@ -814,11 +1975,40 @@ export function stepsFrom(statements) {
814
1975
  if (s.arms) {
815
1976
  const subject = armsSubject(choice ? choice.rest : head0);
816
1977
  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 } : {}) };
1978
+ // With no subject (`when {`, `switch {`), each arm is a condition of its own: "When x is a string", not
1979
+ // "When it is isString(x)".
1980
+ if (!subject) {
1981
+ const pats = (s.children || []).filter((c) => c.arm != null).map((c) => String(c.arm).trim());
1982
+ const arms = kids.filter((k) => k.caseLabel);
1983
+ if (pats.length === arms.length) arms.forEach((k, i) => { if (!/^(?:_|else|default)$/.test(pats[i])) k.says = `When ${sayCodeCondition(pats[i])}`; });
1984
+ }
1985
+ const chooser = { kind: 'branch', says: subject ? `Chooses by ${words(clip(subject, 40))}` : 'Checks these cases in order', code: clip(head0, 90), expr: { kind: 'switch', ...(subject ? { subject: parseExpr(subject, readingLanguage()) ?? codeExpr(subject) } : {}) }, line: s.line, span: spanOf(s), ...(kids.length ? { children: kids } : {}), ...(choice ? { valueOf: choice.target } : {}) };
818
1986
  steps.push(chooser);
819
1987
  continue;
820
1988
  }
821
- let step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
1989
+ // Kotlin `val m = call() ?: return null`: the value, then the early way out when there is none.
1990
+ const elvis = !s.children?.length && String(s.text).replace(/\s+/g, ' ').trim().match(/^((?:val|var|let)\s+([A-Za-z_]\w*)(?:\s*:\s*[^=]+)?\s*=\s*.+?)\s*\?:\s*((?:return|throw)\b.*)$/);
1991
+ if (elvis && balancedText(elvis[1]) && balancedText(elvis[3])) {
1992
+ steps.push({ ...classifyStatement(elvis[1]), line: s.line, span: spanOf(s) });
1993
+ const out = classifyStatement(elvis[3]);
1994
+ steps.push({ kind: 'branch', says: `If ${words(elvis[2])} is empty`, cond: `${elvis[2]} == null`, expr: { kind: 'if', test: { kind: 'compare', op: '==', left: { kind: 'name', name: elvis[2] }, right: { kind: 'literal', type: 'null', value: null, raw: 'null' } }, elvis: true }, code: clip(String(s.text).replace(/\s+/g, ' '), 90), line: s.line, span: spanOf(s), children: [{ ...out, line: s.line, span: spanOf(s) }] });
1995
+ continue;
1996
+ }
1997
+ let step = { ...classifyStatement(s.implicitReturn ? `return ${s.text}` : s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
1998
+ if (s.implicitReturn) step.code = clip(headLine(s.text), 90);
1999
+ // A Swift body that is one call with a trailing closure gives back what the last call makes, with the closure's
2000
+ // steps under it: `parseDirectives(…).compactMap { … }` -> "Returns the result of compact map".
2001
+ const closureHead = headLine(s.text).replace(/\{[^{}]*?(?<![\w$])in\s*$/, '{');
2002
+ if (s.implicitReturn && s.children?.length && /\{\s*$/.test(closureHead)) {
2003
+ const last = closureHead.replace(/\{\s*$/, '').trim().replace(/\([^()]*\)\s*$/, '').match(/([A-Za-z_]\w*)\s*$/);
2004
+ if (last) {
2005
+ const kids = stepsFrom(s.children).steps;
2006
+ if (kids.length) steps.push({ kind: 'call', says: `Calls ${words(last[1])} with these steps`, code: step.code, line: s.line, span: spanOf(s), children: kids, nested: true });
2007
+ steps.push({ ...step, kind: 'return', says: `Returns the result of ${words(last[1])}` });
2008
+ delete steps[steps.length - 1].value;
2009
+ continue;
2010
+ }
2011
+ }
822
2012
  // `val label = if (user == null) { … } else { … }` over several lines reads as the question it asks, each side
823
2013
  // ending in "Sets label to …".
824
2014
  if (choice && /^(?:if|unless|case)\b/.test(choice.rest) && (s.endLine ?? s.line) > s.line) {
@@ -826,7 +2016,15 @@ export function stepsFrom(statements) {
826
2016
  } else {
827
2017
  const nest = nestedStep(s, step);
828
2018
  // `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) {
2019
+ if (!nest && step.kind === 'return' && s.fn && s.fn.depth === 0 && s.children?.length) {
2020
+ // `return function () { … }` / `return () => …`: the caller gets a new function; its steps run later.
2021
+ const kids = stepsFrom(s.children).steps;
2022
+ if (kids.length) {
2023
+ steps.push({ kind: 'set', says: 'Makes a new function that does these steps', code: step.code, expr: step.expr, line: s.line, span: spanOf(s), children: kids, nested: true });
2024
+ step = { ...step, says: 'Returns that function' };
2025
+ delete step.value; delete step.restates;
2026
+ }
2027
+ } else if (!nest && step.kind === 'return' && s.fn && !s.fn.expr && s.fn.depth >= 1 && s.children?.length) {
830
2028
  const kids = stepsFrom(s.children).steps;
831
2029
  if (kids.length) {
832
2030
  let m;
@@ -834,11 +2032,11 @@ export function stepsFrom(statements) {
834
2032
  const said = (m = body.match(/^new\s+([A-Z]\w*)/)) ? `Makes a new ${m[1]} with these steps`
835
2033
  : thenSays(body) ? thenSays(body)
836
2034
  : 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 });
2035
+ if (said) steps.push({ kind: 'call', says: said, code: step.code, expr: step.expr, line: s.line, span: spanOf(s), children: kids, nested: true });
838
2036
  }
839
2037
  }
840
2038
  if (nest) {
841
- step = { ...nest, line: s.line, span: spanOf(s) };
2039
+ step = { ...nest, line: s.line, span: spanOf(s), expr: nest.expr ?? step.expr };
842
2040
  for (const c of s.clauses || []) attachClause(step, c);
843
2041
  steps.push(step);
844
2042
  continue;
@@ -846,9 +2044,10 @@ export function stepsFrom(statements) {
846
2044
  }
847
2045
  // A one-line `if (x) return reply.code(400).send({ error: 'bad' })` is one statement: its braces belong to the
848
2046
  // object being sent, not to a block, so read the statement after the condition instead of the braces' inside.
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; }
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))) {
851
- const kids = stepsFrom(s.children).steps;
2047
+ if (step.inline && !/^\{/.test(step.inline.trim())) { step.children = [inlineKid(step.inline, s)]; delete step.inline; }
2048
+ else if (s.children?.length && (['branch', 'loop', 'try'].includes(step.kind) || (step.kind === 'check' && step.caseLabel) || /^(?:Defines a helper|Defines how|Opens |Uses |At the end, runs )/.test(step.says))) {
2049
+ let kids = stepsFrom(s.children).steps;
2050
+ if (step.kind === 'branch' && /^(?:Chooses by|Checks these cases)/.test(step.says)) kids = groupCases(kids);
852
2051
  if (kids.length) { step.children = kids; step.says = step.says.replace(/ \(\d+ steps? inside\)$/, ''); if (/^Defines/.test(step.says)) step.nested = true; }
853
2052
  // Go select: whichever channel is ready first (or, with a default, whichever is ready now).
854
2053
  if (/^select\s*\{/.test(head0) && step.children) {
@@ -856,8 +2055,10 @@ export function stepsFrom(statements) {
856
2055
  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
2056
  }
858
2057
  }
859
- if (step.inline && !step.children) { const kid = classifyStatement(step.inline); step.children = [{ ...kid, line: s.line, span: spanOf(s) }]; delete step.inline; }
2058
+ if (step.inline && !step.children) { step.children = [inlineKid(step.inline, s)]; delete step.inline; }
860
2059
  else delete step.inline;
2060
+ // A block with code in it that gave no step was not read: say so, never "Yes: continue" / an empty "For each".
2061
+ if ((step.kind === 'branch' || step.kind === 'loop') && !step.children?.length && (s.inner > 0 || s.children?.length) && !(s.children || []).every((c) => /^(?:pass|\}|end)\b/.test(String(c.text || '').trim()))) step.unread = true;
861
2062
  // 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
2063
  if (step.kind === 'branch' || step.kind === 'try') for (const c of s.clauses || []) attachClause(step, c);
863
2064
  steps.push(step);
@@ -924,6 +2125,11 @@ export function fnLiteral(text) {
924
2125
  for (let i = 0; i < text.length; i++) {
925
2126
  const c = text[i];
926
2127
  if (c === '"' || c === "'" || c === '`') { i = skipQuoted(text, i); continue; }
2128
+ // A C++ lambda: [captures](params) { … }, passed to a call or kept in a name.
2129
+ if (c === '[' && LANG === 'cpp' && /(?:^|[(,={]|\breturn)\s*$/.test(text.slice(Math.max(0, i - 12), i))) {
2130
+ const lm = text.slice(i, i + 400).match(/^\[[^[\]]*\]\s*(?:\((?:[^()]|\([^()]*\))*\))?\s*(?:mutable\s*)?(?:constexpr\s*)?(?:noexcept\s*)?(?:->\s*[\w:<>*&]+(?:\s+[\w:<>*&]+)*\s*)?(?=\{)/);
2131
+ if (lm) { const body = bodyAt(i + lm[0].length, depth); if (body) return body; }
2132
+ }
927
2133
  if (c === '(' || c === '[') { depth++; continue; }
928
2134
  if (c === ')' || c === ']') { depth--; continue; }
929
2135
  // Object literals, destructured parameters, struct literals: not functions; read past them.
@@ -972,6 +2178,8 @@ export function fnLiteral(text) {
972
2178
  return null;
973
2179
  }
974
2180
 
2181
+ /** Swift closure parameters at the start of a block: `{ req in`, `{ (a, b) -> Bool in`, `{ [weak self] x in`. One line. */
2182
+ export const SWIFT_CLOSURE_PARAMS = /^\s*?[ \t]*(?:\[[^\]\n]*\][ \t]*)?(?:(?:\([^()\n]*\)|[\w$]+(?:[ \t]*,[ \t]*[\w$]+)*)[ \t]*)?(?:async[ \t]+)?(?:throws[ \t]+)?(?:->[ \t]*[^\s{}]+[ \t]*)?(?<![\w$])in\b/;
975
2183
  /** The text of a statement's own lambda parameters at the start of a Kotlin block: `{ item ->` gives "item ->". */
976
2184
  const LAMBDA_PARAMS = /^\s*(?:\(?[\w$]+(?:\s*:\s*[\w<>?.]+)?(?:\s*,\s*[\w$]+(?:\s*:\s*[\w<>?.]+)?)*\)?|_)\s*->(?![^\n]*->)/;
977
2185
 
@@ -1028,17 +2236,53 @@ const ARMS_HEAD = /(?:^|=\s*|return\s+)(?:[\w.]+\s+(?=switch))?(?:match\b\s*[^{\
1028
2236
  * (`useEffect(() => { … })`, `go func() { … }()`) has its own body read as the statement's children, and the arms of
1029
2237
  * a match/when are read one by one.
1030
2238
  */
2239
+ /**
2240
+ * Where a statement's own block starts. For `if (…)`, `for (…)`, `while (…)`: the brace right after the header's
2241
+ * parentheses, or none (a brace-less body, whose braces belong to its one statement: `if (x) throw new E($"{a}")`).
2242
+ * Otherwise the first brace outside quotes.
2243
+ */
2244
+ function blockOpen(text, head0) {
2245
+ if (/^(?:if|else\s+if|for|foreach|while|using|lock|fixed|switch|catch)\s*\(/.test(head0)) {
2246
+ const o = text.indexOf('(');
2247
+ const c = closeOf(text, o);
2248
+ if (c < 0) return text.indexOf('{');
2249
+ let j = c + 1;
2250
+ while (j < text.length && /\s/.test(text[j])) j++;
2251
+ if (text[j] === '{') return j;
2252
+ // The header goes on past its parentheses on the same line (`for (a, b) in xs {`, `if (a) && b {`): the brace
2253
+ // that ends that line opens the block.
2254
+ const nl = text.indexOf('\n', c);
2255
+ const line = text.slice(c + 1, nl < 0 ? text.length : nl);
2256
+ if (/^\s*(?:in|of|&&|\|\||and|or|[-+*/%<>=!])/.test(line) && /\{\s*$/.test(line)) return c + 1 + line.lastIndexOf('{');
2257
+ if (/^(?:if|else\s+if|for|foreach|while|using|lock|fixed)\s*\(/.test(head0)) return -1;
2258
+ return text.indexOf('{', j);
2259
+ }
2260
+ for (let i = 0; i < text.length; i++) {
2261
+ const ch = text[i];
2262
+ if (ch === "'") { const nl = text.indexOf('\n', i); const e = text.indexOf("'", i + 1); if (e < 0 || (nl >= 0 && e > nl)) continue; }
2263
+ if (ch === '"' || ch === "'" || ch === '`') { const q = ch; for (i++; i < text.length && text[i] !== q; i++) if (text[i] === '\\') i++; continue; }
2264
+ // Go composite literals in a header (`range []string{"a", "b"} {`) are values, not the block.
2265
+ if (ch === '{' && /(?:\[\d*\][\w.*]+|map\[[^\]]+\][\w.*[\]]+)\s*$/.test(text.slice(Math.max(0, i - 60), i))) { const c = closeOf(text, i); if (c > 0) { i = c; continue; } }
2266
+ if (ch === '{') return i;
2267
+ }
2268
+ return -1;
2269
+ }
2270
+
1031
2271
  export function braceStatements(stmts, split = null) {
1032
2272
  return stmts.map((s) => {
1033
2273
  const text = s.text;
1034
2274
  const head0 = headLine(text);
1035
2275
  const lit = BLOCK_HEAD.test(head0) && !/^func\s*\(/.test(head0) ? null : fnLiteral(text);
1036
- let open = lit?.open ?? text.indexOf('{');
2276
+ // The block is the first brace outside brackets: in Swift and C++ a condition can hold a closure or lambda
2277
+ // (`if let i = list.firstIndex(where: { $0 > 1 }) {`). (Other headers: see blockOpen.)
2278
+ let open = lit?.open ?? (LANG === 'swift' || (C_FAMILY.has(LANG) && !/^(?:if|else\s+if|for|while|switch|catch)\s*\(/.test(head0)) ? blockBrace(text) : C_FAMILY.has(LANG) ? cBlockOpen(text, head0) : blockOpen(text, head0));
1037
2279
  const lineAtPos = (pos) => s.line + (text.slice(0, pos).match(/\n/g) || []).length;
1038
2280
  const read = (o, e) => {
1039
2281
  let from = o + 1;
1040
2282
  // Kotlin lambda parameters (`{ item ->`) name the item; they are not a step.
1041
- const params = text.slice(from, e).match(LAMBDA_PARAMS);
2283
+ // Swift closure parameters (`{ req in`, `{ (a, b) -> Bool in`) name what the closure is given; not a step.
2284
+ // (C and C++ have no such parameters: `{ prev->next = cur;` starts with a field, not a lambda's `prev ->`.)
2285
+ const params = C_FAMILY.has(LANG) ? null : text.slice(from, e).match(LANG === 'swift' ? SWIFT_CLOSURE_PARAMS : LAMBDA_PARAMS);
1042
2286
  if (params && !ARMS_HEAD.test(head0)) from += params[0].length;
1043
2287
  const body = e > from ? text.slice(from, e) : '';
1044
2288
  const base = s.start != null ? s.start + from : null;
@@ -1081,6 +2325,10 @@ export function braceStatements(stmts, split = null) {
1081
2325
  const body = end > open ? text.slice(open + 1, end) : '';
1082
2326
  inner = body ? body.split(/;|\n/).filter((l) => l.trim() && !/^[{}]$/.test(l.trim())).length : 0;
1083
2327
  children = read(open, end);
2328
+ // A classic switch: each `case X:` with the statements under it, so the switch is one question with one side
2329
+ // per case (consecutive labels share a side: `case 1: case 2:` is "When it is 1 or 2").
2330
+ // (C, C++, and Swift; the older readers keep a classic switch as a list of steps.)
2331
+ if (/^switch\b/.test(head0) && split && (C_FAMILY.has(LANG) || LANG === 'swift')) children = groupClassicCases(children, split);
1084
2332
  let pos = end + 1;
1085
2333
  while (end >= 0) {
1086
2334
  const rest = text.slice(pos);
@@ -1096,11 +2344,125 @@ export function braceStatements(stmts, split = null) {
1096
2344
  pos = e + 1;
1097
2345
  }
1098
2346
  }
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) } } : {}) };
2347
+ 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), before: text.slice(0, lit.open) } } : {}) };
1100
2348
  });
1101
2349
  }
1102
2350
 
2351
+ /** blockOpen, with C++ attributes between the header and its block skipped: `if (x) [[unlikely]] {`. */
2352
+ function cBlockOpen(text, head0) {
2353
+ const o = text.indexOf('(');
2354
+ const c = o >= 0 ? closeOf(text, o) : -1;
2355
+ const attr = c > 0 ? text.slice(c + 1).match(/^\s*\[\[[^\[\]]*\]\]\s*\{/) : null;
2356
+ return attr ? c + attr[0].length : blockOpen(text, head0);
2357
+ }
2358
+ /** The first `{` that is not inside parentheses or brackets (strings skipped), or -1. */
2359
+ function blockBrace(text) {
2360
+ let depth = 0;
2361
+ for (let i = 0; i < text.length; i++) {
2362
+ const c = text[i];
2363
+ if (c === '"' || c === "'" || c === '`') { i = skipQuoted(text, i); continue; }
2364
+ if (c === '(' || c === '[') depth++;
2365
+ else if (c === ')' || c === ']') depth--;
2366
+ else if (c === '{' && depth <= 0) return i;
2367
+ }
2368
+ return text.indexOf('{');
2369
+ }
2370
+
2371
+ /** A `case X:` / `default:` label at the start of a statement: { pattern, restAt } (restAt: where code after it starts). */
2372
+ function caseLabelOf(text) {
2373
+ const t = String(text);
2374
+ const lead = t.match(/^\s*(case\b|default\b)/);
2375
+ if (!lead) return null;
2376
+ let depth = 0;
2377
+ for (let i = lead[0].length; i < t.length; i++) {
2378
+ const c = t[i];
2379
+ if (c === '"' || c === "'" || c === '`') { i = skipQuoted(t, i); continue; }
2380
+ if (c === '(' || c === '[' || c === '{') depth++;
2381
+ else if (c === ')' || c === ']' || c === '}') depth--;
2382
+ else if (c === ':' && depth === 0) {
2383
+ if (t[i + 1] === ':' || t[i - 1] === ':') { i++; continue; }
2384
+ if (lead[1] === 'default' && t.slice(lead[0].length, i).trim()) return null;
2385
+ let r = i + 1;
2386
+ while (r < t.length && /\s/.test(t[r])) r++;
2387
+ return { pattern: lead[1] === 'default' ? 'default' : t.slice(lead[0].length, i).trim(), restAt: r < t.length ? r : -1 };
2388
+ } else if (c === '-' && t[i + 1] === '>' && depth === 0) return null; // Java `case X ->` arms are read elsewhere
2389
+ else if (c === '\n' && depth === 0 && lead[1] === 'default') return null;
2390
+ }
2391
+ return null;
2392
+ }
2393
+
2394
+ /** The statements of a switch body grouped under their case labels (see braceStatements). */
2395
+ function groupClassicCases(kids, split) {
2396
+ if (!kids.some((k) => caseLabelOf(k.text))) return kids;
2397
+ const out = [];
2398
+ let cur = null;
2399
+ for (const k of kids) {
2400
+ const lab = caseLabelOf(k.text);
2401
+ if (!lab) {
2402
+ if (cur) { cur.children.push(k); cur.endLine = k.endLine ?? k.line; if (k.end != null) cur.end = k.end; } else out.push(k);
2403
+ continue;
2404
+ }
2405
+ // Code on the label's own line (`case 1: return "a";`) is the first statement of that case.
2406
+ let rest = null;
2407
+ if (lab.restAt >= 0) {
2408
+ const restText = k.text.slice(lab.restAt).trim();
2409
+ const line = k.line + (k.text.slice(0, lab.restAt).match(/\n/g) || []).length;
2410
+ rest = braceStatements([{ text: restText, line, endLine: k.endLine ?? line, ...(k.start != null ? { start: k.start + lab.restAt, end: k.start + lab.restAt + restText.length } : {}) }], split)[0];
2411
+ }
2412
+ const labelText = lab.restAt >= 0 ? k.text.slice(0, lab.restAt).trim() : k.text.trim();
2413
+ if (cur && !cur.children.length) {
2414
+ cur.patterns.push(lab.pattern);
2415
+ cur.text += `\n${labelText}`;
2416
+ } else {
2417
+ cur = { text: labelText, patterns: [lab.pattern], line: k.line, endLine: k.line, ...(k.start != null ? { start: k.start, end: k.start + labelText.length } : {}), children: [] };
2418
+ out.push(cur);
2419
+ }
2420
+ if (rest) { cur.children.push(rest); cur.endLine = k.endLine ?? k.line; if (k.end != null) cur.end = k.end; }
2421
+ }
2422
+ // C and C++: a case whose steps do not end in break, return, goto, continue, or throw carries on into the next one.
2423
+ if (C_FAMILY.has(LANG)) {
2424
+ const cases = out.filter((c) => c.patterns);
2425
+ for (let i = 0; i < cases.length - 1; i++) {
2426
+ const last = cases[i].children[cases[i].children.length - 1];
2427
+ if (last && !/(?:^|[;{}\s])(?:break|return\b[^;]*|goto\s+\w+|continue|throw\b[^;]*|(?:std::)?(?:exit|abort|_exit)\([^)]*\)|\[\[fallthrough\]\])\s*;?\s*\}?\s*$/.test(last.text.trim())) cases[i].fallsThrough = true;
2428
+ }
2429
+ }
2430
+ for (const c of out) {
2431
+ if (!c.patterns) continue;
2432
+ c.arm = c.patterns.includes('default') ? 'default' : c.patterns.join(', ');
2433
+ c.inner = c.children.length;
2434
+ delete c.patterns;
2435
+ }
2436
+ return out;
2437
+ }
2438
+
1103
2439
  /** Top-level statements for an indentation body (Python) or depth body (Ruby). */
2440
+ /**
2441
+ * Python lines that continue a statement (inside open brackets, or after a `\`) belong to the line that opened it:
2442
+ * `elif (\n a\n and b\n):` is one condition, not a question with "Calls and" inside it.
2443
+ */
2444
+ function joinContinued(lines) {
2445
+ const out = [];
2446
+ let open = null, depth = 0;
2447
+ for (const l of lines) {
2448
+ const t = String(l.text);
2449
+ if (open) { open.text += `\n${t}`; open.endLine = l.endLine ?? l.line; }
2450
+ else { open = { ...l }; depth = 0; }
2451
+ let back = false;
2452
+ for (let i = 0; i < t.length; i++) {
2453
+ const c = t[i];
2454
+ if (c === '#') break;
2455
+ if (c === '"' || c === "'") { const q = c; for (i++; i < t.length && t[i] !== q; i++) if (t[i] === '\\') i++; continue; }
2456
+ if (c === '(' || c === '[' || c === '{') depth++;
2457
+ else if (c === ')' || c === ']' || c === '}') depth = Math.max(0, depth - 1);
2458
+ }
2459
+ back = /\\\s*$/.test(t);
2460
+ if (depth === 0 && !back) { out.push(open); open = null; }
2461
+ }
2462
+ if (open) out.push(open);
2463
+ return out;
2464
+ }
2465
+
1104
2466
  export function indentStatements(body, { depthKey = 'indent' } = {}) {
1105
2467
  if (!body?.length) return [];
1106
2468
  // Drop multi-line docstrings first: everything between an opening and closing triple quote.
@@ -1114,7 +2476,7 @@ export function indentStatements(body, { depthKey = 'indent' } = {}) {
1114
2476
  if (q) { const doc = { ...l, text: q, endLine: l.line }; kept.push(doc); if (t.slice(t.indexOf(q) + 3).includes(q) === false) { inDoc = q; docEntry = doc; } continue; }
1115
2477
  kept.push(l);
1116
2478
  }
1117
- body = kept;
2479
+ body = depthKey === 'indent' ? joinContinued(kept) : kept;
1118
2480
  if (!body.length) return [];
1119
2481
  const base = Math.min(...body.map((l) => l[depthKey] ?? 0));
1120
2482
  const out = [];