@skillstech/thunderlang 0.5.11 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +437 -0
  2. package/dist/core.cjs +30431 -7604
  3. package/dist/index.cjs +28577 -5331
  4. package/dist/learn.cjs +22676 -3870
  5. package/package.json +12 -3
  6. package/src/bicep.mjs +167 -0
  7. package/src/cli.mjs +169 -3
  8. package/src/commands.mjs +464 -0
  9. package/src/core.d.ts +12 -4
  10. package/src/core.mjs +12 -4
  11. package/src/emit.mjs +1 -1
  12. package/src/executed.d.mts +53 -0
  13. package/src/executed.mjs +465 -0
  14. package/src/faithful.mjs +137 -0
  15. package/src/file-formats.mjs +35 -0
  16. package/src/hcl.mjs +94 -0
  17. package/src/index.d.ts +7 -1
  18. package/src/index.mjs +6 -1
  19. package/src/infra-bicep.mjs +312 -0
  20. package/src/infra-cloud.mjs +348 -0
  21. package/src/infra-compose.mjs +315 -0
  22. package/src/infra-containers.mjs +100 -0
  23. package/src/infra-docker.mjs +267 -0
  24. package/src/infra-expr.mjs +509 -0
  25. package/src/infra-gha.mjs +350 -0
  26. package/src/infra-k8s.mjs +657 -0
  27. package/src/infra-terraform.mjs +499 -0
  28. package/src/infra-words.mjs +811 -0
  29. package/src/libraries.mjs +202 -0
  30. package/src/lift.mjs +48 -6
  31. package/src/meaning.d.mts +89 -0
  32. package/src/meaning.mjs +2544 -0
  33. package/src/model.d.mts +59 -12
  34. package/src/model.mjs +462 -80
  35. package/src/powershell.mjs +1361 -0
  36. package/src/read-repo-fs.mjs +29 -7
  37. package/src/read-repo.d.mts +5 -1
  38. package/src/read-repo.mjs +33 -7
  39. package/src/read.d.mts +21 -1
  40. package/src/read.mjs +1015 -42
  41. package/src/review.d.mts +35 -0
  42. package/src/review.mjs +671 -0
  43. package/src/rlang.mjs +1084 -0
  44. package/src/round-trip.d.mts +12 -0
  45. package/src/round-trip.mjs +174 -0
  46. package/src/runners/thunder-generate.mjs +56 -0
  47. package/src/runners/thunder-trace.cjs +284 -0
  48. package/src/runners/thunder_trace.py +599 -0
  49. package/src/running.d.mts +104 -0
  50. package/src/running.mjs +787 -0
  51. package/src/same.d.mts +1 -0
  52. package/src/same.mjs +24 -3
  53. package/src/shell.mjs +1212 -0
  54. package/src/sql.mjs +3 -2
  55. package/src/steps.d.mts +6 -1
  56. package/src/steps.mjs +1448 -86
  57. package/src/system.d.mts +12 -0
  58. package/src/system.mjs +845 -0
  59. package/src/things-langs.mjs +275 -0
  60. package/src/thunderize.mjs +3 -3
  61. package/src/visual.d.mts +5 -5
  62. package/src/visual.mjs +24 -3
  63. package/src/write-steps.d.mts +64 -0
  64. package/src/write-steps.mjs +1608 -0
  65. package/src/write.mjs +2 -1
  66. package/src/yaml.mjs +403 -0
@@ -0,0 +1,2544 @@
1
+ // The meaning model underneath Thunder's words (thunder-expr-v1).
2
+ //
3
+ // Thunder's words are short on purpose ("Calls save"). So that nothing in the code is lost, every step also carries
4
+ // `expr`: a small, language-neutral tree of exactly what the statement says — calls with their callee path and every
5
+ // argument, assignments with their full target (index, keys) and value, comparisons and logic with every operand and
6
+ // negation, literals with their exact value, object and array literals with every key and item, lambdas (their body
7
+ // is the step's own children), returns and throws with their value, error type and message.
8
+ //
9
+ // The tree is read from the code, never guessed: when a statement is not fully understood, its expr is
10
+ // `{ kind: 'code', text }` (the code itself). Every function here is linear in the statement's length.
11
+ //
12
+ // Pieces:
13
+ // parseStatement(text, language) -> statement tree (what a step's `expr` holds)
14
+ // parseExpr(text, language) -> expression tree, or null when the text is not one whole expression
15
+ // renderStatement(tree, language) -> code again (TypeScript/JavaScript, Python, Go), for the round trip
16
+ // sayFull(tree) -> every detail in plain, neutral form ("save(order, { validate: false })")
17
+ // detailOf(step) -> what the short words leave out, as a sentence tail ("with: order, …")
18
+ // exprCounts(tree) -> negations, and/or, and comparisons (the faithfulness gate counts these)
19
+ // sameExpr(a, b) -> structural equality after normalizing spelling (quotes, spacing)
20
+
21
+ export const EXPR_SCHEMA = 'thunder-expr-v1';
22
+
23
+ // ── Languages ────────────────────────────────────────────────────────────────────────────────────────────────
24
+
25
+ const FAMILY = {
26
+ typescript: 'c', javascript: 'c', java: 'c', csharp: 'c', php: 'c', kotlin: 'c', scala: 'c', swift: 'c', dart: 'c', c: 'c', cpp: 'c',
27
+ python: 'py', ruby: 'rb', go: 'go', rust: 'rs',
28
+ };
29
+ const famOf = (lang) => FAMILY[lang] || 'c';
30
+ const isJs = (lang) => lang === 'typescript' || lang === 'javascript' || !lang;
31
+
32
+ // Thrown when the reader gives up on a statement (a plain object: no stack trace to build, so giving up is cheap).
33
+ class Fail { constructor(why) { this.message = why; } }
34
+ const fail = (why) => { throw new Fail(why); };
35
+
36
+ // ── Lexer: lazy, so a block statement is scanned only as far as its header ───────────────────────────────────
37
+
38
+ const OPS_ALL = ['>>>=', '...', '===', '!==', '**=', '&.', '<<=', '>>=', '>>>', '&&=', '||=', '??=', '//=', '..=', '&^=', '?.', '??', '?:', '=>', '->', '::', ':=', '==', '!=', '<>', '<=', '>=', '&&', '||', '++', '--', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '**', '//', '<<', '>>', '&^', '<-', '..', '!!', '.=',
39
+ '+', '-', '*', '/', '%', '=', '<', '>', '!', '&', '|', '^', '~', '?', ':', '.', ',', ';', '(', ')', '[', ']', '{', '}', '@', '#', '\\'];
40
+ const OPS_BY_FAMILY = {};
41
+ for (const f of ['c', 'py', 'rb', 'go', 'rs', 'kt', 'php']) {
42
+ OPS_BY_FAMILY[f] = OPS_ALL.filter((o) => {
43
+ if (o === '//' || o === '//=') return f === 'py';
44
+ if (o === '::') return f !== 'py' && f !== 'go';
45
+ if (o === '?:') return f === 'kt';
46
+ if (o === '!!') return f === 'kt';
47
+ if (o === '..' || o === '..=') return f === 'kt' || f === 'rs' || f === 'rb';
48
+ if (o === '&^' || o === '&^=' || o === '<-') return f === 'go';
49
+ if (o === ':=') return f === 'go' || f === 'py';
50
+ if (o === '.=') return f === 'php';
51
+ if (o === '<>') return f === 'php';
52
+ if (o === '>>>' || o === '>>>=' || o === '!==') return f === 'c' || f === 'kt' || f === 'php';
53
+ if (o === '===') return f === 'c' || f === 'kt' || f === 'php' || f === 'rb';
54
+ if (o === '**' || o === '**=') return f !== 'rs' && f !== 'go';
55
+ if (o === '&.') return f === 'rb';
56
+ if (o === '#') return f === 'rs' || f === 'c';
57
+ return true;
58
+ });
59
+ }
60
+ // Operators by their first character, longest first, so the lexer tries only the few that can match.
61
+ const OPS_BY_CHAR = {};
62
+ for (const [f, list] of Object.entries(OPS_BY_FAMILY)) {
63
+ const m = new Map();
64
+ for (const o of list) { if (!m.has(o[0])) m.set(o[0], []); m.get(o[0]).push(o); }
65
+ for (const l of m.values()) l.sort((a, b) => b.length - a.length);
66
+ OPS_BY_CHAR[f] = m;
67
+ }
68
+ const opFamily = (lang) => (lang === 'kotlin' ? 'kt' : lang === 'php' ? 'php' : famOf(lang));
69
+
70
+ const ID_START = /[A-Za-z_$\u00C0-\uFFFF]/;
71
+ const ID_RE = /[A-Za-z_$\u00C0-\uFFFF][\w$\u00C0-\uFFFF]*/y;
72
+ const NUM_RE = /(?:0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*(?:\.(?!\.)\d[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?)(?:[a-zA-Z]\w*)?/y;
73
+ const OPERAND_END = new Set(['id', 'num', 'str', 'tpl', 'regex']);
74
+ const REGEX_AFTER_KW = /^(?:return|typeof|case|in|of|delete|void|throw|new|instanceof|yield|await|else|do)$/;
75
+
76
+ function makeLexer(src, lang) {
77
+ const fam = famOf(lang);
78
+ const ops = OPS_BY_CHAR[opFamily(lang)];
79
+ const hashComment = fam === 'py' || fam === 'rb' || lang === 'php';
80
+ const toks = [];
81
+ let pos = 0;
82
+ const n = src.length;
83
+
84
+ function skipSpace() {
85
+ let nl = false, sp = false;
86
+ while (pos < n) {
87
+ const c = src.charCodeAt(pos);
88
+ if (c === 10) { nl = true; sp = true; pos++; continue; }
89
+ if (c === 32 || c === 9 || c === 13) { sp = true; pos++; continue; }
90
+ if (c === 92 && (fam === 'py' || fam === 'rb') && /^\\\r?\n/.test(src.slice(pos, pos + 3))) { pos += src[pos + 1] === '\r' ? 3 : 2; sp = true; continue; }
91
+ if (c === 47 && src.charCodeAt(pos + 1) === 47 && fam !== 'py') { while (pos < n && src.charCodeAt(pos) !== 10) pos++; sp = true; continue; }
92
+ if (c === 47 && src.charCodeAt(pos + 1) === 42) { const e = src.indexOf('*/', pos + 2); pos = e < 0 ? n : e + 2; sp = true; continue; }
93
+ if (c === 35 && hashComment && !(fam === 'rb' && src[pos + 1] === '{')) { while (pos < n && src.charCodeAt(pos) !== 10) pos++; sp = true; continue; }
94
+ break;
95
+ }
96
+ return { nl, sp };
97
+ }
98
+
99
+ /** End index (exclusive) of a quoted string starting at `i` with quote q. */
100
+ function stringEnd(i, q, { raw = false, triple = false, verbatim = false } = {}) {
101
+ if (triple) { const e = src.indexOf(q + q + q, i + 3); if (e < 0) fail('unterminated string'); let k = e + 3; while (src[k] === q) k++; return k; }
102
+ for (let j = i + 1; j < n; j++) {
103
+ const ch = src[j];
104
+ if (ch === '\\' && (!raw || fam === 'py') && !verbatim) { j++; continue; }
105
+ if (verbatim && ch === q && src[j + 1] === q) { j++; continue; }
106
+ if (ch === q) return j + 1;
107
+ if (ch === '\n' && q !== '`' && !verbatim && !triple) fail('unterminated string');
108
+ }
109
+ return fail('unterminated string');
110
+ }
111
+ /** End of a JS template literal starting at i (handles `${ … }` with nested strings and templates). */
112
+ function templateEnd(i) {
113
+ for (let j = i + 1; j < n; j++) {
114
+ const ch = src[j];
115
+ if (ch === '\\') { j++; continue; }
116
+ if (ch === '`') return j + 1;
117
+ if (ch === '$' && src[j + 1] === '{') { const e = blockEnd(src, j + 1, lang); if (e < 0) fail('unterminated template'); j = e; }
118
+ }
119
+ return fail('unterminated template');
120
+ }
121
+
122
+ function lexOne() {
123
+ const { nl, sp } = skipSpace();
124
+ if (pos >= n) return { t: 'eof', v: '', s: n, e: n, nl, sp };
125
+ const s = pos;
126
+ const c = src[pos];
127
+ const prev = toks[toks.length - 1];
128
+ // Strings (with Python / C# / Rust prefixes).
129
+ let m;
130
+ if (fam === 'py' && /[rRbBuUfF]/.test(c) && (m = /^([rRbBuUfF]{1,2})(["'])/.exec(src.slice(pos, pos + 3)))) {
131
+ const prefix = m[1].toLowerCase(), q = m[2], at = pos + prefix.length;
132
+ const triple = src.slice(at, at + 3) === q + q + q;
133
+ const e = stringEnd(at, q, { raw: prefix.includes('r'), triple });
134
+ pos = e;
135
+ return { t: 'str', v: src.slice(s, e), q, prefix, triple, s, e, nl, sp };
136
+ }
137
+ if (lang === 'csharp' && (c === '$' || c === '@') && (src[pos + 1] === '"' || ((src[pos + 1] === '@' || src[pos + 1] === '$') && src[pos + 2] === '"'))) {
138
+ const at = src.indexOf('"', pos);
139
+ const prefix = src.slice(pos, at);
140
+ let e;
141
+ if (prefix.includes('$')) {
142
+ // $"…{(a ? "x" : "y")}…": a value inside braces may hold strings of its own.
143
+ let j = at + 1;
144
+ for (; j < n; j++) {
145
+ const ch = src[j];
146
+ if (ch === '\\' && !prefix.includes('@')) { j++; continue; }
147
+ if (ch === '{' && src[j + 1] === '{') { j++; continue; }
148
+ if (ch === '{') { const close = blockEnd(src, j, 'csharp'); if (close < 0) fail('unterminated string'); j = close; continue; }
149
+ if (ch === '"') { if (prefix.includes('@') && src[j + 1] === '"') { j++; continue; } break; }
150
+ }
151
+ if (j >= n) fail('unterminated string');
152
+ e = j + 1;
153
+ } else e = stringEnd(at, '"', { verbatim: prefix.includes('@') });
154
+ pos = e;
155
+ return { t: 'str', v: src.slice(s, e), q: '"', prefix, s, e, nl, sp };
156
+ }
157
+ if (fam === 'rs' && (c === 'r' || c === 'b') && /^(?:b?r#*"|b")/.test(src.slice(pos, pos + 4))) {
158
+ const mm = /^(b?r?)(#*)"/.exec(src.slice(pos, pos + 12));
159
+ const hashes = mm[2];
160
+ const at = pos + mm[1].length + hashes.length;
161
+ let e;
162
+ if (mm[1].includes('r')) { const close = src.indexOf(`"${hashes}`, at + 1); if (close < 0) fail('unterminated string'); e = close + 1 + hashes.length; }
163
+ else e = stringEnd(at, '"');
164
+ pos = e;
165
+ return { t: 'str', v: src.slice(s, e), q: '"', prefix: mm[1] + hashes, s, e, nl, sp };
166
+ }
167
+ if (c === '"' || c === "'") {
168
+ if (c === "'" && (fam === 'go' || fam === 'rs' || lang === 'java' || lang === 'csharp' || lang === 'kotlin' || lang === 'scala')) {
169
+ const e = stringEnd(pos, "'");
170
+ pos = e;
171
+ return { t: 'str', v: src.slice(s, e), q: "'", char: true, s, e, nl, sp };
172
+ }
173
+ const triple = (fam === 'py' || lang === 'kotlin') && src.slice(pos, pos + 3) === c + c + c;
174
+ const e = stringEnd(pos, c, { triple });
175
+ pos = e;
176
+ return { t: 'str', v: src.slice(s, e), q: c, triple, s, e, nl, sp };
177
+ }
178
+ if (c === '`') {
179
+ if (isJs(lang)) { const e = templateEnd(pos); pos = e; return { t: 'tpl', v: src.slice(s, e), s, e, nl, sp }; }
180
+ if (fam === 'go') { const e = src.indexOf('`', pos + 1); if (e < 0) fail('unterminated string'); pos = e + 1; return { t: 'str', v: src.slice(s, pos), q: '`', s, e: pos, nl, sp }; }
181
+ return fail('backtick');
182
+ }
183
+ // Ruby symbols :name (not :: and not a ternary's ": x").
184
+ if (fam === 'rb' && c === ':' && src[pos + 1] !== ':' && ID_START.test(src[pos + 1] || '') && !(prev && OPERAND_END.has(prev.t) && !sp)) {
185
+ ID_RE.lastIndex = pos + 1; const mm = ID_RE.exec(src); let e = pos + 1 + mm[0].length; if (/[?!]/.test(src[e] || '')) e++;
186
+ pos = e; return { t: 'str', v: src.slice(s, e), symbol: true, s, e, nl, sp };
187
+ }
188
+ // Numbers.
189
+ if ((c >= '0' && c <= '9') || (c === '.' && /[0-9]/.test(src[pos + 1] || '') && !(prev && OPERAND_END.has(prev.t)))) {
190
+ NUM_RE.lastIndex = pos; const mm = NUM_RE.exec(src);
191
+ pos += mm[0].length;
192
+ return { t: 'num', v: mm[0], s, e: pos, nl, sp };
193
+ }
194
+ // C# names that are keywords, written with @: @interface, @event.
195
+ if (c === '@' && lang === 'csharp' && ID_START.test(src[pos + 1] || '')) { ID_RE.lastIndex = pos + 1; const mm = ID_RE.exec(src); pos += 1 + mm[0].length; return { t: 'id', v: src.slice(s, pos), s, e: pos, nl, sp }; }
196
+ // JavaScript private names: this.#run, #options in x.
197
+ if (c === '#' && isJs(lang) && ID_START.test(src[pos + 1] || '')) { ID_RE.lastIndex = pos + 1; const mm = ID_RE.exec(src); pos += 1 + mm[0].length; return { t: 'id', v: src.slice(s, pos), s, e: pos, nl, sp }; }
198
+ // Identifiers (Ruby @ivar / $global; Rust/Ruby name! and Ruby name?).
199
+ if (lang === 'php' && c === '\\' && ID_START.test(src[pos + 1] || '')) {
200
+ let e = pos + 1;
201
+ for (;;) { ID_RE.lastIndex = e; const mm = ID_RE.exec(src); e += mm[0].length; if (src[e] === '\\' && ID_START.test(src[e + 1] || '')) { e++; continue; } break; }
202
+ pos = e;
203
+ return { t: 'id', v: src.slice(s, e), s, e, nl, sp };
204
+ }
205
+ if (ID_START.test(c) || (fam === 'rb' && c === '@' && ID_START.test(src[pos + 1] === '@' ? src[pos + 2] || '' : src[pos + 1] || ''))) {
206
+ let at = pos;
207
+ if (c === '@') at += src[pos + 1] === '@' ? 2 : 1;
208
+ ID_RE.lastIndex = at; const mm = ID_RE.exec(src);
209
+ let e = at + mm[0].length;
210
+ while (lang === 'php' && src[e] === '\\' && ID_START.test(src[e + 1] || '')) { ID_RE.lastIndex = e + 1; e += 1 + ID_RE.exec(src)[0].length; }
211
+ if (fam === 'rs' && src[e] === '!' && /[(\[{]/.test(src[e + 1] || '')) e++;
212
+ else if (fam === 'rb' && (src[e] === '?' || src[e] === '!') && src[e + 1] !== '=' && src[e + 1] !== ':' && !(src[e] === '!' && src[e + 1] === '~')) {
213
+ // `empty?` / `save!` — but not a ternary `a ? b : c` (which has a space before ?).
214
+ e++;
215
+ }
216
+ pos = e;
217
+ return { t: 'id', v: src.slice(s, e), s, e, nl, sp };
218
+ }
219
+ // Regular expressions (JavaScript): where an operand is expected.
220
+ if (c === '/' && isJs(lang) && (!prev || (!OPERAND_END.has(prev.t) && !(prev.t === 'op' && /^[)\]}]$/.test(prev.v))) || (prev.t === 'id' && REGEX_AFTER_KW.test(prev.v)))) {
221
+ let j = pos + 1, cls = false;
222
+ for (; j < n; j++) {
223
+ const ch = src[j];
224
+ if (ch === '\\') { j++; continue; }
225
+ if (ch === '\n') fail('unterminated regex');
226
+ if (cls) { if (ch === ']') cls = false; continue; }
227
+ if (ch === '[') cls = true; else if (ch === '/') break;
228
+ }
229
+ if (j >= n) fail('unterminated regex');
230
+ j++;
231
+ while (j < n && /[a-z]/.test(src[j])) j++;
232
+ pos = j;
233
+ return { t: 'regex', v: src.slice(s, j), s, e: j, nl, sp };
234
+ }
235
+ for (const o of ops.get(c) || []) {
236
+ if (src.startsWith(o, pos)) {
237
+ // `?.5` is a ternary on a number, not optional chaining.
238
+ if (o === '?.' && /[0-9]/.test(src[pos + 2] || '')) continue;
239
+ pos += o.length;
240
+ return { t: 'op', v: o, s, e: pos, nl, sp };
241
+ }
242
+ }
243
+ return fail(`unexpected character ${c}`);
244
+ }
245
+
246
+ return {
247
+ src, lang, fam,
248
+ at(k) { while (toks.length <= k) { const last = toks[toks.length - 1]; if (last && last.t === 'eof') return last; toks.push(lexOne()); } return toks[k]; },
249
+ /** Skip a brace block whose `{` is token k: everything up to its matching `}` becomes one 'block' token. */
250
+ skipBlock(k) {
251
+ const open = this.at(k);
252
+ const close = blockEnd(src, open.s, lang);
253
+ toks.length = k;
254
+ pos = close < 0 ? n : close + 1;
255
+ toks.push({ t: 'block', v: '{…}', s: open.s, e: pos, nl: open.nl, sp: open.sp, open: close < 0 });
256
+ },
257
+ rest(k) { return src.slice(this.at(k).s); },
258
+ /** Go back to token k and carry on lexing from source offset p (after something read character by character). */
259
+ seek(k, p) { toks.length = k; pos = p; },
260
+ };
261
+ }
262
+
263
+ /** Index of the `}` that closes the `{` at `open`, skipping strings, templates, and comments; -1 when none. */
264
+ export function blockEnd(src, open, lang) {
265
+ const fam = famOf(lang);
266
+ const hash = fam === 'py' || fam === 'rb' || lang === 'php';
267
+ let depth = 0;
268
+ for (let i = open; i < src.length; i++) {
269
+ const c = src[i];
270
+ if (c === '"' || c === "'" || (c === '`' && (isJs(lang) || fam === 'go'))) {
271
+ if (c === "'" && fam === 'rs' && !/^'(?:\\.|[^\\'])'/.test(src.slice(i, i + 4)) && !/^'\\u\{/.test(src.slice(i, i + 4))) continue; // a lifetime
272
+ for (i++; i < src.length && src[i] !== c; i++) {
273
+ if (src[i] === '\\' && !(c === '`' && fam === 'go')) i++;
274
+ else if (c === '`' && src[i] === '$' && src[i + 1] === '{') { const e = blockEnd(src, i + 1, lang); if (e < 0) return -1; i = e; }
275
+ }
276
+ continue;
277
+ }
278
+ if (c === '/' && src[i + 1] === '/' && fam !== 'py') { while (i < src.length && src[i] !== '\n') i++; continue; }
279
+ if (c === '/' && src[i + 1] === '*') { const e = src.indexOf('*/', i + 2); if (e < 0) return -1; i = e + 1; continue; }
280
+ if (c === '#' && hash && !(fam === 'rb' && src[i + 1] === '{')) { while (i < src.length && src[i] !== '\n') i++; continue; }
281
+ if (c === '{') depth++;
282
+ else if (c === '}' && --depth === 0) return i;
283
+ }
284
+ return -1;
285
+ }
286
+
287
+ // ── Literals ─────────────────────────────────────────────────────────────────────────────────────────────────
288
+
289
+ const ESC = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', 0: '\0', a: '\x07', e: '\x1b', '\\': '\\', "'": "'", '"': '"', '`': '`', $: '$', '\n': '' };
290
+ function unescape(body) {
291
+ if (!body.includes('\\')) return body;
292
+ return body.replace(/\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|U[0-9a-fA-F]{8}|[0-7]{1,3}|[^])/g, (m, e) => {
293
+ if (/^u\{/.test(e)) return String.fromCodePoint(parseInt(e.slice(2, -1), 16));
294
+ if (/^[uUx]/.test(e) && e.length > 1) return String.fromCodePoint(parseInt(e.slice(1), 16));
295
+ if (/^[0-7]+$/.test(e) && e !== '0') return String.fromCharCode(parseInt(e, 8));
296
+ return ESC[e] ?? `\\${e}`;
297
+ });
298
+ }
299
+ function stringValue(tok) {
300
+ const raw = tok.v;
301
+ if (tok.symbol) return { kind: 'literal', type: 'symbol', value: raw.slice(1), raw };
302
+ const prefix = tok.prefix || '';
303
+ const q = tok.q;
304
+ let body;
305
+ if (tok.triple) body = raw.slice(prefix.length + 3, raw.length - 3);
306
+ else if (/r#/.test(prefix)) { const h = prefix.replace(/^b?r/, ''); body = raw.slice(prefix.length + 1, raw.length - 1 - h.length); }
307
+ else body = raw.slice(prefix.length + 1, -1);
308
+ const rawStr = /r/i.test(prefix) || q === '`';
309
+ const value = rawStr ? body : prefix.includes('@') ? body.replace(/""/g, '"') : unescape(body);
310
+ const node = { kind: 'literal', type: tok.char ? 'char' : 'text', value, raw };
311
+ if (/b/i.test(prefix)) node.bytes = true;
312
+ // Interpolated text whose parts are not read one by one (C# $"…", Kotlin "$x", Ruby "#{x}", PHP "…$x"): the exact
313
+ // text is kept; the names inside stay in `raw`.
314
+ if (prefix.includes('$') || (q === '"' && ((/\$\{|\$[A-Za-z_]/.test(body) && /^(kotlin|scala|php|dart)$/.test(globalLang)) || (/#\{/.test(body) && globalLang === 'ruby')))) node.interpolated = true;
315
+ return node;
316
+ }
317
+ let globalLang = '';
318
+ function numberValue(raw) {
319
+ const t = raw.replace(/_/g, '');
320
+ let v = null;
321
+ if (/^0[xX][0-9a-fA-F]+/.test(t)) v = parseInt(t.slice(2).match(/^[0-9a-fA-F]+/)[0], 16);
322
+ else if (/^0[bB][01]+/.test(t)) v = parseInt(t.slice(2).match(/^[01]+/)[0], 2);
323
+ else if (/^0[oO][0-7]+/.test(t)) v = parseInt(t.slice(2).match(/^[0-7]+/)[0], 8);
324
+ else { const m = t.match(/^(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?/); if (m) v = Number(m[0]); }
325
+ return { kind: 'literal', type: 'number', value: Number.isFinite(v) ? v : null, raw };
326
+ }
327
+ const NULLS = { null: 'null', nil: 'nil', None: 'None', undefined: 'undefined', NULL: 'NULL' };
328
+ const BOOLS = { true: true, false: false, True: true, False: false };
329
+
330
+ // ── Parser ───────────────────────────────────────────────────────────────────────────────────────────────────
331
+
332
+ // Binding powers for infix operators, per family. Higher binds tighter.
333
+ const BP = {
334
+ c: { '??': 4, '||': 5, '&&': 6, '|': 7, '^': 8, '&': 9, '==': 10, '!=': 10, '===': 10, '!==': 10, '<>': 10, '<': 11, '>': 11, '<=': 11, '>=': 11, instanceof: 11, in: 11, is: 11, as: 11, satisfies: 11, '<<': 12, '>>': 12, '>>>': 12, '+': 13, '-': 13, '*': 14, '/': 14, '%': 14, '**': 15, '.': 13 },
335
+ kt: { '||': 5, '&&': 6, '==': 10, '!=': 10, '===': 10, '!==': 10, '<': 11, '>': 11, '<=': 11, '>=': 11, in: 11.5, '!in': 11.5, is: 11.5, '!is': 11.5, '?:': 12, '..': 13.5, '..<': 13.5, '+': 14, '-': 14, '*': 15, '/': 15, '%': 15, as: 16, 'as?': 16 },
336
+ py: { or: 5, and: 6, '==': 8, '!=': 8, '<': 8, '>': 8, '<=': 8, '>=': 8, in: 8, 'not in': 8, is: 8, 'is not': 8, '|': 9, '^': 10, '&': 11, '<<': 12, '>>': 12, '+': 13, '-': 13, '*': 14, '/': 14, '//': 14, '%': 14, '@': 14, '**': 16 },
337
+ rb: { or: 2, and: 2, '||': 5, '&&': 6, '..': 4.5, '...': 4.5, '==': 8, '!=': 8, '===': 8, '=~': 8, '<': 9, '>': 9, '<=': 9, '>=': 9, '<=>': 8, '|': 10, '^': 10, '&': 11, '<<': 12, '>>': 12, '+': 13, '-': 13, '*': 14, '/': 14, '%': 14, '**': 16 },
338
+ go: { '||': 5, '&&': 6, '==': 8, '!=': 8, '<': 8, '>': 8, '<=': 8, '>=': 8, '+': 9, '-': 9, '|': 9, '^': 9, '*': 10, '/': 10, '%': 10, '<<': 10, '>>': 10, '&': 10, '&^': 10 },
339
+ rs: { '..': 3, '..=': 3, '||': 5, '&&': 6, '==': 8, '!=': 8, '<': 8, '>': 8, '<=': 8, '>=': 8, '|': 9, '^': 10, '&': 11, '<<': 12, '>>': 12, '+': 13, '-': 13, '*': 14, '/': 14, '%': 14, as: 15 },
340
+ };
341
+ // Words that cannot be a value where one is expected (a statement keyword): the reader gives up rather than guess.
342
+ const HARD = {
343
+ c: /^(?:if|for|while|switch|try|class|return|throw|else|do|case|var|let|const|catch|finally|break|continue|import|export|default)$/,
344
+ py: /^(?:if|for|while|try|class|def|return|raise|else|elif|import|from|with|pass|del|global|nonlocal|assert|except|finally|break|continue|in|is|and|or)$/,
345
+ rb: /^(?:if|unless|while|until|for|case|when|def|class|module|return|else|elsif|begin|rescue|ensure|end|then|do|and|or)$/,
346
+ go: /^(?:if|for|switch|select|case|default|return|go|defer|var|const|type|struct|interface|chan|range|else|fallthrough|break|continue|goto|package|import)$/,
347
+ rs: /^(?:if|for|while|loop|match|fn|let|return|impl|struct|enum|trait|else|use|mod|break|continue)$/,
348
+ };
349
+ const PREFIX_BP = { c: 17, kt: 17, py: 15, rb: 15, go: 11, rs: 16 };
350
+ const COMPARE = new Set(['==', '!=', '===', '!==', '<>', '<', '>', '<=', '>=', 'in', 'not in', 'is', 'is not', 'instanceof', '!in', '!is', '=~']);
351
+ const LOGIC = { '||': 'or', '&&': 'and', or: 'or', and: 'and' };
352
+ const ASSIGN_OPS = new Set(['=', '+=', '-=', '*=', '/=', '%=', '**=', '//=', '&=', '|=', '^=', '<<=', '>>=', '>>>=', '&&=', '||=', '??=', ':=', '.=', '&^=']);
353
+
354
+ function bpTable(lang) { const f = opFamily(lang); return f === 'kt' ? BP.kt : f === 'php' ? BP.c : BP[famOf(lang)] || BP.c; }
355
+
356
+ class Parser {
357
+ constructor(src, lang) {
358
+ this.L = makeLexer(src, lang);
359
+ this.lang = lang;
360
+ this.fam = famOf(lang);
361
+ this.bp = bpTable(lang);
362
+ this.k = 0;
363
+ this.noBrace = false; // in a Go/Rust header, `name {` opens the block, not a literal
364
+ }
365
+ peek(o = 0) { return this.L.at(this.k + o); }
366
+ next() { const t = this.L.at(this.k); this.k++; return t; }
367
+ is(v, o = 0) { const t = this.peek(o); return t.t !== 'str' && t.t !== 'tpl' && t.t !== 'regex' && t.v === v; }
368
+ isOp(v, o = 0) { const t = this.peek(o); return t.t === 'op' && t.v === v; }
369
+ isId(v, o = 0) { const t = this.peek(o); return t.t === 'id' && t.v === v; }
370
+ eat(v) { if (!this.is(v)) fail(`expected ${v}, saw ${this.peek().v || 'the end'}`); return this.next(); }
371
+ atEnd() { const t = this.peek(); return t.t === 'eof' || (t.t === 'op' && t.v === ';' && this.L.at(this.k + 1).t === 'eof'); }
372
+
373
+ /** Raw source text of tokens [a, b). */
374
+ text(a, b) { return this.L.src.slice(this.L.at(a).s, this.L.at(b - 1).e).replace(/\s+/g, ' ').trim(); }
375
+
376
+ // A type written after `:` / `as` / `is`, kept as text: Foo, Foo.Bar<X, Y>[], X | undefined, () => void.
377
+ typeText(stops = []) {
378
+ const a = this.k;
379
+ let depth = 0;
380
+ for (;;) {
381
+ const t = this.peek();
382
+ if (t.t === 'eof') break;
383
+ if (t.t === 'block') break;
384
+ if (t.t === 'op') {
385
+ if ('([{<'.includes(t.v)) { if (t.v === '{' && depth === 0 && (this.fam !== 'c' || stops.includes('{'))) break; depth++; }
386
+ else if (')]}'.includes(t.v)) { if (depth === 0) break; depth--; }
387
+ else if (t.v === '>' || t.v === '>>') { if (depth === 0) break; depth -= t.v.length; if (depth < 0) depth = 0; }
388
+ else if (depth === 0 && (t.v === ',' || t.v === ';' || t.v === '=' || stops.includes(t.v) || ASSIGN_OPS.has(t.v) || t.v === '&&' || t.v === '||' || t.v === '==' || t.v === '!=' || t.v === '===' || t.v === '!==' || t.v === '?' || t.v === ':' || t.v === '+' || t.v === '-' || t.v === '*' || t.v === '/')) break;
389
+ else if (depth === 0 && t.v === '=>' && !stops.includes('=>')) { /* a function type */ }
390
+ else if (depth === 0 && t.v === '->' && this.fam !== 'rs') break;
391
+ } else if (depth === 0 && t.t === 'id' && (stops.includes(t.v) || /^(?:as|is|in|instanceof|satisfies|and|or|if|else)$/.test(t.v)) && this.k > a) break;
392
+ this.next();
393
+ }
394
+ if (this.k === a) fail('expected a type');
395
+ return this.text(a, this.k);
396
+ }
397
+
398
+ // ── expressions ──
399
+ expr(min = 0) {
400
+ if (this.spans) { const a = this.peek().s; const e = this.expr0(min); this.spans.set(e, [a, this.L.at(this.k - 1).e]); return e; }
401
+ return this.expr0(min);
402
+ }
403
+ expr0(min) {
404
+ let left = this.prefix();
405
+ for (;;) {
406
+ const t = this.peek();
407
+ if (t.t === 'eof' || t.t === 'block') break;
408
+ // Assignment inside an expression (`while ((m = re.exec(s)))`, Python `:=`): lowest, right-associative.
409
+ if (t.t === 'op' && ASSIGN_OPS.has(t.v) && min <= 0.5) {
410
+ if (t.v === ':=' && this.fam === 'go') break; // a Go declaration is a statement
411
+ this.next();
412
+ const value = this.expr(0.5);
413
+ left = { kind: 'assign', op: t.v, target: left, value };
414
+ continue;
415
+ }
416
+ // Ternary a ? b : c (C family, Ruby).
417
+ if (t.t === 'op' && t.v === '?' && (this.fam === 'c' || this.fam === 'rb') && min <= 1 && this.lang !== 'kotlin') {
418
+ this.next();
419
+ const then = this.expr(0.5);
420
+ this.eat(':');
421
+ const els = this.expr(1);
422
+ left = { kind: 'conditional', test: left, then, else: els };
423
+ continue;
424
+ }
425
+ // Python: x if c else y.
426
+ if (this.fam === 'py' && t.t === 'id' && t.v === 'if' && min <= 1 && !this.noIf) {
427
+ this.next();
428
+ const test = this.expr(2);
429
+ if (!this.isId('else')) fail('if without else');
430
+ this.next();
431
+ const els = this.expr(1);
432
+ left = { kind: 'conditional', test, then: left, else: els };
433
+ continue;
434
+ }
435
+ const op = this.infixOp();
436
+ if (!op) break;
437
+ const bp = this.bp[op.key];
438
+ if (bp == null || bp < min) break;
439
+ this.k += op.len;
440
+ if (op.key === 'as' || op.key === 'as?' || op.key === 'satisfies') { left = { kind: 'cast', value: left, type: this.typeText(), form: op.key }; continue; }
441
+ if ((op.key === 'is' || op.key === '!is') && (this.lang === 'kotlin' || this.lang === 'csharp')) {
442
+ const ty = this.typeText(['->']);
443
+ left = { kind: 'compare', op: op.key, left, right: { kind: 'name', name: ty }, type: true };
444
+ continue;
445
+ }
446
+ if (op.key === 'instanceof' && this.lang === 'java') { left = { kind: 'compare', op: 'instanceof', left, right: { kind: 'name', name: this.typeText(['&&', '||', ')']) }, type: true }; continue; }
447
+ const right = this.expr(op.key === '**' ? bp : bp + 0.01);
448
+ if (LOGIC[op.key] && !(this.lang === 'kotlin' && /^(and|or)$/.test(op.key))) {
449
+ const lop = LOGIC[op.key];
450
+ // (and / or are associative: `(a && b) && c` and `a && b && c` mean the same, so they read the same.)
451
+ const operands = [...(left.kind === 'logic' && left.op === lop ? left.operands : [left]), right];
452
+ left = { kind: 'logic', op: lop, operands };
453
+ } else if (COMPARE.has(op.key)) {
454
+ if (this.fam === 'py' && (left.kind === 'compare' || left.kind === 'chain') && !GROUPED.has(left)) {
455
+ // Python chains comparisons: a < b < c means a < b and b < c.
456
+ const ch = left.kind === 'chain' ? left : { kind: 'chain', ops: [left.op], operands: [left.left, left.right] };
457
+ left = { kind: 'chain', ops: [...ch.ops, op.key], operands: [...ch.operands, right] };
458
+ } else left = { kind: 'compare', op: op.key, left, right };
459
+ } else if (op.key === '??' || op.key === '?:') left = { kind: 'binary', op: '??', left, right, ...(op.key === '?:' ? { spelled: '?:' } : {}) };
460
+ else left = { kind: 'binary', op: op.key, left, right };
461
+ }
462
+ return left;
463
+ }
464
+
465
+ /** The infix operator at the current token: { key, len } or null. */
466
+ infixOp() {
467
+ const t = this.peek();
468
+ if (t.t === 'op') {
469
+ if (t.v === '!' && (this.lang === 'kotlin') && this.peek(1).t === 'id' && /^(is|in)$/.test(this.peek(1).v)) return { key: `!${this.peek(1).v}`, len: 2 };
470
+ if (t.v === '.' && this.lang === 'php' && t.sp) return { key: '.', len: 1 };
471
+ if (t.v === '..' && this.lang === 'kotlin' && this.isOp('<', 1)) return { key: '..<', len: 2 };
472
+ if (t.v === '=' && this.fam === 'rb' && this.isOp('~', 1)) return { key: '=~', len: 2 };
473
+ if (t.v === '<=' && this.fam === 'rb' && this.isOp('>', 1)) return { key: '<=>', len: 2 };
474
+ if (t.v === '.' || t.v === '?.' || t.v === '::') return null;
475
+ if (this.bp[t.v] != null) return { key: t.v, len: 1 };
476
+ return null;
477
+ }
478
+ if (t.t === 'id') {
479
+ if (this.fam === 'py' && t.v === 'not' && this.isId('in', 1)) return { key: 'not in', len: 2 };
480
+ if (this.fam === 'py' && t.v === 'is' && this.isId('not', 1)) return { key: 'is not', len: 2 };
481
+ if (t.v === 'as' && this.lang === 'kotlin' && this.isOp('?', 1)) return { key: 'as?', len: 2 };
482
+ if (/^(and|or|in|is|instanceof|as|satisfies)$/.test(t.v) && this.bp[t.v] != null) {
483
+ if (t.v === 'instanceof' && !isJs(this.lang) && this.lang !== 'java' && this.lang !== 'php') return null;
484
+ if (t.v === 'in' && this.fam === 'c' && !isJs(this.lang) && this.lang !== 'kotlin') return null;
485
+ if ((t.v === 'and' || t.v === 'or') && this.fam === 'c' && this.lang !== 'php') return null;
486
+ if (t.v === 'as' && this.lang !== 'typescript' && this.lang !== 'csharp' && this.lang !== 'kotlin' && this.lang !== 'rust' && this.lang !== 'swift') return null;
487
+ if (t.v === 'satisfies' && this.lang !== 'typescript') return null;
488
+ if (t.v === 'is' && this.fam === 'c' && this.lang !== 'csharp' && this.lang !== 'kotlin') return null;
489
+ return { key: t.v, len: 1 };
490
+ }
491
+ }
492
+ return null;
493
+ }
494
+
495
+ prefix() {
496
+ const t = this.peek();
497
+ const fam = this.fam;
498
+ if (t.t === 'op') {
499
+ if (t.v === '<' && isJs(this.lang) && /^<(?:[A-Za-z_$]|>)/.test(this.L.src.slice(t.s, t.s + 2))) {
500
+ // A generic arrow function `<T,>(x: T) => …` / `<T extends X>(…) => …`; anything else is JSX.
501
+ if (/^<[A-Za-z_$][\w$]*\s*(?:,|extends\b|=|>\s*\()/.test(this.L.src.slice(t.s, t.s + 200)) && this.lang === 'typescript') {
502
+ const typeParams = this.typeArgs();
503
+ if (!this.isOp('(')) fail('generic');
504
+ const f = this.arrowOrParen();
505
+ if (f.kind !== 'lambda') fail('generic arrow');
506
+ return { ...f, typeParams };
507
+ }
508
+ return this.postfix(this.jsx());
509
+ }
510
+ if (t.v === '!' || (t.v === '~')) { this.next(); const v = this.expr(PREFIX_BP[opFamily(this.lang)] ?? 17); return t.v === '!' ? { kind: 'not', value: v } : { kind: 'unary', op: '~', value: v }; }
511
+ if (t.v === '-' || t.v === '+') {
512
+ this.next();
513
+ // Python: -x ** 2 is -(x ** 2); elsewhere unary binds tighter than everything but postfix.
514
+ const v = this.expr(fam === 'py' ? 15 : PREFIX_BP[opFamily(this.lang)] ?? 17);
515
+ // A negative number is one literal (-1), as a reader would write it.
516
+ if (t.v === '-' && v.kind === 'literal' && v.type === 'number' && !GROUPED.has(v) && this.L.src[t.e] !== ' ') return { ...v, value: v.value == null ? null : -v.value, raw: `-${v.raw}` };
517
+ return { kind: 'unary', op: t.v, value: v };
518
+ }
519
+ if (t.v === '++' || t.v === '--') { this.next(); return { kind: 'unary', op: t.v, value: this.expr(17) }; }
520
+ if (t.v === '...' && (fam === 'c')) { this.next(); return { kind: 'spread', value: this.expr(1), form: '...' }; }
521
+ if ((t.v === '*' || t.v === '**') && (fam === 'py' || fam === 'rb' || this.lang === 'kotlin')) { this.next(); return { kind: 'spread', value: this.expr(fam === 'py' ? 13 : 15), form: t.v }; }
522
+ if (t.v === '&' && fam === 'rb') { this.next(); return { kind: 'spread', value: this.expr(15), form: '&' }; }
523
+ if ((t.v === '*' || t.v === '&' || t.v === '<-') && (fam === 'go' || fam === 'rs')) {
524
+ this.next();
525
+ if (t.v === '&' && fam === 'rs' && this.isId('mut')) { this.next(); return { kind: 'unary', op: '&mut', value: this.expr(16) }; }
526
+ return { kind: 'unary', op: t.v, value: this.expr(PREFIX_BP[fam]) };
527
+ }
528
+ if (t.v === '&&' && fam === 'rs') { this.next(); return { kind: 'unary', op: '&', value: { kind: 'unary', op: '&', value: this.expr(16) } }; }
529
+ if ((t.v === '|' || t.v === '||') && fam === 'rs') return this.rustClosure();
530
+ if (t.v === '(') return this.postfix(this.paren());
531
+ if (t.v === '[') return this.postfix(fam === 'go' ? this.goTypedLiteral() : this.arrayLit());
532
+ if (t.v === '{') {
533
+ if (this.lang === 'kotlin') return this.postfix(this.kotlinLambda());
534
+ if (fam === 'rb') return this.postfix(this.hashLit());
535
+ if (fam === 'go' || fam === 'rs') fail('a block where a value was expected');
536
+ return this.postfix(this.objectLit());
537
+ }
538
+ if (t.v === '@' && isJs(this.lang)) fail('decorator');
539
+ if (t.v === '::' && (this.lang === 'php' || fam === 'rs')) { this.next(); return this.postfix({ kind: 'name', name: `::${this.next().v}` }); }
540
+ return fail(`unexpected ${t.v}`);
541
+ }
542
+ if (t.t === 'num') { this.next(); return this.postfix(numberValue(t.v)); }
543
+ if (t.t === 'str') {
544
+ this.next();
545
+ let node = this.stringNode(t);
546
+ // Adjacent strings join (Python, C): "a" "b".
547
+ while (this.peek().t === 'str' && (fam === 'py' || this.lang === 'c' || this.lang === 'cpp') && !this.peek().symbol) {
548
+ const u = this.next();
549
+ const b = this.stringNode(u);
550
+ if (node.kind === 'literal' && b.kind === 'literal') { if (!!node.bytes !== !!b.bytes) fail('bytes and text'); node = { ...node, value: node.value + b.value, raw: `${node.raw} ${b.raw}` }; continue; }
551
+ // "a " f"b {x}": one f-string, its parts joined.
552
+ const partsOf = (x) => (x.kind === 'template' ? x.parts : x.kind === 'literal' && x.type === 'text' && !x.bytes ? [x.value] : fail('joined strings'));
553
+ const parts = [];
554
+ for (const x of [...partsOf(node), ...partsOf(b)]) { if (typeof x === 'string' && typeof parts[parts.length - 1] === 'string') parts[parts.length - 1] += x; else parts.push(x); }
555
+ node = { kind: 'template', parts, raw: `${node.raw} ${b.raw}`, form: 'f' };
556
+ }
557
+ return this.postfix(node);
558
+ }
559
+ if (t.t === 'tpl') { this.next(); return this.postfix(this.template(t.v)); }
560
+ if (t.t === 'regex') { this.next(); const i = t.v.lastIndexOf('/'); return this.postfix({ kind: 'literal', type: 'regex', value: t.v.slice(1, i), flags: t.v.slice(i + 1), raw: t.v }); }
561
+ if (t.t === 'block') fail('a block where a value was expected');
562
+ if (t.t === 'id') return this.word(t);
563
+ return fail('unexpected end');
564
+ }
565
+
566
+ /** JSX, read character by character from the current token (`<`): elements, attributes, text, and {values}. */
567
+ jsx() {
568
+ const src = this.L.src;
569
+ const start = this.peek().s;
570
+ const k0 = this.k;
571
+ const ws = (i) => { while (i < src.length && /\s/.test(src[i])) i++; return i; };
572
+ const nameAt = (i) => { const m = /^[A-Za-z_$][\w$.:-]*/.exec(src.slice(i, i + 200)); return m ? m[0] : ''; };
573
+ const exprIn = (open) => {
574
+ const close = blockEnd(src, open, this.lang);
575
+ if (close < 0) fail('JSX value');
576
+ const inner = src.slice(open + 1, close).trim();
577
+ return { close, inner };
578
+ };
579
+ const element = (i) => {
580
+ i++;
581
+ const tag = src[i] === '>' ? '' : nameAt(i);
582
+ i += tag.length;
583
+ const attrs = [];
584
+ let selfClosing = false;
585
+ for (;;) {
586
+ i = ws(i);
587
+ if (i >= src.length) fail('JSX');
588
+ if (src.startsWith('/>', i)) { i += 2; selfClosing = true; break; }
589
+ if (src[i] === '>') { i++; break; }
590
+ if (src[i] === '{') {
591
+ const { close, inner } = exprIn(i);
592
+ const e = parseExpr(inner, this.lang);
593
+ if (!e || e.kind !== 'spread') fail('JSX attribute');
594
+ attrs.push({ spread: e.value });
595
+ i = close + 1;
596
+ continue;
597
+ }
598
+ const name = nameAt(i);
599
+ if (!name) fail('JSX attribute name');
600
+ i = ws(i + name.length);
601
+ if (src[i] !== '=') { attrs.push({ name }); continue; }
602
+ i = ws(i + 1);
603
+ if (src[i] === '"' || src[i] === "'") {
604
+ const q = src[i], e = src.indexOf(q, i + 1);
605
+ if (e < 0) fail('JSX text');
606
+ attrs.push({ name, value: { kind: 'literal', type: 'text', value: src.slice(i + 1, e), raw: src.slice(i, e + 1) } });
607
+ i = e + 1;
608
+ } else if (src[i] === '{') {
609
+ const { close, inner } = exprIn(i);
610
+ const e = parseExpr(inner, this.lang);
611
+ if (!e) fail('JSX value');
612
+ attrs.push({ name, value: e });
613
+ i = close + 1;
614
+ } else if (src[i] === '<') { const [el, j] = element(i); attrs.push({ name, value: el }); i = j; }
615
+ else fail('JSX attribute value');
616
+ }
617
+ const children = [];
618
+ if (!selfClosing) {
619
+ for (;;) {
620
+ if (i >= src.length) fail('unclosed JSX');
621
+ if (src.startsWith('</', i)) {
622
+ const j = ws(i + 2);
623
+ const closeName = nameAt(j);
624
+ if (closeName !== tag) fail('JSX closing tag');
625
+ const k = ws(j + closeName.length);
626
+ if (src[k] !== '>') fail('JSX closing tag');
627
+ i = k + 1;
628
+ break;
629
+ }
630
+ if (src[i] === '<') { const [el, j] = element(i); children.push(el); i = j; continue; }
631
+ if (src[i] === '{') {
632
+ const { close, inner } = exprIn(i);
633
+ i = close + 1;
634
+ if (!inner || /^\/\*[^]*\*\/$/.test(inner)) continue; // {/* a comment */}
635
+ const e = parseExpr(inner, this.lang);
636
+ if (!e) fail('JSX value');
637
+ children.push({ kind: 'jsx-value', value: e });
638
+ continue;
639
+ }
640
+ let j = i;
641
+ while (j < src.length && src[j] !== '<' && src[j] !== '{') j++;
642
+ // JSX text: lines trimmed, blank lines dropped, the rest joined with one space (React's rule).
643
+ const lines = src.slice(i, j).replace(/\t/g, ' ').split(/\r?\n/);
644
+ const text = lines.map((l, n) => { let x = l; if (n > 0) x = x.replace(/^\s+/, ''); if (n < lines.length - 1) x = x.replace(/\s+$/, ''); return x; }).filter((l) => l.length).join(' ');
645
+ if (text) children.push(text);
646
+ i = j;
647
+ }
648
+ }
649
+ return [{ kind: 'jsx', tag, attrs, children }, i];
650
+ };
651
+ const [node, end] = element(start);
652
+ this.L.seek(k0, end);
653
+ this.k = k0;
654
+ return node;
655
+ }
656
+
657
+ stringNode(t) {
658
+ globalLang = this.lang;
659
+ if (t.prefix && t.prefix.includes('f') && this.fam === 'py') return this.fstring(t);
660
+ return stringValue(t);
661
+ }
662
+
663
+ word(t) {
664
+ const v = t.v, fam = this.fam, lang = this.lang;
665
+ // Keyword values.
666
+ if (Object.hasOwn(BOOLS, v) && (fam === 'py' ? /^[TF]/.test(v) : /^[tf]/.test(v))) { this.next(); return this.postfix({ kind: 'literal', type: 'bool', value: BOOLS[v], raw: v }); }
667
+ if (Object.hasOwn(NULLS, v) && ((fam === 'py' && v === 'None') || (fam === 'rb' && v === 'nil') || (fam === 'go' && v === 'nil') || (fam === 'c' && (v === 'null' || (isJs(lang) && v === 'undefined') || (lang === 'php' && v === 'NULL'))))) { this.next(); return this.postfix({ kind: 'literal', type: 'null', value: null, raw: v }); }
668
+ if (fam === 'py' && v === 'not') { this.next(); return { kind: 'not', value: this.expr(7) }; }
669
+ if (fam === 'rb' && v === 'not') { this.next(); return { kind: 'not', value: this.expr(3) }; }
670
+ if (fam === 'py' && v === 'lambda') return this.pyLambda();
671
+ if (v === 'await' && (fam === 'py' || fam === 'c') && this.startsValue(1)) { this.next(); return { kind: 'unary', op: 'await', value: this.expr(fam === 'py' ? 16 : 17) }; }
672
+ if (isJs(lang) && /^(?:typeof|void|delete)$/.test(v) && this.startsValue(1)) { this.next(); return { kind: 'unary', op: v, value: this.expr(17) }; }
673
+ if (v === 'new' && (fam === 'c') && this.peek(1).t === 'id') return this.newExpr();
674
+ if ((v === 'typeof' || v === 'default' || v === 'sizeof') && lang === 'csharp' && this.isOp('(', 1)) {
675
+ // typeof(IHandler<,>): the type as written.
676
+ this.next(); this.next();
677
+ const a = this.k;
678
+ for (let d = 0; ; ) { const t = this.peek(); if (t.t === 'eof') fail('typeof'); if (t.t === 'op' && t.v === '(') d++; if (t.t === 'op' && t.v === ')') { if (d === 0) break; d--; } this.next(); }
679
+ const type = this.text(a, this.k);
680
+ this.next();
681
+ return this.postfix({ kind: 'call', callee: { kind: 'name', name: v }, args: [{ kind: 'name', name: type, type: true }] });
682
+ }
683
+ if (v === 'static' && lang === 'csharp' && (this.isOp('(', 1) || (this.peek(1).t === 'id' && this.isOp('=>', 2)))) { this.next(); const f = this.peek().t === 'id' ? this.arrowSingle() : this.arrowOrParen(); if (f.kind !== 'lambda') fail('static'); return { ...f, static: true }; }
684
+ if (v === 'new' && lang === 'csharp' && this.isOp('(', 1)) { this.next(); const args = this.args(')'); return this.postfix({ kind: 'call', callee: { kind: 'name', name: '' }, args, new: true, ...this.initializer() }); }
685
+ if ((v === 'function' && isJs(lang)) || (v === 'async' && isJs(lang) && this.isId('function', 1))) return this.postfix(this.jsFunction());
686
+ if (lang === 'php' && (v === 'function' || v === 'fn' || (v === 'static' && (this.isId('function', 1) || this.isId('fn', 1))))) {
687
+ // (PHP's `$fn` is read as `fn`: a variable named fn, called, is not an arrow function.)
688
+ const k0 = this.k;
689
+ try { return this.postfix(this.phpFunction()); } catch (e) { if (!(e instanceof Fail) || v !== 'fn') throw e; this.k = k0; }
690
+ }
691
+ if (v === 'func' && fam === 'go' && this.isOp('(', 1)) return this.postfix(this.goFunc());
692
+ if (v === 'fn' && fam === 'rs' && this.isOp('(', 1)) fail('fn item');
693
+ if (fam === 'rs' && v.endsWith('!') && this.isOp('[', 1)) { this.next(); const arr = this.arrayLit(); return this.postfix({ kind: 'call', callee: { kind: 'name', name: v }, args: arr.items ?? [arr], form: 'macro[]', ...(arr.repeat ? { repeat: arr.repeat } : {}) }); }
694
+ if (v === 'move' && fam === 'rs' && (this.isOp('|', 1) || this.isOp('||', 1))) { this.next(); const c = this.rustClosure(); c.move = true; return c; }
695
+ if (v === 'async' && isJs(lang) && (this.isOp('(', 1) || (this.peek(1).t === 'id' && this.isOp('=>', 2)))) { this.next(); const f = this.peek().t === 'id' ? this.arrowSingle() : this.arrowOrParen(); if (f.kind !== 'lambda') fail('async'); f.async = true; return f; }
696
+ if (fam === 'c' && this.isOp('=>', 1) && (isJs(lang) || lang === 'csharp')) return this.arrowSingle();
697
+ if (lang === 'java' && this.isOp('->', 1)) return this.arrowSingle('->');
698
+ if (fam === 'go' && (v === 'map' && this.isOp('[', 1))) return this.goTypedLiteral();
699
+ if (fam === 'go' && (v === 'struct' || v === 'interface') && this.isOp('{', 1)) return this.postfix(this.goTypedLiteral());
700
+ if (fam === 'go' && (v === 'chan' || (v === 'func' && false))) return this.postfix(this.goTypedLiteral());
701
+ if (v === 'yield' && (fam === 'py' || isJs(lang))) { this.next(); const delegate = fam === 'py' ? this.isId('from') && !!this.next() : this.isOp('*') && !!this.next(); return { kind: 'yield', ...(this.startsValue(0) ? { value: this.expr(1) } : {}), ...(delegate ? { delegate: true } : {}) }; }
702
+ if (fam === 'rb' && v === 'defined?') { this.next(); return this.postfix({ kind: 'call', callee: { kind: 'name', name: v }, args: this.isOp('(') ? (this.next(), this.args(')')) : [this.expr(14)] }); }
703
+ if (HARD[fam].test(v) || (lang === 'kotlin' && /^(?:when|val|fun|object)$/.test(v))) fail(`${v} where a value was expected`);
704
+ this.next();
705
+ let node = { kind: 'name', name: v };
706
+ // Ruby: a method called without brackets is still a call when arguments follow (`raise Error, "x"` is handled by the statement).
707
+ return this.postfix(node);
708
+ }
709
+
710
+ startsValue(o = 0) {
711
+ const t = this.peek(o);
712
+ if (t.t === 'eof' || t.t === 'block') return false;
713
+ if (t.t !== 'op') return !(t.t === 'id' && /^(?:if|else|for|in|of|and|or|then|do|as|is)$/.test(t.v));
714
+ return /^(?:\(|\[|\{|!|-|\+|~|\.\.\.|\*|&|<-)$/.test(t.v);
715
+ }
716
+
717
+ postfix(node) {
718
+ const fam = this.fam, lang = this.lang;
719
+ for (;;) {
720
+ const t = this.peek();
721
+ if (t.t === 'eof' || t.t === 'block') {
722
+ if (t.t === 'block' && this.trailingBlockOk(node, t)) { this.next(); node = this.withTrailing(node, { kind: 'lambda', params: [], body: { kind: 'block' } }); continue; }
723
+ break;
724
+ }
725
+ if (t.t === 'op') {
726
+ if (t.v === '(') {
727
+ if (t.nl && fam === 'rb') break;
728
+ this.next();
729
+ const args = this.args(')');
730
+ node = { kind: 'call', callee: node, args };
731
+ if (lang === 'csharp' && node.callee.kind === 'name' && node.callee.name === 'typeof') node.args = args;
732
+ continue;
733
+ }
734
+ if (t.v === '[') {
735
+ if (t.nl && (isJs(lang) || fam === 'rb')) break;
736
+ this.next();
737
+ if (this.isOp(']') && fam === 'go') fail('a Go type');
738
+ if (this.isOp(']') && this.lang === 'java' && this.isOp('.', 1) && this.isId('class', 2)) { this.next(); node = { kind: 'name', name: `${flatName(node) ?? fail('array type')}[]`, type: true }; continue; }
739
+ if (this.isOp(']') && this.lang === 'php') { this.next(); node = { kind: 'index', object: node, index: { kind: 'hole' }, append: true }; continue; }
740
+ const index = this.indexOrSlice();
741
+ this.eat(']');
742
+ node = { kind: 'index', object: node, index };
743
+ continue;
744
+ }
745
+ if (t.v === '.' && !(lang === 'php' && t.sp)) {
746
+ this.next();
747
+ const p = this.peek();
748
+ if (p.t === 'op' && p.v === '(' && fam === 'go') { this.next(); const ty = this.isId('type') ? this.next().v : this.goType(); this.eat(')'); node = { kind: 'cast', value: node, type: ty, form: 'assert' }; continue; }
749
+ if (p.t === 'op' && p.v === '<' && lang === 'java') fail('explicit type arguments');
750
+ if (p.t !== 'id' && p.t !== 'num') fail('expected a name after .');
751
+ this.next();
752
+ if (fam === 'rs' && p.v === 'await') { node = { kind: 'unary', op: 'await', value: node, postfix: true }; continue; }
753
+ node = { kind: 'member', object: node, property: p.v };
754
+ continue;
755
+ }
756
+ if (t.v === '&.' && fam === 'rb') { this.next(); const pn = this.next(); if (pn.t !== 'id') fail('a name after &.'); node = { kind: 'member', object: node, property: pn.v, optional: true }; continue; }
757
+ if (t.v === '?.' && fam === 'c') {
758
+ this.next();
759
+ if (this.isOp('(')) { this.next(); node = { kind: 'call', callee: node, args: this.args(')'), optional: true }; continue; }
760
+ if (this.isOp('[')) { this.next(); const index = this.expr(0); this.eat(']'); node = { kind: 'index', object: node, index, optional: true }; continue; }
761
+ const p = this.next();
762
+ if (p.t !== 'id') fail('expected a name after ?.');
763
+ node = { kind: 'member', object: node, property: p.v, optional: true };
764
+ continue;
765
+ }
766
+ if (t.v === '::' && (fam === 'rs' || lang === 'php' || fam === 'rb' || lang === 'java' || lang === 'kotlin' || lang === 'cpp' || lang === 'c')) {
767
+ this.next();
768
+ if (this.isOp('<') && fam === 'rs') { node = { ...node, typeArgs: this.typeArgs() }; continue; }
769
+ const p = this.next();
770
+ if (p.t !== 'id' && !(p.t === 'op' && p.v === '*')) fail('expected a name after ::');
771
+ node = { kind: 'member', object: node, property: p.v, static: true };
772
+ continue;
773
+ }
774
+ if (t.v === '!' && !t.sp && (lang === 'typescript' || lang === 'csharp') && this.notStartOfValue(1)) { this.next(); continue; } // a non-null claim changes nothing at run time
775
+ if (t.v === '!!' && lang === 'kotlin') { this.next(); node = { kind: 'unary', op: '!!', value: node, postfix: true }; continue; }
776
+ if (t.v === '?' && fam === 'rs' && !t.sp) { this.next(); node = { kind: 'unary', op: '?', value: node, postfix: true }; continue; }
777
+ if ((t.v === '++' || t.v === '--') && !t.nl && fam !== 'py') { this.next(); node = { kind: 'unary', op: t.v, value: node, postfix: true }; continue; }
778
+ if (t.v === '<' && (lang === 'typescript' || lang === 'csharp' || lang === 'java' || lang === 'kotlin') && !t.sp && this.looksLikeTypeArgs()) { node = { ...node, typeArgs: this.typeArgs() }; continue; }
779
+ if (t.v === '{' && !this.noBrace && (fam === 'go' || fam === 'rs') && this.isTypeName(node)) { node = this.compositeLit(node); continue; }
780
+ if (t.v === '{' && lang === 'kotlin' && !this.noBrace && (node.kind === 'call' || node.kind === 'name' || node.kind === 'member')) { node = this.withTrailing(node, this.kotlinLambda()); continue; }
781
+ // Ruby: braces after a call are its block (`items.each { |x| … }`, `loop { … }`); a hash is only ever an argument.
782
+ if (t.v === '{' && fam === 'rb' && (node.kind === 'call' || node.kind === 'member' || node.kind === 'name')) { node = this.withTrailing(node, this.rubyBraceBlock()); continue; }
783
+ if (t.v === '{' && lang === 'csharp' && node.kind === 'call' && node.new) { Object.assign(node, this.initializer()); continue; }
784
+ break;
785
+ }
786
+ if (t.t === 'id' && t.v === 'do' && fam === 'rb') { node = this.withTrailing(node, this.rubyDoBlock()); continue; }
787
+ if (t.t === 'tpl' && isJs(lang) && !t.sp) { this.next(); node = { ...this.template(t.v), tag: node }; continue; }
788
+ break;
789
+ }
790
+ return node;
791
+ }
792
+
793
+ notStartOfValue(o) { const t = this.peek(o); return t.t === 'eof' || (t.t === 'op' && /^(?:\.|\?\.|\(|\[|\)|\]|\}|,|;|=|==|===|!=|!==|&&|\|\||\?\?|:|\+|-|\*|\/|<|>|<=|>=)$/.test(t.v)); }
794
+ trailingBlockOk(node, t) { return (this.lang === 'kotlin' && !this.noBrace && (node.kind === 'call' || node.kind === 'name' || node.kind === 'member')) || false; }
795
+ withTrailing(node, lambda) {
796
+ lambda.trailing = true;
797
+ if (node.kind === 'call') return { ...node, args: [...node.args, lambda] };
798
+ return { kind: 'call', callee: node, args: [lambda], parens: false };
799
+ }
800
+ isTypeName(node) {
801
+ if (this.fam === 'go') return node.kind === 'name' || (node.kind === 'member' && node.object.kind === 'name') || node.kind === 'index';
802
+ return (node.kind === 'name' && /^[A-Z]/.test(node.name)) || (node.kind === 'member' && node.static && /^[A-Z]/.test(node.property));
803
+ }
804
+ looksLikeTypeArgs() {
805
+ let depth = 0;
806
+ for (let o = 0; o < 40; o++) {
807
+ const t = this.peek(o);
808
+ if (t.t === 'eof' || t.t === 'block') return false;
809
+ if (t.t === 'op') {
810
+ if (t.v === '<') depth++;
811
+ else if (t.v === '>' || t.v === '>>') { depth -= t.v.length; if (depth <= 0) { const nx = this.peek(o + 1); return nx.t === 'op' && (nx.v === '(' || (nx.v === '{' && this.lang === 'csharp')); } }
812
+ else if (!/^(?:,|\.|\[|\]|\||&|\?|=>|\(|\)|:)$/.test(t.v)) return false;
813
+ } else if (t.t !== 'id' && t.t !== 'str' && t.t !== 'num') return false;
814
+ }
815
+ return false;
816
+ }
817
+ typeArgs() {
818
+ const a = this.k;
819
+ let depth = 0;
820
+ for (;;) {
821
+ const t = this.next();
822
+ if (t.t === 'eof') fail('type arguments');
823
+ if (t.t === 'op' && t.v === '<') depth++;
824
+ else if (t.t === 'op' && (t.v === '>' || t.v === '>>')) { depth -= t.v.length; if (depth <= 0) break; }
825
+ }
826
+ return this.text(a, this.k);
827
+ }
828
+
829
+ indexOrSlice() {
830
+ const sliceLang = this.fam === 'py' || this.fam === 'go';
831
+ if (!sliceLang) return this.expr(0);
832
+ const part = () => (this.isOp(':') || this.isOp(']') ? null : this.expr(0.6));
833
+ const start = part();
834
+ if (!this.isOp(':')) {
835
+ if (this.fam === 'py' && this.isOp(',')) { const items = [start]; while (this.isOp(',')) { this.next(); if (this.isOp(']')) break; items.push(this.expr(0.6)); } return { kind: 'array', form: 'tuple', items }; }
836
+ return start;
837
+ }
838
+ this.next();
839
+ const end = part();
840
+ let step = null;
841
+ if (this.isOp(':')) { this.next(); step = part(); }
842
+ return { kind: 'slice', ...(start ? { start } : {}), ...(end ? { end } : {}), ...(step ? { step } : {}) };
843
+ }
844
+
845
+ /** Arguments up to `close`: positional, named (Python / Kotlin / C# / Swift), spread; generator expressions. */
846
+ args(close) {
847
+ const out = [];
848
+ while (!this.isOp(close)) {
849
+ if (this.peek().t === 'eof') fail('unclosed call');
850
+ const t = this.peek();
851
+ const namedSep = this.fam === 'py' || this.lang === 'kotlin' || this.lang === 'scala' ? '=' : this.lang === 'csharp' || this.lang === 'swift' || this.lang === 'php' || this.fam === 'rb' ? ':' : null;
852
+ if (t.t === 'id' && namedSep && this.isOp(namedSep, 1) && !(namedSep === ':' && this.isOp(':', 2))) {
853
+ this.next(); this.next();
854
+ out.push({ kind: 'named', name: t.v, value: this.expr(0.6) });
855
+ } else if (this.fam === 'rb' && (t.t === 'str' || t.t === 'id') && this.isOp('=>', 1)) {
856
+ out.push(this.hashPairsInline());
857
+ continue;
858
+ } else {
859
+ let a = this.expr(this.fam === 'c' || this.fam === 'rs' ? 0.5 : 0.6);
860
+ if (this.fam === 'py' && this.isId('for')) a = this.comprehension(a, 'generator');
861
+ // Go: passing a list as separate arguments, `append(xs, ys...)`.
862
+ if (this.fam === 'go' && this.isOp('...')) { this.next(); a = { kind: 'spread', value: a, form: '...', postfix: true }; }
863
+ if (this.fam === 'rb' && this.isOp('=>')) { this.next(); a = { kind: 'object', entries: [{ key: a, value: this.expr(0.6) }], form: 'hash', bare: true }; }
864
+ if (this.lang === 'php' && this.isOp('=>')) { this.next(); a = { kind: 'object', entries: [{ key: a, value: this.expr(0.6) }], bare: true }; }
865
+ out.push(a);
866
+ }
867
+ if (this.isOp(',')) { this.next(); continue; }
868
+ if (!this.isOp(close)) fail(`expected , or ${close}`);
869
+ }
870
+ this.next();
871
+ return out;
872
+ }
873
+ hashPairsInline() {
874
+ const entries = [];
875
+ while (!this.isOp(')') && this.peek().t !== 'eof') {
876
+ const key = this.expr(0.6); this.eat('=>'); entries.push({ key, value: this.expr(0.6) });
877
+ if (this.isOp(',')) this.next(); else break;
878
+ }
879
+ return { kind: 'object', entries, form: 'hash', bare: true };
880
+ }
881
+
882
+ paren() {
883
+ // An arrow function `(a, b) => …` / `(a: T): R => …`?
884
+ if (this.fam === 'c' && (isJs(this.lang) || this.lang === 'csharp' || this.lang === 'java')) {
885
+ // JSX inside brackets (`return (\n <div>…`) is read as JSX, not scanned as code.
886
+ if (isJs(this.lang) && /^\(\s*</.test(this.L.src.slice(this.peek().s, this.peek().s + 400))) return this.plainParen();
887
+ const k0 = this.k;
888
+ try { return this.arrowOrParen(); } catch (e) { if (!(e instanceof Fail) || this.k !== k0) throw e; return this.plainParen(); }
889
+ }
890
+ return this.plainParen();
891
+ }
892
+ arrowOrParen() {
893
+ // Find the matching ) and look for => (or ->, Java) after it, past an optional return type.
894
+ let depth = 0, o = 0;
895
+ for (;; o++) {
896
+ const t = this.peek(o);
897
+ if (t.t === 'eof' || t.t === 'block') break;
898
+ if (t.t === 'op') { if ('([{'.includes(t.v)) depth++; else if (')]}'.includes(t.v)) { depth--; if (depth === 0) break; } }
899
+ }
900
+ const after = this.peek(o + 1);
901
+ const arrow = this.lang === 'java' ? '->' : '=>';
902
+ let isArrow = after.t === 'op' && after.v === arrow;
903
+ let typeAt = -1;
904
+ if (!isArrow && after.t === 'op' && after.v === ':' && this.lang === 'typescript') {
905
+ // (a): Promise<X> => …
906
+ for (let j = o + 2, d = 0; j < o + 60; j++) {
907
+ const u = this.peek(j);
908
+ if (u.t === 'eof') break;
909
+ if (u.t === 'op') { if ('(<[{'.includes(u.v)) d++; else if (')>]}'.includes(u.v)) d--; else if (u.v === '=>' && d <= 0) { isArrow = true; typeAt = o + 2; break; } else if (d <= 0 && /^(?:;|,|=)$/.test(u.v)) break; }
910
+ }
911
+ }
912
+ if (!isArrow || this.fam === 'py') return this.plainParen();
913
+ this.next();
914
+ const params = this.paramList(')');
915
+ let returns = null;
916
+ if (typeAt > 0) { this.next(); returns = this.typeText(['=>']); }
917
+ this.eat(arrow);
918
+ return { kind: 'lambda', params, ...(returns ? { returns } : {}), body: this.lambdaBody() };
919
+ }
920
+ arrowSingle(arrow = '=>') { const p = this.next(); this.eat(arrow); return { kind: 'lambda', params: [p.v], body: this.lambdaBody() }; }
921
+ lambdaBody() {
922
+ if (this.isOp('{')) { this.L.skipBlock(this.k); this.next(); return { kind: 'block' }; }
923
+ if (this.peek().t === 'block') { this.next(); return { kind: 'block' }; }
924
+ return this.expr(0.5);
925
+ }
926
+ /** Parameters as written (names, types, defaults, destructuring), one string each, up to `close`. */
927
+ paramList(close) {
928
+ const out = [];
929
+ let a = this.k, depth = 0;
930
+ for (;;) {
931
+ const t = this.peek();
932
+ if (t.t === 'eof') fail('unclosed parameters');
933
+ if (t.t === 'op') {
934
+ if ('([{<'.includes(t.v) && !(t.v === '<' && this.fam === 'py')) depth++;
935
+ else if (t.v === close && depth === 0) { if (this.k > a) out.push(this.text(a, this.k)); this.next(); return out; }
936
+ else if (')]}>'.includes(t.v) && !(t.v === '>' && this.fam === 'py')) depth--;
937
+ else if (t.v === '=>' && depth > 0) { /* a function type */ }
938
+ else if (t.v === ',' && depth === 0) { out.push(this.text(a, this.k)); this.next(); a = this.k; continue; }
939
+ }
940
+ this.next();
941
+ }
942
+ }
943
+ plainParen() {
944
+ this.next();
945
+ if (this.isOp(')')) { this.next(); return { kind: 'array', form: 'tuple', items: [] }; }
946
+ // Java / C# cast: (Type) value.
947
+ if ((this.lang === 'java' || this.lang === 'csharp' || this.lang === 'c' || this.lang === 'cpp' || this.lang === 'php') && this.peek().t === 'id' && this.castAhead()) {
948
+ const ty = this.typeText([')']);
949
+ this.eat(')');
950
+ return { kind: 'cast', value: this.expr(PREFIX_BP.c), type: ty, form: 'paren' };
951
+ }
952
+ const saveBrace = this.noBrace, saveIf = this.noIf;
953
+ this.noBrace = false; this.noIf = false;
954
+ let e = this.expr(0);
955
+ if (this.fam === 'py' && this.isId('for')) e = this.comprehension(e, 'generator');
956
+ if (this.isOp(',')) {
957
+ const items = [e];
958
+ while (this.isOp(',')) { this.next(); if (this.isOp(')')) break; items.push(this.expr(0.6)); }
959
+ e = { kind: 'array', form: 'tuple', items };
960
+ } else if (e && typeof e === 'object') GROUPED.add(e);
961
+ this.noBrace = saveBrace; this.noIf = saveIf;
962
+ this.eat(')');
963
+ return e;
964
+ }
965
+ castAhead() {
966
+ // (Foo) x, (Foo<Bar>) x, (int) x — a type in brackets followed directly by a value.
967
+ let o = 0, depth = 0;
968
+ const prim = /^(?:int|integer|long|short|byte|char|float|double|boolean|bool|decimal|string|object|array|uint|ulong|sbyte|ushort|var)$/;
969
+ const first = this.peek(0);
970
+ if (!(/^[A-Z]/.test(first.v) || prim.test(first.v))) return false;
971
+ for (;; o++) {
972
+ const t = this.peek(o);
973
+ if (t.t === 'eof') return false;
974
+ if (t.t === 'op') {
975
+ if (t.v === '<' || t.v === '[') depth++;
976
+ else if (t.v === '>' || t.v === ']') depth--;
977
+ else if (t.v === ')' && depth === 0) break;
978
+ else if (!/^(?:\.|,|\?)$/.test(t.v)) return false;
979
+ } else if (t.t !== 'id') return false;
980
+ }
981
+ const nx = this.peek(o + 1);
982
+ return nx.t === 'id' ? !/^(?:instanceof|is|as|and|or)$/.test(nx.v) : nx.t === 'num' || nx.t === 'str' || (nx.t === 'op' && (nx.v === '(' || nx.v === '!'));
983
+ }
984
+
985
+ arrayLit() {
986
+ this.next();
987
+ const items = [];
988
+ while (!this.isOp(']')) {
989
+ if (this.peek().t === 'eof') fail('unclosed list');
990
+ if (this.isOp(',') && this.fam === 'c') { this.next(); items.push({ kind: 'hole' }); continue; }
991
+ let it = this.expr(0.6);
992
+ if (this.fam === 'py' && this.isId('for')) { it = this.comprehension(it, 'list'); this.eat(']'); return it; }
993
+ if ((this.lang === 'php') && this.isOp('=>')) { this.next(); const value = this.expr(0.6); items.push({ kind: 'pair', key: it, value }); }
994
+ else items.push(it);
995
+ if (this.isOp(',')) { this.next(); continue; }
996
+ if (this.fam === 'rs' && this.isOp(';')) { this.next(); const count = this.expr(0.6); this.eat(']'); return { kind: 'array', items, repeat: count }; }
997
+ if (!this.isOp(']')) fail('expected , or ]');
998
+ }
999
+ this.next();
1000
+ if (items.some((x) => x.kind === 'pair')) {
1001
+ if (!items.every((x) => x.kind === 'pair')) fail('mixed array');
1002
+ return { kind: 'object', entries: items.map((x) => ({ key: x.key, value: x.value })), form: 'array' };
1003
+ }
1004
+ return { kind: 'array', items };
1005
+ }
1006
+
1007
+ objectLit() {
1008
+ // JavaScript object, Python dict or set, C#/Java array initializer.
1009
+ this.next();
1010
+ if (this.fam === 'py') return this.pyBrace();
1011
+ const entries = [];
1012
+ while (!this.isOp('}')) {
1013
+ const t = this.peek();
1014
+ if (t.t === 'eof') fail('unclosed object');
1015
+ if (t.t === 'op' && t.v === '...') { this.next(); entries.push({ kind: 'spread', value: this.expr(0.6), form: '...' }); }
1016
+ else if (t.t === 'op' && t.v === '[') { this.next(); const key = this.expr(0); this.eat(']'); this.eat(':'); entries.push({ key, value: this.expr(0.6), computed: true }); }
1017
+ else if ((t.t === 'id' || t.t === 'str' || t.t === 'num') && (this.isOp(':', 1))) {
1018
+ this.next(); this.next();
1019
+ const key = t.t === 'id' ? { kind: 'literal', type: 'text', value: t.v, raw: t.v } : t.t === 'num' ? numberValue(t.v) : stringValue(t);
1020
+ entries.push({ key, value: this.expr(0.6) });
1021
+ } else if (t.t === 'id' && (this.isOp(',', 1) || this.isOp('}', 1)) && isJs(this.lang)) {
1022
+ this.next();
1023
+ entries.push({ key: { kind: 'literal', type: 'text', value: t.v, raw: t.v }, value: { kind: 'name', name: t.v }, shorthand: true });
1024
+ } else if (t.t === 'id' && isJs(this.lang) && this.isOp('=', 1)) fail('a default in a pattern');
1025
+ else if (isJs(this.lang) && (t.t === 'id' || t.t === 'str') && (this.isOp('(', 1) || ((t.v === 'get' || t.v === 'set' || t.v === 'async') && this.peek(1).t === 'id' && this.isOp('(', 2)) || (t.v === 'async' && this.isOp('*', 1)) || (t.t === 'op' && t.v === '*'))) {
1026
+ // A method: `transform(chunk) { … }`, `get size() { … }`, `async load() { … }`. Its steps are the step's children.
1027
+ let form = 'method';
1028
+ if ((t.v === 'get' || t.v === 'set' || t.v === 'async') && !this.isOp('(', 1)) { form = t.v === 'async' ? 'async method' : `${t.v}ter`; this.next(); }
1029
+ if (this.isOp('*')) { this.next(); form = 'generator method'; }
1030
+ const k = this.next();
1031
+ this.eat('(');
1032
+ const params = this.paramList(')');
1033
+ if (this.isOp(':')) { this.next(); this.typeText(['{']); }
1034
+ if (!this.isOp('{')) fail('method body');
1035
+ entries.push({ key: k.t === 'str' ? stringValue(k) : { kind: 'literal', type: 'text', value: k.v, raw: k.v }, value: { kind: 'lambda', params, body: this.lambdaBody(), form }, method: true });
1036
+ } else if (isJs(this.lang)) fail('a method in an object');
1037
+ else { entries.push({ value: this.expr(0.6) }); }
1038
+ if (this.isOp(',')) { this.next(); continue; }
1039
+ if (!this.isOp('}')) fail('expected , or }');
1040
+ }
1041
+ this.next();
1042
+ if (entries.length && entries.every((e) => !e.key && e.kind !== 'spread')) return { kind: 'array', items: entries.map((e) => e.value), form: 'braces' };
1043
+ return { kind: 'object', entries };
1044
+ }
1045
+ pyBrace() {
1046
+ if (this.isOp('}')) { this.next(); return { kind: 'object', entries: [] }; }
1047
+ const entries = [], items = [];
1048
+ for (;;) {
1049
+ if (this.peek().t === 'eof') fail('unclosed dict');
1050
+ if (this.isOp('**')) { this.next(); entries.push({ kind: 'spread', value: this.expr(13), form: '**' }); }
1051
+ else {
1052
+ const k = this.expr(0.6);
1053
+ if (this.isOp(':')) {
1054
+ this.next();
1055
+ const v = this.expr(0.6);
1056
+ if (this.isId('for')) { const c = this.comprehension(v, 'dict'); c.key = k; this.eat('}'); return c; }
1057
+ entries.push({ key: k, value: v });
1058
+ } else {
1059
+ if (this.isId('for')) { const c = this.comprehension(k, 'set'); this.eat('}'); return c; }
1060
+ items.push(k);
1061
+ }
1062
+ }
1063
+ if (this.isOp(',')) { this.next(); if (this.isOp('}')) break; continue; }
1064
+ break;
1065
+ }
1066
+ this.eat('}');
1067
+ if (items.length && entries.length) fail('mixed set and dict');
1068
+ return items.length ? { kind: 'array', items, form: 'set' } : { kind: 'object', entries };
1069
+ }
1070
+ hashLit() {
1071
+ // Ruby { a: 1, "b" => 2 }
1072
+ this.next();
1073
+ const entries = [];
1074
+ while (!this.isOp('}')) {
1075
+ const t = this.peek();
1076
+ if (t.t === 'eof') fail('unclosed hash');
1077
+ if (t.t === 'id' && this.isOp(':', 1) && !this.peek(1).sp) { this.next(); this.next(); entries.push({ key: { kind: 'literal', type: 'symbol', value: t.v, raw: `:${t.v}` }, value: this.expr(0.6), colon: true }); }
1078
+ else if (t.t === 'op' && t.v === '**') { this.next(); entries.push({ kind: 'spread', value: this.expr(14), form: '**' }); }
1079
+ else { const key = this.expr(0.6); this.eat('=>'); entries.push({ key, value: this.expr(0.6) }); }
1080
+ if (this.isOp(',')) { this.next(); continue; }
1081
+ if (!this.isOp('}')) fail('expected , or }');
1082
+ }
1083
+ this.next();
1084
+ return { kind: 'object', entries, form: 'hash' };
1085
+ }
1086
+ rubyBraceBlock() {
1087
+ const open = this.k;
1088
+ let params = [];
1089
+ let from = this.peek().e;
1090
+ if (this.isOp('|', 1)) { const a = this.peek(1); for (let o = 2; o < 40; o++) { const t = this.peek(o); if (t.t === 'eof') break; if (t.t === 'op' && t.v === '|') { params = splitParams(this.L.src.slice(a.e, t.s)); from = t.e; break; } } }
1091
+ return { kind: 'lambda', params, body: this.braceBody(open, from), form: 'block' };
1092
+ }
1093
+ rubyDoBlock() {
1094
+ this.next();
1095
+ const params = this.isOp('|') ? (this.next(), this.paramList('|')) : [];
1096
+ // The rest of the statement is the block (its body is the step's children).
1097
+ while (this.peek().t !== 'eof') this.next();
1098
+ return { kind: 'lambda', params, body: { kind: 'block' }, form: 'do' };
1099
+ }
1100
+ kotlinLambda() {
1101
+ // { a, b -> … } or { … }: the body is the step's children.
1102
+ const open = this.k, ot = this.peek();
1103
+ let params = [];
1104
+ let from = ot.e;
1105
+ for (let o = 1, d = 0; o < 40; o++) {
1106
+ const t = this.peek(o);
1107
+ if (t.t === 'eof' || t.t === 'block') break;
1108
+ if (t.t === 'op') {
1109
+ if (t.v === '->' && d === 0) { params = splitParams(this.L.src.slice(ot.e, t.s)); from = t.e; break; }
1110
+ if ('([{<'.includes(t.v)) d++; else if (')]}>'.includes(t.v)) { if (d === 0) break; d--; } else if (!/^(?:,|:|\.|\?)$/.test(t.v)) break;
1111
+ }
1112
+ }
1113
+ return { kind: 'lambda', params, body: this.braceBody(open, from), form: 'braces' };
1114
+ }
1115
+ /**
1116
+ * The body of a block written in braces (Kotlin, Ruby) at token `open`, from source offset `from`: one expression
1117
+ * when it is exactly one (`{ "message" }`, `{ it.name }`), so the value is kept; otherwise a block whose statements
1118
+ * are the step's children.
1119
+ */
1120
+ braceBody(open, from) {
1121
+ const close = blockEnd(this.L.src, this.L.at(open).s, this.lang);
1122
+ const inner = close > 0 ? this.L.src.slice(from, close).trim() : '';
1123
+ this.L.skipBlock(open); this.k = open; this.next();
1124
+ const one = inner && !/[;\n]/.test(inner.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, '')) ? parseExpr(inner, this.lang) : null;
1125
+ return one ?? { kind: 'block' };
1126
+ }
1127
+ initializer() {
1128
+ if (!this.isOp('{')) return {};
1129
+ this.next();
1130
+ const entries = [];
1131
+ while (!this.isOp('}')) {
1132
+ if (this.peek().t === 'eof') fail('unclosed initializer');
1133
+ const t = this.peek();
1134
+ if (t.t === 'id' && this.isOp('=', 1)) { this.next(); this.next(); entries.push({ key: { kind: 'name', name: t.v }, value: this.expr(0.6) }); }
1135
+ else entries.push({ value: this.expr(0.6) });
1136
+ if (this.isOp(',')) { this.next(); continue; }
1137
+ if (!this.isOp('}')) fail('expected , or }');
1138
+ }
1139
+ this.next();
1140
+ return { init: entries };
1141
+ }
1142
+ compositeLit(typeNode) {
1143
+ // Go T{…} / &T{…} / []T{…}; Rust Foo { a: 1, ..rest }.
1144
+ this.next();
1145
+ const entries = [];
1146
+ let keyed = false;
1147
+ while (!this.isOp('}')) {
1148
+ if (this.peek().t === 'eof') fail('unclosed literal');
1149
+ if (this.fam === 'rs' && this.isOp('..')) { this.next(); entries.push({ kind: 'spread', value: this.expr(0.6), form: '..' }); }
1150
+ else {
1151
+ const saved = this.noBrace; this.noBrace = false;
1152
+ let k = this.isOp('{') ? this.bareBraces() : this.expr(0.6);
1153
+ if (this.isOp(':')) { this.next(); keyed = true; const v = this.isOp('{') ? this.bareBraces() : this.expr(0.6); entries.push({ key: k, value: v }); }
1154
+ else if (this.fam === 'rs' && k.kind === 'name' && (this.isOp(',') || this.isOp('}'))) { keyed = true; entries.push({ key: k, value: k, shorthand: true }); }
1155
+ else entries.push({ value: k });
1156
+ this.noBrace = saved;
1157
+ }
1158
+ if (this.isOp(',')) { this.next(); continue; }
1159
+ if (!this.isOp('}')) fail('expected , or }');
1160
+ }
1161
+ this.next();
1162
+ const type = typeNode.kind === 'goType' ? typeNode.text : flatName(typeNode) ?? fail('literal type');
1163
+ if (!keyed && entries.every((e) => !e.key && e.kind !== 'spread')) return { kind: 'array', items: entries.map((e) => e.value), type };
1164
+ if (entries.some((e) => !e.key && e.kind !== 'spread')) fail('mixed literal');
1165
+ return { kind: 'object', entries, type };
1166
+ }
1167
+ bareBraces() { return this.compositeLit({ kind: 'goType', text: '' }); }
1168
+ /** A Go type, as written: *T, []T, [4]T, map[K]V, chan T, func(…) R, struct{…}, interface{…}, pkg.Name[T]. */
1169
+ goType() {
1170
+ const a = this.k;
1171
+ const one = () => {
1172
+ for (;;) {
1173
+ if (this.isOp('*')) { this.next(); continue; }
1174
+ if (this.isOp('[')) { this.next(); if (!this.isOp(']')) { if (this.isOp('...')) this.next(); else this.expr(0.6); } this.eat(']'); continue; }
1175
+ if (this.isId('map') && this.isOp('[', 1)) { this.next(); this.next(); one(); this.eat(']'); continue; }
1176
+ if (this.isId('chan')) { this.next(); if (this.isOp('<-')) this.next(); continue; }
1177
+ if (this.isOp('<-') && this.isId('chan', 1)) { this.next(); continue; }
1178
+ break;
1179
+ }
1180
+ const t = this.peek();
1181
+ if (t.t === 'id' && (t.v === 'struct' || t.v === 'interface') && this.isOp('{', 1)) { this.next(); this.L.skipBlock(this.k); this.next(); return; }
1182
+ if (t.t === 'id' && t.v === 'func' && this.isOp('(', 1)) { this.next(); this.next(); this.paramList(')'); if (this.isOp('(')) { this.next(); this.paramList(')'); } else if (this.peek().t === 'id' || this.isOp('*') || this.isOp('[')) one(); return; }
1183
+ if (t.t !== 'id') fail('Go type');
1184
+ this.next();
1185
+ while (this.isOp('.') && this.peek(1).t === 'id') { this.next(); this.next(); }
1186
+ if (this.isOp('[') && !this.isOp(']', 1)) { this.next(); one(); while (this.isOp(',')) { this.next(); one(); } this.eat(']'); }
1187
+ };
1188
+ one();
1189
+ return this.text(a, this.k);
1190
+ }
1191
+ /** A Go value that starts with a type: []T{…} / map[K]V{…} / struct{}{} (literals), []byte(x) (a conversion), or the type itself (make([]T, n)). */
1192
+ goTypedLiteral() {
1193
+ const type = this.goType();
1194
+ if (this.isOp('{')) return this.compositeLit({ kind: 'goType', text: type });
1195
+ if (this.isOp('(')) { this.next(); return { kind: 'call', callee: { kind: 'name', name: type, type: true }, args: this.args(')') }; }
1196
+ return { kind: 'name', name: type, type: true };
1197
+ }
1198
+ goFunc() {
1199
+ this.next(); this.eat('(');
1200
+ const params = this.paramList(')');
1201
+ let returns = null;
1202
+ if (!this.isOp('{') && this.peek().t !== 'block') { const a = this.k; while (!this.isOp('{') && this.peek().t !== 'eof' && this.peek().t !== 'block') { if (this.isOp('(')) { this.next(); this.paramList(')'); continue; } this.next(); } returns = this.text(a, this.k); }
1203
+ return { kind: 'lambda', params, ...(returns ? { returns } : {}), body: this.lambdaBody(), form: 'func' };
1204
+ }
1205
+ jsFunction() {
1206
+ let async = false;
1207
+ if (this.isId('async')) { this.next(); async = true; }
1208
+ this.next();
1209
+ let gen = false;
1210
+ if (this.isOp('*')) { this.next(); gen = true; }
1211
+ const name = this.peek().t === 'id' ? this.next().v : null;
1212
+ this.eat('(');
1213
+ const params = this.paramList(')');
1214
+ if (this.isOp(':')) { this.next(); this.typeText(['{']); }
1215
+ if (!this.isOp('{') && this.peek().t !== 'block') fail('function body');
1216
+ return { kind: 'lambda', params, body: this.lambdaBody(), form: 'function', ...(name ? { name } : {}), ...(async ? { async } : {}), ...(gen ? { generator: true } : {}) };
1217
+ }
1218
+ phpFunction() {
1219
+ const isStatic = this.isId('static') && !!this.next();
1220
+ const kw = this.next().v;
1221
+ if (this.isOp('&')) this.next();
1222
+ this.eat('(');
1223
+ const params = this.paramList(')');
1224
+ let uses = null;
1225
+ if (this.isId('use')) { this.next(); this.eat('('); uses = this.paramList(')'); }
1226
+ if (this.isOp(':')) { this.next(); this.typeText(['{', '=>']); }
1227
+ if (kw === 'fn') { this.eat('=>'); return { kind: 'lambda', params, body: this.expr(0.5), form: 'fn', ...(isStatic ? { static: true } : {}) }; }
1228
+ if (!this.isOp('{')) fail('function body');
1229
+ return { kind: 'lambda', params, body: this.lambdaBody(), form: 'function', ...(uses ? { uses } : {}), ...(isStatic ? { static: true } : {}) };
1230
+ }
1231
+ rustClosure() {
1232
+ let params = [];
1233
+ if (this.isOp('||')) this.next();
1234
+ else { this.next(); params = this.paramList('|'); }
1235
+ if (this.isOp('->')) { this.next(); this.typeText(['{']); }
1236
+ return { kind: 'lambda', params, body: this.lambdaBody(), form: 'closure' };
1237
+ }
1238
+ pyLambda() {
1239
+ this.next();
1240
+ const params = [];
1241
+ let a = this.k;
1242
+ while (!this.isOp(':')) {
1243
+ if (this.peek().t === 'eof') fail('lambda');
1244
+ if (this.isOp(',')) { params.push(this.text(a, this.k)); this.next(); a = this.k; continue; }
1245
+ this.next();
1246
+ }
1247
+ if (this.k > a) params.push(this.text(a, this.k));
1248
+ this.next();
1249
+ return { kind: 'lambda', params, body: this.expr(1) };
1250
+ }
1251
+ newExpr() {
1252
+ this.next();
1253
+ let callee = { kind: 'name', name: this.next().v };
1254
+ while (this.isOp('.') || (this.isOp('::') && this.lang === 'php')) { this.next(); callee = { kind: 'member', object: callee, property: this.next().v }; }
1255
+ let typeArgs = null;
1256
+ if (this.isOp('<')) typeArgs = this.typeArgs();
1257
+ if (this.isOp('[')) {
1258
+ // new int[] {1, 2} / new String[n] / new byte[0]: an array of a type, with its size or its items.
1259
+ const sizes = [];
1260
+ while (this.isOp('[')) { this.next(); sizes.push(this.isOp(']') ? null : this.expr(0)); this.eat(']'); }
1261
+ const type = `${flatName(callee)}${typeArgs ?? ''}${'[]'.repeat(sizes.length)}`;
1262
+ if (this.isOp('{')) { const lit = this.objectLit(); return this.postfix({ kind: 'array', items: lit.kind === 'array' ? lit.items : lit.entries.length ? fail('array initializer') : [], type, new: true }); }
1263
+ return this.postfix({ kind: 'call', callee: { kind: 'name', name: type, type: true }, args: sizes.filter(Boolean), new: true, array: true });
1264
+ }
1265
+ let args = [], parens = true;
1266
+ if (this.isOp('(')) { this.next(); args = this.args(')'); } else parens = false;
1267
+ const node = { kind: 'call', callee, args, new: true, ...(typeArgs ? { typeArgs } : {}), ...(parens ? {} : { parens: false }) };
1268
+ // An anonymous class (Java): its methods are not steps of this statement, and are not read here.
1269
+ if (this.isOp('{') && this.lang === 'java') { this.L.skipBlock(this.k); this.next(); node.classBody = { kind: 'code', text: '{…}' }; return this.postfix(node); }
1270
+ if (this.isOp('{') && this.lang === 'kotlin') fail('anonymous class');
1271
+ if (this.lang === 'csharp') Object.assign(node, this.initializer());
1272
+ return this.postfix(node);
1273
+ }
1274
+
1275
+ comprehension(item, form) {
1276
+ this.noIf = true;
1277
+ const clauses = [];
1278
+ while (this.isId('for') || (this.isId('async') && this.isId('for', 1))) {
1279
+ if (this.isId('async')) this.next();
1280
+ this.next();
1281
+ const targets = [];
1282
+ while (!this.isId('in')) { if (this.peek().t === 'eof') fail('for without in'); if (this.isOp(',')) { this.next(); continue; } targets.push(this.expr(8.5)); }
1283
+ this.next();
1284
+ const iter = this.expr(2);
1285
+ const conds = [];
1286
+ while (this.isId('if')) { this.next(); conds.push(this.expr(2)); }
1287
+ clauses.push({ targets, iter, ...(conds.length ? { conds } : {}) });
1288
+ }
1289
+ this.noIf = false;
1290
+ return { kind: 'comprehension', form, item, clauses };
1291
+ }
1292
+
1293
+ template(raw) {
1294
+ const parts = [];
1295
+ let buf = '';
1296
+ for (let i = 1; i < raw.length - 1; i++) {
1297
+ const c = raw[i];
1298
+ if (c === '\\') { buf += raw.slice(i, i + 2); i++; continue; }
1299
+ if (c === '$' && raw[i + 1] === '{') {
1300
+ const e = blockEnd(raw, i + 1, this.lang);
1301
+ if (e < 0) fail('template');
1302
+ if (buf) parts.push(unescape(buf));
1303
+ buf = '';
1304
+ const inner = parseExpr(raw.slice(i + 2, e), this.lang);
1305
+ if (!inner || inner.kind === 'code') fail('template part');
1306
+ parts.push({ expr: inner });
1307
+ i = e;
1308
+ continue;
1309
+ }
1310
+ buf += c;
1311
+ }
1312
+ if (buf) parts.push(unescape(buf));
1313
+ return { kind: 'template', parts, raw };
1314
+ }
1315
+ fstring(tok) {
1316
+ const raw = tok.v;
1317
+ const q = tok.q;
1318
+ const off = tok.prefix.length + (tok.triple ? 3 : 1);
1319
+ const body = raw.slice(off, raw.length - (tok.triple ? 3 : 1));
1320
+ const rawStr = tok.prefix.includes('r');
1321
+ const parts = [];
1322
+ let buf = '';
1323
+ for (let i = 0; i < body.length; i++) {
1324
+ const c = body[i];
1325
+ if (c === '{' && body[i + 1] === '{') { buf += '{'; i++; continue; }
1326
+ if (c === '}' && body[i + 1] === '}') { buf += '}'; i++; continue; }
1327
+ if (c === '\\' && !rawStr) { buf += body.slice(i, i + 2); i++; continue; }
1328
+ if (c === '{') {
1329
+ // Find the end of the expression part: a top-level ! (conversion), : (format), or }.
1330
+ let depth = 0, j = i + 1, exprEnd = -1, convAt = -1, fmtAt = -1;
1331
+ for (; j < body.length; j++) {
1332
+ const d = body[j];
1333
+ if (d === '"' || d === "'") { if (d === q) fail('quote in f-string'); const k = body.indexOf(d, j + 1); if (k < 0) fail('f-string'); j = k; continue; }
1334
+ if ('([{'.includes(d)) depth++;
1335
+ else if (')]'.includes(d)) depth--;
1336
+ else if (d === '}') { if (depth === 0) break; depth--; }
1337
+ else if (depth === 0 && d === '!' && body[j + 1] !== '=' && exprEnd < 0) { exprEnd = j; convAt = j; }
1338
+ else if (depth === 0 && d === ':' && fmtAt < 0 && (exprEnd < 0 || convAt >= 0)) { if (exprEnd < 0) exprEnd = j; fmtAt = j; }
1339
+ }
1340
+ if (j >= body.length) fail('f-string');
1341
+ if (exprEnd < 0) exprEnd = j;
1342
+ let text = body.slice(i + 1, exprEnd);
1343
+ const selfDoc = /=\s*$/.test(text) && !/[=!<>]=\s*$/.test(text);
1344
+ if (selfDoc) text = text.replace(/=\s*$/, '');
1345
+ const inner = parseExpr(text, 'python');
1346
+ if (!inner || inner.kind === 'code') fail('f-string part');
1347
+ if (buf) parts.push(unescape(buf));
1348
+ buf = '';
1349
+ const part = { expr: inner };
1350
+ if (convAt >= 0) part.conv = body.slice(convAt + 1, fmtAt >= 0 ? fmtAt : j);
1351
+ if (fmtAt >= 0) part.format = body.slice(fmtAt + 1, j);
1352
+ if (selfDoc) part.selfDoc = true;
1353
+ parts.push(part);
1354
+ i = j;
1355
+ continue;
1356
+ }
1357
+ buf += c;
1358
+ }
1359
+ if (buf) parts.push(rawStr ? buf : unescape(buf));
1360
+ return { kind: 'template', parts, raw, form: 'f' };
1361
+ }
1362
+ }
1363
+
1364
+ /** Parameters written as text, split at top-level commas. */
1365
+ function splitParams(text) {
1366
+ const out = [];
1367
+ let d = 0, from = 0;
1368
+ for (let i = 0; i < text.length; i++) { const c = text[i]; if ('([{<'.includes(c)) d++; else if (')]}>'.includes(c)) d--; else if (c === ',' && d === 0) { out.push(text.slice(from, i)); from = i + 1; } }
1369
+ out.push(text.slice(from));
1370
+ return out.map((x) => x.replace(/\s+/g, ' ').trim()).filter(Boolean);
1371
+ }
1372
+ const flatName = (n) => (n.kind === 'name' ? n.name : n.kind === 'member' ? (flatName(n.object) == null ? null : `${flatName(n.object)}${n.static ? '::' : '.'}${n.property}`) : n.kind === 'index' ? (flatName(n.object) == null ? null : `${flatName(n.object)}[${n.index.kind === 'name' ? n.index.name : '…'}]`) : null);
1373
+
1374
+ // Nodes written in brackets, while reading: `(a < b) < c` is not a Python chain, `-(1)` not the literal -1. The
1375
+ // tree itself has no brackets (its shape is the reading order).
1376
+ const GROUPED = new WeakSet();
1377
+ // ── Public: expressions and statements ───────────────────────────────────────────────────────────────────────
1378
+
1379
+ const CACHE = new Map();
1380
+ const cached = (key, fn) => {
1381
+ const hit = CACHE.get(key);
1382
+ if (hit !== undefined) return hit;
1383
+ const v = fn();
1384
+ if (CACHE.size > 4000) CACHE.clear();
1385
+ CACHE.set(key, v);
1386
+ return v;
1387
+ };
1388
+
1389
+ /** One whole expression as a tree, or null when the text is not exactly one expression this reader understands. */
1390
+ export function parseExpr(text, language = '') {
1391
+ const src = String(text ?? '').trim();
1392
+ if (!src || src.length > 4000) return null;
1393
+ return cached(`e\u0001${language}\u0001${src}`, () => {
1394
+ try {
1395
+ const p = new Parser(src, language);
1396
+ const e = p.expr(0);
1397
+ if (p.isOp(';')) p.next();
1398
+ if (p.peek().t !== 'eof') return null;
1399
+ return e;
1400
+ } catch (e) { if (e instanceof Fail) return null; throw e; }
1401
+ });
1402
+ }
1403
+
1404
+ const code = (text) => ({ kind: 'code', text: String(text).replace(/\s+/g, ' ').trim() });
1405
+
1406
+ /**
1407
+ * A statement as a tree: what a step's `expr` holds. For a statement that opens a block (if, for, while, a call with
1408
+ * a function in it) only the head is read; the block's statements are the step's own children. Never guessed: what
1409
+ * is not fully understood is `{ kind: 'code', text }`.
1410
+ */
1411
+ export function parseStatement(text, language = '') {
1412
+ const src = String(text ?? '').trim();
1413
+ if (!src) return code('');
1414
+ return cached(`s\u0001${language}\u0001${src.length > 600 ? `${src.length}\u0001${src.slice(0, 300)}\u0001${src.slice(-300)}` : src}`, () => {
1415
+ try { return statement(new Parser(src, language)); } catch (e) { if (e instanceof Fail) return code(headOf(src)); throw e; }
1416
+ });
1417
+ }
1418
+ /**
1419
+ * A statement read with where each part came from: { tree, textOf(node) } (node: a part of `tree`, before
1420
+ * normalizing). The round trip uses it to run the original code of a condition or value against the code written
1421
+ * back from the tree.
1422
+ */
1423
+ export function parseStatementSpans(text, language = '') {
1424
+ const src = String(text ?? '').trim();
1425
+ try {
1426
+ const p = new Parser(src, language);
1427
+ p.spans = new Map();
1428
+ const tree = statement(p);
1429
+ return { tree, textOf: (node) => { const sp = p.spans.get(node); return sp ? src.slice(sp[0], sp[1]) : null; }, rangeOf: (node) => p.spans.get(node) ?? null, source: src };
1430
+ } catch (e) { if (e instanceof Fail) return null; throw e; }
1431
+ }
1432
+ // The code of a statement that could not be read: all of it when it is one statement; the first line when it opens
1433
+ // a block (the block's statements are the step's children).
1434
+ const headOf = (src) => {
1435
+ const first = src.split('\n')[0];
1436
+ const t = !src.includes('\n') || /[{:]\s*$/.test(first) ? first : src;
1437
+ const one = t.replace(/\s+/g, ' ').trim();
1438
+ return one.length > 400 ? `${one.slice(0, 399)}…` : one;
1439
+ };
1440
+
1441
+ function endStatement(p, node) {
1442
+ if (p.isOp(';')) p.next();
1443
+ const t = p.peek();
1444
+ if (t.t === 'eof') return node;
1445
+ // Ruby / Perl modifiers: `return x if y` — the step is the question; its inline statement is its child.
1446
+ if (t.t === 'id' && (t.v === 'if' || t.v === 'unless') && (p.fam === 'rb')) {
1447
+ p.next();
1448
+ const test = p.expr(0);
1449
+ if (p.peek().t !== 'eof') fail('after modifier');
1450
+ return { kind: 'if', test, ...(t.v === 'unless' ? { negate: true } : {}), inline: node };
1451
+ }
1452
+ if (t.t === 'id' && (t.v === 'while' || t.v === 'until') && p.fam === 'rb') { p.next(); const test = p.expr(0); return { kind: 'loop', form: t.v, test, inline: node }; }
1453
+ return fail('more after the statement');
1454
+ }
1455
+
1456
+ function headerTest(p, { parens }) {
1457
+ // `if (cond)` in C-family languages; `if cond {` / `if cond:` elsewhere.
1458
+ if (parens) {
1459
+ p.eat('(');
1460
+ const t = p.expr(0);
1461
+ p.eat(')');
1462
+ return t;
1463
+ }
1464
+ p.noBrace = true;
1465
+ const t = p.expr(0);
1466
+ p.noBrace = false;
1467
+ return t;
1468
+ }
1469
+ /** After a header: `{` (the block), `:` (Python), `then` / `do`, the end, or an inline statement (one-line if). */
1470
+ function headerEnd(p, node) {
1471
+ const t = p.peek();
1472
+ if (t.t === 'eof' || t.t === 'block') return node;
1473
+ if (t.t === 'op' && (t.v === '{' || t.v === ':')) return node;
1474
+ if (t.t === 'id' && (t.v === 'then' || t.v === 'do')) return node;
1475
+ if (t.t === 'op' && t.v === ';' && p.fam !== 'go') return node;
1476
+ // A one-line if: `if (x) return y;` — the statement after the condition is the step's child.
1477
+ return { ...node, inline: true };
1478
+ }
1479
+
1480
+ function statement(p) {
1481
+ const t = p.peek();
1482
+ const fam = p.fam, lang = p.lang;
1483
+ const parens = fam === 'c' && lang !== 'swift';
1484
+ if (t.t === 'id') {
1485
+ const v = t.v;
1486
+ // Annotations / decorators before a declaration.
1487
+ if (v === 'else' && p.isId('if', 1)) { p.next(); return statement(p); }
1488
+ // A method written inside a body (an anonymous class, a local function): `public String toString() {`.
1489
+ if (/^(?:java|csharp|kotlin)$/.test(lang) && !/^(?:return|throw|new|await|if|for|while|var|val)$/.test(v)) { const m = methodHeader(p); if (m) return m; }
1490
+ if (v === 'if' || v === 'elif' || v === 'elsif' || v === 'unless' || (v === 'else' && p.isId('if', 1))) {
1491
+ p.next();
1492
+ if (fam === 'rs' && p.isId('let')) fail('if let');
1493
+ if (fam === 'go' || (fam === 'c' && lang === 'swift')) {
1494
+ // Go: an optional simple statement first: `if v, ok := m[k]; ok {`.
1495
+ const k0 = p.k;
1496
+ p.noBrace = true;
1497
+ let init = null;
1498
+ try {
1499
+ const first = simpleStatement(p);
1500
+ if (p.isOp(';')) { p.next(); init = first; } else p.k = k0;
1501
+ } catch (e) { if (!(e instanceof Fail)) throw e; p.k = k0; }
1502
+ p.noBrace = true;
1503
+ const test = p.expr(0);
1504
+ p.noBrace = false;
1505
+ return headerEnd(p, { kind: 'if', test, ...(init ? { init } : {}) });
1506
+ }
1507
+ const test = headerTest(p, { parens: parens && p.isOp('(') });
1508
+ return headerEnd(p, { kind: 'if', test, ...(v === 'unless' ? { negate: true } : {}) });
1509
+ }
1510
+ if (v === 'while' || v === 'until') {
1511
+ p.next();
1512
+ if (fam === 'rs' && p.isId('let')) fail('while let');
1513
+ const test = headerTest(p, { parens: parens && p.isOp('(') });
1514
+ return headerEnd(p, { kind: 'loop', form: v, test });
1515
+ }
1516
+ if (v === 'loop' && fam === 'rs') { p.next(); return headerEnd(p, { kind: 'loop', form: 'forever' }); }
1517
+ if (v === 'do' && (p.isOp('{', 1) || p.peek(1).t === 'eof' || p.peek(1).t === 'block')) {
1518
+ // do { … } while (cond)
1519
+ const m = p.L.src.match(/\}\s*while\s*\(([\s\S]*)\)\s*;?\s*$/);
1520
+ const test = m ? parseExpr(m[1], lang) : null;
1521
+ return test ? { kind: 'loop', form: 'do-while', test } : { kind: 'loop', form: 'do-while', test: code(m ? m[1] : '') };
1522
+ }
1523
+ if (v === 'for' || v === 'foreach') return forHeader(p);
1524
+ const soft = fam === 'py' && /:\s*$/.test(p.L.src) && !(p.peek(1).t === 'op' && /^(?:=|\.|,|\[|\)|:)$/.test(p.peek(1).v)) && !ASSIGN_OPS.has(p.peek(1).v);
1525
+ if ((v === 'switch' && fam !== 'py' && fam !== 'rb') || (v === 'match' && (fam === 'rs' || soft)) || (v === 'select' && fam === 'go') || (v === 'when' && lang === 'kotlin') || (v === 'case' && fam === 'rb')) {
1526
+ p.next();
1527
+ if (fam === 'go' && v === 'switch' && !p.isOp('{') && p.peek().t !== 'block' && p.peek().t !== 'eof') {
1528
+ p.noBrace = true;
1529
+ let init = null, subject = simpleStatement(p);
1530
+ if (p.isOp(';')) { p.next(); init = subject; subject = p.isOp('{') ? null : p.expr(0); }
1531
+ p.noBrace = false;
1532
+ return headerEnd(p, { kind: 'switch', form: v, ...(init ? { init } : {}), ...(subject ? { subject } : {}) });
1533
+ }
1534
+ if (p.isOp('{') || p.peek().t === 'eof' || p.peek().t === 'block' || (v === 'select' && fam === 'go')) return { kind: 'switch', form: v };
1535
+ if (fam === 'go' && p.isId('true') && (p.isOp('{', 1) || p.peek(1).t === 'block')) { p.next(); return { kind: 'switch', form: v, subject: { kind: 'literal', type: 'bool', value: true, raw: 'true' } }; }
1536
+ const subject = headerTest(p, { parens: parens && p.isOp('(') });
1537
+ if (p.isOp(':') && fam === 'py') p.next();
1538
+ return headerEnd(p, { kind: 'switch', form: v, subject });
1539
+ }
1540
+ if ((v === 'case' && (fam !== 'py' || soft) && fam !== 'rb') || (v === 'when' && fam === 'rb')) {
1541
+ p.next();
1542
+ const patterns = [];
1543
+ p.noIf = true;
1544
+ for (;;) {
1545
+ if (fam === 'go' && p.isOp('<-')) { patterns.push(simpleStatement(p)); }
1546
+ else {
1547
+ const k0 = p.k;
1548
+ let pat;
1549
+ try { pat = simpleStatement(p); } catch (e) { if (!(e instanceof Fail)) throw e; p.k = k0; pat = p.expr(0.6); }
1550
+ patterns.push(pat);
1551
+ }
1552
+ if (p.isOp(',')) { p.next(); continue; }
1553
+ if (p.isOp('|') && fam !== 'c') { p.next(); continue; }
1554
+ break;
1555
+ }
1556
+ p.noIf = false;
1557
+ let guard = null;
1558
+ if (fam === 'py' && p.isId('if')) { p.next(); guard = p.expr(0); }
1559
+ const node = { kind: 'case', patterns, ...(guard ? { guard } : {}) };
1560
+ if (p.isOp(':') || p.isOp('->') || p.isId('then')) { p.next(); return p.peek().t === 'eof' ? node : { ...node, inline: true }; }
1561
+ if (fam === 'rb') return p.peek().t === 'eof' ? node : fail('after when');
1562
+ return node;
1563
+ }
1564
+ if (v === 'default' && fam !== 'py' && (p.isOp(':', 1) || p.isOp('->', 1))) { p.next(); p.next(); return p.peek().t === 'eof' ? { kind: 'case', default: true } : { kind: 'case', default: true, inline: true }; }
1565
+ if (v === 'try' || v === 'begin') { p.next(); return { kind: 'try' }; }
1566
+ if (v === 'return' && !(p.isOp('=', 1))) {
1567
+ p.next();
1568
+ if (p.atEnd() || (fam === 'rb' && p.peek().t === 'id' && /^(?:if|unless)$/.test(p.peek().v))) return endStatement(p, { kind: 'return' });
1569
+ const value = fam === 'c' ? p.expr(0.5) : valueList(p);
1570
+ return endStatement(p, { kind: 'return', value });
1571
+ }
1572
+ if (v === 'throw' || v === 'raise') {
1573
+ p.next();
1574
+ if (p.atEnd()) return endStatement(p, { kind: 'throw' });
1575
+ let value = fam === 'rb' ? rubyCommandArgs(p, { kind: 'name', name: 'raise' }) : p.expr(0);
1576
+ let cause = null;
1577
+ if (fam === 'py' && p.isId('from')) { p.next(); cause = p.expr(0); }
1578
+ return endStatement(p, throwNode(value, cause, v));
1579
+ }
1580
+ if ((v === 'panic' && fam === 'go' && p.isOp('(', 1)) || (v === 'panic!' && fam === 'rs')) {
1581
+ const value = p.expr(0);
1582
+ if (value.kind !== 'call') fail('panic');
1583
+ const msg = value.args.find((a) => a.kind === 'literal' && a.type === 'text');
1584
+ return endStatement(p, { kind: 'throw', form: 'panic', value, ...(msg ? { message: msg.value } : {}) });
1585
+ }
1586
+ if ((v === 'break' || v === 'continue' || (v === 'next' && fam === 'rb') || v === 'fallthrough') && !(p.isOp('(', 1)) && !(p.isOp('=', 1))) {
1587
+ p.next();
1588
+ const label = (p.peek().t === 'id' && !/^(?:if|unless)$/.test(p.peek().v)) || (lang === 'php' && p.peek().t === 'num') ? p.next().v : null;
1589
+ return endStatement(p, { kind: 'jump', jump: v === 'next' ? 'continue' : v, ...(label ? { label } : {}) });
1590
+ }
1591
+ if (v === 'yield' && !p.isOp('(', 1)) {
1592
+ p.next();
1593
+ if (lang === 'csharp' && p.isId('break')) { p.next(); return endStatement(p, { kind: 'yield', end: true }); }
1594
+ if (lang === 'csharp' && p.isId('return')) p.next();
1595
+ if (fam === 'rb') return endStatement(p, { kind: 'call', callee: { kind: 'name', name: 'yield' }, args: p.atEnd() ? [] : rubyArgList(p), parens: false });
1596
+ const delegate = (fam === 'py' && p.isId('from')) || (isJs(lang) && p.isOp('*'));
1597
+ if (delegate) p.next();
1598
+ if (p.atEnd()) return endStatement(p, { kind: 'yield' });
1599
+ return endStatement(p, { kind: 'yield', value: valueList(p), ...(delegate ? { delegate: true } : {}) });
1600
+ }
1601
+ if ((v === 'defer' || v === 'go') && fam === 'go') { p.next(); return endStatement(p, { kind: v, value: p.expr(0) }); }
1602
+ if (v === 'delete' && isJs(lang)) { p.next(); return endStatement(p, { kind: 'delete', target: p.expr(16) }); }
1603
+ if (v === 'del' && fam === 'py') { p.next(); return endStatement(p, { kind: 'delete', target: valueList(p) }); }
1604
+ if (v === 'assert' && (fam === 'py' || lang === 'java')) {
1605
+ p.next();
1606
+ const test = p.expr(0);
1607
+ let message = null;
1608
+ if (p.isOp(fam === 'py' ? ',' : ':')) { p.next(); message = p.expr(0); }
1609
+ return endStatement(p, { kind: 'assert', test, ...(message ? { message } : {}) });
1610
+ }
1611
+ if (v === 'with' && fam === 'py') return pyWith(p);
1612
+ if (v === 'async' && fam === 'py' && (p.isId('with', 1) || p.isId('for', 1) || p.isId('def', 1))) { p.next(); const s = statement(p); return { ...s, async: true }; }
1613
+ if (v === 'pass' && fam === 'py') { p.next(); return endStatement(p, { kind: 'pass' }); }
1614
+ if (v === 'def' || (v === 'function' && p.peek(1).t === 'id') || (v === 'func' && p.peek(1).t === 'id') || (v === 'fn' && fam === 'rs') || (v === 'fun' && lang === 'kotlin') || (v === 'async' && isJs(lang) && p.isId('function', 1) && p.peek(2).t === 'id')) return functionHeader(p);
1615
+ if (/^(?:class|struct|interface|enum|impl|trait|object|record|module|type|namespace|import|export|from|package|use|using|lock|synchronized|unsafe|goto|static|public|private|protected|internal|abstract|override|virtual|final|readonly|global|nonlocal|extern|template|typedef|label)$/.test(v) && !(p.isOp('(', 1) && !/^(?:using|lock|synchronized)$/.test(v)) && !(p.isOp('.', 1)) && !(p.peek(1).t === 'op' && (ASSIGN_OPS.has(p.peek(1).v) || p.peek(1).v === ',' || p.peek(1).v === '['))) {
1616
+ if (v === 'export' && (p.isId('const', 1) || p.isId('let', 1) || p.isId('function', 1))) { p.next(); return statement(p); }
1617
+ if ((v === 'global' || v === 'nonlocal') && fam === 'py') { p.next(); const names = []; while (p.peek().t === 'id') { names.push(p.next().v); if (p.isOp(',')) p.next(); } return endStatement(p, { kind: 'declare', names, scope: v }); }
1618
+ fail(`${v} declaration`);
1619
+ }
1620
+ if (fam === 'go' && (v === 'var' || v === 'const') && p.isOp('(', 1)) return goDeclBlock(p);
1621
+ if (/^(?:const|let|var|val|auto|my|local)$/.test(v) && (p.peek(1).t === 'id' || p.isOp('{', 1) || p.isOp('[', 1) || p.isOp('(', 1))) return declaration(p);
1622
+ if (fam === 'rb' && /^(?:attr_reader|attr_accessor|attr_writer|include|extend|require|require_relative|private|protected|public|puts|print|p|pp|raise|fail|alias|alias_method|define_method)$/.test(v) && p.peek(1).t !== 'eof' && !p.isOp('(', 1) && !p.isOp('.', 1) && !p.isOp('=', 1)) {
1623
+ p.next();
1624
+ return endStatement(p, { kind: 'call', callee: { kind: 'name', name: v }, args: rubyArgList(p), parens: false });
1625
+ }
1626
+ // Typed declarations: `Type name = value;` (Java, C#, C/C++, Dart).
1627
+ if (/^(?:java|csharp|c|cpp|dart)$/.test(lang) && typedDeclAhead(p)) return typedDeclaration(p);
1628
+ if (lang === 'php' && /^(?:echo|print)$/.test(v) && p.peek(1).t !== 'eof' && !p.isOp('(', 1)) { p.next(); const vs = valueList(p, true); return endStatement(p, { kind: 'call', callee: { kind: 'name', name: v }, args: vs.kind === 'array' && vs.form === 'tuple' ? vs.items : [vs], parens: false }); }
1629
+ }
1630
+ if (t.t === 'op' && t.v === '@') fail('annotation');
1631
+ const node = simpleStatement(p, { top: true });
1632
+ // A Ruby command call with arguments and no brackets: `render json: x`, `redirect_to root_path`.
1633
+ if (fam === 'rb' && p.peek().t !== 'eof' && (node.kind === 'name' || node.kind === 'member') && rubyCommandStart(p)) {
1634
+ return endStatement(p, { kind: 'call', callee: node, args: rubyArgList(p), parens: false });
1635
+ }
1636
+ if (node.kind === 'call' && p.peek().t === 'block') { p.next(); }
1637
+ return endStatement(p, node);
1638
+ }
1639
+
1640
+ function rubyCommandStart(p) {
1641
+ const t = p.peek();
1642
+ if (t.t === 'id') return !/^(?:if|unless|while|until|and|or|then|do|rescue|in)$/.test(t.v);
1643
+ if (t.t === 'str' || t.t === 'num') return true;
1644
+ if (t.t === 'op') return (t.v === '*' || t.v === '&' || t.v === '!' || t.v === '-' || t.v === '[' || t.v === '->') && t.sp && !p.peek(1).sp;
1645
+ return false;
1646
+ }
1647
+ function rubyArgList(p) {
1648
+ const out = [];
1649
+ for (;;) {
1650
+ const t = p.peek();
1651
+ if (t.t === 'eof' || (t.t === 'id' && /^(?:if|unless|do)$/.test(t.v))) break;
1652
+ if (t.t === 'id' && p.isOp(':', 1) && !p.peek(1).sp) { p.next(); p.next(); out.push({ kind: 'named', name: t.v, value: p.expr(0.6) }); }
1653
+ else if ((t.t === 'str') && p.isOp('=>', 1)) { const key = p.expr(0.6); p.eat('=>'); out.push({ kind: 'object', entries: [{ key, value: p.expr(0.6) }], form: 'hash', bare: true }); }
1654
+ else out.push(p.expr(0.6));
1655
+ if (p.isOp(',')) { p.next(); continue; }
1656
+ break;
1657
+ }
1658
+ if (p.isId('do')) { const blk = p.rubyDoBlock(); blk.trailing = true; out.push(blk); }
1659
+ return out;
1660
+ }
1661
+ function rubyCommandArgs(p, callee) {
1662
+ const args = rubyArgList(p);
1663
+ return args.length === 1 ? args[0] : { kind: 'call', callee, args, parens: false, form: 'raise-args' };
1664
+ }
1665
+
1666
+ function throwNode(value, cause, form) {
1667
+ const node = { kind: 'throw', ...(value ? { value } : {}), ...(cause ? { cause } : {}), ...(form !== 'throw' ? { form } : {}) };
1668
+ // What error, and the message people see (the first text argument).
1669
+ let v = value;
1670
+ if (v && v.kind === 'call' && v.form === 'raise-args') { const [e, msg] = v.args; if (e) node.error = flatName(e.kind === 'call' ? e.callee : e) ?? undefined; if (msg && msg.kind === 'literal' && msg.type === 'text') node.message = msg.value; return node; }
1671
+ if (v && v.kind === 'call') {
1672
+ const n = flatName(v.callee);
1673
+ if (n) node.error = n.split(/\.|::/).pop();
1674
+ const msg = v.args.find((a) => (a.kind === 'literal' && a.type === 'text') || a.kind === 'template');
1675
+ if (msg) node.message = msg.kind === 'literal' ? msg.value : templateText(msg);
1676
+ } else if (v && v.kind === 'name') node.error = v.name;
1677
+ if (node.error === undefined) delete node.error;
1678
+ return node;
1679
+ }
1680
+ const templateText = (t) => t.parts.map((x) => (typeof x === 'string' ? x : `{${sayFull(x.expr)}}`)).join('');
1681
+
1682
+ /** A statement with no keyword: an assignment, a call, an expression; Go `a, b := f()`; Python `a, b = c`. */
1683
+ function simpleStatement(p, { top = false } = {}) {
1684
+ const fam = p.fam;
1685
+ let left = p.expr(0.6);
1686
+ // Tuple targets: a, b = … / a, b := …
1687
+ if (p.isOp(',') && (fam === 'py' || fam === 'go' || fam === 'rb' || p.lang === 'lua')) {
1688
+ const items = [left];
1689
+ while (p.isOp(',')) { p.next(); if (p.peek().t === 'eof') break; items.push(p.expr(0.6)); }
1690
+ left = { kind: 'array', form: 'tuple', items };
1691
+ }
1692
+ const t = p.peek();
1693
+ if (t.t === 'op' && ASSIGN_OPS.has(t.v)) {
1694
+ p.next();
1695
+ const value = assignValue(p);
1696
+ return { kind: 'assign', op: t.v, target: left, value };
1697
+ }
1698
+ if (t.t === 'op' && t.v === ':' && fam === 'py' && top) {
1699
+ // x: int = 5 (an annotated name)
1700
+ p.next();
1701
+ const type = p.typeText(['=']);
1702
+ if (p.isOp('=')) { p.next(); return { kind: 'assign', op: '=', target: left, type, value: assignValue(p) }; }
1703
+ return { kind: 'declare', names: [flatName(left) ?? fail('annotation')], type };
1704
+ }
1705
+ if (left.kind === 'assign') return left;
1706
+ if (left.kind === 'array' && left.form === 'tuple' && fam === 'py' && top) return left;
1707
+ return left;
1708
+ }
1709
+ function assignValue(p) {
1710
+ // a = b = c (chained) and Python / Go multiple values: a, b = 1, 2
1711
+ const v = valueList(p);
1712
+ if (p.peek().t === 'op' && ASSIGN_OPS.has(p.peek().v) && p.peek().v === '=') { p.next(); return { kind: 'assign', op: '=', target: v, value: assignValue(p) }; }
1713
+ return v;
1714
+ }
1715
+ /** One value, or several separated by commas (Python / Go / Ruby return and assignment), as a tuple. */
1716
+ function valueList(p, always = false) {
1717
+ const first = p.expr(0.6);
1718
+ if (!p.isOp(',') || !(p.fam === 'py' || p.fam === 'go' || p.fam === 'rb' || always)) return first;
1719
+ const items = [first];
1720
+ while (p.isOp(',')) { p.next(); if (p.atEnd()) break; items.push(p.expr(0.6)); }
1721
+ return { kind: 'array', form: 'tuple', items };
1722
+ }
1723
+
1724
+ function declaration(p, inner = false) {
1725
+ const kw = p.next().v;
1726
+ const items = [];
1727
+ for (;;) {
1728
+ let target;
1729
+ let mutable = false;
1730
+ if (p.isId('mut') && p.fam === 'rs') { p.next(); mutable = true; }
1731
+ if (p.isOp('{') || p.isOp('[') || p.isOp('(')) target = pattern(p);
1732
+ else { const n = p.next(); if (n.t !== 'id') fail('a name'); target = { kind: 'name', name: n.v }; }
1733
+ let type = null;
1734
+ if (p.isOp(':')) { p.next(); type = p.typeText(['=']); }
1735
+ else if (p.fam === 'go' && !p.isOp('=') && !p.isOp(',') && !p.atEnd()) type = p.goType();
1736
+ if (p.isOp(',') && p.fam === 'go') {
1737
+ // var a, b int
1738
+ const names = [target];
1739
+ while (p.isOp(',')) { p.next(); names.push({ kind: 'name', name: p.next().v }); }
1740
+ if (!p.isOp('=') && !p.atEnd()) type = p.fam === 'go' ? p.goType() : p.typeText(['=']);
1741
+ target = { kind: 'array', form: 'tuple', items: names };
1742
+ }
1743
+ if (p.isOp('!') && p.lang === 'typescript') { p.next(); if (p.isOp(':')) { p.next(); type = p.typeText(['=']); } }
1744
+ let value = null;
1745
+ if (p.isOp('=')) { p.next(); value = p.fam === 'go' ? valueList(p) : p.expr(0.5); }
1746
+ items.push(value ? { kind: 'assign', op: '=', declare: kw, target, ...(type ? { type } : {}), ...(mutable ? { mutable } : {}), value } : { kind: 'declare', declare: kw, names: target.kind === 'name' ? [target.name] : [target], ...(type ? { type } : {}), ...(mutable ? { mutable } : {}) });
1747
+ if (p.isOp(',') && p.fam !== 'go') { p.next(); continue; }
1748
+ break;
1749
+ }
1750
+ const node = items.length === 1 ? items[0] : { kind: 'sequence', items };
1751
+ return inner ? node : endStatement(p, node);
1752
+ }
1753
+ /** Go `const ( a = 1; b int = 2 )` / `var ( … )`: one declaration per line, as a sequence. */
1754
+ function goDeclBlock(p) {
1755
+ const kw = p.next().v;
1756
+ p.eat('(');
1757
+ const items = [];
1758
+ while (!p.isOp(')')) {
1759
+ if (p.peek().t === 'eof') fail('unclosed declaration block');
1760
+ if (p.isOp(';')) { p.next(); continue; }
1761
+ const names = [];
1762
+ for (;;) { const n = p.next(); if (n.t !== 'id') fail('a name'); names.push({ kind: 'name', name: n.v }); if (p.isOp(',')) { p.next(); continue; } break; }
1763
+ const target = names.length === 1 ? names[0] : { kind: 'array', form: 'tuple', items: names };
1764
+ let type = null, value = null;
1765
+ if (!p.isOp('=') && !p.isOp(')') && !p.isOp(';') && !p.peek().nl) type = p.goType();
1766
+ if (p.isOp('=')) { p.next(); value = valueList(p); }
1767
+ items.push(value ? { kind: 'assign', op: '=', declare: kw, target, ...(type ? { type } : {}), value } : { kind: 'declare', declare: kw, names: names.map((x) => x.name), ...(type ? { type } : {}) });
1768
+ if (!p.isOp(')') && !p.isOp(';') && !p.peek().nl) fail('after a declaration');
1769
+ }
1770
+ p.next();
1771
+ return endStatement(p, { kind: 'sequence', items, block: kw });
1772
+ }
1773
+
1774
+ function pattern(p) {
1775
+ // { a, b: c, ...rest } / [a, , b] / (a, b): kept as the names it binds, with the shape as written.
1776
+ const open = p.next().v;
1777
+ const close = open === '{' ? '}' : open === '[' ? ']' : ')';
1778
+ const a = p.k - 1;
1779
+ let depth = 1;
1780
+ while (depth > 0) { const t = p.next(); if (t.t === 'eof') fail('pattern'); if (t.t === 'op' && '{[('.includes(t.v)) depth++; else if (t.t === 'op' && '}])'.includes(t.v)) depth--; }
1781
+ const text = p.text(a, p.k);
1782
+ const names = [...text.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, '').matchAll(/(?:^|[{[(,]\s*|\.\.\.)([A-Za-z_$][\w$]*)\s*(?=[,}\])=]|$)|:\s*([A-Za-z_$][\w$]*)\s*(?=[,}\]=])/g)].map((m) => m[1] || m[2]).filter(Boolean);
1783
+ void close;
1784
+ return { kind: 'pattern', text, names };
1785
+ }
1786
+ /** `[modifiers] [<T>] Type name(params) [throws X] {` (Java / C#) or `fun name(params): T {` (Kotlin) as a function header, or null. */
1787
+ function methodHeader(p) {
1788
+ const k0 = p.k;
1789
+ try {
1790
+ const mods = [];
1791
+ while (p.peek().t === 'id' && /^(?:public|private|protected|internal|static|final|abstract|override|virtual|sealed|async|synchronized|unsafe|open|suspend|inline|operator|default|native|strictfp|extern|new)$/.test(p.peek().v) && (p.peek(1).t === 'id' || p.isOp('<', 1))) mods.push(p.next().v);
1792
+ if (p.lang === 'kotlin') {
1793
+ if (!p.isId('fun')) { p.k = k0; return null; }
1794
+ p.next();
1795
+ if (p.isOp('<')) p.typeArgs();
1796
+ const name = p.next();
1797
+ if (name.t !== 'id' || !p.isOp('(')) { p.k = k0; return null; }
1798
+ p.next();
1799
+ const params = p.paramList(')');
1800
+ let returns = null;
1801
+ if (p.isOp(':')) { p.next(); returns = p.typeText(['{', '=']); }
1802
+ return { kind: 'function', name: name.v, params, ...(returns ? { returns } : {}), ...(mods.length ? { modifiers: mods } : {}), body: { kind: 'block' } };
1803
+ }
1804
+ let typeParams = null;
1805
+ if (p.isOp('<')) typeParams = p.typeArgs();
1806
+ const at = typedDeclAhead(p, true);
1807
+ if (at === false) { p.k = k0; return null; }
1808
+ const a = p.k;
1809
+ p.k += at;
1810
+ const returns = p.text(a, p.k);
1811
+ const name = p.next().v;
1812
+ p.eat('(');
1813
+ const params = p.paramList(')');
1814
+ if (p.isId('throws')) { p.next(); while (p.peek().t === 'id' || p.isOp(',') || p.isOp('.')) p.next(); }
1815
+ if (!p.isOp('{') && !p.isOp('=>') && p.peek().t !== 'eof' && p.peek().t !== 'block' && !p.isOp(';')) { p.k = k0; return null; }
1816
+ return { kind: 'function', name, params, returns, ...(typeParams ? { typeParams } : {}), ...(mods.length ? { modifiers: mods } : {}), body: { kind: 'block' } };
1817
+ } catch (e) { if (e instanceof Fail) { p.k = k0; return null; } throw e; }
1818
+ }
1819
+ function typedDeclAhead(p, method = false) {
1820
+ // Type name = …; Type<A, B>[] name; final Type name = …
1821
+ let o = 0;
1822
+ while (p.peek(o).t === 'id' && /^(?:final|static|readonly|const|volatile|var|unsigned|signed)$/.test(p.peek(o).v) && p.peek(o + 1).t === 'id') o++;
1823
+ if (p.peek(o).t !== 'id') return false;
1824
+ if (/^(?:return|throw|new|await|yield|case|goto|else|in|is|as|out|ref|params|this|base|super)$/.test(p.peek(o).v)) return false;
1825
+ o++;
1826
+ let depth = 0;
1827
+ for (let guard = 0; guard < 40; guard++) {
1828
+ const t = p.peek(o);
1829
+ if (t.t === 'op' && (t.v === '.' || t.v === '?' || t.v === '*' || t.v === '&') && depth === 0) { o++; if (p.peek(o).t === 'id' && t.v === '.') o++; continue; }
1830
+ if (t.t === 'op' && t.v === '<') { depth++; o++; continue; }
1831
+ if (t.t === 'op' && (t.v === '>' || t.v === '>>')) { depth -= t.v.length; o++; continue; }
1832
+ if (t.t === 'op' && t.v === '[' && p.isOp(']', o + 1)) { o += 2; continue; }
1833
+ if (depth > 0) { if (t.t === 'eof') return false; o++; continue; }
1834
+ break;
1835
+ }
1836
+ if (depth !== 0 || p.peek(o).t !== 'id') return false;
1837
+ const after = p.peek(o + 1);
1838
+ if (method) return after.t === 'op' && after.v === '(' ? o : false;
1839
+ return after.t === 'eof' || (after.t === 'op' && (after.v === '=' || after.v === ';' || after.v === ',')) ? o : false;
1840
+ }
1841
+ function typedDeclaration(p, inner = false) {
1842
+ const a = p.k;
1843
+ const at = typedDeclAhead(p);
1844
+ if (at === false) fail('typed declaration');
1845
+ p.k += at;
1846
+ const type = p.text(a, p.k);
1847
+ const items = [];
1848
+ for (;;) {
1849
+ const name = p.next().v;
1850
+ if (p.isOp('=')) { p.next(); items.push({ kind: 'assign', op: '=', declare: 'typed', type, target: { kind: 'name', name }, value: p.isOp('{') ? p.objectLit() : p.expr(0.6) }); }
1851
+ else items.push({ kind: 'declare', declare: 'typed', type, names: [name] });
1852
+ if (p.isOp(',')) { p.next(); continue; }
1853
+ break;
1854
+ }
1855
+ const node = items.length === 1 ? items[0] : { kind: 'sequence', items };
1856
+ return inner ? node : endStatement(p, node);
1857
+ }
1858
+
1859
+ function forHeader(p) {
1860
+ const fam = p.fam, lang = p.lang;
1861
+ p.next();
1862
+ if (fam === 'py' || fam === 'rb') {
1863
+ // for a, b in items:
1864
+ if (p.isId('await')) fail('async for');
1865
+ const targets = [];
1866
+ p.noIf = true;
1867
+ while (!p.isId('in')) { if (p.peek().t === 'eof') fail('for without in'); if (p.isOp(',')) { p.next(); continue; } targets.push(p.expr(8.5)); }
1868
+ p.next();
1869
+ const iterable = valueList(p);
1870
+ p.noIf = false;
1871
+ if (p.isId('do')) p.next();
1872
+ return headerEnd(p, { kind: 'loop', form: 'each', targets, iterable });
1873
+ }
1874
+ if (fam === 'go') {
1875
+ if (p.isOp('{') || p.peek().t === 'eof' || p.peek().t === 'block') return { kind: 'loop', form: 'forever' };
1876
+ // for k, v := range xs { / for i := 0; i < n; i++ { / for cond {
1877
+ p.noBrace = true;
1878
+ const k0 = p.k;
1879
+ let o = 0, hasRange = false, semis = 0;
1880
+ for (;; o++) { const t = p.peek(o); if (t.t === 'eof' || t.t === 'block' || (t.t === 'op' && t.v === '{')) break; if (t.t === 'id' && t.v === 'range') hasRange = true; if (t.t === 'op' && t.v === ';') semis++; }
1881
+ if (hasRange) {
1882
+ const targets = [];
1883
+ if (!p.isId('range')) { while (!p.isOp(':=') && !p.isOp('=')) { if (p.peek().t === 'eof') fail('range'); if (p.isOp(',')) { p.next(); continue; } targets.push(p.expr(8.5)); } p.next(); }
1884
+ p.next(); // range
1885
+ const iterable = p.expr(0);
1886
+ p.noBrace = false;
1887
+ return headerEnd(p, { kind: 'loop', form: 'each', targets, iterable, range: true });
1888
+ }
1889
+ if (semis === 2) {
1890
+ const init = p.isOp(';') ? null : simpleStatement(p);
1891
+ p.eat(';');
1892
+ const test = p.isOp(';') ? null : p.expr(0);
1893
+ p.eat(';');
1894
+ const update = p.isOp('{') || p.peek().t === 'block' || p.peek().t === 'eof' ? null : simpleStatement(p);
1895
+ p.noBrace = false;
1896
+ return headerEnd(p, { kind: 'loop', form: 'for', ...(init ? { init } : {}), ...(test ? { test } : {}), ...(update ? { update } : {}) });
1897
+ }
1898
+ void k0;
1899
+ const test = p.expr(0);
1900
+ p.noBrace = false;
1901
+ return headerEnd(p, { kind: 'loop', form: 'while', test });
1902
+ }
1903
+ if (fam === 'rs') {
1904
+ const targets = [];
1905
+ if (p.isOp('(')) targets.push(pattern(p)); else targets.push({ kind: 'name', name: p.next().v });
1906
+ if (!p.isId('in')) fail('for without in');
1907
+ p.next();
1908
+ p.noBrace = true;
1909
+ const iterable = p.expr(0);
1910
+ p.noBrace = false;
1911
+ return headerEnd(p, { kind: 'loop', form: 'each', targets, iterable });
1912
+ }
1913
+ // C family: for (init; test; update) / for (const x of xs) / for (x in xs) / for (Type x : xs) / foreach (var x in xs)
1914
+ if (p.isId('await')) { p.next(); }
1915
+ p.eat('(');
1916
+ let semi = false;
1917
+ for (let o = 0, d = 0; ; o++) { const t = p.peek(o); if (t.t === 'eof') break; if (t.t === 'op') { if ('([{'.includes(t.v)) d++; else if (')]}'.includes(t.v)) { if (d === 0) break; d--; } else if (t.v === ';' && d === 0) { semi = true; break; } } }
1918
+ if (semi) {
1919
+ const init = p.isOp(';') ? null : (/^(?:const|let|var)$/.test(p.peek().v) ? declaration(p, true) : typedDeclAhead(p) ? typedDeclaration(p, true) : simpleStatement(p));
1920
+ if (p.isOp(';')) p.next();
1921
+ const test = p.isOp(';') ? null : p.expr(0);
1922
+ p.eat(';');
1923
+ const updates = [];
1924
+ while (!p.isOp(')')) { updates.push(simpleStatement(p)); if (p.isOp(',')) p.next(); else break; }
1925
+ p.eat(')');
1926
+ const update = updates.length === 1 ? updates[0] : updates.length ? { kind: 'sequence', items: updates } : null;
1927
+ return headerEnd(p, { kind: 'loop', form: 'for', ...(init ? { init } : {}), ...(test ? { test } : {}), ...(update ? { update } : {}) });
1928
+ }
1929
+ if (lang === 'php') {
1930
+ const iterable = p.expr(0.6);
1931
+ if (!p.isId('as')) fail('foreach without as');
1932
+ p.next();
1933
+ const targets = [p.expr(0.6)];
1934
+ if (p.isOp('=>')) { p.next(); targets.push(p.expr(0.6)); }
1935
+ p.eat(')');
1936
+ return headerEnd(p, { kind: 'loop', form: 'each', targets, iterable });
1937
+ }
1938
+ let declare = null;
1939
+ if (p.peek().t === 'id' && /^(?:const|let|var|val|final|auto)$/.test(p.peek().v) && (p.peek(1).t === 'id' || p.isOp('[', 1) || p.isOp('{', 1) || p.isOp('(', 1))) declare = p.next().v;
1940
+ // Java/C#: the element's type before its name.
1941
+ let type = null;
1942
+ if (p.peek().t === 'id' && !declare) {
1943
+ const k0 = p.k;
1944
+ let o = 0;
1945
+ while (p.peek(o).t === 'id' || (p.peek(o).t === 'op' && /^(?:\.|<|>|\[|\]|,|\?)$/.test(p.peek(o).v))) { if (p.peek(o).t === 'id' && (/^(?:of|in)$/.test(p.peek(o).v))) break; if (p.isOp(':', o)) break; o++; }
1946
+ if (o >= 2 && p.peek(o - 1).t === 'id') { type = p.text(k0, k0 + o - 1); p.k = k0 + o - 1; }
1947
+ }
1948
+ const targets = [];
1949
+ if (p.isOp('[') || p.isOp('{') || p.isOp('(')) targets.push(pattern(p));
1950
+ else { const n = p.next(); if (n.t !== 'id') fail('loop name'); targets.push({ kind: 'name', name: n.v }); }
1951
+ if (p.isOp(':') && lang === 'kotlin') { p.next(); p.typeText(['in']); }
1952
+ let form;
1953
+ if (p.isId('of')) form = 'of'; else if (p.isId('in')) form = 'in'; else if (p.isOp(':')) form = ':'; else fail('loop');
1954
+ p.next();
1955
+ const iterable = p.expr(0);
1956
+ p.eat(')');
1957
+ return headerEnd(p, { kind: 'loop', form: 'each', targets, iterable, ...(form !== 'of' && form !== ':' && isJs(lang) ? { keys: true } : {}), ...(declare ? { declare } : {}), ...(type ? { type } : {}) });
1958
+ }
1959
+
1960
+ function pyWith(p) {
1961
+ p.next();
1962
+ const items = [];
1963
+ for (;;) {
1964
+ const value = p.expr(0.6);
1965
+ let as = null;
1966
+ if (p.isId('as')) { p.next(); as = p.expr(8.5); }
1967
+ items.push({ value, ...(as ? { as } : {}) });
1968
+ if (p.isOp(',')) { p.next(); continue; }
1969
+ break;
1970
+ }
1971
+ return headerEnd(p, { kind: 'with', items });
1972
+ }
1973
+
1974
+ function functionHeader(p) {
1975
+ let async = false;
1976
+ if (p.isId('async')) { p.next(); async = true; }
1977
+ const kw = p.next().v;
1978
+ if (kw === 'func' && p.isOp('(')) fail('method');
1979
+ const name = p.next();
1980
+ if (name.t !== 'id') fail('function name');
1981
+ if (p.isOp('<') || p.isOp('[')) { const close = p.isOp('<') ? '>' : ']'; p.next(); p.paramList(close); }
1982
+ p.eat('(');
1983
+ const params = p.paramList(')');
1984
+ // What it gives back, when written: `-> int:` (Python), `: Promise<T> {` (TypeScript), `(int, error) {` (Go).
1985
+ let returns = null;
1986
+ if (p.isOp('->') || (p.isOp(':') && p.fam === 'c') || (p.fam === 'go' && !p.isOp('{') && p.peek().t !== 'eof' && p.peek().t !== 'block')) {
1987
+ if (p.fam !== 'go') p.next();
1988
+ const a = p.k;
1989
+ while (p.peek().t !== 'eof' && p.peek().t !== 'block' && !p.isOp('{') && !(p.fam === 'py' && p.isOp(':') && p.peek(1).t === 'eof')) p.next();
1990
+ if (p.k > a) returns = p.text(a, p.k);
1991
+ }
1992
+ return { kind: 'function', name: name.v, params, ...(returns ? { returns } : {}), ...(async ? { async } : {}), body: { kind: 'block' } };
1993
+ }
1994
+
1995
+ // ── Walking, counting, normalizing ───────────────────────────────────────────────────────────────────────────
1996
+
1997
+ /** Every node in a tree (depth first). */
1998
+ export function* nodesOf(node) {
1999
+ if (!node || typeof node !== 'object') return;
2000
+ if (Array.isArray(node)) { for (const x of node) yield* nodesOf(x); return; }
2001
+ if (node.kind) yield node;
2002
+ for (const k of Object.keys(node)) {
2003
+ const v = node[k];
2004
+ if (v && typeof v === 'object') yield* nodesOf(v);
2005
+ }
2006
+ }
2007
+
2008
+ const NEG_NAME = /^(?:not|no|non|never|cannot|none)$/;
2009
+ const nameWords = (name) => String(name).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().split(/\s+/).filter(Boolean);
2010
+ const isNullLit = (n) => n && n.kind === 'literal' && n.type === 'null';
2011
+
2012
+ /**
2013
+ * What the faithfulness gate counts, read from the tree instead of the text: negations (`!`, `not`, `!=`, `!==`,
2014
+ * `is not`, `not in`, and negative words inside names), and/or joins, and comparisons. A loose `!= null` (`is not
2015
+ * None`, `!= nil`) is "is set": one comparison, no negation, as the gate has always counted it.
2016
+ */
2017
+ export function exprCounts(tree) {
2018
+ let neg = 0, logic = 0, compare = 0;
2019
+ for (const n of nodesOf(tree)) {
2020
+ if (n.kind === 'not') neg++;
2021
+ else if (n.kind === 'logic') logic += n.operands.length - 1;
2022
+ else if (n.kind === 'compare' || n.kind === 'chain') {
2023
+ for (const op of n.kind === 'chain' ? n.ops : [n.op]) {
2024
+ const loose = (op === '!=' || op === 'is not' || op === '<>') && (isNullLit(n.right) || isNullLit(n.left)) && !(op === '!==' );
2025
+ const strictNilish = op === '!==' && (isNullLit(n.right) && /^(?:nil|None)$/.test(n.right.raw));
2026
+ compare++;
2027
+ if ((op === '!=' || op === '!==' || op === 'is not' || op === 'not in' || op === '<>' || op === '!is' || op === '!in') && !loose && !strictNilish) neg++;
2028
+ }
2029
+ } else if (n.kind === 'name' || (n.kind === 'member')) {
2030
+ const w = n.kind === 'name' ? n.name : n.property;
2031
+ if (/^(?:not|and|or|is|in|instanceof|typeof|true|false|null|nil|None|undefined|this|self|new|await)$/.test(w)) continue;
2032
+ for (const x of nameWords(w)) if (NEG_NAME.test(x)) neg++;
2033
+ }
2034
+ }
2035
+ return { neg, logic, compare };
2036
+ }
2037
+
2038
+ /** A tree with spelling removed (quote style, spacing in types and parameters), so equal meaning compares equal. */
2039
+ export function normalizeExpr(node) {
2040
+ if (Array.isArray(node)) return node.map(normalizeExpr);
2041
+ if (!node || typeof node !== 'object') return node;
2042
+ const out = {};
2043
+ for (const k of Object.keys(node).sort()) {
2044
+ const v = node[k];
2045
+ if (k === 'raw' && node.kind === 'literal' && node.type !== 'number' && !node.interpolated) continue;
2046
+ if (k === 'raw' && node.kind === 'template') continue;
2047
+ if (k === 'raw' && node.kind === 'literal' && node.type === 'number' && node.value != null) continue;
2048
+ // Layout, not meaning: a one-line body (`if (a) return b;`) is the step's own child either way.
2049
+ if (k === 'spelled' || k === 'inline') continue;
2050
+ if (typeof v === 'string' && (k === 'type' || k === 'text' || k === 'typeArgs' || k === 'returns') && node.kind !== 'literal') { out[k] = v.replace(/\s+/g, ''); continue; }
2051
+ if (k === 'params' && Array.isArray(v)) { out[k] = v.map((x) => String(x).replace(/\s+/g, '')); continue; }
2052
+ out[k] = normalizeExpr(v);
2053
+ }
2054
+ return out;
2055
+ }
2056
+ /** True when two trees mean the same (after normalizing spelling). */
2057
+ export function sameExpr(a, b) { return JSON.stringify(normalizeExpr(a)) === JSON.stringify(normalizeExpr(b)); }
2058
+
2059
+ // ── Every detail in plain, neutral form ──────────────────────────────────────────────────────────────────────
2060
+
2061
+ const PREC = { conditional: 1, logicor: 2, logicand: 3, not: 4, compare: 5, '??': 1.5, '|': 6, '^': 6, '&': 6, '<<': 7, '>>': 7, '>>>': 7, '+': 8, '-': 8, '.': 8, '*': 9, '/': 9, '//': 9, '%': 9, '@': 9, '&^': 9, '**': 10, '..': 5.5, '..=': 5.5, '..<': 5.5, '...': 5.5, '<=>': 5 };
2062
+ const precOf = (n) => (n.kind === 'conditional' || n.kind === 'lambda' || n.kind === 'assign' ? 1 : n.kind === 'logic' ? (n.op === 'or' ? 2 : 3) : n.kind === 'not' ? 4 : n.kind === 'compare' || n.kind === 'chain' ? 5 : n.kind === 'binary' ? PREC[n.op] ?? 8 : n.kind === 'cast' ? 9.5 : n.kind === 'unary' && !n.postfix ? 11 : 12);
2063
+ const lit = (n) => (n.type === 'text' ? JSON.stringify(n.value) : n.type === 'char' ? n.raw : n.type === 'symbol' ? `:${n.value}` : n.type === 'null' ? (n.raw || 'null') : n.type === 'bool' ? String(n.value) : n.raw ?? String(n.value));
2064
+ const NEUTRAL_OP = { '===': '===', '!==': '!==', '==': '==', '!=': '!=', '<>': '!=', 'not in': 'not in', 'is not': 'is not', '!in': 'not in', '!is': 'is not', instanceof: 'is a' };
2065
+
2066
+ /**
2067
+ * Every detail of a tree as one line of neutral, readable code: calls with every argument, values with every key, logic
2068
+ * as and / or / not. This is what Details and the full Thunder Text show under the short words.
2069
+ */
2070
+ export function sayFull(n, outer = 0) {
2071
+ if (!n) return '';
2072
+ const wrap = (s, p) => (p < outer ? `(${s})` : s);
2073
+ switch (n.kind) {
2074
+ case 'code': return `\`${n.text}\``;
2075
+ case 'name': return n.name;
2076
+ case 'literal': return lit(n);
2077
+ case 'template': return `"${n.parts.map((x) => (typeof x === 'string' ? x.replace(/"/g, '\\"') : `{${sayFull(x.expr)}}`)).join('')}"`;
2078
+ case 'member': return `${sayFull(n.object, 12)}${n.static ? '::' : '.'}${n.property}`;
2079
+ case 'index': return `${sayFull(n.object, 12)}[${n.index.kind === 'slice' ? sayFull(n.index) : sayFull(n.index)}]`;
2080
+ case 'slice': return `${n.start ? sayFull(n.start) : ''}:${n.end ? sayFull(n.end) : ''}${n.step ? `:${sayFull(n.step)}` : ''}`;
2081
+ case 'call': {
2082
+ const callee = n.callee.kind === 'name' && n.callee.name === '' ? '' : sayFull(n.callee, 12);
2083
+ return `${n.new ? 'new ' : ''}${callee}(${n.args.map((a) => sayFull(a)).join(', ')})${n.init ? ` { ${n.init.map((e) => (e.key ? `${sayFull(e.key)} = ${sayFull(e.value)}` : sayFull(e.value))).join(', ')} }` : ''}`;
2084
+ }
2085
+ case 'named': return `${n.name}: ${sayFull(n.value)}`;
2086
+ case 'spread': return `...${sayFull(n.value, 11)}`;
2087
+ case 'hole': return '';
2088
+ case 'not': return wrap(`not ${sayFull(n.value, 5)}`, 4);
2089
+ case 'unary': return n.postfix ? `${sayFull(n.value, 12)}${n.op}` : wrap(`${n.op}${/^[a-z]/.test(n.op) ? ' ' : ''}${sayFull(n.value, 11)}`, 11);
2090
+ case 'logic': return wrap(n.operands.map((x) => sayFull(x, n.op === 'or' ? 3 : 4)).join(` ${n.op} `), n.op === 'or' ? 2 : 3);
2091
+ case 'compare': return wrap(`${sayFull(n.left, 6)} ${NEUTRAL_OP[n.op] ?? n.op} ${sayFull(n.right, 6)}`, 5);
2092
+ case 'chain': return wrap(n.operands.map((x, i) => (i ? `${NEUTRAL_OP[n.ops[i - 1]] ?? n.ops[i - 1]} ${sayFull(x, 6)}` : sayFull(x, 6))).join(' '), 5);
2093
+ case 'binary': { const p = PREC[n.op] ?? 8; return wrap(`${sayFull(n.left, p)} ${n.op === '??' ? 'or else' : n.op} ${sayFull(n.right, p + 0.5)}`, p); }
2094
+ case 'conditional': return wrap(`${sayFull(n.then, 2)} if ${sayFull(n.test, 2)}, otherwise ${sayFull(n.else, 1)}`, 1);
2095
+ case 'array': {
2096
+ const items = n.items.map((x) => sayFull(x)).join(', ');
2097
+ return n.form === 'tuple' ? `(${items})` : n.form === 'set' ? `set {${items}}` : `${n.type ? n.type : ''}[${items}]`;
2098
+ }
2099
+ case 'object': if (!n.entries.length) return `${n.type ? `${n.type} ` : ''}{}`; return `${n.type ? `${n.type} ` : ''}{ ${n.entries.map((e) => (e.kind === 'spread' ? `...${sayFull(e.value)}` : e.shorthand ? sayFull(e.value) : `${e.computed ? `[${sayFull(e.key)}]` : e.key?.kind === 'literal' && e.key.type === 'text' && /^[A-Za-z_$][\w$]*$/.test(e.key.value) ? e.key.value : sayFull(e.key)}: ${sayFull(e.value)}`)).join(', ')} }`;
2100
+ case 'comprehension': return `[${n.key ? `${sayFull(n.key)}: ` : ''}${sayFull(n.item)} ${n.clauses.map((c) => `for each ${c.targets.map((t) => sayFull(t)).join(', ')} in ${sayFull(c.iter)}${(c.conds || []).map((x) => ` where ${sayFull(x)}`).join('')}`).join(' ')}]`;
2101
+ case 'lambda': return wrap(`(${n.params.join(', ')})${n.returns ? `: ${n.returns}` : ''} => ${n.body.kind === 'block' ? 'the steps below' : sayFull(n.body, 1)}`, 1);
2102
+ case 'cast': return n.form === 'nonnull' ? sayFull(n.value, outer) : wrap(`${sayFull(n.value, 10)} as ${n.type}`, 9.5);
2103
+ case 'assign': return wrap(`${sayFull(n.target)} ${n.op === ':=' || n.op === '=' ? '=' : n.op} ${sayFull(n.value)}`, 1);
2104
+ case 'pattern': return n.text;
2105
+ case 'jsx': return `<${n.tag}${n.attrs.map((a) => (a.spread ? ` {...${sayFull(a.spread)}}` : a.value ? ` ${a.name}=${a.value.kind === 'literal' ? JSON.stringify(a.value.value) : `{${sayFull(a.value)}}`}` : ` ${a.name}`)).join('')}${n.children.length ? `>${n.children.map((c) => (typeof c === 'string' ? c : c.kind === 'jsx-value' ? `{${sayFull(c.value)}}` : sayFull(c))).join('')}</${n.tag}>` : ' />'}`;
2106
+ case 'jsx-value': return `{${sayFull(n.value)}}`;
2107
+ case 'yield': return `yield ${n.value ? sayFull(n.value) : ''}`.trim();
2108
+ case 'block': return 'the steps below';
2109
+ default: return statementFull(n);
2110
+ }
2111
+ }
2112
+
2113
+ function statementFull(n) {
2114
+ switch (n.kind) {
2115
+ case 'return': return n.value ? `return ${sayFull(n.value)}` : 'return';
2116
+ case 'throw': return n.value ? `fail with ${sayFull(n.value)}` : 'fail again with the same error';
2117
+ case 'if': return `if ${n.init ? `${sayFull(n.init)}; ` : ''}${n.negate ? 'not ' : ''}${sayFull(n.test, n.negate ? 5 : 0)}`;
2118
+ case 'loop': return n.form === 'each' ? `for each ${n.targets.map((t) => sayFull(t)).join(', ')} in ${sayFull(n.iterable)}` : n.form === 'for' ? `for (${n.init ? sayFull(n.init) : ''}; ${n.test ? sayFull(n.test) : ''}; ${n.update ? sayFull(n.update) : ''})` : n.form === 'forever' ? 'repeat' : `${n.form === 'until' ? 'until' : 'while'} ${sayFull(n.test)}`;
2119
+ case 'switch': return n.subject ? `choose by ${sayFull(n.subject)}` : 'check these cases in order';
2120
+ case 'case': return n.default ? 'otherwise' : `when ${n.patterns.map((x) => sayFull(x)).join(' or ')}${n.guard ? ` and ${sayFull(n.guard)}` : ''}`;
2121
+ case 'try': return 'try';
2122
+ case 'jump': return `${n.jump}${n.label ? ` ${n.label}` : ''}`;
2123
+ case 'defer': return `at the end: ${sayFull(n.value)}`;
2124
+ case 'go': return `alongside: ${sayFull(n.value)}`;
2125
+ case 'delete': return `remove ${sayFull(n.target)}`;
2126
+ case 'assert': return `check ${sayFull(n.test)}${n.message ? `, else ${sayFull(n.message)}` : ''}`;
2127
+ case 'with': return `with ${n.items.map((i) => `${sayFull(i.value)}${i.as ? ` as ${sayFull(i.as)}` : ''}`).join(', ')}`;
2128
+ case 'function': return `${n.name}(${n.params.join(', ')})${n.returns ? `: ${n.returns}` : ''}`;
2129
+ case 'catch': return `catch ${n.errors.length ? n.errors.join(' or ') : 'any error'}${n.as ? ` as ${n.as}` : ''}`;
2130
+ case 'declare': return `${n.names.map((x) => (typeof x === 'string' ? x : sayFull(x))).join(', ')}${n.type ? `: ${n.type}` : ''}`;
2131
+ case 'sequence': return n.items.map((x) => sayFull(x)).join('; ');
2132
+ case 'pass': return 'nothing';
2133
+ default: return `\`${n.kind}\``;
2134
+ }
2135
+ }
2136
+
2137
+ // What the short words leave out, by kind: the parts of the tree a reader can open one level down.
2138
+ const wordsOfText = (s) => ` ${String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_\-.$:]+/g, ' ').replace(/[^\w\s]+/g, ' ').toLowerCase().replace(/\s+/g, ' ').trim()} `;
2139
+ /** The names and values in a tree, as a reader would look for them in words. */
2140
+ export function namesIn(tree) {
2141
+ const out = [];
2142
+ for (const n of nodesOf(tree)) {
2143
+ if (n.kind === 'name' && n.name && !/^(?:self|this)$/.test(n.name)) out.push(n.name);
2144
+ else if (n.kind === 'member') out.push(n.property);
2145
+ else if (n.kind === 'named') out.push(n.name);
2146
+ else if (n.kind === 'literal' && (n.type === 'number' || n.type === 'bool')) out.push(String(n.raw ?? n.value));
2147
+ else if (n.kind === 'literal' && n.type === 'text' && n.value.length < 40) out.push(n.value);
2148
+ // Written as text in the tree: parameters, types, the names a pattern or declaration binds.
2149
+ if (n.kind === 'lambda' || n.kind === 'function') out.push(...n.params, ...(n.returns ? [n.returns] : []), ...(n.name ? [n.name] : []));
2150
+ if (typeof n.type === 'string' && n.kind !== 'literal') out.push(n.type);
2151
+ if (n.kind === 'pattern') out.push(...n.names);
2152
+ if (n.kind === 'declare') out.push(...n.names.filter((x) => typeof x === 'string'));
2153
+ if (n.kind === 'catch') out.push(...n.errors, ...(n.as ? [n.as] : []));
2154
+ if (n.kind === 'jsx') { if (n.tag) out.push(n.tag); for (const a of n.attrs) if (a.name) out.push(a.name); for (const c of n.children) if (typeof c === 'string' && c.length < 40) out.push(c); }
2155
+ }
2156
+ return out.flatMap((x) => (/^[\w$]+$/.test(x) ? [x] : String(x).match(/[A-Za-z_$][\w$]*/g) || []));
2157
+ }
2158
+ const missingFrom = (said, tree) => {
2159
+ const sw = wordsOfText(said);
2160
+ return namesIn(tree).some((x) => { const w = wordsOfText(x).trim(); return w && !sw.includes(` ${w} `); });
2161
+ };
2162
+
2163
+ /**
2164
+ * The details a step's short words leave out, as parts of one sentence: [{ label, text }] (empty when the words already
2165
+ * say everything). Built only from the step's `expr`.
2166
+ */
2167
+ export function detailParts(step) {
2168
+ const e = step?.expr;
2169
+ if (!e) return [];
2170
+ const said = step.says || '';
2171
+ const parts = [];
2172
+ // A step shown as code: the whole statement (the short form may be cut), or what the code means when it was read.
2173
+ if (step.kind === 'other' || step.restates) {
2174
+ if (e.kind === 'code') { if (e.text && e.text !== String(step.code ?? '').replace(/\s+/g, ' ').trim()) parts.push({ label: 'code', text: e.text }); }
2175
+ else parts.push({ label: 'means', text: sayFull(e) });
2176
+ return parts;
2177
+ }
2178
+ const add = (label, node) => { if (node && missingFrom(said, node)) parts.push({ label, text: sayFull(node) }); };
2179
+ const core = e.kind === 'unary' && e.op === 'await' ? e.value : e;
2180
+ switch (core.kind) {
2181
+ case 'code': parts.push({ label: 'code', text: core.text }); break;
2182
+ case 'call': {
2183
+ // The words name the call ("Calls save"): only the arguments are added. When they do not name it (a library
2184
+ // phrase, "Runs the parent version first"), the whole call is shown: what is called, on what, with what.
2185
+ const name = core.callee.kind === 'member' ? core.callee.property : core.callee.kind === 'name' ? core.callee.name : null;
2186
+ if (!name || missingFrom(said, { kind: 'name', name }) || (core.callee.kind === 'member' && missingFrom(said, core.callee.object))) {
2187
+ if (missingFrom(said, core)) parts.push({ label: 'calls', text: sayFull(core) });
2188
+ if (core.init) parts.push({ label: 'filled with', text: core.init.map((x) => (x.key ? `${sayFull(x.key)} = ${sayFull(x.value)}` : sayFull(x.value))).join(', ') });
2189
+ break;
2190
+ }
2191
+ const args = core.args.filter((a) => !(a.kind === 'lambda' && a.body.kind === 'block'));
2192
+ if (args.length && args.some((a) => missingFrom(said, a))) parts.push({ label: 'with', text: args.map((a) => sayFull(a)).join(', ') });
2193
+ for (const a of core.args) if (a.kind === 'lambda' && a.body.kind === 'block' && a.params.length && missingFrom(said, { kind: 'array', items: a.params.map((x) => ({ kind: 'name', name: x })) })) parts.push({ label: 'each step gets', text: a.params.join(', ') });
2194
+ if (core.init) parts.push({ label: 'filled with', text: core.init.map((x) => (x.key ? `${sayFull(x.key)} = ${sayFull(x.value)}` : sayFull(x.value))).join(', ') });
2195
+ break;
2196
+ }
2197
+ case 'assign': add('target', core.target); if (core.type && !wordsOfText(said).includes(` ${wordsOfText(core.type).trim()} `)) parts.push({ label: 'a', text: core.type }); add(core.op === '=' || core.op === ':=' ? 'value' : `${core.op} by`, core.value); break;
2198
+ case 'sequence': for (const x of core.items) { if (x.kind === 'assign') { add('target', x.target); add('value', x.value); } else add('declares', x); } break;
2199
+ case 'return': add('value', core.value); break;
2200
+ case 'yield': add('value', core.value); break;
2201
+ case 'throw': if (core.value) add('error', core.value); if (core.cause) add('caused by', core.cause); break;
2202
+ case 'if': if (core.init) add('first', core.init); add('condition', core.test); break;
2203
+ case 'loop': if (core.form === 'each') { add('each', { kind: 'array', items: core.targets }); add('in', core.iterable); } else { if (core.init) add('starts', core.init); if (core.test) add('while', core.test); if (core.update) add('each time', core.update); } break;
2204
+ case 'switch': add('by', core.subject); break;
2205
+ case 'case': for (const x of core.patterns || []) add('when', x); if (core.guard) add('and', core.guard); break;
2206
+ case 'assert': add('checks', core.test); add('message', core.message); break;
2207
+ case 'delete': add('removes', core.target); break;
2208
+ case 'with': for (const i of core.items) { add('uses', i.value); add('as', i.as); } break;
2209
+ case 'function': if (missingFrom(said, { kind: 'lambda', params: core.params, returns: core.returns, body: { kind: 'block' } })) { parts.push({ label: 'takes', text: core.params.join(', ') || 'nothing' }); if (core.returns) parts.push({ label: 'gives back', text: core.returns }); } break;
2210
+ case 'defer': case 'go': add('runs', core.value); break;
2211
+ case 'jump': case 'try': case 'pass': break;
2212
+ default: add('value', core); break;
2213
+ }
2214
+ return parts;
2215
+ }
2216
+
2217
+ /** The step's short words with every omitted detail after them: "Calls save — with: order, { validate: false }". */
2218
+ export function detailOf(step) {
2219
+ const parts = detailParts(step);
2220
+ if (!parts.length) return null;
2221
+ return `${step.says} — ${parts.map((x) => `${x.label}: ${x.text}`).join('; ')}`;
2222
+ }
2223
+
2224
+ // ── Words agree with the tree ────────────────────────────────────────────────────────────────────────────────
2225
+
2226
+ /**
2227
+ * Do a step's words agree with its tree? Every number and quoted text in the words must be a value in the tree, and a
2228
+ * step that says "Calls X" must call X. Returns the disagreements (empty when they agree). Steps shown as code agree.
2229
+ */
2230
+ export function wordsAgree(step) {
2231
+ const e = step?.expr;
2232
+ const out = [];
2233
+ if (!e || e.kind === 'code' || step.kind === 'other' || step.restates) return out;
2234
+ const said = String(step.says || '').replace(/\bor \d+ other values?\b/g, '').replace(/\(\d+ steps? inside\)/g, '');
2235
+ const says = said.replace(/`[^`]*`/g, '');
2236
+ const values = [];
2237
+ for (const n of nodesOf(e)) {
2238
+ if (n.kind === 'literal') values.push(String(n.raw ?? ''), String(n.value ?? ''));
2239
+ else if (n.kind === 'template') { values.push(n.raw ?? ''); for (const x of n.parts) if (typeof x === 'string') values.push(x); }
2240
+ else if (n.kind === 'code') values.push(n.text);
2241
+ else if (n.kind === 'pattern') values.push(n.text);
2242
+ }
2243
+ const all = values.join('\n');
2244
+ // Numbers: in any literal (or a name/text that contains it: `http2`, `"v1"`), or the small counts Thunder writes itself.
2245
+ const flatText = `${all}\n${namesIn(e).join(' ')}\n${typeof e.type === 'string' ? e.type : ''}`;
2246
+ for (const num of says.match(/(?<![\w.])-?\d+(?:\.\d+)?(?![\w.])/g) || []) if (!flatText.includes(num.replace(/^-/, '')) && !/^(?:0|1)$/.test(num) && !/^[2-5]\d\d$/.test(num)) out.push(`number ${num} is not in the code`);
2247
+ for (const q of said.match(/"[^"]{0,80}"/g) || []) {
2248
+ // (A quote mark that is itself a value, `'"'`, cannot be paired: skip it.)
2249
+ if (q.length < 3 || /^"'|'"$/.test(q)) continue;
2250
+ const inner = q.slice(1, -1).replace(/…$/, '');
2251
+ const parts = inner.split(/…|`/).map((x) => x.trim()).filter((x) => x.length > 2);
2252
+ if (parts.length && !parts.every((x) => flatText.includes(x) || flatText.includes(x.replace(/"/g, '\\"')))) out.push(`text ${q} is not in the code`);
2253
+ }
2254
+ const call = /^Calls ([\w ]+?)(?: with these steps|:.*)?$/.exec(says);
2255
+ const core = e.kind === 'unary' && e.op === 'await' ? e.value : e;
2256
+ if (call && core.kind === 'call') {
2257
+ const last = core.callee.kind === 'member' ? core.callee.property : core.callee.kind === 'name' ? core.callee.name : null;
2258
+ if (last && wordsOfText(last).trim() !== call[1].trim().toLowerCase() && !wordsOfText(sayFull(core.callee)).includes(` ${call[1].trim().toLowerCase()} `)) out.push(`says it calls ${call[1]}, the code calls ${last}`);
2259
+ }
2260
+ return out;
2261
+ }
2262
+
2263
+ // ── Code again: TypeScript / JavaScript, Python, Go ──────────────────────────────────────────────────────────
2264
+
2265
+ export const RENDER_LANGUAGES = ['typescript', 'javascript', 'python', 'go'];
2266
+
2267
+ const RP = {
2268
+ // Binding strength in each target, for brackets: higher binds tighter.
2269
+ c: { assign: 1, conditional: 2, '??': 3, or: 4, and: 5, '|': 6, '^': 7, '&': 8, eq: 9, rel: 10, '<<': 11, '>>': 11, '>>>': 11, '+': 12, '-': 12, '*': 13, '/': 13, '%': 13, '**': 14, unary: 15, postfix: 16 },
2270
+ py: { assign: 0.5, lambda: 1, conditional: 2, or: 3, and: 4, not: 5, eq: 6, rel: 6, '|': 7, '^': 8, '&': 9, '<<': 10, '>>': 10, '+': 11, '-': 11, '*': 12, '/': 12, '//': 12, '%': 12, '@': 12, unary: 13, '**': 14, await: 15, postfix: 16 },
2271
+ go: { or: 1, and: 2, eq: 3, rel: 3, '+': 4, '-': 4, '|': 4, '^': 4, '*': 5, '/': 5, '%': 5, '<<': 5, '>>': 5, '&': 5, '&^': 5, unary: 6, postfix: 7 },
2272
+ };
2273
+ const EQ = new Set(['==', '!=', '===', '!==']);
2274
+
2275
+ class Unrenderable extends Error { constructor(why) { super(why); this.name = "Unrenderable"; } }
2276
+ const no = (why) => { throw new Unrenderable(why); };
2277
+
2278
+ /** Code for an expression tree in a target language; throws when the tree has something the target cannot say. */
2279
+ export function renderExpr(n, lang) {
2280
+ const fam = lang === 'python' ? 'py' : lang === 'go' ? 'go' : 'c';
2281
+ const P = RP[fam];
2282
+ const r = (x, min) => {
2283
+ const [s, p] = one(x);
2284
+ return p < min ? `(${s})` : s;
2285
+ };
2286
+ const strOf = (node) => {
2287
+ if (fam === 'py' && node.bytes) return node.raw;
2288
+ if (node.raw && node.kind === 'literal' && ((fam === 'go' && /^["`]/.test(node.raw)) || (fam === 'py' && /^[rRuU]?["']/.test(node.raw) && !/^[fF]/.test(node.raw)) || (fam === 'c' && /^["']/.test(node.raw)))) return node.raw;
2289
+ return JSON.stringify(node.value);
2290
+ };
2291
+ function one(x) {
2292
+ switch (x.kind) {
2293
+ case 'name': return [`${x.name}${x.typeArgs && lang === 'typescript' ? x.typeArgs : ''}`, 99];
2294
+ case 'literal': {
2295
+ if (x.type === 'text') { if (x.interpolated) no('interpolated text'); return [strOf(x), 99]; }
2296
+ if (x.type === 'number') return [x.raw, String(x.raw).startsWith('-') ? P.unary : 99];
2297
+ if (x.type === 'bool') return [fam === 'py' ? (x.value ? 'True' : 'False') : String(x.value), 99];
2298
+ if (x.type === 'null') return [fam === 'py' ? 'None' : fam === 'go' ? 'nil' : x.raw === 'undefined' ? 'undefined' : 'null', 99];
2299
+ if (x.type === 'regex' && fam === 'c') return [x.raw, 99];
2300
+ if (x.type === 'char' && fam === 'go') return [x.raw, 99];
2301
+ return no(`${x.type} literal`);
2302
+ }
2303
+ case 'template': {
2304
+ if (fam === 'c' && !x.form) return [`${x.tag ? r(x.tag, P.postfix) : ''}\`${x.parts.map((p) => (typeof p === 'string' ? p.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${') : `\${${renderExpr(p.expr, lang)}}`)).join('')}\``, 99];
2305
+ if (fam === 'py' && x.form === 'f') {
2306
+ const q = x.parts.some((p) => typeof p === 'string' && p.includes('"')) ? "'" : '"';
2307
+ return [`f${q}${x.parts.map((p) => (typeof p === 'string' ? p.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\{/g, '{{').replace(/\}/g, '}}') : `{${renderExpr(p.expr, lang)}${p.selfDoc ? '=' : ''}${p.conv ? `!${p.conv}` : ''}${p.format != null ? `:${p.format}` : ''}}`)).join('')}${q}`, 99];
2308
+ }
2309
+ return no('template');
2310
+ }
2311
+ case 'member': {
2312
+ if (x.static) no('static member');
2313
+ return [`${r(x.object, P.postfix)}${x.optional ? (fam === 'c' ? '?.' : no('optional member')) : '.'}${x.property}${x.typeArgs && lang === 'typescript' ? x.typeArgs : ''}`, P.postfix];
2314
+ }
2315
+ case 'index': {
2316
+ const idx = x.index.kind === 'slice' ? (fam === 'c' ? no('slice') : `${x.index.start ? renderExpr(x.index.start, lang) : ''}:${x.index.end ? renderExpr(x.index.end, lang) : ''}${x.index.step ? `:${renderExpr(x.index.step, lang)}` : ''}`) : x.index.kind === 'array' && x.index.form === 'tuple' && fam === 'py' ? x.index.items.map((i) => renderExpr(i, lang)).join(', ') : renderExpr(x.index, lang);
2317
+ return [`${r(x.object, P.postfix)}${x.optional ? '?.' : ''}[${idx}]`, P.postfix];
2318
+ }
2319
+ case 'call': {
2320
+ if (x.init) no('initializer');
2321
+ if (x.parens === false && !x.new) no('call without brackets');
2322
+ const callee = r(x.callee, P.postfix);
2323
+ const args = x.args.map((a) => arg(a)).join(', ');
2324
+ if (x.new) { if (fam !== 'c') no('new'); return [`new ${callee}${x.typeArgs ? x.typeArgs : ''}${x.parens === false ? '' : `(${args})`}`, P.postfix]; }
2325
+ return [`${callee}${x.optional ? '?.' : ''}(${args})`, P.postfix];
2326
+ }
2327
+ case 'not': return fam === 'py' ? [`not ${r(x.value, P.not)}`, P.not] : [`!${r(x.value, P.unary)}`, P.unary];
2328
+ case 'unary': {
2329
+ if (x.postfix) { if (fam === 'py' || (x.op !== '++' && x.op !== '--')) no(`postfix ${x.op}`); return [`${r(x.value, P.postfix)}${x.op}`, P.postfix]; }
2330
+ if (x.op === 'await') { if (fam === 'go') no('await'); return [`await ${r(x.value, fam === 'py' ? P.await : P.unary)}`, fam === 'py' ? P.await : P.unary]; }
2331
+ if (/^(?:typeof|void|delete)$/.test(x.op)) { if (fam !== 'c') no(x.op); return [`${x.op} ${r(x.value, P.unary)}`, P.unary]; }
2332
+ if ((x.op === '*' || x.op === '&' || x.op === '<-') && fam !== 'go') no(x.op);
2333
+ if ((x.op === '++' || x.op === '--') && fam === 'py') no(x.op);
2334
+ if (x.op === '~' && fam === 'go') return [`^${r(x.value, P.unary)}`, P.unary];
2335
+ const inner = r(x.value, P.unary);
2336
+ // `- -x` must not become `--x`.
2337
+ return [`${x.op}${(x.op === '-' && inner.startsWith('-')) || (x.op === '+' && inner.startsWith('+')) ? ' ' : ''}${inner}`, P.unary];
2338
+ }
2339
+ case 'logic': {
2340
+ const p = x.op === 'or' ? P.or : P.and;
2341
+ const op = fam === 'py' ? ` ${x.op} ` : x.op === 'or' ? ' || ' : ' && ';
2342
+ // In JavaScript, ?? cannot be mixed with && / || without brackets.
2343
+ return [x.operands.map((o, i) => { const s = r(o, i ? p + 0.5 : p); return fam === 'c' && o.kind === 'binary' && o.op === '??' && !s.startsWith('(') ? `(${s})` : s; }).join(op), p];
2344
+ }
2345
+ case 'compare': {
2346
+ let op = x.op;
2347
+ if (fam === 'py') { if (op === '===' || op === '!==' || op === 'instanceof') no(op); op = op === '!is' ? 'is not' : op === '!in' ? 'not in' : op; }
2348
+ if (fam === 'go' && !/^(?:==|!=|<|>|<=|>=)$/.test(op)) no(op);
2349
+ if (fam === 'c' && /^(?:is|is not|not in|!in|!is)$/.test(op)) no(op);
2350
+ const p = EQ.has(op) ? P.eq : P.rel;
2351
+ return [`${r(x.left, p)} ${op} ${r(x.right, p + 0.5)}`, p];
2352
+ }
2353
+ case 'chain': { if (fam !== 'py') no('chain'); return [x.operands.map((o, i) => (i ? `${x.ops[i - 1]} ${r(o, P.rel + 0.5)}` : r(o, P.rel + 0.5))).join(' '), P.rel]; }
2354
+ case 'binary': {
2355
+ let op = x.op;
2356
+ if (op === '??') { if (fam !== 'c') no('??'); const p = P['??']; return [`${r(x.left, p)} ?? ${r(x.right, p + 0.5)}`, p]; }
2357
+ if (op === '**' && fam === 'go') no('**');
2358
+ if ((op === '//' || op === '@') && fam !== 'py') no(op);
2359
+ if (op === '&^' && fam !== 'go') no(op);
2360
+ if ((op === '>>>' ) && fam !== 'c') no(op);
2361
+ if (/^(?:\.\.|\.\.=|\.\.<|\.\.\.|\.|<=>|=~)$/.test(op)) no(op);
2362
+ const p = P[op] ?? no(op);
2363
+ if (op === '**') return [`${r(x.left, p + 0.5)} ** ${r(x.right, fam === 'py' ? P.unary : p)}`, p];
2364
+ return [`${r(x.left, p)} ${op} ${r(x.right, p + 0.5)}`, p];
2365
+ }
2366
+ case 'conditional': {
2367
+ if (fam === 'go') no('conditional');
2368
+ if (fam === 'py') return [`${r(x.then, P.conditional + 0.5)} if ${r(x.test, P.conditional + 0.5)} else ${r(x.else, P.conditional)}`, P.conditional];
2369
+ return [`${r(x.test, P.conditional + 0.5)} ? ${r(x.then, P.assign)} : ${r(x.else, P.conditional)}`, P.conditional];
2370
+ }
2371
+ case 'array': {
2372
+ const items = x.items.map((i) => (i.kind === 'hole' ? '' : arg(i))).join(', ');
2373
+ if (x.repeat) no('repeat');
2374
+ if (fam === 'go') { if (x.form === 'tuple') return [items, 0]; if (x.type == null) no('untyped list'); return [`${x.type}{${items}}`, P.postfix]; }
2375
+ if (x.form === 'tuple') { if (fam === 'c') return [items, 0]; return [`(${items}${x.items.length === 1 ? ',' : ''})`, 99]; }
2376
+ if (x.form === 'set') { if (fam !== 'py') no('set'); return [`{${items}}`, 99]; }
2377
+ if (x.form === 'braces') no('braces list');
2378
+ return [`[${items}]`, 99];
2379
+ }
2380
+ case 'object': {
2381
+ if (fam === 'go') {
2382
+ const body = x.entries.map((e) => (e.kind === 'spread' ? no('spread') : `${renderExpr(e.key, lang)}: ${renderExpr(e.value, lang)}`)).join(', ');
2383
+ return [`${x.type ?? no('untyped object')}{${body}}`, P.postfix];
2384
+ }
2385
+ if (x.type || x.form) no(x.form || 'typed object');
2386
+ const body = x.entries.map((e) => {
2387
+ if (e.kind === 'spread') return fam === 'py' ? `**${renderExpr(e.value, lang)}` : `...${renderExpr(e.value, lang)}`;
2388
+ if (fam === 'py') return `${renderExpr(e.key, lang)}: ${renderExpr(e.value, lang)}`;
2389
+ if (e.shorthand) return renderExpr(e.value, lang);
2390
+ if (e.method) {
2391
+ const v = e.value, k0 = e.key.kind === 'literal' && e.key.raw === e.key.value ? e.key.value : renderExpr(e.key, lang);
2392
+ const pre = v.form === 'getter' ? 'get ' : v.form === 'setter' ? 'set ' : v.form === 'async method' ? 'async ' : v.form === 'generator method' ? '*' : '';
2393
+ return `${pre}${k0}(${v.params.join(', ')}) {\n}`;
2394
+ }
2395
+ if (e.computed) return `[${renderExpr(e.key, lang)}]: ${renderExpr(e.value, lang)}`;
2396
+ const k = e.key.kind === 'literal' && e.key.type === 'text' && e.key.raw === e.key.value ? e.key.value : renderExpr(e.key, lang);
2397
+ return `${k}: ${renderExpr(e.value, lang)}`;
2398
+ }).join(', ');
2399
+ return [fam === 'py' ? `{${body}}` : x.entries.length ? `{ ${body} }` : '{}', 99];
2400
+ }
2401
+ case 'comprehension': {
2402
+ if (fam !== 'py') no('comprehension');
2403
+ const clauses = x.clauses.map((c) => ` for ${c.targets.map((t) => renderExpr(t, lang)).join(', ')} in ${r(c.iter, P.or)}${(c.conds || []).map((k) => ` if ${r(k, P.or)}`).join('')}`).join('');
2404
+ const head = x.form === 'dict' ? `${renderExpr(x.key, lang)}: ${renderExpr(x.item, lang)}` : renderExpr(x.item, lang);
2405
+ return [x.form === 'list' ? `[${head}${clauses}]` : x.form === 'dict' || x.form === 'set' ? `{${head}${clauses}}` : `(${head}${clauses})`, 99];
2406
+ }
2407
+ case 'lambda': {
2408
+ if (fam === 'py') { if (x.body.kind === 'block') no('block lambda'); return [`lambda${x.params.length ? ` ${x.params.join(', ')}` : ''}: ${renderExpr(x.body, lang)}`, P.lambda]; }
2409
+ if (fam === 'go') { if (x.form !== 'func') no('lambda'); return [`func(${x.params.join(', ')})${x.returns ? ` ${x.returns}` : ''} {\n}`, P.postfix]; }
2410
+ if (x.form === 'function') return [`${x.async ? 'async ' : ''}function${x.generator ? '*' : ''}${x.name ? ` ${x.name}` : ''}(${x.params.join(', ')}) {\n}`, P.postfix];
2411
+ if (x.form && x.form !== 'function') no(`${x.form} lambda`);
2412
+ const body = x.body.kind === 'block' ? '{\n}' : x.body.kind === 'object' || x.body.kind === 'assign' ? `(${renderExpr(x.body, lang)})` : r(x.body, P.assign);
2413
+ return [`${x.async ? 'async ' : ''}${x.typeParams ?? ''}(${x.params.join(', ')})${x.returns ? `: ${x.returns}` : ''} => ${body}`, P.assign];
2414
+ }
2415
+ case 'cast': {
2416
+ if (fam === 'c' && lang === 'typescript' && (x.form === 'as' || x.form === 'satisfies')) return [`${r(x.value, P.rel)} ${x.form} ${x.type}`, P.rel];
2417
+ if (fam === 'go' && x.form === 'assert') return [`${r(x.value, P.postfix)}.(${x.type})`, P.postfix];
2418
+ return no('cast');
2419
+ }
2420
+ case 'spread': return fam === 'c' && x.form === '...' && !x.postfix ? [`...${r(x.value, P.assign)}`, 0] : fam === 'py' && (x.form === '*' || x.form === '**') ? [`${x.form}${r(x.value, P.unary)}`, 0] : fam === 'go' && x.postfix ? [`${r(x.value, P.postfix)}...`, 0] : no('spread');
2421
+ case 'named': return fam === 'py' ? [`${x.name}=${renderExpr(x.value, lang)}`, 0] : no('named argument');
2422
+ case 'assign': {
2423
+ if (fam === 'go') no('assignment in an expression');
2424
+ if (fam === 'py' && x.op !== ':=') no('assignment in an expression');
2425
+ return [`${renderExpr(x.target, lang)} ${x.op} ${r(x.value, P.assign)}`, P.assign];
2426
+ }
2427
+ case 'yield': { if (fam === 'go') no('yield'); return [`yield${x.delegate ? (fam === 'py' ? ' from' : '*') : ''}${x.value ? ` ${renderExpr(x.value, lang)}` : ''}`, fam === 'py' ? 0.5 : P.assign]; }
2428
+ case 'pattern': return [x.text, 99];
2429
+ case 'jsx': {
2430
+ if (fam !== 'c') no('jsx');
2431
+ const attrs = x.attrs.map((a) => (a.spread ? ` {...${renderExpr(a.spread, lang)}}` : a.value ? ` ${a.name}=${a.value.kind === 'literal' && a.value.type === 'text' ? a.value.raw : a.value.kind === 'jsx' ? renderExpr(a.value, lang) : `{${renderExpr(a.value, lang)}}`}` : ` ${a.name}`)).join('');
2432
+ if (!x.children.length) return [`<${x.tag}${attrs} />`, 99];
2433
+ return [`<${x.tag}${attrs}>${x.children.map((c) => (typeof c === 'string' ? c : c.kind === 'jsx-value' ? `{${renderExpr(c.value, lang)}}` : renderExpr(c, lang))).join('')}</${x.tag}>`, 99];
2434
+ }
2435
+ default: return no(x.kind);
2436
+ }
2437
+ }
2438
+ const arg = (a) => {
2439
+ if (a.kind === 'lambda' && a.trailing) no('trailing block');
2440
+ const [s] = one(a);
2441
+ return a.kind === 'array' && a.form === 'tuple' && fam !== 'py' ? `(${s})` : s;
2442
+ };
2443
+ try { return one(n)[0]; } catch (e) { if (e instanceof Unrenderable) throw e; throw e; }
2444
+ }
2445
+
2446
+ /**
2447
+ * Code for a statement tree (a step's `expr`) in a target language. A step that opens a block (if, for, a function)
2448
+ * is written with an empty block; its children are their own steps. Throws when the tree cannot be written there.
2449
+ */
2450
+ export function renderStatement(n, lang) {
2451
+ const fam = lang === 'python' ? 'py' : lang === 'go' ? 'go' : 'c';
2452
+ // JSX as a value is written the way people write it, in brackets on its own lines (`return (\n <div>…\n);`).
2453
+ const R = (x) => (x.kind === 'jsx' && fam === 'c' ? `(\n${renderExpr(x, lang)}\n)` : renderExpr(x, lang));
2454
+ const semi = fam === 'c' ? ';' : '';
2455
+ const block = (head) => (fam === 'py' ? `${head}:\n pass` : `${head} {\n}`);
2456
+ switch (n.kind) {
2457
+ case 'code': return no('code');
2458
+ case 'assign': {
2459
+ const target = n.target.kind === 'array' && n.target.form === 'tuple' && n.target.items.length > 1 ? n.target.items.map(R).join(', ') : R(n.target);
2460
+ const value = n.value.kind === 'array' && n.value.form === 'tuple' && fam !== 'c' && n.value.items.length > 1 ? n.value.items.map(R).join(', ') : n.value.kind === 'assign' ? renderStatement(n.value, lang).replace(/;$/, '') : R(n.value);
2461
+ if (n.declare) {
2462
+ if (fam === 'c') { if (!/^(?:const|let|var)$/.test(n.declare)) no(n.declare); return `${n.declare} ${target}${n.type ? `: ${n.type}` : ''} = ${value};`; }
2463
+ if (fam === 'go') { if (n.declare !== 'var' && n.declare !== 'const') no(n.declare); return `${n.declare} ${target}${n.type ? ` ${n.type}` : ''} = ${value}`; }
2464
+ return no('declaration');
2465
+ }
2466
+ if (n.type && fam === 'py') return `${target}: ${n.type} = ${value}`;
2467
+ if (n.op === ':=' && fam !== 'go') no(':=');
2468
+ return `${target} ${n.op} ${value}${semi}`;
2469
+ }
2470
+ case 'declare': {
2471
+ if (fam === 'c' && /^(?:let|var)$/.test(n.declare)) return `${n.declare} ${n.names.join(', ')}${n.type ? `: ${n.type}` : ''};`;
2472
+ if (fam === 'go' && n.declare === 'var') return `var ${n.names.map((x) => (typeof x === 'string' ? x : R(x))).join(', ')}${n.type ? ` ${n.type}` : ''}`;
2473
+ if (fam === 'py' && n.type) return `${n.names[0]}: ${n.type}`;
2474
+ if (fam === 'py' && n.scope) return `${n.scope} ${n.names.join(', ')}`;
2475
+ return no('declaration');
2476
+ }
2477
+ case 'sequence': {
2478
+ if (fam === 'go' && n.block) return `${n.block} (\n${n.items.map((x) => `\t${renderStatement(x, lang).replace(/^(?:var|const) /, '')}`).join('\n')}\n)`;
2479
+ if (fam === 'c' && n.items.every((x) => x.declare && x.declare === n.items[0].declare)) return `${n.items[0].declare} ${n.items.map((x) => (x.kind === 'assign' ? `${R(x.target)}${x.type ? `: ${x.type}` : ''} = ${R(x.value)}` : x.names.join(', '))).join(', ')};`;
2480
+ return no('sequence');
2481
+ }
2482
+ case 'return': return n.value ? `return ${n.value.kind === 'array' && n.value.form === 'tuple' && fam !== 'c' && n.value.items.length > 1 ? n.value.items.map(R).join(', ') : R(n.value)}${semi}` : `return${semi}`;
2483
+ case 'throw':
2484
+ if (n.form === 'panic') { if (fam !== 'go') no('panic'); return R(n.value); }
2485
+ if (fam === 'go') no('throw');
2486
+ if (fam === 'py') return n.value ? `raise ${R(n.value)}${n.cause ? ` from ${R(n.cause)}` : ''}` : 'raise';
2487
+ return n.value ? `throw ${R(n.value)};` : no('rethrow');
2488
+ case 'if': {
2489
+ if (n.negate) no('unless');
2490
+ if (fam === 'go') return block(`if ${n.init ? `${renderStatement(n.init, lang)}; ` : ''}${R(n.test)}`);
2491
+ if (n.init) no('if with a first statement');
2492
+ return fam === 'py' ? block(`if ${R(n.test)}`) : block(`if (${R(n.test)})`);
2493
+ }
2494
+ case 'loop': {
2495
+ if (n.form === 'each') {
2496
+ if (fam === 'py') return block(`for ${n.targets.map(R).join(', ')} in ${n.iterable.kind === 'array' && n.iterable.form === 'tuple' ? n.iterable.items.map(R).join(', ') : R(n.iterable)}`);
2497
+ if (fam === 'go') { if (!n.range) no('each'); return block(`for ${n.targets.length ? `${n.targets.map(R).join(', ')} := ` : ''}range ${R(n.iterable)}`); }
2498
+ if (n.type) no('typed loop');
2499
+ return block(`for (${n.declare ? `${n.declare} ` : ''}${n.targets.map(R).join(', ')} ${n.keys ? 'in' : 'of'} ${R(n.iterable)})`);
2500
+ }
2501
+ if (n.form === 'while') return fam === 'go' ? block(`for ${R(n.test)}`) : fam === 'py' ? block(`while ${R(n.test)}`) : block(`while (${R(n.test)})`);
2502
+ if (n.form === 'forever') { if (fam === 'go') return block('for'); return no('forever'); }
2503
+ if (n.form === 'for') {
2504
+ if (fam === 'py') no('for');
2505
+ const init = n.init ? renderStatement(n.init, lang).replace(/;$/, '') : '';
2506
+ const update = n.update ? renderStatement(n.update, lang).replace(/;$/, '') : '';
2507
+ return fam === 'go' ? block(`for ${init}; ${n.test ? R(n.test) : ''}; ${update}`) : block(`for (${init}; ${n.test ? R(n.test) : ''}; ${update})`);
2508
+ }
2509
+ return no(`${n.form} loop`);
2510
+ }
2511
+ case 'switch': {
2512
+ if (fam === 'py') return no('match');
2513
+ if (n.form !== 'switch' && !(fam === 'go' && n.form === 'select')) no(n.form);
2514
+ if (fam === 'go') return n.form === 'select' ? 'select {\n}' : block(`switch${n.init ? ` ${renderStatement(n.init, lang)};` : ''}${n.subject ? ` ${n.subject.kind === 'assign' ? renderStatement(n.subject, lang) : R(n.subject)}` : ''}`);
2515
+ return block(`switch (${R(n.subject)})`);
2516
+ }
2517
+ case 'case': {
2518
+ // Only the label (its steps are its children); it is read inside a switch / match.
2519
+ const pats = n.patterns || [];
2520
+ if (n.guard && fam !== 'py') no('guard');
2521
+ if (fam === 'py') { if (n.default || !pats.length) no('default'); return `case ${pats.map(R).join(' | ')}${n.guard ? ` if ${R(n.guard)}` : ''}:`; }
2522
+ if (fam === 'go') { if (n.default && pats.length) no('default with cases'); return n.default ? 'default:' : `case ${pats.map((x) => (x.kind === 'assign' || (x.kind === 'unary' && x.op === '<-') ? renderStatement(x, lang) : R(x))).join(', ')}:`; }
2523
+ return [...pats.map((x) => `case ${R(x)}:`), ...(n.default ? ['default:'] : [])].join('\n');
2524
+ }
2525
+ case 'try': return fam === 'py' ? 'try:\n pass\nexcept Exception:\n pass' : fam === 'go' ? no('try') : 'try {\n} catch (e) {\n}';
2526
+ case 'jump': if (n.jump === 'fallthrough' && fam !== 'go') no('fallthrough'); return `${n.jump}${n.label ? ` ${n.label}` : ''}${semi}`;
2527
+ case 'yield': return `${R(n)}${semi}`;
2528
+ case 'defer': case 'go': if (fam !== 'go') no(n.kind); return `${n.kind} ${R(n.value)}`;
2529
+ case 'delete': return fam === 'py' ? `del ${n.target.kind === 'array' && n.target.form === 'tuple' ? n.target.items.map(R).join(', ') : R(n.target)}` : fam === 'c' ? `delete ${R(n.target)};` : no('delete');
2530
+ case 'assert': if (fam !== 'py') no('assert'); return `assert ${R(n.test)}${n.message ? `, ${R(n.message)}` : ''}`;
2531
+ case 'with': if (fam !== 'py') no('with'); return block(`${n.async ? 'async ' : ''}with ${n.items.map((i) => `${R(i.value)}${i.as ? ` as ${R(i.as)}` : ''}`).join(', ')}`);
2532
+ case 'function': return fam === 'py' ? block(`${n.async ? 'async ' : ''}def ${n.name}(${n.params.join(', ')})${n.returns ? ` -> ${n.returns}` : ''}`) : fam === 'go' ? block(`func ${n.name}(${n.params.join(', ')})${n.returns ? ` ${n.returns}` : ''}`) : block(`${n.async ? 'async ' : ''}function ${n.name}(${n.params.join(', ')})${n.returns ? `: ${n.returns}` : ''}`);
2533
+ case 'pass': return fam === 'py' ? 'pass' : no('pass');
2534
+ default: {
2535
+ // An expression used as a statement: a call, an await, an increment.
2536
+ if (n.inline) no('inline');
2537
+ const s = R(n);
2538
+ if (fam === 'c' && (s.startsWith('{') || s.startsWith('function') || /^async\s+function/.test(s) || s.startsWith('('))) return `(${s});`;
2539
+ return `${s}${semi}`;
2540
+ }
2541
+ }
2542
+ }
2543
+
2544
+ export { Unrenderable };