@skillstech/thunderlang 0.5.11 → 1.0.3

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 +441 -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
package/src/rlang.mjs ADDED
@@ -0,0 +1,1084 @@
1
+ // R in Thunder. A linear tokenizer and statement reader for R: `name <- function(a, b = 3) { … }` (and `=`, `<<-`),
2
+ // if / else if / else, for, while, repeat, switch() (cases), stop() as a Stop with its message, warning(), message(),
3
+ // tryCatch(error = …, warning = …, finally = …) as handlers and an always-at-the-end, return() and the implicit last
4
+ // value, library()/require() as setup, data-frame pipelines (|> and %>%) as one step per verb ("Keeps only the rows
5
+ // where x is more than 1"), lapply/purrr::map as loops, R6Class / setRefClass / setClass as Things, roxygen #' and
6
+ // plumber #* @get /path annotations, and testthat tests. Deterministic, browser-safe; what it cannot say keeps its code.
7
+ import { words, cap, listWords, gerund } from './commands.mjs';
8
+ import { accountsFor } from './faithful.mjs';
9
+
10
+ function lineFinder(src) {
11
+ const starts = [0];
12
+ for (let i = src.indexOf('\n'); i >= 0; i = src.indexOf('\n', i + 1)) starts.push(i + 1);
13
+ return (idx) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= idx) lo = mid; else hi = mid - 1; } return lo + 1; };
14
+ }
15
+
16
+ // ── Tokens ────────────────────────────────────────────────────────────────────────────────────────────
17
+
18
+ const OPS = [':::', '<<-', '->>', '|>', '<-', '->', '<=', '>=', '==', '!=', '&&', '||', '::', '[[', '(', ')', '{', '}', '[', ']', ',', ';', '=', '+', '-', '*', '/', '^', '~', '?', ':', '$', '@', '!', '&', '|', '<', '>', '\\'];
19
+ const CLOSE = { '(': ')', '{': '}', '[': ']', '[[': ']]' };
20
+
21
+ function tokenize(src) {
22
+ const toks = [];
23
+ const stack = [];
24
+ let i = 0;
25
+ const n = src.length;
26
+ const push = (t, text, at, end, extra) => { const tok = { t, text, at, end, i: toks.length, ...extra }; toks.push(tok); return tok; };
27
+ while (i < n) {
28
+ const c = src[i];
29
+ if (c === ' ' || c === '\t' || c === '\r' || c === '\f' || c === '') { i++; continue; }
30
+ if (c === '\n') { push('nl', '\n', i, i + 1); i++; continue; }
31
+ if (c === '#') { let e = src.indexOf('\n', i); if (e < 0) e = n; push('comment', src.slice(i, e), i, e); i = e; continue; }
32
+ const raw = src.slice(i, i + 3).match(/^[rR](["'])(-*)[([{]/) && src.slice(i).match(/^[rR](["'])(-*)([([{])/);
33
+ if (raw) {
34
+ const closer = { '(': ')', '[': ']', '{': '}' }[raw[3]] + raw[2] + raw[1];
35
+ const e = src.indexOf(closer, i + raw[0].length);
36
+ const end = e < 0 ? n : e + closer.length;
37
+ push('str', src.slice(i, end), i, end, { value: src.slice(i + raw[0].length, e < 0 ? n : e) });
38
+ i = end;
39
+ continue;
40
+ }
41
+ if (c === '"' || c === "'") {
42
+ let j = i + 1, v = '';
43
+ for (; j < n && src[j] !== c; j++) { if (src[j] === '\\') { const e = src[j + 1]; v += e === 'n' || e === 't' ? ' ' : e ?? ''; j++; } else v += src[j]; }
44
+ push('str', src.slice(i, j + 1), i, Math.min(n, j + 1), { value: v });
45
+ i = j + 1;
46
+ continue;
47
+ }
48
+ if (c === '`') { const e = src.indexOf('`', i + 1); const end = e < 0 ? n : e + 1; push('id', src.slice(i + 1, end - 1), i, end); i = end; continue; }
49
+ if (/\d/.test(c) || (c === '.' && /\d/.test(src[i + 1] || ''))) {
50
+ const m = src.slice(i, i + 60).match(/^(?:0[xX][\da-fA-F]+|\d*\.?\d+(?:[eE][+-]?\d+)?|\d+\.)[Li]?/);
51
+ push('num', m[0], i, i + m[0].length);
52
+ i += m[0].length;
53
+ continue;
54
+ }
55
+ if (/[A-Za-z_.]/.test(c)) {
56
+ const m = src.slice(i, i + 200).match(/^[A-Za-z_.][\w.]*/);
57
+ push('id', m[0], i, i + m[0].length);
58
+ i += m[0].length;
59
+ continue;
60
+ }
61
+ if (c === '%') { const e = src.indexOf('%', i + 1); const nl = src.indexOf('\n', i); if (e > 0 && (nl < 0 || e < nl)) { push('op', src.slice(i, e + 1), i, e + 1); i = e + 1; continue; } }
62
+ if (c === ']' && stack[stack.length - 1]?.text === '[[' && src[i + 1] === ']') {
63
+ const t = push('op', ']]', i, i + 2);
64
+ stack.pop().match = t.i;
65
+ i += 2;
66
+ continue;
67
+ }
68
+ const op = OPS.find((o) => src.startsWith(o, i)) ?? c;
69
+ const t = push('op', op, i, i + op.length);
70
+ if (CLOSE[op]) stack.push(t);
71
+ else if (op === ')' || op === '}' || op === ']') {
72
+ for (let k = stack.length - 1; k >= 0; k--) if (CLOSE[stack[k].text] === op) { stack[k].match = t.i; stack.length = k; break; }
73
+ }
74
+ i += op.length;
75
+ }
76
+ return toks;
77
+ }
78
+
79
+ // ── Statements ────────────────────────────────────────────────────────────────────────────────────────
80
+
81
+ const BINARY = new Set(['<-', '<<-', '=', '->', '->>', '|>', '+', '-', '*', '/', '^', '~', '==', '!=', '<', '>', '<=', '>=', '&', '&&', '|', '||', ',', '$', '@', ':', '::', ':::', '!', '?', '\\']);
82
+ const isOp = (t, v) => t && t.t === 'op' && t.text === v;
83
+ const isId = (t, v) => t && t.t === 'id' && t.text === v;
84
+
85
+ /** Statement ranges in toks[from..to): R ends a statement at a line break once the expression is complete. */
86
+ function splitStatements(toks, from, to) {
87
+ const out = [];
88
+ let i = from;
89
+ while (i < to) {
90
+ while (i < to && (toks[i].t === 'nl' || toks[i].t === 'comment' || isOp(toks[i], ';'))) i++;
91
+ if (i >= to) break;
92
+ const s = i;
93
+ let needBody = false;
94
+ while (i < to) {
95
+ const t = toks[i];
96
+ if (t.match != null && t.match < to) {
97
+ const before = toks[i - 1];
98
+ // `if (…)`, `for (…)`, `while (…)`, `function(…)` still need their body.
99
+ needBody = isOp(t, '(') && before && (isId(before, 'if') || isId(before, 'for') || isId(before, 'while') || isId(before, 'function') || isOp(before, '\\'));
100
+ i = t.match + 1;
101
+ continue;
102
+ }
103
+ if (isOp(t, ';')) break;
104
+ if (t.t === 'nl' || t.t === 'comment') {
105
+ let k = i;
106
+ while (k < to && (toks[k].t === 'nl' || toks[k].t === 'comment')) k++;
107
+ let p = i - 1;
108
+ while (p > s && toks[p].t === 'comment') p--;
109
+ const prev = toks[p];
110
+ if (needBody || (prev && prev.t === 'op' && (BINARY.has(prev.text) || /^%.*%$/.test(prev.text))) || isId(prev, 'else') || isId(prev, 'repeat') || isId(toks[k], 'else')) { i = k; needBody = false; continue; }
111
+ break;
112
+ }
113
+ needBody = isId(t, 'else') || isId(t, 'repeat');
114
+ i++;
115
+ }
116
+ out.push([s, i]);
117
+ }
118
+ return out;
119
+ }
120
+
121
+ const at0 = (list) => list.filter((t) => t.t !== 'nl' && t.t !== 'comment');
122
+ /** Top-level items of a token list: each a token, or a bracket with its contents. */
123
+ function groups(list) {
124
+ const out = [];
125
+ let cur = null, depth = 0;
126
+ for (const t of list) {
127
+ if (depth === 0) { cur = [t]; out.push(cur); } else cur.push(t);
128
+ if (t.t === 'op' && CLOSE[t.text]) depth++;
129
+ else if (t.t === 'op' && (t.text === ')' || t.text === '}' || t.text === ']' || t.text === ']]')) depth = Math.max(0, depth - 1);
130
+ }
131
+ return out;
132
+ }
133
+ /** Arguments of a call: [{ name, toks }] split at top-level commas. */
134
+ function argsOf(list) {
135
+ if (!at0(list).length) return [];
136
+ const parts = [[]];
137
+ for (const g of groups(at0(list))) { if (g.length === 1 && isOp(g[0], ',')) parts.push([]); else parts[parts.length - 1].push(...g); }
138
+ return parts.map((p) => (p.length >= 2 && (p[0].t === 'id' || p[0].t === 'str') && isOp(p[1], '=') ? { name: p[0].t === 'str' ? p[0].value : p[0].text, toks: p.slice(2) } : { name: null, toks: p }));
139
+ }
140
+
141
+ // ── Words ─────────────────────────────────────────────────────────────────────────────────────────────
142
+
143
+ const rWords = (name) => { const w = words(String(name).replace(/^\.+/, '').replace(/\./g, ' ')); return w || String(name); };
144
+ const quote = (s) => `"${s.length > 100 ? `${s.slice(0, 99)}…` : s}"`;
145
+
146
+ // Text with values inside (docs/spec.md): the literal parts are kept exactly as the code writes them (escapes
147
+ // included), and each inserted value is a «placeholder»: a plain variable shows its name, anything else its code.
148
+ let SRC = '';
149
+ /** The code of a token list, as written (on one line). */
150
+ const codeText = (list) => { const v = at0(list); return v.length ? SRC.slice(v[0].at, v[v.length - 1].end).replace(/\s*\n\s*/g, ' ') : ''; };
151
+ /** The text of a string token exactly as written between its quotes (raw strings: their contents). */
152
+ const rawText = (t) => (/^[rR]["']/.test(t.text) ? t.value : t.text.slice(1, -1));
153
+ /** One inserted value: «name» for a plain variable, «code» for anything else. */
154
+ const placeholder = (list) => `«${codeText(list)}»`;
155
+ /** glue / cli text: `{x}` is an inserted value, `{{` and `}}` are literal braces (kept as written). */
156
+ function glueText(s) {
157
+ let out = '';
158
+ for (let i = 0; i < s.length; i++) {
159
+ const c = s[i];
160
+ if ((c === '{' || c === '}') && s[i + 1] === c) { out += c + c; i++; continue; }
161
+ if (c !== '{') { out += c; continue; }
162
+ let d = 0, j = i;
163
+ for (; j < s.length; j++) { if (s[j] === '{') d++; else if (s[j] === '}' && --d === 0) break; }
164
+ if (j >= s.length) { out += s.slice(i); break; }
165
+ out += `«${s.slice(i + 1, j).trim()}»`;
166
+ i = j;
167
+ }
168
+ return out;
169
+ }
170
+ /** Text joined from parts (paste0, cat, message, stop): literal strings as written, other parts as placeholders. */
171
+ function textOf(args, sep = '', glue = false) {
172
+ return args.filter((a) => !a.name).map((a) => { const v = at0(a.toks); return v.length === 1 && v[0].t === 'str' ? (glue ? glueText(rawText(v[0])) : rawText(v[0])) : placeholder(a.toks); }).join(sep);
173
+ }
174
+ /** True when the parts are one inserted value and nothing else: a value, said in words rather than as text. */
175
+ const oneValue = (args) => { const p = args.filter((a) => !a.name); return p.length === 1 && !(at0(p[0].toks).length === 1 && at0(p[0].toks)[0].t === 'str'); };
176
+ /** A named argument's literal text, '' for none, or null when it is not a plain string. */
177
+ const namedText = (args, k, dflt) => { const a = args.find((x) => x.name === k); if (!a) return dflt; const v = at0(a.toks); return v.length === 1 && v[0].t === 'str' ? rawText(v[0]) : null; };
178
+ /** sprintf("%s/%05d", a, n) -> "«a»/«n as %05d»"; null when the arguments cannot be paired with the conversions. */
179
+ function sprintfText(args) {
180
+ const plain = args.filter((a) => !a.name);
181
+ const fmt = at0(plain[0]?.toks ?? []);
182
+ if (fmt.length !== 1 || fmt[0].t !== 'str') return null;
183
+ const s = rawText(fmt[0]);
184
+ let k = 1, bad = false;
185
+ const out = s.replace(/%(?:%|([-+ 0#]*\d*(?:\.\d+)?)([a-zA-Z]))/g, (m, flags, conv) => {
186
+ if (m === '%%') return m;
187
+ if (/\$|\*/.test(m) || !plain[k]) { bad = true; return m; }
188
+ const v = placeholder(plain[k++].toks).slice(1, -1);
189
+ return flags || !/^[sdi]$/.test(conv) ? `«${v} as ${m}»` : `«${v}»`;
190
+ });
191
+ return bad || k !== plain.length ? null : out;
192
+ }
193
+ /** paste0 / paste as text, with how the pieces are joined when they are vectors (collapse). */
194
+ function pasteText(args, sep) {
195
+ const s = namedText(args, 'sep', sep), collapse = namedText(args, 'collapse', undefined);
196
+ if (s == null || collapse === null) return null;
197
+ const t = quote(textOf(args, s));
198
+ return collapse === undefined ? t : `${t} (each, joined with "${collapse}")`;
199
+ }
200
+ const AGG = { sum: 'the total of', mean: 'the average of', median: 'the middle value of', max: 'the highest', min: 'the lowest', sd: 'how spread out', n_distinct: 'how many different', first: 'the first', last: 'the last' };
201
+
202
+
203
+ const VALUE_OPS = new Set(['||', '|', '&&', '&', '==', '!=', '<', '>', '<=', '>=', '+', '-', '*', '/', '^', ':']);
204
+ /** A value in words, or null when Thunder will not guess. */
205
+ function sayValue(list) {
206
+ const v = at0(list);
207
+ if (!v.length) return null;
208
+ const g = groups(v);
209
+ if (g.length === 1 && g[0].length === 1) {
210
+ const t = g[0][0];
211
+ if (t.t === 'str') return quote(rawText(t));
212
+ if (t.t === 'num') return t.text.replace(/L$/, '');
213
+ if (t.t === 'id') return { TRUE: 'yes', FALSE: 'no', T: 'yes', F: 'no', NULL: 'nothing', NA: 'missing (NA)', Inf: 'infinity' }[t.text] ?? rWords(t.text);
214
+ }
215
+ if (g.length === 2 && isOp(g[0][0], '-') && g[1].length === 1 && g[1][0].t === 'num') return `-${g[1][0].text.replace(/L$/, '')}`;
216
+ if (g.length === 2 && isOp(g[0][0], '-') && g[1].length === 1 && g[1][0].t === 'id') return `minus ${rWords(g[1][0].text)}`;
217
+ // res <- f(x) inside a value: the value, and the name it is kept as.
218
+ const inner = g.findIndex((x, k) => k > 0 && x.length === 1 && (isOp(x[0], '<-') || isOp(x[0], '<<-')));
219
+ if (inner > 0) { const r = sayValue(g.slice(inner + 1).flat()); const n = at0(g.slice(0, inner).flat()); return r && n.length === 1 && n[0].t === 'id' ? `${r} (kept as ${rWords(n[0].text)})` : null; }
220
+ // A top-level operator decides what the value is; the $field / $method readings below are only for a single chain.
221
+ const hasOp = g.some((x, k) => k > 0 && x.length === 1 && x[0].t === 'op' && (VALUE_OPS.has(x[0].text) || /^%.*%$/.test(x[0].text)));
222
+ // a %||% b: a, or b when a is not set (rlang and base R 4.4).
223
+ const orNull = g.findIndex((x, k) => k > 0 && x.length === 1 && isOp(x[0], '%||%'));
224
+ if (orNull > 0) { const a = sayValue(g.slice(0, orNull).flat()), b = sayValue(g.slice(orNull + 1).flat()); return a && b ? `${a} (or ${b} when it is not set)` : null; }
225
+ // f(x)$field: a fact about what a call gives back.
226
+ if (!hasOp && g.length >= 3 && g[g.length - 1].length === 1 && g[g.length - 1][0].t === 'id' && isOp(g[g.length - 2][0], '$') && g.slice(0, -2).some((x) => isOp(x[0], '('))) {
227
+ const owner = sayValue(g.slice(0, -2).flat());
228
+ if (owner && /^the result of /.test(owner)) return `the ${rWords(g[g.length - 1][0].text)} from ${owner.replace(/^the result of /, '')}`;
229
+ }
230
+ // obj$method(args): what the method gives back.
231
+ const lg = g[g.length - 1];
232
+ if (!hasOp && g.length >= 4 && isOp(lg[0], '(') && g[g.length - 2][0].t === 'id' && isOp(g[g.length - 3][0], '$')) {
233
+ const owner = sayValue(g.slice(0, -3).flat());
234
+ if (owner) return `the result of ${rWords(g[g.length - 2][0].text)} on ${owner}`;
235
+ }
236
+ // Binary operators, lowest first.
237
+ for (const [ops, say] of [[['||', '|', '&&', '&'], null], [['==', '!=', '<', '>', '<=', '>=', '%in%'], null], [['+', '-'], { '+': 'plus', '-': 'minus' }], [['*', '/', '%%', '%/%'], { '*': 'times', '/': 'divided by', '%%': 'remainder after dividing by', '%/%': 'divided by (whole number)' }], [['^'], { '^': 'to the power of' }], [[':'], { ':': 'to' }]]) {
238
+ let at = -1;
239
+ for (let k = g.length - 1; k > 0; k--) if (g[k].length === 1 && g[k][0].t === 'op' && ops.includes(g[k][0].text)) { at = k; break; }
240
+ if (at > 0) {
241
+ if (!say) { const c = condSaid(v); return c ? `whether ${c}` : null; }
242
+ const a = sayValue(g.slice(0, at).flat()), b = sayValue(g.slice(at + 1).flat());
243
+ return a && b ? `${a} ${say[g[at][0].text]} ${b}` : null;
244
+ }
245
+ }
246
+ if (g.length === 2 && isOp(g[0][0], '!')) { const c = condSaid(v); return c ? `whether ${c}` : null; }
247
+ // x$y, x[["y"]], x@y, pkg::name
248
+ if (v[0].t === 'id' && g.every((x, k) => k === 0 || (x.length === 1 && (x[0].t === 'id' || isOp(x[0], '$') || isOp(x[0], '@'))) || (x[0].text === '[[' && x.length === 3 && x[1].t === 'str'))) {
249
+ const parts = [v[0].text];
250
+ for (let k = 1; k < g.length; k++) { const x = g[k]; if (x[0].t === 'id') parts.push(x[0].text); else if (x[0].text === '[[') parts.push(x[1].value); }
251
+ if (parts.length >= 2) {
252
+ const owns = (x) => (/s$/.test(x) ? `${x}'` : `${x}'s`);
253
+ const owner = parts.length > 2 ? `${owns(`the ${rWords(parts[parts.length - 3])}`)} ${rWords(parts[parts.length - 2])}` : rWords(parts[0]);
254
+ return owner === 'self' || owner === 'private' || owner === 'self' ? rWords(parts.at(-1)) : `${owns(/^the /.test(owner) ? owner : `the ${owner}`)} ${rWords(parts.at(-1))}`;
255
+ }
256
+ }
257
+ // x[rows, cols]: the rows of x where …, or an item of x.
258
+ const last = g[g.length - 1];
259
+ if (g.length >= 2 && last[0].text === '[' && last.length > 2) {
260
+ const owner = sayValue(g.slice(0, -1).flat());
261
+ if (owner) {
262
+ const parts = argsOf(last.slice(1, -1));
263
+ const rows = parts[0] && at0(parts[0].toks).length ? parts[0].toks : null;
264
+ if (parts.length === 2 && rows) { const c = condSaid(rows); if (c) return `the rows of ${owner} where ${c}`; }
265
+ return `part of ${owner}`;
266
+ }
267
+ }
268
+ if (g.length >= 2 && last[0].text === '[[' ) { const owner = sayValue(g.slice(0, -1).flat()); if (owner) return `an item of ${owner}`; }
269
+ const call = callOf(v);
270
+ if (call) return callNoun(call) ?? (callVerb(call) ? `the result of ${gerund(callVerb(call))}` : `the result of ${rWords(call.name)}`);
271
+ if (g.length === 1 && isOp(g[0][0], '(')) return sayValue(g[0].slice(1, -1));
272
+ if (isId(v[0], 'function') || isOp(v[0], '\\')) return 'a small function';
273
+ return null;
274
+ }
275
+
276
+ /** `pkg::name(args)` or `name(args)` taking the whole list. */
277
+ function callOf(v) {
278
+ let k = 0, name = '';
279
+ if (v[0]?.t !== 'id') return null;
280
+ name = v[0].text;
281
+ if (isOp(v[1], '::') || isOp(v[1], ':::')) { if (v[2]?.t !== 'id') return null; name = `${v[0].text}::${v[2].text}`; k = 2; }
282
+ const open = v[k + 1];
283
+ if (!isOp(open, '(') || open.match == null) return null;
284
+ const close = v.findIndex((t) => t.i === open.match);
285
+ if (close !== v.length - 1) return null;
286
+ const bare = name.replace(/^\w+:::?/, '');
287
+ return { name, bare, args: argsOf(v.slice(k + 2, close)), open, close: v[close] };
288
+ }
289
+
290
+ /** A call as a noun phrase ("the total of x"), or null. */
291
+ function callNoun({ bare, args }) {
292
+ const a0 = args[0] ? sayValue(args[0].toks) : null;
293
+ switch (bare) {
294
+ case 'c': case 'list': case 'vector': return args.length && at0(args[0].toks).length ? `the list ${listWords(args.slice(0, 6).map((a) => (a.name ? `${/^[A-Za-z.][\w.]*$/.test(a.name) ? rWords(a.name) : quote(a.name)} = ${sayValue(a.toks) ?? '…'}` : sayValue(a.toks) ?? '…')))}${args.length > 6 ? ', …' : ''}` : 'an empty list';
295
+ case 'character': case 'numeric': case 'integer': case 'logical': return 'an empty list';
296
+ case 'paste0': return pasteText(args, '');
297
+ case 'paste': return pasteText(args, ' ');
298
+ case 'sprintf': { const t = sprintfText(args); return t == null ? null : quote(t); }
299
+ case 'glue': case 'str_glue': case 'format_inline': { const v = at0(args[0]?.toks ?? []); return v.length === 1 && v[0].t === 'str' && args.filter((a) => !a.name).length === 1 ? quote(glueText(rawText(v[0]))) : null; }
300
+ case 'nrow': return `the number of rows in ${a0 ?? 'it'}`;
301
+ case 'ncol': return `the number of columns in ${a0 ?? 'it'}`;
302
+ case 'length': case 'NROW': return `how many ${a0 ?? 'items'}`;
303
+ case 'nchar': return `the length of ${a0 ?? 'the text'}`;
304
+ case 'n': return 'how many rows';
305
+ case 'Sys.time': case 'now': return 'the current time';
306
+ case 'Sys.Date': case 'today': return "today's date";
307
+ case 'Sys.getenv': return `the ${at0(args[0]?.toks ?? [])[0]?.value ? rWords(at0(args[0].toks)[0].value) : 'environment'} setting`;
308
+ case 'file.path': return args.some((a) => a.name) ? null : quote(textOf(args, '/'));
309
+ case 'toupper': return `${a0} in capital letters`;
310
+ case 'tolower': return `${a0} in small letters`;
311
+ case 'round': return `${a0} rounded`;
312
+ case 'abs': return `the size of ${a0} (without its sign)`;
313
+ case 'seq_along': return `the positions in ${a0}`;
314
+ case 'seq_len': return `1 to ${a0}`;
315
+ case 'invisible': return a0;
316
+ case 'conditionMessage': return `the message of ${a0 ?? 'the error'}`;
317
+ case 'data.frame': case 'tibble': case 'data.table': return args.length ? `a table of ${listWords(args.filter((x) => x.name).map((x) => rWords(x.name)).slice(0, 6))}` : 'an empty table';
318
+ case 'new': return `a new ${at0(args[0]?.toks ?? [])[0]?.value ?? 'object'}`;
319
+ case 'is.null': case 'is.na': case 'file.exists': case 'dir.exists': case 'nzchar': case 'isTRUE': case 'isFALSE': case 'inherits': case 'identical': case 'exists': case 'missing': case 'is.character': case 'is.numeric': case 'is.function': case 'is.list': case 'is.data.frame': case 'any': case 'all': { const c = condWords([...[]], false, { bare, args }); return c ? `whether ${c}` : null; }
320
+ default: return AGG[bare] && a0 ? `${AGG[bare]} ${a0}` : null;
321
+ }
322
+ }
323
+ /** A call as a verb phrase ("Reads the CSV file "orders.csv""), or null. */
324
+ function callVerb({ bare, name, args }) {
325
+ const a0 = args[0] ? sayValue(args[0].toks) : null;
326
+ const named = (k) => { const x = args.find((a) => a.name === k); return x ? sayValue(x.toks) : null; };
327
+ switch (bare) {
328
+ case 'read.csv': case 'read_csv': case 'fread': case 'read.csv2': case 'read_tsv': case 'read.delim': return `Reads the ${/tsv|delim/.test(bare) ? 'TSV' : 'CSV'} file ${a0 ?? '?'}`;
329
+ case 'readRDS': case 'read_rds': return `Reads the R data file ${a0 ?? '?'}`;
330
+ case 'readLines': case 'read_lines': return `Reads the lines of ${a0 ?? '?'}`;
331
+ case 'read_excel': case 'read.xlsx': return `Reads the Excel file ${a0 ?? '?'}`;
332
+ case 'fromJSON': case 'read_json': return `Reads the JSON ${a0 ?? ''}`.trim();
333
+ case 'write.csv': case 'write_csv': case 'fwrite': return `Saves ${a0 ?? 'the table'} to the CSV file ${named('file') ?? (args[1] ? sayValue(args[1].toks) : '?')}`;
334
+ case 'saveRDS': case 'write_rds': return `Saves ${a0 ?? 'it'} to the R data file ${named('file') ?? (args[1] ? sayValue(args[1].toks) : '?')}`;
335
+ case 'writeLines': case 'write_lines': return `Writes ${a0 ?? 'the lines'}${args[1] || named('con') ? ` to ${named('con') ?? sayValue(args[1].toks)}` : ''}`;
336
+ case 'toJSON': return 'Turns it into JSON';
337
+ case 'GET': case 'POST': case 'PUT': case 'DELETE': case 'PATCH': case 'HEAD': return `Sends a ${bare} request to ${a0 ?? '?'}`;
338
+ case 'request': return `Prepares a request to ${a0 ?? '?'}`;
339
+ case 'req_perform': return 'Sends the request';
340
+ case 'download.file': return `Downloads ${a0 ?? '?'}${args[1] ? ` to ${sayValue(args[1].toks)}` : ''}`;
341
+ case 'dir.create': return `Makes the folder ${a0 ?? '?'}`;
342
+ case 'unlink': case 'file.remove': return `Deletes ${a0 ?? '?'}`;
343
+ case 'file.copy': return `Copies ${a0 ?? '?'} to ${args[1] ? sayValue(args[1].toks) : '?'}`;
344
+ case 'setwd': return `Goes into the folder ${a0 ?? '?'}`;
345
+ case 'Sys.setenv': return `Sets ${listWords(args.filter((x) => x.name).map((x) => `the ${rWords(x.name)} setting to ${sayValue(x.toks) ?? '…'}`))}`;
346
+ case 'set.seed': return `Fixes the random numbers (seed ${a0 ?? '?'}) so results repeat`;
347
+ case 'print': return `Shows ${a0 ?? 'it'}`;
348
+ case 'cat': { const sep = namedText(args, 'sep', ' '); const to = args.find((a) => a.name === 'file'); return sep == null ? null : `Shows ${oneValue(args) ? sayValue(args.find((a) => !a.name).toks) ?? 'a value' : quote(textOf(args, sep))}${to ? ` (to ${sayValue(to.toks) ?? 'a connection'})` : ''}`; }
349
+ case 'message': case 'inform': case 'cli_alert_info': case 'cli_inform': case 'cli_alert': case 'cli_alert_success': return `Writes a message: ${messageText(args, bare.startsWith('cli'))}`;
350
+ case 'warning': case 'warn': case 'cli_warn': case 'cli_alert_warning': return `Warns: ${messageText(args, bare.startsWith('cli'))}`;
351
+ case 'ggplot': return `Draws a chart of ${a0 ?? 'the data'}`;
352
+ case 'ggsave': return `Saves the chart to ${a0 ?? '?'}`;
353
+ case 'plot': case 'hist': case 'barplot': case 'boxplot': return `Draws a ${bare === 'hist' ? 'histogram' : bare === 'plot' ? 'chart' : bare} of ${a0 ?? 'the data'}`;
354
+ case 'lm': case 'glm': return `Fits a ${bare === 'lm' ? 'straight-line' : 'general'} model: ${a0 ?? 'a formula'}`;
355
+ case 'Sys.sleep': return `Waits ${a0 ?? '?'} seconds`;
356
+ case 'match.arg': return `Checks that ${a0 ?? 'the choice'} is one of the allowed choices`;
357
+ case 'system': case 'system2': return `Runs the command ${a0 ?? '?'}`;
358
+ case 'dbConnect': return 'Connects to the database';
359
+ case 'dbGetQuery': case 'dbReadTable': return 'Reads from the database';
360
+ case 'dbExecute': case 'dbWriteTable': case 'dbAppendTable': return 'Writes to the database';
361
+ case 'dbDisconnect': return 'Disconnects from the database';
362
+ case 'assign': return `Sets ${a0 ?? 'a value'} to ${args[1] ? sayValue(args[1].toks) ?? 'a value' : 'a value'}`;
363
+ case 'rm': { const list = args.find((x) => x.name === 'list'), env = args.find((x) => x.name === 'envir' || x.name === 'pos'); const what = [...args.filter((x) => !x.name).map((x) => rWords(codeText(x.toks))), ...(list ? [`the variables named in ${sayValue(list.toks) ?? 'a list'}`] : [])]; return what.length ? `Removes ${listWords(what)}${env ? ` from ${sayValue(env.toks) ?? 'an environment'}` : ''}` : null; }
364
+ case 'invisible': return null;
365
+ case 'deprecate_warn': case 'deprecate_soft': { const p = args.filter((x) => !x.name); const pick = (k, i) => args.find((x) => x.name === k) ?? p[i]; const lit = (a) => { if (!a) return null; let v = at0(a.toks); const c = callOf(v); if (c?.bare === 'I' && c.args.length === 1) v = at0(c.args[0].toks); return sayValue(v); }; const when = lit(pick('when', 0)), what = lit(pick('what', 1)), withx = lit(pick('with', 2)); return `Warns that ${what ?? 'this'} is out of date (deprecated${when ? ` in ${when}` : ''})${withx ? `; use ${withx} instead` : ''}`; }
366
+ case 'signal_stage': return `Marks this as ${a0 ?? 'changing'}`;
367
+ default:
368
+ if (/^(?:\w+_)?check_\w+$/.test(bare)) { const what = rWords(bare.replace(/^(?:\w+_)?check_/, '')); return a0 && a0 !== 'nothing' ? `Checks that ${a0} is a valid ${what}` : `Runs the check ${what}`; }
369
+ return KNOWN_FNS.has(name) ? `Runs ${rWords(bare)}${args.length ? ` with ${argWords(args)}` : ''}` : null;
370
+ }
371
+ }
372
+
373
+ /** Arguments in words: a named argument keeps its name, and its value unless the value is that same name. */
374
+ function argWords(args, n = 4) {
375
+ const say = (x) => { const v = at0(x.toks); if (!x.name) return sayValue(x.toks) ?? 'a value'; if (v.length === 1 && v[0].t === 'id' && v[0].text === x.name) return rWords(x.name); return `${rWords(x.name)} = ${sayValue(x.toks) ?? '…'}`; };
376
+ const shown = args.slice(0, n).map(say);
377
+ return args.length > n ? `${shown.join(', ')}, …` : listWords(shown);
378
+ }
379
+ /** A message's text: literal parts as written, values as placeholders; one value alone is said in words. */
380
+ function messageText(args, glue) {
381
+ const parts = args.filter((x) => !x.name);
382
+ if (oneValue(args)) { const v = sayValue(parts[0].toks); return v ?? placeholder(parts[0].toks); }
383
+ return quote(textOf(parts, '', glue));
384
+ }
385
+
386
+ const CMP = { '==': ['is', 'is not'], '!=': ['is not', 'is'], '>': ['is more than', 'is at most'], '>=': ['is at least', 'is less than'], '<': ['is less than', 'is at least'], '<=': ['is at most', 'is more than'], '%in%': ['is one of', 'is not one of'] };
387
+ const KIND_IS = { 'is.character': 'text', 'is.numeric': 'a number', 'is.function': 'a function', 'is.list': 'a list', 'is.data.frame': 'a table', 'is.logical': 'a true/false value', 'is.factor': 'a set of categories', 'is.environment': 'an environment' };
388
+ /** A condition in words: `x > 1 && !is.null(y)` -> "x is more than 1 and y is set". */
389
+ function condWords(list, neg, preCall = null) {
390
+ const v = at0(list);
391
+ if (!v.length && !preCall) return null;
392
+ const g = groups(v);
393
+ for (const [ops, join, flip] of [[['||', '|'], ' or ', ' and '], [['&&', '&'], ' and ', ' or ']]) {
394
+ const parts = [[]];
395
+ for (const x of g) { if (x.length === 1 && x[0].t === 'op' && ops.includes(x[0].text)) parts.push([]); else parts[parts.length - 1].push(...x); }
396
+ // A negated compound (!(a && b)) is not rewritten (De Morgan): it is shown as code. A part that is a bare call
397
+ // must not start with "not:", which the picture reads as negating the whole question.
398
+ if (parts.length > 1) { if (neg) return null; const said = parts.map((p) => condWords(p, neg)); return said.some((s) => !s || /^not: /.test(s)) ? null : said.join(join); }
399
+ }
400
+ if (!preCall && isOp(g[0]?.[0], '!')) return condWords(v.slice(1), !neg);
401
+ if (!preCall && g.length === 1 && isOp(g[0][0], '(')) return condWords(g[0].slice(1, -1), neg);
402
+ if (!preCall) {
403
+ for (let k = g.length - 1; k > 0; k--) {
404
+ const x = g[k];
405
+ if (x.length === 1 && x[0].t === 'op' && CMP[x[0].text]) {
406
+ const a = sayValue(g.slice(0, k).flat()), b = sayValue(g.slice(k + 1).flat());
407
+ // x %in% c("a", "b"): the choices listed, not "the list a and b".
408
+ const choices = x[0].text === '%in%' ? callOf(at0(g.slice(k + 1).flat())) : null;
409
+ const b2 = choices?.bare === 'c' && choices.args.length && choices.args.every((y) => !y.name) ? choices.args.map((y) => sayValue(y.toks)).join(', ') : b;
410
+ return a && b2 && !/\bnull\b/.test(b2) ? `${a} ${CMP[x[0].text][neg ? 1 : 0]} ${b2}` : null;
411
+ }
412
+ }
413
+ }
414
+ const call = preCall ?? callOf(v);
415
+ if (call) {
416
+ const a0 = call.args[0] ? sayValue(call.args[0].toks) : null;
417
+ const yes = (p, n) => (neg ? n : p);
418
+ switch (call.bare) {
419
+ // NULL, not "empty": an empty text "" is a different thing in R.
420
+ case 'is.null': case 'is_null': return `${a0} is ${yes('NULL', 'set')}`;
421
+ case 'is.na': return `${a0} is ${yes('missing', 'not missing')}`;
422
+ case 'missing': return `${a0} was ${yes('not given', 'given')}`;
423
+ case 'file.exists': return `the file ${a0} ${yes('exists', 'does not exist')}`;
424
+ case 'dir.exists': return `the folder ${a0} ${yes('exists', 'does not exist')}`;
425
+ case 'exists': { const where = call.args.find((x) => x.name === 'envir' || x.name === 'where') ?? call.args.filter((x) => !x.name)[1]; return `${a0} ${yes('exists', 'does not exist')}${where ? ` in ${sayValue(where.toks) ?? 'an environment'}` : ''}`; }
426
+ case 'length': case 'nrow': case 'NROW': case 'ncol': case 'nchar': return `${callNoun(call)} is ${yes('not 0', '0')}`;
427
+ case 'nzchar': return `${a0} is ${yes('not empty', 'empty')}`;
428
+ case 'isTRUE': return `${a0} is ${yes('yes', 'not yes')}`;
429
+ case 'isFALSE': return `${a0} is ${yes('no', 'not no')}`;
430
+ case 'inherits': case 'is': return `${a0} is ${yes('', 'not ')}a ${call.args[1] ? (at0(call.args[1].toks)[0]?.value ?? sayValue(call.args[1].toks)) : 'kind'}`;
431
+ case 'identical': return `${a0} is ${yes('', 'not ')}${call.args[1] ? sayValue(call.args[1].toks) : '?'}`;
432
+ case 'interactive': return `it is ${yes('', 'not ')}running with a person at the keyboard`;
433
+ case 'requireNamespace': return `the ${at0(call.args[0]?.toks ?? [])[0]?.value ?? 'needed'} package is ${yes('installed', 'not installed')}`;
434
+ case 'any': return `${yes('any', 'none')} of ${a0 ?? 'them'}${call.args[0] ? '' : ''} ${neg ? 'holds' : 'holds'}`.replace(/ +/g, ' ');
435
+ case 'all': return `${yes('all', 'not all')} of ${a0 ?? 'them'} hold`;
436
+ default:
437
+ if (KIND_IS[call.bare] && call.args.length === 1) return `${a0} is ${yes('', 'not ')}${KIND_IS[call.bare]}`;
438
+ // Every argument is kept: is_string(x, string = "C") is not is_string(x).
439
+ return `${yes('', 'not: ')}${rWords(call.bare)}${call.args.length ? ` (${call.args.map((x) => (x.name ? `${rWords(x.name)} = ${sayValue(x.toks) ?? '…'}` : sayValue(x.toks) ?? '…')).join(', ')})` : ''}`;
440
+ }
441
+ }
442
+ const val = sayValue(v);
443
+ if (!val) return null;
444
+ if (val === 'yes' || val === 'no') return (val === 'yes') !== neg ? 'always' : 'never';
445
+ return neg ? `not ${val}` : val;
446
+ }
447
+
448
+ // ── The faithfulness gate (faithful.mjs) for R ──
449
+ // R writes some negations inside a function name (`is.null` reads "is not set", `missing` "was not given") and says
450
+ // FALSE as "no"; the code is rewritten so those count the same on both sides before accountsFor compares them.
451
+ const WORDS_NOT = new Set(['missing', 'nzchar', 'isFALSE']);
452
+ const NO_NOT = new Set(['is.null', 'is_null']);
453
+ const LENGTHS = new Set(['length', 'nrow', 'NROW', 'ncol', 'nchar']);
454
+ function rCanon(list) {
455
+ const v = at0(list);
456
+ const out = [];
457
+ const callEnd = (k) => { let j = k; if (isOp(v[j + 1], '::') || isOp(v[j + 1], ':::')) j += 2; const open = v[j + 1]; if (v[k].t !== 'id' || !isOp(open, '(') || open.match == null) return -1; const e = v.findIndex((t) => t.i === open.match); return e < 0 ? -1 : e; };
458
+ const bare = (k) => (isOp(v[k + 1], '::') || isOp(v[k + 1], ':::') ? v[k + 2]?.text : v[k].text);
459
+ for (let k = 0; k < v.length; k++) {
460
+ const t = v[k];
461
+ const negated = isOp(t, '!');
462
+ const at = negated ? k + 1 : k;
463
+ const e = v[at]?.t === 'id' ? callEnd(at) : -1;
464
+ // length(x) alone is a yes/no ("is not 0"); in length(x) == 1 it is a number.
465
+ const LOGIC = (t) => !t || (t.t === 'op' && /^(&&|\|\||&|\||\(|\)|!)$/.test(t.text));
466
+ const whole = e > 0 && LOGIC(v[k - 1]) && LOGIC(v[e + 1]);
467
+ if (e > 0 && (WORDS_NOT.has(bare(at)) || NO_NOT.has(bare(at)) || (whole && LENGTHS.has(bare(at))))) {
468
+ const open = isOp(v[at + 1], '(') ? at + 1 : at + 3;
469
+ const inner = rCanon(v.slice(open + 1, e));
470
+ // Words: is.null "not set" / !is.null "set"; length(x) "is not 0" / !length(x) "is 0"; isFALSE "is no" / "is not no".
471
+ if (bare(at) === 'isFALSE') out.push(`${negated ? '! ' : ''}! chk( ${inner} )`);
472
+ else if (NO_NOT.has(bare(at))) out.push(`chk( ${inner} )`);
473
+ else out.push(`${negated ? '' : '! '}chk( ${inner} )`);
474
+ k = e;
475
+ continue;
476
+ }
477
+ if (negated) { out.push('!'); continue; }
478
+ if (t.t === 'str') out.push('Q');
479
+ else if (t.t === 'id') out.push(/^(FALSE|F)$/.test(t.text) ? '! Q' : t.text.replace(/\./g, '_'));
480
+ else if (t.t === 'num') out.push(t.text);
481
+ else if (t.text === '&') out.push('&&');
482
+ else if (t.text === '|') out.push('||');
483
+ else if (t.text === '%in%') out.push(' in ');
484
+ else if (/^%.*%$/.test(t.text)) out.push(' Q ');
485
+ else if (t.text === '<-' || t.text === '<<-') out.push(' := ');
486
+ else if (t.text === '$' || t.text === '@') out.push('.');
487
+ else out.push(t.text);
488
+ }
489
+ return out.join(' ');
490
+ }
491
+ /** A condition in words, only when the words account for every negation and and/or of the code (else null: code). */
492
+ function condSaid(list) {
493
+ const c = condWords(list, false);
494
+ // An apostrophe in words ("the req's token") is not a quote: faithful.mjs would read it as one.
495
+ const counted = c && c.replace(/n't\b/g, ' not').replace(/(\w)'s\b/g, '$1s').replace(/(\w)s'(?=\s|$)/g, '$1s');
496
+ return c && accountsFor(rCanon(list), counted) ? c : null;
497
+ }
498
+
499
+ /** A condition as an expression the Thunder decision reader understands (`score >= 90 && member`), or null. */
500
+ function condJs(list) {
501
+ const out = [];
502
+ const v = at0(list);
503
+ for (let k = 0; k < v.length; k++) {
504
+ const t = v[k];
505
+ if (t.t === 'id') { if (/^(TRUE|T)$/.test(t.text)) out.push('true'); else if (/^(FALSE|F)$/.test(t.text)) out.push('false'); else if (/^(NULL|NA)$/.test(t.text) || isOp(v[k + 1], '(')) return null; else out.push(t.text.replace(/\./g, '_')); continue; }
506
+ if (t.t === 'num') { out.push(t.text.replace(/L$/, '')); continue; }
507
+ if (t.t === 'str') { out.push(JSON.stringify(t.value)); continue; }
508
+ const m = { '==': '==', '!=': '!=', '<': '<', '>': '>', '<=': '<=', '>=': '>=', '&&': '&&', '&': '&&', '||': '||', '|': '||', '!': '!', '(': '(', ')': ')', $: '.' }[t.text];
509
+ if (!m) return null;
510
+ out.push(m);
511
+ }
512
+ return out.join(' ').replace(/ \. /g, '.');
513
+ }
514
+ const fixedOf = (list) => {
515
+ const v = at0(list);
516
+ if (v.length === 1 && v[0].t === 'str') return v[0].value ? JSON.stringify(v[0].value) : null;
517
+ if (v.length === 1 && v[0].t === 'num' && /^\d+(\.\d+)?L?$/.test(v[0].text)) return v[0].text.replace(/L$/, '');
518
+ if (v.length === 2 && isOp(v[0], '-') && v[1].t === 'num') return `-${v[1].text.replace(/L$/, '')}`;
519
+ if (v.length === 1 && v[0].t === 'id' && /^(TRUE|FALSE)$/.test(v[0].text)) return v[0].text.toLowerCase();
520
+ const call = callOf(v);
521
+ if (call && (call.bare === 'return' || call.bare === 'invisible') && call.args.length === 1) return fixedOf(call.args[0].toks);
522
+ return null;
523
+ };
524
+
525
+ // ── Pipelines: data-frame verbs as steps ─────────────────────────────────────────────────────────────────
526
+
527
+ const colsOf = (args) => listWords(args.map((a) => (a.name ? rWords(a.name) : sayValue(a.toks) ?? '…')).slice(0, 6));
528
+ function verbStep(call) {
529
+ const { bare, args } = call;
530
+ const plain = args.filter((a) => !a.name);
531
+ switch (bare) {
532
+ case 'filter': case 'subset': { const c = plain.map((a) => condSaid(a.toks)); return { kind: 'call', callee: 'filter', says: `Keeps only the rows where ${c.every(Boolean) ? c.join(' and ') : 'a condition holds'}` }; }
533
+ case 'select': { const drop = plain.every((a) => isOp(at0(a.toks)[0], '-')); return { kind: 'call', callee: 'select', says: drop ? `Drops the column${plain.length > 1 ? 's' : ''} ${listWords(plain.map((a) => sayValue(at0(a.toks).slice(1)) ?? '…'))}` : `Keeps only the column${args.length > 1 ? 's' : ''} ${colsOf(args)}` }; }
534
+ case 'mutate': case 'transmute': return { kind: 'set', says: args.filter((a) => a.name).map((a) => `Works out the column ${rWords(a.name)}: ${sayValue(a.toks) ?? 'a calculation'}`).join('; ') || 'Changes some columns' };
535
+ case 'summarise': case 'summarize': return { kind: 'set', says: `Sums up ${args.some((a) => a.name === '.by') ? 'each group' : 'the rows'}: ${args.filter((a) => a.name && a.name !== '.by' && a.name !== '.groups').map((a) => `${rWords(a.name)} is ${sayValue(a.toks) ?? 'a calculation'}`).join(', ')}` };
536
+ case 'group_by': return { kind: 'set', says: `Groups the rows by ${colsOf(args)}` };
537
+ case 'ungroup': return { kind: 'set', says: 'Stops grouping the rows' };
538
+ case 'arrange': return { kind: 'set', says: `Sorts the rows by ${listWords(args.map((a) => { const c = callOf(at0(a.toks)); return c?.bare === 'desc' ? `${sayValue(c.args[0]?.toks ?? []) ?? '…'}, highest first` : sayValue(a.toks) ?? '…'; }))}` };
539
+ case 'head': case 'slice_head': { const n = args.find((a) => a.name === 'n') ?? plain[bare === 'head' ? 1 : 0]; return { kind: 'set', says: `Takes the first ${n ? sayValue(n.toks) : bare === 'head' ? '6' : '1'} rows` }; }
540
+ case 'tail': case 'slice_tail': { const n = args.find((a) => a.name === 'n') ?? plain[bare === 'tail' ? 1 : 0]; return { kind: 'set', says: `Takes the last ${n ? sayValue(n.toks) : '6'} rows` }; }
541
+ case 'slice_max': case 'slice_min': { const n = args.find((a) => a.name === 'n'); return { kind: 'set', says: `Takes the ${n ? sayValue(n.toks) : '1'} rows with the ${bare === 'slice_max' ? 'highest' : 'lowest'} ${plain[0] ? sayValue(plain[0].toks) : 'value'}` }; }
542
+ case 'left_join': case 'inner_join': case 'right_join': case 'full_join': case 'merge': { const by = args.find((a) => a.name === 'by'); const other = plain[0] ? sayValue(plain[0].toks) : 'the other table'; return { kind: 'call', callee: 'find', says: `${bare === 'inner_join' ? 'Keeps only the rows that match' : 'Adds the matching rows from'} ${other}${by ? `, by ${sayValue(by.toks)}` : ''}` }; }
543
+ case 'anti_join': return { kind: 'call', callee: 'filter', says: `Keeps only the rows with no match in ${plain[0] ? sayValue(plain[0].toks) : 'the other table'}` };
544
+ case 'count': case 'tally': return { kind: 'set', says: args.length ? `Counts the rows for each ${colsOf(plain)}` : 'Counts the rows' };
545
+ case 'distinct': case 'unique': return { kind: 'set', says: args.length ? `Keeps one row for each ${colsOf(plain)}` : 'Removes repeated rows' };
546
+ case 'rename': return { kind: 'set', says: `Renames ${listWords(args.filter((a) => a.name).map((a) => `${sayValue(a.toks) ?? '…'} to ${rWords(a.name)}`))}` };
547
+ case 'pull': return { kind: 'set', says: `Takes out the column ${plain[0] ? sayValue(plain[0].toks) : 'it needs'}` };
548
+ case 'drop_na': case 'na.omit': return { kind: 'call', callee: 'filter', says: 'Removes the rows with missing values' };
549
+ case 'bind_rows': case 'rbind': return { kind: 'set', says: `Adds the rows of ${listWords(plain.map((a) => sayValue(a.toks) ?? '…'))}` };
550
+ case 'pivot_longer': case 'pivot_wider': case 'gather': case 'spread': return { kind: 'set', says: `Reshapes the table ${/longer|gather/.test(bare) ? 'into more rows' : 'into more columns'}` };
551
+ case 'nrow': return { kind: 'set', says: 'Counts the rows' };
552
+ case 'print': return { kind: 'call', says: 'Shows it' };
553
+ case 'as_tibble': case 'as.data.frame': case 'data.frame': return { kind: 'set', says: 'Turns it into a table' };
554
+ default: {
555
+ const verb = callVerb({ ...call, args: [{ name: null, toks: [] }, ...args] });
556
+ if (verb) return { kind: 'call', says: verb.replace(/ \?/g, '') };
557
+ const noun = callNoun(call);
558
+ if (noun) return { kind: 'set', says: `Works out ${noun}` };
559
+ return { kind: 'call', says: `Calls ${rWords(bare)}`, callee: bare };
560
+ }
561
+ }
562
+ }
563
+
564
+ // ── The reader ────────────────────────────────────────────────────────────────────────────────────────
565
+
566
+ let KNOWN_FNS = new Set();
567
+
568
+ function makeReader(src) {
569
+ SRC = src;
570
+ const toks = tokenize(src);
571
+ const lineAt = lineFinder(src);
572
+ const fns = [], things = [], errors = new Map(), tests = [], defs = [];
573
+ const code = (s, e) => { const t = src.slice(toks[s].at, toks[e - 1].end).replace(/\s+/g, ' ').trim(); return t.length > 160 ? `${t.slice(0, 159)}…` : t; };
574
+ const head = (s, e) => { const t = src.slice(toks[s].at, toks[e - 1].end).split('\n')[0].trim(); return t.length > 160 ? `${t.slice(0, 159)}…` : t; };
575
+ const spanOf = (s, e) => ({ startLine: lineAt(toks[s].at), endLine: lineAt(toks[e - 1].end - 1) });
576
+ const base = (s, e, c = code(s, e)) => ({ code: c, line: lineAt(toks[s].at), span: spanOf(s, e) });
577
+ const next = (i, to) => { while (i < to && (toks[i].t === 'nl' || toks[i].t === 'comment')) i++; return i; };
578
+ const range = (list) => [list[0].i, list[list.length - 1].i + 1];
579
+
580
+ /** A body: `{ … }` (its statements) or one expression. Gives [from, to). */
581
+ const bodyRange = (i, to) => { const k = next(i, to); return isOp(toks[k], '{') && toks[k].match != null && toks[k].match < to ? [k + 1, toks[k].match, true] : [k, to, false]; };
582
+
583
+ function stepsIn(from, to, ctx = {}) {
584
+ const out = [];
585
+ const stmts = splitStatements(toks, from, to);
586
+ stmts.forEach(([s, e], n) => {
587
+ try { out.push(...statement(s, e, { ...ctx, last: ctx.last && n === stmts.length - 1 })); } catch (err) { if (typeof process !== 'undefined' && process.env?.R_DEBUG) console.error(err); out.push({ kind: 'other', says: code(s, e), ...base(s, e) }); }
588
+ });
589
+ return out;
590
+ }
591
+ /** Steps of an expression or block used as a branch, loop body, or handler. */
592
+ const stepsOfBody = (i, to, ctx) => { const [a, b] = bodyRange(i, to); return a < b ? stepsIn(a, b, ctx) : []; };
593
+
594
+ function ifSteps(s, e, ctx) {
595
+ const open = next(s + 1, e);
596
+ if (!isOp(toks[open], '(') || toks[open].match == null) return null;
597
+ const close = toks[open].match;
598
+ const condT = toks.slice(open + 1, close);
599
+ // Then-part: a block, or an expression up to `else`.
600
+ let k = next(close + 1, e), thenTo, elseAt = -1;
601
+ if (isOp(toks[k], '{') && toks[k].match != null) { thenTo = toks[k].match + 1; const n2 = next(thenTo, e); if (isId(toks[n2], 'else')) elseAt = n2; }
602
+ else { let d = k; for (; d < e; d++) { if (toks[d].match != null && toks[d].match < e) { d = toks[d].match; continue; } if (isId(toks[d], 'else')) { elseAt = d; break; } } thenTo = elseAt >= 0 ? elseAt : e; }
603
+ const c = condSaid(condT);
604
+ const step = { kind: 'branch', says: `If ${c ?? `\`${code(open + 1, close)}\``}`, cond: condJs(condT), code: head(s, e), line: lineAt(toks[s].at), span: spanOf(s, e) };
605
+ const kids = stepsOfBody(close + 1, thenTo, ctx);
606
+ if (kids.length) step.children = kids;
607
+ if (elseAt >= 0) {
608
+ const after = next(elseAt + 1, e);
609
+ if (isId(toks[after], 'if')) { const inner = ifSteps(after, e, ctx); if (inner) { inner.elseIf = true; inner.span = spanOf(after, e); step.otherwise = [inner]; } }
610
+ else { step.otherwise = stepsOfBody(elseAt + 1, e, ctx); step.otherwiseLine = lineAt(toks[elseAt].at); }
611
+ }
612
+ return step;
613
+ }
614
+
615
+ /** The value an expression gives back, as a step (last statement of a function, or `return(x)`). */
616
+ function returnStep(list, s, e) {
617
+ const v = at0(list);
618
+ const call = callOf(v);
619
+ if (call && (call.bare === 'return' || call.bare === 'invisible') && call.args.length <= 1) {
620
+ if (!call.args.length || !at0(call.args[0].toks).length) return { kind: 'return', says: 'Stops here', ...base(s, e) };
621
+ return returnStep(call.args[0].toks, s, e);
622
+ }
623
+ const pipe = pipeline(v);
624
+ if (pipe) return null;
625
+ const said = sayValue(v);
626
+ if (said) return { kind: 'return', says: `Returns ${said}`, ...base(s, e) };
627
+ if (call) { const verb = callVerb(call); if (verb) return { kind: 'return', says: `Returns the result of ${gerund(verb)}`, ...base(s, e) }; }
628
+ return { kind: 'return', says: 'Returns a computed value', restates: true, ...base(s, e) };
629
+ }
630
+
631
+ /** `x |> f() |> g()` or `x %>% f() %>% g()`: the source and each verb. Null when there is no pipe. */
632
+ function pipeline(v) {
633
+ const g = groups(v);
634
+ const parts = [[]];
635
+ for (const x of g) { if (x.length === 1 && (isOp(x[0], '|>') || isOp(x[0], '%>%'))) parts.push([]); else parts[parts.length - 1].push(...x); }
636
+ return parts.length > 1 ? parts : null;
637
+ }
638
+ function pipelineSteps(parts, s, e) {
639
+ const steps = [];
640
+ const src0 = at0(parts[0]);
641
+ const call0 = callOf(src0);
642
+ const verb0 = call0 ? callVerb(call0) : null;
643
+ steps.push(verb0 ? { kind: 'call', says: verb0 } : { kind: 'set', says: `Starts from ${sayValue(src0) ?? 'the data'}` });
644
+ for (const p of parts.slice(1)) {
645
+ const c = callOf(at0(p));
646
+ steps.push(c ? verbStep(c) : { kind: 'other', says: at0(p).map((t) => t.text).join(' ') });
647
+ }
648
+ return steps.map((x) => ({ ...x, ...base(s, e) }));
649
+ }
650
+
651
+ /** The function value in `name <- function(…) body`: its params and body token range. */
652
+ function fnValue(list) {
653
+ const v = at0(list);
654
+ if (!(isId(v[0], 'function') || isOp(v[0], '\\'))) return null;
655
+ const open = v[1];
656
+ if (!isOp(open, '(') || open.match == null) return null;
657
+ const params = argsOf(toks.slice(open.i + 1, open.match)).filter((a) => a.name || at0(a.toks).length).map((a) => ({ name: a.name ?? at0(a.toks)[0]?.text, type: null, default: a.name ? a.toks : null }));
658
+ const end = v[v.length - 1].i + 1;
659
+ return { params: params.filter((p) => p.name && p.name !== '...'), from: open.match + 1, to: end };
660
+ }
661
+ function docAbove(s) {
662
+ const lines = [];
663
+ let route = null;
664
+ let k = s - 1;
665
+ while (k >= 0 && toks[k].t === 'nl') k--;
666
+ const run = [];
667
+ while (k >= 0 && toks[k].t === 'comment') { run.unshift(toks[k].text); k--; while (k >= 0 && toks[k].t === 'nl' && toks[k - 1]?.t === 'comment' && toks[k - 1].end === toks[k].at) k--; if (toks[k]?.t === 'nl') { if (toks[k - 1]?.t !== 'comment') break; k--; } }
668
+ for (const r of run) {
669
+ const t = r.replace(/^#['*]?\s?/, '').trim();
670
+ const m = t.match(/^@(get|post|put|delete|patch|head)\s+(\S+)/i);
671
+ if (m && /^#[*']/.test(r)) { route = { method: m[1].toUpperCase(), path: m[2] }; continue; }
672
+ if (/^@/.test(t)) { if (lines.length) break; continue; }
673
+ if (!t) { if (lines.length) break; continue; }
674
+ lines.push(t);
675
+ }
676
+ const doc = lines.join(' ').replace(/\s+/g, ' ').trim();
677
+ return { doc: doc ? (doc.length > 300 ? `${doc.slice(0, 299)}…` : doc) : null, route };
678
+ }
679
+ function defineFunction(name, fv, s, nameTok, owner = null) {
680
+ const { doc, route } = docAbove(s);
681
+ const params = fv.params.map((p) => ({ name: p.name, type: null }));
682
+ const fnSteps = stepsOfBody(fv.from, fv.to, { last: true, fn: true });
683
+ if (!fnSteps.length) fnSteps.push({ kind: 'return', says: 'Does nothing', ...base(nameTok.i, fv.to, head(nameTok.i, fv.to)) });
684
+ const [a, b] = bodyRange(fv.from, fv.to);
685
+ const f = { name: route && !name ? `${route.method} ${route.path}` : name, line: lineAt(nameTok.at), params, doc, steps: fnSteps, body: a < b && next(a, b) < b ? [lineAt(toks[next(a, b)].at), lineAt(toks[b - 1].end - 1)] : null, ...(route ? { route } : {}), _fv: fv, ...(owner ? { owner } : {}) };
686
+ fns.push(f);
687
+ return f;
688
+ }
689
+
690
+ function statement(s, e, ctx) {
691
+ const v = at0(toks.slice(s, e));
692
+ const t0 = v[0];
693
+ if (!t0) return [];
694
+ if (isId(t0, 'if')) { const st = ifSteps(s, e, ctx); return st ? [st] : [{ kind: 'other', says: code(s, e), ...base(s, e) }]; }
695
+ if (isId(t0, 'for')) {
696
+ const open = v[1];
697
+ if (!isOp(open, '(') || open.match == null) return [{ kind: 'other', says: code(s, e), ...base(s, e) }];
698
+ const inner = at0(toks.slice(open.i + 1, open.match));
699
+ const inAt = inner.findIndex((x) => isId(x, 'in'));
700
+ const x = inner[0]?.text ?? 'item';
701
+ const over = inner.slice(inAt + 1);
702
+ const call = callOf(over);
703
+ const og = groups(over);
704
+ let says;
705
+ if (call?.bare === 'seq_along') says = `For each position ${rWords(x)} in ${sayValue(call.args[0]?.toks ?? []) ?? 'the list'}`;
706
+ else if (call?.bare === 'seq_len') says = `Counts ${rWords(x)} from 1 to ${sayValue(call.args[0]?.toks ?? []) ?? 'n'}`;
707
+ else if (og.length === 3 && isOp(og[1][0], ':')) says = `Counts ${rWords(x)} from ${sayValue(og[0]) ?? '?'} to ${sayValue(og[2]) ?? '?'}`;
708
+ else says = `For each ${rWords(x)} in ${sayValue(over) ?? 'the list'}`;
709
+ const kids = stepsOfBody(open.match + 1, e, { ...ctx, last: false });
710
+ return [{ kind: 'loop', says, ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) }];
711
+ }
712
+ if (isId(t0, 'while')) {
713
+ const open = v[1];
714
+ if (!isOp(open, '(') || open.match == null) return [{ kind: 'other', says: code(s, e), ...base(s, e) }];
715
+ const c = condSaid(toks.slice(open.i + 1, open.match));
716
+ const kids = stepsOfBody(open.match + 1, e, { ...ctx, last: false });
717
+ return [{ kind: 'loop', says: c === 'always' ? 'Repeats until something stops it' : `Repeats while ${c ?? 'a condition holds'}`, ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) }];
718
+ }
719
+ if (isId(t0, 'repeat')) { const kids = stepsOfBody(t0.i + 1, e, { ...ctx, last: false }); return [{ kind: 'loop', says: 'Repeats until something stops it', ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) }]; }
720
+ if (isId(t0, 'break') && v.length === 1) return [];
721
+ if (isId(t0, 'next') && v.length === 1) return [{ kind: 'call', says: 'Skips to the next one', ...base(s, e) }];
722
+ if (isId(t0, 'NULL') && v.length === 1) return [];
723
+ // Assignment: name <- value, name = value, name <<- value, value -> name.
724
+ const g = groups(v);
725
+ const asg = g.findIndex((x) => x.length === 1 && x[0].t === 'op' && (x[0].text === '<-' || x[0].text === '<<-' || x[0].text === '='));
726
+ const rasg = g.findIndex((x) => x.length === 1 && x[0].t === 'op' && (x[0].text === '->' || x[0].text === '->>'));
727
+ if (asg > 0 || rasg > 0) {
728
+ const lhs = asg > 0 ? g.slice(0, asg).flat() : g.slice(rasg + 1).flat();
729
+ let rhs = asg > 0 ? g.slice(asg + 1).flat() : g.slice(0, rasg).flat();
730
+ // a <- b <- NULL: every name gets the same value.
731
+ const names = [];
732
+ for (let rg = groups(rhs), at = rg.findIndex((x) => x.length === 1 && isOp(x[0], '<-')); asg > 0 && at === 1 && rg[0][0].t === 'id'; rg = groups(rhs), at = rg.findIndex((x) => x.length === 1 && isOp(x[0], '<-'))) { names.push(rWords(rg[0][0].text)); rhs = rg.slice(2).flat(); }
733
+ if (names.length) { const val = sayValue(rhs); return [{ kind: 'set', says: `Sets ${listWords([sayValue(lhs) ?? 'a value', ...names])} to ${val ?? 'a computed value'}`, ...(val ? {} : { restates: true }), ...base(s, e) }]; }
734
+ return assignSteps(lhs, rhs, s, e, ctx);
735
+ }
736
+ // Anonymous function at the top level: a plumber endpoint (#* @get /path above it).
737
+ const fv = fnValue(v);
738
+ if (fv) { const f = defineFunction(null, fv, s, t0); if (!f.route) f.name = `function at line ${f.line}`; return []; }
739
+ return exprSteps(v, s, e, ctx);
740
+ }
741
+
742
+ function assignSteps(lhs, rhs, s, e, ctx) {
743
+ const lv = at0(lhs);
744
+ // names(x) <- v, levels(x) <- v, attr(x, "a") <- v: a replacement function sets that part of x.
745
+ const repl = callOf(lv);
746
+ const replOf = repl && repl.args.length ? sayValue(repl.args[0].toks) : null;
747
+ const target = repl && replOf
748
+ ? (repl.bare === 'attr' && repl.args[1] ? `the ${sayValue(repl.args[1].toks) ?? '…'} attribute of ${replOf}` : `the ${rWords(repl.bare)} of ${replOf}`)
749
+ : sayValue(lv) ?? (lv[0] ? rWords(lv[0].text) : 'a value');
750
+ const rv0 = at0(rhs);
751
+ // x[[k]] <- NULL removes the item; is_x <- is.x makes another name for the same function.
752
+ if (rv0.length === 1 && isId(rv0[0], 'NULL') && groups(lv).at(-1)?.[0]?.text === '[[') return [{ kind: 'set', says: `Removes ${target}`, ...base(s, e) }];
753
+ if (lv.length === 1 && rv0.length === 1 && rv0[0].t === 'id' && lv[0].text !== rv0[0].text && rWords(lv[0].text) === rWords(rv0[0].text)) return [{ kind: 'set', says: `Makes ${lv[0].text} another name for ${rv0[0].text}`, ...base(s, e) }];
754
+ const fv = fnValue(rhs);
755
+ if (fv && lv.length === 1) {
756
+ defineFunction(lv[0].text, fv, s, lv[0]);
757
+ return ctx.fn ? [{ kind: 'set', says: `Defines a helper, ${rWords(lv[0].text)}`, ...base(s, e, head(s, e)) }] : [];
758
+ }
759
+ const rv = at0(rhs);
760
+ const call = callOf(rv);
761
+ if (call && /^(R6Class|setRefClass|setClass)$/.test(call.bare)) { defineThing(lv[0]?.text ?? '', call, s, e); return []; }
762
+ if (call && call.bare === 'tryCatch') return [tryStep(call, s, e, ctx, target)];
763
+ if (call && /^(lapply|sapply|vapply|map|map_chr|map_dbl|map_int|map_lgl|map_dfr|purrr::map|Map|mapply)$/.test(call.bare)) { const l = loopOfApply(call, s, e, ctx); if (l) return [{ ...l, says: `${l.says}, keeping the answers as ${target}` }]; }
764
+ if (isId(rv[0], 'if')) { const st = ifSteps(rv[0].i, e, { ...ctx, last: true }); if (st) { giveValue(st, target); return [st]; } }
765
+ const pipe = pipeline(rv);
766
+ if (pipe) return [{ kind: 'set', says: `Works out ${target}, step by step`, ...base(s, e, head(s, e)), children: pipelineSteps(pipe, s, e) }];
767
+ if (lv.length >= 3 && isId(lv[0], 'self') && isOp(lv[1], '$') && rv.length === 1 && rv[0].t === 'id' && rv[0].text === lv[2].text) return [{ kind: 'set', says: `Keeps the ${rWords(rv[0].text)} it is given`, ...base(s, e) }];
768
+ if (lv.length === 1 && rv.length === 1 && rv[0].t === 'id' && ctx.fn && rv[0].text === lv[0].text) return [{ kind: 'set', says: `Keeps the ${rWords(rv[0].text)} it is given`, ...base(s, e) }];
769
+ if (call) {
770
+ if (call.bare === 'switch') { const st = switchStep(call, s, e, { ...ctx, last: true }); giveValue(st, target); return [st]; }
771
+ const verb = callVerb(call);
772
+ if (verb) return [{ kind: 'call', says: `${verb}, keeping it as ${target}`, callee: call.bare, ...base(s, e) }];
773
+ const noun = callNoun(call);
774
+ if (noun) return [{ kind: 'set', says: noun === 'an empty list' || noun === 'an empty table' ? `Starts ${target} as ${noun}` : `Sets ${target} to ${noun}`, ...base(s, e) }];
775
+ return [{ kind: 'set', says: `Works out ${target} from ${rWords(call.bare)}`, callee: call.bare, ...base(s, e) }];
776
+ }
777
+ const val = sayValue(rv);
778
+ return [{ kind: 'set', says: val ? `Sets ${target} to ${val}` : `Works out ${target}`, ...(val ? {} : { restates: true }), ...base(s, e) }];
779
+ }
780
+
781
+ /** Make the last value in each side of a choice say it sets `target` (or returns, when target is null). */
782
+ function giveValue(step, target) {
783
+ const fix = (list) => {
784
+ if (!list?.length) return;
785
+ const last = list[list.length - 1];
786
+ if (last.kind === 'branch') { fix(last.children); fix(last.otherwise); for (const c of last.children || []) if (c.caseLabel) fix(c.children); return; }
787
+ if (last.kind === 'return' && /^Returns /.test(last.says) && target) list[list.length - 1] = { ...last, kind: 'set', says: last.says.replace(/^Returns /, `Sets ${target} to `) };
788
+ };
789
+ fix([step]);
790
+ }
791
+
792
+ function loopOfApply(call, s, e, ctx) {
793
+ const [xs, f] = call.args.filter((a) => !a.name || a.name === 'X' || a.name === 'FUN' || a.name === '.x' || a.name === '.f');
794
+ if (!xs || !f) return null;
795
+ const fv = fnValue(f.toks);
796
+ const what = sayValue(xs.toks) ?? 'the list';
797
+ if (!fv) { const fname = at0(f.toks)[0]; return { kind: 'loop', says: `For each item in ${what}, runs ${rWords(fname?.text ?? 'a function')}`, ...base(s, e) }; }
798
+ const kids = stepsOfBody(fv.from, fv.to, { ...ctx, last: true, fn: true });
799
+ return { kind: 'loop', says: `For each ${rWords(fv.params[0]?.name ?? 'item')} in ${what}`, ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}) };
800
+ }
801
+
802
+ function tryStep(call, s, e, ctx, target = null) {
803
+ const step = { kind: 'try', says: `Tries these steps and handles any error${target ? ` (the answer becomes ${target})` : ''}`, ...base(s, e, head(s, e)) };
804
+ const expr = call.args.find((a) => !a.name || a.name === 'expr');
805
+ if (expr && at0(expr.toks).length) { const r = range(at0(expr.toks)); const kids = stepsOfBody(r[0], r[1], { ...ctx, last: !!target || ctx.last }); if (kids.length) step.children = kids; }
806
+ for (const a of call.args.filter((x) => x.name && x.name !== 'expr')) {
807
+ const fv = fnValue(a.toks);
808
+ const r = at0(a.toks).length ? range(at0(a.toks)) : null;
809
+ if (a.name === 'finally') { step.always = { line: lineAt(at0(a.toks)[0]?.at ?? toks[s].at), steps: r ? stepsOfBody(r[0], r[1], { ...ctx, last: false }) : [] }; continue; }
810
+ const says = a.name === 'error' ? 'If anything goes wrong' : a.name === 'warning' ? 'If there is a warning' : a.name === 'message' ? 'If a message is written' : a.name === 'interrupt' ? 'If it is stopped' : `If ${a.name} goes wrong`;
811
+ (step.handlers ||= []).push({ says, line: lineAt(at0(a.toks)[0]?.at ?? toks[s].at), steps: fv ? stepsOfBody(fv.from, fv.to, { ...ctx, last: !!target || ctx.last, fn: true }) : [] });
812
+ }
813
+ if (target) { for (const list of [step.children, ...(step.handlers || []).map((h) => h.steps)]) if (list?.length) giveValue({ kind: 'branch', children: list }, target); }
814
+ return step;
815
+ }
816
+
817
+ function switchStep(call, s, e, ctx) {
818
+ const [subject, ...rest] = call.args;
819
+ const arms = [];
820
+ let pending = [];
821
+ for (const a of rest) {
822
+ const vtoks = at0(a.toks);
823
+ if (a.name && !vtoks.length) { pending.push(a.name); continue; }
824
+ const names = a.name ? [...pending, a.name] : null;
825
+ pending = [];
826
+ const r = vtoks.length ? range(vtoks) : null;
827
+ const kids = r ? stepsOfBody(r[0], r[1], ctx) : [];
828
+ arms.push({ kind: 'check', says: names ? `When it is ${listWords(names.map((n) => `"${n}"`)).replace(/,? and ([^,]*)$/, ' or $1')}` : 'Otherwise', caseLabel: true, code: names ? `${names.join(', ')} =` : '(default)', line: lineAt(vtoks[0]?.at ?? toks[s].at), span: r ? spanOf(r[0], r[1]) : spanOf(s, e), ...(kids.length ? { children: kids } : {}) });
829
+ }
830
+ return { kind: 'branch', says: `Chooses by ${sayValue(subject?.toks ?? []) ?? 'value'}`, ...base(s, e, head(s, e)), ...(arms.length ? { children: arms } : {}) };
831
+ }
832
+
833
+ function exprSteps(v, s, e, ctx) {
834
+ const pipe = pipeline(v);
835
+ if (pipe) {
836
+ const steps = pipelineSteps(pipe, s, e);
837
+ if (ctx.last) steps.push({ kind: 'return', says: 'Returns the result', ...base(s, e) });
838
+ return steps;
839
+ }
840
+ const call = callOf(v);
841
+ if (call) {
842
+ const { bare, args } = call;
843
+ const a0 = args[0] ? sayValue(args[0].toks) : null;
844
+ if (bare === 'stop' || bare === 'abort' || bare === 'cli_abort' || bare === 'stopf') {
845
+ // Only cli_abort fills in {…}; stop() and rlang's abort() show their text as written.
846
+ const parts = args.filter((a) => !a.name || a.name === 'message').map((a) => ({ ...a, name: null }));
847
+ const one = at0(parts[0]?.toks ?? []);
848
+ const isVar = parts.length === 1 && one.length === 1 && one[0].t === 'id';
849
+ const single = !isVar && oneValue(parts) ? sayValue(parts[0].toks) : null;
850
+ const msg = isVar || single || !parts.length ? null : textOf(parts, '', bare === 'cli_abort');
851
+ if (msg) errors.set(msg, errors.get(msg) ?? lineAt(toks[s].at));
852
+ const cls = args.find((a) => a.name === 'class');
853
+ const name = cls ? (at0(cls.toks)[0]?.value ?? 'an error') : 'an error';
854
+ const says = isVar ? `Fails with the error in ${rWords(one[0].text)}` : single ? `Fails with the error ${/^the result of /.test(single) ? single.replace(/^the result of /, 'made by ') : `in ${single}`}` : `Fails with ${name}${msg ? `: "${msg}"` : ''}`;
855
+ return [{ kind: 'fail', says, error: name, ...(msg ? { message: msg } : {}), ...base(s, e) }];
856
+ }
857
+ if (bare === 'deprecate_stop') {
858
+ const what = at0(args[1]?.toks ?? [])[0]?.value;
859
+ // lifecycle writes the message; Thunder says what it is about, without inventing its text.
860
+ const msg = `${what ?? 'This'} is no longer available`;
861
+ return [{ kind: 'fail', says: `Fails with an error: ${what ? quote(what) : 'this'} is no longer available (deprecated)`, error: 'an error', message: msg, ...base(s, e) }];
862
+ }
863
+ if (bare === 'stopifnot') {
864
+ const c = args.map((a) => (a.name ? quote(a.name) : condSaid(a.toks)));
865
+ return [{ kind: 'check', says: `Checks that ${c.every(Boolean) ? c.join(' and ') : 'its conditions hold'} (stops with an error if not)`, ...base(s, e) }];
866
+ }
867
+ if (/^(library|require|requireNamespace|suppressPackageStartupMessages|suppressMessages)$/.test(bare)) {
868
+ const inner = bare.startsWith('suppress') ? callOf(at0(args[0]?.toks ?? [])) : call;
869
+ if (inner && /^(library|require)$/.test(inner.bare)) { const p = at0(inner.args[0]?.toks ?? [])[0]; return [{ kind: 'set', says: `Loads the ${p?.value ?? p?.text ?? '?'} package`, ...base(s, e) }]; }
870
+ if (!inner) return [{ kind: 'call', says: 'Runs it quietly', ...base(s, e) }];
871
+ }
872
+ if (bare === 'source') return [{ kind: 'call', says: `Runs the R file ${a0 ?? '?'}`, ...base(s, e) }];
873
+ if (bare === 'tryCatch' || bare === 'withCallingHandlers') return [tryStep(call, s, e, ctx)];
874
+ if (bare === 'try') {
875
+ const r = args[0] && at0(args[0].toks).length ? range(at0(args[0].toks)) : null;
876
+ const kids = r ? stepsOfBody(r[0], r[1], { ...ctx, last: false }) : [];
877
+ return [{ kind: 'try', says: 'Tries these steps, and carries on if they fail', ...base(s, e, head(s, e)), ...(kids.length ? { children: kids } : {}), handlers: [{ says: 'If anything goes wrong', line: lineAt(toks[s].at), steps: [] }] }];
878
+ }
879
+ if (bare === 'on.exit') {
880
+ const r = args[0] && at0(args[0].toks).length ? range(at0(args[0].toks)) : null;
881
+ const kids = r ? stepsOfBody(r[0], r[1], { ...ctx, last: false }) : [];
882
+ return [{ kind: 'call', says: 'At the end, even if something fails, it runs these steps', ...base(s, e, head(s, e)), ...(kids.length ? { children: kids, nested: true } : {}) }];
883
+ }
884
+ if (bare === 'switch') return [switchStep(call, s, e, ctx)];
885
+ if (/^(lapply|sapply|vapply|map|walk|map_chr|map_dbl|map_int|map_lgl|map_dfr|Map|mapply|purrr::walk)$/.test(bare)) { const l = loopOfApply(call, s, e, ctx); if (l) return [l]; }
886
+ if (bare === 'test_that') { const name = at0(args[0]?.toks ?? [])[0]?.value; if (name) tests.push({ name, line: lineAt(toks[s].at) }); return []; }
887
+ if (bare === 'return' || bare === 'invisible') { const r = returnStep(v, s, e); return r ? [r] : []; }
888
+ if (/^(setGeneric|setValidity|setMethod)$/.test(bare)) {
889
+ if (bare === 'setMethod') {
890
+ const name = at0(args[0]?.toks ?? [])[0]?.value;
891
+ const cls = at0(args[1]?.toks ?? [])[0]?.value;
892
+ const def = args.find((a) => a.name === 'definition') ?? args[2];
893
+ const fv2 = def ? fnValue(def.toks) : null;
894
+ if (name && fv2) defineFunction(name, fv2, s, toks[s], cls);
895
+ }
896
+ return [];
897
+ }
898
+ if (ctx.last) { const r = returnStep(v, s, e); if (r && !r.restates) return [r]; }
899
+ const verb = callVerb(call);
900
+ if (verb) return [{ kind: 'call', says: verb, callee: bare, ...base(s, e) }];
901
+ if (ctx.last) { const r = returnStep(v, s, e); if (r) return [r]; }
902
+ return [{ kind: 'call', says: `Calls ${rWords(bare)}`, callee: bare, ...base(s, e) }];
903
+ }
904
+ if (ctx.last) { const r = returnStep(v, s, e); if (r) return [r]; }
905
+ const val = sayValue(v);
906
+ return [val ? { kind: 'call', says: `Works out ${val}`, ...base(s, e) } : { kind: 'other', says: code(s, e), ...base(s, e) }];
907
+ }
908
+
909
+ // ── Things: R6Class, setRefClass, setClass ──
910
+ function defineThing(name, call, s, e) {
911
+ const lines = [lineAt(toks[s].at), lineAt(toks[e - 1].end - 1)];
912
+ const className = at0(call.args[0]?.toks ?? [])[0]?.value ?? (at0(call.args.find((a) => a.name === 'Classname')?.toks ?? [])[0]?.value) ?? name;
913
+ const { doc } = docAbove(s);
914
+ const thing = { kind: 'record', name: className || name, lines, ...(doc ? { doc } : {}), knows: [], choices: [], memberRanges: [] };
915
+ const listArgs = (a) => { const c = a ? callOf(at0(a.toks)) : null; return c && /^(list|c|representation)$/.test(c.bare) ? c.args : null; };
916
+ const R_TYPE = { numeric: 'number', integer: 'int', character: 'string', logical: 'bool', Date: 'date', list: null, 'data.frame': null };
917
+ const knowsFrom = (args, typed) => {
918
+ for (const a of args || []) {
919
+ if (!a.name) { const sv = at0(a.toks)[0]; if (sv?.t === 'str') thing.knows.push({ name: sv.value, type: null, start: null, line: lineAt(sv.at) }); continue; }
920
+ const vt = at0(a.toks);
921
+ if (fnValue(vt)) continue;
922
+ const tv = typed && vt.length === 1 && vt[0].t === 'str' ? vt[0].value : null;
923
+ thing.knows.push({ name: a.name, type: tv ? (R_TYPE[tv] ?? tv) : null, start: typed ? null : vt.map((x) => x.text).join(''), line: lineAt(vt[0]?.at ?? toks[s].at) });
924
+ }
925
+ };
926
+ let methods = 0;
927
+ const methodsFrom = (args) => {
928
+ for (const a of args || []) {
929
+ const fv = a.name ? fnValue(a.toks) : null;
930
+ if (!fv) continue;
931
+ const f = defineFunction(a.name, fv, at0(a.toks)[0].i, toks[at0(a.toks)[0].i - 2] ?? toks[s]);
932
+ f.line = lineAt(toks[at0(a.toks)[0].i - 2]?.at ?? toks[s].at);
933
+ if (a.name !== 'initialize') methods++;
934
+ if (a.name === 'initialize') {
935
+ // Starting values: self$x <- param, or .self / field <<- param.
936
+ const byName = new Map(fv.params.map((p) => [p.name, p.default ? at0(p.default).map((x) => x.text).join('') : null]));
937
+ const [ba, bb] = bodyRange(fv.from, fv.to);
938
+ for (const [x, y] of splitStatements(toks, ba, bb)) {
939
+ const st = at0(toks.slice(x, y));
940
+ const m = st.length >= 5 && /^(self|\.self)$/.test(st[0].text) && isOp(st[1], '$') && (isOp(st[3], '<-') || isOp(st[3], '=')) ? [st[2].text, st.slice(4)] : st.length >= 3 && st[0].t === 'id' && isOp(st[1], '<<-') ? [st[0].text, st.slice(2)] : null;
941
+ if (!m) continue;
942
+ const [field, val] = m;
943
+ const k = thing.knows.find((q) => q.name === field);
944
+ const start = val.length === 1 && byName.has(val[0].text) ? { param: byName.get(val[0].text) } : val.map((q) => q.text).join('');
945
+ if (k) { if (k.start == null || typeof start === 'object') k.start = start; } else thing.knows.push({ name: field, type: null, start, line: lineAt(st[0].at) });
946
+ }
947
+ }
948
+ }
949
+ };
950
+ if (call.bare === 'R6Class') {
951
+ for (const part of ['public', 'private', 'active']) { const args = listArgs(call.args.find((a) => a.name === part)); knowsFrom(args, false); methodsFrom(args); }
952
+ } else if (call.bare === 'setRefClass') {
953
+ knowsFrom(listArgs(call.args.find((a) => a.name === 'fields')), true);
954
+ methodsFrom(listArgs(call.args.find((a) => a.name === 'methods')));
955
+ } else {
956
+ knowsFrom(listArgs(call.args.find((a) => a.name === 'representation' || a.name === 'slots') ?? call.args.find((a, k) => k === 1 && !a.name)), true);
957
+ for (const p of listArgs(call.args.find((a) => a.name === 'prototype')) || []) { const k = thing.knows.find((q) => q.name === p.name); if (k) k.start = at0(p.toks).map((x) => x.text).join(''); }
958
+ }
959
+ if (methods) thing.kind = 'thing';
960
+ thing._methods = methods;
961
+ things.push(thing);
962
+ }
963
+
964
+ return { toks, fns, things, errors, tests, stepsIn, lineAt, next, statement, code, base };
965
+ }
966
+
967
+ // ── Decisions: a function that only chooses between fixed answers ─────────────────────────────────────────
968
+
969
+ function decisionOf(r, fv) {
970
+ const { toks } = r;
971
+ const [from, to] = (() => { const k = r.next(fv.from, fv.to); return isOp(toks[k], '{') && toks[k].match != null ? [k + 1, toks[k].match] : [k, fv.to]; })();
972
+ const stmts = splitStatements(toks, from, to);
973
+ const rules = [];
974
+ let otherwise = null;
975
+ const valueOf = (a, b) => {
976
+ const k = r.next(a, b);
977
+ if (isOp(toks[k], '{') && toks[k].match != null) { const st = splitStatements(toks, k + 1, toks[k].match); return st.length === 1 ? fixedOf(toks.slice(st[0][0], st[0][1])) : null; }
978
+ return fixedOf(toks.slice(k, b));
979
+ };
980
+ const ifChain = (s, e, isLast) => {
981
+ const local = [];
982
+ let at = s;
983
+ for (;;) {
984
+ const open = r.next(at + 1, e);
985
+ if (!isOp(toks[open], '(') || toks[open].match == null) return null;
986
+ const cond = condJs(toks.slice(open + 1, toks[open].match));
987
+ if (!cond) return null;
988
+ let k = r.next(toks[open].match + 1, e), thenTo, elseAt = -1;
989
+ if (isOp(toks[k], '{') && toks[k].match != null) { thenTo = toks[k].match + 1; const n2 = r.next(thenTo, e); if (isId(toks[n2], 'else')) elseAt = n2; }
990
+ else { let d = k; for (; d < e; d++) { if (toks[d].match != null && toks[d].match < e) { d = toks[d].match; continue; } if (isId(toks[d], 'else')) { elseAt = d; break; } } thenTo = elseAt >= 0 ? elseAt : e; }
991
+ const thenToks = toks.slice(toks[open].match + 1, thenTo);
992
+ const val = valueOf(toks[open].match + 1, thenTo);
993
+ // Before the last statement, a branch answers only through return().
994
+ if (!val || (!isLast && !at0(thenToks).some((x) => isId(x, 'return')))) return null;
995
+ local.push({ cond, result: val, line: r.lineAt(toks[at].at) });
996
+ if (elseAt < 0) return { local, fallback: null };
997
+ const after = r.next(elseAt + 1, e);
998
+ if (isId(toks[after], 'if')) { at = after; continue; }
999
+ const fb = valueOf(elseAt + 1, e);
1000
+ if (!fb || !isLast) return null;
1001
+ return { local, fallback: { result: fb, line: r.lineAt(toks[elseAt].at) } };
1002
+ }
1003
+ };
1004
+ for (let n = 0; n < stmts.length; n++) {
1005
+ const [s, e] = stmts[n];
1006
+ const isLast = n === stmts.length - 1;
1007
+ const first = toks[s];
1008
+ if (isId(first, 'if')) {
1009
+ const c = ifChain(s, e, isLast);
1010
+ if (!c) return null;
1011
+ rules.push(...c.local);
1012
+ if (c.fallback) otherwise = c.fallback;
1013
+ continue;
1014
+ }
1015
+ if (!isLast) return null;
1016
+ const v = at0(toks.slice(s, e));
1017
+ const call = callOf(v);
1018
+ if (call?.bare === 'switch') {
1019
+ const subj = condJs(call.args[0]?.toks ?? []);
1020
+ if (!subj || /\s/.test(subj)) return null;
1021
+ let pending = [];
1022
+ for (const a of call.args.slice(1)) {
1023
+ const vt = at0(a.toks);
1024
+ if (a.name && !vt.length) { pending.push(a.name); continue; }
1025
+ const val = fixedOf(vt);
1026
+ if (!val) return null;
1027
+ if (!a.name) { otherwise = { result: val, line: r.lineAt(vt[0].at) }; continue; }
1028
+ for (const nm of [...pending, a.name]) rules.push({ cond: `${subj} == ${JSON.stringify(nm)}`, result: val, line: r.lineAt(vt[0].at) });
1029
+ pending = [];
1030
+ }
1031
+ continue;
1032
+ }
1033
+ const val = fixedOf(v);
1034
+ if (!val) return null;
1035
+ otherwise = { result: val, line: r.lineAt(first.at) };
1036
+ }
1037
+ return rules.length && otherwise ? { rules, otherwise } : null;
1038
+ }
1039
+
1040
+ const DEFINITION = /^(?:library|require|suppressPackageStartupMessages|setGeneric|setMethod|setValidity|setClass|setRefClass|R6Class|test_that|context|NULL)$/;
1041
+
1042
+ /** Read an R file: functions (with steps or decision rules), plumber routes, Things, errors, and testthat tests. */
1043
+ export function rReading(src, file = '') {
1044
+ KNOWN_FNS = new Set([...src.matchAll(/^\s*([A-Za-z.][\w.]*)\s*(?:<-|=|<<-)\s*function\b/gm)].map((m) => m[1]));
1045
+ const r = makeReader(src);
1046
+ const topSteps = [];
1047
+ let real = false;
1048
+ for (const [s, e] of splitStatements(r.toks, 0, r.toks.length)) {
1049
+ const v = at0(r.toks.slice(s, e));
1050
+ const steps = r.statement(s, e, {});
1051
+ const call = callOf(v);
1052
+ const assign = groups(v).findIndex((x) => x.length === 1 && x[0].t === 'op' && /^(<-|=|<<-)$/.test(x[0].text));
1053
+ const rhs = assign > 0 ? callOf(groups(v).slice(assign + 1).flat()) : null;
1054
+ const isDef = (call && DEFINITION.test(call.bare)) || (rhs && DEFINITION.test(rhs.bare)) || !steps.length;
1055
+ if (!isDef) real = true;
1056
+ topSteps.push(...steps);
1057
+ }
1058
+ for (const f of r.fns) {
1059
+ const d = decisionOf(r, f._fv);
1060
+ if (d) f.decision = d;
1061
+ delete f._fv;
1062
+ }
1063
+ const fns = r.fns.filter((f) => !/^function at line /.test(f.name) || f.route);
1064
+ if (real && topSteps.length) {
1065
+ const name = file ? String(file).split(/[\\/]/).pop() : 'script';
1066
+ fns.push({ name, line: topSteps[0].line, params: [], doc: null, steps: topSteps, body: [topSteps[0].span.startLine, topSteps[topSteps.length - 1].span.endLine], topLevel: true, headline: `Runs ${name}, from top to bottom.` });
1067
+ }
1068
+ fns.sort((a, b) => a.line - b.line);
1069
+ // Methods written with setMethod("name", "Class", …) belong to that class.
1070
+ for (const f of fns) if (f.owner) { const t = r.things.find((x) => x.name === f.owner); if (t) { t.memberRanges.push([f.line, f.body?.[1] ?? f.line]); if (t.kind === 'record') t.kind = 'thing'; } delete f.owner; }
1071
+ KNOWN_FNS = new Set();
1072
+ return { fns, things: r.things.map(({ _methods, ...t }) => t), errors: [...r.errors].map(([name, line]) => ({ name, line })), tests: r.tests };
1073
+ }
1074
+
1075
+ /** Things from an R file, in the model's shape. */
1076
+ export function rThings(src, file, { words: w, kindWords, startValue }) {
1077
+ const norm = (v) => String(v ?? '').trim().replace(/^(?:list|c|character|numeric|integer|logical|vector)\(\s*(?:0)?\s*\)$/, '[]').replace(/^NULL$/, 'null').replace(/^NA$/, 'null').replace(/^TRUE$/, 'true').replace(/^FALSE$/, 'false').replace(/^(\d+)L$/, '$1').replace(/^'(.*)'$/, '"$1"');
1078
+ return rReading(src, file).things.map((t) => ({
1079
+ kind: t.kind, name: t.name, file, lines: t.lines, ...(t.doc ? { doc: t.doc } : {}), choices: t.choices, memberRanges: t.memberRanges,
1080
+ knows: t.knows.map((k) => ({ name: k.name, label: w(k.name.replace(/\./g, '_')), kind: k.type ? kindWords(k.type) : null, start: k.start == null || k.start === '' ? null : typeof k.start === 'object' ? (k.start.param == null ? 'given when it starts' : `${startValue(norm(k.start.param))?.replace(/ at first$/, '')} unless told otherwise`) : startValue(norm(k.start)), line: k.line })),
1081
+ }));
1082
+ }
1083
+
1084
+ export { cap };