@skillstech/thunderlang 0.4.2 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/read.mjs ADDED
@@ -0,0 +1,1485 @@
1
+ // Read code you don't know: recover the decision rules inside functions written in TypeScript /
2
+ // JavaScript, Python, Go, Rust, C#, or Java, and show them as ThunderLang plus plain English.
3
+ // Deterministic, no AI, browser-safe. Everything here is INFERRED from code: a reading says what
4
+ // the code appears to decide, never what it was meant to decide, and anything it could not read
5
+ // is listed rather than guessed.
6
+ //
7
+ // Recognized shapes (the common ways code chooses an answer):
8
+ // if (cond) return X; ... return Y; if/else if/else chains returning values
9
+ // return cond ? X : Y (nested ternaries) Python: return X if cond else Y
10
+ // Rust/Go tail forms: if cond { X } else { Y }, if cond { return X }
11
+ // Conditions may use comparisons, &&/||/!, and/or/not, parentheses, literals, and inputs or fields.
12
+ import { compileExpr, simplifyExpr } from './expr.mjs';
13
+ import { extractFacts, languageForFile } from './lift.mjs';
14
+
15
+ export const READ_SCHEMA = 'thunder-reading-v1';
16
+ export const READ_LANGUAGES = ['typescript', 'javascript', 'python', 'go', 'rust', 'csharp', 'java', 'kotlin', 'php', 'ruby'];
17
+ const BRACE_LANGS = new Set(['typescript', 'javascript', 'go', 'rust', 'csharp', 'java', 'kotlin', 'php']);
18
+ const KEYWORDS_NOT_FN = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'new', 'else', 'using', 'lock', 'foreach', 'match', 'loop', 'sizeof', 'typeof', 'nameof']);
19
+
20
+ /** Best-effort language guess for pasted code (a file name, when known, is more reliable). */
21
+ export function detectLanguage(source, file = '') {
22
+ if (file) return languageForFile(file);
23
+ const s = String(source);
24
+ if (/^\s*<\?php\b/.test(s) || /\bfunction\s+\w+\s*\([^)]*\$\w+/.test(s)) return 'php';
25
+ if (/\bfun\s+(<[^>]*>\s*)?[\w.]*\w+\s*\(/.test(s)) return 'kotlin';
26
+ if (/^\s*def\s+[\w.?!]+(\s*\(.*\))?\s*$/m.test(s) && /^\s*end\s*$/m.test(s)) return 'ruby';
27
+ if (/^\s*package\s+\w+\s*$/m.test(s) || /\bfunc\s+(\([^)]*\)\s*)?\w+\s*\(/.test(s)) return 'go';
28
+ if (/\bfn\s+\w+\s*(<[^>]*>)?\s*\(/.test(s) || /\blet\s+mut\b|->\s*&'static/.test(s)) return 'rust';
29
+ if (/^\s*def\s+\w+\s*\(.*\)\s*(->\s*[^:]+)?:\s*$/m.test(s)) return 'python';
30
+ if (/\bnamespace\s+[\w.]+|\busing\s+System\b|\bpublic\s+static\s+string\b|\bstring\s+\w+\s*[,)]/.test(s)) return 'csharp';
31
+ if (/\bpublic\s+(static\s+)?(class|String|boolean|int|double|void)\b|\bString\s+\w+\s*[,)]|\bboolean\b/.test(s)) return 'java';
32
+ if (/:\s*(number|string|boolean)\b|\binterface\s+\w+|\bexport\s+(function|const)\b/.test(s)) return 'typescript';
33
+ return 'javascript';
34
+ }
35
+
36
+ // ── Lexing helpers ──────────────────────────────────────────────────────────────────────────
37
+
38
+ const lineAt = (src, idx) => src.slice(0, idx).split('\n').length;
39
+
40
+ /** Index of the bracket that closes the one at `open`, skipping strings and comments. */
41
+ function matchClose(src, open) {
42
+ const pairs = { '{': '}', '(': ')', '[': ']' };
43
+ const stack = [pairs[src[open]]];
44
+ for (let i = open + 1; i < src.length; i++) {
45
+ const c = src[i];
46
+ if (c === '"' || c === '\'' || c === '`') { i = skipString(src, i); continue; }
47
+ if (c === '/' && src[i + 1] === '/') { i = src.indexOf('\n', i); if (i < 0) return -1; continue; }
48
+ if (c === '/' && src[i + 1] === '*') { i = src.indexOf('*/', i + 2); if (i < 0) return -1; i++; continue; }
49
+ if (pairs[c]) stack.push(pairs[c]);
50
+ else if (c === stack[stack.length - 1]) { stack.pop(); if (!stack.length) return i; }
51
+ }
52
+ return -1;
53
+ }
54
+
55
+ // The language being read. Only Rust has lifetimes ('static, 'a), which look like an opening quote.
56
+ let READING_RUST = false;
57
+
58
+ function skipString(src, i) {
59
+ const q = src[i];
60
+ if (q === '\'' && !READING_RUST) {
61
+ for (let j = i + 1; j < src.length; j++) {
62
+ if (src[j] === '\\') { j++; continue; }
63
+ if (src[j] === q || src[j] === '\n') return j;
64
+ }
65
+ return src.length;
66
+ }
67
+ // Rust lifetimes ('static, 'a) are not strings: a quote, a name, and no closing quote right after it.
68
+ // 'path' and 'a' are strings or chars because the name is followed by a quote.
69
+ if (q === '\'' && /[A-Za-z_]/.test(src[i + 1] || '')) {
70
+ let j = i + 1;
71
+ while (/\w/.test(src[j] || '')) j++;
72
+ if (src[j] !== '\'') return i;
73
+ }
74
+ for (let j = i + 1; j < src.length; j++) {
75
+ if (src[j] === '\\') { j++; continue; }
76
+ if (src[j] === q) return j;
77
+ if (src[j] === '\n' && q !== '`') return j;
78
+ }
79
+ return src.length;
80
+ }
81
+
82
+ const stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:])\/\/.*$/gm, '$1');
83
+
84
+ // ── Function discovery ──────────────────────────────────────────────────────────────────────
85
+
86
+ function parseParams(raw, language) {
87
+ const parts = [];
88
+ let depth = 0, cur = '';
89
+ for (const ch of raw) {
90
+ if ('<([{'.includes(ch)) depth++;
91
+ else if ('>)]}'.includes(ch)) depth--;
92
+ if (ch === ',' && depth === 0) { parts.push(cur); cur = ''; } else cur += ch;
93
+ }
94
+ if (cur.trim()) parts.push(cur);
95
+ const out = [];
96
+ let pendingGo = [];
97
+ for (let p of parts.map((x) => x.trim()).filter(Boolean)) {
98
+ p = p.replace(/=.*$/, '').trim();
99
+ if (/^&?\s*(mut\s+)?self$|^self$|^cls$|^this$/.test(p)) continue;
100
+ if (language === 'ruby') {
101
+ if (/^&/.test(p)) continue; // a block argument
102
+ out.push({ name: p.replace(/^\*+/, '').replace(/:.*$/, '').trim(), type: null });
103
+ continue;
104
+ }
105
+ let name = p, type = null, m;
106
+ if (language === 'go') {
107
+ m = p.match(/^(\w+)\s+(.+)$/);
108
+ if (!m) { pendingGo.push(p); continue; }
109
+ [, name, type] = m;
110
+ for (const g of pendingGo) out.push({ name: g, type: simpleType(type) });
111
+ pendingGo = [];
112
+ } else if (language === 'java' || language === 'csharp' || language === 'php') {
113
+ m = p.replace(/^(final|ref|in|out|params|public|private|protected|readonly)\s+/g, '').replace(/^(public|private|protected|readonly)\s+/g, '').match(/^(.+?)\s+&?(?:\.\.\.)?(\w+)$/);
114
+ if (m) [, type, name] = m;
115
+ } else if ((m = p.match(/^(\w+)\??\s*:\s*(.+)$/))) {
116
+ [, name, type] = m;
117
+ }
118
+ out.push({ name: name.replace(/^(mut|val|var|vararg)\s+/, '').replace(/^[&$]+/, ''), type: simpleType(type ? type.replace(/^\?/, '') : type) });
119
+ }
120
+ for (const g of pendingGo) out.push({ name: g, type: null });
121
+ return out;
122
+ }
123
+
124
+ function simpleType(t) {
125
+ if (!t) return null;
126
+ const s = String(t).trim().replace(/^&(mut\s+)?/, '');
127
+ if (/^(number|int|long|short|float|double|decimal|f32|f64|i\d+|u\d+|usize|isize|float64|float32|int\d*|uint\d*|Integer|Double|Long|BigDecimal|Int|Float|Short|Byte)$/.test(s)) return 'number';
128
+ if (/^(bool|boolean|Boolean)$/.test(s)) return 'boolean';
129
+ if (/^(str|string|String|&str|char)$/.test(s)) return 'string';
130
+ return s;
131
+ }
132
+
133
+ /** Find functions and their bodies. Returns [{ name, line, params, bodyStart, bodyEnd, body, exprBody }]. */
134
+ function findFunctions(src, language) {
135
+ const fns = [];
136
+ if (language === 'python') {
137
+ const lines = src.split('\n');
138
+ lines.forEach((l, i) => {
139
+ const m = l.match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\((.*)\)\s*(?:->\s*([^:]+))?:\s*(.*)$/);
140
+ if (!m) return;
141
+ const indent = m[1].length;
142
+ const body = [];
143
+ if (m[5].trim()) body.push({ text: m[5].trim(), line: i + 1, indent: indent + 4 });
144
+ for (let j = i + 1; j < lines.length; j++) {
145
+ const t = lines[j];
146
+ if (!t.trim() || /^\s*#/.test(t)) continue;
147
+ const ind = t.match(/^\s*/)[0].length;
148
+ if (ind <= indent) break;
149
+ body.push({ text: t.trim(), line: j + 1, indent: ind });
150
+ }
151
+ fns.push({ name: m[2], line: i + 1, params: parseParams(m[3], language), returns: m[4]?.trim() || null, pyBody: body });
152
+ });
153
+ annotateRoutes(fns, src);
154
+ return fns;
155
+ }
156
+ if (language === 'ruby') return findRubyFunctions(src);
157
+ const patterns = {
158
+ typescript: [
159
+ /(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*(\w+)\s*(?:<[^>]*>)?\s*\(/g,
160
+ /(?:export\s+)?(?:const|let|var)\s+(\w+)\s*(?::[^=]+)?=\s*(?:async\s*)?(?:<[^>]*>)?\(/g,
161
+ /^\s*(?:public\s+|private\s+|protected\s+|static\s+|async\s+|readonly\s+)*(\w+)\s*(?:<[^>]*>)?\s*\(/gm,
162
+ ],
163
+ go: [/func\s+(?:\([^)]*\)\s*)?(\w+)\s*(?:\[[^\]]*\])?\s*\(/g],
164
+ rust: [/(?:pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(\w+)\s*(?:<[^>]*>)?\s*\(/g],
165
+ java: [/(?:(?:public|private|protected|static|final|synchronized|abstract)\s+)*(?:<[^>]+>\s+)?[\w.<>\[\],?\s]+?\s+(\w+)\s*\(/g],
166
+ kotlin: [/\bfun\s+(?:<[^>]*>\s*)?(?:[\w.]+\.)?(\w+)\s*\(/g],
167
+ php: [/\bfunction\s+&?(\w+)\s*\(/g],
168
+ };
169
+ patterns.javascript = patterns.typescript;
170
+ patterns.csharp = [/(?:(?:public|private|protected|internal|static|virtual|override|async|sealed|abstract|readonly)\s+)*[\w.<>\[\],?\s]+?\s+(\w+)\s*\(/g];
171
+ const seen = new Set();
172
+ for (const re of patterns[language] || []) {
173
+ let m;
174
+ re.lastIndex = 0;
175
+ while ((m = re.exec(src))) {
176
+ const name = m[1];
177
+ const open = src.indexOf('(', m.index + m[0].length - 1);
178
+ if (KEYWORDS_NOT_FN.has(name) || open < 0) continue;
179
+ const close = matchClose(src, open);
180
+ if (close < 0) continue;
181
+ // After the parameter list: an optional return type / throws clause, then a body.
182
+ const after = src.slice(close + 1);
183
+ const head = language === 'kotlin'
184
+ ? after.match(/^\s*(?::\s*([^{=]+?))?()()\s*(?:where\s+[^{=]+)?(=(?![=>])|\{)/)
185
+ : after.match(/^\s*(?::\s*([^{=;]+?)|->\s*([^{;]+?)|\s+(\([^)]*\)|[\w.<>\[\]*&' ]+?))?\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/);
186
+ if (!head || head[4] === ';') continue;
187
+ if (language === 'kotlin' && head[4] === '=') {
188
+ // Kotlin expression body: fun f(x: Int) = when (x) { ... } / = if (...) "A" else "B" / = "A"
189
+ const markerAt = close + 1 + head[0].length - 1;
190
+ const fnLine = lineAt(src, m.index + m[0].lastIndexOf(name));
191
+ if (seen.has(name + ':' + fnLine)) continue;
192
+ seen.add(name + ':' + fnLine);
193
+ const rest = src.slice(markerAt + 1);
194
+ const lead = rest.match(/^\s*/)[0].length;
195
+ const end = kotlinExprEnd(rest, lead);
196
+ fns.push({ key: `${name}@${m.index}`, name, line: fnLine, params: parseParams(src.slice(open + 1, close), language), returns: (head[1] || '').trim() || null, bodyStart: markerAt + 1 + lead, body: `return ${rest.slice(lead, end).trim()}` });
197
+ continue;
198
+ }
199
+ const key = `${name}@${m.index}`;
200
+ // The function's line is where its name is, not where a multi-line match began.
201
+ const fnLine = lineAt(src, m.index + m[0].lastIndexOf(name));
202
+ if (seen.has(name + ':' + fnLine)) continue;
203
+ seen.add(name + ':' + fnLine);
204
+ const returns = (head[1] || head[2] || head[3] || '').trim() || null;
205
+ const params = parseParams(src.slice(open + 1, close), language);
206
+ const markerAt = close + 1 + head[0].length - head[4].length;
207
+ if (head[4] === '=>') {
208
+ const rest = src.slice(markerAt + 2);
209
+ const lead = rest.match(/^\s*/)[0].length;
210
+ if (rest[lead] === '{') {
211
+ const bo = markerAt + 2 + lead, bc = matchClose(src, bo);
212
+ if (bc > 0) fns.push({ key, name, line: fnLine, params, returns, bodyStart: bo + 1, body: src.slice(bo + 1, bc) });
213
+ } else {
214
+ // An expression body ends at its first top-level semicolon (or a blank line, for JS without semicolons).
215
+ const semi = topLevelIndex(rest, ';');
216
+ const blank = rest.search(/\n\s*\n/);
217
+ const end = semi < 0 ? blank : blank < 0 ? semi : Math.min(semi, blank);
218
+ const expr = (end < 0 ? rest : rest.slice(0, end)).trim();
219
+ fns.push({ key, name, line: fnLine, params, returns, bodyStart: markerAt + 2 + lead, body: `return ${expr};` });
220
+ }
221
+ } else {
222
+ const bc = matchClose(src, markerAt);
223
+ if (bc > 0) fns.push({ key, name, line: fnLine, params, returns, bodyStart: markerAt + 1, body: src.slice(markerAt + 1, bc) });
224
+ }
225
+ }
226
+ }
227
+ // Anonymous HTTP handlers: app.post('/refunds', (req, res) => {...}), r.Get("/x", func(w, r) {...}).
228
+ if (language === 'kotlin') {
229
+ // Ktor: get("/x") { ... } inside routing { }
230
+ const re = /\b(get|post|put|patch|delete)\(\s*"([^"]+)"\s*\)\s*\{/g;
231
+ let m;
232
+ while ((m = re.exec(src))) {
233
+ const brace = m.index + m[0].length - 1;
234
+ const bc = matchClose(src, brace);
235
+ if (bc < 0) continue;
236
+ fns.push({ name: `${m[1].toUpperCase()} ${m[2]}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method: m[1].toUpperCase(), path: m[2] } });
237
+ }
238
+ }
239
+ const routeRes = language === 'php'
240
+ ? [/\bRoute::(get|post|put|patch|delete|any)\(\s*['"]([^'"]+)['"]\s*,\s*(?:static\s+)?function\s*\(/g]
241
+ : language === 'go'
242
+ ? [/\.(Get|Post|Put|Patch|Delete|GET|POST|PUT|PATCH|DELETE|HandleFunc|Handle)\(\s*"([^"]+)"\s*,\s*func\s*\(/g]
243
+ : (language === 'typescript' || language === 'javascript')
244
+ ? [/\b\w+\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,(?:[^,()]*,)*?\s*(?:async\s*)?(?:function\s*\w*\s*)?\(/g]
245
+ : [];
246
+ for (const re of routeRes) {
247
+ let m;
248
+ while ((m = re.exec(src))) {
249
+ const open = src.indexOf('(', m.index + m[0].length - 1);
250
+ const close = matchClose(src, open);
251
+ if (close < 0) continue;
252
+ const brace = src.indexOf('{', close);
253
+ if (brace < 0 || !/^\s*(=>\s*)?(\w[\w.*\s]*)?\s*$/.test(src.slice(close + 1, brace))) continue;
254
+ const bc = matchClose(src, brace);
255
+ if (bc < 0) continue;
256
+ const method = /^handle/i.test(m[1]) ? 'ANY' : m[1].toUpperCase();
257
+ fns.push({ name: `${method} ${m[2]}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method, path: m[2] } });
258
+ }
259
+ }
260
+ annotateRoutes(fns, src);
261
+ return fns.sort((a, b) => a.line - b.line);
262
+ }
263
+ /** Mark functions that a decorator or annotation binds to an HTTP route. */
264
+ function annotateRoutes(fns, src) {
265
+ // Decorated handlers: @app.get("/x") / @router.post (Python), @GetMapping (Spring), [HttpGet] (ASP.NET), @Get() (NestJS).
266
+ const lines = src.split('\n');
267
+ for (const fn of fns) {
268
+ if (fn.route) continue;
269
+ for (let k = fn.line - 2; k >= Math.max(0, fn.line - 6); k--) {
270
+ const l = lines[k].trim();
271
+ let m;
272
+ if ((m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i))) { fn.route = { method: m[1].toUpperCase(), path: m[2] }; break; }
273
+ if ((m = l.match(/^@\w+\.route\(\s*['"]([^'"]*)['"](?:.*methods\s*=\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'GET').toUpperCase(), path: m[1] }; break; }
274
+ if ((m = l.match(/^@(Get|Post|Put|Patch|Delete|Request)Mapping(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?["']([^"']*)["'])?/))) { fn.route = { method: m[1] === 'Request' ? 'ANY' : m[1].toUpperCase(), path: m[2] || '/' }; break; }
275
+ if ((m = l.match(/^#\[Route\(\s*(?:path:\s*)?['"]([^'"]*)['"](?:.*methods:\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'ANY').toUpperCase(), path: m[1] }; break; }
276
+ if ((m = l.match(/^\[Http(Get|Post|Put|Patch|Delete)(?:\(\s*"([^"]*)")?/))) { fn.route = { method: m[1].toUpperCase(), path: m[2] || '' }; break; }
277
+ if ((m = l.match(/^@(Get|Post|Put|Patch|Delete)\(\s*(?:['"]([^'"]*)['"])?\s*\)/))) { fn.route = { method: m[1].toUpperCase(), path: m[2] || '' }; break; }
278
+ if (!/^(@|\[|\/\/|#|\*|\/\*)/.test(l) && l) break;
279
+ }
280
+ }
281
+ }
282
+
283
+
284
+ // ── Kotlin and PHP: small source normalizations so the brace-language reader applies ────────
285
+
286
+ const KT_CONTINUES_NEXT = /^\s*(\.|\?\.|\?:|&&|\|\||[+\-*/%]|else\b(?!\s*->)|->|\)|\]|:)/;
287
+ const KT_CONTINUES_LINE = /(&&|\|\||[=+\-*/%(,.:[]|->|\belse|\bif\s*\([^)]*\))\s*$/;
288
+
289
+ /** Where a Kotlin expression body (after `=`) ends: the first line break at depth 0 that is not a continuation. */
290
+ function kotlinExprEnd(src, from) {
291
+ let depth = 0;
292
+ for (let i = from; i < src.length; i++) {
293
+ const c = src[i];
294
+ if (c === '"' || c === '\'') { i = skipString(src, i); continue; }
295
+ if (c === '/' && src[i + 1] === '/') { const n = src.indexOf('\n', i); if (n < 0) return src.length; i = n - 1; continue; }
296
+ if ('([{'.includes(c)) depth++;
297
+ else if (')]}'.includes(c)) { if (--depth < 0) return i; }
298
+ else if (c === '\n' && depth === 0) {
299
+ const line = src.slice(src.lastIndexOf('\n', i - 1) + 1, i);
300
+ const next = src.slice(i + 1);
301
+ if (/^\s*\n/.test(next) || !next.trim()) return i;
302
+ if (!KT_CONTINUES_LINE.test(line) && !KT_CONTINUES_NEXT.test(next)) return i;
303
+ }
304
+ }
305
+ return src.length;
306
+ }
307
+
308
+ /** Kotlin has no semicolons: end each top-level statement of a body with one so it splits like Java. */
309
+ function kotlinTerminate(body) {
310
+ const src = stripCommentsKeepLayout(body);
311
+ let out = '', depth = 0, last = 0;
312
+ for (let i = 0; i < src.length; i++) {
313
+ const c = src[i];
314
+ if (c === '"' || c === '\'') { i = skipString(src, i); continue; }
315
+ if ('([{'.includes(c)) depth++;
316
+ else if (')]}'.includes(c)) depth--;
317
+ else if (c === '\n' && depth === 0) {
318
+ const line = src.slice(src.lastIndexOf('\n', i - 1) + 1, i);
319
+ const next = src.slice(i + 1);
320
+ if (line.trim() && !/[{;]\s*$/.test(line) && !KT_CONTINUES_LINE.test(line) && !KT_CONTINUES_NEXT.test(next)) {
321
+ out += src.slice(last, i) + ';';
322
+ last = i;
323
+ }
324
+ }
325
+ }
326
+ return out + src.slice(last);
327
+ }
328
+
329
+ /** Apply `fn` to the code between strings and comments (strings and comments are kept as written). */
330
+ function mapCode(src, fn) {
331
+ let out = '', start = 0;
332
+ for (let i = 0; i < src.length; i++) {
333
+ const c = src[i];
334
+ let end = -1;
335
+ if (c === '"' || c === '\'') end = skipString(src, i);
336
+ else if (c === '/' && src[i + 1] === '/') { const n = src.indexOf('\n', i); end = n < 0 ? src.length - 1 : n - 1; }
337
+ else if (c === '/' && src[i + 1] === '*') { const n = src.indexOf('*/', i + 2); end = n < 0 ? src.length - 1 : n + 1; }
338
+ if (end < 0) continue;
339
+ end = Math.max(end, i); // always move forward
340
+ out += fn(src.slice(start, i)) + src.slice(i, end + 1);
341
+ start = i = end + 1;
342
+ i--;
343
+ }
344
+ return out + fn(src.slice(start));
345
+ }
346
+
347
+ /** PHP reads like the other brace languages once `$name` is `name` and `->` is `.` (line numbers unchanged). */
348
+ function normalizePhp(src) {
349
+ return mapCode(src.replace(/(^|[^\[])#(?!\[)/gm, '$1//'), (code) => code
350
+ .replace(/\$this\s*->/g, 'this.')
351
+ .replace(/\$(?=[A-Za-z_])/g, '')
352
+ .replace(/(\w|\))\s*(?:\?)?->\s*(?=[A-Za-z_])/g, '$1.')
353
+ .replace(/\belseif\b/g, 'else if'));
354
+ }
355
+
356
+ /** Kotlin `if (c) A else if (c2) B else C` used as a value. Returns false when the text is not one. */
357
+ function readKotlinIf(text, inputs, rules, unread, line, setOtherwise) {
358
+ let s = text.trim().replace(/;$/, '');
359
+ if (!/^if\s*\(/.test(s)) return false;
360
+ const local = [];
361
+ const value = (v) => {
362
+ v = v.trim();
363
+ if (v.startsWith('{')) { const c = matchClose(v, 0); return c === v.length - 1 ? v.slice(1, -1).trim() : null; }
364
+ return v;
365
+ };
366
+ while (/^if\s*\(/.test(s)) {
367
+ const open = s.indexOf('(');
368
+ const close = matchClose(s, open);
369
+ if (close < 0) return false;
370
+ const cond = s.slice(open + 1, close);
371
+ const rest = s.slice(close + 1).trim();
372
+ const elseAt = rest.startsWith('{') ? matchClose(rest, 0) + 1 : rest.search(/\belse\b/);
373
+ if (elseAt <= 0) return false;
374
+ const thenPart = value(rest.slice(0, elseAt));
375
+ const after = rest.slice(elseAt).trim();
376
+ if (!/^else\b/.test(after)) return false;
377
+ const when = toThunderCondition(cond, inputs), result = thenPart == null ? null : toThunderOutcome(thenPart);
378
+ if (!when || !result) { unread.push({ line, text: `if (${cond.trim()})`, reason: 'This choice uses a condition or answer that is not a fixed value.' }); return true; }
379
+ local.push({ when, result, line });
380
+ s = after.replace(/^else\s*/, '');
381
+ }
382
+ const fb = value(s);
383
+ const fallback = fb == null ? null : toThunderOutcome(fb);
384
+ if (!fallback) { unread.push({ line, text: s.slice(0, 120), reason: 'The fallback answer is computed, not a fixed value.' }); return true; }
385
+ rules.push(...local);
386
+ setOtherwise({ result: fallback, line });
387
+ return true;
388
+ }
389
+
390
+ /** Kotlin `when` arms: `A, B -> value`, `in 1..5 -> value`, `else -> value`, one per line or `;`. */
391
+ function kotlinWhenArms(body, baseLine) {
392
+ const arms = [];
393
+ const src = stripCommentsKeepLayout(body);
394
+ let i = 0;
395
+ while (i < src.length) {
396
+ while (i < src.length && /[\s;]/.test(src[i])) i++;
397
+ if (i >= src.length) break;
398
+ const arrow = (() => {
399
+ let depth = 0;
400
+ for (let j = i; j < src.length; j++) {
401
+ const c = src[j];
402
+ if (c === '"' || c === '\'') { j = skipString(src, j); continue; }
403
+ if ('([{'.includes(c)) depth++; else if (')]}'.includes(c)) depth--;
404
+ else if (c === '-' && src[j + 1] === '>' && depth === 0) return j;
405
+ }
406
+ return -1;
407
+ })();
408
+ if (arrow < 0) return null;
409
+ const pattern = src.slice(i, arrow).trim();
410
+ let j = arrow + 2;
411
+ while (/[ \t]/.test(src[j] || '')) j++;
412
+ let value, end;
413
+ if (src[j] === '{') {
414
+ const c = matchClose(src, j);
415
+ if (c < 0) return null;
416
+ const inner = src.slice(j + 1, c).trim();
417
+ value = /[;\n]/.test(inner) ? null : inner;
418
+ end = c + 1;
419
+ } else {
420
+ end = kotlinExprEnd(src, j);
421
+ const semi = topLevelIndex(src.slice(j, end), ';');
422
+ if (semi >= 0) end = j + semi;
423
+ value = src.slice(j, end).trim();
424
+ }
425
+ if (value) value = value.replace(/^return\s+/, '');
426
+ arms.push({ pattern: pattern === 'else' ? null : pattern, guard: null, value, line: baseLine + lineAt(src, i) - 1 });
427
+ i = end;
428
+ }
429
+ return arms;
430
+ }
431
+
432
+ /** Kotlin `in a..b` (inclusive), `in a until b`, `in a..<b` as the reader's range forms. */
433
+ function kotlinPattern(p) {
434
+ return p.split(/,(?![^(]*\))/).map((x) => x.trim()
435
+ .replace(/^in\s+(-?[\d.]+)\s*\.\.\s*(-?[\d.]+)$/, '$1..=$2')
436
+ .replace(/^in\s+(-?[\d.]+)\s*(?:until|\.\.<)\s*(-?[\d.]+)$/, '$1..$2')).join(', ');
437
+ }
438
+
439
+ // ── Expressions: source language -> ThunderLang ─────────────────────────────────────────────
440
+
441
+ const EXPR_TOKEN = /\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|===|!==|==|!=|>=|<=|&&|\|\||->|::|[<>!()?:,.]|\d+(?:\.\d+)?(?:f64|f32|[fFdDmMlL])?|[A-Za-z_$][\w$]*)/y;
442
+
443
+ function lex(text) {
444
+ const out = [];
445
+ EXPR_TOKEN.lastIndex = 0;
446
+ let i = 0;
447
+ const s = text.trim();
448
+ while (i < s.length) {
449
+ EXPR_TOKEN.lastIndex = i;
450
+ const m = EXPR_TOKEN.exec(s);
451
+ if (!m) return null;
452
+ out.push(m[1]);
453
+ i = EXPR_TOKEN.lastIndex;
454
+ while (i < s.length && /\s/.test(s[i])) i++;
455
+ }
456
+ return out;
457
+ }
458
+
459
+ const unquote = (t) => t.slice(1, -1);
460
+
461
+ /** Convert a condition to ThunderLang, or return null with nothing guessed. */
462
+ export function toThunderCondition(text, inputs = []) {
463
+ const toks = lex(text);
464
+ if (!toks || !toks.length) return null;
465
+ const out = [];
466
+ for (let i = 0; i < toks.length; i++) {
467
+ let t = toks[i];
468
+ const next = toks[i + 1];
469
+ if (t === 'this' || t === 'self') { if (next === '.') i++; continue; }
470
+ if (t === '&&' || t === 'and') { out.push('and'); continue; }
471
+ if (t === '||' || t === 'or') { out.push('or'); continue; }
472
+ if (t === '!' || t === 'not') { out.push('not'); continue; }
473
+ if (t === '===' || t === '==') { out.push('=='); continue; }
474
+ if (t === '!==' || t === '!=') { out.push('!='); continue; }
475
+ if (['>', '<', '>=', '<=', '(', ')'].includes(t)) { out.push(t); continue; }
476
+ if (t === 'True' || t === 'true') { out.push('true'); continue; }
477
+ if (t === 'False' || t === 'false') { out.push('false'); continue; }
478
+ if (/^["']/.test(t)) { if (t[0] === '"' && /#\{|\$\{|\$[A-Za-z_]/.test(t)) return null; out.push(JSON.stringify(unquote(t))); continue; }
479
+ if (/^\d/.test(t)) { out.push(t.replace(/(f64|f32|[fFdDmMlL])$/, '')); continue; }
480
+ if (/^[A-Za-z_$]/.test(t)) {
481
+ // Java/C# equality helpers: a.equals(b), Objects.equals(a, b), string.Equals(a, b).
482
+ if ((t === 'Objects' || t === 'string' || t === 'String') && next === '.' && /^(equals|Equals)$/.test(toks[i + 2] || '') && toks[i + 3] === '(') {
483
+ const close = findClose(toks, i + 3);
484
+ const args = splitArgs(toks.slice(i + 4, close));
485
+ if (args.length !== 2) return null;
486
+ const a = toThunderCondition(args[0].join(' '), inputs), b = toThunderCondition(args[1].join(' '), inputs);
487
+ if (!a || !b) return null;
488
+ out.push(`${a} == ${b}`);
489
+ i = close;
490
+ continue;
491
+ }
492
+ let path = t;
493
+ while (toks[i + 1] === '.' && /^[A-Za-z_$]/.test(toks[i + 2] || '')) {
494
+ if (/^(equals|Equals)$/.test(toks[i + 2]) && toks[i + 3] === '(') break;
495
+ path += '.' + toks[i + 2];
496
+ i += 2;
497
+ }
498
+ if (toks[i + 1] === '.' && /^(equals|Equals)$/.test(toks[i + 2] || '') && toks[i + 3] === '(') {
499
+ const close = findClose(toks, i + 3);
500
+ // Static two-argument forms: java.util.Objects.equals(a, b), System.String.Equals(a, b).
501
+ if (/(^|\.)(Objects|String|string)$/.test(path)) {
502
+ const args = splitArgs(toks.slice(i + 4, close));
503
+ if (args.length !== 2) return null;
504
+ const a = toThunderCondition(args[0].join(' '), inputs), b = toThunderCondition(args[1].join(' '), inputs);
505
+ if (!a || !b) return null;
506
+ out.push(`${a} == ${b}`);
507
+ i = close;
508
+ continue;
509
+ }
510
+ const arg = toThunderCondition(toks.slice(i + 4, close).join(' '), inputs);
511
+ if (!arg) return null;
512
+ out.push(`${path} == ${arg}`);
513
+ i = close;
514
+ continue;
515
+ }
516
+ // Rust/C++/C# enum paths: Plan::Enterprise -> Enterprise.
517
+ while (toks[i + 1] === '::' && /^[A-Za-z_]/.test(toks[i + 2] || '')) { path = toks[i + 2]; i += 2; }
518
+ // A call with no arguments reads like a field (user.isAdmin()); a call with arguments does not.
519
+ if (toks[i + 1] === '(') {
520
+ if (toks[i + 2] !== ')') return null;
521
+ i += 2;
522
+ }
523
+ if (/^(null|nil|None|undefined)$/.test(path)) return null;
524
+ out.push(path);
525
+ continue;
526
+ }
527
+ return null;
528
+ }
529
+ for (let k = 0; k < out.length; k++) if (/^[<>]=?$/.test(out[k]) && (/^"/.test(out[k - 1] || '') || /^"/.test(out[k + 1] || ''))) return null; // text ordering differs by language
530
+ const expr = out.join(' ').replace(/\( /g, '(').replace(/ \)/g, ')').replace(/not \(/g, 'not (').replace(/\bnot not /g, ''); // !!x is x
531
+ try { compileExpr(expr, { inputs }); } catch { return null; }
532
+ return simplifyExpr(expr);
533
+ }
534
+
535
+ function findClose(toks, open) {
536
+ let depth = 0;
537
+ for (let i = open; i < toks.length; i++) {
538
+ if (toks[i] === '(') depth++;
539
+ else if (toks[i] === ')' && --depth === 0) return i;
540
+ }
541
+ return toks.length - 1;
542
+ }
543
+ function splitArgs(toks) {
544
+ const args = [[]];
545
+ let depth = 0;
546
+ for (const t of toks) {
547
+ if (t === '(') depth++;
548
+ if (t === ')') depth--;
549
+ if (t === ',' && depth === 0) args.push([]); else args[args.length - 1].push(t);
550
+ }
551
+ return args;
552
+ }
553
+
554
+ /** An answer a decision can return: a string, enum member, number, or boolean. Null otherwise. */
555
+ export function toThunderOutcome(text) {
556
+ let s = String(text).trim().replace(/;$/, '').trim();
557
+ s = s.replace(/^Ok\((.*)\)$/, '$1').replace(/\.(to_string|into|to_owned)\(\)$/, '').replace(/^String::from\((.*)\)$/, '$1').trim();
558
+ // Absence is not an answer: None/null/nil/undefined are "returns nothing", handled as guards.
559
+ if (/^(None|null|nil|undefined|Nothing)$/.test(s)) return null;
560
+ let m;
561
+ if ((m = s.match(/^"([^"\\]*)"$|^'([^'\\]*)'$|^`([^`$\\]*)`$/))) {
562
+ // "#{x}" (Ruby) and "$x" / "${x}" (Kotlin, PHP) build the text from values: computed, not fixed.
563
+ if (m[1] != null && /#\{|\$\{|\$[A-Za-z_]/.test(m[1])) return null;
564
+ const v = m[1] ?? m[2] ?? m[3];
565
+ if (v === '') return null; // an empty string is not an answer a reader can act on
566
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(v) ? v : JSON.stringify(v);
567
+ }
568
+ if (/^-?\d+(\.\d+)?(f64|f32|[fFdDmMlL])?$/.test(s)) return s.replace(/(f64|f32|[fFdDmMlL])$/, '');
569
+ if (/^(true|false|True|False)$/.test(s)) return s.toLowerCase();
570
+ if ((m = s.match(/^(?:[A-Za-z_][\w]*(?:\.|::))+([A-Z][A-Za-z0-9_]*)$/))) return m[1];
571
+ if (/^[A-Z][A-Za-z0-9_]*$/.test(s)) return s;
572
+ return null;
573
+ }
574
+
575
+
576
+ // ── Guards: early exits inside any function ─────────────────────────────────────────────────
577
+ // Most real functions are not pure decisions, but they still enforce rules as early exits:
578
+ // "if the row is missing, fail with NotFound". A guard is an `if` with no else whose branch is a
579
+ // single terminating statement. Routine error passing (Go `if err != nil { return err }`) is noise
580
+ // to a reader and is skipped.
581
+
582
+ const lastSeg = (s) => String(s).split(/\.|::/).pop();
583
+ const firstString = (s) => (String(s).match(/^\s*(?:f|r|b)?["'`]([^"'`]{1,80})["'`]/) || [])[1] || null;
584
+
585
+ function splitTop(str, delim) {
586
+ const out = [];
587
+ let depth = 0, cur = '';
588
+ for (let i = 0; i < str.length; i++) {
589
+ const ch = str[i];
590
+ if (ch === '"' || ch === '\'' || ch === '`') { const j = skipString(str, i); cur += str.slice(i, j + 1); i = j; continue; }
591
+ if ('([{'.includes(ch)) depth++;
592
+ else if (')]}'.includes(ch)) depth--;
593
+ if (ch === delim && depth === 0) { out.push(cur); cur = ''; } else cur += ch;
594
+ }
595
+ out.push(cur);
596
+ return out;
597
+ }
598
+
599
+ /** What a terminating statement does, or null when the statement does not end the function. */
600
+ export function terminatorEffect(stmt, language) {
601
+ const s = String(stmt).trim().replace(/;$/, '').trim();
602
+ let m;
603
+ if ((m = s.match(/^throw\s+new\s+([\w.$]+)\s*\(([\s\S]*)\)$/))) return { kind: 'fails', name: lastSeg(m[1]), detail: firstString(m[2]) };
604
+ if ((m = s.match(/^throw\s+([\w.$]+)$/))) return { kind: 'fails', name: lastSeg(m[1]) };
605
+ if ((m = s.match(/^throw\s+([A-Z][\w.$]*)\s*\(([\s\S]*)\)$/))) return { kind: 'fails', name: lastSeg(m[1]), detail: firstString(m[2]) }; // Kotlin: no `new`
606
+ if ((m = s.match(/^error\(([\s\S]*)\)$/)) && language === 'kotlin') return { kind: 'fails', name: 'IllegalStateException', detail: firstString(m[1]) };
607
+ if ((m = s.match(/^abort\(\s*(\d{3})\b/))) return { kind: 'responds', name: m[1] }; // Laravel
608
+ if ((m = s.match(/^raise\s+([\w.]+)(?:\(([\s\S]*)\))?$/))) return { kind: 'fails', name: lastSeg(m[1]), detail: m[2] ? firstString(m[2]) : null };
609
+ if (language === 'ruby') {
610
+ if ((m = s.match(/^raise\s+([A-Z][\w:]*)(?:\.new)?\s*(?:,\s*|\(\s*)?([\s\S]*?)\)?$/))) return { kind: 'fails', name: lastSeg(m[1]), detail: firstString(m[2] || '') };
611
+ if ((m = s.match(/^(?:raise|fail)\s+(["'][\s\S]*)$/))) return { kind: 'fails', name: 'RuntimeError', detail: firstString(m[1]) };
612
+ if ((m = s.match(/^(?:head|halt)\s+(?::|")?(\w+)"?/))) return { kind: 'responds', name: m[1] }; // Rails head :forbidden, Sinatra halt 401
613
+ }
614
+ if ((m = s.match(/^panic!?\(([\s\S]*)\)$/))) return { kind: 'fails', name: 'panic', detail: firstString(m[1]) };
615
+ if ((m = s.match(/^return\s+Err\(([\s\S]*)\)$/))) {
616
+ const inner = m[1].trim();
617
+ return { kind: 'fails', name: firstString(inner) ? 'error' : lastSeg(inner.replace(/\(.*$/s, '')), detail: firstString(inner) };
618
+ }
619
+ if (s === 'return') return { kind: 'stops' };
620
+ if ((m = s.match(/^render\b.*\bstatus:\s*(?::|")?(\w+)/)) && language === 'ruby') return { kind: 'responds', name: m[1] };
621
+ if (!(m = s.match(/^return\s+([\s\S]+)$/))) return null;
622
+ const v = m[1].trim();
623
+ if (language === 'go') {
624
+ const parts = splitTop(v, ',').map((x) => x.trim());
625
+ const last = parts[parts.length - 1];
626
+ if (last === 'err' || /^fmt\.Errorf\([^)]*%w/.test(last)) return { kind: 'passes-error' };
627
+ if ((m = last.match(/^(?:errors\.New|fmt\.Errorf)\(\s*"([^"]*)"/))) return { kind: 'fails', name: 'error', detail: m[1] };
628
+ if (/^Err[A-Z]\w*$/.test(last)) return { kind: 'fails', name: last };
629
+ if (parts.length === 1 && last === 'nil') return { kind: 'nothing' };
630
+ }
631
+ if (/^(null|undefined|None|nil|void 0)$/.test(v)) return { kind: 'nothing' };
632
+ if ((m = v.match(/(?:\b(?:status|Status|StatusCode|HttpStatus|sendStatus)|\.code)\s*\(\s*(\d{3})\s*\)/)) || (m = v.match(/^\{\s*status\s*:\s*(\d{3})\b/))) return { kind: 'responds', name: m[1] };
633
+ if ((m = v.match(/^(BadRequest|Unauthorized|Forbid|Forbidden|NotFound|Conflict|UnprocessableEntity)\s*\(/))) return { kind: 'responds', name: m[1] };
634
+ const fixed = toThunderOutcome(v);
635
+ if (fixed) return { kind: 'returns', name: fixed };
636
+ return { kind: 'returns-computed' };
637
+ }
638
+
639
+ function sayGuard(effect, condText) {
640
+ const when = `if ${condText}`;
641
+ switch (effect.kind) {
642
+ case 'fails': return `Fails with ${effect.name}${effect.detail ? ` ("${effect.detail}")` : ''} ${when}.`;
643
+ case 'responds': return `Responds ${effect.name} ${when}.`;
644
+ case 'nothing': return `Stops early and returns nothing ${when}.`;
645
+ case 'stops': return `Stops early ${when}.`;
646
+ case 'returns': return `Returns ${effect.name} early ${when}.`;
647
+ default: return `Returns early ${when}.`;
648
+ }
649
+ }
650
+
651
+ /** Build a guard from a condition and a single terminating statement, or null (or 'skip' for noise). */
652
+ function makeGuard(cond, branch, language, inputs, line) {
653
+ const stmts = splitTop(branch.trim().replace(/;\s*$/, ''), ';').map((x) => x.trim()).filter(Boolean);
654
+ if (stmts.length !== 1 || /\n\s*\S[\s\S]*\n/.test(stmts[0]) && !/^(throw|raise|return)/.test(stmts[0])) return null;
655
+ const effect = terminatorEffect(stmts[0], language);
656
+ if (!effect) return null;
657
+ if (effect.kind === 'passes-error') return 'skip';
658
+ const when = toThunderCondition(cond, inputs);
659
+ const code = cond.trim().replace(/\s+/g, ' ');
660
+ return { when, code, effect, line, readable: !!when, says: sayGuard(effect, when ? sayCondition(when) : `\`${code}\``) };
661
+ }
662
+
663
+ /** Parse `if COND BRANCH [rest]` in a brace language: { cond, branch, remaining } or null. */
664
+ function splitIf(text, language) {
665
+ let rest = text.replace(/^if\b\s*/, '');
666
+ let cond, after;
667
+ if (language === 'go' || language === 'rust' || rest[0] !== '(') {
668
+ const b = findTopBrace(rest);
669
+ if (b < 0) return null;
670
+ cond = rest.slice(0, b).trim(); after = rest.slice(b);
671
+ } else {
672
+ const close = matchClose(rest, 0);
673
+ if (close < 0) return null;
674
+ cond = rest.slice(1, close); after = rest.slice(close + 1).trimStart();
675
+ }
676
+ let branch, remaining;
677
+ if (after[0] === '{') {
678
+ const bc = matchClose(after, 0);
679
+ if (bc < 0) return null;
680
+ branch = after.slice(1, bc).trim(); remaining = after.slice(bc + 1).trim();
681
+ } else {
682
+ const semi = topLevelIndex(after, ';');
683
+ branch = (semi < 0 ? after : after.slice(0, semi)).trim(); remaining = semi < 0 ? '' : after.slice(semi + 1).trim();
684
+ }
685
+ return { cond: cond.trim(), branch, remaining };
686
+ }
687
+
688
+
689
+ // ── switch / match ──────────────────────────────────────────────────────────────────────────
690
+ // Each arm becomes a rule: `subject == value` (several values joined with or), a range, a C#
691
+ // relational pattern, or (Go's subject-less switch) the case's own condition; Rust/Python guards
692
+ // are added with and. The default arm (default, _, case _) becomes the fallback. Any arm whose
693
+ // body does more than give a fixed answer makes the whole switch "not read", never half-guessed.
694
+
695
+ /** One switch label or pattern as a ThunderLang condition, or null. */
696
+ function patternCondition(pattern, subject, inputs, language) {
697
+ const p = pattern.trim();
698
+ let m;
699
+ if (subject == null) return toThunderCondition(p, inputs); // Go: switch { case cond: }
700
+ if ((m = p.match(/^(-?\d+(?:\.\d+)?)\s*\.\.(=?)\s*(-?\d+(?:\.\d+)?)$/))) return `${subject} >= ${m[1]} and ${subject} ${m[2] ? '<=' : '<'} ${m[3]}`;
701
+ if ((m = p.match(/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/))) return `${subject} ${m[1]} ${m[2]}`; // C# relational pattern
702
+ if ((m = p.match(/^not\s+(.+)$/)) && language === 'csharp') { const v = toThunderOutcome(m[1]); return v ? `${subject} != ${/^[A-Za-z_]/.test(v) && !/^(true|false)$/.test(v) ? v : v}` : null; }
703
+ const parts = splitTop(p.replace(/\s+or\s+/g, '|'), language === 'rust' || language === 'csharp' || language === 'python' ? '|' : ',').map((x) => x.trim()).filter(Boolean);
704
+ if (parts.length > 1) {
705
+ const each = parts.map((x) => patternCondition(x, subject, inputs, language));
706
+ return each.every(Boolean) ? each.map((c) => (/\s(and|or)\s/.test(c) ? `(${c})` : c)).join(' or ') : null;
707
+ }
708
+ const v = valueLiteral(p);
709
+ return v == null ? null : `${subject} == ${v}`;
710
+ }
711
+
712
+ /** A case label value as a ThunderLang literal: "text", 42, true, or an enum member name. */
713
+ function valueLiteral(text) {
714
+ const s = text.trim();
715
+ let m;
716
+ if (/^(nil|null|None|undefined)$/.test(s)) return null; // "is missing" is not a value a rule can hold
717
+ if ((m = s.match(/^"([^"\\]*)"$|^'([^'\\]*)'$/))) return m[1] != null && /#\{|\$\{|\$[A-Za-z_]/.test(m[1]) ? null : JSON.stringify(m[1] ?? m[2]);
718
+ if (/^-?\d+(\.\d+)?$/.test(s)) return s;
719
+ if (/^(true|false|True|False)$/.test(s)) return s.toLowerCase();
720
+ if ((m = s.match(/^(?:[A-Za-z_]\w*(?:\.|::))*([A-Za-z_]\w*)$/))) return m[1];
721
+ return null;
722
+ }
723
+
724
+ /** Replace a pattern binding (Rust `n if n > 3`) with the subject inside its guard. */
725
+ const rebind = (guard, name, subject) => guard.replace(new RegExp(`\\b${name}\\b`, 'g'), subject);
726
+
727
+ /** The arms of a switch/match body: [{ pattern|null (default), guard, value, line }] or null. */
728
+ function switchArms(body, language, baseLine) {
729
+ const arms = [];
730
+ const lineOf = (idx) => baseLine + lineAt(body, idx) - 1;
731
+ if (language === 'rust' || language === 'csharp-expr') {
732
+ // pattern => value, separated by top-level commas (Rust arms may use blocks without commas).
733
+ let i = 0;
734
+ while (i < body.length) {
735
+ while (i < body.length && /[\s,]/.test(body[i])) i++;
736
+ if (i >= body.length) break;
737
+ const arrow = body.indexOf('=>', i);
738
+ if (arrow < 0) return null;
739
+ const head = body.slice(i, arrow).trim();
740
+ let j = arrow + 2;
741
+ while (/\s/.test(body[j] || '')) j++;
742
+ let value, end;
743
+ if (body[j] === '{') { const c = matchClose(body, j); if (c < 0) return null; value = blockOnlyValue(body.slice(j + 1, c), language); end = c + 1; }
744
+ else { const c = topLevelIndex(body, ',', j); end = c < 0 ? body.length : c; value = body.slice(j, end).trim(); }
745
+ const g = head.match(/^(.*?)\s+(?:if|when)\s+(.+)$/s);
746
+ arms.push({ pattern: (g ? g[1] : head).trim(), guard: g ? g[2].trim() : null, value, line: lineOf(i) });
747
+ i = end + 1;
748
+ }
749
+ return arms;
750
+ }
751
+ // C-family: case LABELS: / case LABELS -> / default: / default ->
752
+ const starts = [];
753
+ const re = /(^|[\s;{}:])(case\b|default\b)/g;
754
+ let m;
755
+ while ((m = re.exec(body))) {
756
+ const at = m.index + m[1].length;
757
+ if (depthAt(body, at) === 0) starts.push(at);
758
+ }
759
+ let pending = [];
760
+ for (let k = 0; k < starts.length; k++) {
761
+ const clause = body.slice(starts[k], starts[k + 1] ?? body.length).trim();
762
+ const isDefault = clause.startsWith('default');
763
+ const afterKw = clause.replace(/^(case|default)\b/, '');
764
+ const arrowAt = topLevelIndex(afterKw, '-') >= 0 && /->/.test(afterKw) ? afterKw.indexOf('->') : -1;
765
+ const colonAt = topLevelIndex(afterKw, ':');
766
+ const useArrow = arrowAt >= 0 && (colonAt < 0 || arrowAt < colonAt);
767
+ const cut = useArrow ? arrowAt : colonAt;
768
+ if (cut < 0) return null;
769
+ const label = afterKw.slice(0, cut).trim();
770
+ let rest = afterKw.slice(cut + (useArrow ? 2 : 1)).trim();
771
+ const g = label.match(/^(.*?)\s+when\s+(.+)$/s);
772
+ const pattern = isDefault ? null : (g ? g[1] : label);
773
+ if (!useArrow && !rest) { pending.push(pattern); continue; } // C fall-through: case A: case B: return X;
774
+ let value;
775
+ if (rest.startsWith('{')) value = blockOnlyValue(rest.slice(1, matchClose(rest, 0)), language);
776
+ else {
777
+ rest = rest.replace(/;?\s*break\s*;?\s*$/, '').replace(/;\s*$/, '').trim();
778
+ value = useArrow ? rest : (rest.match(/^return\s+([\s\S]+)$/) || [])[1] ?? null;
779
+ if (value && /;/.test(value)) value = null; // more than one statement
780
+ }
781
+ const patterns = [...pending, pattern];
782
+ pending = [];
783
+ if (patterns.includes(null)) arms.push({ pattern: null, guard: null, value, line: lineOf(starts[k]) });
784
+ else arms.push({ pattern: patterns.join(language === 'go' && patterns.length === 1 ? '' : ', ') || patterns[0], guard: g ? g[2].trim() : null, value, line: lineOf(starts[k]) });
785
+ }
786
+ return arms;
787
+ }
788
+
789
+ function depthAt(s, idx) {
790
+ let d = 0;
791
+ for (let i = 0; i < idx; i++) {
792
+ const c = s[i];
793
+ if (c === '"' || c === '\'' || c === '`') { i = skipString(s, i); continue; }
794
+ if ('({['.includes(c)) d++; else if (')}]'.includes(c)) d--;
795
+ }
796
+ return d;
797
+ }
798
+
799
+ /** The single answer a block gives: `{ return X; }` or a Rust tail value. */
800
+ function blockOnlyValue(inner, language) {
801
+ const t = inner.trim().replace(/;\s*$/, '');
802
+ if (/;/.test(t)) return null;
803
+ const m = t.match(/^return\s+([\s\S]+)$/);
804
+ if (m) return m[1].trim();
805
+ return language === 'rust' || language === 'csharp-expr' ? t : null;
806
+ }
807
+
808
+ /**
809
+ * Read a switch/match statement or expression. `text` is `switch (x) {...}`, `switch x {...}`,
810
+ * `match x {...}`, or C# `x switch {...}`. Returns { rules, otherwise } or { unread } or null.
811
+ */
812
+ function readSwitch(text, language, inputs, line) {
813
+ let subjectText, body, kind = language;
814
+ let m;
815
+ const t = text.trim();
816
+ if ((m = t.match(/^switch\s*\(([\s\S]*?)\)\s*\{/)) && language !== 'go' && language !== 'rust') {
817
+ const open = t.indexOf('{', m[0].length - 1); subjectText = m[1]; body = t.slice(open + 1, matchClose(t, open));
818
+ } else if (language === 'go' && (m = t.match(/^switch\b([^{]*)\{/))) {
819
+ const open = t.indexOf('{'); subjectText = m[1].trim() || null; body = t.slice(open + 1, matchClose(t, open));
820
+ } else if (language === 'rust' && (m = t.match(/^match\s+([^{]+?)\s*\{/))) {
821
+ const open = t.indexOf('{', m[0].length - 1); subjectText = m[1]; body = t.slice(open + 1, matchClose(t, open));
822
+ } else if (language === 'php' && (m = t.match(/^match\s*\(([\s\S]*?)\)\s*\{/))) {
823
+ const open = t.indexOf('{', m[0].length - 1); subjectText = /^\s*true\s*$/.test(m[1]) ? null : m[1]; body = t.slice(open + 1, matchClose(t, open)); kind = 'csharp-expr';
824
+ } else if (language === 'kotlin' && (m = t.match(/^when\s*(?:\(([\s\S]*?)\))?\s*\{/))) {
825
+ const open = t.indexOf('{', m[0].length - 1); subjectText = m[1] ?? null; body = t.slice(open + 1, matchClose(t, open)); kind = 'kotlin-when';
826
+ } else if (language === 'csharp' && (m = t.match(/^([\w.]+)\s+switch\s*\{/))) {
827
+ const open = t.indexOf('{'); subjectText = m[1]; body = t.slice(open + 1, matchClose(t, open)); kind = 'csharp-expr';
828
+ } else return null;
829
+ if (body == null) return null;
830
+ const subject = subjectText == null ? null : toThunderCondition(subjectText, inputs);
831
+ if (subjectText != null && (!subject || /\s/.test(subject))) return { unread: [{ line, text: t.split('\n')[0].slice(0, 120), reason: 'This switch compares something other than an input or field.' }] };
832
+ const arms = kind === 'kotlin-when'
833
+ ? (kotlinWhenArms(body, line) || null)?.map((a) => (a.pattern == null || subjectText == null ? a : { ...a, pattern: kotlinPattern(a.pattern) }))
834
+ : switchArms(body, kind, line)?.map((a) => (language === 'php' && a.pattern === 'default' ? { ...a, pattern: null } : a));
835
+ if (!arms || !arms.length) return { unread: [{ line, text: t.split('\n')[0].slice(0, 120), reason: 'This switch has a shape the reader does not recognize yet.' }] };
836
+ return armsToRules(arms, subject, inputs, language);
837
+ }
838
+
839
+ /** Switch arms -> { rules, otherwise } or { unread }. Any arm that is not a fixed answer leaves the whole switch unread. */
840
+ function armsToRules(arms, subject, inputs, language) {
841
+ const rules = [];
842
+ let otherwise = null;
843
+ for (const a of arms) {
844
+ const result = a.value == null ? null : toThunderOutcome(a.value);
845
+ if (!result) return { unread: [{ line: a.line, text: (a.pattern ?? 'default') + ' => ' + String(a.value ?? '...').slice(0, 60), reason: 'This case does more than give a fixed answer, so the switch is not shown as rules.' }] };
846
+ const isDefault = a.pattern == null || a.pattern === '_' || (language === 'rust' && /^[a-z_]\w*$/.test(a.pattern) && !a.guard && !inputs.includes(a.pattern));
847
+ if (isDefault && !a.guard) { otherwise = { result, line: a.line }; break; }
848
+ let when = isDefault ? null : patternCondition(a.pattern, subject, inputs, language);
849
+ if (a.guard) {
850
+ const binding = (a.pattern || '').match(/^([a-z_]\w*)$/);
851
+ const g = toThunderCondition(binding && subject ? rebind(a.guard, binding[1], subject) : a.guard, inputs);
852
+ if (!g) return { unread: [{ line: a.line, text: `${a.pattern} if ${a.guard}`, reason: 'This case guard uses something besides comparisons and and/or/not.' }] };
853
+ when = when && !binding ? `(${when}) and (${g})` : g;
854
+ }
855
+ if (!when) return { unread: [{ line: a.line, text: String(a.pattern).slice(0, 80), reason: 'This case pattern is not a value, range, or comparison the reader recognizes.' }] };
856
+ try { compileExpr(when, { inputs }); } catch { return { unread: [{ line: a.line, text: String(a.pattern), reason: 'This case pattern could not be read as a condition.' }] }; }
857
+ rules.push({ when: simplifyExpr(when), result, line: a.line });
858
+ }
859
+ return { rules, otherwise };
860
+ }
861
+
862
+ // ── Statement readers ───────────────────────────────────────────────────────────────────────
863
+
864
+ /** Split a brace-language body into top-level statements with their source line numbers. */
865
+ function splitStatements(body, baseLine) {
866
+ const src = stripCommentsKeepLayout(body);
867
+ const out = [];
868
+ let i = 0;
869
+ while (i < src.length) {
870
+ while (i < src.length && /[\s;]/.test(src[i])) i++;
871
+ if (i >= src.length) break;
872
+ const start = i;
873
+ let depth = 0;
874
+ for (; i < src.length; i++) {
875
+ const c = src[i];
876
+ if (c === '"' || c === '\'' || c === '`') { i = skipString(src, i); continue; }
877
+ if (c === '(' || c === '[') depth++;
878
+ else if (c === ')' || c === ']') depth--;
879
+ else if (c === '{') {
880
+ const close = matchClose(src, i);
881
+ if (close < 0) { i = src.length; break; }
882
+ i = close;
883
+ if (depth === 0) {
884
+ // An if/else chain continues past a closing brace.
885
+ const rest = src.slice(i + 1).match(/^\s*else\b/);
886
+ if (!rest) { i++; break; }
887
+ }
888
+ } else if (c === ';' && depth === 0) { i++; break; }
889
+ }
890
+ const text = src.slice(start, i).trim();
891
+ if (text) out.push({ text, line: baseLine + lineAt(src, start) - 1 });
892
+ }
893
+ return out;
894
+ }
895
+ const stripCommentsKeepLayout = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:])\/\/.*$/gm, '$1');
896
+
897
+ /** Read `if ... else ...` / `return ...` statements into rules. Returns { rules, otherwise, unread }. */
898
+ function readBraceStatements(stmts, language, inputs) {
899
+ const rules = [], unread = [], guards = [];
900
+ let otherwise = null;
901
+ const take = (cond, outcomeText, line) => {
902
+ const when = cond == null ? null : toThunderCondition(cond, inputs);
903
+ const result = toThunderOutcome(outcomeText);
904
+ if (cond != null && !when) { unread.push({ line, text: `if ${cond}`, reason: 'This condition uses something besides comparisons and and/or/not.' }); return false; }
905
+ if (!result) { unread.push({ line, text: outcomeText.trim(), reason: 'This answer is computed, not a fixed value.' }); return false; }
906
+ if (when == null) otherwise = { result, line }; else rules.push({ when, result, line });
907
+ return true;
908
+ };
909
+ const blockValue = (block) => {
910
+ // A block that only returns (or, in Rust/Go tail position, yields) one value.
911
+ const inner = block.trim().replace(/^\{|\}$/g, '').trim();
912
+ const m = inner.match(/^return\s+([\s\S]+?);?$/) || (language === 'rust' && !/;/.test(inner) ? [null, inner] : null);
913
+ return m && !/\n\s*\S/.test(m[1].trim()) ? m[1].trim() : null;
914
+ };
915
+ for (const st of stmts) {
916
+ const t = st.text;
917
+ let m;
918
+ if (/^if\b/.test(t)) {
919
+ // A guard: an `if` with no else whose branch exits without a fixed answer.
920
+ const head = splitIf(t, language);
921
+ if (head && !/^else\b/.test(head.remaining)) {
922
+ const single = head.branch.replace(/^return\s+/, '').replace(/;\s*$/, '');
923
+ // Error values (ErrNotFound, NotFoundError, BadRequestException) are failures, not answers.
924
+ const looksLikeError = /^(Err[A-Z]\w*|\w*(Error|Exception))$/.test(lastSeg(single));
925
+ const isFixedReturn = /^return\s/.test(head.branch) && toThunderOutcome(single) && !looksLikeError && (language !== 'go' || !single.includes(','));
926
+ if (!isFixedReturn) {
927
+ const g = makeGuard(head.cond, head.branch, language, inputs, st.line);
928
+ if (g === 'skip') continue;
929
+ if (g) { guards.push(g); continue; }
930
+ }
931
+ }
932
+ // Walk the chain: if C B (else if C B)* (else B)?
933
+ let rest = t;
934
+ let ok = true;
935
+ while (rest) {
936
+ const head = rest.match(/^(?:else\s+)?if\b\s*/);
937
+ if (!head) break;
938
+ rest = rest.slice(head[0].length);
939
+ let cond, after;
940
+ if (rest[0] === '(' && (language !== 'go' && language !== 'rust' || true)) {
941
+ const close = matchClose(rest, 0);
942
+ const tail = rest.slice(close + 1).trimStart();
943
+ if (language === 'go' || language === 'rust') {
944
+ // Go/Rust may wrap only part of the condition in parentheses: if (a) && b {
945
+ const brace = findTopBrace(rest);
946
+ cond = rest.slice(0, brace).trim(); after = rest.slice(brace);
947
+ } else { cond = rest.slice(1, close); after = tail; }
948
+ } else {
949
+ const brace = findTopBrace(rest);
950
+ if (brace < 0) { ok = false; break; }
951
+ cond = rest.slice(0, brace).trim(); after = rest.slice(brace);
952
+ }
953
+ let value, remaining;
954
+ if (after[0] === '{') {
955
+ const bc = matchClose(after, 0);
956
+ value = blockValue(after.slice(0, bc + 1));
957
+ remaining = after.slice(bc + 1).trim();
958
+ } else {
959
+ const semi = after.indexOf(';');
960
+ const single = (semi < 0 ? after : after.slice(0, semi)).trim();
961
+ value = single.startsWith('return ') ? single.slice(7) : null;
962
+ remaining = (semi < 0 ? '' : after.slice(semi + 1)).trim();
963
+ }
964
+ if (value == null) { unread.push({ line: st.line, text: `if ${cond.trim()}`, reason: 'This branch does more than choose an answer.' }); ok = false; break; }
965
+ if (!take(cond, value, st.line)) { ok = false; break; }
966
+ if (/^else\s+if\b/.test(remaining)) { rest = remaining; continue; }
967
+ if (/^else\b/.test(remaining)) {
968
+ const elseBody = remaining.replace(/^else\s*/, '');
969
+ const v = elseBody.startsWith('{') ? blockValue(elseBody) : (elseBody.startsWith('return ') ? elseBody.slice(7).replace(/;$/, '') : null);
970
+ if (v == null) { unread.push({ line: st.line, text: 'else', reason: 'The fallback branch does more than choose an answer.' }); ok = false; }
971
+ else take(null, v, st.line);
972
+ }
973
+ rest = '';
974
+ }
975
+ if (!ok) continue;
976
+ continue;
977
+ }
978
+ // Kotlin preconditions: require(cond) { "msg" } fails unless cond holds.
979
+ if (language === 'kotlin' && (m = t.match(/^(require|check|requireNotNull|checkNotNull)\s*\(/))) {
980
+ const open = t.indexOf('(');
981
+ const close = matchClose(t, open);
982
+ const cond = t.slice(open + 1, close);
983
+ const name = m[1].startsWith('require') ? 'IllegalArgumentException' : 'IllegalStateException';
984
+ const detail = firstString(t.slice(close + 1).replace(/^\s*\{/, '')) || null;
985
+ const when = /NotNull$/.test(m[1]) ? null : toThunderCondition(`!(${cond})`, inputs);
986
+ const effect = { kind: 'fails', name, detail };
987
+ const condSaid = when ? sayCondition(when) : `\`${/NotNull$/.test(m[1]) ? `${cond.trim()} is null` : `not (${cond.trim()})`}\``;
988
+ guards.push({ when, code: `${m[1]}(${cond.trim()})`, effect, line: st.line, readable: !!when, says: sayGuard(effect, condSaid) });
989
+ continue;
990
+ }
991
+ if (language === 'php' && (m = t.match(/^abort_(if|unless)\s*\(([\s\S]*)\)\s*;?$/))) {
992
+ const args = splitTop(m[2], ',').map((x) => x.trim());
993
+ if (args.length >= 2 && /^\d{3}$/.test(args[1])) {
994
+ const cond = m[1] === 'if' ? args[0] : `!(${args[0]})`;
995
+ const when = toThunderCondition(cond, inputs);
996
+ const effect = { kind: 'responds', name: args[1] };
997
+ guards.push({ when, code: `abort_${m[1]}(${args[0]})`, effect, line: st.line, readable: !!when, says: sayGuard(effect, when ? sayCondition(when) : `\`${cond}\``) });
998
+ continue;
999
+ }
1000
+ }
1001
+ // switch / match, as a statement or as the returned value.
1002
+ {
1003
+ const isLast = st === stmts[stmts.length - 1];
1004
+ const val = (t.match(/^return\s+([\s\S]+?);?$/) || [])[1];
1005
+ const candidate = /^(switch|match|when)\b/.test(t) && (language === 'kotlin' || !/^when\b/.test(t)) ? t : val && /^(switch\b|match\b|when\b|[\w.]+\s+switch\s*\{)/.test(val) && (language === 'kotlin' || !/^when\b/.test(val)) ? val : null;
1006
+ const sw = candidate && (candidate === t ? !(language === 'rust' && !isLast && /^match/.test(t) && false) : true) ? readSwitch(candidate, language, inputs, st.line) : null;
1007
+ if (sw) {
1008
+ if (sw.unread) { unread.push(...sw.unread); continue; }
1009
+ rules.push(...sw.rules);
1010
+ if (sw.otherwise) otherwise = sw.otherwise;
1011
+ continue;
1012
+ }
1013
+ }
1014
+ const ret = t.match(/^return\s+([\s\S]+?);?$/) || (language === 'rust' && st === stmts[stmts.length - 1] && !/;\s*$/.test(t) ? [null, t] : null);
1015
+ if (ret) {
1016
+ if (language === 'kotlin' && readKotlinIf(ret[1], inputs, rules, unread, st.line, (o) => { otherwise = o; })) continue;
1017
+ if (readTernary(ret[1], inputs, rules, unread, st.line, (o) => { otherwise = o; })) continue;
1018
+ take(null, ret[1], st.line);
1019
+ continue;
1020
+ }
1021
+ unread.push({ line: st.line, text: t.split('\n')[0].slice(0, 120), reason: 'This statement does work besides choosing an answer.' });
1022
+ }
1023
+ return { rules, otherwise, unread, guards };
1024
+ }
1025
+
1026
+ function findTopBrace(s) {
1027
+ let depth = 0;
1028
+ for (let i = 0; i < s.length; i++) {
1029
+ const c = s[i];
1030
+ if (c === '"' || c === '\'') { i = skipString(s, i); continue; }
1031
+ if (c === '(' || c === '[') depth++;
1032
+ else if (c === ')' || c === ']') depth--;
1033
+ else if (c === '{' && depth === 0) return i;
1034
+ }
1035
+ return -1;
1036
+ }
1037
+
1038
+ /** `cond ? A : (cond2 ? B : C)` -> rules. Returns false when the text is not a ternary chain. */
1039
+ function readTernary(text, inputs, rules, unread, line, setOtherwise) {
1040
+ let s = text.trim().replace(/;$/, '');
1041
+ if (!/\?/.test(s)) return false;
1042
+ const local = [];
1043
+ while (true) {
1044
+ while (s.startsWith('(') && matchClose(s, 0) === s.length - 1) s = s.slice(1, -1).trim();
1045
+ const q = topLevelIndex(s, '?');
1046
+ if (q < 0) break;
1047
+ const c = topLevelIndex(s, ':', q + 1);
1048
+ if (c < 0) return false;
1049
+ const when = toThunderCondition(s.slice(0, q), inputs);
1050
+ const result = toThunderOutcome(s.slice(q + 1, c));
1051
+ if (!when || !result) { unread.push({ line, text: s.slice(0, 120), reason: 'This choice uses a condition or answer that is not a fixed value.' }); return true; }
1052
+ local.push({ when, result, line });
1053
+ s = s.slice(c + 1).trim();
1054
+ }
1055
+ const fallback = toThunderOutcome(s);
1056
+ if (!fallback) { unread.push({ line, text: s.slice(0, 120), reason: 'The fallback answer is computed, not a fixed value.' }); return true; }
1057
+ rules.push(...local);
1058
+ setOtherwise({ result: fallback, line });
1059
+ return true;
1060
+ }
1061
+ function topLevelIndex(s, ch, from = 0) {
1062
+ let depth = 0;
1063
+ for (let i = from; i < s.length; i++) {
1064
+ const c = s[i];
1065
+ if (c === '"' || c === '\'') { i = skipString(s, i); continue; }
1066
+ if (c === '(' || c === '[') depth++;
1067
+ else if (c === ')' || c === ']') depth--;
1068
+ else if (c === ':' && s[i + 1] === ':') { i++; continue; }
1069
+ else if (c === ch && depth === 0) return i;
1070
+ }
1071
+ return -1;
1072
+ }
1073
+
1074
+ function readPythonBody(body, inputs) {
1075
+ const rules = [], unread = [], guards = [];
1076
+ let otherwise = null;
1077
+ const base = body[0]?.indent ?? 0;
1078
+ for (let i = 0; i < body.length; i++) {
1079
+ const { text, line, indent } = body[i];
1080
+ if (indent !== base) continue;
1081
+ let m;
1082
+ if ((m = text.match(/^match\s+(.+?):\s*$/))) {
1083
+ const subject = toThunderCondition(m[1], inputs);
1084
+ const block = [];
1085
+ for (let k = i + 1; k < body.length && body[k].indent > base; k++) block.push(body[k]);
1086
+ i += block.length;
1087
+ const caseIndent = block[0]?.indent;
1088
+ const arms = [];
1089
+ for (let k = 0; k < block.length; k++) {
1090
+ const c = block[k];
1091
+ if (c.indent !== caseIndent) continue;
1092
+ const cm = c.text.match(/^case\s+(.+?)(?:\s+if\s+(.+?))?:\s*(.*)$/);
1093
+ if (!cm) { arms.length = 0; break; }
1094
+ const inner = block.slice(k + 1).filter((x, n, arr) => x.indent > caseIndent && arr.slice(0, n).every((y) => y.indent > caseIndent));
1095
+ const valueLine = cm[3].trim() || (inner.length === 1 ? inner[0].text : '');
1096
+ const r = valueLine.match(/^return\s+(.+)$/);
1097
+ arms.push({ pattern: cm[1].trim(), guard: cm[2]?.trim() || null, value: r ? r[1] : null, line: c.line });
1098
+ }
1099
+ let ok = !!subject && !/\s/.test(subject) && arms.length > 0;
1100
+ const local = [];
1101
+ let fallback = null;
1102
+ for (const a of ok ? arms : []) {
1103
+ const result = a.value == null ? null : toThunderOutcome(a.value);
1104
+ if (!result) { ok = false; break; }
1105
+ if (a.pattern === '_' && !a.guard) { fallback = { result, line: a.line }; break; }
1106
+ const binding = a.pattern.match(/^([a-z_]\w*)$/) && a.pattern !== '_' ? a.pattern : null;
1107
+ let when = a.pattern === '_' || binding ? null : patternCondition(a.pattern, subject, inputs, 'python');
1108
+ if (a.guard) {
1109
+ const g = toThunderCondition(binding ? rebind(a.guard, binding, subject) : a.guard, inputs);
1110
+ if (!g) { ok = false; break; }
1111
+ when = when ? `(${when}) and (${g})` : g;
1112
+ }
1113
+ if (!when) { ok = false; break; }
1114
+ local.push({ when: simplifyExpr(when), result, line: a.line });
1115
+ }
1116
+ if (!ok) { unread.push({ line, text: text.slice(0, 120), reason: 'This match has a case that does more than give a fixed answer.' }); continue; }
1117
+ rules.push(...local);
1118
+ if (fallback) otherwise = fallback;
1119
+ continue;
1120
+ }
1121
+ if ((m = text.match(/^(?:if|elif)\s+(.+?):\s*(.*)$/))) {
1122
+ const inline = m[2].trim();
1123
+ const next = body[i + 1];
1124
+ const valueText = inline ? inline : next && next.indent > base ? next.text : '';
1125
+ const deeper = body.slice(i + 1).filter((b, k, arr) => b.indent > base && arr.slice(0, k).every((x) => x.indent > base));
1126
+ const r = valueText.match(/^return\s+(.+)$/);
1127
+ if (/^if\s/.test(text) && (inline || deeper.length === 1) && !body.slice(i + 1).find((b) => b.indent === base && /^(elif|else)\b/.test(b.text) && b.line > line && body.slice(i + 1, body.indexOf(b)).every((x) => x.indent > base)) && !(r && toThunderOutcome(r[1]))) {
1128
+ const g = makeGuard(m[1], valueText, 'python', inputs, line);
1129
+ if (g && g !== 'skip') { guards.push(g); continue; }
1130
+ }
1131
+ if (!r || (!inline && deeper.length > 1)) { unread.push({ line, text: text.slice(0, 120), reason: 'This branch does more than choose an answer.' }); continue; }
1132
+ const when = toThunderCondition(m[1], inputs), result = toThunderOutcome(r[1]);
1133
+ if (!when) { unread.push({ line, text: `if ${m[1]}`, reason: 'This condition uses something besides comparisons and and/or/not.' }); continue; }
1134
+ if (!result) { unread.push({ line, text: r[1], reason: 'This answer is computed, not a fixed value.' }); continue; }
1135
+ rules.push({ when, result, line });
1136
+ continue;
1137
+ }
1138
+ if ((m = text.match(/^else:\s*(.*)$/))) {
1139
+ const v = (m[1].trim() || body[i + 1]?.text || '').match(/^return\s+(.+)$/);
1140
+ const result = v && toThunderOutcome(v[1]);
1141
+ if (result) otherwise = { result, line }; else unread.push({ line, text: 'else', reason: 'The fallback branch does more than choose an answer.' });
1142
+ continue;
1143
+ }
1144
+ if ((m = text.match(/^return\s+(.+)$/))) {
1145
+ const tern = m[1].match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/);
1146
+ if (tern) {
1147
+ const when = toThunderCondition(tern[2], inputs), a = toThunderOutcome(tern[1]), b = toThunderOutcome(tern[3]);
1148
+ if (when && a && b) { rules.push({ when, result: a, line }); otherwise = { result: b, line }; }
1149
+ else unread.push({ line, text: m[1].slice(0, 120), reason: 'This choice uses a condition or answer that is not a fixed value.' });
1150
+ continue;
1151
+ }
1152
+ const result = toThunderOutcome(m[1]);
1153
+ if (result) otherwise = { result, line }; else unread.push({ line, text: m[1].slice(0, 120), reason: 'This answer is computed, not a fixed value.' });
1154
+ continue;
1155
+ }
1156
+ if (/^("""|''')/.test(text)) continue;
1157
+ unread.push({ line, text: text.slice(0, 120), reason: 'This statement does work besides choosing an answer.' });
1158
+ }
1159
+ return { rules, otherwise, unread, guards };
1160
+ }
1161
+
1162
+ // ── Ruby: `def ... end`, implicit returns, modifier if/unless, case/when ───────────────────
1163
+
1164
+ const RB_OPENER = /^(if|unless|while|until|case|begin|for|def|class|module)\b/;
1165
+ const rbCodeOnly = (l) => l.replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""').replace(/(^|\s)#.*$/, '$1');
1166
+ /** A Ruby line without its trailing # comment (strings kept as written). */
1167
+ function rbNoComment(l) {
1168
+ for (let i = 0; i < l.length; i++) {
1169
+ const c = l[i];
1170
+ if (c === '"' || c === '\'') { i = skipString(l, i); continue; }
1171
+ if (c === '#' && l[i + 1] !== '{' && (i === 0 || /\s/.test(l[i - 1]))) return l.slice(0, i);
1172
+ }
1173
+ return l;
1174
+ }
1175
+
1176
+ /** How much a Ruby line opens (+) or closes (-) blocks. */
1177
+ function rbDelta(raw) {
1178
+ const l = rbCodeOnly(raw).trim();
1179
+ if (!l) return 0;
1180
+ let d = 0;
1181
+ if (RB_OPENER.test(l) && !/^def\s+[\w.?!]+(\([^)]*\))?\s*=/.test(l)) d++;
1182
+ if (/\bdo\s*(\|[^|]*\|)?\s*$/.test(l)) d++;
1183
+ if (/[=(,]\s*(if|unless|case|begin)\b/.test(l) && !RB_OPENER.test(l)) d++;
1184
+ d -= (l.match(/(^|[^.\w])end\b(?![?!:])/g) || []).length;
1185
+ return d;
1186
+ }
1187
+
1188
+ function findRubyFunctions(src) {
1189
+ const lines = src.split('\n');
1190
+ const fns = [];
1191
+ const collect = (from, headIndent) => {
1192
+ const body = [];
1193
+ let depth = 0;
1194
+ for (let j = from; j < lines.length; j++) {
1195
+ const t = lines[j];
1196
+ const code = rbCodeOnly(t).trim();
1197
+ if (!code) continue;
1198
+ if (depth === 0 && /^end\b/.test(code)) return body;
1199
+ body.push({ text: t.trim(), line: j + 1, depth });
1200
+ depth += rbDelta(t);
1201
+ if (depth < 0) return body;
1202
+ }
1203
+ return body;
1204
+ };
1205
+ lines.forEach((l, i) => {
1206
+ let m;
1207
+ if ((m = l.match(/^(\s*)def\s+(?:self\.)?([\w]+[?!=]?)\s*(?:\((.*?)\)|\s+([^=#][^#]*?))?\s*(=\s*(.+))?\s*$/))) {
1208
+ const params = parseParams(m[3] ?? m[4] ?? '', 'ruby');
1209
+ const body = m[5] ? [{ text: m[6].trim(), line: i + 1, depth: 0 }] : collect(i + 1, m[1].length);
1210
+ fns.push({ name: m[2], line: i + 1, params, returns: null, rbBody: body });
1211
+ return;
1212
+ }
1213
+ if ((m = l.match(/^\s*(get|post|put|patch|delete)\s+['"]([^'"]+)['"]\s+do\b/))) { // Sinatra
1214
+ const method = m[1].toUpperCase();
1215
+ fns.push({ name: `${method} ${m[2]}`, line: i + 1, params: [], returns: null, rbBody: collect(i + 1), route: { method, path: m[2] } });
1216
+ }
1217
+ });
1218
+ return fns;
1219
+ }
1220
+
1221
+ const RB_PREDICATE_NOT_FIELD = /^(nil|empty|zero|blank|present|any|none|all|include|key|is_a|kind_of|respond_to|start_with|end_with|between|positive|negative|even|odd)$/;
1222
+
1223
+ /** Ruby expression -> the shape the shared converters read: @x -> x, :sym -> "sym", user.admin? -> user.admin. */
1224
+ function rbExpr(text) {
1225
+ let bad = false;
1226
+ // Ruby's === is "matches" (a pattern, a class, a range), not equality: never read it as ==.
1227
+ // And `<` / `<=` beside a class name asks "is a subclass of", not "is less than".
1228
+ const bare = String(text).replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
1229
+ if (/===/.test(bare) || /(<=?|>=?)\s*[A-Z][a-z]\w*(?!\w*\s*[(.])/.test(bare.replace(/<=>/g, '')) || /\b[A-Z][a-z]\w*\s*(<=?|>=?)/.test(bare)) return null;
1230
+ const out = mapCode(String(text), (code) => code
1231
+ .replace(/@(?=[A-Za-z_])/g, '')
1232
+ .replace(/(^|[\s(,=!<>[])::?([A-Za-z_]\w*)\b(?!:)/g, (all, pre, name) => (all.includes('::') ? all : `${pre}"${name}"`))
1233
+ .replace(/\.(\w+)\?/g, (all, name) => { if (RB_PREDICATE_NOT_FIELD.test(name)) bad = true; return `.${name}`; })
1234
+ .replace(/\bunless\b/g, 'if not'));
1235
+ return bad ? null : out;
1236
+ }
1237
+ const rbCond = (text, inputs, negate = false) => { const e = rbExpr(text); return e == null ? null : toThunderCondition(negate ? `!(${e})` : e, inputs); };
1238
+ const rbOutcome = (text) => { const e = rbExpr(String(text).replace(/^return\s+/, '')); return e == null ? null : toThunderOutcome(e); };
1239
+
1240
+ /** Ruby ranges as the reader's range forms: a..b is inclusive (a..=b), a...b excludes b (a..b). */
1241
+ function rbRange(p) {
1242
+ return p.split(/,(?![^(]*\))/).map((x) => x.trim().replace(/^\(?(-?\d+(?:\.\d+)?)\s*(\.\.\.?)\s*(-?\d+(?:\.\d+)?)\)?$/,
1243
+ (_, a, dots, b) => (dots === '...' ? `${a}..${b}` : `${a}..=${b}`))).join(', ');
1244
+ }
1245
+
1246
+ function readRubyBody(body, inputs) {
1247
+ const rules = [], unread = [], guards = [];
1248
+ let otherwise = null;
1249
+ let top = body.map((b, k) => ({ ...b, k })).filter((b) => b.depth === 0);
1250
+ // A method-level `rescue` or `ensure` starts error handling; the answer is what comes before it.
1251
+ const rescueAt = top.findIndex((b) => /^(rescue|ensure)\b/.test(rbNoComment(b.text).trim()));
1252
+ if (rescueAt >= 0) {
1253
+ unread.push({ line: top[rescueAt].line, text: rbNoComment(top[rescueAt].text).trim().slice(0, 120), reason: 'Error handling (rescue) is not read as rules.' });
1254
+ top = top.slice(0, rescueAt);
1255
+ }
1256
+ // The lines inside a block, without the block's own closing `end`.
1257
+ const blockOf = (start) => {
1258
+ const out = [];
1259
+ for (let k = start + 1; k < body.length && body[k].depth > 0; k++) if (!(body[k].depth === 1 && /^end\b/.test(rbNoComment(body[k].text).trim()))) out.push(body[k]);
1260
+ return out;
1261
+ };
1262
+ const sole = (lines) => (lines.length === 1 ? lines[0].text : null);
1263
+ top.forEach((st, n) => {
1264
+ const t = rbNoComment(st.text).trim();
1265
+ const isLast = n === top.length - 1;
1266
+ let m;
1267
+ // Modifier form: `return X if cond`, `raise Error, "msg" unless cond`.
1268
+ if ((m = t.match(/^(return\b.*?|raise\b.*?|fail\b.*?|head\b.*?|halt\b.*?|render\b.*?)\s+(if|unless)\s+(.+)$/))) {
1269
+ const when = rbCond(m[3], inputs, m[2] === 'unless');
1270
+ const stmt = m[1].trim();
1271
+ const fixed = /^return\s+\S/.test(stmt) ? rbOutcome(stmt) : null;
1272
+ if (fixed) {
1273
+ if (!when) unread.push({ line: st.line, text: t.slice(0, 120), reason: 'This condition uses something besides comparisons and and/or/not.' });
1274
+ else rules.push({ when, result: fixed, line: st.line });
1275
+ return;
1276
+ }
1277
+ const effect = terminatorEffect(rbExpr(stmt) ?? stmt, 'ruby');
1278
+ if (effect) {
1279
+ const code = (m[2] === 'unless' ? 'unless ' : '') + m[3].trim();
1280
+ guards.push({ when, code, effect, line: st.line, readable: !!when, says: sayGuard(effect, when ? sayCondition(when) : `\`${code}\``) });
1281
+ return;
1282
+ }
1283
+ }
1284
+ // if / unless ... elsif ... else ... end
1285
+ if ((m = t.match(/^(if|unless)\s+(.+?)(?:\s+then)?$/))) {
1286
+ const block = blockOf(st.k);
1287
+ const parts = [];
1288
+ let cur = { cond: m[2], negate: m[1] === 'unless', lines: [], line: st.line };
1289
+ for (const b of block) {
1290
+ const bt = rbNoComment(b.text).trim();
1291
+ let e;
1292
+ if (b.depth === 1 && (e = bt.match(/^elsif\s+(.+?)(?:\s+then)?$/))) { parts.push(cur); cur = { cond: e[1], negate: false, lines: [], line: b.line }; continue; }
1293
+ if (b.depth === 1 && /^else$/.test(bt)) { parts.push(cur); cur = { cond: null, lines: [], line: b.line }; continue; }
1294
+ cur.lines.push({ ...b, text: bt });
1295
+ }
1296
+ parts.push(cur);
1297
+ const hasElse = parts.some((p) => p.cond == null);
1298
+ // A guard: one branch, no else, that exits without a fixed answer.
1299
+ if (parts.length === 1 && !hasElse) {
1300
+ const only = sole(parts[0].lines);
1301
+ const fixed = only && /^return\s/.test(only) ? rbOutcome(only) : null;
1302
+ if (only && !fixed) {
1303
+ const effect = terminatorEffect(rbExpr(only) ?? only, 'ruby');
1304
+ if (effect && effect.kind !== 'returns-computed') {
1305
+ const when = rbCond(parts[0].cond, inputs, parts[0].negate);
1306
+ const code = (parts[0].negate ? 'unless ' : '') + parts[0].cond;
1307
+ guards.push({ when, code, effect, line: st.line, readable: !!when, says: sayGuard(effect, when ? sayCondition(when) : `\`${code}\``) });
1308
+ return;
1309
+ }
1310
+ }
1311
+ }
1312
+ const local = [];
1313
+ let fallback = null;
1314
+ for (const p of parts) {
1315
+ const v = sole(p.lines);
1316
+ // A bare value only answers when the whole `if` is the method's last expression.
1317
+ const valueText = v && (/^return\s/.test(v) || isLast) ? v : null;
1318
+ const result = valueText ? rbOutcome(valueText) : null;
1319
+ if (!result) { unread.push({ line: p.line, text: p.cond ? `${p.negate ? 'unless' : 'if'} ${p.cond}` : 'else', reason: 'This branch does more than choose an answer.' }); return; }
1320
+ if (p.cond == null) { fallback = { result, line: p.line }; continue; }
1321
+ const when = rbCond(p.cond, inputs, p.negate);
1322
+ if (!when) { unread.push({ line: p.line, text: `if ${p.cond}`, reason: 'This condition uses something besides comparisons and and/or/not.' }); return; }
1323
+ local.push({ when, result, line: p.line });
1324
+ }
1325
+ rules.push(...local);
1326
+ if (fallback) otherwise = fallback;
1327
+ return;
1328
+ }
1329
+ // case subject / when values [then answer] / else / end
1330
+ if ((m = t.match(/^(?:return\s+)?case(?:\s+(.+))?$/))) {
1331
+ const subject = m[1] ? rbCond(m[1], inputs) : null;
1332
+ if (m[1] && (!subject || /\s/.test(subject))) { unread.push({ line: st.line, text: t.slice(0, 120), reason: 'This case compares something other than an input or field.' }); return; }
1333
+ const block = blockOf(st.k);
1334
+ const arms = [];
1335
+ let cur = null;
1336
+ for (const b of block) {
1337
+ const bt = rbNoComment(b.text).trim();
1338
+ let w;
1339
+ if (b.depth === 1 && (w = bt.match(/^when\s+(.+?)(?:\s+then\s+(.+))?$/))) { cur = { pattern: w[1], value: w[2] ?? null, lines: [], line: b.line }; arms.push(cur); continue; }
1340
+ if (b.depth === 1 && (w = bt.match(/^else(?:\s+(.+))?$/))) { cur = { pattern: null, value: w[1] ?? null, lines: [], line: b.line }; arms.push(cur); continue; }
1341
+ if (cur) cur.lines.push(bt);
1342
+ }
1343
+ const answerable = isLast || /^return\s/.test(t);
1344
+ const ready = arms.map((a) => {
1345
+ const v = a.value ?? (a.lines.length === 1 ? a.lines[0] : null);
1346
+ const ok = v && (answerable || /^return\s/.test(v));
1347
+ const conv = ok ? rbExpr(v.replace(/^return\s+/, '')) : null;
1348
+ // `when SomeClass` asks "is it a kind of SomeClass?" (===), not equality: not read.
1349
+ const typeCheck = m[1] && a.pattern != null && a.pattern.split(',').some((x) => /^[A-Z][\w:]*$/.test(x.trim()) && !/^[A-Z][A-Z0-9_]*$/.test(x.trim().split('::').pop()));
1350
+ const pattern = a.pattern == null ? null : typeCheck ? null : m[1] ? rbExpr(rbRange(a.pattern)) : rbExpr(a.pattern);
1351
+ return { pattern: a.pattern != null && pattern == null ? '\u0000' : pattern, guard: null, value: conv, line: a.line };
1352
+ });
1353
+ const sw = arms.length ? armsToRules(ready, subject, inputs, 'ruby') : { unread: [{ line: st.line, text: t, reason: 'This case has no when branches the reader recognizes.' }] };
1354
+ if (sw.unread) { unread.push(...sw.unread); return; }
1355
+ rules.push(...sw.rules);
1356
+ if (sw.otherwise) otherwise = sw.otherwise;
1357
+ return;
1358
+ }
1359
+ // The last expression is the answer; `return X` answers anywhere.
1360
+ if (/^return\s/.test(t) || isLast) {
1361
+ const v = t.replace(/^return\s+/, '');
1362
+ const e = rbExpr(v);
1363
+ if (e && readTernary(e, inputs, rules, unread, st.line, (o) => { otherwise = o; })) return;
1364
+ const result = rbOutcome(v);
1365
+ if (result) { otherwise = { result, line: st.line }; return; }
1366
+ unread.push({ line: st.line, text: t.slice(0, 120), reason: 'This answer is computed, not a fixed value.' });
1367
+ return;
1368
+ }
1369
+ unread.push({ line: st.line, text: t.slice(0, 120), reason: 'This statement does work besides choosing an answer.' });
1370
+ });
1371
+ return { rules, otherwise, unread, guards };
1372
+ }
1373
+
1374
+ // ── Plain English ───────────────────────────────────────────────────────────────────────────
1375
+
1376
+ const OP_WORDS = { '>=': 'is at least', '>': 'is more than', '<=': 'is at most', '<': 'is less than', '==': 'is', '!=': 'is not' };
1377
+
1378
+ /** Read a ThunderLang condition aloud: `amount <= 100 and withinWindow` -> "amount is at most 100 and withinWindow". */
1379
+ const NOT_OP_WORDS = { '>=': 'is less than', '>': 'is at most', '<=': 'is more than', '<': 'is at least', '==': 'is not', '!=': 'is' };
1380
+
1381
+ export function sayCondition(cond) {
1382
+ return cond
1383
+ // `not x > 0` negates the whole comparison in ThunderLang; say it the way a person would.
1384
+ .replace(/\bnot\s+([A-Za-z_][\w.]*)\s*(>=|<=|==|!=|>|<)\s*("[^"]*"|-?[\w.]+)/g, (_, a, op, b) => `${a} ${NOT_OP_WORDS[op]} ${b}`)
1385
+ .replace(/\s*(>=|<=|==|!=|>|<)\s*/g, (_, op) => ` ${OP_WORDS[op]} `)
1386
+ .replace(/\bnot\s+/g, 'not ')
1387
+ .replace(/\s+/g, ' ')
1388
+ .trim();
1389
+ }
1390
+
1391
+ function sayDecision(rules, otherwise) {
1392
+ const parts = rules.map((r, i) => `${i === 0 ? 'If' : 'Otherwise, if'} ${sayCondition(r.when)}, the answer is ${r.result}.`);
1393
+ if (otherwise) parts.push(rules.length ? `Otherwise, the answer is ${otherwise.result}.` : `The answer is always ${otherwise.result}.`);
1394
+ return parts.join(' ');
1395
+ }
1396
+
1397
+ function decisionSource(name, inputs, rules, otherwise) {
1398
+ const L = [`decision ${name}`, ' inputs'];
1399
+ for (const p of inputs) L.push(` ${p.name}${['number', 'boolean', 'string'].includes(p.type) ? `: ${p.type}` : ''}`);
1400
+ rules.forEach((r, i) => L.push(` rule rule_${i + 1}`, ` when ${r.when}`, ` return ${r.result}`));
1401
+ if (otherwise) L.push(' default', ` return ${otherwise.result}`);
1402
+ return L.join('\n');
1403
+ }
1404
+
1405
+ // ── The reading ─────────────────────────────────────────────────────────────────────────────
1406
+
1407
+ /**
1408
+ * Read source code into a searchable list of items: each function, the decision rules it makes
1409
+ * (as ThunderLang and plain English), the errors it raises, and the tests that exist.
1410
+ */
1411
+ export function readCode(source, { language, file = '' } = {}) {
1412
+ const src = String(source ?? '');
1413
+ if (src.length > 400000) throw new Error('Source is larger than 400 KB. Read one file or module at a time.');
1414
+ const lang = String(language || detectLanguage(src, file)).toLowerCase().replace(/^ts$/, 'typescript').replace(/^js$/, 'javascript').replace(/^py$/, 'python').replace(/^(cs|c#)$/, 'csharp').replace(/^rs$/, 'rust').replace(/^golang$/, 'go').replace(/^kts?$/, 'kotlin').replace(/^rb$/, 'ruby');
1415
+ if (!READ_LANGUAGES.includes(lang)) throw new Error(`Reading rules supports ${READ_LANGUAGES.join(', ')}. Got "${lang}".`);
1416
+ READING_RUST = lang === 'rust';
1417
+ // PHP is read after `$name` -> `name` and `->` -> `.`; every line stays on its line.
1418
+ const code = lang === 'php' ? normalizePhp(src) : src;
1419
+ const items = [];
1420
+ for (const fn of findFunctions(code, lang)) {
1421
+ const inputs = fn.params;
1422
+ const names = inputs.map((p) => p.name);
1423
+ const read = lang === 'python'
1424
+ ? readPythonBody(fn.pyBody, names)
1425
+ : lang === 'ruby'
1426
+ ? readRubyBody(fn.rbBody, names)
1427
+ : readBraceStatements(splitStatements(lang === 'kotlin' ? kotlinTerminate(fn.body) : fn.body, lineAt(code, fn.bodyStart)), lang, names);
1428
+ const isDecision = read.rules.length > 0 && !!read.otherwise;
1429
+ const guards = read.guards || [];
1430
+ // In a function that is not a pure decision, early fixed returns are still rules worth reading.
1431
+ if (!isDecision) {
1432
+ for (const r of read.rules) guards.push({ when: r.when, code: r.when, effect: { kind: 'returns', name: r.result }, line: r.line, readable: true, says: sayGuard({ kind: 'returns', name: r.result }, sayCondition(r.when)) });
1433
+ guards.sort((a, b) => a.line - b.line);
1434
+ }
1435
+ const guardNote = guards.length ? ` It checks ${guards.length} condition${guards.length === 1 ? '' : 's'} first: ${guards.map((g) => g.says.replace(/\.$/, '')).join('; ')}.` : '';
1436
+ const base = {
1437
+ id: `${fn.name}:${fn.line}`, name: fn.name, line: fn.line, inputs, returns: simpleType(fn.returns),
1438
+ ...(fn.route ? { route: fn.route } : {}),
1439
+ provenance: 'inferred-from-code',
1440
+ };
1441
+ if (isDecision) {
1442
+ items.push({
1443
+ ...base, kind: 'decision', status: read.unread.length ? 'partial' : 'read',
1444
+ rules: read.rules.map((r) => ({ ...r, says: sayCondition(r.when) })), otherwise: read.otherwise,
1445
+ says: (fn.route ? `Handles ${fn.route.method} ${fn.route.path}. ` : '') + sayDecision(read.rules, read.otherwise) + guardNote, guards,
1446
+ thunder: decisionSource(fn.name, inputs, read.rules, read.otherwise),
1447
+ unread: read.unread,
1448
+ });
1449
+ } else {
1450
+ items.push({
1451
+ ...base, kind: 'function', status: 'signature-only',
1452
+ says: fn.route ? `Handles ${fn.route.method} ${fn.route.path || '(this controller\'s path)'}.${guardNote}` : `${fn.name} takes ${inputs.length ? inputs.map((p) => p.type && !/[<>\[\]]/.test(p.type) ? `${p.name} (${p.type})` : p.name).join(', ') : 'no inputs'}${fn.returns ? ` and returns ${simpleType(fn.returns)}` : ''}. ${guards.length ? '' : ' Its body does more than choose between fixed answers, so no rules are shown.'}${guardNote}`,
1453
+ guards, unread: read.unread,
1454
+ });
1455
+ }
1456
+ }
1457
+ // Errors and tests come from the existing lift adapters (signature-level facts).
1458
+ const facts = extractFacts(src, lang, file || undefined);
1459
+ for (const e of facts?.errors || []) items.push({ id: `error:${e.name}:${e.line}`, kind: 'error', name: e.name, line: e.line, status: 'read', says: /\s/.test(e.name) ? `Can fail with the error "${e.name}".` : `Raises ${e.name}.`, provenance: 'inferred-from-code' });
1460
+ for (const t of facts?.tests || []) items.push({ id: `test:${t.name}:${t.line}`, kind: 'test', name: t.name, line: t.line, status: 'read', says: `A test named "${t.name}".`, provenance: 'inferred-from-code' });
1461
+ items.sort((a, b) => a.line - b.line);
1462
+ const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
1463
+ for (const it of items) { counts[it.kind]++; if (it.status === 'partial') counts.partial++; if (it.guards?.length) counts.guarded++; if (it.route) counts.route++; }
1464
+ return {
1465
+ schema: READ_SCHEMA, language: lang, detected: !language, items, counts,
1466
+ limitations: [
1467
+ 'Inferred from code by pattern, not by running it. Confirm a reading before relying on it.',
1468
+ 'Rules are shown only for functions that choose between fixed answers; other logic is listed as not read.',
1469
+ ],
1470
+ };
1471
+ }
1472
+
1473
+ /** Filter a reading by free text and facets. Text matches names, inputs, conditions, answers, and plain-English text. */
1474
+ export function searchReading(reading, { query = '', kinds = [], status = [] } = {}) {
1475
+ const q = String(query).trim().toLowerCase();
1476
+ const terms = q ? q.split(/\s+/) : [];
1477
+ return reading.items.filter((it) => {
1478
+ if (kinds.length && !kinds.includes(it.kind) && !(kinds.includes('guard') && it.guards?.length) && !(kinds.includes('route') && it.route)) return false;
1479
+ if (status.length && !status.includes(it.status)) return false;
1480
+ if (!terms.length) return true;
1481
+ const hay = [it.name, it.route && `${it.route.method} ${it.route.path}`, it.says, it.thunder, ...(it.guards || []).flatMap((g) => [g.code, g.effect.name, g.says]), ...(it.inputs || []).map((p) => `${p.name} ${p.type ?? ''}`), ...(it.rules || []).flatMap((r) => [r.when, r.result, r.says]), it.otherwise?.result]
1482
+ .filter(Boolean).join(' ').toLowerCase();
1483
+ return terms.every((t) => hay.includes(t));
1484
+ });
1485
+ }