@skillstech/thunderlang 0.5.8 → 0.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/learn.cjs CHANGED
@@ -26,9 +26,452 @@ __export(learn_exports, {
26
26
  });
27
27
  module.exports = __toCommonJS(learn_exports);
28
28
 
29
+ // src/sql.mjs
30
+ var words = (s) => String(s).replace(/^["`[]|["`\]]$/g, "").replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
31
+ var unquote = (s) => String(s).trim().replace(/^["`[](.*)["`\]]$/, "$1");
32
+ var bare = (name) => unquote(String(name).split(".").pop());
33
+ var singular = (w) => w.replace(/ies$/, "y").replace(/(ss|sh|ch|x)es$/, "$1").replace(/([^s])s$/, "$1");
34
+ var article = (w) => /^[aeiou]/i.test(w) ? `an ${w}` : `a ${w}`;
35
+ function lineFinder(src) {
36
+ const starts = [0];
37
+ for (let i = src.indexOf("\n"); i >= 0; i = src.indexOf("\n", i + 1)) starts.push(i + 1);
38
+ return (idx) => {
39
+ let lo = 0, hi = starts.length - 1;
40
+ while (lo < hi) {
41
+ const mid = lo + hi + 1 >> 1;
42
+ if (starts[mid] <= idx) lo = mid;
43
+ else hi = mid - 1;
44
+ }
45
+ return lo + 1;
46
+ };
47
+ }
48
+ function mask(src) {
49
+ let out = "";
50
+ for (let i = 0; i < src.length; i++) {
51
+ const c = src[i];
52
+ if (c === "-" && src[i + 1] === "-") {
53
+ const n = src.indexOf("\n", i);
54
+ const end = n < 0 ? src.length : n;
55
+ out += " ".repeat(end - i);
56
+ i = end - 1;
57
+ continue;
58
+ }
59
+ if (c === "/" && src[i + 1] === "*") {
60
+ const n = src.indexOf("*/", i + 2);
61
+ const end = n < 0 ? src.length : n + 2;
62
+ out += src.slice(i, end).replace(/[^\n]/g, " ");
63
+ i = end - 1;
64
+ continue;
65
+ }
66
+ if (c === "'") {
67
+ let j = i + 1;
68
+ for (; j < src.length; j++) {
69
+ if (src[j] === "'" && src[j + 1] === "'") {
70
+ j++;
71
+ continue;
72
+ }
73
+ if (src[j] === "'") break;
74
+ }
75
+ out += "'" + src.slice(i + 1, j).replace(/[^\n]/g, "x") + (j < src.length ? "'" : "");
76
+ i = j;
77
+ continue;
78
+ }
79
+ out += c;
80
+ }
81
+ return out;
82
+ }
83
+ function parenEnd(m, open) {
84
+ for (let i = open, d = 0; i < m.length; i++) {
85
+ if (m[i] === "(") d++;
86
+ else if (m[i] === ")" && --d === 0) return i;
87
+ }
88
+ return -1;
89
+ }
90
+ function splitTop(text, masked = mask(text)) {
91
+ const out = [];
92
+ let d = 0, start = 0;
93
+ for (let i = 0; i < masked.length; i++) {
94
+ if (masked[i] === "(") d++;
95
+ else if (masked[i] === ")") d--;
96
+ else if (masked[i] === "," && d === 0) {
97
+ out.push({ text: text.slice(start, i), at: start });
98
+ start = i + 1;
99
+ }
100
+ }
101
+ out.push({ text: text.slice(start), at: start });
102
+ return out.filter((p) => p.text.trim());
103
+ }
104
+ function docAbove(src, idx) {
105
+ const lines = src.slice(0, idx).split("\n");
106
+ lines.pop();
107
+ const run = [];
108
+ for (let k = lines.length - 1; k >= 0 && /^\s*--/.test(lines[k]); k--) run.unshift(lines[k].replace(/^\s*--+\s?/, "").trim());
109
+ const text = run.filter(Boolean).join(" ");
110
+ return text || null;
111
+ }
112
+ var TYPE_WORDS = [
113
+ [/^(small|big)?serial\b|^serial\d/i, "a number, given automatically"],
114
+ [/^(int|integer|smallint|bigint|tinyint|mediumint|numeric|decimal|real|float|double|money|number)\b|^int\d/i, "a number"],
115
+ [/^(text|varchar|char|character|nvarchar|nchar|citext|string|clob)\b/i, "words"],
116
+ [/^(bool|boolean|bit)\b/i, "yes or no"],
117
+ [/^(date|time|timestamp|timestamptz|datetime|datetime2|interval)\b/i, "a date"],
118
+ [/^uuid\b|^uniqueidentifier\b/i, "an id"],
119
+ [/^jsonb?\b/i, "structured data"],
120
+ [/^(bytea|blob|binary|varbinary)\b/i, "a file or bytes"]
121
+ ];
122
+ var typeWords = (t) => {
123
+ for (const [re, w] of TYPE_WORDS) if (re.test(String(t).trim())) return w;
124
+ return /\[\]$/.test(String(t).trim()) ? "a list" : null;
125
+ };
126
+ function defaultWords(v) {
127
+ const e = String(v).trim().replace(/::\w+(\[\])?$/, "");
128
+ if (/^null$/i.test(e)) return "nothing at first";
129
+ if (/^(true|false)$/i.test(e)) return `${/^true$/i.test(e) ? "yes" : "no"} at first`;
130
+ if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
131
+ if (/^'.*'$/s.test(e)) return `"${e.slice(1, -1).replace(/''/g, "'")}" at first`;
132
+ if (/^(now\(\)|current_timestamp|current_date|getdate\(\)|sysdate|localtimestamp|transaction_timestamp\(\))$/i.test(e)) return "the moment it is saved";
133
+ if (/gen_random_uuid|uuid_generate|newid\(\)/i.test(e)) return "a new id";
134
+ return "worked out when it is saved";
135
+ }
136
+ function sqlCondition(cond, { aliases = {}, vars = false } = {}) {
137
+ let c = String(cond).trim().replace(/\s+/g, " ");
138
+ while (/^\(.*\)$/.test(c) && parenEnd(mask(c), 0) === c.length - 1) c = c.slice(1, -1).trim();
139
+ c = c.replace(/'((?:[^']|'')*)'/g, (m, v) => `"${v.replace(/''/g, "'")}"`);
140
+ const plain = (x) => words(vars ? String(x).replace(/^(?:p|v|l|in|out|var)_(?=\w)/i, "") : x);
141
+ const name = (x) => {
142
+ const p = String(x).split(".");
143
+ if (p.length < 2) return plain(x);
144
+ const table = aliases[p[0].toLowerCase()] ?? p[0];
145
+ return `the ${singular(words(table))}'s ${words(p[1])}`;
146
+ };
147
+ return c.replace(/\b(NEW|OLD)\.(\w+)/g, (m, which, col) => `the ${which === "NEW" ? "new" : "old"} ${words(col)}`).replace(/([\w."]+)\s+NOT\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => `${name(a)} is not one of ${l.split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")).join(", ")}`).replace(/([\w."]+)\s+IN\s*\(([^)]*)\)/gi, (m, a, l) => /^\s*select\b/i.test(l) ? `${name(a)} is in the results of a query` : `${name(a)} is one of ${l.split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")).join(", ")}`).replace(/([\w."]+)\s+IS\s+NOT\s+NULL/gi, (m, a) => `${name(a)} is set`).replace(/([\w."]+)\s+IS\s+NULL/gi, (m, a) => `${name(a)} is empty`).replace(/([\w.]+)\s+NOT\s+LIKE\s+"([^"]*)"/gi, (m, a, p) => `${name(a)} does not match "${p.replace(/%/g, "\u2026")}"`).replace(/([\w.]+)\s+I?LIKE\s+"([^"]*)"/gi, (m, a, p) => /^[^%]+%$/.test(p) ? `${name(a)} starts with "${p.slice(0, -1)}"` : /^%[^%]+%$/.test(p) ? `${name(a)} contains "${p.slice(1, -1)}"` : `${name(a)} matches "${p.replace(/%/g, "\u2026")}"`).replace(/([\w."]+)\s+BETWEEN\s+(\S+)\s+AND\s+(\S+)/gi, (m, a, lo, hi) => `${name(a)} is from ${lo} to ${hi}`).replace(/\s*(<>|!=)\s*/g, " is not ").replace(/\s*>=\s*/g, " is at least ").replace(/\s*<=\s*/g, " is at most ").replace(/\s*>\s*/g, " is more than ").replace(/\s*<\s*/g, " is less than ").replace(/\s*=\s*/g, " is ").replace(/\bAND\b/gi, "and").replace(/\bOR\b/gi, "or").replace(/\bNOT\s+/gi, "not ").replace(/\b(?:length|char_length)\s*\(\s*([\w."]+)\s*\)/gi, (m, a) => `the length of ${name(a)}`).replace(/\b(?!is\b|and\b|or\b|not\b|at\b|least\b|most\b|more\b|less\b|than\b|one\b|of\b|the\b|set\b|empty\b|from\b|to\b|new\b|old\b|starts\b|with\b|contains\b|does\b|match\b|matches\b|in\b|results\b|a\b|query\b|length\b|s\b)([a-z_][\w]*\.)?([a-z_][\w]*)\b(?![^"]*"(?:[^"]*"[^"]*")*[^"]*$)/gi, (m, t, col) => t ? name(`${t}${col}`) : /^[A-Z_]+$/.test(col) && col.length > 1 ? m : plain(col)).replace(/\s+/g, " ").trim();
148
+ }
149
+ function readSchema(src) {
150
+ const m = mask(src);
151
+ const lineAt2 = lineFinder(src);
152
+ const tables = [], choices = [], rules = [];
153
+ const docs = /* @__PURE__ */ new Map();
154
+ for (const c of src.matchAll(/COMMENT\s+ON\s+TABLE\s+([\w."]+)\s+IS\s+'((?:[^']|'')*)'/gi)) docs.set(bare(c[1]).toLowerCase(), c[2].replace(/''/g, "'"));
155
+ for (const t of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w."[\]`]+)\s*\(/gi)) {
156
+ const open = t.index + t[0].length - 1;
157
+ const close = parenEnd(m, open);
158
+ if (close < 0) continue;
159
+ const name = bare(src.slice(t.index, open).match(/([\w."[\]`]+)\s*$/)[1]);
160
+ const table = { name, lines: [lineAt2(t.index), lineAt2(close)], doc: docs.get(name.toLowerCase()) ?? docAbove(src, t.index), columns: [], checks: [], uniques: [], refs: [] };
161
+ for (const part of splitTop(src.slice(open + 1, close), m.slice(open + 1, close))) {
162
+ const text = part.text.trim().replace(/\s+/g, " ");
163
+ const line = lineAt2(open + 1 + part.at + (part.text.length - part.text.trimStart().length));
164
+ let x;
165
+ if (x = text.match(/^(?:CONSTRAINT\s+([\w"]+)\s+)?CHECK\s*\((.*)\)$/i)) {
166
+ table.checks.push({ name: x[1] && unquote(x[1]), cond: x[2], line });
167
+ continue;
168
+ }
169
+ if (x = text.match(/^(?:CONSTRAINT\s+([\w"`]+)\s+)?UNIQUE(?:\s+(?:KEY|INDEX))?(?:\s+([\w"`]+))?\s*\(([^)]*)\)/i)) {
170
+ table.uniques.push({ name: (x[1] || x[2]) && unquote(x[1] || x[2]), cols: x[3].split(",").map((c) => unquote(c.trim())), line });
171
+ continue;
172
+ }
173
+ if (x = text.match(/^(?:CONSTRAINT\s+[\w"]+\s+)?FOREIGN\s+KEY\s*\(([^)]*)\)\s+REFERENCES\s+([\w."]+)/i)) {
174
+ for (const c of x[1].split(",")) table.refs.push({ col: unquote(c.trim()), to: bare(x[2]) });
175
+ continue;
176
+ }
177
+ if (/^(?:CONSTRAINT\s+[\w"]+\s+)?(PRIMARY\s+KEY|INDEX|KEY|EXCLUDE)\b/i.test(text)) continue;
178
+ const col = text.match(/^([\w"`[\]]+)\s+([\w]+(?:\s*\([^)]*\))?(?:\s+(?:varying|precision|with(?:out)?\s+time\s+zone))*(?:\[\])?)(.*)$/i);
179
+ if (!col || /^(LIKE|PERIOD)$/i.test(col[1])) continue;
180
+ const rest2 = col[3] || "";
181
+ const ref = rest2.match(/\bREFERENCES\s+([\w."]+)/i);
182
+ const def = rest2.match(/\bDEFAULT\s+('(?:[^']|'')*'|\([^)]*\)|[\w.:]+(?:\(\))?)/i);
183
+ const column = { name: unquote(col[1]), type: col[2], line, primary: /\bPRIMARY\s+KEY\b/i.test(rest2), notNull: /\bNOT\s+NULL\b/i.test(rest2), ...def ? { default: def[1] } : {}, ...ref ? { ref: bare(ref[1]) } : {} };
184
+ table.columns.push(column);
185
+ const check = rest2.match(/\bCHECK\s*\((.*)\)/i);
186
+ if (check) table.checks.push({ cond: check[1], line });
187
+ if (/\bUNIQUE\b/i.test(rest2)) table.uniques.push({ cols: [column.name], line });
188
+ }
189
+ tables.push(table);
190
+ }
191
+ for (const e of m.matchAll(/\bCREATE\s+TYPE\s+([\w."]+)\s+AS\s+ENUM\s*\(/gi)) {
192
+ const open = e.index + e[0].length - 1;
193
+ const close = parenEnd(m, open);
194
+ if (close < 0) continue;
195
+ const values = [...src.slice(open + 1, close).matchAll(/'((?:[^']|'')*)'/g)].map((v) => v[1].replace(/''/g, "'").replace(/_/g, " "));
196
+ choices.push({ name: bare(e[1]), lines: [lineAt2(e.index), lineAt2(close)], doc: docAbove(src, e.index), values });
197
+ }
198
+ for (const t of tables) {
199
+ for (const c of t.checks) rules.push({ table: t.name, kind: "check", ...c });
200
+ for (const u of t.uniques) rules.push({ table: t.name, kind: "unique", ...u });
201
+ }
202
+ return { tables, choices, rules };
203
+ }
204
+ function sqlThings(src, file) {
205
+ const { tables, choices } = readSchema(src);
206
+ const enums = new Set(choices.map((c) => c.name.toLowerCase()));
207
+ const out = [];
208
+ for (const t of tables) {
209
+ const refs = new Map(t.refs.map((r) => [r.col, r.to]));
210
+ const knows = t.columns.map((c) => {
211
+ const to = c.ref ?? refs.get(c.name);
212
+ const kind = to ? `${article(singular(words(to)))} (by its id)` : c.primary ? `${typeWords(c.type) ?? "a value"}, the id` : enums.has(bare(c.type).toLowerCase()) ? article(words(bare(c.type))) : typeWords(c.type);
213
+ return { name: c.name, label: words(c.name), kind: kind && c.notNull && !c.primary ? `${kind}, always set` : kind, start: c.default != null ? defaultWords(c.default) : null, line: c.line };
214
+ });
215
+ out.push({ kind: t.checks.length || t.uniques.length ? "thing" : "record", name: t.name, file, lines: t.lines, ...t.doc ? { doc: t.doc } : {}, knows, choices: [] });
216
+ }
217
+ for (const c of choices) out.push({ kind: "choices", name: c.name, file, lines: c.lines, ...c.doc ? { doc: c.doc } : {}, knows: [], choices: c.values });
218
+ return out;
219
+ }
220
+ var colWords = (expr) => {
221
+ const e = expr.trim();
222
+ const as = e.match(/\s+(?:AS\s+)?([\w"]+)$/i);
223
+ if (as && !/^(DESC|ASC|END)$/i.test(as[1]) && /[\s)]/.test(e.slice(0, as.index + 1))) return words(unquote(as[1]));
224
+ const agg = e.match(/^(count|sum|avg|min|max)\s*\(\s*(distinct\s+)?([^)]*)\)$/i);
225
+ if (agg) {
226
+ const what = agg[3].trim() === "*" ? "rows" : words(bare(agg[3]));
227
+ return { count: `how many ${what === "rows" ? "rows" : what}`, sum: `the total of ${what}`, avg: `the average ${what}`, min: `the lowest ${what}`, max: `the highest ${what}` }[agg[1].toLowerCase()];
228
+ }
229
+ if (e === "*") return "every column";
230
+ if (/^\w+\.\*$/.test(e)) return `every column of ${words(e.split(".")[0])}`;
231
+ return /^[\w."]+$/.test(e) ? words(bare(e)) : "a worked-out value";
232
+ };
233
+ var listWords = (xs) => xs.length <= 1 ? xs.join("") : `${xs.slice(0, -1).join(", ")}${xs.length > 2 ? "," : ""} and ${xs.at(-1)}`;
234
+ function selectSteps(sql, line, { give = true, vars = false } = {}) {
235
+ const s = sql.replace(/\s+/g, " ").trim().replace(/;$/, "");
236
+ const m = mask(s);
237
+ const at = (kw) => {
238
+ const r = new RegExp(`\\b${kw}\\b`, "i").exec(m);
239
+ return r ? r.index : -1;
240
+ };
241
+ const clauses = ["SELECT", "FROM", "WHERE", "GROUP BY", "HAVING", "ORDER BY", "LIMIT", "OFFSET", "INTO"].map((k) => [k, at(k)]).filter(([, i]) => i >= 0).sort((a, b) => a[1] - b[1]);
242
+ const part = (k) => {
243
+ const i = clauses.findIndex(([n]) => n === k);
244
+ if (i < 0) return null;
245
+ const start = clauses[i][1] + k.length;
246
+ const end = clauses[i + 1]?.[1] ?? s.length;
247
+ return s.slice(start, end).trim();
248
+ };
249
+ const steps = [];
250
+ const code = s;
251
+ const from = part("FROM");
252
+ const aliases = {};
253
+ for (const a of (from || "").matchAll(/([\w."]+)\s+(?:AS\s+)?([a-z_]\w*)\b(?=\s*(?:,|$|\bON\b|\bJOIN\b|\bLEFT\b|\bRIGHT\b|\bINNER\b|\bFULL\b|\bCROSS\b|\bWHERE\b))/gi)) {
254
+ if (!/^(ON|JOIN|LEFT|RIGHT|INNER|FULL|CROSS|OUTER|WHERE|AS)$/i.test(a[2])) aliases[a[2].toLowerCase()] = bare(a[1]);
255
+ }
256
+ const cond = (text) => sqlCondition(text, { aliases, vars });
257
+ if (from) {
258
+ const [first, ...joins] = from.split(/\b(?:(?:LEFT|RIGHT|INNER|FULL|CROSS)\s+(?:OUTER\s+)?)?JOIN\b/i);
259
+ const base = bare(first.trim().split(/\s+/)[0]);
260
+ steps.push({ kind: "call", callee: "find", says: `Finds the ${words(base)}`, code, line });
261
+ for (const j of joins) {
262
+ const jt = bare(j.trim().split(/\s+/)[0]);
263
+ const left = /\bLEFT\b/i.test(from.slice(0, from.indexOf(j)).slice(-20));
264
+ steps.push({ kind: "call", callee: "find", says: `${left ? "Adds, when there is one," : "Adds"} the matching ${words(singular(jt))} to each`, code, line });
265
+ }
266
+ }
267
+ const where = part("WHERE");
268
+ if (where) steps.push({ kind: "call", callee: "filter", says: `Keeps only those where ${cond(where)}`, code, line });
269
+ const group = part("GROUP BY");
270
+ if (group) steps.push({ kind: "set", says: `Groups them by ${listWords(splitTop(group).map((p) => words(bare(p.text.trim()))))}`, code, line });
271
+ const having = part("HAVING");
272
+ if (having) steps.push({ kind: "call", callee: "filter", says: `Keeps only groups where ${cond(having.replace(/\b(count|sum|avg|min|max)\s*\(([^)]*)\)/gi, (x) => colWords(x).replace(/ /g, "_")))}`.replace(/_/g, " "), code, line });
273
+ const order = part("ORDER BY");
274
+ if (order) steps.push({ kind: "set", says: `Sorts them by ${listWords(splitTop(order).map((p) => {
275
+ const t = p.text.trim();
276
+ return `${colWords(t.replace(/\s+(ASC|DESC)(\s+NULLS\s+(FIRST|LAST))?$/i, ""))}${/\bDESC\b/i.test(t) ? ", highest first" : ""}`;
277
+ }))}`, code, line });
278
+ const limit = part("LIMIT");
279
+ if (limit && /^\d+/.test(limit)) steps.push({ kind: "set", says: `Takes the first ${limit.match(/^\d+/)[0]}`, code, line });
280
+ const cols = part("SELECT");
281
+ if (give && cols) {
282
+ const names = splitTop(cols.replace(/^DISTINCT\s+/i, "")).map((p) => colWords(p.text));
283
+ steps.push({ kind: "return", says: `Returns ${listWords(names.length > 8 ? [...names.slice(0, 7), "more"] : names)}`, code, line });
284
+ }
285
+ return steps;
286
+ }
287
+ function bodyStatement(text, line) {
288
+ const cnd = (x2) => sqlCondition(x2, { vars: true });
289
+ const v = (x2) => words(String(x2).replace(/^(?:p|v|l|var)_(?=\w)/i, ""));
290
+ const t = text.replace(/\s+/g, " ").trim().replace(/;$/, "");
291
+ const code = t;
292
+ let x;
293
+ if (x = t.match(/^RAISE\s+(?:EXCEPTION|ERROR)\s+'((?:[^']|'')*)'/i)) {
294
+ const msg = x[1].replace(/''/g, "'").replace(/%/g, "\u2026");
295
+ return { kind: "fail", says: `Fails with an error: "${msg}"`, error: "an error", message: msg, code, line };
296
+ }
297
+ if ((x = t.match(/^(?:RAISERROR|THROW)\s*\(?\s*(?:\d+\s*,\s*)?N?'((?:[^']|'')*)'/i)) || (x = t.match(/^SIGNAL\s+SQLSTATE\s+'\w+'\s+SET\s+MESSAGE_TEXT\s*=\s*'((?:[^']|'')*)'/i))) return { kind: "fail", says: `Fails with an error: "${x[1].replace(/''/g, "'")}"`, error: "an error", message: x[1].replace(/''/g, "'"), code, line };
298
+ if (x = t.match(/^RETURN\s+QUERY\s+(SELECT\b.*)$/i)) return { kind: "return", says: selectSteps(x[1], line).at(-1)?.says ?? "Returns the rows a query finds", code, line, query: selectSteps(x[1], line, { give: false }) };
299
+ if (x = t.match(/^RETURN\s+(NEW|OLD)$/i)) return { kind: "return", says: x[1].toUpperCase() === "NEW" ? "Lets the change go ahead" : "Keeps the old row", code, line };
300
+ if (x = t.match(/^RETURN\s*(.*)$/i)) return { kind: "return", says: x[1] ? /^'(.*)'$/.test(x[1]) ? `Returns "${x[1].slice(1, -1)}"` : /^(true|false)$/i.test(x[1]) ? `Returns ${x[1].toLowerCase() === "true" ? "yes" : "no"}` : `Returns ${cnd(x[1])}` : "Stops here", code, line };
301
+ if (x = t.match(/^INSERT\s+INTO\s+([\w."]+)(?:\s*\(([^)]*)\))?/i)) return { kind: "call", says: `Records a new ${singular(words(bare(x[1])))}${x[2] ? ` with ${listWords(x[2].split(",").map((c) => words(c.trim())))}` : ""}`, code, line };
302
+ if (x = t.match(/^UPDATE\s+([\w."]+)\s+SET\s+(.*?)(?:\s+WHERE\s+(.*))?$/i)) {
303
+ const sets = splitTop(x[2]).map((p) => {
304
+ const kv = p.text.match(/^\s*([\w."]+)\s*=\s*(.*)$/s);
305
+ return kv ? `${words(bare(kv[1]))} to ${/^'.*'$/.test(kv[2].trim()) ? `"${kv[2].trim().slice(1, -1)}"` : cnd(kv[2])}` : null;
306
+ }).filter(Boolean);
307
+ return { kind: "call", says: `Records the change in ${words(bare(x[1]))}: sets ${listWords(sets)}${x[3] ? ` where ${cnd(x[3])}` : ""}`, code, line };
308
+ }
309
+ if (x = t.match(/^DELETE\s+FROM\s+([\w."]+)(?:\s+WHERE\s+(.*))?$/i)) return { kind: "call", says: `Removes ${words(bare(x[1]))}${x[2] ? ` where ${cnd(x[2])}` : ""}`, code, line };
310
+ if (x = t.match(/^SELECT\s+(.*?)\s+INTO\s+(?:STRICT\s+)?([\w,\s]+?)\s+FROM\s+(.*)$/i)) {
311
+ const from = x[3].match(/^([\w."]+)(?:\s+(?:AS\s+)?\w+)?(?:\s+WHERE\s+(.*))?$/i);
312
+ const what = listWords(x[2].split(",").map((n) => v(n.trim())));
313
+ if (from) return { kind: "call", callee: "find", says: `Finds ${what} in the ${words(bare(from[1]))}${from[2] ? ` where ${cnd(from[2])}` : ""}`, code, line };
314
+ const found = selectSteps(`SELECT ${x[1]} FROM ${x[3]}`, line, { give: false, vars: true });
315
+ return { kind: "call", callee: "find", says: `Finds ${what}: ${found.map((f) => f.says.charAt(0).toLowerCase() + f.says.slice(1)).join(", ")}`, code, line };
316
+ }
317
+ if (x = t.match(/^(?:PERFORM|CALL|EXEC(?:UTE)?)\s+([\w.]+)\s*\(/i)) return { kind: "call", says: `Runs ${words(bare(x[1]))}`, code, line };
318
+ if (x = t.match(/^(?:SET\s+)?@?([\w.]+)\s*:?=\s*(.+)$/i)) return { kind: "set", says: `Sets ${v(bare(x[1]))} to ${/^'.*'$/.test(x[2].trim()) ? `"${x[2].trim().slice(1, -1)}"` : cnd(x[2])}`, code, line };
319
+ return { kind: "other", says: code, code, line, restates: code };
320
+ }
321
+ function procSteps(body, firstLine) {
322
+ const m = mask(body);
323
+ const stmts = [];
324
+ let start = 0;
325
+ const re = /;|\bTHEN\b|\bELSE\b(?!\s*IF)|\bELSIF\b|\bELSEIF\b|\bEND\s+IF\b|\bBEGIN\b|\bEND\b(?!\s+IF)/gi;
326
+ const lineAt2 = lineFinder(body);
327
+ let r;
328
+ while (r = re.exec(m)) {
329
+ const kw = r[0].toUpperCase().replace(/\s+/g, " ");
330
+ if (kw === ";") {
331
+ const text = body.slice(start, r.index).trim();
332
+ if (text) stmts.push({ text, line: firstLine + lineAt2(start + (body.slice(start).length - body.slice(start).trimStart().length)) - 1 });
333
+ start = r.index + 1;
334
+ continue;
335
+ }
336
+ if (kw === "THEN") {
337
+ stmts.push({ text: body.slice(start, r.index).trim(), line: firstLine + lineAt2(start + (body.slice(start).length - body.slice(start).trimStart().length)) - 1, then: true });
338
+ start = r.index + r[0].length;
339
+ continue;
340
+ }
341
+ const before = body.slice(start, r.index).trim();
342
+ if (before) stmts.push({ text: before, line: firstLine + lineAt2(start) - 1 });
343
+ stmts.push({ keyword: kw === "ELSEIF" ? "ELSIF" : kw });
344
+ start = r.index + r[0].length;
345
+ }
346
+ const tail = body.slice(start).trim();
347
+ if (tail) stmts.push({ text: tail, line: firstLine + lineAt2(start) - 1 });
348
+ let i = 0;
349
+ const block = (stop) => {
350
+ const out = [];
351
+ while (i < stmts.length) {
352
+ const s = stmts[i];
353
+ if (s.keyword && stop.includes(s.keyword)) return out;
354
+ i++;
355
+ if (s.keyword === "BEGIN" || s.keyword === "END") continue;
356
+ if (s.then && /^(IF|ELSIF)\b/i.test(s.text)) {
357
+ const cond = s.text.replace(/^(IF|ELSIF)\s+/i, "");
358
+ const step = { kind: "branch", says: `If ${sqlCondition(cond, { vars: true })}`, code: s.text, line: s.line, children: block(["ELSIF", "ELSE", "END IF"]) };
359
+ let tail2 = step;
360
+ while (stmts[i]?.keyword === "ELSIF") {
361
+ i++;
362
+ const h = stmts[i++];
363
+ const next = { kind: "branch", says: `If ${sqlCondition(h.text.replace(/^ELSIF\s+/i, ""), { vars: true })}`, code: h.text, line: h.line, children: block(["ELSIF", "ELSE", "END IF"]) };
364
+ tail2.otherwise = [next];
365
+ tail2 = next;
366
+ }
367
+ if (stmts[i]?.keyword === "ELSE") {
368
+ i++;
369
+ tail2.otherwise = block(["END IF"]);
370
+ }
371
+ if (stmts[i]?.keyword === "END IF") i++;
372
+ out.push(step);
373
+ continue;
374
+ }
375
+ if (s.text && !/^(DECLARE|LANGUAGE|AS)\b/i.test(s.text) && !/^\w+\s+[\w(),]+(\s*:=.*)?$/.test(s.text) || /:=/.test(s.text ?? "")) {
376
+ if (s.text && !/^DECLARE\b/i.test(s.text)) out.push(bodyStatement(s.text.replace(/^DECLARE\s+/i, ""), s.line));
377
+ }
378
+ }
379
+ return out;
380
+ };
381
+ return block([]);
382
+ }
383
+ function sqlItems(src) {
384
+ const m = mask(src);
385
+ const lineAt2 = lineFinder(src);
386
+ const items = [];
387
+ const push = (name, line, steps, extra = {}) => {
388
+ const code = steps.filter((s) => s.kind === "other").length;
389
+ items.push({
390
+ id: `${name}:${line}`,
391
+ name,
392
+ label: words(name).charAt(0).toUpperCase() + words(name).slice(1),
393
+ line,
394
+ inputs: extra.inputs ?? [],
395
+ returns: extra.returns ?? null,
396
+ ...extra.doc ? { doc: extra.doc } : {},
397
+ provenance: "inferred-from-code",
398
+ kind: "function",
399
+ status: "signature-only",
400
+ steps,
401
+ stepsMore: 0,
402
+ stepsReadable: steps.length ? Math.round((steps.length - code) / steps.length * 100) / 100 : 0,
403
+ says: extra.says ?? `${words(name)} has ${steps.length} step${steps.length === 1 ? "" : "s"}.`,
404
+ headline: extra.headline ?? `${words(name)}.`,
405
+ guards: [],
406
+ unread: []
407
+ });
408
+ };
409
+ for (const v of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?([\w."]+)(?:\s*\([^)]*\))?\s+AS\s+/gi)) {
410
+ const end = m.indexOf(";", v.index);
411
+ const query = src.slice(v.index + v[0].length, end < 0 ? src.length : end);
412
+ const name = bare(v[1]);
413
+ push(name, lineAt2(v.index), selectSteps(query, lineAt2(v.index + v[0].length)), { doc: docAbove(src, v.index), says: `${words(name)} is a saved query.`, headline: `${words(name)}: a saved query.` });
414
+ }
415
+ for (const f of m.matchAll(/\bCREATE\s+(?:OR\s+(?:REPLACE|ALTER)\s+)?(?:DEFINER\s*=\s*\S+\s+)?(FUNCTION|PROCEDURE|PROC)\s+([\w."[\]]+)\s*\(/gi)) {
416
+ const open = f.index + f[0].length - 1;
417
+ const close = parenEnd(m, open);
418
+ if (close < 0) continue;
419
+ const name = bare(f[2]);
420
+ const inputs = splitTop(src.slice(open + 1, close)).map((p) => {
421
+ const pm = p.text.trim().match(/^(?:IN\s+|OUT\s+|INOUT\s+)?@?([\w"]+)\s+(.+?)(?:\s+(?:DEFAULT|=)\s+.+)?$/i);
422
+ return pm ? { name: unquote(pm[1]).replace(/^p_|^_/, ""), type: pm[2].trim() } : null;
423
+ }).filter(Boolean);
424
+ const after = src.slice(close + 1);
425
+ const ret = after.match(/^\s*RETURNS\s+(TABLE\s*\([^)]*\)|SETOF\s+[\w.]+|[\w.]+(?:\[\])?)/i);
426
+ const dollar = after.match(/\$(\w*)\$([\s\S]*?)\$\1\$/);
427
+ const beginAt = mask(after).search(/\bBEGIN\b/i);
428
+ const bodyText = dollar ? dollar[2] : beginAt >= 0 ? after.slice(beginAt) : "";
429
+ const bodyStart = close + 1 + (dollar ? dollar.index + dollar[0].indexOf(dollar[2]) : Math.max(beginAt, 0));
430
+ const isTrigger = ret && /^trigger$/i.test(ret[1]);
431
+ const steps = procSteps(bodyText, lineAt2(bodyStart));
432
+ const returns = ret && !isTrigger ? typeWords(ret[1]) ?? (/^(SETOF|TABLE)\b/i.test(ret[1]) ? "rows" : words(ret[1])) : null;
433
+ push(name, lineAt2(f.index), steps, {
434
+ inputs,
435
+ returns,
436
+ doc: docAbove(src, f.index),
437
+ says: `${words(name)} takes ${inputs.length ? inputs.map((p) => words(p.name)).join(", ") : "no inputs"}${returns ? ` and returns ${returns}` : ""}.`,
438
+ headline: `${words(name)} takes ${inputs.length ? inputs.map((p) => words(p.name)).join(", ") : "no inputs"}.`
439
+ });
440
+ }
441
+ for (const t of m.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\s+([\w."]+)\s+(BEFORE|AFTER|INSTEAD\s+OF)\s+([\w\s,]+?)\s+ON\s+([\w."]+)[\s\S]*?EXECUTE\s+(?:FUNCTION|PROCEDURE)\s+([\w.]+)/gi)) {
442
+ const events = t[3].split(/\s+OR\s+/i).map((e) => ({ INSERT: "added", UPDATE: "changed", DELETE: "removed", TRUNCATE: "emptied" })[e.trim().split(/\s+/)[0].toUpperCase()] || words(e)).filter(Boolean);
443
+ const what = article(singular(words(bare(t[4]))));
444
+ const when = `${t[2].toUpperCase() === "BEFORE" ? "Before" : t[2].toUpperCase() === "AFTER" ? "After" : "Instead of when"} ${what} is ${events.join(" or ")}`;
445
+ push(bare(t[1]), lineAt2(t.index), [{ kind: "call", says: `${when}, runs ${words(bare(t[5]))}`, code: t[0].replace(/\s+/g, " "), line: lineAt2(t.index) }], { says: `${when}, the database runs ${words(bare(t[5]))}.`, headline: `${when}.`, doc: docAbove(src, t.index) });
446
+ }
447
+ for (const r of readSchema(src).rules) {
448
+ const table = words(r.table);
449
+ if (r.kind === "check") {
450
+ const cond = sqlCondition(r.cond);
451
+ const name = r.name || `${(r.cond.match(/[a-z_]\w*/i) || ["value"])[0]}_check`;
452
+ push(
453
+ name,
454
+ r.line,
455
+ [{ kind: "branch", says: `If not: ${cond}`, code: `CHECK (${r.cond})`, line: r.line, children: [{ kind: "fail", says: `Fails with Refused by the database: "The ${singular(table)} needs ${cond.replace(/"/g, "'")}"`, error: "Refused by the database", message: `The ${singular(table)} needs ${cond.replace(/"/g, "'")}`, code: `CHECK (${r.cond})`, line: r.line }] }],
456
+ { says: `Every ${singular(table)} must have ${cond}.`, headline: `Every ${singular(table)} must have ${cond}.` }
457
+ );
458
+ } else {
459
+ const cols = listWords(r.cols.map(words));
460
+ push(
461
+ r.name || `unique_${r.cols.join("_and_")}`,
462
+ r.line,
463
+ [{ kind: "branch", says: `If not: no other ${singular(table)} has the same ${cols}`, code: `UNIQUE (${r.cols.join(", ")})`, line: r.line, children: [{ kind: "fail", says: `Fails with Refused by the database: "Each ${cols} can be used only once"`, error: "Refused by the database", message: `Each ${cols} can be used only once`, code: `UNIQUE (${r.cols.join(", ")})`, line: r.line }] }],
464
+ { says: `Each ${cols} can be used by only one ${singular(table)}.`, headline: `Each ${cols} can be used by only one ${singular(table)}.` }
465
+ );
466
+ }
467
+ }
468
+ items.sort((a, b) => a.line - b.line);
469
+ return items;
470
+ }
471
+
29
472
  // src/steps.mjs
30
473
  var MAX_STEPS = 14;
31
- var words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
474
+ var words2 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
32
475
  var clip = (s, n = 70) => {
33
476
  const t = String(s).replace(/\s+/g, " ").trim();
34
477
  return t.length > n ? `${t.slice(0, n - 1)}\u2026` : t;
@@ -44,24 +487,24 @@ var KNOWN_CALLS = [
44
487
  ];
45
488
  var possessiveWords = (path) => {
46
489
  const parts = String(path).replace(/^\$/, "").replace(/\[\s*['"]?([\w$]+)['"]?\s*\]/g, ".$1").split(/\.|->/).filter((x) => x && !/^(self|this)$/.test(x));
47
- return parts.length > 1 ? `the ${words(parts[parts.length - 2])}'s ${words(parts[parts.length - 1])}` : words(parts[0] || path);
490
+ return parts.length > 1 ? `the ${words2(parts[parts.length - 2])}'s ${words2(parts[parts.length - 1])}` : words2(parts[0] || path);
48
491
  };
49
- var plainEnums = (text) => String(text).replace(/\b[A-Z][A-Za-z0-9]*\.([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*)\b(?!\s*\()/g, (m, v) => v.length > 1 && v === v.toUpperCase() ? words(v) : m);
492
+ var plainEnums = (text) => String(text).replace(/\b[A-Z][A-Za-z0-9]*\.([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*)\b(?!\s*\()/g, (m, v) => v.length > 1 && v === v.toUpperCase() ? words2(v) : m);
50
493
  function sayCodeCondition(cond) {
51
494
  let c = plainEnums(String(cond)).trim().replace(/\s*(\{|:|then|do)\s*$/, "").trim();
52
495
  while (c.startsWith("(") && matchingClose(c, 0) === c.length - 1) c = c.slice(1, -1).trim();
53
496
  const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
54
497
  const plural = (w, call2) => !call2 && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
55
- if (prop && plural(words(prop[3]), !!prop[4])) return `${words(prop[2])} ${prop[1] ? "has no" : "has"} ${words(prop[3])}`;
498
+ if (prop && plural(words2(prop[3]), !!prop[4])) return `${words2(prop[2])} ${prop[1] ? "has no" : "has"} ${words2(prop[3])}`;
56
499
  const yesNo = (w, call2) => /^(is|has|can|should|was) /.test(w) || !call2 && (/ed$/.test(w) || /^(active|valid|open|empty|ready|visible|available|enabled|required|admin|public|private|paid|due|overdue|eligible|blocked)$/.test(w));
57
- if (prop && yesNo(words(prop[3]), !!prop[4])) {
500
+ if (prop && yesNo(words2(prop[3]), !!prop[4])) {
58
501
  const neg = !!prop[1];
59
- const w = words(prop[3]).replace(/^(is|has|can|should|was) /, (m) => m);
502
+ const w = words2(prop[3]).replace(/^(is|has|can|should|was) /, (m) => m);
60
503
  const verb = /^(is|was) /.test(w) ? w.replace(/^(is|was) /, neg ? "$1 not " : "$1 ") : /^(has|can|should) /.test(w) ? (neg ? `does not ${w.replace(/^has /, "have ")}` : w).replace(/^does not can /, "cannot ").replace(/^does not should /, "should not ") : `is ${neg ? "not " : ""}${w}`;
61
- return `${words(prop[2])} ${verb}`;
504
+ return `${words2(prop[2])} ${verb}`;
62
505
  }
63
506
  let pred;
64
- if (pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/)) return `${pred[2] ? words(pred[2]) : "it"} is ${pred[1] ? "not " : ""}${words(pred[3])}`;
507
+ if (pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/)) return `${pred[2] ? words2(pred[2]) : "it"} is ${pred[1] ? "not " : ""}${words2(pred[3])}`;
65
508
  c = c.replace(/\\?\b(?:count|len|sizeof)\(\s*\$?([\w$.\[\]'">-]+)\s*\)/g, (m0, x) => `how many ${possessiveWords(x)}`).replace(/\b([\w$]+(?:\.[\w$]+)*)\.(?:length|Length|Count|count\(\)|size\(\)|len\(\))(?![\w(])/g, (m0, x) => `how many ${possessiveWords(x)}`);
66
509
  c = c.replace(/\\(?=[a-z_]\w*\()/g, "");
67
510
  let call;
@@ -71,14 +514,14 @@ function sayCodeCondition(cond) {
71
514
  return call[2] === "isset" || call[2] === "is_null" ? `${what} is ${call[2] === "isset" === !call[1] ? "" : "not "}set` : `${what} is ${neg ? "not " : ""}empty`;
72
515
  }
73
516
  if (call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?((?:is|has|can|should|was|are|does)[A-Z_]\w*)\s*\([^()]*\)$/)) {
74
- const w = words(call[2]);
517
+ const w = words2(call[2]);
75
518
  return call[1] ? `not: ${w}` : w;
76
519
  }
77
- const bare = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
78
- if (bare && !/^(true|false|True|False|None|null|nil)$/.test(bare[2])) {
79
- const parts = bare[2].split(".");
80
- const what = parts.length > 1 ? `the ${words(parts[0])}'s ${words(parts[1])}` : words(parts[0]);
81
- return `${what} is ${bare[1] ? "not " : ""}set`;
520
+ const bare2 = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
521
+ if (bare2 && !/^(true|false|True|False|None|null|nil)$/.test(bare2[2])) {
522
+ const parts = bare2[2].split(".");
523
+ const what = parts.length > 1 ? `the ${words2(parts[0])}'s ${words2(parts[1])}` : words2(parts[0]);
524
+ return `${what} is ${bare2[1] ? "not " : ""}set`;
82
525
  }
83
526
  return clip(c.replace(/\s*(===|==)\s*(nil|null|None|undefined|""|'')(?=\s|\)|$)/g, " is empty").replace(/\s*(!==|!=)\s*(""|'')(?=\s|\)|$)/g, " is not empty").replace(/\s*(!==|!=)\s*(nil|null|None|undefined)\b/g, " is set").replace(/\bis not None\b/g, "is set").replace(/\bis None\b/g, "is empty").replace(/\s*(===|==)\s*/g, " is ").replace(/\s*(!==|!=)\s*/g, " is not ").replace(/\s*&&\s*/g, " and ").replace(/\s*\|\|\s*/g, " or ").replace(/\s+not\s+in\s+/g, " is not in ").replace(/(?<!\bis(?: not)?)\s+in\s+(?=[\w$])/g, " is in ").replace(/\s+<=\s+/g, " is at most ").replace(/\s+>=\s+/g, " is at least ").replace(/\s+<\s+/g, " is less than ").replace(/(?<![-=])\s+>\s+/g, " is more than ").replace(/(^|[\s(])!(?=[\w(])/g, "$1not ").replace(/\s+/g, " "), 70);
84
527
  }
@@ -90,11 +533,11 @@ function matchingClose(str, open) {
90
533
  }
91
534
  return -1;
92
535
  }
93
- var lastWords = (path) => words(String(path).split(".").pop());
536
+ var lastWords = (path) => words2(String(path).split(".").pop());
94
537
  function targetWords(path) {
95
538
  const parts = String(path).replace(/^[@$]+/, "").replace(/#/g, "").replace(/\[.*$/, "").split(".").filter((p) => !/^(this|self)$/.test(p));
96
- if (parts.length <= 1) return words(parts[0] || path);
97
- return `the ${words(parts[parts.length - 2])}'s ${words(parts[parts.length - 1])}`;
539
+ if (parts.length <= 1) return words2(parts[0] || path);
540
+ return `the ${words2(parts[parts.length - 2])}'s ${words2(parts[parts.length - 1])}`;
98
541
  }
99
542
  function callee(text) {
100
543
  const m = String(text).replace(/\[[^\]]*\]/g, "").match(/^(?:await\s+|try\s+|yield\s+|void\s+)?(?:new\s+)?([A-Za-z_$#@][\w$#]*(?:<[^()]*?>)?(?:(?:\.|::|->)[A-Za-z_$#][\w$#]*(?:<[^()]*?>)?(?:\(\))?)*)!?\s*\(/);
@@ -126,10 +569,16 @@ function sayValue(expr) {
126
569
  if (/^new\s/.test(e)) return `a new ${c.split(".").pop()}`;
127
570
  return `the result of ${lastWords(c)}`;
128
571
  }
129
- if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words(e.replace(/^\$/, "").split(".").pop());
572
+ if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words2(e.replace(/^\$/, "").split(".").pop());
130
573
  if (/^\$?[A-Za-z_][\w$]*(?:\[\s*['"]?\w+['"]?\s*\]|->\w+|\.\w+)+$/.test(e)) return possessiveWords(e);
131
574
  return null;
132
575
  }
576
+ function sayArithmetic(expr) {
577
+ const ar = String(expr).trim().match(/^([A-Za-z_$][\w$.]*|\d+(?:\.\d+)?)\s*([-+*/])\s*([A-Za-z_$][\w$.]*|\d+(?:\.\d+)?)$/);
578
+ if (!ar || ar[2] === "+" && !/^\d/.test(ar[1]) && !/^\d/.test(ar[3])) return null;
579
+ const side = (x) => /^\d/.test(x) ? x : possessiveWords(x);
580
+ return `${side(ar[1])} ${{ "+": "plus", "-": "minus", "*": "times", "/": "divided by" }[ar[2]]} ${side(ar[3])}`;
581
+ }
133
582
  var PY_SUMMARY = [
134
583
  { re: /^any$/, say: (src, cond) => `whether any item in ${src}${cond ? ` where ${cond}` : ""} matches` },
135
584
  { re: /^all$/, say: (src, cond) => `whether every item in ${src}${cond ? ` where ${cond}` : ""} matches` },
@@ -138,7 +587,7 @@ var PY_SUMMARY = [
138
587
  { re: /^max$/, say: (src) => `the largest in ${src}` },
139
588
  { re: /^(?:sorted)$/, say: (src) => `${src}, sorted` }
140
589
  ];
141
- var lastSeg = (x) => words(String(x).trim().replace(/\(\)$/, "").split(".").pop());
590
+ var lastSeg = (x) => words2(String(x).trim().replace(/\(\)$/, "").split(".").pop());
142
591
  function sayPython(value) {
143
592
  const e = String(value).trim();
144
593
  let m = e.match(/^\[\s*(.+?)\s+for\s+([\w, ()]+?)\s+in\s+(.+?)(?:\s+if\s+(.+?))?\s*\]$/);
@@ -146,7 +595,7 @@ function sayPython(value) {
146
595
  const [, expr, v, src, cond] = m;
147
596
  const vars = v.replace(/[()]/g, "").split(/\s*,\s*/);
148
597
  const bareCond = cond && cond.replace(new RegExp(`\\b(?:${vars.join("|")})\\.`, "g"), "");
149
- const condSaid = cond ? /^\w+$/.test(bareCond) ? words(bareCond) : sayCodeCondition(bareCond) : null;
598
+ const condSaid = cond ? /^\w+$/.test(bareCond) ? words2(bareCond) : sayCodeCondition(bareCond) : null;
150
599
  if (vars.includes(expr.trim())) return condSaid ? `the items in ${lastSeg(src)} where ${condSaid}` : `the items in ${lastSeg(src)}`;
151
600
  return `one ${lastSeg(expr.replace(/\(.*$/, ""))} for each item in ${lastSeg(src)}${condSaid ? ` where ${condSaid}` : ""}`;
152
601
  }
@@ -166,9 +615,11 @@ function sayPython(value) {
166
615
  function sayCommon(value) {
167
616
  const e = String(value).trim().replace(/\s+as\s+[\w.<>\[\]|, ]+$/, "");
168
617
  let m;
169
- const side = (x) => sayValue(x) ?? possessiveWords(x.trim());
618
+ const side = (x) => sayValue(x) ?? sayArithmetic(x) ?? possessiveWords(x.trim());
170
619
  if ((m = e.match(/^(.+?)\s+\?\s+([^:?]+?)\s+:\s+([^:?]+)$/)) && !/^(?:[\w$]+\??\s*:)/.test(e)) return `${side(m[2])} if ${sayCodeCondition(m[1])}, otherwise ${side(m[3])}`;
171
- if (m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/)) return `${side(m[1])} if ${sayCodeCondition(m[2])}, otherwise ${side(m[3])}`;
620
+ if ((m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/)) && !/^(?:if|unless)\b/.test(e)) return `${side(m[1])} if ${sayCodeCondition(m[2])}, otherwise ${side(m[3])}`;
621
+ const ifValue = ifAsValue(e);
622
+ if (ifValue) return `${side(ifValue.yes)} if ${sayCodeCondition(ifValue.cond)}, otherwise ${side(ifValue.no)}`;
172
623
  if ((m = e.match(/^&?([A-Z]\w*)(?:::new\s*\(|\s*\{)/)) || (m = e.match(/^(?:[\w.]+\.)?([A-Z]\w*)\{/))) return `a new ${m[1]}`;
173
624
  if (m = e.match(/^new\s*\(\s*(?:[\w]+\.)?([A-Z]\w*)\s*\)$/)) return `a new ${m[1]}`;
174
625
  if (m = e.match(/^&([A-Z]\w*)$/)) return `a new ${m[1]}`;
@@ -191,6 +642,20 @@ function sayCommon(value) {
191
642
  if ((m = e.match(/^len\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:length|size\(\)|Count|count\(\)|len\(\))$/))) return `how many ${lastSeg(m[1])}`;
192
643
  return null;
193
644
  }
645
+ function ifAsValue(e) {
646
+ let m;
647
+ if (m = e.match(/^if\s*\(/)) {
648
+ const close = matchingClose(e, e.indexOf("("));
649
+ if (close < 0) return null;
650
+ const rest2 = e.slice(close + 1).match(/^\s*(?:\{\s*([^{};]+?)\s*\}|([^{};]+?))\s+else\s+(?:\{\s*([^{};]+?)\s*\}|([^{};]+))$/);
651
+ if (rest2) return { cond: e.slice(e.indexOf("(") + 1, close), yes: rest2[1] ?? rest2[2], no: rest2[3] ?? rest2[4] };
652
+ return null;
653
+ }
654
+ if (m = e.match(/^if\s+([^{}]+?)\s*\{\s*([^{};]+?)\s*\}\s*else\s*\{\s*([^{};]+?)\s*\}$/)) return { cond: m[1], yes: m[2], no: m[3] };
655
+ if (m = e.match(/^if\s+(.+?)\s+then\s+(.+?)\s+else\s+(.+?)\s+end$/)) return { cond: m[1], yes: m[2], no: m[3] };
656
+ if (m = e.match(/^unless\s+(.+?)\s+then\s+(.+?)\s+else\s+(.+?)\s+end$/)) return { cond: m[1], yes: m[3], no: m[2] };
657
+ return null;
658
+ }
194
659
  var LOGIC = /(&&|\|\||[<>]=?|[!=]==?|\band\b|\bor\b|\bnot\b|\bis\b|^\s*!)/;
195
660
  function sayWhether(expr) {
196
661
  const e = String(expr).trim();
@@ -215,7 +680,7 @@ function sayChain(value) {
215
680
  const m = value.match(c.re);
216
681
  if (m && (!hit || m.index > hit.index)) hit = { index: m.index, c };
217
682
  }
218
- return hit ? hit.c.say(words(src.split(".").pop().replace(/^#/, ""))) : null;
683
+ return hit ? hit.c.say(words2(src.split(".").pop().replace(/^#/, ""))) : null;
219
684
  }
220
685
  var HTTP_STATUS = { 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 410: "Gone", 413: "Payload Too Large", 415: "Unsupported Media Type", 422: "Unprocessable Content", 429: "Too Many Requests", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout" };
221
686
  function httpErrorOf(head) {
@@ -227,32 +692,105 @@ function httpErrorOf(head) {
227
692
  const msg = (expr.match(/\b(?:error|message|detail|msg)\s*[:=]\s*["'`]([^"'`]{1,80})["'`]/) || expr.match(/\.(?:send|json|end)\(\s*["'`]([^"'`]{1,80})["'`]/) || [])[1];
228
693
  return { kind: "fail", says: `Fails with ${status} ${name}${msg ? `: "${msg}"` : ""}`, error: `${status} ${name}`, ...msg ? { message: msg } : {}, status };
229
694
  }
695
+ function redirectTarget(arg) {
696
+ const a = String(arg || "").trim().replace(/^(?:url|to|location|redirect_to)\s*=\s*/, "");
697
+ let m;
698
+ if (m = a.match(/^(?:new\s+URL\(\s*)?["'`](\/[^"'`$?#]*|https?:\/\/[^"'`$/?#]+[^"'`$?#]*)/)) return m[1];
699
+ if (m = a.match(/^`\$\{\s*([A-Za-z_][\w.]*)\s*\}/)) return `the ${words2(m[1].split(".").pop()).replace(/\burl\b/i, "URL")}`;
700
+ if (m = a.match(/\b(?:url_for|reverse|route|url)\(\s*["']([\w.:-]+)["']/)) return `the ${words2(m[1].split(/[.:]/).pop())} page`;
701
+ if (m = a.match(/^([A-Za-z_][\w.]*)$/)) return `the ${words2(m[1].split(".").pop()).replace(/\burl\b/i, "URL")}`;
702
+ return "another page";
703
+ }
704
+ function redirectOf(head) {
705
+ const isReturn = /^return\b/.test(head);
706
+ const expr = head.replace(/^return\s+/, "").replace(/^await\s+/, "").replace(/;\s*$/, "").trim();
707
+ let m = expr.match(/^(?:reply|res|response|resp|ctx|c)\s*\.\s*redirect\s*\(\s*(?:\d{3}\s*,\s*)?(.*)\)\s*$/) || expr.match(/^(?:Response|NextResponse)\s*\.\s*redirect\s*\(\s*(.*?)\s*(?:,\s*\d{3}\s*)?\)\s*$/) || expr.match(/^(?:HttpResponseRedirect|HttpResponsePermanentRedirect|RedirectResponse|redirect)\s*\(\s*(.*?)\s*(?:,\s*(?:\d{3}|status(?:_code)?\s*=\s*\d{3}|permanent\s*=\s*\w+)\s*)?\)\s*$/) || expr.match(/^redirect\(\s*\)\s*->\s*(route\(.*\))\s*$/);
708
+ if (!m) return null;
709
+ const to = redirectTarget(m[1]);
710
+ return { kind: isReturn ? "return" : "call", says: `Sends the person to ${to}`, redirect: to };
711
+ }
712
+ function objectKeys(expr) {
713
+ const open = expr.indexOf("{");
714
+ if (open < 0) return [];
715
+ let close = -1;
716
+ for (let i = open, d = 0; i < expr.length; i++) {
717
+ const c = expr[i];
718
+ if (c === '"' || c === "'" || c === "`") {
719
+ for (i++; i < expr.length && expr[i] !== c; i++) if (expr[i] === "\\") i++;
720
+ continue;
721
+ }
722
+ if (c === "{") d++;
723
+ else if (c === "}" && --d === 0) {
724
+ close = i;
725
+ break;
726
+ }
727
+ }
728
+ if (close < 0) return [];
729
+ const inner = expr.slice(open + 1, close);
730
+ const keys = [];
731
+ let depth = 0, cur = "";
732
+ const take = (part) => {
733
+ const m = part.trim().match(/^(?:["'](\w+)["']|(\w+))\s*(?::|$|\()/);
734
+ if (m && !part.trim().startsWith("...")) keys.push(m[1] || m[2]);
735
+ };
736
+ for (const c of inner) {
737
+ if ("([{".includes(c)) depth++;
738
+ if (")]}".includes(c)) depth--;
739
+ if (c === "," && depth === 0) {
740
+ take(cur);
741
+ cur = "";
742
+ } else cur += c;
743
+ }
744
+ if (cur.trim()) take(cur);
745
+ return keys.length > 8 ? [...keys.slice(0, 7), "more"] : keys;
746
+ }
747
+ var listWords2 = (xs) => xs.length <= 1 ? xs.join("") : `${xs.slice(0, -1).join(", ")}${xs.length > 2 ? "," : ""} and ${xs.at(-1)}`;
230
748
  function classifyStatement(raw, { inner = 0 } = {}) {
231
749
  const text = String(raw).trim();
232
- const head = text.split("\n")[0].trim().replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, "$1").replace(/([\w$\])])!(?=[.(\[])/g, "$1").replace(/\?\.(?=[\w(\[])/g, ".").replace(/\.\(/g, "(").replace(/^\(\*+(self|this)\)\./, "$1.").replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, "$1").replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, "$1");
750
+ let first = text.split("\n")[0].trim();
751
+ if (/^(?:if|else\s+if|while|for|switch)\s*\($/.test(first.replace(/\s*\{$/, "")) || /^(?:if|else\s+if|while)\s*\(/.test(first) && !bracketsClosed(first.replace(/\{\s*$/, ""))) {
752
+ const o = text.indexOf("("), c2 = matchingClose(text, o);
753
+ if (c2 > 0 && c2 < 2e3) first = `${text.slice(0, c2 + 1)}${text.slice(c2 + 1).split("\n")[0]}`.replace(/\s+/g, " ").replace(/\(\s+/g, "(").replace(/\s+\)/g, ")").trim();
754
+ }
755
+ const head = first.replace(/(^|[^\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, "$1$2").replace(/([\w$\])])\(\s*([\w$#.]+)\s+as\s+[^()]+\)/g, "$1($2)").replace(/([\w$\])])!(?=[.(\[])/g, "$1").replace(/\?\.(?=[\w(\[])/g, ".").replace(/\.\(/g, "(").replace(/^\(\*+(self|this)\)\./, "$1.").replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, "$1").replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, "$1");
233
756
  const code = clip(head, 90);
234
757
  let m;
235
758
  const innerNote = inner ? ` (${inner} step${inner === 1 ? "" : "s"} inside)` : "";
236
759
  let inl;
237
- if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?)$/)) && balanced(inl[2])) {
760
+ if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?|[\w$.]+(?:\+\+|--);?|(?:\+\+|--)[\w$.]+;?)$/)) && balanced(inl[2])) {
238
761
  return { kind: "branch", says: `If ${sayCodeCondition(inl[2])}`, cond: inl[2], code, inline: inl[3] };
239
762
  }
240
- if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/^(?:[\w$.\[\]]+\s*=)/.test(inl[1])) {
763
+ if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && bracketsClosed(inl[1]) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/^(?:[\w$.\[\]]+\s*=)/.test(inl[1])) {
241
764
  const cond = sayCodeCondition(inl[3]);
242
765
  return { kind: "branch", says: inl[2] === "unless" ? `If not: ${cond}` : `If ${cond}`, cond: inl[3], negate: inl[2] === "unless", code, inline: inl[1] };
243
766
  }
244
- if (inl = head.match(/^(?:let|var|const)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?;?$/)) return { kind: "set", says: `Starts with no ${words(inl[1])} yet`, code };
767
+ if (inl = head.match(/^(?:let|var|const)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?;?$/)) return { kind: "set", says: `Starts with no ${words2(inl[1])} yet`, code };
245
768
  if (inl = head.match(/^([\w$.]+)\s*=\s*(?:async\s+)?(?:function\b|\([^()]*\)\s*(?::\s*[^=]+)?=>|[\w$]+\s*=>)/)) return { kind: "set", says: `Defines how ${targetWords(inl[1])} works`, code };
246
- if (m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/)) return { kind: "check", says: `When it is ${/^[A-Z][A-Z0-9_]+$/.test(m[1].replace(/^[A-Z]\w*\./, "")) ? words(m[1].replace(/^[A-Z]\w*\./, "")) : sayCodeCondition(plainEnums(m[1]))}`, code, caseLabel: true };
769
+ if (inl = head.match(/^([\w$.]+)\s*:?=\s*func\s*\(/)) return { kind: "set", says: `Defines how ${targetWords(inl[1])} works`, code };
770
+ if (inl = head.match(/^delete\s+([\w$.]+)(?:\[\s*([^\]]+?)\s*\]|\.([\w$]+));?$/)) return { kind: "call", says: `Removes ${words2(String(inl[2] ?? inl[3]).replace(/["'`]/g, ""))} from ${targetWords(inl[1])}`, code };
771
+ if (/^fallthrough\b/.test(head)) return { kind: "call", says: "Carries on into the next case too", code };
772
+ if (inl = head.match(/^goto\s+case\s+(.+?);?$/)) return { kind: "call", says: `Carries on into the case for ${words2(plainEnums(inl[1]))}`, code };
773
+ if (/^do\s*\{?$/.test(head)) {
774
+ const dw = text.match(/\}\s*while\s*\(([\s\S]*)\)\s*;?\s*$/);
775
+ if (dw) return { kind: "loop", says: `Runs once, then repeats while ${sayCodeCondition(dw[1].replace(/\s+/g, " "))}${innerNote}`, code };
776
+ }
777
+ if ((inl = head.match(/^when\s+(.+?)(?:\s+then\s+(.+))?$/)) && !/[{]\s*$/.test(head) && !/^when\s*\(/.test(head)) {
778
+ return { kind: "check", says: armSays(inl[1]), code, caseLabel: true, ...inl[2] ? { inline: inl[2] } : {} };
779
+ }
780
+ if (inl = head.match(/^when\s*(?:\((.+)\))?\s*\{$/)) return { kind: "branch", says: inl[1] ? `Chooses by ${words2(clip(inl[1], 40))}${innerNote}` : `Checks these cases in order${innerNote}`, code };
781
+ if ((m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/)) && /(?:[<>]=?|[!=]==?|&&|\|\|)/.test(m[1].replace(/<-|->/g, "")) && !/^["']/.test(m[1])) return { kind: "check", says: `When ${sayCodeCondition(m[1])}`, code, caseLabel: true };
782
+ if (m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/)) return { kind: "check", says: `When it is ${/^[A-Z][A-Z0-9_]+$/.test(m[1].replace(/^[A-Z]\w*\./, "")) ? words2(m[1].replace(/^[A-Z]\w*\./, "")) : sayCodeCondition(plainEnums(m[1]))}`, code, caseLabel: true };
247
783
  if (/^default\s*(?::|->)/.test(head)) return { kind: "check", says: "Otherwise", code, caseLabel: true };
248
784
  if ((m = head.match(/^(?:throw|raise)\s+(?:new\s+)?([A-Za-z_][\w.]*)?/)) || /^panic!?\s*\(/.test(head)) {
249
785
  const name = m?.[1] ? m[1].split(".").pop() : null;
250
786
  const msg = (head.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
251
- const said = name && /^[a-z]/.test(name) ? `the error made by ${words(name)}` : name;
787
+ const said = name && /^[a-z]/.test(name) ? `the error made by ${words2(name)}` : name;
252
788
  return { kind: "fail", says: `Fails${said ? ` with ${said}` : ""}${msg ? `: "${msg}"` : ""}`, code, ...name ? { error: name } : {}, ...msg ? { message: msg } : {} };
253
789
  }
254
790
  const httpFail = httpErrorOf(head);
255
791
  if (httpFail) return { ...httpFail, code };
792
+ const redirect = redirectOf(head);
793
+ if (redirect) return { ...redirect, code };
256
794
  if (m = head.match(/^return\b\s*(.*)$/)) {
257
795
  const expr = stripTail(m[1]);
258
796
  if (!expr) return { kind: "return", says: "Stops here", code };
@@ -267,26 +805,30 @@ function classifyStatement(raw, { inner = 0 } = {}) {
267
805
  }
268
806
  const chain = sayChain(expr);
269
807
  if (chain) return { kind: "return", says: `Returns ${chain}`, code };
270
- if (/^\(?\s*\{/.test(expr)) return { kind: "return", says: "Returns an object", code };
808
+ if (/^\(?\s*\{/.test(expr)) {
809
+ const keys = objectKeys(expr);
810
+ return { kind: "return", says: keys.length ? `Returns ${listWords2(keys.map(words2))}` : "Returns an object", code, ...keys.length ? { keys } : {} };
811
+ }
271
812
  if (/^\(?\s*</.test(expr)) return { kind: "return", says: "Returns what to show on screen", code };
272
813
  const v = sayValue(expr) || sayWhether(expr);
273
814
  return { kind: "return", says: v ? `Returns ${v}` : "Returns a computed value", code, ...v ? {} : { value: clip(expr, 60) } };
274
815
  }
275
816
  if (m = head.match(/^for\b\s*\(?\s*(?:(?:var|let|const|int|long|size_t|auto|\$)\s*)?\$?(\w+)\s*:?=\s*([^;]+?)\s*;\s*([^;]*?)\s*;\s*[^)]*?\)?\s*\{?\s*$/)) {
276
- return { kind: "loop", says: `Counts ${words(m[1])} from ${clip(m[2], 20)}${m[3] ? ` while ${sayCodeCondition(m[3])}` : ""}${innerNote}`, code };
817
+ return { kind: "loop", says: `Counts ${words2(m[1])} from ${clip(m[2], 20)}${m[3] ? ` while ${sayCodeCondition(m[3])}` : ""}${innerNote}`, code };
277
818
  }
819
+ if (m = head.match(/^for\s*\(\s*[^;]*;\s*([^;]*?)\s*;[^)]*\)\s*\{?\s*$/)) return { kind: "loop", says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
278
820
  if (m = head.match(/^for\b\s*\(?\s*(?:const|let|var|val)?\s*[\[{(]?\s*([\w$]+)\s*,\s*([\w$]+)\s*[\]})]?\s+(?:of|in)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/)) {
279
821
  const src = stripTail(m[3]).replace(/\($/, "()").replace(/^Object\.entries\((.+)\)$/, "$1").replace(/\.(?:items|entries)\(\)$/, "");
280
- return { kind: "loop", says: `For each ${words(m[1])} and ${words(m[2])} in ${words(src.split(".").pop())}${innerNote}`, code };
822
+ return { kind: "loop", says: `For each ${words2(m[1])} and ${words2(m[2])} in ${words2(src.split(".").pop())}${innerNote}`, code };
281
823
  }
282
824
  if (m = head.match(/^for\b\s*\(?\s*(?:const|let|var|val|final|auto|[\w<>\[\],? ]+?\s)?\s*\(?([\w$, _]+?)\)?\s+(?:of|in|:)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/)) {
283
- return { kind: "loop", says: `For each ${words(m[1].split(",").pop().trim())} in ${words(stripTail(m[2]).split(".").pop().replace(/\(\)$/, ""))}${innerNote}`, code };
825
+ return { kind: "loop", says: `For each ${words2(m[1].split(",").pop().trim())} in ${words2(stripTail(m[2]).split(".").pop().replace(/\(\)$/, ""))}${innerNote}`, code };
284
826
  }
285
- if (m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/)) return { kind: "loop", says: `For each item in ${words(stripTail(m[1]).split(".").pop())}${innerNote}`, code };
286
- if (m = head.match(/^foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/)) return { kind: "loop", says: `For each ${words(m[1])} in ${words(m[2].split(".").pop())}${innerNote}`, code };
287
- if (m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:\w+\s*=>\s*)?(\w+)\s*\)\s*\{?$/)) return { kind: "loop", says: `For each ${words(m[2])} in ${words(m[1].split(".").pop())}${innerNote}`, code };
288
- if (m = head.match(/^([\w.]+)\.each(?:_with_index)?\s+do\s*\|(\w+)/)) return { kind: "loop", says: `For each ${words(m[2])} in ${words(m[1].split(".").pop())}${innerNote}`, code };
289
- if (m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/)) return { kind: "loop", says: `For each item in ${words(m[1].split(".").pop())}${innerNote}`, code };
827
+ if (m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/)) return { kind: "loop", says: `For each item in ${words2(stripTail(m[1]).split(".").pop())}${innerNote}`, code };
828
+ if (m = head.match(/^foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/)) return { kind: "loop", says: `For each ${words2(m[1])} in ${words2(m[2].split(".").pop())}${innerNote}`, code };
829
+ if (m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:\w+\s*=>\s*)?(\w+)\s*\)\s*\{?$/)) return { kind: "loop", says: `For each ${words2(m[2])} in ${words2(m[1].split(".").pop())}${innerNote}`, code };
830
+ if (m = head.match(/^([\w.]+)\.each(?:_with_index)?\s+do\s*\|(\w+)/)) return { kind: "loop", says: `For each ${words2(m[2])} in ${words2(m[1].split(".").pop())}${innerNote}`, code };
831
+ if (m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/)) return { kind: "loop", says: `For each item in ${words2(m[1].split(".").pop())}${innerNote}`, code };
290
832
  if (m = head.match(/^(?:while|until|loop)\b\s*\(?(.*?)\)?\s*(?:\{|:|do)?\s*$/)) return { kind: "loop", says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
291
833
  if (m = head.match(/^(?:if|else\s+if)\s+(?:[\w]+\s*,\s*)?err\s*:?=\s*([\w.]+)\(.*\);\s*err\s*!=\s*nil\s*\{?\s*$/)) return { kind: "branch", says: `If ${lastWords(m[1])} fails${innerNote}`, code };
292
834
  if (m = head.match(/^(?:if|else\s+if)\s+[^;{]*:=[^;{]*;\s*(.+?)\s*\{?\s*$/)) {
@@ -297,20 +839,21 @@ function classifyStatement(raw, { inner = 0 } = {}) {
297
839
  const cond = sayCodeCondition(m[1]);
298
840
  return { kind: "branch", says: `If ${/^unless\b/.test(head) ? "not: " : ""}${cond}${innerNote}`, cond: m[1].replace(/^\((.*)\)$/, "$1"), code, negate: /^unless\b/.test(head) };
299
841
  }
300
- if (m = head.match(/^(?:switch|match|case|select)\b\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/)) return { kind: "branch", says: `Chooses by ${words(clip(m[1], 40)) || "value"}${innerNote}`, code };
842
+ if (/^switch\s*(?:true\s*)?\{$/.test(head)) return { kind: "branch", says: `Checks these cases in order${innerNote}`, code };
843
+ if (m = head.match(/^(?:switch|match|case|select)\b\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/)) return { kind: "branch", says: `Chooses by ${words2(clip(m[1], 40)) || "value"}${innerNote}`, code };
301
844
  if (/^(?:try|begin)\b/.test(head)) return { kind: "try", says: `Tries the next steps and handles any error${innerNote}`, code };
302
845
  if (m = head.match(/^assert\b\s*(.*?)\s*;?$/)) return { kind: "check", says: `Checks that ${m[1] ? sayCodeCondition(m[1].replace(/,\s*["'].*$/, "")) : "a condition holds"}`, code };
303
846
  if (m = head.match(/^assert(?:_\w+|That|Equals|True|False|NotNull|Null)\b/)) return { kind: "check", says: `Checks: ${clip(head, 60)}`, code };
304
847
  if (m = head.match(/^(?:expect|t\.(?:Error|Fatal|Errorf|Fatalf|Run)|require\.\w+|assert\.\w+)\b/)) return { kind: "check", says: `Checks: ${clip(head, 60)}`, code };
305
- if (m = head.match(/^with\s+(.+?)\s+as\s+(.+?):\s*$/)) {
306
- const what = /^open\s*\(/.test(m[1]) ? "a file" : words(clip(stripTail(m[1]).replace(/\(.*$/, ""), 40));
307
- return { kind: "set", says: `Opens ${what} as ${words(m[2].replace(/[()]/g, ""))}`, code };
848
+ if (m = head.match(/^(?:async\s+)?with\s+(.+?)\s+as\s+(.+?):\s*$/)) {
849
+ const what = /^open\s*\(/.test(m[1]) ? "a file" : words2(clip(stripTail(m[1]).replace(/\(.*$/, ""), 40));
850
+ return { kind: "set", says: `Opens ${what} as ${words2(m[2].replace(/[()]/g, ""))}`, code };
308
851
  }
309
852
  if (m = head.match(/^(?:using|lock|synchronized)\s*\((.+?)\)/)) return { kind: "set", says: `Uses ${clip(m[1], 50)}`, code };
310
853
  if (/^defer\b/.test(head)) return { kind: "call", says: `At the end, ${clip(head.replace(/^defer\s+/, ""), 60)}`, code };
311
854
  if (/^super\b/.test(head)) return { kind: "call", says: "Runs the parent version first", code };
312
855
  if (/^yield\b/.test(head)) return { kind: "call", says: "Hands control to the given block", code };
313
- if ((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) return { kind: "return", says: `Returns a new ${words(m[1])}`, code };
856
+ if ((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) return { kind: "return", says: `Returns a new ${words2(m[1])}`, code };
314
857
  if (m = head.match(/^(?:[A-Z]\w*::)+([A-Z]\w*)$/)) return { kind: "return", says: `Returns ${m[1]}`, code };
315
858
  if (/^vec!?\[/.test(head)) return { kind: "return", says: "Returns a list", code };
316
859
  if (/^(?:["'`].*["'`]|-?\d+(?:\.\d+)?|true|false|nil|null|None|self|[a-z_][\w.]*)$/.test(head) && !/^(?:else|end|break|next|redo|retry|pass)$/.test(head)) {
@@ -318,21 +861,21 @@ function classifyStatement(raw, { inner = 0 } = {}) {
318
861
  return { kind: "return", says: v ? `Returns ${v}` : "Returns a value", code };
319
862
  }
320
863
  if ((m = head.match(/^(?:\+\+|--)?([@A-Za-z_$#][\w$#.]*)(\+\+|--)?;?$/)) && (/^(\+\+|--)/.test(head) || m[2])) return { kind: "set", says: `${/\+\+/.test(head) ? "Adds one to" : "Subtracts one from"} ${targetWords(m[1].replace(/#/g, ""))}`, code };
321
- if (m = head.match(/^(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface|enum|record|object)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines ${words(m[1])}`, code };
322
- if (m = head.match(/^(?:async\s+)?(?:function|def|fn|fun|func)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines a helper, ${words(m[1])}`, code };
323
- if (m = head.match(/^(?:const|let|var|val)\s+([A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=>/)) return { kind: "set", says: `Defines a helper, ${words(m[1])}`, code };
864
+ if (m = head.match(/^(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface|enum|record|object)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines ${words2(m[1])}`, code };
865
+ if (m = head.match(/^(?:async\s+)?(?:function|def|fn|fun|func)\s+([A-Za-z_]\w*)/)) return { kind: "set", says: `Defines a helper, ${words2(m[1])}`, code };
866
+ if (m = head.match(/^(?:const|let|var|val)\s+([A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=>/)) return { kind: "set", says: `Defines a helper, ${words2(m[1])}`, code };
324
867
  if (m = head.match(/^(?:const|let|var|val)\s+([{[])\s*(.*?)\s*[}\]]\s*(?::\s*[^=]+)?=\s*(.+)$/)) {
325
- const names = m[2].split(",").map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, "")).filter(Boolean).map(words);
868
+ const names = m[2].split(",").map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, "")).filter(Boolean).map(words2);
326
869
  const value = stripTail(m[3]);
327
870
  const c2 = callee(value);
328
- const from = c2 ? lastWords(c2) : sayValue(value) || words(value.split(".").pop());
871
+ const from = c2 ? lastWords(c2) : sayValue(value) || words2(value.split(".").pop());
329
872
  return { kind: "set", says: `Takes ${names.slice(0, 4).join(", ")}${names.length > 4 ? ", \u2026" : ""} from ${from}`, code };
330
873
  }
331
874
  if (m = head.match(/^(?:var|const)\s*\($/)) return { kind: "set", says: "Declares some values", code };
332
- if (m = head.match(/^var\s+([\w, ]+?)\s+[\w.*\[\]]+$/)) return { kind: "set", says: `Declares ${m[1].split(/\s*,\s*/).map(words).join(", ")}`, code };
875
+ if (m = head.match(/^var\s+([\w, ]+?)\s+[\w.*\[\]]+$/)) return { kind: "set", says: `Declares ${m[1].split(/\s*,\s*/).map(words2).join(", ")}`, code };
333
876
  if (m = head.match(/^(?:final\s+|static\s+|readonly\s+)*([A-Z][\w.]*(?:<[^=]*>)?(?:\[\])?|int|long|double|float|boolean|bool|char|byte|short|string|decimal|var|auto)\s+([a-zA-Z_$][\w$]*)\s*=(?!=)\s*(.*)$/)) {
334
877
  const value = stripTail(m[3]);
335
- const target = words(m[2]);
878
+ const target = words2(m[2]);
336
879
  const c2 = value ? callee(value) : null;
337
880
  const everyday = value ? sayPython(value) || sayCommon(value) : null;
338
881
  if (everyday) return { kind: "set", says: `Sets ${target} to ${everyday}`, code };
@@ -348,14 +891,14 @@ function classifyStatement(raw, { inner = 0 } = {}) {
348
891
  if ((m = head.replace(/^(?:final\s+)?(?!return\b|throw\b|yield\b|await\b|new\b)[A-Z][\w.]*(?:<[^=;]*?>)?(?:\[\])*\??\s+(?=[a-z_]\w*\s*=[^=])/, "").match(/^(?:(?:const|let|var|val|final|auto|my|local)\s+)?(?:mut\s+)?([@A-Za-z_$#][\w$#.\[\]'"@]*?(?:\s*,\s*[@A-Za-z_$#][\w$#.@]*)*)(?:\s*:\s*[\w<>\[\]?, .|]+)?\s*(:=|\+=|-=|\*=|\/=|\|\|=|\?\?=|=)(?!=)\s*(.*)$/)) && !/^(?:if|for|while|return)\b/.test(head)) {
349
892
  const target = m[1].split(/\s*,\s*/).filter((t) => t !== "_").map(targetWords).join(", ") || targetWords(m[1]);
350
893
  const value = stripTail(m[3]);
351
- if (m[2] === "=" && !/[(?]/.test(value.replace(/^\(|\)$/g, "")) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(value.replace(/->|=>/g, ".")) && !/=>/.test(value)) return { kind: "set", says: `Works out ${target}: whether ${sayCodeCondition(value)}`, code };
352
- if (m[2] === "=" && /^[A-Za-z_]\w*$/.test(value) && m[1].split(".").pop() === value && /^(self|this)\./.test(m[1])) return { kind: "set", says: `Keeps the ${words(value)} it is given`, code };
894
+ if (m[2] === "=" && !/^(?:if|unless|match|when|case)\b/.test(value) && !/[(?]/.test(value.replace(/^\(|\)$/g, "")) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(value.replace(/->|=>/g, ".")) && !/=>/.test(value)) return { kind: "set", says: `Works out ${target}: whether ${sayCodeCondition(value)}`, code };
895
+ if (m[2] === "=" && /^[A-Za-z_]\w*$/.test(value) && m[1].split(".").pop() === value && /^(self|this)\./.test(m[1])) return { kind: "set", says: `Keeps the ${words2(value)} it is given`, code };
353
896
  const chain = value ? sayPython(value) || sayChain(value) : null;
354
897
  if (chain) return { kind: "set", says: `Works out ${target}: ${chain}`, code };
355
898
  const common = value ? sayCommon(m[3].trim().replace(/;$/, "")) || sayCommon(value) : null;
356
899
  if (common) return { kind: "set", says: `Sets ${target} to ${common}`, code };
357
900
  const keyed = m[2] === "=" && m[1].match(/^([\w$.]+)\[\s*([^\]]+?)\s*\]$/);
358
- if (keyed) return { kind: "set", says: `Records ${words(keyed[2].replace(/["'`]/g, ""))} in ${targetWords(keyed[1])}`, code };
901
+ if (keyed) return { kind: "set", says: `Records ${words2(keyed[2].replace(/["'`]/g, ""))} in ${targetWords(keyed[1])}`, code };
359
902
  const c2 = callee(value);
360
903
  if (c2) {
361
904
  const known = sayCall(c2, firstArgs(value));
@@ -365,7 +908,7 @@ function classifyStatement(raw, { inner = 0 } = {}) {
365
908
  }
366
909
  if (!value) return { kind: "set", says: `Works out ${target}`, code };
367
910
  if (m[2] === "+=" || m[2] === "-=") {
368
- const what = /^[\w.]+$/.test(value) ? `${value.split(".").filter((p) => !/^(self|this)$/.test(p)).slice(-2).map(words).join(" ")} ` : /^-?\d+(\.\d+)?$/.test(value) ? `${value} ` : "";
911
+ const what = /^[\w.]+$/.test(value) ? `${value.split(".").filter((p) => !/^(self|this)$/.test(p)).slice(-2).map(words2).join(" ")} ` : /^-?\d+(\.\d+)?$/.test(value) ? `${value} ` : "";
369
912
  return { kind: "set", says: what ? `${m[2] === "+=" ? "Adds" : "Subtracts"} ${what}${m[2] === "+=" ? "to" : "from"} ${target}` : `${m[2] === "+=" ? "Adds to" : "Subtracts from"} ${target}`, code };
370
913
  }
371
914
  const v = sayValue(value);
@@ -374,14 +917,14 @@ function classifyStatement(raw, { inner = 0 } = {}) {
374
917
  if (m = head.match(/^([\w$.]+)\.(?:set|Set|put|setdefault|Add)\(\s*["'`]([\w.\-: ]{1,40})["'`]\s*,/)) return { kind: "call", says: `Sets "${m[2]}" on ${lastSeg(m[1])}`, code, callee: `${m[1]}.set` };
375
918
  if ((m = head.match(/^([\w$.]+)\.(?:remove|Remove|discard|delete|pop)\(\s*([\w$]+)\s*\)/)) && !/^(?:db|session|repo|conn|cursor)\b/.test(m[1])) {
376
919
  const owner = m[1].split(".").filter((p) => !/^(self|this)$/.test(p));
377
- const where = owner.length > 1 ? `${words(owner[owner.length - 2])}'s ${words(owner[owner.length - 1])}` : words(owner[0] || m[1]);
378
- return { kind: "call", says: `Removes ${words(m[2])} from ${where}`, code, callee: m[1] };
920
+ const where = owner.length > 1 ? `${words2(owner[owner.length - 2])}'s ${words2(owner[owner.length - 1])}` : words2(owner[0] || m[1]);
921
+ return { kind: "call", says: `Removes ${words2(m[2])} from ${where}`, code, callee: m[1] };
379
922
  }
380
923
  if ((m = head.match(/^([\w$.]+)\.(?:append|push|add|Add|insert|appendleft|extend)\(\s*([\w$.]*)\s*\)?/)) && !/^(?:db|session|repo|conn|cursor)\b/.test(m[1])) {
381
924
  const owner = m[1].split(".").filter((p) => !/^(self|this)$/.test(p));
382
- const where = owner.length > 1 ? `${words(owner[owner.length - 2])}'s ${words(owner[owner.length - 1])}` : words(owner[0] || m[1]);
925
+ const where = owner.length > 1 ? `${words2(owner[owner.length - 2])}'s ${words2(owner[owner.length - 1])}` : words2(owner[0] || m[1]);
383
926
  const added = /^new\s+([A-Z]\w*)/.exec(head.slice(head.indexOf("(") + 1))?.[1];
384
- return { kind: "call", says: added ? `Adds a new ${words(added)} to ${where}` : m[2] && /^[A-Za-z_][\w$]*$/.test(m[2]) && m[2] !== "new" ? `Adds ${words(m[2])} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
927
+ return { kind: "call", says: added ? `Adds a new ${words2(added)} to ${where}` : m[2] && /^[A-Za-z_][\w$]*$/.test(m[2]) && m[2] !== "new" ? `Adds ${words2(m[2])} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
385
928
  }
386
929
  const c = callee(head);
387
930
  if (c) {
@@ -392,12 +935,20 @@ function classifyStatement(raw, { inner = 0 } = {}) {
392
935
  if (/^assert/.test(m[1])) return { kind: "check", says: `Checks: ${clip(head, 60)}`, code };
393
936
  const known = sayCall(m[1], m[2]);
394
937
  const named = /^[:'"]([\w ]+)['"]?/.exec(m[2].trim())?.[1];
395
- return { kind: "call", says: known || (named ? `Calls ${lastWords(m[1])}: ${words(named)}` : `Calls ${lastWords(m[1])}`), code, callee: m[1] };
938
+ return { kind: "call", says: known || (named ? `Calls ${lastWords(m[1])}: ${words2(named)}` : `Calls ${lastWords(m[1])}`), code, callee: m[1] };
396
939
  }
397
940
  return { kind: "other", says: clip(head, 70), code };
398
941
  }
399
942
  var spanOf = (s) => ({ startLine: s.line, endLine: s.endLine ?? s.line, ...s.start != null && s.end != null ? { start: s.start, end: s.end } : {} });
400
943
  var BARE_CALL = /^[a-z_][\w.]*[?!]?$/;
944
+ var bracketsClosed = (x) => {
945
+ let d = 0;
946
+ for (const ch of x) {
947
+ if ("([{".includes(ch)) d++;
948
+ else if (")]}".includes(ch)) d--;
949
+ }
950
+ return d === 0;
951
+ };
401
952
  var balanced = (x) => {
402
953
  let d = 0;
403
954
  for (const ch of x) {
@@ -434,12 +985,195 @@ function attachClause(step, clause) {
434
985
  step.always = { line: clause.line, steps: kids2 };
435
986
  }
436
987
  }
988
+ function orList(names) {
989
+ const n = [...new Set(names)];
990
+ if (n.length <= 3) return n.length > 1 ? `${n.slice(0, -1).join(", ")} or ${n[n.length - 1]}` : n[0] || "";
991
+ return `${n.slice(0, 3).join(", ")} or ${n.length - 3} other value${n.length - 3 === 1 ? "" : "s"}`;
992
+ }
993
+ function depsOf(after) {
994
+ const a = String(after || "");
995
+ if (/^\s*\)/.test(a)) return null;
996
+ const m = a.match(/^\s*,\s*\[([^\]]*)\]/);
997
+ if (!m) return "unknown";
998
+ return m[1].split(",").map((x) => x.trim().replace(/\?\./g, ".").replace(/\(\)$/, "")).filter(Boolean).map((x) => words2(x.split(".").pop()));
999
+ }
1000
+ var changesWords = (deps) => `${orList(deps)} ${deps.length > 3 ? "change" : "changes"}`;
1001
+ function effectSays(deps) {
1002
+ if (deps === null) return "Every time this is drawn on screen";
1003
+ if (deps === "unknown") return "When this first shows on screen, and whenever what it watches changes";
1004
+ if (!deps.length) return "When this first shows on screen";
1005
+ return `When this first shows on screen, and whenever ${changesWords(deps)}`;
1006
+ }
1007
+ var HOOK = /^(?:(?:const|let|var)\s+([\w$]+)(?:\s*:[^=]+?)?\s*=\s*)?(?:React\.)?(use[A-Z]\w*)\s*(?:<[^(]*?>)?\(/;
1008
+ var TRAILING_LAMBDA = /^(?:(?:val|var)\s+[\w$]+(?:\s*:[^=]+)?\s*=\s*)?([a-z_$][\w$]*(?:\??\.[\w$]+)*)\s*(\([^{}]*\))?\s*\{\s*(?:\(?[\w$, ]+\)?\s*->)?\s*$/;
1009
+ var RUBY_DO = /^(?:[@$]?[\w]+\s*=\s*)?([a-z_][\w.?!]*)(?:\(.*\)|\s+[^|]*?)?\s+do\s*(?:\|[^|]*\|)?\s*$/;
1010
+ var NOT_A_CALL = /^(?:if|else|for|while|when|return|object|init|companion|class|interface|fun|try|catch|finally|do|loop|unsafe|match|switch|select|synchronized|lock|using|get|set)$/;
1011
+ function thenSays(text) {
1012
+ const m = String(text).match(/^(?:await\s+)?([^{};\n]*?)\.(then|catch)\(\s*(?:async\s+)?(?:function\b|\(|[\w$]+\s*=>)/);
1013
+ if (!m) return null;
1014
+ const recvText = m[1].trim().replace(/^\(\s*([\w$.]+)\s+as\s+[^()]*\)$/, "$1");
1015
+ const recv = recvText.match(/^([\w$.]+)\(.*\)$/s) || recvText.match(/^([\w$.]+)$/);
1016
+ const what = recv ? lastWords(recv[1]) : "that";
1017
+ return m[2] === "then" ? `When ${what} is done` : `If ${what} goes wrong`;
1018
+ }
1019
+ function nestedStep(s, base) {
1020
+ const text = String(s.text || "").trim();
1021
+ const head = text.split("\n")[0].trim();
1022
+ const kids2 = () => stepsFrom(s.children || []).steps;
1023
+ const own = (step, children) => children.length ? { ...step, children, nested: true } : step;
1024
+ let m;
1025
+ if (s.fn && s.fn.depth === 1 && (m = text.match(HOOK))) {
1026
+ const [, name, hook] = m;
1027
+ const deps = depsOf(s.fn.after);
1028
+ if (/^use\w*Effect$/.test(hook)) {
1029
+ for (const c of s.children || []) if (c.fn && /^return\b/.test(c.text.trim())) c.cleanup = deps && deps !== "unknown" && !deps.length ? "When this is taken off the screen, cleans up" : "Cleans up before it runs again, and when this is taken off the screen";
1030
+ return own({ kind: "call", says: effectSays(deps), code: base.code, callee: hook }, kids2());
1031
+ }
1032
+ if (hook === "useMemo" && name) {
1033
+ let children = kids2();
1034
+ if (s.fn.expr && children.length === 1) {
1035
+ const v = classifyStatement(`return ${s.children[0].text}`);
1036
+ children = [{ ...children[0], kind: v.kind, says: v.says }];
1037
+ }
1038
+ const says = deps === null ? `Works out ${words2(name)}` : Array.isArray(deps) && !deps.length ? `Works out ${words2(name)} once and remembers it` : Array.isArray(deps) ? `Works out ${words2(name)} and remembers it until ${changesWords(deps)}` : `Works out ${words2(name)} and remembers it until what it watches changes`;
1039
+ return own({ kind: "set", says, code: base.code, callee: hook }, children);
1040
+ }
1041
+ if (/^use\w*Callback$/.test(hook) && name) return own({ kind: "set", says: `Defines how ${words2(name)} works`, code: base.code, callee: hook }, kids2());
1042
+ }
1043
+ if (s.cleanup) return own({ kind: "call", says: s.cleanup, code: base.code }, kids2());
1044
+ if (s.fn && !s.fn.expr) {
1045
+ if (s.fn.depth === 0 && /^go\s+func\b/.test(head)) return own({ kind: "call", says: "Starts these steps running alongside, without waiting for them", code: base.code }, kids2());
1046
+ if (s.fn.depth === 0 && /^defer\s+func\b/.test(head)) return own({ kind: "call", says: "At the end, runs these steps", code: base.code }, kids2());
1047
+ if (/^return\b/.test(head) || base.kind === "return" || base.kind === "other" || base.kind === "branch" || base.kind === "fail") return null;
1048
+ if (base.kind === "loop") return null;
1049
+ let said = base.says;
1050
+ if (base.kind !== "call") {
1051
+ } else if (m = text.match(/^(?:window\.|globalThis\.)?(setTimeout|setInterval)\(/)) {
1052
+ const ms = (s.fn.after.match(/^\s*,\s*(\d+)\s*\)/) || [])[1];
1053
+ said = m[1] === "setTimeout" ? ms ? `After ${ms} milliseconds` : "After a wait" : ms ? `Every ${ms} milliseconds` : "Again and again, with a wait in between";
1054
+ } else if (m = text.match(/\.(addEventListener|on|once)\(\s*['"`]([\w:.-]+)['"`]\s*,/)) {
1055
+ said = m[1] === "once" ? `The first time "${m[2]}" happens` : `Whenever "${m[2]}" happens`;
1056
+ } else if (thenSays(text)) {
1057
+ said = thenSays(text);
1058
+ } else if (/^Calls [\w ]+$/.test(said)) said = `${said} with these steps`;
1059
+ return own({ ...base, kind: base.kind === "set" ? "set" : "call", says: said }, kids2());
1060
+ }
1061
+ if (!s.children?.length) return null;
1062
+ const raw = String(s.text || "").split("\n")[0].trim();
1063
+ if (!s.fn && !BLOCK_HEAD.test(raw) && (m = raw.match(TRAILING_LAMBDA)) && !NOT_A_CALL.test(m[1])) {
1064
+ const safe = m[1].match(/^(.+?)\?\.(?:let|also|run|apply)$/);
1065
+ if (safe) return own({ kind: "branch", says: `If ${words2(safe[1].split(/\??\./).pop())} is set`, code: clip(raw, 90) }, kids2());
1066
+ if (m = raw.match(/^repeat\s*\(\s*(.+?)\s*\)\s*\{/)) return own({ kind: "loop", says: `Repeats ${/^\d+$/.test(m[1]) ? m[1] : words2(m[1])} times`, code: base.code }, kids2());
1067
+ if (base.kind === "loop") return null;
1068
+ if (base.kind === "call" && /^Calls [\w ]+$/.test(base.says)) return own({ ...base, says: `${base.says} with these steps` }, kids2());
1069
+ if (base.kind === "set" || base.kind === "call") return own(base, kids2());
1070
+ return null;
1071
+ }
1072
+ if ((m = raw.match(RUBY_DO)) && base.kind !== "loop" && !/^(?:if|unless|while|until|for|case|begin)\b/.test(raw)) {
1073
+ if (base.kind === "call" && /^Calls [\w ]+$/.test(base.says)) return own({ ...base, says: `${base.says.replace(/: .*$/, "")} with these steps` }, kids2());
1074
+ if (base.kind === "call" || base.kind === "set") return own(base, kids2());
1075
+ }
1076
+ return null;
1077
+ }
1078
+ function valueChoice(s) {
1079
+ const head = headLine(s.text || "");
1080
+ let m = head.match(/^(?:(?:const|let|var|val|my)\s+(?:mut\s+)?)?([@$]?[\w$.]+)(?:\s*:\s*[^=]+?)?\s*=\s*((?:if|unless|match|when|case)\b.*|[\w.]+\s+switch\s*\{\s*)$/);
1081
+ if (m && !/^(?:if|for|while|return)$/.test(m[1])) return { target: targetWords(m[1]), rest: m[2] };
1082
+ if (m = head.match(/^return\s+((?:if|match|when)\b.*|[\w.]+\s+switch\s*\{\s*)$/)) return { target: null, rest: m[1] };
1083
+ return null;
1084
+ }
1085
+ function armsSubject(rest2) {
1086
+ const r = rest2.replace(/\{\s*$/, "").trim();
1087
+ const m = r.match(/^match\s*\((.+)\)$/) || r.match(/^match\s+(.+)$/) || r.match(/^when\s*\((.+)\)$/) || r.match(/^([\w.]+)\s+switch$/);
1088
+ return m ? m[1].trim() : null;
1089
+ }
1090
+ function armSays(pattern) {
1091
+ let p = String(pattern).trim();
1092
+ if (/^(?:_|else|default)$/.test(p)) return "Otherwise";
1093
+ let guard = null;
1094
+ const g = p.match(/^(.+?)\s+(?:if|when)\s+(.+)$/);
1095
+ if (g) {
1096
+ p = g[1];
1097
+ guard = g[2];
1098
+ }
1099
+ if (LOGIC.test(p) && !/^(?:!?in|!?is)\s/.test(p) && !/\.\./.test(p) && !/\|/.test(p.replace(/\|\|/g, ""))) return `When ${sayCodeCondition(p)}`;
1100
+ const parts = [];
1101
+ let depth = 0, from = 0;
1102
+ for (let i = 0; i <= p.length; i++) {
1103
+ const c = p[i];
1104
+ if (c === "(" || c === "[" || c === "{") depth++;
1105
+ else if (c === ")" || c === "]" || c === "}") depth--;
1106
+ if (i === p.length || depth === 0 && (c === "|" && p[i + 1] !== "|" && p[i - 1] !== "|" || c === ",")) {
1107
+ parts.push(p.slice(from, i).trim());
1108
+ from = i + 1;
1109
+ }
1110
+ }
1111
+ const one = (x) => {
1112
+ let m;
1113
+ if ((m = x.match(/^(!?)in\s+(.+?)\.\.(=?)(.+)$/)) || (m = x.match(/^()(-?[\w.]+)\.\.(=)(-?[\w.]+)$/))) return `${m[1] ? "not " : ""}from ${m[2].trim()} to ${m[4].trim()}`;
1114
+ if (m = x.match(/^(!?)is\s+([\w.<>?]+)$/)) return `${m[1] ? "not " : ""}a ${m[2].split(".").pop()}`;
1115
+ if (m = x.match(/^(?:[A-Z]\w*(?:::|\.))+([A-Z]\w*)$/)) return words2(m[1]);
1116
+ if (/^[A-Z][A-Z0-9_]+$/.test(x)) return words2(x);
1117
+ return x;
1118
+ };
1119
+ return `When it is ${orList(parts.filter(Boolean).map(one))}${guard ? `, and ${sayCodeCondition(guard)}` : ""}`;
1120
+ }
1121
+ function giveValue(list, target) {
1122
+ if (!list?.length) return;
1123
+ if (list.some((x) => x.caseLabel)) {
1124
+ for (const x of list) if (x.caseLabel) giveValue(x.children, target);
1125
+ return;
1126
+ }
1127
+ const i = list.length - 1;
1128
+ const last = list[i];
1129
+ if (last.kind === "branch" && !Object.hasOwn(last, "valueOf")) {
1130
+ giveValue(last.children, target);
1131
+ giveValue(last.otherwise, target);
1132
+ return;
1133
+ }
1134
+ if (last.kind === "fail" || /^(?:return|break|continue|throw|raise)\b/.test(last.code || "")) return;
1135
+ const v = classifyStatement(`return ${String(last.code || "").replace(/,$/, "")}`);
1136
+ if (v.kind !== "return") return;
1137
+ const said = v.says.replace(/^Returns /, "");
1138
+ list[i] = target ? { ...last, kind: "set", says: v.value ? `Sets ${target} to a computed value` : `Sets ${target} to ${said}` } : { ...last, kind: "return", says: v.says };
1139
+ delete list[i].callee;
1140
+ if (list[i].says && restates(list[i])) list[i].restates = true;
1141
+ else delete list[i].restates;
1142
+ }
1143
+ function selectCaseSays(code) {
1144
+ const c = String(code).trim();
1145
+ if (/^default\s*:/.test(c)) return "If none is ready yet";
1146
+ let m = c.match(/^case\s+(?:([\w$]+)(?:\s*,\s*([\w$]+))?\s*:?=\s*)?<-\s*(.+?)\s*:\s*$/);
1147
+ if (m) {
1148
+ const [, name, ok, ch] = m;
1149
+ let d;
1150
+ if (/\.Done\(\)$/.test(ch)) return `When ${lastWords(ch.replace(/\.Done\(\)$/, ""))} is cancelled or times out`;
1151
+ if (d = ch.match(/^time\.After\((.+)\)$/)) {
1152
+ const t = d[1].trim();
1153
+ const u = t.match(/^(\d+)\s*\*\s*time\.(Millisecond|Second|Minute|Hour)$/) || t.match(/^time\.(Millisecond|Second|Minute|Hour)$/);
1154
+ const dur = u ? u.length === 3 ? `${u[1]} ${u[2].toLowerCase()}${u[1] === "1" ? "" : "s"}` : `1 ${u[1].toLowerCase()}` : words2(t.split(".").pop());
1155
+ return `When ${dur} ${/s$/.test(dur) && !/^1 /.test(dur) ? "have" : "has"} passed`;
1156
+ }
1157
+ if (/\.C$/.test(ch)) return `When ${lastWords(ch.replace(/\.C$/, ""))} ticks`;
1158
+ const from = lastWords(ch.replace(/\(\)$/, ""));
1159
+ return name && name !== "_" ? `When ${words2(name)} arrives from ${from}${ok ? ` (or ${from} is closed)` : ""}` : `When something arrives from ${from}`;
1160
+ }
1161
+ if (m = c.match(/^case\s+(.+?)\s*<-\s*(.+?)\s*:\s*$/)) return `When ${words2(m[2].split(".").pop())} can be sent to ${lastWords(m[1])}`;
1162
+ return null;
1163
+ }
437
1164
  function stepsFrom(statements) {
438
1165
  const steps = [];
439
1166
  const skipped = [];
440
1167
  let into = null, intoAlways = false;
441
1168
  for (const s of statements) {
442
1169
  const t0 = (s.text || "").trim();
1170
+ if (s.arm != null) {
1171
+ const arm = { kind: "check", says: armSays(s.arm), code: clip(t0.split("\n")[0].trim(), 90), caseLabel: true, line: s.line, span: spanOf(s) };
1172
+ const kids2 = stepsFrom(s.children || []).steps;
1173
+ if (kids2.length) arm.children = kids2;
1174
+ steps.push(arm);
1175
+ continue;
1176
+ }
443
1177
  if (into && !CLAUSE.test(t0) && t0 && !/^(?:end\b|#)/.test(t0)) {
444
1178
  const st = stepsFrom([s]).steps;
445
1179
  into.push(...st);
@@ -457,7 +1191,9 @@ function stepsFrom(statements) {
457
1191
  if (prev2 && (prev2.kind === "branch" || prev2.kind === "try")) {
458
1192
  const prev3 = prev2;
459
1193
  const kw = /^(?:elif|elsif|else\s+if)\b/.test(t0) ? "elif" : /^else\b/.test(t0) ? "else" : /^(?:finally|ensure)\b/.test(t0) ? "finally" : "catch";
460
- attachClause(prev3, { kind: kw, head: t0.replace(/:\s*$/, ""), line: s.line, endLine: s.endLine, children: s.children || [] });
1194
+ const inlineElse = kw === "else" && t0.match(/^else\s+(?!if\b)([^{:\s].*)$/);
1195
+ const clauseKids = inlineElse ? [{ text: inlineElse[1], line: s.line, endLine: s.line }, ...s.children || []] : s.children || [];
1196
+ attachClause(prev3, { kind: kw, head: t0.replace(/:\s*$/, ""), line: s.line, endLine: s.endLine, children: clauseKids });
461
1197
  intoAlways = kw === "finally";
462
1198
  into = s.children?.length ? null : kw === "catch" ? prev3.handlers?.[prev3.handlers.length - 1]?.steps ?? null : kw === "finally" ? prev3.always?.steps ?? null : null;
463
1199
  prev3.span = { ...prev3.span, endLine: Math.max(prev3.span.endLine, s.endLine ?? s.line) };
@@ -466,7 +1202,7 @@ function stepsFrom(statements) {
466
1202
  skipped.push(spanOf(s));
467
1203
  continue;
468
1204
  }
469
- if (!t0 || /^(?:end\b|\}|pass$|break$|continue$|#)/.test(t0)) {
1205
+ if (!t0 || /^(?:end\b|\}|pass$|break;?$|continue;?$|#)/.test(t0)) {
470
1206
  if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s));
471
1207
  continue;
472
1208
  }
@@ -478,16 +1214,54 @@ function stepsFrom(statements) {
478
1214
  skipped.push(spanOf(s));
479
1215
  continue;
480
1216
  }
481
- const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
1217
+ const head0 = headLine(s.text);
1218
+ if (/^\{/.test(t0) && s.children?.length) {
1219
+ steps.push(...stepsFrom(s.children).steps);
1220
+ continue;
1221
+ }
1222
+ const choice = s.children?.length || s.clauses || s.arms ? valueChoice(s) : null;
1223
+ if (s.arms) {
1224
+ const subject = armsSubject(choice ? choice.rest : head0);
1225
+ const kids2 = stepsFrom(s.children || []).steps;
1226
+ const chooser = { kind: "branch", says: subject ? `Chooses by ${words2(clip(subject, 40))}` : "Checks these cases in order", code: clip(head0, 90), line: s.line, span: spanOf(s), ...kids2.length ? { children: kids2 } : {}, ...choice ? { valueOf: choice.target } : {} };
1227
+ steps.push(chooser);
1228
+ continue;
1229
+ }
1230
+ let step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
1231
+ if (choice && /^(?:if|unless|case)\b/.test(choice.rest) && (s.endLine ?? s.line) > s.line) {
1232
+ step = { ...classifyStatement(choice.rest, { inner: s.inner || 0 }), code: step.code, line: s.line, span: spanOf(s), valueOf: choice.target };
1233
+ } else {
1234
+ const nest = nestedStep(s, step);
1235
+ if (!nest && step.kind === "return" && s.fn && !s.fn.expr && s.fn.depth >= 1 && s.children?.length) {
1236
+ const kids2 = stepsFrom(s.children).steps;
1237
+ if (kids2.length) {
1238
+ let m;
1239
+ const body = s.text.trim().replace(/^return\s+/, "");
1240
+ const said = (m = body.match(/^new\s+([A-Z]\w*)/)) ? `Makes a new ${m[1]} with these steps` : thenSays(body) ? thenSays(body) : callee(body) ? `Calls ${lastWords(callee(body))} with these steps` : null;
1241
+ if (said) steps.push({ kind: "call", says: said, code: step.code, line: s.line, span: spanOf(s), children: kids2, nested: true });
1242
+ }
1243
+ }
1244
+ if (nest) {
1245
+ step = { ...nest, line: s.line, span: spanOf(s) };
1246
+ for (const c of s.clauses || []) attachClause(step, c);
1247
+ steps.push(step);
1248
+ continue;
1249
+ }
1250
+ }
482
1251
  if (step.inline && !/^\{/.test(step.inline.trim())) {
483
1252
  const kid = classifyStatement(step.inline);
484
1253
  step.children = [{ ...kid, line: s.line, span: spanOf(s) }];
485
1254
  delete step.inline;
486
- } else if (s.children?.length && ["branch", "loop", "try"].includes(step.kind)) {
1255
+ } else if (s.children?.length && (["branch", "loop", "try"].includes(step.kind) || step.kind === "check" && step.caseLabel || /^(?:Defines a helper|Defines how|Opens |Uses )/.test(step.says))) {
487
1256
  const kids2 = stepsFrom(s.children).steps;
488
1257
  if (kids2.length) {
489
1258
  step.children = kids2;
490
1259
  step.says = step.says.replace(/ \(\d+ steps? inside\)$/, "");
1260
+ if (/^Defines/.test(step.says)) step.nested = true;
1261
+ }
1262
+ if (/^select\s*\{/.test(head0) && step.children) {
1263
+ for (const k of step.children) if (k.caseLabel) k.says = selectCaseSays(k.code) ?? k.says;
1264
+ step.says = step.children.some((k) => /^default\b/.test(k.code || "")) ? "Checks which of these is ready, without waiting" : "Waits for whichever of these is ready first";
491
1265
  }
492
1266
  }
493
1267
  if (step.inline && !step.children) {
@@ -495,10 +1269,16 @@ function stepsFrom(statements) {
495
1269
  step.children = [{ ...kid, line: s.line, span: spanOf(s) }];
496
1270
  delete step.inline;
497
1271
  } else delete step.inline;
498
- for (const c of s.clauses || []) attachClause(step, c);
1272
+ if (step.kind === "branch" || step.kind === "try") for (const c of s.clauses || []) attachClause(step, c);
499
1273
  steps.push(step);
500
1274
  }
501
1275
  for (let i = 0; i < steps.length - 1; i++) asCall(steps, i);
1276
+ for (const st of steps) if (Object.hasOwn(st, "valueOf")) {
1277
+ const t = st.valueOf;
1278
+ delete st.valueOf;
1279
+ giveValue(st.children, t);
1280
+ giveValue(st.otherwise, t);
1281
+ }
502
1282
  const more = Math.max(0, steps.length - MAX_STEPS);
503
1283
  for (const st of steps) if (restates(st)) st.restates = true;
504
1284
  return { steps, more, skipped, readable: readableShare(steps) };
@@ -507,7 +1287,7 @@ var GENERIC_CALLS = /^(?:get|set|run|do|call|apply|handle|process|execute|exec|m
507
1287
  function restates(st) {
508
1288
  const s = st.says || "";
509
1289
  if (st.kind === "other") return false;
510
- if (/^Works out [^:]+$/.test(s) && !/ from /.test(s)) return true;
1290
+ if (/^Works out [^:]+$/.test(s) && !/ from | remembers it/.test(s)) return true;
511
1291
  const same = s.match(/^Works out (.+) from (.+)$/);
512
1292
  if (same && same[1].trim() === same[2].trim()) return true;
513
1293
  if (/^(Returns a computed value|Returns a value|Sets .+ to a computed value)$/.test(s)) return true;
@@ -529,22 +1309,225 @@ var blockEnd = (text, open) => {
529
1309
  }
530
1310
  return -1;
531
1311
  };
1312
+ var headLine = (text) => String(text).trim().replace(/^([^\n]*?=)[ \t]*\r?\n\s*/, "$1 ").split("\n")[0].trim();
1313
+ var skipQuoted = (text, i) => {
1314
+ const q = text[i];
1315
+ for (i++; i < text.length && text[i] !== q; i++) if (text[i] === "\\") i++;
1316
+ return i;
1317
+ };
1318
+ var BLOCK_HEAD = /^(?:if|else|for|foreach|while|until|switch|try|catch|finally|do|match|loop|unsafe|select|using|lock|synchronized|when|case|default|elif|with|class|struct|interface|enum|impl|fn|fun|func|def)\b/;
1319
+ function fnLiteral(text) {
1320
+ let depth = 0;
1321
+ const bodyAt = (j, d) => {
1322
+ while (j < text.length && /\s/.test(text[j])) j++;
1323
+ if (text[j] !== "{") return null;
1324
+ const close = blockEnd(text, j);
1325
+ return close < 0 ? null : { open: j, close, depth: d };
1326
+ };
1327
+ for (let i = 0; i < text.length; i++) {
1328
+ const c = text[i];
1329
+ if (c === '"' || c === "'" || c === "`") {
1330
+ i = skipQuoted(text, i);
1331
+ continue;
1332
+ }
1333
+ if (c === "(" || c === "[") {
1334
+ depth++;
1335
+ continue;
1336
+ }
1337
+ if (c === ")" || c === "]") {
1338
+ depth--;
1339
+ continue;
1340
+ }
1341
+ if (c === "{") {
1342
+ const e = blockEnd(text, i);
1343
+ if (e < 0) return null;
1344
+ i = e;
1345
+ continue;
1346
+ }
1347
+ if (c === "=" && text[i + 1] === ">") {
1348
+ const before = text.slice(Math.max(0, i - 80), i).trimEnd();
1349
+ if (!/(?:\)|[A-Za-z_$][\w$]*)(?:\s*:\s*[^=()]+)?$/.test(before) || /["']$/.test(before)) {
1350
+ i++;
1351
+ continue;
1352
+ }
1353
+ const body = bodyAt(i + 2, depth);
1354
+ if (body) return body;
1355
+ if (depth < 1) {
1356
+ i++;
1357
+ continue;
1358
+ }
1359
+ let j = i + 2, d = 0;
1360
+ for (; j < text.length; j++) {
1361
+ const ch = text[j];
1362
+ if (ch === '"' || ch === "'" || ch === "`") {
1363
+ j = skipQuoted(text, j);
1364
+ continue;
1365
+ }
1366
+ if (ch === "(" || ch === "[" || ch === "{") d++;
1367
+ else if (ch === ")" || ch === "]" || ch === "}") {
1368
+ if (--d < 0) break;
1369
+ } else if (ch === "," && d === 0) break;
1370
+ }
1371
+ return { expr: [i + 2, j], depth };
1372
+ }
1373
+ if (c === "-" && text[i + 1] === ">" && depth >= 1) {
1374
+ const body = bodyAt(i + 2, depth);
1375
+ if (body) return body;
1376
+ i++;
1377
+ continue;
1378
+ }
1379
+ if (c === "f" && /\b(?:function|func)\b/y.test(text.slice(i, i + 9)) && !/[\w$.]/.test(text[i - 1] || "")) {
1380
+ const m = text.slice(i, i + 120).match(/^(?:function\s*\*?\s*[\w$]*|func)\s*\(/);
1381
+ if (!m) continue;
1382
+ let p = i + m[0].length - 1, pd = 0;
1383
+ for (; p < text.length; p++) {
1384
+ if (text[p] === "(") pd++;
1385
+ else if (text[p] === ")" && --pd === 0) break;
1386
+ }
1387
+ let j = p + 1;
1388
+ const use = text.slice(j, j + 24).match(/^\s*use\s*\(/);
1389
+ if (use) {
1390
+ j += use[0].length - 1;
1391
+ for (let ud = 0; j < text.length; j++) {
1392
+ if (text[j] === "(") ud++;
1393
+ else if (text[j] === ")" && --ud === 0) {
1394
+ j++;
1395
+ break;
1396
+ }
1397
+ }
1398
+ }
1399
+ for (; j < text.length && j < p + 200; j++) {
1400
+ if (text[j] === "{") {
1401
+ if (/(?:interface|struct)\s*$/.test(text.slice(Math.max(0, j - 12), j))) {
1402
+ j = blockEnd(text, j);
1403
+ continue;
1404
+ }
1405
+ break;
1406
+ }
1407
+ if (text[j] === "\n" && /^\s*$/.test(text.slice(p + 1, j))) break;
1408
+ }
1409
+ const body = text[j] === "{" ? bodyAt(j, depth) : null;
1410
+ if (body) return body;
1411
+ continue;
1412
+ }
1413
+ if (c === "|" && depth >= 1 && /[(,]\s*(?:move\s+)?$/.test(text.slice(Math.max(0, i - 8), i))) {
1414
+ const m = text.slice(i, i + 200).match(/^\|[^|]*\|\s*(?:->\s*[\w<>&' ]+?\s*)?(?=\{)/);
1415
+ if (m) {
1416
+ const body = bodyAt(i + m[0].length, depth);
1417
+ if (body) return body;
1418
+ }
1419
+ }
1420
+ }
1421
+ return null;
1422
+ }
1423
+ var LAMBDA_PARAMS = /^\s*(?:\(?[\w$]+(?:\s*:\s*[\w<>?.]+)?(?:\s*,\s*[\w$]+(?:\s*:\s*[\w<>?.]+)?)*\)?|_)\s*->(?![^\n]*->)/;
1424
+ function armsOf(body) {
1425
+ const arms = [];
1426
+ let i = 0;
1427
+ while (i < body.length) {
1428
+ while (i < body.length && /[\s,;]/.test(body[i])) i++;
1429
+ if (i >= body.length) break;
1430
+ const at = i;
1431
+ let depth = 0, arrow = -1, end = -1;
1432
+ for (; i < body.length; i++) {
1433
+ const c = body[i];
1434
+ if (c === '"' || c === "'" || c === "`") {
1435
+ i = skipQuoted(body, i);
1436
+ continue;
1437
+ }
1438
+ if (c === "(" || c === "[" || c === "{") {
1439
+ depth++;
1440
+ continue;
1441
+ }
1442
+ if (c === ")" || c === "]" || c === "}") {
1443
+ depth--;
1444
+ if (depth === 0 && c === "}" && arrow >= 0 && /^\{/.test(body.slice(arrow + 2).trimStart())) {
1445
+ i++;
1446
+ end = i;
1447
+ break;
1448
+ }
1449
+ continue;
1450
+ }
1451
+ if (depth !== 0) continue;
1452
+ if (arrow < 0 && (c === "=" || c === "-") && body[i + 1] === ">") {
1453
+ arrow = i;
1454
+ i++;
1455
+ continue;
1456
+ }
1457
+ if (arrow >= 0 && (c === "," || c === ";")) {
1458
+ end = i;
1459
+ break;
1460
+ }
1461
+ if (arrow >= 0 && c === "\n") {
1462
+ const before = body.slice(arrow + 2, i).trim();
1463
+ let j = i + 1;
1464
+ while (j < body.length && /\s/.test(body[j])) j++;
1465
+ const after = body.slice(j, j + 12);
1466
+ if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) && !/^[.)\]}+\-*/%&|^=<>?:,]/.test(after) && !/^else\b(?!\s*->)/.test(after)) {
1467
+ end = i;
1468
+ break;
1469
+ }
1470
+ }
1471
+ }
1472
+ if (end < 0) end = i;
1473
+ if (arrow < 0) return null;
1474
+ const pattern = body.slice(at, arrow).trim();
1475
+ let bodyAt = arrow + 2;
1476
+ while (bodyAt < end && /\s/.test(body[bodyAt])) bodyAt++;
1477
+ if (!pattern) return null;
1478
+ arms.push({ pattern, at, end, bodyAt, body: body.slice(bodyAt, end).trim() });
1479
+ i = end + 1;
1480
+ }
1481
+ return arms.length ? arms : null;
1482
+ }
1483
+ var ARMS_HEAD = /(?:^|=\s*|return\s+)(?:[\w.]+\s+(?=switch))?(?:match\b\s*[^{\s][^{]*|when\s*(?:\([^{]*\))?|switch)\s*\{\s*$/;
532
1484
  function braceStatements(stmts, split = null) {
533
1485
  return stmts.map((s) => {
534
1486
  const text = s.text;
535
- const open = text.indexOf("{");
1487
+ const head0 = headLine(text);
1488
+ const lit = BLOCK_HEAD.test(head0) && !/^func\s*\(/.test(head0) ? null : fnLiteral(text);
1489
+ let open = lit?.open ?? text.indexOf("{");
536
1490
  const lineAtPos = (pos) => s.line + (text.slice(0, pos).match(/\n/g) || []).length;
537
1491
  const read = (o, e) => {
538
- const body = e > o ? text.slice(o + 1, e) : "";
539
- const base = s.start != null ? s.start + o + 1 : null;
1492
+ let from = o + 1;
1493
+ const params = text.slice(from, e).match(LAMBDA_PARAMS);
1494
+ if (params && !ARMS_HEAD.test(head0)) from += params[0].length;
1495
+ const body = e > from ? text.slice(from, e) : "";
1496
+ const base = s.start != null ? s.start + from : null;
540
1497
  if (!body || !split) return [];
541
- const kids2 = split(body, lineAtPos(o + 1)).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {} }));
1498
+ const kids2 = split(body, lineAtPos(from)).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {} }));
542
1499
  return braceStatements(kids2, split);
543
1500
  };
1501
+ const readArms = (o, e) => {
1502
+ const body = e > o ? text.slice(o + 1, e) : "";
1503
+ const arms = body ? armsOf(body) : null;
1504
+ if (!arms || !split) return null;
1505
+ return arms.map((a) => {
1506
+ const at = o + 1 + a.at, bodyAt = o + 1 + a.bodyAt, end = o + 1 + a.end;
1507
+ const pos = (p) => s.start != null ? { start: s.start + p } : {};
1508
+ let kids2 = [];
1509
+ if (a.body.startsWith("{")) kids2 = read(bodyAt, blockEnd(text, bodyAt));
1510
+ else if (a.body) kids2 = braceStatements([{ text: a.body.replace(/,$/, ""), line: lineAtPos(bodyAt), endLine: lineAtPos(Math.max(bodyAt, end - 1)), ...s.start != null ? { start: s.start + bodyAt, end: s.start + bodyAt + a.body.replace(/,$/, "").length } : {} }], split);
1511
+ return { text: text.slice(at, end).trim(), arm: a.pattern, line: lineAtPos(at), endLine: lineAtPos(Math.max(at, end - 1)), ...pos(at), ...s.start != null ? { end: s.start + end } : {}, inner: kids2.length, children: kids2 };
1512
+ });
1513
+ };
544
1514
  let children = [], inner = 0;
545
1515
  const clauses = [];
1516
+ if (lit?.expr) {
1517
+ const [f, t] = lit.expr;
1518
+ const raw = text.slice(f, t);
1519
+ const lead = raw.length - raw.trimStart().length;
1520
+ const expr = raw.trim();
1521
+ if (expr) children = braceStatements([{ text: expr, line: lineAtPos(f + lead), endLine: lineAtPos(f + lead + expr.length - 1), ...s.start != null ? { start: s.start + f + lead, end: s.start + f + lead + expr.length } : {} }], split);
1522
+ inner = children.length;
1523
+ return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, fn: { depth: lit.depth, expr: true, after: text.slice(t) } };
1524
+ }
546
1525
  if (open >= 0) {
547
1526
  const end = blockEnd(text, open);
1527
+ if (!lit && ARMS_HEAD.test(head0)) {
1528
+ const arms = readArms(open, end);
1529
+ if (arms) return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner: arms.length, children: arms, arms: true };
1530
+ }
548
1531
  const body = end > open ? text.slice(open + 1, end) : "";
549
1532
  inner = body ? body.split(/;|\n/).filter((l) => l.trim() && !/^[{}]$/.test(l.trim())).length : 0;
550
1533
  children = read(open, end);
@@ -563,7 +1546,7 @@ function braceStatements(stmts, split = null) {
563
1546
  pos = e + 1;
564
1547
  }
565
1548
  }
566
- return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...clauses.length ? { clauses } : {} };
1549
+ return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...clauses.length ? { clauses } : {}, ...lit ? { fn: { depth: lit.depth, after: text.slice(lit.close + 1) } } : {} };
567
1550
  });
568
1551
  }
569
1552
  function indentStatements(body, { depthKey = "indent" } = {}) {
@@ -1937,7 +2920,7 @@ var SEMANTIC_TYPES = Object.keys(SEMANTIC);
1937
2920
  var PRIMITIVE_TYPES = Object.keys(PRIMITIVE);
1938
2921
 
1939
2922
  // src/emit.mjs
1940
- var COMPILER_VERSION = "0.5.8";
2923
+ var COMPILER_VERSION = "0.5.10";
1941
2924
 
1942
2925
  // src/lift.mjs
1943
2926
  var IR_SCHEMA_VERSION = "0.1.0";
@@ -2522,8 +3505,8 @@ var LANG_EXT = {
2522
3505
 
2523
3506
  // src/read.mjs
2524
3507
  var READ_SCHEMA = "thunder-reading-v1";
2525
- var READ_LANGUAGES = ["typescript", "javascript", "python", "go", "rust", "csharp", "java", "kotlin", "php", "ruby"];
2526
- var KEYWORDS_NOT_FN = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "return", "new", "else", "using", "lock", "foreach", "match", "loop", "sizeof", "typeof", "nameof"]);
3508
+ var READ_LANGUAGES = ["typescript", "javascript", "python", "go", "rust", "csharp", "java", "kotlin", "php", "ruby", "sql"];
3509
+ var KEYWORDS_NOT_FN = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "return", "new", "else", "using", "lock", "synchronized", "foreach", "match", "loop", "sizeof", "typeof", "nameof"]);
2527
3510
  function detectLanguage(source, file = "") {
2528
3511
  if (file) return languageForFile(file);
2529
3512
  const s = String(source);
@@ -3076,7 +4059,7 @@ function kotlinTerminate(body) {
3076
4059
  else if (")]}".includes(c)) depth--;
3077
4060
  else if (c === "\n" && depth === 0) {
3078
4061
  const line = src.slice(src.lastIndexOf("\n", i - 1) + 1, i);
3079
- const next = src.slice(i + 1);
4062
+ const next = src.slice(i + 1, i + 400);
3080
4063
  if (line.trim() && !/[{;]\s*$/.test(line) && !KT_CONTINUES_LINE.test(line) && !KT_CONTINUES_NEXT.test(next)) {
3081
4064
  out += src.slice(last, i) + ";";
3082
4065
  last = i;
@@ -3213,7 +4196,7 @@ function lex(text) {
3213
4196
  }
3214
4197
  return out;
3215
4198
  }
3216
- var unquote = (t) => t.slice(1, -1);
4199
+ var unquote2 = (t) => t.slice(1, -1);
3217
4200
  function toThunderCondition(text, inputs = []) {
3218
4201
  const toks = lex(text);
3219
4202
  if (!toks || !toks.length) return null;
@@ -3259,7 +4242,7 @@ function toThunderCondition(text, inputs = []) {
3259
4242
  }
3260
4243
  if (/^["']/.test(t)) {
3261
4244
  if (t[0] === '"' && /#\{|\$\{|\$[A-Za-z_]/.test(t)) return null;
3262
- out.push(JSON.stringify(unquote(t)));
4245
+ out.push(JSON.stringify(unquote2(t)));
3263
4246
  continue;
3264
4247
  }
3265
4248
  if (/^\d/.test(t)) {
@@ -3361,7 +4344,7 @@ function toThunderOutcome(text) {
3361
4344
  }
3362
4345
  var lastSeg2 = (s) => String(s).split(/\.|::/).pop();
3363
4346
  var firstString = (s) => (String(s).match(/^\s*(?:f|r|b)?["'`]([^"'`]{1,80})["'`]/) || [])[1] || null;
3364
- function splitTop(str, delim) {
4347
+ function splitTop2(str, delim) {
3365
4348
  const out = [];
3366
4349
  let depth = 0, cur = "";
3367
4350
  for (let i = 0; i < str.length; i++) {
@@ -3406,7 +4389,7 @@ function terminatorEffect(stmt, language) {
3406
4389
  if (!(m = s.match(/^return\s+([\s\S]+)$/))) return null;
3407
4390
  const v = m[1].trim();
3408
4391
  if (language === "go") {
3409
- const parts = splitTop(v, ",").map((x) => x.trim());
4392
+ const parts = splitTop2(v, ",").map((x) => x.trim());
3410
4393
  const last = parts[parts.length - 1];
3411
4394
  if (last === "err" || /^fmt\.Errorf\([^)]*%w/.test(last)) return { kind: "passes-error" };
3412
4395
  if (m = last.match(/^(?:errors\.New|fmt\.Errorf)\(\s*"([^"]*)"/)) return { kind: "fails", name: "error", detail: m[1] };
@@ -3438,7 +4421,7 @@ function sayGuard(effect, condText) {
3438
4421
  }
3439
4422
  }
3440
4423
  function makeGuard(cond, branch, language, inputs, line) {
3441
- const stmts = splitTop(branch.trim().replace(/;\s*$/, ""), ";").map((x) => x.trim()).filter(Boolean);
4424
+ const stmts = splitTop2(branch.trim().replace(/;\s*$/, ""), ";").map((x) => x.trim()).filter(Boolean);
3442
4425
  if (stmts.length !== 1 || /\n\s*\S[\s\S]*\n/.test(stmts[0]) && !/^(throw|raise|return)/.test(stmts[0])) return null;
3443
4426
  const effect = terminatorEffect(stmts[0], language);
3444
4427
  if (!effect) return null;
@@ -3484,7 +4467,7 @@ function patternCondition(pattern, subject, inputs, language) {
3484
4467
  const v2 = toThunderOutcome(m[1]);
3485
4468
  return v2 ? `${subject} != ${/^[A-Za-z_]/.test(v2) && !/^(true|false)$/.test(v2) ? v2 : v2}` : null;
3486
4469
  }
3487
- const parts = splitTop(p.replace(/\s+or\s+/g, "|"), language === "rust" || language === "csharp" || language === "python" ? "|" : ",").map((x) => x.trim()).filter(Boolean);
4470
+ const parts = splitTop2(p.replace(/\s+or\s+/g, "|"), language === "rust" || language === "csharp" || language === "python" ? "|" : ",").map((x) => x.trim()).filter(Boolean);
3488
4471
  if (parts.length > 1) {
3489
4472
  const each = parts.map((x) => patternCondition(x, subject, inputs, language));
3490
4473
  return each.every(Boolean) ? each.map((c) => /\s(and|or)\s/.test(c) ? `(${c})` : c).join(" or ") : null;
@@ -3690,8 +4673,9 @@ function splitStatements(body, baseLine) {
3690
4673
  }
3691
4674
  i = close;
3692
4675
  if (depth === 0) {
3693
- const rest2 = src.slice(i + 1).match(/^\s*else\b/);
3694
- if (!rest2) {
4676
+ const next = src.slice(i + 1, i + 40);
4677
+ 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);
4678
+ if (!goes) {
3695
4679
  i++;
3696
4680
  break;
3697
4681
  }
@@ -3705,6 +4689,10 @@ function splitStatements(body, baseLine) {
3705
4689
  let j = i + 1;
3706
4690
  while (j < src.length && (src[j] === " " || src[j] === " " || src[j] === "\n" || src[j] === "\r")) j++;
3707
4691
  const after = src.slice(j, j + 24);
4692
+ if (/^(?:case\b[^\n]*|default\s*):$/.test(before)) {
4693
+ i++;
4694
+ break;
4695
+ }
3708
4696
  if (before && !/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) && !/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after)) {
3709
4697
  i++;
3710
4698
  break;
@@ -3839,7 +4827,7 @@ function readBraceStatements(stmts, language, inputs) {
3839
4827
  continue;
3840
4828
  }
3841
4829
  if (language === "php" && (m = t.match(/^abort_(if|unless)\s*\(([\s\S]*)\)\s*;?$/))) {
3842
- const args = splitTop(m[2], ",").map((x) => x.trim());
4830
+ const args = splitTop2(m[2], ",").map((x) => x.trim());
3843
4831
  if (args.length >= 2 && /^\d{3}$/.test(args[1])) {
3844
4832
  const cond = m[1] === "if" ? args[0] : `!(${args[0]})`;
3845
4833
  const when = toThunderCondition(cond, inputs);
@@ -4127,8 +5115,8 @@ function findRubyFunctions(src) {
4127
5115
  var RB_PREDICATE_NOT_FIELD = /^(nil|empty|zero|blank|present|any|none|all|include|key|is_a|kind_of|respond_to|start_with|end_with|between|positive|negative|even|odd)$/;
4128
5116
  function rbExpr(text) {
4129
5117
  let bad = false;
4130
- const bare = String(text).replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
4131
- if (/===/.test(bare) || /(<=?|>=?)\s*[A-Z][a-z]\w*(?!\w*\s*[(.])/.test(bare.replace(/<=>/g, "")) || /\b[A-Z][a-z]\w*\s*(<=?|>=?)/.test(bare)) return null;
5118
+ const bare2 = String(text).replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""');
5119
+ if (/===/.test(bare2) || /(<=?|>=?)\s*[A-Z][a-z]\w*(?!\w*\s*[(.])/.test(bare2.replace(/<=>/g, "")) || /\b[A-Z][a-z]\w*\s*(<=?|>=?)/.test(bare2)) return null;
4132
5120
  const out = mapCode(String(text), (code) => code.replace(/@(?=[A-Za-z_])/g, "").replace(/(^|[\s(,=!<>[])::?([A-Za-z_]\w*)\b(?!:)/g, (all, pre, name) => all.includes("::") ? all : `${pre}"${name}"`).replace(/\.(\w+)\?/g, (all, name) => {
4133
5121
  if (RB_PREDICATE_NOT_FIELD.test(name)) bad = true;
4134
5122
  return `.${name}`;
@@ -4428,9 +5416,10 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
4428
5416
  function readCode(source, { language, file = "" } = {}) {
4429
5417
  const src = String(source ?? "");
4430
5418
  if (src.length > 4e5) throw new Error("Source is larger than 400 KB. Read one file or module at a time.");
4431
- 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");
5419
+ 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");
4432
5420
  if (!READ_LANGUAGES.includes(lang)) throw new Error(`Reading rules supports ${READ_LANGUAGES.join(", ")}. Got "${lang}".`);
4433
5421
  READING_RUST = lang === "rust";
5422
+ if (lang === "sql") return sqlReading(src);
4434
5423
  const code = lang === "php" ? normalizePhp(src) : src;
4435
5424
  const items = [];
4436
5425
  const srcLines = src.split("\n");
@@ -4518,6 +5507,22 @@ function readCode(source, { language, file = "" } = {}) {
4518
5507
  ]
4519
5508
  };
4520
5509
  }
5510
+ function sqlReading(src) {
5511
+ const items = sqlItems(src);
5512
+ for (const it of items) it.completeness = completenessOf(it);
5513
+ const counts = { decision: 0, function: items.length, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
5514
+ return {
5515
+ schema: READ_SCHEMA,
5516
+ language: "sql",
5517
+ detected: false,
5518
+ items,
5519
+ counts,
5520
+ limitations: [
5521
+ "Read by pattern, not by running it on a database. PostgreSQL first; other dialects where their syntax agrees.",
5522
+ "Tables are drawn as Data or Things; CHECK and UNIQUE as rules the database enforces; views, functions, procedures, and triggers as steps."
5523
+ ]
5524
+ };
5525
+ }
4521
5526
 
4522
5527
  // src/runtime.mjs
4523
5528
  var RUNTIME_SCHEMA = "intent-runtime-v1";
@@ -4754,7 +5759,7 @@ var STEP_MARKS = {
4754
5759
  restates: { mark: "\xB7", label: "Code", color: "unread", show: "code", line: "dashed" },
4755
5760
  other: { mark: "\xB7", label: "Not read yet", color: "unread", show: "code", line: "dashed" }
4756
5761
  };
4757
- var words2 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
5762
+ var words3 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
4758
5763
  function visualFor(item) {
4759
5764
  if (!item || typeof item !== "object") throw new Error("visualFor needs a reader item.");
4760
5765
  const base = { provenance: item.provenance === "confirmed" ? "confirmed" : "from-code", ...item.doc ? { doc: { text: item.doc, provenance: "authors-note" } } : {} };
@@ -4763,11 +5768,11 @@ function visualFor(item) {
4763
5768
  const badge = item.route ? { kind: "route", text: `${item.route.method} ${item.route.path}`.trim() } : void 0;
4764
5769
  if (item.kind === "decision") {
4765
5770
  const card = safePlain(item);
4766
- return { element: "decision", shape: "card", line: item.status === "partial" ? "dashed" : "solid", title: card?.question || `How ${words2(item.name)} decides`, ...badge ? { badge } : {}, ...item.status === "partial" ? { note: "Partly read" } : {}, ...base };
5771
+ return { element: "decision", shape: "card", line: item.status === "partial" ? "dashed" : "solid", title: card?.question || `How ${words3(item.name)} decides`, ...badge ? { badge } : {}, ...item.status === "partial" ? { note: "Partly read" } : {}, ...base };
4767
5772
  }
4768
5773
  const readable = (item.stepsReadable ?? 0) >= 0.5 && item.steps?.length;
4769
- if (!readable) return { element: "not-read", shape: "dashed-card", line: "dashed", title: `What ${words2(item.name)} does`, ...badge ? { badge } : {}, ...base, provenance: "not-read" };
4770
- return { element: item.route ? "action" : "function", shape: "steps-card", line: "solid", title: item.route ? `When someone calls ${badge.text}` : `What ${words2(item.name)} does`, ...badge ? { badge } : {}, ...base };
5774
+ if (!readable) return { element: "not-read", shape: "dashed-card", line: "dashed", title: `What ${words3(item.name)} does`, ...badge ? { badge } : {}, ...base, provenance: "not-read" };
5775
+ return { element: item.route ? "action" : "function", shape: "steps-card", line: "solid", title: item.route ? `When someone calls ${badge.text}` : `What ${words3(item.name)} does`, ...badge ? { badge } : {}, ...base };
4771
5776
  }
4772
5777
  function visualForStep(step) {
4773
5778
  const key = step?.restates ? "restates" : STEP_MARKS[step?.kind] ? step.kind : "other";
@@ -4794,7 +5799,7 @@ function thunderText(item) {
4794
5799
  }
4795
5800
  const out = [v.title];
4796
5801
  if (item.doc) out.push(` Author's note: "${item.doc}"`);
4797
- if (item.inputs?.length) out.push(` Takes ${item.inputs.map((p) => words2(p.name)).join(", ")}`);
5802
+ if (item.inputs?.length) out.push(` Takes ${item.inputs.map((p) => words3(p.name)).join(", ")}`);
4798
5803
  const steps = item.steps || [];
4799
5804
  const lines = (list, depth) => {
4800
5805
  for (const st of list) {
@@ -4853,7 +5858,8 @@ var EXT_LANG = [
4853
5858
  [/\.java$/i, "java"],
4854
5859
  [/\.kts?$/i, "kotlin"],
4855
5860
  [/\.php$/i, "php"],
4856
- [/\.rb$/i, "ruby"]
5861
+ [/\.rb$/i, "ruby"],
5862
+ [/\.sql$/i, "sql"]
4857
5863
  ];
4858
5864
  var READ_SKIP_DIRS = /* @__PURE__ */ new Set([
4859
5865
  "node_modules",
@@ -4890,43 +5896,435 @@ function readableLanguage(path) {
4890
5896
  for (const [re, lang] of EXT_LANG) if (re.test(p)) return lang;
4891
5897
  return null;
4892
5898
  }
5899
+ function readingOf(f, language = readableLanguage(f.path)) {
5900
+ if (f.readError) throw new Error(f.readError);
5901
+ return f.reading ?? readCode(f.source, { language, file: f.path });
5902
+ }
5903
+
5904
+ // src/things-langs.mjs
5905
+ function braceEnd(src, open) {
5906
+ let depth = 0;
5907
+ for (let i = open; i < src.length; i++) {
5908
+ const c = src[i];
5909
+ if (c === "/" && src[i + 1] === "/") {
5910
+ const n = src.indexOf("\n", i);
5911
+ if (n < 0) return -1;
5912
+ i = n;
5913
+ continue;
5914
+ }
5915
+ if (c === "/" && src[i + 1] === "*") {
5916
+ const n = src.indexOf("*/", i + 2);
5917
+ if (n < 0) return -1;
5918
+ i = n + 1;
5919
+ continue;
5920
+ }
5921
+ if (c === '"' || c === "`") {
5922
+ const q = c;
5923
+ for (i++; i < src.length && src[i] !== q; i++) if (src[i] === "\\") i++;
5924
+ continue;
5925
+ }
5926
+ if (c === "'" && /^'(?:\\.|[^\\'])'/.test(src.slice(i, i + 4))) {
5927
+ i = src.indexOf("'", i + 1 + (src[i + 1] === "\\" ? 1 : 0));
5928
+ continue;
5929
+ }
5930
+ if (c === "{") depth++;
5931
+ else if (c === "}" && --depth === 0) return i;
5932
+ }
5933
+ return -1;
5934
+ }
5935
+ function lineFinder2(src) {
5936
+ const starts = [0];
5937
+ for (let i = src.indexOf("\n"); i >= 0; i = src.indexOf("\n", i + 1)) starts.push(i + 1);
5938
+ return (idx) => {
5939
+ let lo = 0, hi = starts.length - 1;
5940
+ while (lo < hi) {
5941
+ const mid = lo + hi + 1 >> 1;
5942
+ if (starts[mid] <= idx) lo = mid;
5943
+ else hi = mid - 1;
5944
+ }
5945
+ return lo + 1;
5946
+ };
5947
+ }
5948
+ function docAbove2(src, idx) {
5949
+ let before = src.slice(Math.max(0, idx - 1200), idx).trimEnd();
5950
+ for (let n = 0; n < 20; n++) {
5951
+ const next = before.replace(/(?:@\w+(?:\([^)]*\))?|#\[[^\]]*\]|\[[A-Z]\w*(?:\([^)]*\))?\])$/, "").trimEnd();
5952
+ if (next === before) break;
5953
+ before = next;
5954
+ }
5955
+ let m = /\*\/\s*$/.test(before) ? before.slice(before.lastIndexOf("/**")).match(/^\/\*\*([\s\S]*?)\*\/\s*$/) : null;
5956
+ if (m) return m[1].split("\n").map((l) => l.replace(/^\s*\*\s?/, "").trim()).filter((l) => l && !l.startsWith("@")).join(" ").split(/\s{2,}/)[0] || null;
5957
+ const lines = before.split("\n");
5958
+ const run = [];
5959
+ for (let k = lines.length - 1; k >= 0 && /^\s*(?:\/\/\/?|#(?!\[))/.test(lines[k]); k--) run.unshift(lines[k]);
5960
+ if (run.length) {
5961
+ const text = run.map((l) => l.replace(/^\s*(?:\/\/\/?|#)\s?/, "").trim()).filter(Boolean).join(" ").replace(/<\/?summary>/g, "").trim();
5962
+ return text && !/^(frozen_string_literal|!|typed:)/.test(text) ? text : null;
5963
+ }
5964
+ return null;
5965
+ }
5966
+ function ownLevel(body) {
5967
+ let depth = 0, own = "";
5968
+ for (const c of body) {
5969
+ if (c === "{") depth++;
5970
+ if (depth === 0) own += c;
5971
+ if (c === "}") depth--;
5972
+ }
5973
+ return own;
5974
+ }
5975
+ function splitParams(s) {
5976
+ const out = [];
5977
+ let depth = 0, cur = "";
5978
+ for (const c of String(s)) {
5979
+ if ("(<[{".includes(c)) depth++;
5980
+ if (")>]}".includes(c)) depth--;
5981
+ if (c === "," && depth === 0) {
5982
+ out.push(cur.trim());
5983
+ cur = "";
5984
+ } else cur += c;
5985
+ }
5986
+ if (cur.trim()) out.push(cur.trim());
5987
+ return out;
5988
+ }
5989
+ function goDoc(src, at, name) {
5990
+ const d = docAbove2(src, at);
5991
+ if (!d) return null;
5992
+ const t = d.replace(new RegExp(`^${name}\\s+(?:is|holds|represents)\\s+`), "").replace(new RegExp(`^${name}\\s+`), "");
5993
+ return t.charAt(0).toUpperCase() + t.slice(1);
5994
+ }
5995
+ function makeThingReaders({ words: words5, kindWords: kindWords2, startValue: startValue2 }) {
5996
+ const know = (name, type, start, params, line = null) => ({ name, label: words5(name.replace(/^[_$]+|_$/g, "")), kind: type ? kindWords2(type) : null, start: start != null && start !== "" ? startValue2(start, params) : null, line });
5997
+ function curlyThings(src, file, language) {
5998
+ const lineAt2 = lineFinder2(src);
5999
+ const out = [];
6000
+ const kw = {
6001
+ java: /(?:^|\n)[ \t]*(?:@\w+(?:\([^)]*\))?\s*)*(?:(?:public|private|protected|static|final|abstract|sealed|non-sealed)\s+)*(class|enum|record)\s+(\w+)\s*(?:<[^>{]*>)?\s*(\([^)]*\))?[^{;]*\{/g,
6002
+ csharp: /(?:^|\n)[ \t]*(?:\[[^\]]*\]\s*)*(?:(?:public|private|protected|internal|static|sealed|abstract|partial|readonly|file)\s+)*(class|struct|enum|record(?:\s+(?:class|struct))?)\s+(\w+)\s*(?:<[^>{(]*>)?\s*(\([^)]*\))?[^{;]*(?:\{|;)/g,
6003
+ kotlin: /(?:^|\n)[ \t]*(?:@\w+(?:\([^)]*\))?\s*)*(?:(?:public|private|protected|internal|open|abstract|sealed|final|data|enum|value|inline)\s+)*(class|object)\s+(\w+)\s*(?:<[^>{(]*>)?\s*(?:(?:private|internal|public)?\s*constructor\s*)?(\((?:[^()]|\([^()]*\))*\))?[^{\n]*(\{)?/g,
6004
+ php: /(?:^|\n)[ \t]*(?:#\[[^\]]*\]\s*)*(?:(?:final|abstract|readonly)\s+)*(class|enum)\s+(\w+)(?:\s*:\s*\w+)?[^{;]*\{/g
6005
+ }[language];
6006
+ if (!kw) return out;
6007
+ let m;
6008
+ while (m = kw.exec(src)) {
6009
+ const declAt = m.index + (m[0].startsWith("\n") ? 1 : 0);
6010
+ const head = m[0];
6011
+ const kindWord = m[1];
6012
+ const name = m[2];
6013
+ const ctorParams = m[3] && m[3].startsWith("(") ? m[3].slice(1, -1) : "";
6014
+ const isData = language === "kotlin" ? /\bdata\s+class\b|\bvalue\s+class\b/.test(head) : false;
6015
+ const isEnum = kindWord === "enum" || language === "kotlin" && /\benum\s+class\b/.test(head);
6016
+ const isRecord = !isEnum && (/^record/.test(kindWord) || isData || language === "csharp" && kindWord === "struct");
6017
+ const open = head.trimEnd().endsWith("{") ? m.index + head.trimEnd().length - 1 : -1;
6018
+ const close = open >= 0 ? braceEnd(src, open) : -1;
6019
+ if (open >= 0 && close < 0) continue;
6020
+ const body = open >= 0 ? src.slice(open + 1, close) : "";
6021
+ const thing = {
6022
+ kind: isEnum ? "choices" : isRecord ? "record" : "thing",
6023
+ name,
6024
+ file,
6025
+ lines: [lineAt2(declAt), lineAt2(close >= 0 ? close : m.index + head.length)],
6026
+ ...docAbove2(src, declAt) ? { doc: docAbove2(src, declAt) } : {},
6027
+ knows: [],
6028
+ choices: []
6029
+ };
6030
+ const params = {};
6031
+ for (const p of splitParams(ctorParams)) {
6032
+ let pm;
6033
+ if (language === "kotlin" && (pm = p.match(/^(?:@\w+\s+)*(?:(?:private|public|protected|internal|override|open)\s+)*(val|var)?\s*(\w+)\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/))) {
6034
+ params[pm[2]] = pm[4] ?? null;
6035
+ if (pm[1]) thing.knows.push(know(pm[2], pm[3], pm[4], {}, null));
6036
+ } else if (pm = p.match(/^(?:@\w+\s+)*(?:final\s+)?([\w.<>[\],? ]+?)\s+(\w+)(?:\s*=\s*(.+))?$/)) {
6037
+ params[pm[2]] = pm[3] ?? null;
6038
+ if (/^record/.test(kindWord) || language === "csharp" && /^record/.test(kindWord)) thing.knows.push(know(pm[2], pm[1], pm[3], {}, null));
6039
+ }
6040
+ }
6041
+ if (isEnum) {
6042
+ const own2 = ownLevel(body.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, ""));
6043
+ const list = language === "php" ? [...own2.matchAll(/\bcase\s+(\w+)(?:\s*=\s*([^;]+))?;/g)].map((x) => [x[1], x[2]]) : own2.split(";")[0].split(",").map((x) => x.trim().match(/^(?:@\w+\s+)*(\w+)\s*(?:\((.*)\))?(?:\s*=\s*(.+))?/s)).filter(Boolean).map((x) => [x[1], x[2] ?? x[3]]);
6044
+ for (const [n, v] of list) if (n && !/^(public|private|protected|fun|val|var|companion)$/.test(n)) thing.choices.push(v && /^\s*["']/.test(v) ? v.trim().replace(/^["'](.*)["']$/s, "$1") : words5(n));
6045
+ out.push(thing);
6046
+ continue;
6047
+ }
6048
+ const own = ownLevel(body);
6049
+ for (const raw of own.split(/[;\n]/)) {
6050
+ const l = raw.trim().replace(/^(?:@\w+(?:\([^)]*\))?\s*)+/, "").replace(/^#\[[^\]]*\]\s*/, "");
6051
+ if (!l || /^(\/\/|\/\*|\*|import|package|use|return|case|default|enum\s|class\s|interface\s|fun\s|function\s|def\s|init\b|constructor|companion|object\s)/.test(l) || /\)\s*$/.test(l) && !/=/.test(l)) continue;
6052
+ let f;
6053
+ if (language === "kotlin" && (f = l.match(/^(?:(?:private|public|protected|internal|override|open|lateinit|const)\s+)*(?:val|var)\s+(\w+)\s*(?::\s*([^=]+?))?\s*(?:=\s*(.+))?$/))) {
6054
+ thing.knows.push(know(f[1], f[2], f[3], params));
6055
+ } else if (language === "php" && (f = l.match(/^(?:(?:public|private|protected|static|readonly)\s+)+(?:\??[\w\\]+\s+)?\$(\w+)(?:\s*=\s*(.+))?$/))) {
6056
+ const type = l.match(/^(?:(?:public|private|protected|static|readonly)\s+)+(\??[\w\\]+)\s+\$/)?.[1];
6057
+ thing.knows.push(know(f[1], type, f[2], params));
6058
+ } else if (language === "csharp" && (f = l.match(/^(?:(?:public|private|protected|internal|static|readonly|required|virtual|override|const)\s+)*([\w.<>[\],? ]+?)\s+(\w+)\s*\{\s*(?:get|init|set)[^}]*\}(?:\s*=\s*(.+))?$/))) {
6059
+ thing.knows.push(know(f[2], f[1], f[3], params));
6060
+ } else if ((language === "java" || language === "csharp") && (f = l.match(/^(?:(?:public|private|protected|internal|static|final|readonly|transient|volatile|const)\s+)*([\w.<>[\],? ]+?)\s+(\w+)(?:\s*=\s*(.+))?$/)) && !/^(new|return|throw|if|for|while)$/.test(f[1].trim())) {
6061
+ if (/\bstatic\b/.test(l) && /\bfinal\b|\bconst\b/.test(l)) continue;
6062
+ thing.knows.push(know(f[2], f[1], f[3], params));
6063
+ }
6064
+ }
6065
+ const ctorRe = language === "php" ? /function\s+__construct\s*\(([^)]*)\)\s*\{/ : language === "kotlin" ? /\binit\s*\{/ : new RegExp(`(?:public|private|protected|internal)?\\s*${name}\\s*\\(([^)]*)\\)\\s*(?::\\s*(?:this|base)\\([^)]*\\)\\s*)?\\{`);
6066
+ const ctor = body.match(ctorRe);
6067
+ if (ctor) {
6068
+ for (const p of splitParams(ctor[1] || "")) {
6069
+ const pm = language === "php" ? p.match(/^(?:(public|private|protected)(?:\s+readonly)?\s+)?(?:\??[\w\\]+\s+)?\$(\w+)(?:\s*=\s*(.+))?$/) : p.match(/^(?:final\s+)?(?:[\w.<>[\],? ]+?)\s+(\w+)(?:\s*=\s*(.+))?$/);
6070
+ if (!pm) continue;
6071
+ if (language === "php") {
6072
+ params[pm[2]] = pm[3] ?? null;
6073
+ if (pm[1] && !thing.knows.some((k) => k.name === pm[2])) thing.knows.push(know(pm[2], p.match(/(\??[\w\\]+)\s+\$/)?.[1], pm[3], {}));
6074
+ } else params[pm[1]] = pm[2] ?? null;
6075
+ }
6076
+ const cOpen = body.indexOf("{", ctor.index + ctor[0].length - 1);
6077
+ const cBody = body.slice(cOpen + 1, braceEnd(body, cOpen));
6078
+ const assign = language === "php" ? /\$this->(\w+)\s*=\s*([^;\n]+)/g : language === "kotlin" ? /(?:this\.)?(\w+)\s*=\s*([^\n;]+)/g : /(?:this\.)?(\w+)\s*=\s*([^;\n]+);/g;
6079
+ for (const a of cBody.matchAll(assign)) {
6080
+ const k = thing.knows.find((x) => x.name === a[1] || x.name === `_${a[1]}` || x.name.replace(/^_/, "") === a[1]);
6081
+ const value = a[2].trim().replace(/^\$/, "");
6082
+ if (k) {
6083
+ if (!k.start) k.start = startValue2(value, params);
6084
+ } else if (language === "php" || /^this\./.test(a[0])) thing.knows.push(know(a[1], null, value, params));
6085
+ }
6086
+ }
6087
+ out.push(thing);
6088
+ }
6089
+ return out;
6090
+ }
6091
+ function goThings(src, file) {
6092
+ const lineAt2 = lineFinder2(src);
6093
+ const out = [];
6094
+ const byName = /* @__PURE__ */ new Map();
6095
+ for (const m of src.matchAll(/(?:^|\n)type\s+(\w+)\s+struct\s*\{/g)) {
6096
+ const at = m.index + (m[0].startsWith("\n") ? 1 : 0);
6097
+ const open = m.index + m[0].length - 1;
6098
+ const close = braceEnd(src, open);
6099
+ if (close < 0) continue;
6100
+ const t = { kind: "record", name: m[1], file, lines: [lineAt2(at), lineAt2(close)], ...goDoc(src, at, m[1]) ? { doc: goDoc(src, at, m[1]) } : {}, knows: [], choices: [], memberRanges: [] };
6101
+ for (const raw of src.slice(open + 1, close).split("\n")) {
6102
+ const f = raw.replace(/\/\/.*$/, "").replace(/`[^`]*`/g, "").trim().match(/^([A-Za-z_]\w*(?:\s*,\s*[A-Za-z_]\w*)*)\s+(\S.*)$/);
6103
+ if (f) for (const n of f[1].split(",")) t.knows.push(know(n.trim(), f[2].trim(), null, {}));
6104
+ }
6105
+ out.push(t);
6106
+ byName.set(m[1], t);
6107
+ }
6108
+ for (const m of src.matchAll(/(?:^|\n)func\s*\(\s*\w*\s*\*?\s*(\w+)(?:\[[^\]]*\])?\s*\)\s*\w+/g)) {
6109
+ const t = byName.get(m[1]);
6110
+ if (!t) continue;
6111
+ const at = m.index + (m[0].startsWith("\n") ? 1 : 0);
6112
+ const open = src.indexOf("{", at);
6113
+ const close = open >= 0 ? braceEnd(src, open) : -1;
6114
+ t.kind = "thing";
6115
+ t.memberRanges.push([lineAt2(at), lineAt2(close >= 0 ? close : at)]);
6116
+ }
6117
+ for (const m of src.matchAll(/func\s+New(\w+)\s*\(([^)]*)\)[^{]*\{/g)) {
6118
+ const t = byName.get(m[1]);
6119
+ if (!t) continue;
6120
+ const open = m.index + m[0].length - 1;
6121
+ const body = src.slice(open, braceEnd(src, open) + 1);
6122
+ const params = Object.fromEntries(splitParams(m[2]).map((p) => [p.split(/\s+/)[0], null]));
6123
+ const litAt = body.search(new RegExp(`&?${m[1]}\\s*\\{`));
6124
+ const litOpen = litAt >= 0 ? body.indexOf("{", litAt) : -1;
6125
+ const litBody = litOpen >= 0 ? body.slice(litOpen + 1, braceEnd(body, litOpen)) : "";
6126
+ for (const kv of splitParams(litBody.replace(/\n/g, ","))) {
6127
+ const f = kv.match(/^(\w+)\s*:\s*(.+)$/);
6128
+ const k = f && t.knows.find((x) => x.name === f[1]);
6129
+ if (k && !k.start) k.start = startValue2(f[2].trim(), params);
6130
+ }
6131
+ }
6132
+ for (const m of src.matchAll(/(?:^|\n)type\s+(\w+)\s+(?:int|int8|int16|int32|uint|uint8|string)\b/g)) {
6133
+ const name = m[1];
6134
+ const block = src.match(new RegExp(`const\\s*\\(([^)]*\\b${name}\\b[^)]*)\\)`));
6135
+ if (!block) continue;
6136
+ const at = m.index + (m[0].startsWith("\n") ? 1 : 0);
6137
+ const choices = [];
6138
+ let inType = false;
6139
+ for (const raw of block[1].split("\n")) {
6140
+ const l = raw.replace(/\/\/.*$/, "").trim();
6141
+ if (!l) continue;
6142
+ const f = l.match(/^(\w+)(?:\s+(\w+))?(?:\s*=\s*(.+))?$/);
6143
+ if (!f) continue;
6144
+ if (f[2]) inType = f[2] === name;
6145
+ if (!inType) continue;
6146
+ const label = f[3] && /^"/.test(f[3].trim()) ? f[3].trim().slice(1, -1) : words5(f[1].replace(new RegExp(`^${name}`), "") || f[1]);
6147
+ choices.push(label);
6148
+ }
6149
+ if (choices.length) out.push({ kind: "choices", name, file, lines: [lineAt2(at), lineAt2(at)], ...goDoc(src, at, name) ? { doc: goDoc(src, at, name) } : {}, knows: [], choices });
6150
+ }
6151
+ return out;
6152
+ }
6153
+ function rustThings(src, file) {
6154
+ const lineAt2 = lineFinder2(src);
6155
+ const out = [];
6156
+ const byName = /* @__PURE__ */ new Map();
6157
+ for (const m of src.matchAll(/(?:^|\n)[ \t]*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?(struct|enum)\s+(\w+)\s*(?:<[^>{]*>)?\s*(?:where[^{]*)?(\{|\(|;)/g)) {
6158
+ const at = m.index + (m[0].startsWith("\n") ? 1 : 0);
6159
+ const doc = docAbove2(src, at);
6160
+ if (m[3] !== "{") {
6161
+ const t2 = { kind: "record", name: m[2], file, lines: [lineAt2(at), lineAt2(at)], ...doc ? { doc } : {}, knows: [], choices: [], memberRanges: [] };
6162
+ out.push(t2);
6163
+ byName.set(m[2], t2);
6164
+ continue;
6165
+ }
6166
+ const open = m.index + m[0].length - 1;
6167
+ const close = braceEnd(src, open);
6168
+ if (close < 0) continue;
6169
+ const body = ownLevel(src.slice(open + 1, close));
6170
+ const t = { kind: m[1] === "enum" ? "choices" : "record", name: m[2], file, lines: [lineAt2(at), lineAt2(close)], ...doc ? { doc } : {}, knows: [], choices: [], memberRanges: [] };
6171
+ if (m[1] === "enum") {
6172
+ for (const v of splitParams(body.replace(/\/\/[^\n]*/g, "").replace(/#\[[^\]]*\]/g, ""))) {
6173
+ const n = v.trim().match(/^(\w+)/);
6174
+ if (n) t.choices.push(words5(n[1]));
6175
+ }
6176
+ } else {
6177
+ for (const f of splitParams(body.replace(/\/\/[^\n]*/g, "").replace(/#\[[^\]]*\]/g, ""))) {
6178
+ const fm = f.trim().match(/^(?:pub(?:\([^)]*\))?\s+)?(\w+)\s*:\s*(.+)$/s);
6179
+ if (fm) t.knows.push(know(fm[1], fm[2].trim(), null, {}));
6180
+ }
6181
+ }
6182
+ out.push(t);
6183
+ byName.set(m[2], t);
6184
+ }
6185
+ for (const m of src.matchAll(/(?:^|\n)[ \t]*impl(?:\s*<[^>]*>)?\s+(?:[\w:]+(?:<[^>]*>)?\s+for\s+)?(\w+)(?:<[^>]*>)?\s*(?:where[^{]*)?\{/g)) {
6186
+ const t = byName.get(m[1]);
6187
+ if (!t) continue;
6188
+ const at = m.index + (m[0].startsWith("\n") ? 1 : 0);
6189
+ const close = braceEnd(src, m.index + m[0].length - 1);
6190
+ if (close < 0) continue;
6191
+ if (/\bfn\s+\w+\s*(?:<[^>]*>)?\s*\(\s*&?(?:mut\s+)?self\b/.test(src.slice(at, close))) {
6192
+ if (t.kind === "record") t.kind = "thing";
6193
+ }
6194
+ t.memberRanges.push([lineAt2(at), lineAt2(close)]);
6195
+ const block = src.slice(at, close);
6196
+ const fnNew = block.match(/fn\s+new\s*\(([^)]*)\)[^{;]*\{/);
6197
+ const fnOpen = fnNew ? fnNew.index + fnNew[0].length - 1 : -1;
6198
+ const fnBody = fnOpen >= 0 ? block.slice(fnOpen + 1, braceEnd(block, fnOpen)) : "";
6199
+ const litAt = fnBody.search(new RegExp(`\\b(?:Self|${m[1]})\\s*\\{`));
6200
+ const litOpen = litAt >= 0 ? fnBody.indexOf("{", litAt) : -1;
6201
+ const ctor = litOpen >= 0 ? [null, fnNew[1], fnBody.slice(litOpen + 1, braceEnd(fnBody, litOpen))] : null;
6202
+ if (ctor) {
6203
+ const params = Object.fromEntries(splitParams(ctor[1]).map((p) => [p.split(":")[0].trim(), null]));
6204
+ for (const kv of splitParams(ctor[2].replace(/\n/g, ","))) {
6205
+ const f = kv.match(/^(\w+)(?:\s*:\s*(.+))?$/);
6206
+ const k = f && t.knows.find((x) => x.name === f[1]);
6207
+ if (k && !k.start) k.start = startValue2((f[2] ?? f[1]).trim().replace(/^Vec::new\(\)$|^vec!\[\]$|^HashMap::new\(\)$|^String::new\(\)$/, "[]"), params);
6208
+ }
6209
+ }
6210
+ }
6211
+ return out;
6212
+ }
6213
+ function rubyThings(src, file) {
6214
+ const lines = src.split("\n");
6215
+ const out = [];
6216
+ for (let i = 0; i < lines.length; i++) {
6217
+ const struct = lines[i].match(/^\s*(\w+)\s*=\s*(?:Struct|Data)\.(?:new|define)\(([^)]*)\)/);
6218
+ if (struct) {
6219
+ const t2 = { kind: "record", name: struct[1], file, lines: [i + 1, i + 1], knows: [], choices: [] };
6220
+ for (const s of struct[2].split(",")) {
6221
+ const n = s.trim().match(/^:(\w+)/);
6222
+ if (n) t2.knows.push(know(n[1], null, null, {}, i + 1));
6223
+ }
6224
+ out.push(t2);
6225
+ continue;
6226
+ }
6227
+ const m = lines[i].match(/^(\s*)class\s+(\w+)/);
6228
+ if (!m) continue;
6229
+ const indent = m[1].length;
6230
+ let end = i;
6231
+ for (let j = i + 1; j < lines.length; j++) if (new RegExp(`^\\s{${indent}}end\\b`).test(lines[j]) && lines[j].match(/^\s*/)[0].length === indent) {
6232
+ end = j;
6233
+ break;
6234
+ }
6235
+ if (end === i) continue;
6236
+ const doc = (() => {
6237
+ const d = [];
6238
+ for (let k = i - 1; k >= 0 && /^\s*#/.test(lines[k]); k--) d.unshift(lines[k].replace(/^\s*#\s?/, "").trim());
6239
+ return d.join(" ").trim() || null;
6240
+ })();
6241
+ const t = { kind: "thing", name: m[2], file, lines: [i + 1, end + 1], ...doc && !/frozen_string_literal/.test(doc) ? { doc } : {}, knows: [], choices: [] };
6242
+ const body = lines.slice(i + 1, end);
6243
+ for (let k = 0; k < body.length; k++) {
6244
+ const a = body[k].match(/^\s*attr_(?:reader|accessor|writer)\s+(.+)$/);
6245
+ if (a) for (const s of a[1].split(",")) {
6246
+ const n = s.trim().match(/^:(\w+)/);
6247
+ if (n && !t.knows.some((x) => x.name === n[1])) t.knows.push(know(n[1], null, null, {}, i + 2 + k));
6248
+ }
6249
+ }
6250
+ const init = body.findIndex((l) => /^\s*def\s+initialize\b/.test(l));
6251
+ if (init >= 0) {
6252
+ const sig = body[init].match(/def\s+initialize\s*\(?([^)]*)\)?/);
6253
+ const params = {};
6254
+ for (const p of splitParams(sig?.[1] || "")) {
6255
+ const pm = p.match(/^(\w+):?\s*(?:=\s*)?(.*)$/);
6256
+ if (pm) params[pm[1]] = pm[2] || null;
6257
+ }
6258
+ const ii = body[init].match(/^\s*/)[0].length;
6259
+ for (let k = init + 1; k < body.length; k++) {
6260
+ if (body[k].trim() && body[k].match(/^\s*/)[0].length <= ii) break;
6261
+ const a = body[k].trim().match(/^@(\w+)\s*=\s*(.+)$/);
6262
+ if (!a) continue;
6263
+ const kn = t.knows.find((x) => x.name === a[1]);
6264
+ if (kn) {
6265
+ if (!kn.start) kn.start = startValue2(a[2], params);
6266
+ } else t.knows.push(know(a[1], null, a[2], params, i + 2 + k));
6267
+ }
6268
+ }
6269
+ if (!t.knows.length && !body.some((l) => /^\s*def\s/.test(l))) t.kind = "record";
6270
+ out.push(t);
6271
+ }
6272
+ return out;
6273
+ }
6274
+ return function thingsFor2(language, src, file) {
6275
+ if (language === "go") return goThings(src, file);
6276
+ if (language === "rust") return rustThings(src, file);
6277
+ if (language === "ruby") return rubyThings(src, file);
6278
+ if (["java", "csharp", "kotlin", "php"].includes(language)) return curlyThings(src, file, language);
6279
+ return [];
6280
+ };
6281
+ }
4893
6282
 
4894
6283
  // src/model.mjs
4895
6284
  var MODEL_SCHEMA = "thunder-model-v1";
4896
- var THING_LANGUAGES = ["python", "typescript", "javascript"];
4897
- var words3 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
6285
+ var THING_LANGUAGES = ["python", "typescript", "javascript", "java", "csharp", "kotlin", "php", "go", "rust", "ruby", "sql"];
6286
+ var words4 = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase().trim();
4898
6287
  var cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
4899
6288
  var stripQuotes2 = (v) => v.replace(/^[rbuf]*(["'`])(.*)\1$/s, "$2");
4900
6289
  function startValue(expr, params = {}) {
4901
6290
  const e = String(expr ?? "").trim();
4902
6291
  if (!e) return null;
4903
6292
  if (e in params) return params[e] != null ? `${startValue(params[e])?.replace(/ at first$/, "")} unless told otherwise` : "given when it starts";
4904
- if (/^(\[\]|\{\}|list\(\)|dict\(\)|set\(\)|new (Map|Set|Array)\(\)|\[\]\s*as\s+.+)$/.test(e)) return "empty at first";
4905
- if (/^(None|null|undefined)$/.test(e)) return "nothing at first";
6293
+ if (/^(\[\]|\{\}|list\(\)|dict\(\)|set\(\)|new (Map|Set|Array)\(\)|\[\]\s*as\s+.+|array\(\)|new \w*(?:List|Map|Set|Dictionary|HashMap|HashSet|ArrayList|LinkedList)(?:<[^>]*>)?\(\)|(?:mutable)?(?:List|Map|Set|listOf|mapOf|setOf|mutableListOf|mutableMapOf|mutableSetOf|emptyList|emptyMap|arrayListOf)(?:<[^>]*>)?\(\)|(?:List|Set|Map)\.of\(\)|Vec::new\(\)|vec!\[\]|HashMap::new\(\)|String::new\(\)|\[\]\w+\{\}|make\(\[\][^)]*\)|new\(\)|Hash\.new|\{\s*\})$/.test(e)) return "empty at first";
6294
+ if (/^(None|null|undefined|nil|NULL|Option::None)$/.test(e)) return "nothing at first";
4906
6295
  if (/^(True|true)$/.test(e)) return "yes at first";
4907
6296
  if (/^(False|false)$/.test(e)) return "no at first";
4908
6297
  if (/^-?\d+(\.\d+)?$/.test(e)) return `${e} at first`;
4909
6298
  if (/^[rbuf]*["'`].*["'`]$/.test(e)) return `"${stripQuotes2(e)}" at first`;
4910
- const en = e.match(/^[A-Z]\w*\.([A-Z][A-Z0-9_]+)$/);
4911
- if (en) return `${words3(en[1])} at first`;
6299
+ const en = e.match(/^[A-Z]\w*(?:\.|::)([A-Z][A-Z0-9_]+|[A-Z][a-z]\w*)$/);
6300
+ if (en) return `${words4(en[1])} at first`;
4912
6301
  return "worked out when it starts";
4913
6302
  }
4914
6303
  var KIND_WORDS = [
4915
- [/^(int|float|number|double|long|decimal|Decimal|bigint)$/i, "a number"],
4916
- [/^(str|string|String|text)$/i, "words"],
4917
- [/^(bool|boolean)$/i, "yes or no"],
4918
- [/^(date|datetime|Date|LocalDate|Instant)$/i, "a date"]
6304
+ [/^(int|float|number|double|long|short|decimal|Decimal|bigint|BigDecimal|BigInteger|Integer|Int|Long|Double|Float|Short|Byte|byte|uint|usize|isize|[iuf](?:8|16|32|64|128)|int(?:8|16|32|64)|uint(?:8|16|32|64)|float(?:32|64)|Number)$/, "a number"],
6305
+ [/^(str|string|String|text|&str|&'static str|char|Char|Character|rune)$/, "words"],
6306
+ [/^(bool|boolean|Boolean|Bool)$/, "yes or no"],
6307
+ [/^(date|datetime|Date|LocalDate|LocalDateTime|Instant|DateTime|DateTimeOffset|ZonedDateTime|time\.Time|NaiveDate|NaiveDateTime|DateTimeImmutable)$/, "a date"]
4919
6308
  ];
4920
6309
  function kindWords(type) {
4921
6310
  const t = String(type ?? "").trim();
4922
6311
  if (!t) return null;
4923
6312
  for (const [re, w] of KIND_WORDS) if (re.test(t)) return w;
4924
- const list = t.match(/^(?:list|List|Array|Sequence|Iterable)\[(.+)\]$|^Array<(.+)>$|^(.+)\[\]$/);
4925
- if (list) return `a list of ${(list[1] || list[2] || list[3]).trim()}s`;
4926
- const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$/);
4927
- if (opt) return `${kindWords(opt[1] || opt[2] || opt[3]) ?? `a ${opt[1] || opt[2] || opt[3]}`}, or nothing`;
6313
+ const list = t.match(/^(?:list|List|Array|Sequence|Iterable)\[(.+)\]$|^(?:Array|List|ArrayList|LinkedList|Vec|VecDeque|IList|IEnumerable|ICollection|IReadOnlyList|Collection|Set|HashSet|MutableList|MutableSet|Sequence|Iterable)<(.+)>$|^(.+)\[\]$|^\[\](.+)$/);
6314
+ if (list) {
6315
+ const inner = (list[1] || list[2] || list[3] || list[4]).trim();
6316
+ return `a list of ${kindWords(inner)?.replace(/^an? /, "") ?? inner}s`.replace(/wordss$/, "words").replace(/ys$/, "ies").replace(/(yes or no)s$/, "$1 answers");
6317
+ }
6318
+ const opt = t.match(/^Optional\[(.+)\]$|^(.+?)\s*\|\s*None$|^(.+?)\s*\|\s*(null|undefined)$|^(?:Option|Optional|Nullable)<(.+)>$|^(.+)\?$|^\*(\w+)$/);
6319
+ if (opt) {
6320
+ const inner = opt[1] || opt[2] || opt[3] || opt[5] || opt[6] || opt[7];
6321
+ return `${kindWords(inner) ?? `a ${inner}`}, or nothing`;
6322
+ }
6323
+ const map = t.match(/^(?:Map|HashMap|Dictionary|IDictionary|MutableMap|BTreeMap|dict|Dict|Record)[<\[]/) || /^map\[/.test(t);
6324
+ if (map) return "a lookup table";
4928
6325
  return /^[A-Z]/.test(t) ? `a ${t}` : null;
4929
6326
  }
6327
+ var thingsFor = makeThingReaders({ words: (x) => words4(x), kindWords: (x) => kindWords(x), startValue: (x, p) => startValue(x, p) });
4930
6328
  function pythonThings(src, file) {
4931
6329
  const lines = src.split("\n");
4932
6330
  const out = [];
@@ -4955,8 +6353,8 @@ function pythonThings(src, file) {
4955
6353
  const t = l.text.trim();
4956
6354
  if (/^(def|async def|class|@|"""|'''|#)/.test(t)) continue;
4957
6355
  let f;
4958
- if (isEnum && (f = t.match(/^([A-Z][A-Z0-9_]*)\s*=\s*(.+)$/))) thing.choices.push(/^[rbuf]*["']/.test(f[2]) ? stripQuotes2(f[2].trim()) : words3(f[1]));
4959
- else if (f = t.match(/^(\w+)\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/)) thing.knows.push({ name: f[1], label: words3(f[1]), kind: kindWords(f[2]), start: f[3] ? startValue(f[3]) : null, line: l.line });
6356
+ if (isEnum && (f = t.match(/^([A-Z][A-Z0-9_]*)\s*=\s*(.+)$/))) thing.choices.push(/^[rbuf]*["']/.test(f[2]) ? stripQuotes2(f[2].trim()) : words4(f[1]));
6357
+ else if (f = t.match(/^(\w+)\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/)) thing.knows.push({ name: f[1], label: words4(f[1]), kind: kindWords(f[2]), start: f[3] ? startValue(f[3]) : null, line: l.line });
4960
6358
  }
4961
6359
  const init = body.findIndex((l) => /^\s*def\s+__init__\s*\(/.test(l));
4962
6360
  if (init >= 0) {
@@ -4973,7 +6371,7 @@ function pythonThings(src, file) {
4973
6371
  const a = ln.trim().match(/^self\.(\w+)\s*(?::\s*([^=]+))?=\s*(.+)$/);
4974
6372
  if (a && !thing.knows.some((x) => x.name === a[1])) {
4975
6373
  const pType = /^\w+$/.test(a[3].trim()) ? (sig?.[1] || "").match(new RegExp(`\\b${a[3].trim()}\\s*:\\s*([\\w\\[\\]. |]+)`))?.[1] : void 0;
4976
- thing.knows.push({ name: a[1], label: words3(a[1]), kind: kindWords(a[2] || pType) ?? (/^\[/.test(a[3]) ? "a list" : null), start: startValue(a[3], params), line: i + 2 + k });
6374
+ thing.knows.push({ name: a[1], label: words4(a[1]), kind: kindWords(a[2] || pType) ?? (/^\[/.test(a[3]) ? "a list" : null), start: startValue(a[3], params), line: i + 2 + k });
4977
6375
  }
4978
6376
  }
4979
6377
  }
@@ -4981,7 +6379,7 @@ function pythonThings(src, file) {
4981
6379
  }
4982
6380
  return out;
4983
6381
  }
4984
- function braceEnd(src, open) {
6382
+ function braceEnd2(src, open) {
4985
6383
  let depth = 0;
4986
6384
  for (let i = open; i < src.length; i++) {
4987
6385
  const c = src[i];
@@ -5002,7 +6400,7 @@ function tsThings(src, file) {
5002
6400
  let m;
5003
6401
  while (m = re.exec(src)) {
5004
6402
  const open = m.index + m[0].length - 1;
5005
- const close = braceEnd(src, open);
6403
+ const close = braceEnd2(src, open);
5006
6404
  if (close < 0) continue;
5007
6405
  const body = src.slice(open + 1, close);
5008
6406
  const startLine = lineOf2(src, m.index + (m[0].startsWith("\n") ? 1 : 0));
@@ -5013,7 +6411,7 @@ function tsThings(src, file) {
5013
6411
  if (m[1] === "enum") {
5014
6412
  for (const part of body.split(",")) {
5015
6413
  const e = part.trim().match(/^(\w+)(?:\s*=\s*(.+))?$/s);
5016
- if (e) thing.choices.push(e[2] && /^["'`]/.test(e[2].trim()) ? stripQuotes2(e[2].trim()) : words3(e[1]));
6414
+ if (e) thing.choices.push(e[2] && /^["'`]/.test(e[2].trim()) ? stripQuotes2(e[2].trim()) : words4(e[1]));
5017
6415
  }
5018
6416
  } else {
5019
6417
  let depth = 0, own = "";
@@ -5027,7 +6425,7 @@ function tsThings(src, file) {
5027
6425
  const f = l.match(/^(?:(?:public|private|protected|readonly|static|declare)\s+)*(\w+)(\?)?\s*:\s*([^=]+?)(?:\s*=\s*(.+))?$/) || l.match(/^(?:(?:public|private|protected|readonly|static)\s+)*(\w+)()\s*=\s*(.+)$/);
5028
6426
  if (!f || /\(/.test(f[1])) continue;
5029
6427
  const hasType = f.length > 4 && f[3] && !l.match(/^(?:(?:public|private|protected|readonly|static)\s+)*\w+\s*=/);
5030
- thing.knows.push({ name: f[1], label: words3(f[1]), kind: hasType ? kindWords(f[3]) : null, start: hasType ? f[4] ? startValue(f[4]) : null : startValue(f[3]), line: null });
6428
+ thing.knows.push({ name: f[1], label: words4(f[1]), kind: hasType ? kindWords(f[3]) : null, start: hasType ? f[4] ? startValue(f[4]) : null : startValue(f[3]), line: null });
5031
6429
  }
5032
6430
  const ctor = body.match(/constructor\s*\(([^)]*)\)\s*\{/);
5033
6431
  if (ctor) {
@@ -5037,9 +6435,9 @@ function tsThings(src, file) {
5037
6435
  if (pm) params[pm[1]] = pm[2] ?? null;
5038
6436
  }
5039
6437
  const cOpen = body.indexOf("{", ctor.index + ctor[0].length - 1);
5040
- const cBody = body.slice(cOpen + 1, braceEnd(body, cOpen));
6438
+ const cBody = body.slice(cOpen + 1, braceEnd2(body, cOpen));
5041
6439
  for (const a of cBody.matchAll(/this\.(\w+)\s*=\s*([^;\n]+)/g)) {
5042
- if (!thing.knows.some((x) => x.name === a[1])) thing.knows.push({ name: a[1], label: words3(a[1]), kind: null, start: startValue(a[2], params), line: null });
6440
+ if (!thing.knows.some((x) => x.name === a[1])) thing.knows.push({ name: a[1], label: words4(a[1]), kind: null, start: startValue(a[2], params), line: null });
5043
6441
  else {
5044
6442
  const k = thing.knows.find((x) => x.name === a[1]);
5045
6443
  if (!k.start) k.start = startValue(a[2], params);
@@ -5055,6 +6453,7 @@ function stepDoes(step) {
5055
6453
  const s = step.says || "", c = step.callee || "";
5056
6454
  if (step.restates || step.kind === "other") return "code";
5057
6455
  if (step.kind === "fail") return "stop";
6456
+ if (step.redirect) return "redirect";
5058
6457
  if (step.kind === "loop") return "repeat";
5059
6458
  if (step.kind === "return") return "answer";
5060
6459
  if (step.kind === "check") return "check";
@@ -5066,8 +6465,8 @@ function stepDoes(step) {
5066
6465
  if (step.kind === "set") return "calculate";
5067
6466
  return "do";
5068
6467
  }
5069
- var possessive = (text) => String(text).replace(/\b([a-z_][\w]*)\.([a-z_][\w]*)\b(?!\s*\()/gi, (m, a, b) => /^(self|this)$/.test(a) ? `the ${words3(b)}` : `the ${words3(a)}'s ${words3(b)}`).replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words3(m));
5070
- var answerWords = (r) => /^true$/i.test(r) ? "Yes" : /^false$/i.test(r) ? "No" : cap(words3(r));
6468
+ var possessive = (text) => String(text).replace(/\b([a-z_][\w]*)\.([a-z_][\w]*)\b(?!\s*\()/gi, (m, a, b) => /^(self|this)$/.test(a) ? `the ${words4(b)}` : `the ${words4(a)}'s ${words4(b)}`).replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words4(m));
6469
+ var answerWords = (r) => /^true$/i.test(r) ? "Yes" : /^false$/i.test(r) ? "No" : cap(words4(r));
5071
6470
  function askAsQuestion(step, ruleLabel) {
5072
6471
  let c = String(step.says).replace(/^If /, "").replace(/ \(\d+ steps? inside\)$/, "").trim();
5073
6472
  let flip = false;
@@ -5213,7 +6612,7 @@ function flowOf(steps, { start = "Start", memberIndex = /* @__PURE__ */ new Map(
5213
6612
  }
5214
6613
  var idOf = (...parts) => parts.join("#").replace(/\s+/g, "");
5215
6614
  function youGiveOf(item) {
5216
- const given = (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing).map((p) => words3(p.name));
6615
+ const given = (item.inputs || []).filter((p) => !/^(self|this|cls)$/.test(p.name) && !p.plumbing).map((p) => words4(p.name));
5217
6616
  const codes = [];
5218
6617
  const walk = (steps) => {
5219
6618
  for (const s of steps || []) {
@@ -5228,7 +6627,7 @@ function youGiveOf(item) {
5228
6627
  if (!m) continue;
5229
6628
  for (const part of m[1].split(",")) {
5230
6629
  const name = part.split(/[:=]/)[0].replace(/^\.\.\./, "").trim();
5231
- if (/^[A-Za-z_$][\w$]*$/.test(name) && !given.includes(words3(name))) given.push(words3(name));
6630
+ if (/^[A-Za-z_$][\w$]*$/.test(name) && !given.includes(words4(name))) given.push(words4(name));
5232
6631
  }
5233
6632
  }
5234
6633
  return given;
@@ -5240,14 +6639,14 @@ function thunderModel(files, { name = "app" } = {}) {
5240
6639
  if (!language || !f.source) continue;
5241
6640
  let reading;
5242
6641
  try {
5243
- reading = readCode(f.source, { language, file: f.path });
6642
+ reading = readingOf(f, language);
5244
6643
  } catch (e) {
5245
6644
  unknowns.push({ file: f.path, line: 1, why: `Could not read this file: ${e.message}` });
5246
6645
  continue;
5247
6646
  }
5248
6647
  let fileThings = [];
5249
6648
  try {
5250
- fileThings = language === "python" ? pythonThings(f.source, f.path) : THING_LANGUAGES.includes(language) ? tsThings(f.source, f.path) : [];
6649
+ fileThings = language === "python" ? pythonThings(f.source, f.path) : language === "typescript" || language === "javascript" ? tsThings(f.source, f.path) : language === "sql" ? sqlThings(f.source, f.path) : thingsFor(language, f.source, f.path);
5251
6650
  } catch (e) {
5252
6651
  unknowns.push({ file: f.path, line: 1, why: `Classes in this file could not be drawn as Things: ${e.message}` });
5253
6652
  }
@@ -5256,17 +6655,18 @@ function thunderModel(files, { name = "app" } = {}) {
5256
6655
  }
5257
6656
  for (const t of fileThings) {
5258
6657
  t.id = idOf(f.path, t.name);
5259
- t.label = cap(words3(t.name));
6658
+ t.label = cap(words4(t.name));
5260
6659
  t.can = [];
5261
6660
  things.push(t);
5262
6661
  }
5263
6662
  const moduleDoc = language === "python" ? (f.source.match(/^\s*(?:#.*\n|\s*\n)*[rRuU]?("""|''')([\s\S]*?)\1/)?.[2] ?? "").trim().split(/\n\s*\n/)[0].replace(/\s+/g, " ") : "";
5264
6663
  fileInfo.push({ path: f.path, language, ...moduleDoc ? { purpose: moduleDoc } : {} });
5265
6664
  const fns = reading.items.filter((i) => i.kind === "function" || i.kind === "decision");
5266
- const fileMembers = fns.map((item) => {
5267
- const owner = fileThings.filter((t) => item.line > t.lines[0] && item.line <= t.lines[1]).sort((a, b) => b.lines[0] - a.lines[0])[0];
6665
+ const declaredThing = (item) => fileThings.some((t) => t.name === item.name && t.lines[0] === item.line);
6666
+ const fileMembers = fns.filter((item) => !declaredThing(item)).map((item) => {
6667
+ const owner = fileThings.filter((t) => item.line > t.lines[0] && item.line <= t.lines[1] || (t.memberRanges || []).some(([a, b]) => item.line >= a && item.line <= b)).sort((a, b) => b.lines[0] - a.lines[0])[0];
5268
6668
  const v = visualFor(item);
5269
- const setup = /^(__init__|constructor|init|New)$/.test(item.name) && owner;
6669
+ const setup = (/^(__init__|constructor|init|New|__construct|initialize|new)$/.test(item.name) || owner && item.name === owner.name) && owner;
5270
6670
  const kind = setup ? "setup" : v.element === "action" ? "action" : v.element === "decision" ? "rule" : v.element === "not-read" ? "not-read" : "steps";
5271
6671
  const bodyEnd = item.anchor?.bodyLines?.[1] ?? Math.max(item.line, ...(item.rules || []).map((r) => r.line || 0), item.otherwise?.line || 0);
5272
6672
  let rule = null;
@@ -5281,7 +6681,7 @@ function thunderModel(files, { name = "app" } = {}) {
5281
6681
  id: idOf(f.path, owner?.name ?? "", item.name, item.line),
5282
6682
  kind,
5283
6683
  name: item.name,
5284
- label: setup ? `A new ${owner.label} starts with` : cap(words3(item.name.replace(/^__|__$/g, ""))),
6684
+ label: setup ? `A new ${owner.label} starts with` : cap(words4(item.name.replace(/^__|__$/g, ""))),
5285
6685
  ...owner ? { owner: owner.id } : {},
5286
6686
  file: f.path,
5287
6687
  language,
@@ -5311,6 +6711,14 @@ function thunderModel(files, { name = "app" } = {}) {
5311
6711
  members.push(m);
5312
6712
  }
5313
6713
  }
6714
+ for (const t of things) delete t.memberRanges;
6715
+ const owners = new Set(members.map((x) => x.owner).filter(Boolean));
6716
+ for (let i = things.length - 1; i >= 0; i--) {
6717
+ const t = things[i];
6718
+ if (t.kind !== "thing" || t.knows.length || owners.has(t.id)) continue;
6719
+ if (/(Exception|Error)$/.test(t.name)) things.splice(i, 1);
6720
+ else t.kind = "record";
6721
+ }
5314
6722
  return { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns };
5315
6723
  }
5316
6724
  function flowLines(flow, depth = 1) {
@@ -5397,7 +6805,7 @@ function readAll(files) {
5397
6805
  if (!language || !f.source) continue;
5398
6806
  let reading;
5399
6807
  try {
5400
- reading = readCode(f.source, { language, file: f.path });
6808
+ reading = readingOf(f, language);
5401
6809
  } catch (e) {
5402
6810
  unreadable.push({ path: f.path, reason: e.message });
5403
6811
  continue;