@skillstech/thunderlang 0.5.4 → 0.5.5

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 CHANGED
@@ -9,7 +9,7 @@
9
9
  // return cond ? X : Y (nested ternaries) Python: return X if cond else Y
10
10
  // Rust/Go tail forms: if cond { X } else { Y }, if cond { return X }
11
11
  // Conditions may use comparisons, &&/||/!, and/or/not, parentheses, literals, and inputs or fields.
12
- import { stepsFrom, braceStatements, indentStatements } from './steps.mjs';
12
+ import { stepsFrom, braceStatements, indentStatements, plainEnums } from './steps.mjs';
13
13
  import { compileExpr, simplifyExpr } from './expr.mjs';
14
14
  import { extractFacts, languageForFile } from './lift.mjs';
15
15
 
@@ -36,7 +36,25 @@ export function detectLanguage(source, file = '') {
36
36
 
37
37
  // ── Lexing helpers ──────────────────────────────────────────────────────────────────────────
38
38
 
39
- const lineAt = (src, idx) => src.slice(0, idx).split('\n').length;
39
+ // Line of a character offset. The line starts of the last few sources are kept, so each lookup is a binary search
40
+ // instead of counting every newline from the top (which made large files quadratic).
41
+ const lineStarts = new Map();
42
+ function startsOf(src) {
43
+ let starts = lineStarts.get(src);
44
+ if (!starts) {
45
+ starts = [0];
46
+ for (let i = src.indexOf('\n'); i >= 0; i = src.indexOf('\n', i + 1)) starts.push(i + 1);
47
+ if (lineStarts.size > 8) lineStarts.delete(lineStarts.keys().next().value);
48
+ lineStarts.set(src, starts);
49
+ }
50
+ return starts;
51
+ }
52
+ const lineAt = (src, idx) => {
53
+ const starts = startsOf(src);
54
+ let lo = 0, hi = starts.length - 1;
55
+ while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= idx) lo = mid; else hi = mid - 1; }
56
+ return lo + 1;
57
+ };
40
58
 
41
59
  /** Index of the bracket that closes the one at `open`, skipping strings and comments. */
42
60
  function matchClose(src, open) {
@@ -85,6 +103,7 @@ const stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:
85
103
  // ── Function discovery ──────────────────────────────────────────────────────────────────────
86
104
 
87
105
  function parseParams(raw, language) {
106
+ raw = String(raw).replace(/#\[[^\]]*\]\s*/g, '').replace(/\[\w+(?:\([^)]*\))?\]\s*/g, ''); // #[SensitiveParameter], [FromBody]
88
107
  const parts = [];
89
108
  let depth = 0, cur = '';
90
109
  for (const ch of raw) {
@@ -122,6 +141,33 @@ function parseParams(raw, language) {
122
141
  return out;
123
142
  }
124
143
 
144
+ /**
145
+ * A TypeScript signature head after ")": `: <type>` read with balanced <>, {}, (), [] (so `Promise<{ a: 1 }>` is whole),
146
+ * then the body marker (=>, { or ;). Returns a match-like array [whole, type, , , marker] or null when there is no
147
+ * ": type" (the regular pattern handles that).
148
+ */
149
+ function balancedReturnHead(after) {
150
+ const lead = after.match(/^\s*:/);
151
+ if (!lead) return null;
152
+ let i = lead[0].length, depth = 0;
153
+ for (; i < after.length; i++) {
154
+ const c = after[i];
155
+ if (c === '=' && after[i + 1] === '>') { if (depth === 0) break; i++; continue; } // => ends the type, or is a function type's arrow
156
+ if (c === '<' || c === '(' || c === '[') depth++;
157
+ else if (c === '>' || c === ')' || c === ']') depth--;
158
+ else if (c === '{') { if (depth === 0) break; depth++; }
159
+ else if (c === '}') depth--;
160
+ else if (c === ';' && depth === 0) break;
161
+ else if (c === '"' || c === "'" || c === '`') { const q = c; i++; while (i < after.length && after[i] !== q) i++; }
162
+ }
163
+ const type = after.slice(lead[0].length, i).trim();
164
+ const tail = after.slice(i).match(/^\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/);
165
+ if (!type || !tail) return null;
166
+ const whole = after.slice(0, i) + tail[0];
167
+ const m = [whole, type, undefined, undefined, tail[1]];
168
+ return m;
169
+ }
170
+
125
171
  function simpleType(t) {
126
172
  if (!t) return null;
127
173
  const s = String(t).trim().replace(/^&(mut\s+)?/, '');
@@ -136,13 +182,26 @@ function findFunctions(src, language) {
136
182
  const fns = [];
137
183
  if (language === 'python') {
138
184
  const lines = src.split('\n');
139
- lines.forEach((l, i) => {
140
- const m = l.match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\((.*)\)\s*(?:->\s*([^:]+))?:\s*(.*)$/);
141
- if (!m) return;
142
- const indent = m[1].length;
185
+ let decorators = [];
186
+ for (let i = 0; i < lines.length; i++) {
187
+ const l = lines[i];
188
+ // Decorators: `@router.get(` can run over several lines (FastAPI keyword arguments); keep each one whole.
189
+ if (/^\s*@/.test(l)) {
190
+ const { text, end } = pyBalanced(lines, i, l.indexOf('@'));
191
+ decorators.push(text.replace(/\s+/g, ' ').trim());
192
+ i = end;
193
+ continue;
194
+ }
195
+ const start = l.match(/^(\s*)(?:async\s+)?def\s+(\w+)\s*\(/);
196
+ if (!start) { if (l.trim() && !/^\s*#/.test(l)) decorators = []; continue; }
197
+ // The header can span lines: parameters one per line (FastAPI `Depends(...)`), a wrapped return type.
198
+ const head = pyHeader(lines, i, start[0].length - 1);
199
+ if (!head) { decorators = []; continue; }
200
+ const indent = start[1].length;
143
201
  const body = [];
144
- if (pyNoComment(m[5]).trim()) body.push({ text: pyNoComment(m[5]).trim(), line: i + 1, indent: indent + 4 });
145
- for (let j = i + 1; j < lines.length; j++) {
202
+ const inline = pyNoComment(head.after).trim();
203
+ if (inline) body.push({ text: inline, line: head.endLine + 1, indent: indent + 4 });
204
+ for (let j = head.endLine + 1; j < lines.length; j++) {
146
205
  const t = lines[j];
147
206
  if (!t.trim() || /^\s*#/.test(t)) continue;
148
207
  const ind = t.match(/^\s*/)[0].length;
@@ -151,8 +210,10 @@ function findFunctions(src, language) {
151
210
  if (!code) continue;
152
211
  body.push({ text: code, line: j + 1, indent: ind });
153
212
  }
154
- fns.push({ name: m[2], line: i + 1, params: parseParams(m[3], language), returns: m[4]?.trim() || null, pyBody: body });
155
- });
213
+ const doc = inline ? null : pyDocstring(lines, head.endLine + 1);
214
+ fns.push({ name: start[2], line: i + 1, params: parseParams(head.params, language), returns: head.returns, pyBody: body, ...(decorators.length ? { decorators } : {}), ...(doc ? { doc } : {}) });
215
+ decorators = [];
216
+ }
156
217
  annotateRoutes(fns, src);
157
218
  return fns;
158
219
  }
@@ -181,12 +242,19 @@ function findFunctions(src, language) {
181
242
  if (KEYWORDS_NOT_FN.has(name) || open < 0) continue;
182
243
  const close = matchClose(src, open);
183
244
  if (close < 0) continue;
184
- // After the parameter list: an optional return type / throws clause, then a body.
185
- const after = src.slice(close + 1);
186
- const head = language === 'kotlin'
245
+ // After the parameter list: an optional return type / throws clause, then a body. A signature's head is short,
246
+ // so look at a window, not the rest of the file (copying the rest per function made large files slow).
247
+ const after = src.slice(close + 1, close + 1 + 4000);
248
+ // TypeScript return types can hold braces and generics (`: Promise<{ ok: boolean }>`): read them balanced, so
249
+ // the body's "{" is the one after the type, not a brace inside it.
250
+ const typed = (language === 'typescript' || language === 'javascript') ? balancedReturnHead(after) : null;
251
+ const head = typed ?? (language === 'kotlin'
187
252
  ? after.match(/^\s*(?::\s*([^{=]+?))?()()\s*(?:where\s+[^{=]+)?(=(?![=>])|\{)/)
188
- : after.match(/^\s*(?::\s*([^{=;]+?)|->\s*([^{;]+?)|\s+(\([^)]*\)|[\w.<>\[\]*&' ]+?))?\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/);
253
+ : after.match(/^\s*(?::\s*([^{=;]+?)|->\s*([^{;]+?)|\s+(\([^)]*\)|[\w.<>\[\]*&' ]+?))?\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/));
189
254
  if (!head || head[4] === ';') continue;
255
+ // `const d = (await res.json()) as {...}` is a value, not a function: a const/let/var only declares a
256
+ // function when its parameter list is followed by `=>`.
257
+ if (/\(\?:const\|let\|var\)/.test(re.source) && head[4] !== '=>') continue;
190
258
  if (language === 'kotlin' && head[4] === '=') {
191
259
  // Kotlin expression body: fun f(x: Int) = when (x) { ... } / = if (...) "A" else "B" / = "A"
192
260
  const markerAt = close + 1 + head[0].length - 1;
@@ -260,17 +328,182 @@ function findFunctions(src, language) {
260
328
  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] } });
261
329
  }
262
330
  }
331
+ // Fastify: fastify.route({ method: 'POST', url: '/orders', handler: async (request, reply) => { ... } })
332
+ if (language === 'typescript' || language === 'javascript') {
333
+ const re = /\b\w+\.route\(\s*\{/g;
334
+ let m;
335
+ while ((m = re.exec(src))) {
336
+ const objOpen = m.index + m[0].length - 1;
337
+ const objClose = matchClose(src, objOpen);
338
+ if (objClose < 0) continue;
339
+ const obj = src.slice(objOpen, objClose);
340
+ const method = (obj.match(/\bmethod\s*:\s*['"`](\w+)['"`]/) || [])[1];
341
+ const url = (obj.match(/\b(?:url|path)\s*:\s*['"`]([^'"`]+)['"`]/) || [])[1];
342
+ const h = obj.match(/\bhandler\s*:\s*(?:async\s*)?(?:function\s*\w*\s*)?\(/);
343
+ if (!method || !url || !h) continue;
344
+ const pOpen = objOpen + h.index + h[0].length - 1;
345
+ const pClose = matchClose(src, pOpen);
346
+ const brace = pClose < 0 ? -1 : src.indexOf('{', pClose);
347
+ if (brace < 0 || !/^\s*(=>\s*)?(:\s*[\w<>\[\]|. ]+)?\s*(=>\s*)?$/.test(src.slice(pClose + 1, brace))) continue;
348
+ const bc = matchClose(src, brace);
349
+ if (bc < 0) continue;
350
+ fns.push({ name: `${method.toUpperCase()} ${url}`, line: lineAt(src, m.index), params: [], returns: null, bodyStart: brace + 1, body: src.slice(brace + 1, bc), route: { method: method.toUpperCase(), path: url } });
351
+ }
352
+ }
263
353
  annotateRoutes(fns, src);
264
354
  return fns.sort((a, b) => a.line - b.line);
265
355
  }
356
+ // ── Labels, plumbing, and completeness: facts views need, so they never re-derive them ─────────────────
357
+
358
+ /** A display name: late_fee -> "Late fee", deliveryFee -> "Delivery fee", __init__ -> "Init". */
359
+ export function displayLabel(name) {
360
+ const w = String(name).replace(/^_+|_+$/g, '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
361
+ return w ? w.charAt(0).toUpperCase() + w.slice(1) : String(name);
362
+ }
363
+
364
+ /** Inputs that are framework plumbing rather than something a person gives. */
365
+ const PLUMBING = /^(self|this|cls|db|session|conn|connection|cursor|tx|transaction|request|req|res|response|ctx|context|c|w|r|next|logger|log|deps|container|di|cancellationToken|ct|ec|app|g)$/i;
366
+ const PLUMBING_TYPE = /\b(Session|AsyncSession|DbContext|Connection|HttpRequest|HttpResponse|Request|Response|Context|ResponseWriter|CancellationToken|ILogger|Logger|NextFunction)\b/;
367
+
368
+ const allSteps = (steps) => (steps || []).flatMap((s) => [s, ...allSteps(s.children), ...allSteps(s.otherwise), ...(s.handlers || []).flatMap((h) => allSteps(h.steps)), ...allSteps(s.always?.steps)]);
369
+
370
+ /**
371
+ * How completely Thunder explains an item, with the reasons. "explained": every step says what it does and every
372
+ * branch is shown; "partly explained": something is shown as code or not read; "found": Thunder found the function
373
+ * but could not turn it into steps or rules. ("executed" is for a view that has also run it.)
374
+ */
375
+ export function completenessOf(item) {
376
+ const reasons = [];
377
+ if (item.kind === 'decision') {
378
+ if (item.unread?.length) reasons.push(`${item.unread.length} line${item.unread.length === 1 ? '' : 's'} not read`);
379
+ return { level: reasons.length ? 'partly explained' : 'explained', reasons };
380
+ }
381
+ const steps = allSteps(item.steps);
382
+ if (!steps.length) return { level: 'found', reasons: ['No steps could be read; see the original code.'] };
383
+ const code = steps.filter((s) => s.kind === 'other').length;
384
+ const restated = steps.filter((s) => s.restates).length;
385
+ if (code) reasons.push(`${code} step${code === 1 ? '' : 's'} shown as code`);
386
+ if (restated) reasons.push(`${restated} step${restated === 1 ? '' : 's'} only restate the code`);
387
+ if (item.anchor && item.anchor.coverage < 1) reasons.push(`${item.anchor.missing.length ? `lines ${item.anchor.missing.join(', ')}` : 'some lines'} not tied to a step`);
388
+ return { level: reasons.length ? 'partly explained' : 'explained', reasons };
389
+ }
390
+
391
+ // ── Python helpers: balanced text across lines, multi-line `def` headers, docstrings ─────────────────
392
+ /** Text from lines[i] at column `col` until brackets balance (strings skipped). Returns { text, end } (end line index). */
393
+ function pyBalanced(lines, i, col) {
394
+ let depth = 0, text = '', quote = null;
395
+ for (let j = i; j < lines.length; j++) {
396
+ const l = j === i ? lines[j].slice(col) : lines[j];
397
+ for (let k = 0; k < l.length; k++) {
398
+ const c = l[k];
399
+ if (quote) { if (c === '\\') k++; else if (c === quote) quote = null; continue; }
400
+ if (c === '"' || c === "'") quote = c;
401
+ else if (c === '#') break;
402
+ else if ('([{'.includes(c)) depth++;
403
+ else if (')]}'.includes(c)) depth--;
404
+ }
405
+ text += (j === i ? '' : '\n') + l;
406
+ quote = null; // Python strings do not span lines without triple quotes; triple-quoted args are rare in headers
407
+ if (depth <= 0) return { text, end: j };
408
+ }
409
+ return { text, end: lines.length - 1 };
410
+ }
411
+
412
+ /** A `def name(` header starting at lines[i], `open` = column of `(`. Returns { params, returns, after, endLine } or null. */
413
+ function pyHeader(lines, i, open) {
414
+ let depth = 0, quote = null, params = '', closed = false, tail = '';
415
+ for (let j = i; j < lines.length && j < i + 80; j++) {
416
+ const l = lines[j];
417
+ for (let k = j === i ? open : 0; k < l.length; k++) {
418
+ const c = l[k];
419
+ if (!closed) {
420
+ if (quote) { params += c; if (c === '\\') { params += l[k + 1] ?? ''; k++; } else if (c === quote) quote = null; continue; }
421
+ if (c === '#') break;
422
+ if (c === '"' || c === "'") { quote = c; params += c; continue; }
423
+ if (c === '(') { if (depth++ === 0) continue; }
424
+ else if (c === ')') { if (--depth === 0) { closed = true; continue; } }
425
+ params += c;
426
+ continue;
427
+ }
428
+ // After the parameter list: `-> type` (brackets may wrap lines), then the header's own colon.
429
+ if (c === '#' && depth === 0) break;
430
+ if ('([{'.includes(c)) depth++;
431
+ else if (')]}'.includes(c)) depth--;
432
+ if (c === ':' && depth === 0) {
433
+ const ret = tail.trim().replace(/^->\s*/, '').replace(/\s+/g, ' ').trim();
434
+ return { params: params.replace(/\s+/g, ' ').trim(), returns: ret || null, after: l.slice(k + 1), endLine: j };
435
+ }
436
+ tail += c;
437
+ }
438
+ if (!closed) params += ' ';
439
+ else tail += ' ';
440
+ }
441
+ return null;
442
+ }
443
+
444
+ /** The function's docstring (first statement), as plain text: its first paragraph, without Args/Returns sections. */
445
+ function pyDocstring(lines, from) {
446
+ let j = from;
447
+ while (j < lines.length && (!lines[j].trim() || /^\s*#/.test(lines[j]))) j++;
448
+ const first = lines[j]?.trim();
449
+ const m = first?.match(/^([rRuU]?)("""|\'\'\'|"|')/);
450
+ if (!m) return null;
451
+ const q = m[2];
452
+ let text = first.slice(m[0].length);
453
+ if (text.includes(q)) text = text.slice(0, text.indexOf(q));
454
+ else {
455
+ if (q.length === 1) return null;
456
+ for (let k = j + 1; k < lines.length && k < j + 60; k++) {
457
+ const at = lines[k].indexOf(q);
458
+ if (at >= 0) { text += '\n' + lines[k].slice(0, at); break; }
459
+ text += '\n' + lines[k];
460
+ }
461
+ }
462
+ return cleanDoc(text);
463
+ }
464
+
465
+ /** First paragraph of a doc comment, whitespace collapsed, without parameter sections. Null when empty. */
466
+ function cleanDoc(text) {
467
+ const para = [];
468
+ for (const raw of String(text).split('\n')) {
469
+ const t = raw.replace(/^\s*(\*|\/\/\/?|#)?\s?/, '').trim();
470
+ if (/^(@\w+|:(param|return|rtype|raises|type)\b|(Args|Arguments|Parameters|Returns|Raises|Yields|Example|Examples|Note|Notes)\s*:|<\/?(summary|param|returns)\b)/i.test(t)) break;
471
+ if (!t) { if (para.length) break; continue; }
472
+ para.push(t.replace(/<\/?summary>/g, ''));
473
+ }
474
+ const s = para.join(' ').replace(/\s+/g, ' ').trim();
475
+ if (!s) return null;
476
+ return s.length > 300 ? `${s.slice(0, 299)}…` : s;
477
+ }
478
+
479
+ // A doc comment directly above a function (a /** block, /// lines, Go // lines, Ruby # lines), skipping annotations.
480
+ function leadingDoc(lines, fnLine, language) {
481
+ let k = fnLine - 2;
482
+ while (k >= 0 && /^\s*(@|#\[|\[[A-Z])/.test(lines[k])) k--; // annotations and attributes
483
+ if (k < 0) return null;
484
+ if (/\*\/\s*$/.test(lines[k])) {
485
+ const end = k;
486
+ while (k >= 0 && !/\/\*\*/.test(lines[k])) k--;
487
+ if (k < 0) return null;
488
+ return cleanDoc(lines.slice(k, end + 1).join('\n').replace(/^\s*\/\*\*/, '').replace(/\*\/\s*$/, ''));
489
+ }
490
+ const lineDoc = language === 'go' ? /^\s*\/\/(?!\/)/ : language === 'ruby' ? /^\s*#(?![!{])/ : /^\s*\/\/\//;
491
+ const got = [];
492
+ while (k >= 0 && lineDoc.test(lines[k])) got.unshift(lines[k--]);
493
+ return got.length ? cleanDoc(got.join('\n')) : null;
494
+ }
495
+
266
496
  /** Mark functions that a decorator or annotation binds to an HTTP route. */
267
497
  function annotateRoutes(fns, src) {
268
498
  // Decorated handlers: @app.get("/x") / @router.post (Python), @GetMapping (Spring), [HttpGet] (ASP.NET), @Get() (NestJS).
269
499
  const lines = src.split('\n');
270
500
  for (const fn of fns) {
271
501
  if (fn.route) continue;
272
- for (let k = fn.line - 2; k >= Math.max(0, fn.line - 6); k--) {
273
- const l = lines[k].trim();
502
+ // Python collects whole decorators (they can span lines); other languages look at the few lines above.
503
+ const above = fn.decorators
504
+ ? [...fn.decorators].reverse()
505
+ : lines.slice(Math.max(0, fn.line - 6), Math.max(0, fn.line - 1)).reverse().map((x) => x.trim());
506
+ for (const l of above) {
274
507
  let m;
275
508
  if ((m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i))) { fn.route = { method: m[1].toUpperCase(), path: m[2] }; break; }
276
509
  if ((m = l.match(/^@\w+\.route\(\s*['"]([^'"]*)['"](?:.*methods\s*=\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'GET').toUpperCase(), path: m[1] }; break; }
@@ -897,19 +1130,29 @@ function splitStatements(body, baseLine) {
897
1130
  const rest = src.slice(i + 1).match(/^\s*else\b/);
898
1131
  if (!rest) { i++; break; }
899
1132
  }
900
- } else if (c === ';' && depth === 0) { i++; break; }
1133
+ } else if (c === ';' && depth === 0) {
1134
+ // Go: `if err := open(); err != nil {` and `for i := 0; i < n; i++ {` keep their header together.
1135
+ if (/^\s*(?:if|for|switch|else\s+if)\b/.test(src.slice(start, i)) && !src.slice(start, i).includes('{') && /\{/.test(src.slice(i, src.indexOf('\n', i) < 0 ? undefined : src.indexOf('\n', i)))) continue;
1136
+ i++; break;
1137
+ }
901
1138
  else if (c === '\n' && depth === 0) {
902
1139
  // Newline-terminated statements (Go, Kotlin, JavaScript without semicolons): a complete line
903
1140
  // ends the statement unless the next line continues it.
904
1141
  const before = src.slice(start, i).trimEnd();
905
- const after = src.slice(i + 1).trimStart();
1142
+ // Only the start of the next line matters; never copy the rest of the source (that made this quadratic).
1143
+ let j = i + 1;
1144
+ while (j < src.length && (src[j] === ' ' || src[j] === '\t' || src[j] === '\n' || src[j] === '\r')) j++;
1145
+ const after = src.slice(j, j + 24);
906
1146
  if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) && !/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after)) { i++; break; }
907
1147
  }
908
1148
  }
909
1149
  const raw = src.slice(start, i);
910
1150
  const text = raw.trim();
911
1151
  // Offsets are into the body as given (comments are blanked in place, so lengths are unchanged).
912
- const end = start + raw.replace(/[\s;]+$/, '').length;
1152
+ // Trim trailing whitespace and semicolons by scanning back (the /[\s;]+$/ regex is quadratic on long bodies).
1153
+ let e = raw.length;
1154
+ while (e > 0 && /[\s;]/.test(raw[e - 1])) e--;
1155
+ const end = start + e;
913
1156
  if (text) out.push({ text, line: baseLine + lineAt(src, start) - 1, endLine: baseLine + lineAt(src, Math.max(start, end - 1)) - 1, start, end });
914
1157
  }
915
1158
  return out;
@@ -1502,7 +1745,8 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
1502
1745
  let stmts = [];
1503
1746
  try {
1504
1747
  if (lang === 'python') stmts = indentStatements(fn.pyBody, { depthKey: 'indent' });
1505
- else if (lang === 'ruby') stmts = indentStatements(fn.rbBody, { depthKey: 'depth' });
1748
+ // For steps, elsif / else / rescue / ensure sit beside their if or begin (the rule reader keeps the raw depth).
1749
+ else if (lang === 'ruby') stmts = indentStatements(fn.rbBody.map((l) => (/^(elsif|else|rescue|ensure)\b/.test(l.text) ? { ...l, depth: Math.max(0, l.depth - 1) } : l)), { depthKey: 'depth' });
1506
1750
  else if (typeof fn.body === 'string' && fn.bodyStart != null) stmts = braceStatements(splitStatements(lang === 'kotlin' ? kotlinTerminate(fn.body) : fn.body, lineAt(code, fn.bodyStart)), splitStatements);
1507
1751
  } catch { return null; }
1508
1752
  if (!stmts.length) return null;
@@ -1527,8 +1771,10 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
1527
1771
  }
1528
1772
  for (const st of r.steps) {
1529
1773
  if (st.kind !== 'branch' || !st.cond) continue;
1530
- const cond = toThunderCondition(st.cond, names);
1531
- if (cond) st.says = st.says.replace(/^If .*?( \(\d+ steps? inside\))?$/, (_m, inner) => `If ${st.negate ? 'not: ' : ''}${sayCondition(cond).replace(/ is not ""/g, ' is not empty').replace(/ is ""/g, ' is empty')}${inner || ''}`);
1774
+ // A bare yes/no property (`order.refunded`) already reads as a sentence from the step itself; keep it.
1775
+ const bareProperty = /^(not\s+|!)?(?:self\.|this\.)?\w+\.\w+(\(\))?$/.test(st.cond.trim()) && !/\./.test(st.says.replace(/\(\d+ steps? inside\)$/, ''));
1776
+ const cond = bareProperty ? null : toThunderCondition(st.cond, names);
1777
+ if (cond) st.says = st.says.replace(/^If .*?( \(\d+ steps? inside\))?$/, (_m, inner) => `If ${st.negate ? 'not: ' : ''}${plainEnums(sayCondition(cond)).replace(/ is not ""/g, ' is not empty').replace(/ is ""/g, ' is empty')}${inner || ''}`);
1532
1778
  delete st.cond; delete st.negate;
1533
1779
  }
1534
1780
  return r;
@@ -1544,6 +1790,7 @@ export function readCode(source, { language, file = '' } = {}) {
1544
1790
  const code = lang === 'php' ? normalizePhp(src) : src;
1545
1791
  const items = [];
1546
1792
  const srcLines = src.split('\n');
1793
+ const codeLines = code.split('\n');
1547
1794
  for (const fn of findFunctions(code, lang)) {
1548
1795
  const inputs = fn.params;
1549
1796
  const names = inputs.map((p) => p.name);
@@ -1566,9 +1813,15 @@ export function readCode(source, { language, file = '' } = {}) {
1566
1813
  guards.sort((a, b) => a.line - b.line);
1567
1814
  }
1568
1815
  const guardNote = guards.length ? ` It checks ${guards.length} condition${guards.length === 1 ? '' : 's'} first: ${guards.map((g) => g.says.replace(/\.$/, '')).join('; ')}.` : '';
1816
+ // The author's own words for what the function means (docstring or doc comment), kept apart from the
1817
+ // reading inferred from the code so a view can show both and say which is which.
1818
+ const doc = fn.doc ?? (lang === 'python' ? null : leadingDoc(codeLines, fn.line, lang));
1569
1819
  const base = {
1570
- id: `${fn.name}:${fn.line}`, name: fn.name, line: fn.line, inputs, returns: simpleType(fn.returns),
1820
+ id: `${fn.name}:${fn.line}`, name: fn.name, label: displayLabel(fn.name), line: fn.line,
1821
+ // Framework plumbing (a database session, the request, a context) is marked so views can leave it out of "You give it".
1822
+ inputs: inputs.map((p) => (PLUMBING.test(p.name) || PLUMBING_TYPE.test(String(p.type ?? '')) ? { ...p, plumbing: true } : p)), returns: simpleType(fn.returns),
1571
1823
  ...(fn.route ? { route: fn.route } : {}),
1824
+ ...(doc ? { doc } : {}),
1572
1825
  provenance: 'inferred-from-code',
1573
1826
  };
1574
1827
  if (isDecision) {
@@ -1585,6 +1838,9 @@ export function readCode(source, { language, file = '' } = {}) {
1585
1838
  ...base, kind: 'function', status: 'signature-only',
1586
1839
  ...(st ? { steps: st.steps, stepsMore: st.more, stepsReadable: Math.round(st.readable * 100) / 100, ...(st.anchor ? { anchor: st.anchor } : {}) } : {}),
1587
1840
  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}`,
1841
+ // The same facts as separate fields, so a view never has to cut sentences out of `says`.
1842
+ headline: fn.route ? `Handles ${fn.route.method} ${fn.route.path || "(this controller's path)"}.` : `${displayLabel(fn.name)} takes ${inputs.length ? inputs.map((p) => p.name).join(', ') : 'no inputs'}${fn.returns ? ` and returns ${simpleType(fn.returns)}` : ''}.`,
1843
+ ...(guards.length ? {} : { note: 'Its body does more than choose between fixed answers, so no rules are shown.' }),
1588
1844
  guards, unread: read.unread,
1589
1845
  });
1590
1846
  }
@@ -1594,6 +1850,7 @@ export function readCode(source, { language, file = '' } = {}) {
1594
1850
  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' });
1595
1851
  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' });
1596
1852
  items.sort((a, b) => a.line - b.line);
1853
+ for (const it of items) if (it.kind === 'function' || it.kind === 'decision') it.completeness = completenessOf(it);
1597
1854
  const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
1598
1855
  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++; }
1599
1856
  return {
package/src/same.d.mts ADDED
@@ -0,0 +1,10 @@
1
+ // thunder-same-v1: does new code mean the same as old code? (see src/same.mjs)
2
+ export const SAME_SCHEMA: 'thunder-same-v1';
3
+ export type SameStatus = 'same' | 'different' | 'only-old' | 'only-new' | 'cannot-check';
4
+ type Where = { file: string; line: number; language: string };
5
+ export interface SameItem { name: string; status: SameStatus; reason: string; old?: Where; new?: Where; counterexample?: { values: Record<string, unknown>; facts: string; old: string; new: string } }
6
+ export interface SameReport { schema: 'thunder-same-v1'; verdict: 'same' | 'different' | 'partly-checked'; counts: Record<SameStatus, number>; items: SameItem[]; unreadable: { path: string; reason: string }[] }
7
+ export function nameKey(name: string): string;
8
+ export function compareRules(oldItem: unknown, newItem: unknown): { same: boolean; tried: number; reason?: string; counterexample?: SameItem['counterexample'] } | null;
9
+ export function sameMeaning(oldFiles: { path: string; source: string }[], newFiles: { path: string; source: string }[]): SameReport;
10
+ export function renderSame(report: SameReport): string;
package/src/same.mjs ADDED
@@ -0,0 +1,160 @@
1
+ // thunder same: does new code mean the same as old code? Reads both (in any languages Thunder reads), pairs their
2
+ // functions by name, and compares their Thunder. Rules are compared by RUNNING both on the same inputs (every edge
3
+ // value either rule mentions), not by comparing text, so a rewritten condition that gives the same answers counts as
4
+ // the same, and a changed limit is caught with a counterexample. Browser-safe: takes [{ path, source }].
5
+ import { readCode } from './read.mjs';
6
+ import { readableLanguage } from './read-repo.mjs';
7
+ import { plainFromReading, explainPlain } from './plain-contract.mjs';
8
+ import { visualFor } from './visual.mjs';
9
+
10
+ export const SAME_SCHEMA = 'thunder-same-v1';
11
+ const MAX_CASES = 4096;
12
+
13
+ /** Names written in any convention compare equal: delivery_fee, deliveryFee, DeliveryFee. */
14
+ export const nameKey = (name) => String(name).replace(/[_\s-]/g, '').toLowerCase();
15
+ const norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
16
+
17
+ // A function is identified by its file's stem and its name (and which occurrence, for repeated names such as
18
+ // __init__), written in any convention: app/delivery.py#delivery_fee pairs with app/delivery.ts#deliveryFee.
19
+ const stemKey = (path) => nameKey(String(path).replace(/\.[^./]+$/, '').replace(/\\/g, '/'));
20
+
21
+ // Only what compareItems needs is kept, so comparing a whole app does not hold every reading in memory: rules keep
22
+ // their item (their answers are run), lists of steps keep only their flattened signatures and text.
23
+ function compact(it, key, file, language) {
24
+ const base = { key, file, language, name: it.name, kind: it.kind, line: it.line, route: it.route, element: visualFor(it).element };
25
+ return it.kind === 'decision' ? { ...it, ...base } : { ...base, flat: flatSteps(it.steps) };
26
+ }
27
+
28
+ function readAll(files) {
29
+ const items = new Map(), byName = new Map(), unreadable = [];
30
+ for (const f of files) {
31
+ const language = readableLanguage(f.path);
32
+ if (!language || !f.source) continue;
33
+ let reading;
34
+ try { reading = readCode(f.source, { language, file: f.path }); } catch (e) { unreadable.push({ path: f.path, reason: e.message }); continue; }
35
+ const seen = new Map();
36
+ for (const it of reading.items) {
37
+ if (it.kind !== 'decision' && it.kind !== 'function') continue;
38
+ const n = nameKey(it.name);
39
+ const nth = (seen.get(n) || 0) + 1; seen.set(n, nth);
40
+ const key = `${stemKey(f.path)}#${n}${nth > 1 ? `#${nth}` : ''}`;
41
+ items.set(key, compact(it, key, f.path, language));
42
+ byName.set(n, byName.has(n) ? null : key); // null marks a name used more than once
43
+ }
44
+ }
45
+ return { items, byName, unreadable };
46
+ }
47
+
48
+ /** Every value worth trying for each input: each limit either rule uses, one either side of it, and 0. */
49
+ function caseValues(models) {
50
+ const byInput = new Map();
51
+ for (const m of models) for (const input of m.inputs) {
52
+ if (!byInput.has(input.id)) byInput.set(input.id, { kind: input.kind, values: new Set() });
53
+ const slot = byInput.get(input.id);
54
+ if (input.kind === 'yesno') { slot.values.add(true); slot.values.add(false); }
55
+ }
56
+ for (const m of models) for (const r of m.rules) for (const c of r.conditions) {
57
+ const slot = byInput.get(c.input);
58
+ if (!slot || slot.kind === 'yesno' || typeof c.value !== 'number') continue;
59
+ for (const v of [c.value - 1, c.value, c.value + 1, c.value - 0.01, c.value + 0.01]) slot.values.add(Math.round(v * 100) / 100);
60
+ }
61
+ for (const slot of byInput.values()) if (slot.kind !== 'yesno') slot.values.add(0);
62
+ return [...byInput.entries()].map(([id, s]) => [id, [...s.values].sort((a, b) => (a > b ? 1 : a < b ? -1 : 0))]);
63
+ }
64
+
65
+ function* product(axes, i = 0, acc = {}) {
66
+ if (i === axes.length) { yield { ...acc }; return; }
67
+ const [id, values] = axes[i];
68
+ for (const v of values) { acc[id] = v; yield* product(axes, i + 1, acc); }
69
+ }
70
+
71
+ /** Compare two rules by running both on every edge case. Returns { same, tried, counterexample? }. */
72
+ export function compareRules(oldItem, newItem) {
73
+ let a, b;
74
+ try { a = plainFromReading(oldItem); b = plainFromReading(newItem); } catch { a = b = null; }
75
+ if (!a || !b) return null;
76
+ // Inputs are matched by meaning (their readable label), not by spelling: distance_km and distanceKm are one fact.
77
+ const key = (i) => `${nameKey(i.label)}:${i.kind}`;
78
+ const toA = new Map(a.inputs.map((i) => [key(i), i.id]));
79
+ if (a.inputs.length !== b.inputs.length || !b.inputs.every((i) => toA.has(key(i)))) {
80
+ return { same: false, tried: 0, reason: `They need different facts: ${a.inputs.map((i) => i.label).join(', ')} versus ${b.inputs.map((i) => i.label).join(', ')}.` };
81
+ }
82
+ const bAsA = { ...b, inputs: b.inputs.map((i) => ({ ...i, id: toA.get(key(i)) })), rules: b.rules.map((r) => ({ ...r, conditions: r.conditions.map((c) => ({ ...c, input: toA.get(key(b.inputs.find((i) => i.id === c.input))) })) })) };
83
+ let tried = 0;
84
+ for (const values of product(caseValues([a, bAsA]))) {
85
+ if (++tried > MAX_CASES) { tried--; break; }
86
+ const x = explainPlain(a, values).outcome, y = explainPlain(bAsA, values).outcome;
87
+ if (x !== y) return { same: false, tried, counterexample: { values: { ...values }, facts: a.inputs.map((i) => `${i.label} ${i.kind === 'yesno' ? (values[i.id] ? i.yes ?? 'yes' : i.no ?? 'no') : values[i.id]}`).join(', '), old: x, new: y } };
88
+ }
89
+ return { same: true, tried };
90
+ }
91
+
92
+ // Each step flattened in reading order: `sig` is what is compared (kind and wording, case- and punctuation-blind),
93
+ // `text` is what a person is shown. Code that is not explained compares as code, never by its wording.
94
+ const flatSteps = (steps, depth = 0) => (steps || []).flatMap((s) => [
95
+ { sig: `${depth}:${s.restates ? 'code' : s.kind}:${s.restates || s.kind === 'other' ? '' : norm(s.says)}`, text: s.restates || s.kind === 'other' ? `\`${s.code ?? s.says}\`` : s.says },
96
+ ...flatSteps(s.children, depth + 1),
97
+ ]);
98
+
99
+ function compareItems(o, n) {
100
+
101
+ const where = { old: { file: o.file, line: o.line, language: o.language }, new: { file: n.file, line: n.line, language: n.language } };
102
+ if (o.element === 'not-read' || n.element === 'not-read') return { status: 'cannot-check', reason: 'Thunder cannot read one side yet, so it cannot confirm they mean the same.', ...where };
103
+ if (o.kind !== n.kind) return { status: 'different', reason: `One is a ${o.kind === 'decision' ? 'rule' : 'list of steps'}, the other is a ${n.kind === 'decision' ? 'rule' : 'list of steps'}.`, ...where };
104
+ if ((o.route?.method || '') !== (n.route?.method || '') || (o.route?.path || '') !== (n.route?.path || '')) {
105
+ return { status: 'different', reason: `The address changed: ${o.route ? `${o.route.method} ${o.route.path}` : 'none'} became ${n.route ? `${n.route.method} ${n.route.path}` : 'none'}.`, ...where };
106
+ }
107
+ if (o.kind === 'decision') {
108
+ const r = compareRules(o, n);
109
+ if (!r) return { status: 'cannot-check', reason: 'One rule could not be drawn as a card, so its answers could not be compared.', ...where };
110
+ if (r.same) return { status: 'same', reason: `Same answer on all ${r.tried} edge cases.`, ...where };
111
+ if (r.counterexample) {
112
+ const facts = r.counterexample.facts;
113
+ return { status: 'different', reason: `Different answer for ${facts}: ${r.counterexample.old} before, ${r.counterexample.new} after.`, counterexample: r.counterexample, ...where };
114
+ }
115
+ return { status: 'different', reason: r.reason, ...where };
116
+ }
117
+ const so = o.flat, sn = n.flat;
118
+ const at = so.findIndex((s, i) => s.sig !== sn[i]?.sig);
119
+ if (at === -1 && so.length === sn.length) return { status: 'same', reason: `Same ${so.length} steps.`, ...where };
120
+ const i = at === -1 ? Math.min(so.length, sn.length) : at;
121
+ return { status: 'different', reason: `Steps differ from step ${i + 1}: "${so[i]?.text ?? '(nothing)'}" became "${sn[i]?.text ?? '(nothing)'}".`, ...where };
122
+ }
123
+
124
+ /**
125
+ * Compare old and new code. Returns { verdict, counts, items } where each item is same, different, only-old,
126
+ * only-new, or cannot-check. The verdict is 'same' only when nothing differs and nothing went unchecked.
127
+ */
128
+ export function sameMeaning(oldFiles, newFiles) {
129
+ const A = readAll(oldFiles), B = readAll(newFiles);
130
+ const items = [], used = new Set();
131
+ // Pair by file and name first; if the file was renamed, fall back to a name that is unique on both sides.
132
+ const partner = (key, o) => {
133
+ if (B.items.has(key) && !used.has(key)) return key;
134
+ const n = nameKey(o.name), a = A.byName.get(n), b = B.byName.get(n);
135
+ return a && b && !used.has(b) ? b : null;
136
+ };
137
+ for (const [key, o] of A.items) {
138
+ const k = partner(key, o);
139
+ if (k) used.add(k);
140
+ const n = k && B.items.get(k);
141
+ items.push({ name: o.name, ...(n ? compareItems(o, n) : { status: 'only-old', reason: 'Not found in the new code.', old: { file: o.file, line: o.line, language: o.language } }) });
142
+ }
143
+ for (const [key, n] of B.items) if (!used.has(key)) items.push({ name: n.name, status: 'only-new', reason: 'New: not in the old code.', new: { file: n.file, line: n.line, language: n.language } });
144
+ const counts = { same: 0, different: 0, 'only-old': 0, 'only-new': 0, 'cannot-check': 0 };
145
+ for (const it of items) counts[it.status]++;
146
+ const verdict = counts.different || counts['only-old'] || counts['only-new'] ? 'different' : counts['cannot-check'] ? 'partly-checked' : 'same';
147
+ return { schema: SAME_SCHEMA, verdict, counts, items, unreadable: [...A.unreadable, ...B.unreadable] };
148
+ }
149
+
150
+ export function renderSame(r) {
151
+ const head = r.verdict === 'same' ? 'Same meaning.' : r.verdict === 'partly-checked' ? 'No differences found, but some parts could not be checked.' : 'Different meaning.';
152
+ const lines = [`${head} ${r.counts.same} same, ${r.counts.different} different, ${r.counts['only-old']} only in the old code, ${r.counts['only-new']} only in the new code, ${r.counts['cannot-check']} not checked.`];
153
+ const order = ['different', 'only-old', 'only-new', 'cannot-check', 'same'];
154
+ const label = { different: 'different', 'only-old': 'only old', 'only-new': 'only new', 'cannot-check': 'not checked', same: 'same' };
155
+ for (const st of order) for (const it of r.items.filter((x) => x.status === st)) {
156
+ const loc = [it.old && `${it.old.file}:${it.old.line}`, it.new && `${it.new.file}:${it.new.line}`].filter(Boolean).join(' → ');
157
+ lines.push(` ${label[st].padEnd(11)} ${it.name} (${loc}) ${it.reason}`);
158
+ }
159
+ return `${lines.join('\n')}\n`;
160
+ }