@skillstech/thunderlang 0.5.10 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +450 -0
  2. package/dist/core.cjs +30434 -7577
  3. package/dist/index.cjs +28576 -5328
  4. package/dist/learn.cjs +24201 -5367
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +49 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +65 -14
  34. package/src/model.mjs +496 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1017 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
package/src/read.mjs CHANGED
@@ -1,5 +1,6 @@
1
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.
2
+ // JavaScript, Python, Go, Rust, C#, Java, Kotlin, PHP, Ruby, SQL, C, C++, or Swift, and show them as ThunderLang
3
+ // plus plain English.
3
4
  // Deterministic, no AI, browser-safe. Everything here is INFERRED from code: a reading says what
4
5
  // the code appears to decide, never what it was meant to decide, and anything it could not read
5
6
  // is listed rather than guessed.
@@ -10,31 +11,89 @@
10
11
  // Rust/Go tail forms: if cond { X } else { Y }, if cond { return X }
11
12
  // Conditions may use comparisons, &&/||/!, and/or/not, parentheses, literals, and inputs or fields.
12
13
  import { sqlItems } from './sql.mjs';
13
- import { stepsFrom, braceStatements, indentStatements, plainEnums } from './steps.mjs';
14
+ import { readDockerfile } from './infra-docker.mjs';
15
+ import { readWorkflow } from './infra-gha.mjs';
16
+ import { readTerraform } from './infra-terraform.mjs';
17
+ import { readBicep } from './infra-bicep.mjs';
18
+ import { readKubernetes } from './infra-k8s.mjs';
19
+ import { readCompose } from './infra-compose.mjs';
20
+ import { readableFormat } from './file-formats.mjs';
21
+ import { stepsFrom, braceStatements, indentStatements, plainEnums, withLanguage, SWIFT_CLOSURE_PARAMS, VAPOR_STATUS, withFunctionContext, classifyStatement } from './steps.mjs';
14
22
  import { compileExpr, simplifyExpr } from './expr.mjs';
15
23
  import { extractFacts, languageForFile } from './lift.mjs';
24
+ import { shellReading, shellShebang, SHELL_TRIVIA } from './shell.mjs';
25
+ import { powershellReading } from './powershell.mjs';
26
+ import { rReading } from './rlang.mjs';
16
27
 
17
28
  export const READ_SCHEMA = 'thunder-reading-v1';
18
- export const READ_LANGUAGES = ['typescript', 'javascript', 'python', 'go', 'rust', 'csharp', 'java', 'kotlin', 'php', 'ruby', 'sql'];
19
- const BRACE_LANGS = new Set(['typescript', 'javascript', 'go', 'rust', 'csharp', 'java', 'kotlin', 'php']);
29
+ export const READ_LANGUAGES = ['typescript', 'javascript', 'python', 'go', 'rust', 'csharp', 'java', 'kotlin', 'php', 'ruby', 'sql', 'c', 'cpp', 'swift', 'r', 'shell', 'powershell', 'dockerfile', 'github-actions', 'terraform', 'bicep', 'kubernetes', 'docker-compose'];
30
+ /** Formats read as infrastructure and delivery (spec section 12), not as programming languages. */
31
+ export const INFRA_LANGUAGES = ['dockerfile', 'github-actions', 'terraform', 'bicep', 'kubernetes', 'docker-compose'];
32
+ // Languages whose `if` condition needs no parentheses: `if a && b {` (a leading parenthesis may wrap only part of it).
33
+ const BARE_IF = new Set(['go', 'rust', 'swift']);
34
+ /** Languages read by their own module (shell.mjs, powershell.mjs, rlang.mjs) into the same reading shape. */
35
+ const SCRIPT_READERS = { shell: shellReading, powershell: powershellReading, r: rReading };
20
36
  const KEYWORDS_NOT_FN = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'new', 'else', 'using', 'lock', 'synchronized', 'foreach', 'match', 'loop', 'sizeof', 'typeof', 'nameof']);
21
37
 
22
38
  /** Best-effort language guess for pasted code (a file name, when known, is more reliable). */
23
39
  export function detectLanguage(source, file = '') {
24
- if (file) return languageForFile(file);
25
40
  const s = String(source);
41
+ if (file) {
42
+ const format = readableFormat(file, s.slice(0, 2048));
43
+ if (format) return format;
44
+ // A file with no extension is a shell script when its first line says so (#!/bin/bash).
45
+ if (!/\.[^./\\]+$/.test(String(file)) && shellShebang(s)) return 'shell';
46
+ return /\.h$/i.test(file) ? (looksCpp(source) ? 'cpp' : 'c') : languageForFile(file);
47
+ }
48
+ if (shellShebang(s)) return 'shell';
49
+ // A Dockerfile: its first instruction is FROM (or ARG before FROM), after comments and parser directives.
50
+ if (/^\s*(?:#[^\n]*\n\s*)*(?:ARG\s[^\n]*\n\s*(?:#[^\n]*\n\s*)*)*FROM\s+\S/i.test(s) && /^(RUN|CMD|COPY|ENTRYPOINT|WORKDIR|EXPOSE)\s/m.test(s)) return 'dockerfile';
51
+ // Bicep: `resource name 'Microsoft.X/y@…'`, `module name './x.bicep'`, `param name type`, or `targetScope =`.
52
+ if (/^(?:resource|module)\s+\w+\s+'[^'\n]+'/m.test(s) || /^targetScope\s*=/m.test(s) || (/^param\s+\w+\s+(?:string|int|bool|object|array)\b/m.test(s) && !/^\s*(?:def|function|class)\b/m.test(s))) return 'bicep';
53
+ // Terraform: `resource "type" "name" {`, `variable "x" {`, `terraform {`, `locals {`.
54
+ if (/^(?:resource|data|module|variable|provider|output)\s+"[\w-]+"/m.test(s) || /^(?:terraform|locals)\s*\{/m.test(s)) return 'terraform';
55
+ // A GitHub Actions workflow: top-level `on:` and `jobs:`.
56
+ if (/^(?:on|"on"|'on'):/m.test(s) && /^jobs:\s*$/m.test(s)) return 'github-actions';
57
+ // Kubernetes YAML: top-level apiVersion: and kind:.
58
+ if (/^apiVersion:\s*\S/m.test(s) && /^kind:\s*\S/m.test(s)) return 'kubernetes';
59
+ // Docker Compose: top-level services: with a service that has an image: or build:.
60
+ if (/^services:\s*$/m.test(s) && /^\s+(?:image|build):/m.test(s)) return 'docker-compose';
61
+ // PowerShell: Verb-Noun functions, [CmdletBinding()], param blocks with [type]$name, -eq style operators.
62
+ if (/^\s*function\s+[A-Za-z]+-[A-Za-z]\w*/m.test(s) || /\[CmdletBinding\(/i.test(s) || /\bparam\s*\(\s*(?:\[[^\]]+\]\s*)*\$\w+/i.test(s) || /\$\w+\s+-(?:eq|ne|gt|ge|lt|le|like|match|contains)\b/i.test(s) || /^\s*(?:Write-Host|Get-[A-Z]\w+|Set-[A-Z]\w+|New-[A-Z]\w+)\b/m.test(s)) return 'powershell';
63
+ // R: name <- function(…), library(pkg), pipes with <-, R6Class, plumber annotations.
64
+ if (/[\w.]\s*<-\s*function\s*\(/.test(s) || /^\s*library\(\w+\)\s*$/m.test(s) || /\bR6Class\(|\bsetRefClass\(|^#\*\s*@(?:get|post)\s/m.test(s) || (/<-/.test(s) && /%>%|\|>/.test(s))) return 'r';
65
+ // Shell without a shebang: its own keywords (fi, done, esac, then) alongside $variables.
66
+ if ([/^\s*fi\s*$/m, /^\s*done\s*$/m, /;\s*then\s*$/m, /^\s*esac\s*$/m, /\[\[ .+ \]\]/, /^\s*set -[euo]/m].filter((re) => re.test(s)).length >= 2) return 'shell';
67
+ // SQL: a file that starts with (or is mostly) schema statements.
68
+ if (/^\s*(?:--[^\n]*\n\s*)*(?:CREATE|ALTER|INSERT\s+INTO|SELECT|WITH)\b/i.test(s) && /\b(?:CREATE\s+(?:OR\s+REPLACE\s+)?(?:TABLE|VIEW|FUNCTION|PROCEDURE|TRIGGER|TYPE|INDEX)|SELECT\b[\s\S]*\bFROM)\b/i.test(s)) return 'sql';
26
69
  if (/^\s*<\?php\b/.test(s) || /\bfunction\s+\w+\s*\([^)]*\$\w+/.test(s)) return 'php';
27
70
  if (/\bfun\s+(<[^>]*>\s*)?[\w.]*\w+\s*\(/.test(s)) return 'kotlin';
71
+ // Swift before Go: both write `func`, but only Swift types its parameters with a colon or returns with `->`.
72
+ if (/^[ \t]*import[ \t]+(?:Foundation|UIKit|SwiftUI|Vapor|Combine|XCTest|AppKit|Fluent)\b/m.test(s) || /\bfunc\s+\w+\s*(?:<[^>]*>)?\s*\([^)]*\w\s*:\s*[^)]*\)|\bfunc\s+\w+\s*(?:<[^>]*>)?\s*\([^)]*\)\s*(?:async\s+)?(?:throws\s+)?->/.test(s)) return 'swift';
28
73
  if (/^\s*def\s+[\w.?!]+(\s*\(.*\))?\s*$/m.test(s) && /^\s*end\s*$/m.test(s)) return 'ruby';
29
74
  if (/^\s*package\s+\w+\s*$/m.test(s) || /\bfunc\s+(\([^)]*\)\s*)?\w+\s*\(/.test(s)) return 'go';
30
75
  if (/\bfn\s+\w+\s*(<[^>]*>)?\s*\(/.test(s) || /\blet\s+mut\b|->\s*&'static/.test(s)) return 'rust';
31
76
  if (/^\s*def\s+\w+\s*\(.*\)\s*(->\s*[^:]+)?:\s*$/m.test(s)) return 'python';
77
+ // C and C++: an #include, or C++ syntax (std::, templates, Type::method definitions), or a C function that uses
78
+ // pointers, NULL, or the C library.
79
+ const cSignature = /^[ \t]*(?:static[ \t]+|inline[ \t]+)*(?:const[ \t]+|unsigned[ \t]+|struct[ \t]+\w+[ \t]*)?(?:void|int|char|long|double|float|size_t|bool|u?int\d+_t)[ \t*]+\w+[ \t]*\([^)]*\)[ \t]*\{/m.test(s)
80
+ && /\bNULL\b|->|\bchar[ \t]*\*|\bprintf\(|\bmalloc\(|\bfree\(|\bsizeof\b|\btypedef\b|\bstruct[ \t]+\w+/.test(s) && !/\b(?:public|private|String|boolean|using)\b/.test(s);
81
+ if (cSignature || /^[ \t]*#[ \t]*(?:include|define|ifndef|pragma)\b/m.test(s) || /\bstd::\w|\btemplate[ \t]*<|\b\w+::~?\w+[ \t]*\([^;{)]*\)[ \t]*(?:const[ \t]*)?\{/.test(s)) return looksCpp(s) ? 'cpp' : 'c';
32
82
  if (/\bnamespace\s+[\w.]+|\busing\s+System\b|\bpublic\s+static\s+string\b|\bstring\s+\w+\s*[,)]/.test(s)) return 'csharp';
33
83
  if (/\bpublic\s+(static\s+)?(class|String|boolean|int|double|void)\b|\bString\s+\w+\s*[,)]|\bboolean\b/.test(s)) return 'java';
34
84
  if (/:\s*(number|string|boolean)\b|\binterface\s+\w+|\bexport\s+(function|const)\b/.test(s)) return 'typescript';
35
85
  return 'javascript';
36
86
  }
37
87
 
88
+ /** True when C-family source uses C++ (classes, namespaces, templates, `::`, std), so a `.h` file is read as C++. */
89
+ export function looksCpp(source) {
90
+ // A C header may hold a few lines for C++ callers (#ifdef __cplusplus … #endif); those do not make it C++.
91
+ const s = stripComments(String(source).slice(0, 200000)).replace(/"(?:[^"\\\n]|\\.)*"/g, '""')
92
+ .replace(/^[ \t]*#[ \t]*if(?:def)?[ \t]+(?:defined[ \t]*\(?[ \t]*)?__cplusplus[\s\S]*?^[ \t]*#[ \t]*(?:endif|else)\b/gm, '');
93
+ // C allows `template` and `typename` as names (const char *template), so they count only in their C++ shape.
94
+ return /\bclass[ \t]+\w+[ \t]*[:{]|\bnamespace[ \t]+\w*[ \t]*\{|\btemplate[ \t]*<|\btypename[ \t]+\w+[ \t]*[,>=]|^[ \t]*(?:public|private|protected)[ \t]*:|\bnullptr\b|\bconstexpr\b|\w::\w|\bstd::|#[ \t]*include[ \t]*<(?:iostream|string|vector|map|memory|utility|algorithm|functional|optional|cstdint|cstdio|cstdlib|cstring)>/m.test(s);
95
+ }
96
+
38
97
  // ── Lexing helpers ──────────────────────────────────────────────────────────────────────────
39
98
 
40
99
  // Line of a character offset. The line starts of the last few sources are kept, so each lookup is a binary search
@@ -77,6 +136,8 @@ let READING_RUST = false;
77
136
 
78
137
  function skipString(src, i) {
79
138
  const q = src[i];
139
+ // A multi-line string (triple quotes in Swift, Kotlin, Java, C#) runs to its closing triple quote.
140
+ if (q === '"' && src[i + 1] === '"' && src[i + 2] === '"') { const e = src.indexOf('"""', i + 3); return e < 0 ? src.length : e + 2; }
80
141
  if (q === '\'' && !READING_RUST) {
81
142
  for (let j = i + 1; j < src.length; j++) {
82
143
  if (src[j] === '\\') { j++; continue; }
@@ -104,7 +165,9 @@ const stripComments = (s) => s.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:
104
165
  // ── Function discovery ──────────────────────────────────────────────────────────────────────
105
166
 
106
167
  function parseParams(raw, language) {
107
- raw = String(raw).replace(/#\[[^\]]*\]\s*/g, '').replace(/\[\w+(?:\([^)]*\))?\]\s*/g, ''); // #[SensitiveParameter], [FromBody]
168
+ raw = String(raw).replace(/#\[[^\]]*\]\s*/g, ''); // #[SensitiveParameter]
169
+ // C# [FromBody] attributes (in Swift `[Character]` is an array type, not an attribute).
170
+ if (language !== 'swift') raw = raw.replace(/\[\w+(?:\([^)]*\))?\]\s*/g, '');
108
171
  const parts = [];
109
172
  let depth = 0, cur = '';
110
173
  for (const ch of raw) {
@@ -124,6 +187,23 @@ function parseParams(raw, language) {
124
187
  continue;
125
188
  }
126
189
  let name = p, type = null, m;
190
+ if (language === 'c' || language === 'cpp') {
191
+ const q = p.replace(/\[[^\]]*\]/g, '[]').replace(/\s+/g, ' ').trim();
192
+ if (/^(?:void|\.\.\.)$/.test(q)) continue;
193
+ const fp = q.match(/\(\s*[*&^]\s*(\w+)\s*\)\s*\(/); // a function pointer: int (*compare)(int, int)
194
+ if (fp) { out.push({ name: fp[1], type: 'function' }); continue; }
195
+ const cm = q.match(/^(.*[\s*&])(\w+)(\[\])?$/);
196
+ if (!cm) { if (/^[a-z_]\w*$/.test(q) && !C_TYPE_WORDS.test(q)) out.push({ name: q, type: null }); continue; } // unnamed parameters have only a type
197
+ if (/^(?:const|struct|enum|union|unsigned|signed)?\s*$/.test(cm[1])) { if (!C_TYPE_WORDS.test(cm[2])) out.push({ name: cm[2], type: null }); continue; }
198
+ out.push({ name: cm[2], type: cType(cm[1] + (cm[3] ? '[]' : '')) });
199
+ continue;
200
+ }
201
+ if (language === 'swift') {
202
+ const q = p.replace(/@\w+(?:\([^)]*\))?\s*/g, '').trim();
203
+ const sm = q.match(/^(?:(\w+)\s+)?(\w+)\s*:\s*(.+)$/);
204
+ if (sm) out.push({ name: sm[2], type: simpleType(sm[3].replace(/^(?:inout|borrowing|consuming|sending)\s+/, '').replace(/\.\.\.$/, '').trim()) });
205
+ continue;
206
+ }
127
207
  if (language === 'go') {
128
208
  m = p.match(/^(\w+)\s+(.+)$/);
129
209
  if (!m) { pendingGo.push(p); continue; }
@@ -169,11 +249,23 @@ function balancedReturnHead(after) {
169
249
  return m;
170
250
  }
171
251
 
252
+ /** Type words that are never a C parameter's name (an unnamed parameter is only its type). */
253
+ const C_TYPE_WORDS = /^(?:void|int|char|short|long|float|double|bool|_Bool|unsigned|signed|size_t|ssize_t|u?int\d+_t|wchar_t|auto|const)$/;
254
+ /** A C or C++ parameter type in reader terms: numbers, text, yes/no, or the type itself (`Library*`, `Book`). */
255
+ function cType(raw) {
256
+ let t = String(raw).replace(/\b(?:const|volatile|struct|enum|union|register|restrict|__restrict|typename|class)\b/g, ' ').replace(/\bstd::/g, '').replace(/\s+/g, ' ').trim();
257
+ if (/^(?:unsigned|signed)?\s*char\s*\*$|^(?:string|string_view|wstring|sds)\s*&?$/.test(t)) return 'string';
258
+ t = t.replace(/\s*([*&]+)\s*/g, '$1').replace(/&+$/, '').trim(); // a reference is the value itself
259
+ if (/^(?:(?:unsigned|signed|long|short)\s+)*(?:int|long|short|char|unsigned|signed)$|^(?:float|double|long double|size_t|ssize_t|off_t|ptrdiff_t|u?int\d+_t|u?int_fast\d+_t|intptr_t|uintptr_t|time_t)$/.test(t)) return 'number';
260
+ if (/^(?:bool|_Bool)$/.test(t)) return 'boolean';
261
+ return t || null;
262
+ }
263
+
172
264
  function simpleType(t) {
173
265
  if (!t) return null;
174
266
  const s = String(t).trim().replace(/^&(mut\s+)?/, '');
175
- 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';
176
- if (/^(bool|boolean|Boolean)$/.test(s)) return 'boolean';
267
+ 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|Int\d+|UInt\d*|CGFloat|Float\d+)$/.test(s)) return 'number';
268
+ if (/^(bool|boolean|Boolean|Bool)$/.test(s)) return 'boolean';
177
269
  if (/^(str|string|String|&str|char)$/.test(s)) return 'string';
178
270
  return s;
179
271
  }
@@ -219,6 +311,8 @@ function findFunctions(src, language) {
219
311
  return fns;
220
312
  }
221
313
  if (language === 'ruby') return findRubyFunctions(src);
314
+ if (language === 'c' || language === 'cpp') return findCFunctions(src, language);
315
+ if (language === 'swift') return findSwiftFunctions(src);
222
316
  const patterns = {
223
317
  typescript: [
224
318
  /(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*(\w+)\s*(?:<[^>]*>)?\s*\(/g,
@@ -250,7 +344,9 @@ function findFunctions(src, language) {
250
344
  // the body's "{" is the one after the type, not a brace inside it.
251
345
  const typed = (language === 'typescript' || language === 'javascript') ? balancedReturnHead(after) : null;
252
346
  const head = typed ?? (language === 'kotlin'
253
- ? after.match(/^\s*(?::\s*([^{=]+?))?()()\s*(?:where\s+[^{=]+)?(=(?![=>])|\{)/)
347
+ // (The return type stays on the signature's line: an abstract `fun f(): T` with no body never runs on into
348
+ // the next declarations.)
349
+ ? after.match(/^\s*(?::\s*([^{=\n]+?))?()()\s*(?:where\s+[^{=]+)?(=(?![=>])|\{)/)
254
350
  : after.match(/^\s*(?::\s*([^{=;]+?)|->\s*([^{;]+?)|\s+(\([^)]*\)|[\w.<>\[\]*&' ]+?))?\s*(?:throws\s+[\w.,\s]+)?\s*(=>|\{|;)/));
255
351
  if (!head || head[4] === ';') continue;
256
352
  // `const d = (await res.json()) as {...}` is a value, not a function: a const/let/var only declares a
@@ -273,7 +369,8 @@ function findFunctions(src, language) {
273
369
  const fnLine = lineAt(src, m.index + m[0].lastIndexOf(name));
274
370
  if (seen.has(name + ':' + fnLine)) continue;
275
371
  seen.add(name + ':' + fnLine);
276
- const returns = (head[1] || head[2] || head[3] || '').trim() || null;
372
+ // (A Rust `where` clause is a constraint on the types, not part of what comes back.)
373
+ const returns = (head[1] || head[2] || head[3] || '').replace(/\s+where\b[\s\S]*$/, '').trim() || null;
277
374
  const params = parseParams(src.slice(open + 1, close), language);
278
375
  const markerAt = close + 1 + head[0].length - head[4].length;
279
376
  if (head[4] === '=>') {
@@ -351,9 +448,510 @@ function findFunctions(src, language) {
351
448
  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 } });
352
449
  }
353
450
  }
451
+ if (language === 'typescript' || language === 'javascript') jsMoreFunctions(src, fns);
354
452
  annotateRoutes(fns, src);
355
453
  return fns.sort((a, b) => a.line - b.line);
356
454
  }
455
+
456
+ // ── JavaScript / TypeScript: functions that have no declaration of their own ─────────────────────────────
457
+ // `exports.x = function (…) {…}`, `res.json = function json(obj) {…}`, `Foo.prototype.bar = function`,
458
+ // `var app = function (req, res) {…}` inside another function, `{ key: function () {…} }`, and anonymous callbacks
459
+ // (`app.use(function (req, res, next) {…})`, `.then(function (x) {…})`, `items.forEach((x) => {…})`). Each is an item
460
+ // of its own, so a run, a stack frame, or a link can land on it. A one-line arrow (`(x) => x.id`) stays part of the
461
+ // step that uses it. Names: the name it is assigned to, else `<parent> › callback at line N`.
462
+
463
+ /** What the code just before a function says about it: assigned to `lhs`, a key of an object, or an argument. */
464
+ function jsContext(clean, at) {
465
+ // (Scanned backwards by hand: a regex anchored at the end of a long slice is slow on big files.)
466
+ const isSpace = (c) => c === ' ' || c === '\t' || c === '\n' || c === '\r';
467
+ let i = at - 1;
468
+ while (i >= 0 && isSpace(clean[i])) i--;
469
+ if (clean.slice(i - 4, i + 1) === 'async' && !/[\w$]/.test(clean[i - 5] || '')) { i -= 5; while (i >= 0 && isSpace(clean[i])) i--; }
470
+ let m;
471
+ if (clean[i] === '=' && !/[=!<>+\-*/%&|^?]/.test(clean[i - 1] || '')) {
472
+ const seg = clean.slice(Math.max(0, i - 160), i);
473
+ if ((m = seg.match(/(?:^|[^\w$.])(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]{1,120})?$/))) return { kind: 'assign', lhs: m[1], local: true };
474
+ if ((m = seg.match(/([A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]\n]{1,60}\])*)\s*$/))) return { kind: 'assign', lhs: m[1].replace(/\s+/g, '') };
475
+ }
476
+ if (clean[i] === ':' && (m = clean.slice(Math.max(0, i - 80), i).match(/(?:^|[{,\s])([A-Za-z_$][\w$]*|'[^'\n]+'|"[^"\n]+")\s*$/))) return { kind: 'key', key: m[1].replace(/^['"]|['"]$/g, '') };
477
+ // An argument: find the call it is passed to (the unmatched "(" before it) and that call's name.
478
+ let depth = 0;
479
+ for (i = at - 1; i >= Math.max(0, at - 3000); i--) {
480
+ const c = clean[i];
481
+ if (c === ')' || c === ']' || c === '}') depth++;
482
+ else if (c === '(' || c === '[' || c === '{') {
483
+ if (depth === 0) {
484
+ if (c !== '(') return { kind: 'arg', callee: null };
485
+ const name = clean.slice(Math.max(0, i - 120), i).match(/([A-Za-z_$][\w$]*(?:\s*\??\.\s*[A-Za-z_$][\w$]*)*)\s*$/);
486
+ const callee = name ? name[1].replace(/\s+/g, '').replace(/\?\./g, '.') : null;
487
+ // A call on the result of another call (`fetch(x).then(…)`) is named by its last part (`then`).
488
+ // `const save = useCallback(() => {…})`: a wrapper that only keeps the function gives it its name.
489
+ const kept = callee && WRAPS_FUNCTION.test(callee) && clean.slice(Math.max(0, i - name[0].length - 120), i - name[0].length).match(/(?:^|[^\w$.])(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]{1,80})?=\s*(?:await\s+)?$/);
490
+ return { kind: 'arg', callee, ...(kept ? { kept: kept[1] } : {}) };
491
+ }
492
+ depth--;
493
+ }
494
+ }
495
+ return { kind: 'arg', callee: null };
496
+ }
497
+
498
+ const WRAPS_FUNCTION = /^(?:React\.)?(?:useCallback|useMemo|memo|forwardRef|useEvent|useEffectEvent)$|^(?:_\.|lodash\.)?(?:debounce|throttle|once|memoize)$/;
499
+ const TEST_CALLS = /^(?:describe|it|test|context|suite|specify|before|after|beforeEach|afterEach|beforeAll|afterAll|setup|teardown|x?it|f?it|xdescribe|fdescribe|xtest|bench)(?:\.\w+)*$/;
500
+
501
+ function jsMoreFunctions(src, fns) {
502
+ const clean = stripCommentsKeepLayout(src);
503
+ const known = new Set(fns.map((f) => f.bodyStart));
504
+ const found = [];
505
+ const add = (fnIdx, paramsOpen, paramsClose, arrowParam, bo) => {
506
+ if (known.has(bo + 1)) return null;
507
+ const bc = matchClose(src, bo);
508
+ if (bc < 0) return null;
509
+ known.add(bo + 1);
510
+ const line = lineAt(src, fnIdx);
511
+ const params = arrowParam != null ? parseParams(arrowParam, 'typescript') : parseParams(src.slice(paramsOpen + 1, paramsClose), 'typescript');
512
+ const f = { key: `fn@${fnIdx}`, line, params, returns: null, bodyStart: bo + 1, body: src.slice(bo + 1, bc), at: fnIdx, end: bc };
513
+ found.push(f);
514
+ return f;
515
+ };
516
+ // `function (…) {` and `function name(…) {` (a named one was found already; this gives it its assignment).
517
+ const fnRe = /(?<![\w$.])function\b\s*\*?\s*([A-Za-z_$][\w$]*)?\s*(?:<[^>()]*>)?\s*\(/g;
518
+ let m;
519
+ while ((m = fnRe.exec(clean))) {
520
+ const open = m.index + m[0].length - 1;
521
+ const close = matchClose(src, open);
522
+ if (close < 0) continue;
523
+ const after = clean.slice(close + 1, close + 400);
524
+ const typed = balancedReturnHead(after);
525
+ const head = typed ? typed[0] : (after.match(/^\s*\{/) || [''])[0];
526
+ if (!head.endsWith('{')) continue;
527
+ const bo = close + head.length;
528
+ const ctx = jsContext(clean, m.index);
529
+ if (m[1]) {
530
+ // Named: already an item; record what it is assigned to (`res.json = function json`, `Foo.prototype.bar = function bar`).
531
+ const f = fns.find((x) => x.bodyStart === bo + 1);
532
+ if (f && ctx.kind === 'assign' && !ctx.local) f.assignedTo = ctx.lhs;
533
+ continue;
534
+ }
535
+ const f = add(m.index, open, close, null, bo);
536
+ if (f) f.ctx = ctx;
537
+ }
538
+ // Arrow functions with a block body: `(req, res) => {`, `async x => {`.
539
+ const arrowRe = /=>\s*\{/g;
540
+ while ((m = arrowRe.exec(clean))) {
541
+ const bo = m.index + m[0].length - 1;
542
+ if (known.has(bo + 1)) continue;
543
+ // The parameters: `(…)` (with an optional `: Type` after it) or one bare name, just before the arrow.
544
+ let j = m.index - 1;
545
+ while (j >= 0 && /\s/.test(clean[j])) j--;
546
+ let start, paramText = null, pOpen = -1, pClose = -1;
547
+ if (clean[j] === ')' || /[\w$>\]]/.test(clean[j])) {
548
+ // Skip a return type: `(a: number): Promise<X> =>` — walk back to the ")" that closes the parameters.
549
+ let k = j;
550
+ if (clean[j] !== ')') {
551
+ const bare = clean.slice(Math.max(0, j - 80), j + 1).match(/([A-Za-z_$][\w$]*)$/);
552
+ const beforeBare = bare ? clean.slice(Math.max(0, j - bare[1].length - 40), j - bare[1].length + 1).replace(/\s+$/, '') : '';
553
+ if (bare && !/:$/.test(beforeBare) && clean[j] !== '>' && clean[j] !== ']') { start = j - bare[1].length + 1; paramText = bare[1]; }
554
+ else {
555
+ // A typed return: find the ":" at depth 0 going back, then the ")".
556
+ let d = 0;
557
+ for (k = j; k >= Math.max(0, j - 300); k--) {
558
+ const c = clean[k];
559
+ if (c === '>' || c === ']' || c === ')' || c === '}') d++;
560
+ else if (c === '<' || c === '[' || c === '(' || c === '{') d--;
561
+ else if (c === ':' && d === 0) break;
562
+ }
563
+ k--; while (k >= 0 && /\s/.test(clean[k])) k--;
564
+ if (clean[k] !== ')') continue;
565
+ }
566
+ }
567
+ if (paramText == null) {
568
+ let d = 0;
569
+ for (pClose = k; k >= Math.max(0, pClose - 2000); k--) {
570
+ if (clean[k] === ')') d++;
571
+ else if (clean[k] === '(' && --d === 0) break;
572
+ }
573
+ if (d !== 0 || k < 0) continue;
574
+ pOpen = k; start = k;
575
+ }
576
+ } else continue;
577
+ // `async` and type parameters (`<T,>(x: T) =>`) belong to the function.
578
+ let s = start;
579
+ const lead = clean.slice(Math.max(0, s - 60), s).match(/(?:\basync\s*)?(?:<[^<>()]*>\s*)?$/);
580
+ if (lead) s -= lead[0].length;
581
+ // A call written `fn(x) => {` is not an arrow function's parameters: the "(" must not follow a name.
582
+ if (pOpen >= 0) { const prev = clean.slice(Math.max(0, s - 40), s).replace(/\s+$/, ''); if (/[\w$]$/.test(prev) && !/\b(?:async|return|await|yield|default|in|of|case)$/.test(prev)) continue; }
583
+ const ctx = jsContext(clean, s);
584
+ // `const f = (…) => {` is already an item (found with its name).
585
+ if (ctx.kind === 'assign' && ctx.local && fns.some((x) => x.name === ctx.lhs && x.line === lineAt(src, s))) continue;
586
+ const f = add(s, pOpen, pClose, paramText, bo);
587
+ if (f) f.ctx = ctx;
588
+ }
589
+ if (!found.length) return;
590
+ // A test's body (`describe(…, function () {…})`, `it(…, () => {…})`) is a test, not part of the app: it and every
591
+ // function written inside it stay out (tests are listed as tests).
592
+ const tests = found.filter((f) => f.ctx.kind === 'arg' && TEST_CALLS.test(f.ctx.callee ?? ''));
593
+ if (tests.length) {
594
+ const inTest = (f) => tests.some((t) => t === f || (t.bodyStart <= f.at && f.at <= t.end));
595
+ for (let i = found.length - 1; i >= 0; i--) if (inTest(found[i])) found.splice(i, 1);
596
+ }
597
+ // Names. Every function's range, so a callback is named after the function it is written in.
598
+ const ranges = [...fns, ...found].filter((x) => x.bodyStart != null).map((x) => ({ x, from: x.bodyStart, to: x.end ?? x.bodyStart + (x.body?.length ?? 0) }));
599
+ const parentOf = (f) => {
600
+ let best = null;
601
+ for (const r of ranges) if (r.x !== f && r.x.name && !r.x.callback && r.from <= f.at && f.at <= r.to && (!best || r.from > best.from)) best = r;
602
+ return best?.x ?? null;
603
+ };
604
+ for (const f of found) {
605
+ const ctx = f.ctx;
606
+ if (ctx.kind === 'assign' && !/\]$/.test(ctx.lhs)) {
607
+ const seg = ctx.lhs.split('.').pop();
608
+ f.name = seg;
609
+ if (!ctx.local) f.assignedTo = ctx.lhs;
610
+ } else if (ctx.kind === 'key') f.name = ctx.key;
611
+ else if (ctx.kept) f.name = ctx.kept;
612
+ else f.callback = true;
613
+ }
614
+ // Callbacks are named once every assigned function has its name (a callback inside `exports.x = function` is "x › …").
615
+ for (const f of found) {
616
+ if (!f.callback) continue;
617
+ const parent = parentOf(f);
618
+ const via = f.ctx.kind === 'arg' && f.ctx.callee ? f.ctx.callee : f.ctx.kind === 'assign' ? f.ctx.lhs : null;
619
+ f.name = `${parent?.name ?? via ?? 'function'} › callback at line ${f.line}`;
620
+ if (via) f.passedTo = via;
621
+ }
622
+ for (const f of found) { delete f.ctx; delete f.at; fns.push(f); }
623
+ }
624
+
625
+ // ── C, C++, and Swift: function definitions ──────────────────────────────────────────────────────────
626
+
627
+ /** C/C++ with every preprocessor line (and its `\` continuations) blanked to spaces, so offsets and lines stay put. */
628
+ export function blankPreprocessor(src) {
629
+ const lines = String(src).split('\n');
630
+ let cont = false;
631
+ for (let i = 0; i < lines.length; i++) {
632
+ const l = lines[i];
633
+ if (!cont && !/^[ \t]*#/.test(l)) continue;
634
+ cont = /\\\r?$/.test(l);
635
+ lines[i] = ' '.repeat(l.length);
636
+ }
637
+ return lines.join('\n');
638
+ }
639
+
640
+ /**
641
+ * The source with comments and the inside of strings and chars blanked (same length, same lines), so brackets can be
642
+ * counted without being fooled by a `{` in a string. Handles C++ raw strings R"x(…)x" and triple-quoted strings.
643
+ */
644
+ function maskCode(src) {
645
+ const a = String(src).split('');
646
+ const n = a.length;
647
+ const blank = (from, to) => { for (let k = from; k < to && k < n; k++) if (a[k] !== '\n') a[k] = ' '; };
648
+ for (let i = 0; i < n; i++) {
649
+ const c = a[i];
650
+ if (c === '/' && a[i + 1] === '/') { let j = i; while (j < n && a[j] !== '\n') j++; blank(i, j); i = j; continue; }
651
+ if (c === '/' && a[i + 1] === '*') { let j = i + 2; while (j < n && !(a[j] === '*' && a[j + 1] === '/')) j++; blank(i, j + 2); i = j + 1; continue; }
652
+ if (c === '"' && a[i + 1] === '"' && a[i + 2] === '"') { const e = src.indexOf('"""', i + 3); const end = e < 0 ? n : e; blank(i + 3, end); i = end + 2; continue; }
653
+ if (c === '"' && a[i - 1] === 'R' && /(?:^|[^\w])(?:u8|u|U|L)?R$/.test(src.slice(Math.max(0, i - 4), i))) {
654
+ const paren = src.indexOf('(', i);
655
+ const delim = paren > i && paren - i < 18 ? src.slice(i + 1, paren) : null;
656
+ if (delim != null && /^[^\s()\\]*$/.test(delim)) {
657
+ const e = src.indexOf(`)${delim}"`, paren);
658
+ const end = e < 0 ? n : e;
659
+ blank(i + 1, end + delim.length + 1);
660
+ i = end + delim.length + 1;
661
+ continue;
662
+ }
663
+ }
664
+ if (c === '"' || c === "'") {
665
+ let j = i + 1;
666
+ for (; j < n; j++) {
667
+ if (a[j] === '\\') { if (a[j + 1] !== '\n') a[j + 1] = ' '; a[j] = ' '; j++; continue; }
668
+ if (a[j] === c || a[j] === '\n') break;
669
+ a[j] = ' ';
670
+ }
671
+ i = j;
672
+ }
673
+ }
674
+ return a.join('');
675
+ }
676
+
677
+ /** Index of the bracket closing the one at `open` in masked text (no strings or comments left to skip). */
678
+ function closeIn(masked, open) {
679
+ const o = masked[open], c = { '{': '}', '(': ')', '[': ']' }[o];
680
+ let depth = 0;
681
+ for (let i = open; i < masked.length; i++) {
682
+ if (masked[i] === o) depth++;
683
+ else if (masked[i] === c && --depth === 0) return i;
684
+ }
685
+ return -1;
686
+ }
687
+
688
+ /** Blank `name(…)` groups (balanced) in a header, keeping its length. */
689
+ function blankCalls(h, names) {
690
+ let out = h;
691
+ for (const m of h.matchAll(names)) {
692
+ const open = out.indexOf('(', m.index + m[0].length - 1);
693
+ if (open < 0) continue;
694
+ const close = closeIn(out, open);
695
+ if (close < 0) continue;
696
+ out = out.slice(0, m.index) + ' '.repeat(close + 1 - m.index) + out.slice(close + 1);
697
+ }
698
+ return out;
699
+ }
700
+
701
+ /** A C/C++ declaration header with access labels, templates, and attributes blanked (same length). */
702
+ function cleanCHeader(header) {
703
+ let h = header.replace(/(?<![\w:])(?:public|private|protected|signals|slots|Q_SIGNALS|Q_SLOTS)\s*:(?!:)/g, (m) => ' '.repeat(m.length));
704
+ // template <…> (angle brackets balanced) and [[attributes]].
705
+ for (let at = h.indexOf('template'); at >= 0; at = h.indexOf('template', at + 1)) {
706
+ if (/\w/.test(h[at - 1] || '') || /\w/.test(h[at + 8] || '')) continue;
707
+ let j = at + 8;
708
+ while (/\s/.test(h[j] || '')) j++;
709
+ if (h[j] !== '<') continue;
710
+ let depth = 0, k = j;
711
+ for (; k < h.length; k++) { if (h[k] === '<') depth++; else if (h[k] === '>' && --depth === 0) break; }
712
+ if (k >= h.length) break;
713
+ h = h.slice(0, at) + ' '.repeat(k + 1 - at) + h.slice(k + 1);
714
+ }
715
+ for (let at = h.indexOf('[['); at >= 0; at = h.indexOf('[[', at + 2)) {
716
+ const e = h.indexOf(']]', at);
717
+ if (e < 0) break;
718
+ h = h.slice(0, at) + ' '.repeat(e + 2 - at) + h.slice(e + 2);
719
+ }
720
+ return blankCalls(h, /\b(?:__attribute__|__declspec|alignas|_Alignas|__THROW_?\w*|__nonnull|__wur)\s*\(/g);
721
+ }
722
+
723
+ const C_NOT_NAMES = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'sizeof', 'else', 'do', 'case', 'defined', 'alignof', 'decltype', 'static_assert', '_Static_assert', 'typeof', '__typeof__', 'asm', '__asm__', 'new', 'delete', 'throw', 'noexcept', 'requires', 'operator', 'using', 'typedef', 'goto']);
724
+ const C_STORAGE = /\b(?:static|inline|extern|virtual|explicit|constexpr|consteval|constinit|friend|__inline|__inline__|__forceinline|register|thread_local|_Noreturn|_Thread_local)\b/g;
725
+
726
+ /** After a parameter list: const, noexcept, override, `-> type`, macros, or a constructor's `: init(…)` list. */
727
+ function cSuffixOk(s, language) {
728
+ let i = 0;
729
+ const n = s.length;
730
+ const skipParens = () => { if (s[i] === '(') { const c = closeIn(s, i); i = c < 0 ? n : c + 1; } };
731
+ for (let guard = 0; guard < 40; guard++) {
732
+ while (i < n && /\s/.test(s[i])) i++;
733
+ if (i >= n) return true;
734
+ const rest = s.slice(i, i + 40);
735
+ let m;
736
+ if ((m = rest.match(/^(?:const|volatile|override|final|mutable|noexcept|throw|try|&&|&)(?!\w)/))) { i += m[0].length; while (/\s/.test(s[i] || '')) i++; skipParens(); continue; }
737
+ if (s[i] === '-' && s[i + 1] === '>') return language === 'cpp'; // a trailing return type runs to the body
738
+ if (s[i] === ':' && s[i + 1] !== ':') return language === 'cpp'; // a constructor's member initializer list
739
+ if ((m = rest.match(/^requires\b/))) return language === 'cpp';
740
+ if ((m = rest.match(/^[A-Z_][A-Z0-9_]*(?!\w)/))) { i += m[0].length; while (/\s/.test(s[i] || '')) i++; skipParens(); continue; } // FMT_NOEXCEPT, __THROW
741
+ return false;
742
+ }
743
+ return false;
744
+ }
745
+
746
+ /**
747
+ * What a C/C++ function gives back, from the text before its name and the text after its parameters: macros in front
748
+ * of the type (`FMT_CONSTEXPR void`, `JSON_HEDLEY_ALWAYS_INLINE std::size_t`) are not part of it, `void` is nothing,
749
+ * and `auto f() -> T` gives back T.
750
+ */
751
+ function cReturnType(prefix, after) {
752
+ const toks = String(prefix || '').trim().split(/\s+/).filter(Boolean);
753
+ // A leading all-caps word is a macro when a real type follows it (`FILE *` keeps FILE: only `*` follows).
754
+ while (toks.length > 1 && /^[A-Z_][A-Z0-9_]*$/.test(toks[0]) && toks.slice(1).some((t) => /[A-Za-z_]/.test(t))) toks.shift();
755
+ let t = toks.join(' ');
756
+ if (/^auto$/.test(t)) {
757
+ const tr = String(after || '').match(/->\s*([^{;]+?)\s*(?:requires\b[^{;]*)?$/);
758
+ const trail = tr ? tr[1].replace(/\s+/g, ' ').trim() : '';
759
+ if (trail && !/^decltype\b/.test(trail)) t = trail;
760
+ }
761
+ return t && !/^void$/.test(t) && !/^[A-Z_][A-Z0-9_]*$/.test(t) || /^[A-Z][A-Z0-9]*$/.test(t) ? t : null;
762
+ }
763
+
764
+ /** A function definition head (the text before a `{` at file, namespace, or class level), or null. */
765
+ function cHead(header, language, container) {
766
+ const h = cleanCHeader(header);
767
+ const start = h.search(/\S/);
768
+ if (start < 0) return null;
769
+ let depth = 0;
770
+ for (let o = 0; o < h.length; o++) {
771
+ if (h[o] === ')') { depth--; continue; }
772
+ if (h[o] !== '(') continue;
773
+ if (depth++ !== 0) continue;
774
+ const c = closeIn(h, o);
775
+ if (c < 0) return null;
776
+ const before = h.slice(Math.max(0, o - 300), o);
777
+ const nm = before.match(/((?:[A-Za-z_]\w*(?:<[^<>()]*>)?\s*::\s*)*)(operator\s*(?:\(\s*\)|\[\s*\]|new\b|delete\b|[^\s\w()]+|[A-Za-z_][\w:<> ]*?)|~?[A-Za-z_]\w*)\s*$/);
778
+ if (!nm || C_NOT_NAMES.has(nm[2]) || !cSuffixOk(h.slice(c + 1), language)) { o = c; depth--; continue; }
779
+ const nameAt = o - nm[0].length + nm[1].length;
780
+ const prefix = blankCalls(h.slice(start, o - nm[0].length), /\b[A-Z_][A-Z0-9_]*\s*\(/g);
781
+ if (!/^[\w\s*&:<>,"~]*$/.test(prefix) || /(?:^|\s)(?:return|else|case|goto|new|delete|throw|typedef|using|co_return|co_await|co_yield|sizeof)\s*$/.test(prefix)) return null;
782
+ const qualifier = nm[1] ? nm[1].replace(/<[^<>]*>/g, '').split('::').map((x) => x.trim()).filter(Boolean).pop() : null;
783
+ const name = nm[2].replace(/\s+/g, ' ').trim();
784
+ const returns = prefix.replace(C_STORAGE, ' ').replace(/""/g, ' ').replace(/\s+/g, ' ').trim();
785
+ if (!returns && language === 'c') return null;
786
+ // No return type: only a constructor or destructor has none (`TEST(A, B) {` is a macro, not a function).
787
+ const ctor = /^~/.test(name) || (qualifier && qualifier === name.replace(/^~/, '')) || (container && container === name.replace(/^~/, ''));
788
+ if (!returns && !ctor) return null;
789
+ return { name, nameAt, open: o, close: c, returns: ctor ? null : cReturnType(returns, h.slice(c + 1)), qualifier, startAt: start };
790
+ }
791
+ return null;
792
+ }
793
+
794
+ /** A class, struct, union, namespace, or extern "C" header whose braces hold more declarations. Gives its name ('' if none) or null. */
795
+ function cContainer(header) {
796
+ let h = cleanCHeader(header);
797
+ for (let k = 0; k < 6 && /<[^<>]*>/.test(h); k++) h = h.replace(/<[^<>]*>/g, ' ');
798
+ // A macro may stand in front of the class (NLOHMANN_BASIC_JSON_TPL_DECLARATION class basic_json, FMT_EXPORT class …).
799
+ h = h.trim().replace(/^(?:[A-Z_][A-Z0-9_]*(?:\s*\([^()]*\))?\s+)+(?=(?:typedef\s+)?(?:class|struct|union|namespace|inline\s+namespace|extern)\b)/, '');
800
+ if (/^extern\s*""$/.test(h)) return '';
801
+ if (/^(?:inline\s+)?namespace\b[^()=;]*$/.test(h)) return '';
802
+ const m = h.match(/^(?:typedef\s+)?(?:class|struct|union)\b([^()=;]*)$/);
803
+ if (!m) return null;
804
+ const names = (m[1].split(/:(?!:)/)[0].match(/[A-Za-z_]\w*/g) || []).filter((w) => w !== 'final');
805
+ return names[names.length - 1] || '';
806
+ }
807
+
808
+ /** Lines that can carry the start of a C signature above the name: a return type, a template, a macro. */
809
+ const C_SIG_LINE = /^\s*[\w<>:,*&\s]+$/;
810
+
811
+ /** C and C++ function definitions, found by walking scopes: file, namespaces, extern "C", classes and structs. */
812
+ function findCFunctions(code, language) {
813
+ const masked = maskCode(code);
814
+ const lines = code.split('\n');
815
+ const fns = [];
816
+ const stack = [];
817
+ let stmtStart = 0;
818
+ for (let i = 0; i < masked.length; i++) {
819
+ const ch = masked[i];
820
+ if (ch === ';') { stmtStart = i + 1; continue; }
821
+ if (ch === '}') { stack.pop(); stmtStart = i + 1; continue; }
822
+ if (ch !== '{') continue;
823
+ // Comments and #lines are blank in the mask: a header starts at its first real character (a long license
824
+ // comment above the first function must not make its header look too long to be one).
825
+ while (stmtStart < i && /\s/.test(masked[stmtStart])) stmtStart++;
826
+ const header = masked.slice(stmtStart, i);
827
+ const close = closeIn(masked, i);
828
+ const head = header.length < 4000 ? cHead(header, language, stack[stack.length - 1]) : null;
829
+ if (head && close > 0) {
830
+ const nameAt = stmtStart + head.nameAt;
831
+ const fnLine = lineAt(code, nameAt);
832
+ // The doc comment sits above the whole signature: a return type or template may be on the lines above the name.
833
+ let docLine = fnLine;
834
+ for (let k = 0; k < 3 && docLine >= 2 && lineAt(code, stmtStart + head.startAt) < docLine && C_SIG_LINE.test(lines[docLine - 2]) && lines[docLine - 2].trim(); k++) docLine--;
835
+ const doc = leadingDoc(lines, docLine, language);
836
+ fns.push({
837
+ key: `${head.name}@${nameAt}`, name: head.name, line: fnLine,
838
+ params: parseParams(code.slice(stmtStart + head.open + 1, stmtStart + head.close), language),
839
+ returns: head.returns ? cType(head.returns) : null, bodyStart: i + 1, body: code.slice(i + 1, close),
840
+ ...(head.qualifier ? { qualifier: head.qualifier } : {}), ...(doc ? { doc } : {}),
841
+ });
842
+ i = close; stmtStart = close + 1;
843
+ continue;
844
+ }
845
+ const container = cContainer(header);
846
+ if (container != null) { stack.push(container); stmtStart = i + 1; continue; }
847
+ if (close < 0) break;
848
+ i = close; // an initializer, an enum, a lambda: braces that hold no functions
849
+ }
850
+ return fns;
851
+ }
852
+
853
+ /** After a Swift parameter list: async, throws, `-> Type`, `where …`, then the body's `{`. Null for a bodiless requirement. */
854
+ function swiftHead(after) {
855
+ const brace = after.indexOf('{');
856
+ if (brace < 0) return null;
857
+ const mid = after.slice(0, brace);
858
+ if (/[;}=]/.test(mid.replace(/->/g, '')) || /\n\s*(?:@|func\b|var\b|let\b|case\b|init\b|deinit\b|static\b|class\b|struct\b|enum\b|public\b|private\b|internal\b|fileprivate\b|open\b|mutating\b|override\b|subscript\b|typealias\b|associatedtype\b|convenience\b|required\b|final\b|#)/.test(mid)) return null;
859
+ let rest = mid.replace(/^\s*(?:async\s+)?(?:(?:re)?throws(?:\s*\([^)]*\))?\s*)?(?:async\s+)?/, '');
860
+ let returns = null;
861
+ if (/^->/.test(rest)) {
862
+ rest = rest.slice(2);
863
+ const where = rest.search(/\bwhere\b/);
864
+ returns = (where < 0 ? rest : rest.slice(0, where)).trim() || null;
865
+ } else if (rest.trim() && !/^where\b/.test(rest.trim())) return null;
866
+ return { returns, brace };
867
+ }
868
+
869
+
870
+ /** Swift functions: func, init, computed properties, and Vapor route closures (`app.get("orders", ":id") { req in … }`). */
871
+ function findSwiftFunctions(src) {
872
+ const masked = maskCode(src);
873
+ const fns = [];
874
+ // extension Library { … }: the methods inside belong to Library, though they are written outside the type.
875
+ const exts = [];
876
+ for (const m of masked.matchAll(/(?:^|[\s;}])extension[ \t]+([\w.]+)[^{\n]*\{/g)) {
877
+ const open = m.index + m[0].length - 1, close = closeIn(masked, open);
878
+ if (close > 0) exts.push([open, close, m[1].split('.').pop()]);
879
+ }
880
+ const extOf = (at) => exts.find(([a, b]) => at > a && at < b)?.[2] ?? null;
881
+ const bodies = [];
882
+ const push = (fn, open, close) => { fns.push({ ...fn, bodyStart: open + 1, body: src.slice(open + 1, close) }); bodies.push([open, close]); };
883
+ for (const m of masked.matchAll(/(?:^|[^\w.])(?:func[ \t]+([A-Za-z_]\w*|`\w+`|[^\s(<\w`]+)|(init)[?!]?|(subscript))[ \t]*(?:<[^>{}()]*>)?[ \t]*\(/g)) {
884
+ const name = (m[1] || m[2] || m[3]).replace(/`/g, '');
885
+ const open = m.index + m[0].length - 1;
886
+ const close = closeIn(masked, open);
887
+ if (close < 0) continue;
888
+ const head = swiftHead(masked.slice(close + 1, close + 1 + 2000));
889
+ if (!head) continue;
890
+ const bo = close + 1 + head.brace, bc = closeIn(masked, bo);
891
+ if (bc < 0) continue;
892
+ const nameAt = m.index + m[0].indexOf(m[1] || m[2] || m[3]);
893
+ const qualifier = extOf(m.index);
894
+ // A subscript with get { … } set { … }: what it gives back is its getter.
895
+ const getter = name === 'subscript' ? masked.slice(bo + 1, bc).match(/^\s*get\s*\{/) : null;
896
+ if (getter) { const go = bo + 1 + getter[0].length - 1, gc = closeIn(masked, go); if (gc > 0) { push({ key: `${name}@${nameAt}`, name, line: lineAt(src, nameAt), params: parseParams(src.slice(open + 1, close), 'swift'), returns: head.returns, ...(qualifier ? { qualifier } : {}) }, go, gc); continue; } }
897
+ push({ key: `${name}@${nameAt}`, name, line: lineAt(src, nameAt), params: parseParams(src.slice(open + 1, close), 'swift'), returns: head.returns, ...(qualifier ? { qualifier } : {}) }, bo, bc);
898
+ }
899
+ // Computed properties read like a function with no inputs: var total: Int { … } (or its get { … }).
900
+ for (const m of masked.matchAll(/(?:^|[\s;{}])(?:@\w+(?:\([^()\n]*\))?[ \t]+)*(?:(?:public|private|internal|fileprivate|open|static|class|override|final|nonisolated)(?:\(set\))?[ \t]+)*var[ \t]+(\w+)[ \t]*:[ \t]*([^={}\n]+)\{/g)) {
901
+ let open = m.index + m[0].length - 1;
902
+ let close = closeIn(masked, open);
903
+ if (close < 0 || bodies.some(([a, b]) => open > a && open < b)) continue;
904
+ const inner = masked.slice(open + 1, close).trim();
905
+ if (/^(?:willSet|didSet|set|_read|_modify)\b/.test(inner) || /^get\s*(?:set\s*)?$|^get\s+(?:async|throws)/.test(inner)) continue;
906
+ const g = masked.slice(open + 1, close).match(/^\s*get\s*\{/);
907
+ if (g) { open = open + 1 + g[0].length - 1; close = closeIn(masked, open); if (close < 0) continue; }
908
+ const nameAt = masked.indexOf(m[1], m.index + m[0].lastIndexOf('var') + 3);
909
+ const qualifier = extOf(m.index);
910
+ push({ key: `${m[1]}@${nameAt}`, name: m[1], line: lineAt(src, nameAt), params: [], returns: m[2].trim(), computed: true, ...(qualifier ? { qualifier } : {}) }, open, close);
911
+ }
912
+ // Vapor routes. Literal path pieces only; grouped(...) prefixes are followed when they are literal too.
913
+ const literalPath = (args) => {
914
+ const pieces = [];
915
+ for (const raw of splitTop(args, ',').map((x) => x.trim()).filter(Boolean)) {
916
+ if (/^\w+\s*:/.test(raw)) continue; // named arguments (use:, body:)
917
+ let m;
918
+ if ((m = raw.match(/^"([^"\\]*)"$/))) pieces.push(m[1].replace(/^\/+|\/+$/g, ''));
919
+ else if (raw === '.catchall' || raw === '"**"') pieces.push('**');
920
+ else if (raw === '.anything') pieces.push('*');
921
+ else if (/^\.(?:GET|POST|PUT|PATCH|DELETE)$/.test(raw)) continue;
922
+ else return null;
923
+ }
924
+ return pieces.filter(Boolean).join('/');
925
+ };
926
+ const groups = new Map();
927
+ for (const m of src.matchAll(/\blet[ \t]+(\w+)[ \t]*=[ \t]*(\w+)\.grouped\(([^()\n]*)\)/g)) groups.set(m[1], { parent: m[2], path: literalPath(m[3]) });
928
+ const prefixOf = (v, depth = 0) => { const g = groups.get(v); if (!g || g.path == null || depth > 6) return g ? null : ''; const up = prefixOf(g.parent, depth + 1); return up == null ? null : [up, g.path].filter(Boolean).join('/'); };
929
+ const routeFor = new Map();
930
+ for (const m of masked.matchAll(/\b(\w+)\.(get|post|put|patch|delete|on)\(([^()]*?)\buse:[ \t]*(?:self\.)?(\w+)[ \t]*\)/g)) {
931
+ if (!(groups.has(m[1]) || /^(?:app|routes?|router|r|api|v\d+|\w*(?:[Rr]outes?|[Gg]roup|[Rr]outer))$/.test(m[1]))) continue;
932
+ const args = src.slice(m.index + m[0].indexOf('(') + 1, m.index + m[0].length - 1);
933
+ const method = m[2] === 'on' ? (args.match(/\.(GET|POST|PUT|PATCH|DELETE)\b/) || [])[1] : m[2].toUpperCase();
934
+ const path = literalPath(args.replace(/\buse:[\s\S]*$/, '')), prefix = prefixOf(m[1]);
935
+ if (method && path != null && prefix != null) routeFor.set(m[4], { method, path: `/${[prefix, path].filter(Boolean).join('/')}` });
936
+ }
937
+ for (const m of masked.matchAll(/\b(\w+)\.(get|post|put|patch|delete|on)\(([^()]*)\)[ \t]*\{/g)) {
938
+ const argsAt = m.index + m[0].indexOf('(') + 1;
939
+ const args = src.slice(argsAt, argsAt + m[3].length);
940
+ const method = m[2] === 'on' ? (args.match(/\.(GET|POST|PUT|PATCH|DELETE)\b/) || [])[1] : m[2].toUpperCase();
941
+ const path = literalPath(args), prefix = prefixOf(m[1]);
942
+ // Only a router registers routes (app, routes, a grouped(...) value): `cache.get("x") { … }` is a callback.
943
+ if (!method || path == null || prefix == null || !(groups.has(m[1]) || /^(?:app|routes?|router|r|api|v\d+|\w*(?:[Rr]outes?|[Gg]roup|[Rr]outer))$/.test(m[1]))) continue;
944
+ const bo = m.index + m[0].length - 1, bc = closeIn(masked, bo);
945
+ if (bc < 0) continue;
946
+ const params = src.slice(bo + 1, bc).match(SWIFT_CLOSURE_PARAMS);
947
+ if (!params) continue; // a route's handler always takes the request
948
+ const full = `/${[prefix, path].filter(Boolean).join('/')}`;
949
+ push({ name: `${method} ${full}`, line: lineAt(src, m.index), params: [], returns: null, route: { method, path: full } }, bo + params[0].length, bc);
950
+ }
951
+ for (const fn of fns) if (!fn.route && routeFor.has(fn.name)) fn.route = routeFor.get(fn.name);
952
+ return fns.sort((a, b) => a.line - b.line);
953
+ }
954
+
357
955
  // ── Labels, plumbing, and completeness: facts views need, so they never re-derive them ─────────────────
358
956
 
359
957
  /** A display name: late_fee -> "Late fee", deliveryFee -> "Delivery fee", __init__ -> "Init". */
@@ -364,6 +962,18 @@ export function displayLabel(name) {
364
962
 
365
963
  /** Inputs that are framework plumbing rather than something a person gives. */
366
964
  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;
965
+ /**
966
+ * Framework plumbing is left out of "You give it". A plain `Request` or `Response` (the fetch types, or a response
967
+ * a helper inspects) is plumbing only in a web handler: in `cancelBody(value: Response, keep?: Response)` or
968
+ * `streamRequest(request: Request, …)` it is the very thing the function works on.
969
+ */
970
+ function isPlumbing(p, params, fn) {
971
+ if (/^(self|this|cls)$/i.test(p.name)) return true;
972
+ const web = !!fn.route || params.some((x) => /^(?:req|res|reply|ctx|c|w|r|next)$/.test(x.name) || /HttpRequest|HttpResponse|ResponseWriter|NextFunction|HttpContext|ServerRequest|FastifyRequest|FastifyReply|NextRequest|HttpServletRequest/.test(String(x.type || '')));
973
+ const t = String(p.type || '');
974
+ if (/^(?:request|response)$/i.test(p.name) || (t && /^(?:Request|Response)(?:\s*\|.*)?$|\|\s*(?:Request|Response)\b/.test(t) && !/Http|Servlet|Fastify|Next/.test(t))) return web;
975
+ return t ? PLUMBING_TYPE.test(t) : PLUMBING.test(p.name);
976
+ }
367
977
  const PLUMBING_TYPE = /\b(Session|AsyncSession|DbContext|Connection|HttpRequest|HttpResponse|Request|Response|Context|ResponseWriter|CancellationToken|ILogger|Logger|NextFunction)\b/;
368
978
 
369
979
  const allSteps = (steps) => (steps || []).flatMap((s) => [s, ...allSteps(s.children), ...allSteps(s.otherwise), ...(s.handlers || []).flatMap((h) => allSteps(h.steps)), ...allSteps(s.always?.steps)]);
@@ -384,6 +994,8 @@ export function completenessOf(item) {
384
994
  const code = steps.filter((s) => s.kind === 'other').length;
385
995
  const restated = steps.filter((s) => s.restates).length;
386
996
  if (code) reasons.push(`${code} step${code === 1 ? '' : 's'} shown as code`);
997
+ const named = steps.filter((s) => s.unknownCommand).length;
998
+ if (named) reasons.push(`${named} command${named === 1 ? '' : 's'} only named, not explained`);
387
999
  if (restated) reasons.push(`${restated} step${restated === 1 ? '' : 's'} only restate the code`);
388
1000
  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`);
389
1001
  return { level: reasons.length ? 'partly explained' : 'explained', reasons };
@@ -482,13 +1094,20 @@ function leadingDoc(lines, fnLine, language) {
482
1094
  let k = fnLine - 2;
483
1095
  while (k >= 0 && /^\s*(@|#\[|\[[A-Z])/.test(lines[k])) k--; // annotations and attributes
484
1096
  if (k < 0) return null;
1097
+ // C and C++ document with plain block comments (/* … */) as often as with /** … */.
1098
+ if ((language === 'c' || language === 'cpp') && /\*\/\s*$/.test(lines[k])) {
1099
+ const end = k;
1100
+ while (k >= 0 && !/\/\*/.test(lines[k])) k--;
1101
+ if (k < 0 || !/^\s*\/\*/.test(lines[k])) return null; // a comment at the end of a line of code is not a doc
1102
+ return cleanDoc(lines.slice(k, end + 1).join('\n').replace(/^\s*\/\*+!?/, '').replace(/\*+\/\s*$/, ''));
1103
+ }
485
1104
  if (/\*\/\s*$/.test(lines[k])) {
486
1105
  const end = k;
487
1106
  while (k >= 0 && !/\/\*\*/.test(lines[k])) k--;
488
1107
  if (k < 0) return null;
489
1108
  return cleanDoc(lines.slice(k, end + 1).join('\n').replace(/^\s*\/\*\*/, '').replace(/\*\/\s*$/, ''));
490
1109
  }
491
- const lineDoc = language === 'go' ? /^\s*\/\/(?!\/)/ : language === 'ruby' ? /^\s*#(?![!{])/ : /^\s*\/\/\//;
1110
+ const lineDoc = language === 'go' || language === 'c' || language === 'cpp' ? /^\s*\/\/(?!\/)|^\s*\/\/\/(?!\/)/ : language === 'ruby' ? /^\s*#(?![!{])/ : /^\s*\/\/\//;
492
1111
  const got = [];
493
1112
  while (k >= 0 && lineDoc.test(lines[k])) got.unshift(lines[k--]);
494
1113
  return got.length ? cleanDoc(got.join('\n')) : null;
@@ -583,13 +1202,30 @@ function mapCode(src, fn) {
583
1202
 
584
1203
  /** PHP reads like the other brace languages once `$name` is `name` and `->` is `.` (line numbers unchanged). */
585
1204
  function normalizePhp(src) {
586
- return mapCode(src.replace(/(^|[^\[])#(?!\[)/gm, '$1//'), (code) => code
1205
+ return mapCode(phpHashComments(src), (code) => code
1206
+ // `.` is PHP's text join (`$a.$b`, `'x'.$y`); spaced, it can never be read as `a.b` (a property) below.
1207
+ .replace(/(?<![.\d])\.(?![.=\d])/g, ' . ')
587
1208
  .replace(/\$this\s*->/g, 'this.')
588
1209
  .replace(/\$(?=[A-Za-z_])/g, '')
589
1210
  .replace(/(\w|\))\s*(?:\?)?->\s*(?=[A-Za-z_])/g, '$1.')
590
1211
  .replace(/\belseif\b/g, 'else if'));
591
1212
  }
592
1213
 
1214
+ const stripRubyStrings = (t) => String(t).replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, 'Q');
1215
+
1216
+ /** PHP `# comment` as `// comment`, outside strings (a `#` inside '[^:/?#]' is text). Attributes `#[…]` stay. */
1217
+ function phpHashComments(src) {
1218
+ let out = '', last = 0;
1219
+ for (let i = 0; i < src.length; i++) {
1220
+ const c = src[i];
1221
+ if (c === '"' || c === "'") { i = skipString(src, i); continue; }
1222
+ if (c === '/' && src[i + 1] === '/') { const e = src.indexOf('\n', i); i = e < 0 ? src.length : e - 1; continue; }
1223
+ if (c === '/' && src[i + 1] === '*') { const e = src.indexOf('*/', i + 2); i = e < 0 ? src.length : e + 1; continue; }
1224
+ if (c === '#' && src[i + 1] !== '[') { out += `${src.slice(last, i)}//`; last = i + 1; const e = src.indexOf('\n', i); i = e < 0 ? src.length : e - 1; }
1225
+ }
1226
+ return out + src.slice(last);
1227
+ }
1228
+
593
1229
  /** Kotlin `if (c) A else if (c2) B else C` used as a value. Returns false when the text is not one. */
594
1230
  function readKotlinIf(text, inputs, rules, unread, line, setOtherwise) {
595
1231
  let s = text.trim().replace(/;$/, '');
@@ -727,7 +1363,7 @@ export function toThunderCondition(text, inputs = []) {
727
1363
  continue;
728
1364
  }
729
1365
  let path = t;
730
- while (toks[i + 1] === '.' && /^[A-Za-z_$]/.test(toks[i + 2] || '')) {
1366
+ while ((toks[i + 1] === '.' || toks[i + 1] === '->') && /^[A-Za-z_$]/.test(toks[i + 2] || '')) {
731
1367
  if (/^(equals|Equals)$/.test(toks[i + 2]) && toks[i + 3] === '(') break;
732
1368
  path += '.' + toks[i + 2];
733
1369
  i += 2;
@@ -757,10 +1393,12 @@ export function toThunderCondition(text, inputs = []) {
757
1393
  if (toks[i + 2] !== ')') return null;
758
1394
  i += 2;
759
1395
  }
760
- if (/^(null|nil|None|undefined)$/.test(path)) return null;
1396
+ if (/^(null|nil|None|undefined|NULL|nullptr)$/.test(path)) return null;
761
1397
  out.push(path);
762
1398
  continue;
763
1399
  }
1400
+ // Swift's implicit enum member: `status == .active` compares with the case `active`.
1401
+ if (t === '.' && /^[a-z_]\w*$/.test(next || '') && (!out.length || ['==', '!=', '(', 'and', 'or', 'not'].includes(out[out.length - 1]))) { out.push(next); i++; continue; }
764
1402
  return null;
765
1403
  }
766
1404
  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
@@ -791,9 +1429,11 @@ function splitArgs(toks) {
791
1429
  /** An answer a decision can return: a string, enum member, number, or boolean. Null otherwise. */
792
1430
  export function toThunderOutcome(text) {
793
1431
  let s = String(text).trim().replace(/;$/, '').trim();
1432
+ let m0;
794
1433
  s = s.replace(/^Ok\((.*)\)$/, '$1').replace(/\.(to_string|into|to_owned)\(\)$/, '').replace(/^String::from\((.*)\)$/, '$1').trim();
795
1434
  // Absence is not an answer: None/null/nil/undefined are "returns nothing", handled as guards.
796
- if (/^(None|null|nil|undefined|Nothing)$/.test(s)) return null;
1435
+ if (/^(None|null|nil|undefined|Nothing|NULL|nullptr)$/.test(s)) return null;
1436
+ if ((m0 = s.match(/^\.([a-z]\w*)$/))) return m0[1]; // Swift: return .premium
797
1437
  let m;
798
1438
  if ((m = s.match(/^"([^"\\]*)"$|^'([^'\\]*)'$|^`([^`$\\]*)`$/))) {
799
1439
  // "#{x}" (Ruby) and "$x" / "${x}" (Kotlin, PHP) build the text from values: computed, not fixed.
@@ -838,8 +1478,9 @@ export function terminatorEffect(stmt, language) {
838
1478
  const s = String(stmt).trim().replace(/;$/, '').trim();
839
1479
  let m;
840
1480
  if ((m = s.match(/^throw\s+new\s+([\w.$]+)\s*\(([\s\S]*)\)$/))) return { kind: 'fails', name: lastSeg(m[1]), detail: firstString(m[2]) };
841
- if ((m = s.match(/^throw\s+([\w.$]+)$/))) return { kind: 'fails', name: lastSeg(m[1]) };
842
- 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`
1481
+ if ((m = s.match(/^throw\s+([\w.$]+)$/))) return { kind: 'fails', name: /^[A-Z]\w*\.[a-z]\w*$/.test(m[1]) ? m[1] : lastSeg(m[1]) }; // Swift: throw LibraryError.full
1482
+ if ((m = s.match(/^throw\s+Abort\(\s*\.(\w+)/)) && VAPOR_STATUS[m[1]]) return { kind: 'responds', name: String(VAPOR_STATUS[m[1]]) }; // Vapor
1483
+ if ((m = s.match(/^throw\s+([A-Z][\w.$]*)\s*\(([\s\S]*)\)$/))) return { kind: 'fails', name: /^[A-Z]\w*\.[a-z]\w*$/.test(m[1]) ? m[1] : lastSeg(m[1]), detail: firstString(m[2]) }; // Kotlin and Swift: no `new`
843
1484
  if ((m = s.match(/^error\(([\s\S]*)\)$/)) && language === 'kotlin') return { kind: 'fails', name: 'IllegalStateException', detail: firstString(m[1]) };
844
1485
  if ((m = s.match(/^abort\(\s*(\d{3})\b/))) return { kind: 'responds', name: m[1] }; // Laravel
845
1486
  if ((m = s.match(/^raise\s+([\w.]+)(?:\(([\s\S]*)\))?$/))) return { kind: 'fails', name: lastSeg(m[1]), detail: m[2] ? firstString(m[2]) : null };
@@ -865,7 +1506,7 @@ export function terminatorEffect(stmt, language) {
865
1506
  if (/^Err[A-Z]\w*$/.test(last)) return { kind: 'fails', name: last };
866
1507
  if (parts.length === 1 && last === 'nil') return { kind: 'nothing' };
867
1508
  }
868
- if (/^(null|undefined|None|nil|void 0)$/.test(v)) return { kind: 'nothing' };
1509
+ if (/^(null|undefined|None|nil|void 0|NULL|nullptr)$/.test(v)) return { kind: 'nothing' };
869
1510
  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] };
870
1511
  if ((m = v.match(/^(BadRequest|Unauthorized|Forbid|Forbidden|NotFound|Conflict|UnprocessableEntity)\s*\(/))) return { kind: 'responds', name: m[1] };
871
1512
  const fixed = toThunderOutcome(v);
@@ -901,7 +1542,7 @@ function makeGuard(cond, branch, language, inputs, line) {
901
1542
  function splitIf(text, language) {
902
1543
  let rest = text.replace(/^if\b\s*/, '');
903
1544
  let cond, after;
904
- if (language === 'go' || language === 'rust' || rest[0] !== '(') {
1545
+ if (BARE_IF.has(language) || rest[0] !== '(') {
905
1546
  const b = findTopBrace(rest);
906
1547
  if (b < 0) return null;
907
1548
  cond = rest.slice(0, b).trim(); after = rest.slice(b);
@@ -955,9 +1596,24 @@ function valueLiteral(text) {
955
1596
  if (/^-?\d+(\.\d+)?$/.test(s)) return s;
956
1597
  if (/^(true|false|True|False)$/.test(s)) return s.toLowerCase();
957
1598
  if ((m = s.match(/^(?:[A-Za-z_]\w*(?:\.|::))*([A-Za-z_]\w*)$/))) return m[1];
1599
+ if ((m = s.match(/^\.([a-z_]\w*)$/))) return m[1]; // Swift: case .premium
958
1600
  return null;
959
1601
  }
960
1602
 
1603
+ /** A Swift one-expression body (an implicit return): not a declaration, an assignment, or a statement keyword. */
1604
+ function swiftImplicitValue(text) {
1605
+ const t = String(text).trim();
1606
+ return !!t && !/\n\s*\S/.test(t) && !/^(?:if|guard|for|while|switch|let|var|return|throw|defer|do|repeat|print|try|await)\b/.test(t) && !/^[\w.]+\s*(?:[-+*/]?=)(?!=)/.test(t) && !/^[\w.]+\s*\(/.test(t);
1607
+ }
1608
+
1609
+ /** A Swift one-statement body that gives back its value: the function returns something, and the statement is an expression. */
1610
+ function swiftImplicitResult(text, returns) {
1611
+ const r = String(returns || '').trim();
1612
+ if (!r || /^(?:Void|\(\s*\)|Never)$/.test(r)) return false;
1613
+ const t = String(text).trim();
1614
+ return !!t && !/^(?:if|guard|for|while|switch|let|var|return|throw|defer|do|repeat|fatalError|preconditionFailure|precondition|assert|assertionFailure|break|continue|case|default)\b/.test(t) && !/^[\w.\[\]]+\s*(?:[-+*/]?=)(?!=)/.test(t) && !/^\$0\s*=/.test(t);
1615
+ }
1616
+
961
1617
  /** Replace a pattern binding (Rust `n if n > 3`) with the subject inside its guard. */
962
1618
  const rebind = (guard, name, subject) => guard.replace(new RegExp(`\\b${name}\\b`, 'g'), subject);
963
1619
 
@@ -1013,7 +1669,7 @@ function switchArms(body, language, baseLine) {
1013
1669
  else {
1014
1670
  rest = rest.replace(/;?\s*break\s*;?\s*$/, '').replace(/;\s*$/, '').trim();
1015
1671
  value = useArrow ? rest : (rest.match(/^return\s+([\s\S]+)$/) || [])[1] ?? null;
1016
- if (value && /;/.test(value)) value = null; // more than one statement
1672
+ if (value && (/;/.test(value) || (language === 'swift' && /\n\s*\S/.test(value)))) value = null; // more than one statement
1017
1673
  }
1018
1674
  const patterns = [...pending, pattern];
1019
1675
  pending = [];
@@ -1052,7 +1708,7 @@ function readSwitch(text, language, inputs, line) {
1052
1708
  const t = text.trim();
1053
1709
  if ((m = t.match(/^switch\s*\(([\s\S]*?)\)\s*\{/)) && language !== 'go' && language !== 'rust') {
1054
1710
  const open = t.indexOf('{', m[0].length - 1); subjectText = m[1]; body = t.slice(open + 1, matchClose(t, open));
1055
- } else if (language === 'go' && (m = t.match(/^switch\b([^{]*)\{/))) {
1711
+ } else if ((language === 'go' || language === 'swift') && (m = t.match(/^switch\b([^{]*)\{/))) {
1056
1712
  const open = t.indexOf('{'); subjectText = m[1].trim() || null; body = t.slice(open + 1, matchClose(t, open));
1057
1713
  } else if (language === 'rust' && (m = t.match(/^match\s+([^{]+?)\s*\{/))) {
1058
1714
  const open = t.indexOf('{', m[0].length - 1); subjectText = m[1]; body = t.slice(open + 1, matchClose(t, open));
@@ -1120,8 +1776,10 @@ function splitStatements(body, baseLine) {
1120
1776
  // statement. Any other brace is part of an expression (an object literal, destructuring, a struct
1121
1777
  // literal, JSX): keep reading to the end of the statement.
1122
1778
  const prefix = src.slice(start, i).trim();
1779
+ // A Go composite literal (`[]string{…}`, `map[string]int{…}`) inside a header is a value: read past it.
1780
+ if (/(?:\[\d*\][\w.*]+|map\[[^\]]+\][\w.*[\]]+)$/.test(prefix) && /^(?:for|if|switch)\b/.test(prefix)) { i = close; continue; }
1123
1781
  const blockHeader = !prefix
1124
- || /^(?:if|else|for|foreach|while|switch|try|catch|finally|do|function|class|fn|func|match|loop|unsafe|impl|struct|enum|trait|mod|go|defer|select|using|lock|synchronized|namespace|interface|record|object|init|when|static|async\s+function|export\s+(?:default\s+)?(?:function|class))\b/.test(prefix)
1782
+ || /^(?:if|else|for|foreach|while|switch|try|catch|finally|do|function|class|fn|func|match|loop|unsafe|impl|struct|enum|trait|mod|go|defer|select|using|lock|synchronized|namespace|interface|record|object|init|when|static|guard|repeat|extension|protocol|actor|async\s+function|export\s+(?:default\s+)?(?:function|class))\b/.test(prefix)
1125
1783
  || (/(?:\)|=>|\belse|\btry|\bdo|\bfinally|\bloop|\bunsafe|\bdefer)\s*$/.test(prefix) && !/^(?:return|throw|yield)\b/.test(prefix) && !/[=:]\s*\w*\s*\(/.test(prefix.replace(/=>\s*$/, '')) )
1126
1784
  || (/=>\s*$/.test(prefix));
1127
1785
  if (depth === 0 && !blockHeader) { i = close; continue; }
@@ -1130,7 +1788,7 @@ function splitStatements(body, baseLine) {
1130
1788
  // An if/else chain continues past a closing brace, and so do `do { … } while (…)` and a Go function
1131
1789
  // called where it is written (`go func() { … }()`). Only the next few characters matter.
1132
1790
  const next = src.slice(i + 1, i + 40);
1133
- const goes = /^\s*else\b/.test(next) || (/^do\b/.test(prefix) && /^\s*while\b/.test(next)) || (/^\(/.test(next) && /^(?:go\s+|defer\s+)?func\s*\(/.test(prefix));
1791
+ const goes = /^\s*else\b/.test(next) || (/^(?:do|repeat)\b/.test(prefix) && /^\s*while\b/.test(next)) || (/^\(/.test(next) && /^(?:go\s+|defer\s+)?func\s*\(/.test(prefix));
1134
1792
  if (!goes) { i++; break; }
1135
1793
  }
1136
1794
  } else if (c === ';' && depth === 0) {
@@ -1148,7 +1806,17 @@ function splitStatements(body, baseLine) {
1148
1806
  const after = src.slice(j, j + 24);
1149
1807
  // A switch label (`case 'a':`, `default:`) is a statement of its own: what follows it is the case's first step.
1150
1808
  if (/^(?:case\b[^\n]*|default\s*):$/.test(before)) { i++; break; }
1151
- if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) &&!/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after)) { i++; break; }
1809
+ // A loop label (`outer:`) is its own line, and so is a C label (`cleanup:`), the place a goto jumps to.
1810
+ if (/^[A-Za-z_]\w*\s*:$/.test(before) && !/^(?:public|private|protected|else)\s*:$/.test(before)) { i++; break; }
1811
+ // A brace-less `if (x)` / `for (…)` / `else` carries on into the one statement on the next line.
1812
+ if (/^(?:(?:\}\s*)?else\s+if|if|for|foreach|while|using|lock|fixed)\s*\(/.test(before) && headerClosed(before)) continue;
1813
+ // (Nested: `for (…)\n if (…)\n return 1;` is one statement: the last line is itself a brace-less header.)
1814
+ const lastLine = before.slice(before.lastIndexOf('\n') + 1).trim();
1815
+ if (lastLine !== before && /^(?:(?:\}\s*)?else\s+if|if|for|foreach|while|using|lock|fixed)\s*\(/.test(before) && /^(?:if|for|foreach|while)\s*\(/.test(lastLine) && headerClosed(lastLine)) continue;
1816
+ if (/^(?:\}\s*)?else$/.test(before)) continue;
1817
+ // (`i++` / `n--` at the end of a line is a whole statement, not an operator waiting for more.)
1818
+ // (`do { … }` with its `while (…)` on the next line, Allman style, is one statement.)
1819
+ if (before && (!/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) || /[\w)\]](?:\+\+|--)$/.test(before)) && !/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after) && !(/^(?:do|repeat)\b/.test(before) && /\}$/.test(before) && /^while\b/.test(after))) { i++; break; }
1152
1820
  }
1153
1821
  }
1154
1822
  const raw = src.slice(start, i);
@@ -1162,7 +1830,51 @@ function splitStatements(body, baseLine) {
1162
1830
  }
1163
1831
  return out;
1164
1832
  }
1165
- const stripCommentsKeepLayout = (s) => s.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:])\/\/.*$/gm, '$1');
1833
+ /** `if (a && b)` with its parentheses closed and nothing after them: a header still waiting for its statement. */
1834
+ function headerClosed(before) {
1835
+ const o = before.indexOf('(');
1836
+ let d = 0;
1837
+ for (let k = o; k < before.length; k++) {
1838
+ const c = before[k];
1839
+ if (c === '"' || c === '\'' || c === '`') { k = skipString(before, k); continue; }
1840
+ if (c === '(') d++;
1841
+ else if (c === ')' && --d === 0) return !before.slice(k + 1).trim();
1842
+ }
1843
+ return false;
1844
+ }
1845
+ /**
1846
+ * Comments blanked to spaces (lines and offsets unchanged), outside strings only: `'… use \`//\` …'` and
1847
+ * `"https://…"` keep their text, so a string can never swallow the rest of a line. One pass, linear.
1848
+ */
1849
+ const INTERESTING = /["'`/]/g;
1850
+ function stripCommentsKeepLayout(s) {
1851
+ if (!s.includes('/')) return s; // no comment can start without a slash
1852
+ let out = '', last = 0;
1853
+ for (let i = 0; i < s.length; i++) {
1854
+ // Jump to the next quote or slash: nothing else matters here.
1855
+ INTERESTING.lastIndex = i;
1856
+ const hit = INTERESTING.exec(s);
1857
+ if (!hit) break;
1858
+ i = hit.index;
1859
+ const c = s[i];
1860
+ if (c === '"' || c === "'" || c === '`') {
1861
+ // A quote is a string only when it closes (on the same line, except template and raw strings).
1862
+ let j = i + 1;
1863
+ for (; j < s.length; j++) { if (s[j] === '\\') { j++; continue; } if (s[j] === c || (s[j] === '\n' && c !== '`')) break; }
1864
+ if (j < s.length && s[j] === c) i = j;
1865
+ continue;
1866
+ }
1867
+ if (c === '/' && s[i + 1] === '/' && s[i - 1] !== ':') {
1868
+ let e = s.indexOf('\n', i); if (e < 0) e = s.length;
1869
+ out += s.slice(last, i) + ' '.repeat(e - i); last = i = e; i--; continue;
1870
+ }
1871
+ if (c === '/' && s[i + 1] === '*') {
1872
+ let e = s.indexOf('*/', i + 2); e = e < 0 ? s.length : e + 2;
1873
+ out += s.slice(last, i) + s.slice(i, e).replace(/[^\n]/g, ' '); last = e; i = e - 1; continue;
1874
+ }
1875
+ }
1876
+ return out + s.slice(last);
1877
+ }
1166
1878
 
1167
1879
  /** Read `if ... else ...` / `return ...` statements into rules. Returns { rules, otherwise, unread }. */
1168
1880
  function readBraceStatements(stmts, language, inputs) {
@@ -1185,6 +1897,21 @@ function readBraceStatements(stmts, language, inputs) {
1185
1897
  for (const st of stmts) {
1186
1898
  const t = st.text;
1187
1899
  let m;
1900
+ // Swift: guard cond else { return … } stops unless the condition holds; `guard let x = …` stops when x is not set.
1901
+ if (language === 'swift' && (m = t.match(/^guard\s+([\s\S]+?)\s+else\s*\{([\s\S]*)\}\s*$/))) {
1902
+ const branch = m[2].trim();
1903
+ const stmts1 = splitTop(branch.replace(/;\s*$/, ''), ';').flatMap((x) => x.split('\n')).map((x) => x.trim()).filter(Boolean);
1904
+ const effect = stmts1.length === 1 ? terminatorEffect(stmts1[0], language) : null;
1905
+ if (effect && effect.kind !== 'passes-error') {
1906
+ const parts = splitTop(m[1], ',').map((x) => x.trim()).filter(Boolean);
1907
+ const bound = parts.map((p) => p.match(/^(?:let|var)\s+(\w+)/)?.[1]).filter(Boolean);
1908
+ const plain = parts.filter((p) => !/^(?:let|var|case)\b/.test(p));
1909
+ const when = !bound.length && !parts.some((p) => /^case\b/.test(p)) ? toThunderCondition(`!(${plain.join(' && ')})`, inputs) : null;
1910
+ const said = when ? sayCondition(when) : [...bound.map((b) => `${displayLabel(b).toLowerCase()} is not set`), ...plain.map((p) => { const w = toThunderCondition(`!(${p})`, inputs); return w ? sayCondition(w) : `not \`${p}\``; })].join(' or ');
1911
+ guards.push({ when, code: `guard ${m[1].trim()}`, effect, line: st.line, readable: !!when || (!plain.length && !!bound.length), says: sayGuard(effect, said) });
1912
+ continue;
1913
+ }
1914
+ }
1188
1915
  if (/^if\b/.test(t)) {
1189
1916
  // A guard: an `if` with no else whose branch exits without a fixed answer.
1190
1917
  const head = splitIf(t, language);
@@ -1202,7 +1929,10 @@ function readBraceStatements(stmts, language, inputs) {
1202
1929
  // Walk the chain: if C B (else if C B)* (else B)?
1203
1930
  let rest = t;
1204
1931
  let ok = true;
1932
+ // Each `else if` / `else` is on its own line of the statement: its rule is placed there, not on the first `if`.
1933
+ const lineOf = (part) => { const at = t.lastIndexOf(part); return st.line + (at > 0 ? (t.slice(0, at).match(/\n/g) || []).length : 0); };
1205
1934
  while (rest) {
1935
+ const here = lineOf(rest);
1206
1936
  const head = rest.match(/^(?:else\s+)?if\b\s*/);
1207
1937
  if (!head) break;
1208
1938
  rest = rest.slice(head[0].length);
@@ -1210,7 +1940,7 @@ function readBraceStatements(stmts, language, inputs) {
1210
1940
  if (rest[0] === '(' && (language !== 'go' && language !== 'rust' || true)) {
1211
1941
  const close = matchClose(rest, 0);
1212
1942
  const tail = rest.slice(close + 1).trimStart();
1213
- if (language === 'go' || language === 'rust') {
1943
+ if (BARE_IF.has(language)) {
1214
1944
  // Go/Rust may wrap only part of the condition in parentheses: if (a) && b {
1215
1945
  const brace = findTopBrace(rest);
1216
1946
  cond = rest.slice(0, brace).trim(); after = rest.slice(brace);
@@ -1232,13 +1962,13 @@ function readBraceStatements(stmts, language, inputs) {
1232
1962
  remaining = (semi < 0 ? '' : after.slice(semi + 1)).trim();
1233
1963
  }
1234
1964
  if (value == null) { unread.push({ line: st.line, text: `if ${cond.trim()}`, reason: 'This branch does more than choose an answer.' }); ok = false; break; }
1235
- if (!take(cond, value, st.line)) { ok = false; break; }
1965
+ if (!take(cond, value, here)) { ok = false; break; }
1236
1966
  if (/^else\s+if\b/.test(remaining)) { rest = remaining; continue; }
1237
1967
  if (/^else\b/.test(remaining)) {
1238
1968
  const elseBody = remaining.replace(/^else\s*/, '');
1239
1969
  const v = elseBody.startsWith('{') ? blockValue(elseBody) : (elseBody.startsWith('return ') ? elseBody.slice(7).replace(/;$/, '') : null);
1240
- if (v == null) { unread.push({ line: st.line, text: 'else', reason: 'The fallback branch does more than choose an answer.' }); ok = false; }
1241
- else take(null, v, st.line);
1970
+ if (v == null) { unread.push({ line: lineOf(remaining), text: 'else', reason: 'The fallback branch does more than choose an answer.' }); ok = false; }
1971
+ else take(null, v, lineOf(remaining));
1242
1972
  }
1243
1973
  rest = '';
1244
1974
  }
@@ -1281,7 +2011,9 @@ function readBraceStatements(stmts, language, inputs) {
1281
2011
  continue;
1282
2012
  }
1283
2013
  }
1284
- const ret = t.match(/^return\s+([\s\S]+?);?$/) || (language === 'rust' && st === stmts[stmts.length - 1] && !/;\s*$/.test(t) ? [null, t] : null);
2014
+ // Rust's last expression, and a Swift body that is one expression, give the answer without `return`.
2015
+ const ret = t.match(/^return\s+([\s\S]+?);?$/) || (language === 'rust' && st === stmts[stmts.length - 1] && !/;\s*$/.test(t) ? [null, t] : null)
2016
+ || (language === 'swift' && stmts.length === 1 && swiftImplicitValue(t) ? [null, t] : null);
1285
2017
  if (ret) {
1286
2018
  if (language === 'kotlin' && readKotlinIf(ret[1], inputs, rules, unread, st.line, (o) => { otherwise = o; })) continue;
1287
2019
  if (readTernary(ret[1], inputs, rules, unread, st.line, (o) => { otherwise = o; })) continue;
@@ -1675,7 +2407,8 @@ function sayDecision(rules, otherwise) {
1675
2407
  }
1676
2408
 
1677
2409
  function decisionSource(name, inputs, rules, otherwise) {
1678
- const L = [`decision ${name}`, ' inputs'];
2410
+ // A function with no name of its own ("format › callback at line 579") is written under a name a card can hold.
2411
+ const L = [`decision ${/^[A-Za-z_$][\w$]*$/.test(name) ? name : String(name).replace(/[^\w$]+/g, "_").replace(/^_+|_+$/g, "") || "callback"}`, " inputs"];
1679
2412
  for (const p of inputs) L.push(` ${p.name}${['number', 'boolean', 'string'].includes(p.type) ? `: ${p.type}` : ''}`);
1680
2413
  rules.forEach((r, i) => L.push(` rule rule_${i + 1}`, ` when ${r.when}`, ` return ${r.result}`));
1681
2414
  if (otherwise) L.push(' default', ` return ${otherwise.result}`);
@@ -1708,12 +2441,18 @@ function readPredicate(fn, lang, names, code) {
1708
2441
  if (typeof fn.body !== 'string') return null;
1709
2442
  const body = stripComments(fn.body).trim();
1710
2443
  let m = body.match(/^return\s+([^;{}]+?);?\s*$/s);
1711
- if (!m && lang === 'rust') m = body.match(/^([^;{}]+?)\s*$/s);
2444
+ if (!m && (lang === 'rust' || (lang === 'swift' && swiftImplicitValue(body)))) m = body.match(/^([^;{}]+?)\s*$/s);
1712
2445
  if (!m) return null;
1713
2446
  expr = m[1].replace(/\s+/g, ' ').trim();
1714
2447
  if (fn.bodyStart != null) line = lineAt(code, fn.bodyStart + Math.max(0, fn.body.indexOf(m[1].trim().slice(0, 12))));
1715
2448
  }
1716
2449
  if (!expr || /^(true|false|True|False)$/.test(expr)) return null;
2450
+ // C, C++, and Swift say what comes back: only a yes/no function is a rule (a String property is text, even when the
2451
+ // text holds a comparison sign), and quoted text never makes a value a yes/no.
2452
+ // (C and C++ yes/no functions often return int, so only Swift is held to its declared type.)
2453
+ if (lang === 'swift' && fn.returns && !/^(?:Bool|bool|_Bool|boolean)\??$/.test(String(fn.returns).trim())) return null;
2454
+ if (/^(?:c|cpp)$/.test(lang) && fn.returns && /^(?:string|char\*|const char\*)$/.test(String(fn.returns).trim())) return null;
2455
+ if (/^(?:swift|c|cpp)$/.test(lang) && !BOOL_RETURN.test(String(fn.returns || '').trim()) && !/^Bool\??$/.test(String(fn.returns || '').trim()) && !LOGIC_OR_COMPARE.test(expr.replace(/"(?:\\.|[^"\\])*"/g, 'Q'))) return null;
1717
2456
  if (!(BOOL_RETURN.test(String(fn.returns || '').trim()) || LOGIC_OR_COMPARE.test(expr) || /\?$/.test(fn.name))) return null;
1718
2457
  const when = toThunderCondition(expr.replace(/\?$/, ''), names);
1719
2458
  return when ? { rule: { when, result: 'true', line } } : null;
@@ -1746,19 +2485,95 @@ function anchorSpan(span, fn, lang) {
1746
2485
  else { delete span.start; delete span.end; span.exact = 'lines'; }
1747
2486
  }
1748
2487
 
2488
+ /**
2489
+ * C and C++ steps inside `#if` / `#ifdef` / `#elif` / `#else` run only in some builds: each says so, with the line that
2490
+ * decides it, so alternatives (`#if A … #elif B …`) are never read as steps that all run one after another.
2491
+ */
2492
+ function markBuildOnlySteps(steps, fn, lang, code, srcLines) {
2493
+ const range = srcLines.length ? bodyRange(fn, lang, code) : null;
2494
+ if (!range) return;
2495
+ const only = new Map();
2496
+ const stack = [];
2497
+ const clean = (t) => t.replace(/\s*\/[/*].*$/, '').replace(/\s+/g, ' ').trim();
2498
+ for (let l = range[0]; l <= range[1]; l++) {
2499
+ let t = (srcLines[l - 1] ?? '').trim();
2500
+ // A directive continued with `\` takes its next lines.
2501
+ while (/^#/.test(t) && /\\$/.test(t) && l < range[1]) t = `${t.slice(0, -1).trim()} ${(srcLines[l++] ?? '').trim()}`;
2502
+ let m;
2503
+ if ((m = t.match(/^#\s*(if|ifdef|ifndef)\b(.*)$/))) stack.push({ first: clean(`#${m[1]}${m[2]}`), label: clean(`#${m[1]}${m[2]}`) });
2504
+ else if ((m = t.match(/^#\s*(elif|elifdef|elifndef)\b(.*)$/)) && stack.length) stack[stack.length - 1].label = clean(`#${m[1]}${m[2]}`);
2505
+ else if (/^#\s*else\b/.test(t) && stack.length) stack[stack.length - 1].label = `#else of ${stack[stack.length - 1].first}`;
2506
+ else if (/^#\s*endif\b/.test(t)) stack.pop();
2507
+ else if (stack.length) only.set(l, stack.map((x) => x.label).join(', '));
2508
+ }
2509
+ if (!only.size) return;
2510
+ const walk = (list, outer) => {
2511
+ for (const st of list) {
2512
+ const label = only.get(st.line);
2513
+ // (A question or a loop keeps its own words, which the views turn into "Ask: …?"; the steps under it say it.)
2514
+ const holds = st.kind === 'branch' || st.kind === 'loop' || st.kind === 'try';
2515
+ if (label && label !== outer && !holds) st.says = `${st.says} (only in builds where \`${label}\`)`;
2516
+ const inner = holds ? outer : label || outer;
2517
+ if (st.children) walk(st.children.map((k) => (holds && label && !only.has(k.line) ? (only.set(k.line, label), k) : k)), inner);
2518
+ for (const h of st.handlers || []) if (h.steps) walk(h.steps, inner);
2519
+ }
2520
+ };
2521
+ walk(steps, null);
2522
+ }
2523
+
1749
2524
  function functionSteps(fn, lang, code, names, srcLines = []) {
1750
2525
  let stmts = [];
1751
2526
  try {
1752
2527
  if (lang === 'python') stmts = indentStatements(fn.pyBody, { depthKey: 'indent' });
1753
2528
  // For steps, elsif / else / rescue / ensure sit beside their if or begin (the rule reader keeps the raw depth).
1754
2529
  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' });
1755
- else if (typeof fn.body === 'string' && fn.bodyStart != null) stmts = braceStatements(splitStatements(lang === 'kotlin' ? kotlinTerminate(fn.body) : fn.body, lineAt(code, fn.bodyStart)), splitStatements);
2530
+ else if (typeof fn.body === 'string' && fn.bodyStart != null) stmts = withLanguage(lang, () => braceStatements(splitStatements(lang === 'kotlin' ? kotlinTerminate(fn.body) : fn.body, lineAt(code, fn.bodyStart)), splitStatements));
1756
2531
  } catch { return null; }
1757
2532
  if (!stmts.length) return null;
1758
- const r = stepsFrom(stmts);
2533
+ // A Swift body that is one expression gives it back without `return` (`var isEmpty: Bool { count == 0 }`).
2534
+ // So does one that is a single call or expression when the function says it gives something back
2535
+ // (`func base32Bytes() -> [UInt8] { Base32.default.encode(…) }` gives back what encode makes).
2536
+ if (lang === 'swift' && stmts.length === 1 && ((!stmts[0].children?.length && swiftImplicitValue(stmts[0].text)) || swiftImplicitResult(stmts[0].text, fn.returns || (fn.route ? 'a response' : null)))) stmts[0] = { ...stmts[0], implicitReturn: true };
2537
+ const r = withLanguage(lang, () => withFunctionContext({ params: fn.params || [], language: lang, route: !!fn.route }, () => {
2538
+ const out = stepsFrom(stmts);
2539
+ // Ruby gives back its last value: in a yes/no method (`def accepts?`) or a last line that is a comparison or
2540
+ // and/or, that value is the answer, not a call made for its effect.
2541
+ const last = out.steps[out.steps.length - 1];
2542
+ if (lang === 'ruby' && last && last.kind === 'call' && !last.jump && !last.library && (/\?$/.test(fn.name) || /&&|\|\||\band\b|\bor\b|[!=]=|[<>]/.test(stripRubyStrings(last.code || '')))) {
2543
+ const v = classifyStatement(`return ${String(last.code || '').trim()}`);
2544
+ if (v.kind === 'return') out.steps[out.steps.length - 1] = { ...last, ...v, code: last.code, ...(/^Returns (?:a computed value|a value)$/.test(v.says) ? { restates: true } : {}) };
2545
+ delete out.steps[out.steps.length - 1].callee;
2546
+ }
2547
+ return out;
2548
+ }));
2549
+ if (lang === 'c' || lang === 'cpp') markBuildOnlySteps(r.steps, fn, lang, code, srcLines);
2550
+ // A Swift `switch` that is the whole body of a function that gives something back: each case's one expression is
2551
+ // what comes back (`case .key(let key): String(reflecting: key)` gives back that text; it is not just a call).
2552
+ // So does an if / else if / else that is the whole body (Swift if-expressions).
2553
+ if (lang === 'swift' && fn.returns && !/^(?:Void|\(\s*\)|Never)$/.test(String(fn.returns).trim()) && r.steps.length === 1 && r.steps[0].kind === 'branch' && /^(?:switch|if)\b/.test(String(r.steps[0].code || ''))) {
2554
+ const giveBack = (list) => {
2555
+ const only = list?.length === 1 ? list[0] : null;
2556
+ if (!only) return;
2557
+ if (only.kind === 'branch' && only.elseIf) { giveBack(only.children); giveBack(only.otherwise); return; }
2558
+ if (only.children?.length || !/^(?:call|set|other)$/.test(only.kind) || !only.code || !swiftImplicitResult(only.code, fn.returns) || /^[\w.]+\s*=(?!=)/.test(only.code)) return;
2559
+ const v = withLanguage(lang, () => classifyStatement(`return ${only.code}`));
2560
+ if (v.kind === 'return') { list[0] = { ...only, ...v, code: only.code }; delete list[0].restates; delete list[0].callee; }
2561
+ };
2562
+ const top = r.steps[0];
2563
+ if (/^switch\b/.test(String(top.code))) for (const arm of top.children || []) giveBack(arm.children);
2564
+ else if (top.otherwise) { giveBack(top.children); giveBack(top.otherwise); }
2565
+ }
1759
2566
  // Anchoring: every step (and child step) points at its exact place in the original file.
1760
2567
  const walk = (list) => { for (const st of list) { anchorSpan(st.span, fn, lang); if (st.children) walk(st.children); } };
1761
2568
  walk(r.steps);
2569
+ // Every step carries its meaning tree (`expr`); a step made without one keeps its code, never a guess.
2570
+ const withExpr = (list) => {
2571
+ for (const st of list || []) {
2572
+ if (!st.expr) st.expr = { kind: 'code', text: String(st.code ?? '').replace(/\s+/g, ' ').trim() };
2573
+ withExpr(st.children); withExpr(st.otherwise); for (const h of st.handlers || []) withExpr(h.steps); withExpr(st.always?.steps);
2574
+ }
2575
+ };
2576
+ withExpr(r.steps);
1762
2577
  for (const sk of r.skipped) anchorSpan(sk, fn, lang);
1763
2578
  const range = bodyRange(fn, lang, code);
1764
2579
  if (range) {
@@ -1780,23 +2595,37 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
1780
2595
  const bareProperty = /^(not\s+|!)?(?:self\.|this\.)?\w+\.\w+(\(\))?$/.test(st.cond.trim()) && !/\./.test(st.says.replace(/\(\d+ steps? inside\)$/, ''));
1781
2596
  // A plain name used as a yes/no (`if (!slug)`) already reads as "slug is not set"; keep it rather than "not slug".
1782
2597
  const bareName = /^(not\s+|!)?(?:self\.|this\.)?\w+$/.test(st.cond.trim()) && /\bis (not )?set\b/.test(st.says);
1783
- const cond = bareProperty || bareName ? null : toThunderCondition(st.cond, names);
2598
+ // Request and settings idioms (a header, a value in the address, a setting) already read as words; keep them.
2599
+ const idiom = /\b(?:req|request|ctx|c)\s*\.\s*(?:headers|header|query|params|body|searchParams)\b|\bprocess\s*\.\s*env\b|\bos\s*\.\s*(?:environ|getenv)\b|getenv|GetEnvironmentVariable/.test(st.cond);
2600
+ const cond = bareProperty || bareName || idiom ? null : toThunderCondition(st.cond, names);
1784
2601
  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 || ''}`);
1785
- delete st.cond; delete st.negate;
2602
+ delete st.negate;
2603
+ }
2604
+ // C++ member names carry a mark that means nothing to a reader: items_ and m_items are both "items".
2605
+ if (lang === 'cpp') {
2606
+ const clean = (x) => String(x).replace(/\bm_(?=[A-Za-z])/g, '').replace(/\b([A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*)_(?![\w])/g, '$1');
2607
+ const tidy = (list) => { for (const st of list || []) { st.says = clean(st.says); tidy(st.children); tidy(st.otherwise); for (const h of st.handlers || []) { h.says = clean(h.says); tidy(h.steps); } if (st.always) tidy(st.always.steps); } };
2608
+ tidy(r.steps);
1786
2609
  }
1787
2610
  return r;
1788
2611
  }
1789
2612
 
1790
- export function readCode(source, { language, file = '' } = {}) {
2613
+ export function readCode(source, { language, file = '', allSteps = false } = {}) {
1791
2614
  const src = String(source ?? '');
1792
2615
  if (src.length > 400000) throw new Error('Source is larger than 400 KB. Read one file or module at a time.');
1793
- 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').replace(/^(postgres(ql)?|pgsql|plpgsql|mysql|sqlite|tsql|t-sql|mssql)$/, 'sql');
2616
+ 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').replace(/^(postgres(ql)?|pgsql|plpgsql|mysql|sqlite|tsql|t-sql|mssql)$/, 'sql').replace(/^(docker|containerfile)$/, 'dockerfile').replace(/^(gha|github[ -]?actions?|workflow)$/, 'github-actions').replace(/^(tf|hcl|opentofu|tofu)$/, 'terraform').replace(/^(k8s|kube|kubectl)$/, 'kubernetes').replace(/^(compose|docker[ -]?compose)$/, 'docker-compose').replace(/^(c\+\+|cxx|cc|hpp|hxx|hh)$/, 'cpp').replace(/^h$/, 'c')
2617
+ .replace(/^(sh|bash|zsh|ksh|dash|posix)$/, 'shell').replace(/^(ps1|psm1|pwsh|ps)$/, 'powershell').replace(/^(rlang|rscript)$/, 'r');
1794
2618
  if (!READ_LANGUAGES.includes(lang)) throw new Error(`Reading rules supports ${READ_LANGUAGES.join(', ')}. Got "${lang}".`);
1795
2619
  READING_RUST = lang === 'rust';
1796
2620
  // SQL is read by its own reader: tables, rules (CHECK, UNIQUE), views, functions, procedures, triggers.
1797
2621
  if (lang === 'sql') return sqlReading(src);
2622
+ // Infrastructure and delivery (spec section 12): Dockerfile stages and workflow jobs as steps, plus what they make.
2623
+ if (INFRA_LANGUAGES.includes(lang)) return infraReading(lang, src, file);
2624
+ // Shell, PowerShell, and R are read by their own modules into the same items.
2625
+ if (SCRIPT_READERS[lang]) return scriptReading(lang, src, file, !language);
1798
2626
  // PHP is read after `$name` -> `name` and `->` -> `.`; every line stays on its line.
1799
- const code = lang === 'php' ? normalizePhp(src) : src;
2627
+ // C and C++ are read with preprocessor lines blanked (#include, #define, #if): they are not statements.
2628
+ const code = lang === 'php' ? normalizePhp(src) : lang === 'c' || lang === 'cpp' ? blankPreprocessor(src) : src;
1800
2629
  const items = [];
1801
2630
  const srcLines = src.split('\n');
1802
2631
  const codeLines = code.split('\n');
@@ -1812,9 +2641,11 @@ export function readCode(source, { language, file = '' } = {}) {
1812
2641
  // an implicit last value) reads as "true when <expression>, otherwise false".
1813
2642
  if (!read.rules.length && !read.otherwise) {
1814
2643
  const pred = readPredicate(fn, lang, names, code);
1815
- if (pred) { read.rules.push(pred.rule); read.otherwise = { result: 'false', line: pred.rule.line }; }
2644
+ if (pred) { read.rules.push(pred.rule); read.otherwise = { result: 'false', line: pred.rule.line }; read.unread = []; }
1816
2645
  }
1817
- const isDecision = read.rules.length > 0 && !!read.otherwise;
2646
+ // A rule is drawn only when every statement was read into it; a body with other steps (a loop, an assignment, a
2647
+ // later check) is read as steps instead, so no check is silently left out of the picture.
2648
+ const isDecision = read.rules.length > 0 && !!read.otherwise && !read.unread.length;
1818
2649
  const guards = read.guards || [];
1819
2650
  // In a function that is not a pure decision, early fixed returns are still rules worth reading.
1820
2651
  if (!isDecision) {
@@ -1828,9 +2659,15 @@ export function readCode(source, { language, file = '' } = {}) {
1828
2659
  const base = {
1829
2660
  id: `${fn.name}:${fn.line}`, name: fn.name, label: displayLabel(fn.name), line: fn.line,
1830
2661
  // Framework plumbing (a database session, the request, a context) is marked so views can leave it out of "You give it".
1831
- inputs: inputs.map((p) => (PLUMBING.test(p.name) || PLUMBING_TYPE.test(String(p.type ?? '')) ? { ...p, plumbing: true } : p)), returns: simpleType(fn.returns),
2662
+ // Plumbing (the framework's request, a database session, a context) by its type when it has one, else by name:
2663
+ // `Handle(PingResource request, …)` takes a PingResource, which is the real input although it is named request.
2664
+ inputs: inputs.map((p) => (isPlumbing(p, inputs, fn) ? { ...p, plumbing: true } : p)), returns: simpleType(fn.returns),
1832
2665
  ...(fn.route ? { route: fn.route } : {}),
2666
+ // JS/TS: what a function is assigned to (`exports.x`, `Foo.prototype.bar`), or that it is a callback.
2667
+ ...(fn.assignedTo ? { assignedTo: fn.assignedTo } : {}), ...(fn.callback ? { callback: true } : {}), ...(fn.passedTo ? { passedTo: fn.passedTo } : {}),
1833
2668
  ...(doc ? { doc } : {}),
2669
+ // C++ `Library::lateFee` and Swift methods in `extension Library { … }`: the type they belong to, by name.
2670
+ ...(fn.qualifier ? { qualifier: fn.qualifier } : {}),
1834
2671
  provenance: 'inferred-from-code',
1835
2672
  };
1836
2673
  if (isDecision) {
@@ -1840,6 +2677,8 @@ export function readCode(source, { language, file = '' } = {}) {
1840
2677
  says: (fn.route ? `Handles ${fn.route.method} ${fn.route.path}. ` : '') + sayDecision(read.rules, read.otherwise) + guardNote, guards,
1841
2678
  thunder: decisionSource(fn.name, inputs, read.rules, read.otherwise),
1842
2679
  unread: read.unread,
2680
+ // `allSteps`: a decision also carries its steps (for writing in Thunder, which edits any function by its steps).
2681
+ ...(allSteps ? (() => { const st = functionSteps(fn, lang, code, names, srcLines); return st ? { steps: st.steps, ...(st.anchor ? { anchor: st.anchor } : {}) } : {}; })() : {}),
1843
2682
  });
1844
2683
  } else {
1845
2684
  const st = functionSteps(fn, lang, code, names, srcLines);
@@ -1898,3 +2737,139 @@ function sqlReading(src) {
1898
2737
  ],
1899
2738
  };
1900
2739
  }
2740
+
2741
+ /**
2742
+ * A reading of a Dockerfile or GitHub Actions workflow in the same shape as every other language's, plus `infra`:
2743
+ * the Resources it makes, Permissions, Settings (secrets named only), Facts, and the links between its items.
2744
+ */
2745
+ function infraReading(lang, src, file) {
2746
+ const r = lang === 'dockerfile' ? readDockerfile(src, file || 'Dockerfile') : lang === 'terraform' ? readTerraform(src, file || 'main.tf') : lang === 'bicep' ? readBicep(src, file || 'main.bicep') : lang === 'kubernetes' ? readKubernetes(src, file || 'k8s.yaml') : lang === 'docker-compose' ? readCompose(src, file || 'compose.yaml') : readWorkflow(src, file || 'workflow.yml');
2747
+ for (const it of r.items) it.completeness = completenessOf(it);
2748
+ const counts = { decision: 0, function: r.items.length, error: 0, test: 0, partial: 0, guarded: 0, route: r.items.filter((i) => i.route).length };
2749
+ return {
2750
+ schema: READ_SCHEMA, language: lang, detected: false, items: r.items, counts,
2751
+ ...(r.purpose ? { purpose: r.purpose } : {}),
2752
+ infra: { things: r.things, permissions: r.permissions, settings: r.settings, facts: r.facts, links: r.links, unknowns: r.unknowns ?? [] },
2753
+ limitations: [
2754
+ 'Read from the file, not from what is running: the live system may differ.',
2755
+ 'Secret values are never shown, only their names. Values worked out when it runs or is built say so; the original lines are one click away.',
2756
+ lang === 'dockerfile' ? 'Each build stage is a Steps card; RUN commands are read in words, and commands Thunder does not know are named as they are.'
2757
+ : lang === 'terraform' || lang === 'bicep' ? `Each ${lang === 'bicep' ? 'resource and module' : 'resource, data source, and module'} is a Resource; the order they are created is one Steps card, from the references between them. Links to resources in other files of the same ${lang === 'bicep' ? 'deployment' : 'folder (module)'} are drawn when those files are read together.`
2758
+ : lang === 'kubernetes' ? 'Each resource is a Resource; the order they are made is one Steps card. A Service is linked to the workloads its selector picks, and names in settings (redis:6379) to the Service they name, also across files read together. Helm templates are not read.'
2759
+ : lang === 'docker-compose' ? 'Each service, named volume, network, secret, and config is a Resource; the order services start, from depends_on, is one Steps card. A service built from a folder is linked to the Dockerfile in that folder when both are read together.'
2760
+ : 'Each job is an Action with a "When" badge; well-known actions and common commands are read in words, others are named as they are.',
2761
+ ],
2762
+ };
2763
+ }
2764
+
2765
+ // ── Shell, PowerShell, and R: read by their own modules, shown in the same shape ──────────────────────────
2766
+
2767
+ const SCRIPT_TRIVIA = {
2768
+ shell: SHELL_TRIVIA,
2769
+ powershell: /^\s*(?:[{}()\[\];,]+|<#.*|#>.*|\.[A-Z]+\b.*|\[CmdletBinding\(\)\]|param\s*\(?)\s*$/i,
2770
+ r: /^\s*(?:[{}()\[\],]+\s*)*$/,
2771
+ };
2772
+ const SCRIPT_NOTES = {
2773
+ shell: 'Shell has no classes, so a shell file has no Things; its functions and its top-level script are read as steps.',
2774
+ powershell: 'Cmdlets are read by their Verb-Noun names; native tools (git, docker, az, kubectl, …) by what their arguments show.',
2775
+ r: 'Data-frame pipelines (|> and %>%) are read one verb at a time; S3 methods are read as plain functions.',
2776
+ };
2777
+ /**
2778
+ * A question about something missing is asked the positive way, with "not:" in front, so the picture asks "Does the
2779
+ * file exist?" and puts the Stop on No: "If there is no file x" -> "If not: the file x exists".
2780
+ */
2781
+ const positiveAsk = (says) => String(says)
2782
+ .replace(/^If there is no (file|folder) (.+)$/, 'If not: the $1 $2 exists')
2783
+ .replace(/^If (?!not: )(.+) does not exist$/, 'If not: $1 exists');
2784
+ const dropConds = (steps) => { for (const s of steps || []) { delete s.cond; if (s.kind === 'branch' && s.says) s.says = positiveAsk(s.says); dropConds(s.children); dropConds(s.otherwise); for (const h of s.handlers || []) dropConds(h.steps); if (s.always) dropConds(s.always.steps); } };
2785
+
2786
+ /** A reading for a language with its own module (shell.mjs, powershell.mjs, rlang.mjs). */
2787
+ function scriptReading(lang, src, file, detected) {
2788
+ const r = SCRIPT_READERS[lang](src, file);
2789
+ const srcLines = src.split('\n');
2790
+ const trivia = SCRIPT_TRIVIA[lang];
2791
+ const items = [];
2792
+ // The script's own top-level code leaves out the lines of the functions and classes defined in it.
2793
+ const defined = [...r.fns.filter((f) => !f.topLevel).map((f) => [f.line, Math.max(f.line, f.body?.[1] ?? f.line)]), ...(r.things || []).map((t) => t.lines)];
2794
+ const inDefinition = (l) => defined.some(([a, b]) => l >= a && l <= b);
2795
+ // PowerShell block comments (<# … #>) are comments on every line they cover.
2796
+ const commentLines = new Set();
2797
+ if (lang === 'powershell') {
2798
+ for (let at = src.indexOf('<#'); at >= 0; at = src.indexOf('<#', at + 2)) {
2799
+ const end = src.indexOf('#>', at + 2);
2800
+ const a = lineAt(src, at), b = lineAt(src, end < 0 ? src.length - 1 : end);
2801
+ for (let l = a; l <= b; l++) commentLines.add(l);
2802
+ if (end < 0) break;
2803
+ at = end;
2804
+ }
2805
+ }
2806
+ for (const fn of r.fns) {
2807
+ const inputs = fn.params.map((p) => ({ name: p.name, type: p.type ?? null }));
2808
+ const names = inputs.map((p) => (lang === 'r' ? p.name.replace(/\./g, '_') : p.name));
2809
+ dropConds(fn.steps);
2810
+ let decision = null;
2811
+ if (fn.decision) {
2812
+ const rules = [];
2813
+ for (const x of fn.decision.rules) {
2814
+ const when = toThunderCondition(x.cond, names), result = toThunderOutcome(x.result);
2815
+ if (!when || !result) { rules.length = 0; break; }
2816
+ rules.push({ when, result, line: x.line });
2817
+ }
2818
+ const otherwise = toThunderOutcome(fn.decision.otherwise.result);
2819
+ if (rules.length && otherwise) decision = { rules, otherwise: { result: otherwise, line: fn.decision.otherwise.line } };
2820
+ }
2821
+ const base = {
2822
+ id: `${fn.name}:${fn.line}`, name: fn.name, label: fn.topLevel ? fn.name : displayLabel(fn.name), line: fn.line,
2823
+ inputs: inputs.map((p) => (fn.route && PLUMBING.test(p.name) ? { ...p, plumbing: true } : p)), returns: simpleType(fn.returns ?? null),
2824
+ ...(fn.route ? { route: fn.route } : {}), ...(fn.doc ? { doc: fn.doc } : {}), ...(fn.topLevel ? { topLevel: true } : {}),
2825
+ provenance: 'inferred-from-code',
2826
+ };
2827
+ const takes = `${inputs.length ? inputs.map((p) => p.name).join(', ') : 'no inputs'}`;
2828
+ if (decision) {
2829
+ const thunderName = String(fn.name).replace(/[^\w]/g, '_');
2830
+ items.push({
2831
+ ...base, kind: 'decision', status: 'read', rules: decision.rules.map((x) => ({ ...x, says: sayCondition(x.when) })), otherwise: decision.otherwise,
2832
+ says: (fn.route ? `Handles ${fn.route.method} ${fn.route.path}. ` : '') + sayDecision(decision.rules, decision.otherwise), guards: [],
2833
+ thunder: decisionSource(thunderName, inputs, decision.rules, decision.otherwise), unread: [],
2834
+ });
2835
+ continue;
2836
+ }
2837
+ const steps = fn.steps || [];
2838
+ let anchor = null;
2839
+ if (fn.body) {
2840
+ const covered = new Set();
2841
+ for (const st of steps) if (st.span) for (let l = st.span.startLine; l <= st.span.endLine; l++) covered.add(l);
2842
+ let real = 0, hit = 0;
2843
+ const missing = [];
2844
+ for (let l = fn.body[0]; l <= fn.body[1]; l++) {
2845
+ const t = srcLines[l - 1] ?? '';
2846
+ if (TRIVIA_LINE.test(t) || trivia.test(t) || commentLines.has(l) || (fn.topLevel && inDefinition(l))) continue;
2847
+ real++;
2848
+ if (covered.has(l)) hit++; else if (missing.length < 5) missing.push(l);
2849
+ }
2850
+ anchor = { schema: 'thunder-anchor-v1', bodyLines: fn.body, codeLines: real, coveredLines: hit, coverage: real ? Math.round((hit / real) * 1000) / 1000 : 1, missing };
2851
+ }
2852
+ for (const st of allSteps(steps)) if (st.span && st.span.exact == null) st.span.exact = 'lines';
2853
+ const readable = steps.length ? steps.filter((x) => x.kind !== 'other' && !x.restates).length / steps.length : 0;
2854
+ const headline = fn.headline ?? (fn.route ? `Handles ${fn.route.method} ${fn.route.path}.` : `${displayLabel(fn.name)} takes ${takes}${fn.returns ? ` and returns ${simpleType(fn.returns)}` : ''}.`);
2855
+ items.push({
2856
+ ...base, kind: 'function', status: 'signature-only',
2857
+ ...(steps.length ? { steps, stepsMore: Math.max(0, steps.length - 14), stepsReadable: Math.round(readable * 100) / 100, ...(anchor ? { anchor } : {}) } : {}),
2858
+ says: fn.headline ?? (fn.route ? headline : `${fn.name} takes ${takes}${fn.returns ? ` and returns ${simpleType(fn.returns)}` : ''}.`),
2859
+ headline, guards: [], unread: [],
2860
+ });
2861
+ }
2862
+ for (const e of r.errors || []) items.push({ id: `error:${e.name}:${e.line}`, kind: 'error', name: e.name, line: e.line, status: 'read', says: `Can fail with the error "${e.name}".`, provenance: 'inferred-from-code' });
2863
+ for (const t of r.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' });
2864
+ items.sort((a, b) => a.line - b.line);
2865
+ for (const it of items) if (it.kind === 'function' || it.kind === 'decision') it.completeness = completenessOf(it);
2866
+ const counts = { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
2867
+ for (const it of items) { counts[it.kind]++; if (it.route) counts.route++; }
2868
+ return {
2869
+ schema: READ_SCHEMA, language: lang, detected, items, counts,
2870
+ limitations: [
2871
+ 'Inferred from code by pattern, not by running it. Confirm a reading before relying on it.',
2872
+ SCRIPT_NOTES[lang],
2873
+ ],
2874
+ };
2875
+ }