@skillstech/thunderlang 1.0.3 → 1.1.0

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 (74) hide show
  1. package/CHANGELOG.md +207 -0
  2. package/dist/core.cjs +13779 -10043
  3. package/dist/index.cjs +28500 -24392
  4. package/dist/learn.cjs +12853 -9579
  5. package/intent-graph.schema.json +11 -0
  6. package/package.json +6 -2
  7. package/src/cli.mjs +141 -58
  8. package/src/codegen.mjs +145 -55
  9. package/src/conformance.mjs +15 -6
  10. package/src/core/check.mjs +725 -0
  11. package/src/core/cli.mjs +133 -0
  12. package/src/core/diagnostics.mjs +81 -0
  13. package/src/core/format.mjs +20 -0
  14. package/src/core/from-python.mjs +645 -0
  15. package/src/core/index.mjs +38 -0
  16. package/src/core/lexer.mjs +115 -0
  17. package/src/core/parser.mjs +742 -0
  18. package/src/core/project.mjs +167 -0
  19. package/src/core/round-trip.mjs +150 -0
  20. package/src/core/runtime-python.mjs +801 -0
  21. package/src/core/target-python.mjs +486 -0
  22. package/src/core.d.ts +5 -2
  23. package/src/core.mjs +5 -2
  24. package/src/data-schema.mjs +8 -1
  25. package/src/emit.mjs +1 -1
  26. package/src/evidence.mjs +1 -1
  27. package/src/expr.mjs +81 -4
  28. package/src/form-words.mjs +2 -0
  29. package/src/index.d.ts +8 -1
  30. package/src/index.mjs +5 -1
  31. package/src/intent-schema.mjs +1 -0
  32. package/src/libraries.mjs +2 -2
  33. package/src/mcp.mjs +23 -0
  34. package/src/meaning.mjs +47 -7
  35. package/src/model.d.mts +7 -3
  36. package/src/model.mjs +30 -9
  37. package/src/money.d.mts +18 -0
  38. package/src/money.mjs +124 -0
  39. package/src/plain-contract.mjs +18 -2
  40. package/src/powershell.mjs +24 -5
  41. package/src/read-repo.mjs +1 -0
  42. package/src/read.d.mts +11 -0
  43. package/src/read.mjs +121 -13
  44. package/src/review-comment.d.mts +16 -0
  45. package/src/review-comment.mjs +145 -0
  46. package/src/rlang.mjs +10 -3
  47. package/src/say-less.mjs +1432 -0
  48. package/src/shell.mjs +45 -8
  49. package/src/sql-proc.mjs +1198 -0
  50. package/src/sql.mjs +87 -119
  51. package/src/steps.mjs +188 -37
  52. package/src/system.mjs +153 -44
  53. package/src/target-cs.mjs +39 -34
  54. package/src/target-elixir.mjs +40 -30
  55. package/src/target-go.mjs +41 -36
  56. package/src/target-java.mjs +34 -27
  57. package/src/target-kotlin.mjs +43 -35
  58. package/src/target-py.mjs +57 -55
  59. package/src/target-result.d.mts +48 -0
  60. package/src/target-result.mjs +112 -0
  61. package/src/target-rust.mjs +42 -38
  62. package/src/target-scala.mjs +45 -35
  63. package/src/target-ts.mjs +37 -45
  64. package/src/target-types.mjs +41 -5
  65. package/src/target-util.mjs +55 -2
  66. package/src/trace-cli.mjs +58 -0
  67. package/src/trace-fs.mjs +76 -0
  68. package/src/trace.mjs +261 -0
  69. package/src/translate.d.mts +3 -0
  70. package/src/translate.mjs +62 -32
  71. package/src/why-cli.mjs +31 -0
  72. package/src/why.d.mts +28 -0
  73. package/src/why.mjs +532 -0
  74. package/src/write-steps.mjs +22 -5
@@ -0,0 +1,1432 @@
1
+ // Say less: a step is put into words only when Thunder positively recognizes it, and the words account for it.
2
+ //
3
+ // The readers paraphrase code by pattern. Most patterns are right; but a reading is graded by its worst line, and a
4
+ // false line ("Calls unsafe", "Gives back the items in promise that do not match", "Sets key algo to key algo") is
5
+ // worse than none. Fixing false readings one by one does not generalize to code Thunder has not seen, so this pass
6
+ // turns the reader's output into an ALLOWLIST: after a function is read, every worded step is checked, and a step
7
+ // whose words cannot be accounted for is shown as its code, marked "code, not explained" (honest, never false).
8
+ //
9
+ // A worded step is kept only when all of these hold:
10
+ // 1. Recognized form: its words start with one of Thunder's step forms ("Calls", "Sets", "Returns", "If", "For each",
11
+ // …), and the code is that kind of statement (an ending is a return/throw/raise/exit; "Calls X" is a call of X,
12
+ // and X is not a keyword such as `unsafe`, `using`, `foreach`, `type`).
13
+ // 2. Every word has a source: each word is a word of the step's own code (its names, values, and text), or one of
14
+ // the fixed words the forms are written with, or an idiom word whose trigger is in the code ("log" for a print or
15
+ // log call, "JSON" for json, "how many" for a length, …). Nothing in the words is invented.
16
+ // 3. Every value is exact: each number and quoted text in the words is in the code.
17
+ // 4. Nothing that changes the meaning is dropped: negations, and/or, ordering comparisons (more than / at least /
18
+ // less than / at most, each its own kind), arithmetic, and casts in the code's meaning tree (`step.expr`) are
19
+ // all in the words. A condition (a question, a loop's while, "whether") must name every name in it.
20
+ // 5. No ambiguous names: when two different names in the code read as the same words (`KEY_ALGO`, `__KEY_ALGO`;
21
+ // `kind`, `Kind`), words that use them cannot say which, so the step is shown as code.
22
+ // 6. A meaning tree that was not parsed (`kind: 'code'`) is worded only in a fixed safe form checked against the
23
+ // text: a plain call ("Calls X"), an assignment from a plain call ("Works out T from X"), a bare return.
24
+ // 7. Certain structure: the steps inside a question, loop, or try lie inside its lines; nothing follows an ending in
25
+ // the same list; an implicit return (Ruby, Rust, an expression body) is only the last thing the function does;
26
+ // a question with nothing inside it, and alternatives under #if/#else, are shown as code.
27
+ //
28
+ // Every step then carries `explained` (true/false) and, when false, `notExplainedWhy`; each function carries
29
+ // `explainedSteps` and `totalSteps`. Everything here is linear in the size of the function.
30
+ import { namesIn, parseExpr } from './meaning.mjs';
31
+
32
+ // Every node of a tree, depth first (as meaning.mjs nodesOf), as an array remembered per tree: the checks below ask
33
+ // for the same tree's nodes many times.
34
+ const NODES = new WeakMap();
35
+ function nodesOf(tree) {
36
+ if (!tree || typeof tree !== 'object') return [];
37
+ let out = NODES.get(tree);
38
+ if (out) return out;
39
+ out = [];
40
+ const stack = [tree];
41
+ while (stack.length) {
42
+ const n = stack.pop();
43
+ if (!n || typeof n !== 'object') continue;
44
+ if (Array.isArray(n)) { for (let i = n.length - 1; i >= 0; i--) stack.push(n[i]); continue; }
45
+ if (n.kind) out.push(n);
46
+ const keys = Object.keys(n);
47
+ for (let i = keys.length - 1; i >= 0; i--) { const v = n[keys[i]]; if (v && typeof v === 'object') stack.push(v); }
48
+ }
49
+ NODES.set(tree, out);
50
+ return out;
51
+ }
52
+ import { FORM_WORDS } from './form-words.mjs';
53
+ import { asCodeWords, isCodeWords, stripQuoted, codeCounts, wordCounts, accountsFor } from './faithful.mjs';
54
+
55
+ export const WHY = {
56
+ form: 'the reader did not recognize this form',
57
+ words: 'the words could not be checked against the code',
58
+ value: 'a value in the words is not in the code',
59
+ meaning: 'the words leave out an operator or a negation in the code',
60
+ ambiguous: 'two names in the code read the same in words',
61
+ unparsed: 'the reader could not parse this statement',
62
+ structure: 'block structure uncertain',
63
+ ending: 'not a recognized return, throw, or exit',
64
+ build: 'one of several alternatives chosen when the code is compiled',
65
+ };
66
+
67
+ // SAYLESS_DEBUG=1 writes why each step was shown as code into its words (for working on the pass only).
68
+ const DEBUG = typeof process !== 'undefined' && !!process.env?.SAYLESS_DEBUG;
69
+
70
+ // Which check said no (for measuring the pass; not part of the reading).
71
+ let lastTag = null;
72
+ const M = (tag) => { lastTag = tag; return WHY.meaning; };
73
+
74
+ // ── Words ────────────────────────────────────────────────────────────────────────────────────────────────────
75
+
76
+ const WORDS_CACHE = new Map();
77
+ function splitWordsRaw(s) { return String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean); }
78
+ /** The words of a name or text (camelCase, snake_case, and acronyms split), remembered for short texts. */
79
+ const splitWords = (s) => {
80
+ const t = String(s);
81
+ if (t.length > 64) return splitWordsRaw(t);
82
+ let w = WORDS_CACHE.get(t);
83
+ if (!w) { if (WORDS_CACHE.size > 20000) WORDS_CACHE.clear(); w = splitWordsRaw(t); WORDS_CACHE.set(t, w); }
84
+ return w;
85
+ };
86
+ /** The parts of Thunder's words that are claims in words (quoted text, code in backticks, and placeholders removed). */
87
+ const claimTextRaw = (says) => String(says).replace(/\((?:the loop )?only in builds where[^()]*(?:\([^()]*\)[^()]*)*\)/g, ' ').replace(/`[^`]*`/g, ' ').replace(/"(?:\\.|[^"\\])*"/g, ' ').replace(/«[^»]*»/g, ' ').replace(/(?<=\w)'s\b/g, '');
88
+ const CLAIM_CACHE = new Map();
89
+ const CLAIM_WORDS = new Map();
90
+ /** The words of the claims (remembered). */
91
+ const claimWords = (says) => {
92
+ const k = String(says);
93
+ let v = CLAIM_WORDS.get(k);
94
+ if (v === undefined) { if (CLAIM_WORDS.size > 20000) CLAIM_WORDS.clear(); v = splitWordsRaw(claimText(k)); CLAIM_WORDS.set(k, v); }
95
+ return v;
96
+ };
97
+ /** The parts of Thunder's words that are claims (remembered: every check asks for them). */
98
+ const claimText = (says) => {
99
+ const k = String(says);
100
+ let v = CLAIM_CACHE.get(k);
101
+ if (v === undefined) { if (CLAIM_CACHE.size > 20000) CLAIM_CACHE.clear(); v = claimTextRaw(k); CLAIM_CACHE.set(k, v); }
102
+ return v;
103
+ };
104
+
105
+ // The fixed words Thunder's step forms are written with. Each carries no claim of its own beyond the form; meaning
106
+ // words (negations, comparisons, and/or) are counted separately against the code.
107
+ const GLUE = new Set(`
108
+ the a an of to from is are be was it its in on at by with as and or not no if otherwise when while each for one that this these those here then into than
109
+ returns return gives giving back calls sets works out result value values stops fails steps step next whether checks check stores under adds defines how helper
110
+ declares creates new keeps given repeats leaves loop skips chooses choice case cases tries handles any error errors goes wrong after takes starts yet counts nothing
111
+ jumps part named below always end caught still caller passes again same made inside until something both all set empty more less least most true false null
112
+ yes what time computed does do does makes function which order so also only there their them they has have itself own first last other else
113
+ longest shortest instead
114
+ `.trim().split(/\s+/));
115
+
116
+ // Idiom words: words with a meaning of their own, allowed only when the code has their trigger ("log" for a print or
117
+ // log call, "matches" for a filter or a pattern, "how many" for a length). A wrong idiom is the commonest false line
118
+ // ("the items in promise that do not match" for `Promise.reject(error)`), so these are checked even though they are
119
+ // form words.
120
+ const IDIOM = [
121
+ [/^(?:log|logs|message|messages|prints|warns|warning)$/, /print|log|echo|write|puts|warn|info|debug|error|trace|fmt\.|console|cat\b|say|message|Write-|out|stdout|stderr|emit|notice|fatal|panic|<<|Host|cli_|inform|signal|message|alert/i],
122
+ [/^json$/, /json/i],
123
+ [/^(?:matches|match|matching)$/, /%%|##|\$\{[^}]*[#%/]|\)\s*$|\[\[|!=|find|filter|first|where|select|any\b|all\b|some|every|grep|match|reject|detect|includes|contains|index|search|test|=~|-like|Where-Object|keep|take|drop|skip|case|when|switch|guard|is\b|in\b|\bfor\b|Regex|regex|re\.|\?|startswith|endswith|startsWith|endsWith|glob|fnmatch|==|-eq/i],
124
+ [/^(?:entry|entries)$/, /get|\[|fetch|lookup|at\b|entry|Get|find|::|\$|\./i],
125
+ [/^(?:table|lookup)$/, /map|dict|hash|table|\{|object|Object|list|@\{/i],
126
+ [/^many$/, /\$\{#|len|length|count|size|\$#|nrow|NROW|Count|Length|Size|n\(\)|sizeof|nchar/i],
127
+ [/^(?:copy|copies)$/, /\bcp\b|copy|clone|dup|Copy|Clone|\.\.\.|strcpy|memcpy|strdup|Copy-Item/i],
128
+ [/^(?:removes|deletes|frees|unsets)$/, /\brm\b|remove|delete|del\b|unset|pop|splice|free|drop|Remove|Delete|clear|discard|erase|-=|\[\]|NULL/i],
129
+ [/^(?:empties|zeros)$/, /=\s*(?:;|$|""|''|\(\)|\[\]|0\b)|clear|truncate|memset|fill|zero|reset|bzero/i],
130
+ [/^(?:folder|folders|directory)$/, /^\s*\(\s*(?:\n|$)|cd\b|dir|folder|path|mkdir|pushd|Path|-d\b|Item|Location/i],
131
+ [/^(?:illegal|exception)$/, /require|check|Illegal|assert|Exception|throw|raise/],
132
+ [/^(?:valid)$/, /valid|check|assert|stopifnot|verify/i],
133
+ [/^(?:parent)$/, /super|base\b|parent|Parent|Base|mkdir|\.\./i],
134
+ [/^(?:pattern|patterns|regex)$/, /match|=~|-like|grep|case|regex|Regex|re\.|\*|glob|sed|awk|\/.*\/|~|\[\[|split|-split|-replace|gsub|sub\(/i],
135
+ [/^(?:plus|minus|times|divided|multiplied|remainder|shifted)$/, /[-+*/%<>^&|~]|\btimes\b|range|repeat|\.\./],
136
+ [/^(?:exists|exist)$/, /exist|Exist|-[edfLhrswx]\b|Test-Path|isfile|isdir|file\.|stat|access|has|contains|in\b|key/i],
137
+ [/^(?:setting|settings|environment)$/, /kubectl|helm|apply|env|ENV|environ|getenv|Environment|config|setting|option|\$[A-Z_]{2,}|\bget\b|\bset\s+-[a-z]*u/i],
138
+ [/^(?:second|third|fourth|fifth)$/, /\$[2-9]|\$\{[2-9]|\[[1-9]\]|second|third|nth|at\(|\.\.\.|args/i],
139
+ [/^(?:alongside|background)$/, /await|go\b|async|&\s*$|spawn|thread|Task|later|Start-Job|launch|coroutine/i],
140
+ [/^(?:passed|seconds|milliseconds|minutes|hours|timer)$/, /time\.|After|setTimeout|setInterval|sleep|delay|Timer|timeout|Duration|interval|schedule|every|after/i],
141
+ [/^(?:uploads|upload|pushes)$/, /push|upload|put|send|publish/i],
142
+ [/^(?:latest|newest|oldest)$/, /latest|tail|sort|max|last|head|newest|oldest|-1\b|describe/i],
143
+ [/^(?:redirect|redirects)$/, /redirect|Redirect|location|Location|30[1278]/],
144
+ [/^(?:database|insert|inserts)$/, /db|database|save|query|sql|select|insert|update|session|repo|commit|execute|Insert|Save|create|objects|models|prisma|knex|orm/i],
145
+ [/^(?:forbidden|unauthorized|conflict|unprocessable|unavailable|gateway|teapot)$/, /[45]\d\d|status|abort|HTTP|Http|Forbidden|Unauthorized|Conflict/],
146
+ [/^(?:sum|total|average|mean)$/, /sum|total|reduce|\+|mean|avg|average|Sum|Measure-Object|aggregate|summari/i],
147
+ [/^(?:sorted|sorts|sort|highest|lowest)$/, /sort|order|Sort|Order|arrange|desc|asc/i],
148
+ [/^(?:upper|lower|uppercase|lowercase)$/, /upper|lower|Upper|Lower|toupper|tolower|capitaliz|case/i],
149
+ [/^(?:reversed|reverse)$/, /rev|Reverse|reverse/i],
150
+ ];
151
+ // Words whose presence in the words adds a negation that is part of a form, not a claim about the code.
152
+ const FORM_NEGATIONS = /\bno [\w ]{1,40}? yet\b|\bwhen that has no value\b|\bwhen it has no value\b|\bif nothing is there yet\b|\bif it has no value yet\b|\ban error is not caught here\b|\bdid not leave\b|\bnot explained\b|\bnothing\b|\bwhen it is not set\b/g;
153
+
154
+ /** Every word of the code's names, values, and text. */
155
+ function codeWordSet(code) {
156
+ const out = new Set();
157
+ for (const id of String(code).match(/[A-Za-z0-9]+/g) || []) {
158
+ for (const w of splitWords(id)) out.add(w);
159
+ // The readers split `HTTPMediaType` as "httpmedia type": both spellings are sources.
160
+ if (/[A-Z]{2}/.test(id)) for (const w of id.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(' ')) if (w) out.add(w);
161
+ }
162
+ // Numbers written in words by the readers ("one", "zero").
163
+ if (/\b1\b/.test(code)) out.add('one');
164
+ if (/\b0\b/.test(code)) out.add('zero');
165
+ return out;
166
+ }
167
+
168
+ /** The first word that has no source: not in the code, not a fixed word, and not an idiom with its trigger. */
169
+ const IDIOM_OF = new Map();
170
+ function unsourcedWord(says, code) {
171
+ let have = null;
172
+ const inCode = (w) => {
173
+ have ??= codeWordSet(code);
174
+ // Plurals and simple forms of a code word: "orders" for `order`, "named" for `name`.
175
+ return have.has(w) || have.has(w.replace(/(?:es|s|ed|d|ing)$/, '')) || have.has(`${w}s`) || have.has(w.replace(/ies$/, 'y'));
176
+ };
177
+ for (const w of claimWords(says)) {
178
+ if (/^\d+$/.test(w)) continue;
179
+ let idiom = IDIOM_OF.get(w);
180
+ if (idiom === undefined) { idiom = IDIOM.find(([re]) => re.test(w)) ?? null; IDIOM_OF.set(w, idiom); }
181
+ if (idiom) { if (idiom[1].test(code) || inCode(w)) continue; return w; }
182
+ if (GLUE.has(w) || FORM_WORDS.has(w)) continue;
183
+ if (/ing$/.test(w)) { const st = w.slice(0, -3); if ([`${st}s`, `${st}es`, `${st}e`, `${st.slice(0, -1)}s`].some((x) => FORM_WORDS.has(x))) continue; }
184
+ if (inCode(w)) continue;
185
+ return w;
186
+ }
187
+ return null;
188
+ }
189
+
190
+ // Languages where $ / @ mark a name (PHP, shell, PowerShell, Ruby, Perl) rather than being part of it (JavaScript).
191
+ const SIGIL_LANGS = new Set(['php', 'shell', 'powershell', 'ruby', 'perl', 'r', 'sql']);
192
+ let currentLang = '';
193
+ let LIBRARY_STEP = false;
194
+ /** Two different spellings in the code that read as the same words, and appear in the words. */
195
+ function ambiguousName(says, code) {
196
+ // Cheap first look: no word said twice, nothing can read the same twice.
197
+ const sw = claimWords(says);
198
+ if (new Set(sw).size === sw.length) return null;
199
+ const byWords = new Map();
200
+ const inserted = [...String(code).matchAll(/\$\{([^}]*)\}|#\{([^}]*)\}|\$\(([^)]*)\)|\$([A-Za-z_]\w*)/g)].map((m) => m[1] ?? m[2] ?? m[3] ?? m[4]).join(' ');
201
+ for (const id of `${stripQuoted(code)} ${inserted}`.match(/[A-Za-z_$@][\w$]*/g) || []) {
202
+ const bare = SIGIL_LANGS.has(currentLang) ? id.replace(/^[$@]+/, '') : id;
203
+ const w = splitWords(bare).join(' ');
204
+ if (!w) continue;
205
+ if (!byWords.has(w)) byWords.set(w, new Set());
206
+ byWords.get(w).add(bare);
207
+ }
208
+ // A spelling written as it is (a capitalized or camelCase name such as `CodeWriter`) is told apart from the words.
209
+ const raw = String(says).replace(/`[^`]*`/g, ' ');
210
+ const said = ` ${splitWords(claimText(says.replace(/'s /g, ' possx '))).join(' ')} `;
211
+ for (const [w, spellings] of byWords) {
212
+ if (spellings.size < 2) continue;
213
+ let open = [...spellings].filter((x) => !(/[A-Z]/.test(x) && new RegExp(`(?<![\\w$])${x.replace(/[$]/g, '\\$&')}(?![\\w$])`).test(raw)));
214
+ open = [...new Set(open.map((x) => x[0].toLowerCase() + x.slice(1)))];
215
+ if (open.length < 2) continue;
216
+ // Read the same, said twice, and not told apart by an owner ("the element's value" and "value"): "Sets x to x".
217
+ const all = said.split(` ${w} `).length - 1;
218
+ const plain = all - (said.split(` possx ${w} `).length - 1);
219
+ if (plain >= 2) return w;
220
+ }
221
+ return null;
222
+ }
223
+
224
+ function bracketsClosed(text) {
225
+ let d = 0;
226
+ const t = String(text).replace(/'[^'\s]{1,4}'|`[^`]*`/g, 'Q');
227
+ for (const ch of t) { if (ch === '(' || ch === '[' || ch === '{') d++; else if (ch === ')' || ch === ']' || ch === '}') { if (--d < 0) return false; } }
228
+ return d === 0;
229
+ }
230
+
231
+ // ── Values and meaning ──────────────────────────────────────────────────────────────────────────────────────
232
+
233
+ /** Numbers and quoted text in the words that are not in the code. */
234
+ function inventedValue(says, code) {
235
+ const said = String(says).replace(/`[^`]*`/g, ' ').replace(/\(\d+ steps? inside\)/g, '').replace(/\(\d+ lines?\)/g, '').replace(/\bor \d+ other values?\b/g, '').replace(/\b(?:a list of|a table of|and) \d+ (?:items?|more|entries|values|names|keys)\b/g, ' ').replace(/\b\d+ more\b/g, ' ');
236
+ const text = String(code);
237
+ for (const num of said.replace(/"(?:\\.|[^"\\])*"/g, ' ').match(/(?<![\w.«])-?\d+(?:\.\d+)?(?![\w.»])/g) || []) {
238
+ const n = num.replace(/^-/, '');
239
+ if (!text.includes(n) && !/^[01]$/.test(n) && !statusNamed(n, text) && !text.includes(`..<${Number(n) + 1}`) && !new RegExp(`\\.\\.<\\s*${Number(n) + 1}\\b`).test(text)) return num;
240
+ }
241
+ for (const q of String(says).replace(/^(?:If (?:not: )?|Repeats: |Fails with )?`[^]*`$/, '').match(/"(?:\\.|[^"\\])*"/g) || []) {
242
+ if (!exactText(q.slice(1, -1), text)) return q;
243
+ }
244
+ return null;
245
+ }
246
+
247
+ // Text with every value inserted into it (`${x}`, `$(cmd)`, `#{x}`, `{x}`, `%s`, `\(x)`, `$x`) as \u0001 and every
248
+ // quote mark as \u0002, so a quoted text in the words can be matched against whole texts of the code.
249
+ function textSkeleton(t, words = false, open = false) {
250
+ const s = String(t);
251
+ let out = '';
252
+ for (let i = 0; i < s.length; i++) {
253
+ const c = s[i], n = s[i + 1];
254
+ if (words && c === '«') { const e = s.indexOf('»', i); if (e > i) { out += '\u0001'; i = e; continue; } }
255
+ if (open && c === '$' && n === '(') { out += '\u0001'; i++; continue; }
256
+ if ((c === '$' && (n === '{' || n === '(')) || (c === '#' && n === '{') || (c === '\\' && n === '(')) {
257
+ const open = n, close = open === '{' ? '}' : ')';
258
+ let d = 0, j = i + 1;
259
+ for (; j < s.length; j++) { if (s[j] === open) d++; else if (s[j] === close && --d === 0) break; }
260
+ out += '\u0001'; i = j; continue;
261
+ }
262
+ if (c === '{' && /[\w$.}:]/.test(n ?? '')) {
263
+ let d = 0, j = i;
264
+ for (; j < s.length && j - i < 120; j++) { if (s[j] === '{') d++; else if (s[j] === '}' && --d === 0) break; }
265
+ if (j < s.length && s[j] === '}') { out += '\u0001'; i = j; continue; }
266
+ }
267
+ if (c === '$' && /[A-Za-z_]/.test(n ?? '')) { let j = i + 1; while (j < s.length && /\w/.test(s[j])) j++; out += '\u0001'; i = j - 1; continue; }
268
+ if (c === '$' && /[0-9*@#?!$-]/.test(n ?? '')) { out += '\u0001'; i++; continue; }
269
+ if (c === '%' && /[-+ #0-9.]*[sdifgxXoucpqvT]/.test(s.slice(i + 1, i + 6))) { const m = /^[-+ #0-9.]*[a-zA-Z]/.exec(s.slice(i + 1)); out += '\u0001'; i += m[0].length; continue; }
270
+ if (c === '\\' && /["'`\\]/.test(n ?? '')) { out += n; i++; continue; }
271
+ out += c;
272
+ }
273
+ return out.replace(/\s+/g, ' ');
274
+ }
275
+ /**
276
+ * A quoted text in the words is a whole text of the code: each of its literal parts (between values the code inserts)
277
+ * stands in the code between quote marks or inserted values, not inside a longer text. "Usage" is not the pattern
278
+ * `"# Usage: "*`; a text the words cut short with "…" only has to start a text of the code.
279
+ */
280
+ const SKELETON_CACHE = new Map();
281
+ const FRAG_RE = new Map();
282
+ function exactText(inner, code) { return exactIn(inner, code, false) || exactIn(inner, code, true); }
283
+ function exactIn(inner, code, open) {
284
+ if (!/«|…/.test(inner) && inner.length && [`'${inner}'`, `"${inner}"`, `\`${inner}\``].some((q) => String(code).includes(q))) return true;
285
+ if (!/«|…/.test(inner) && inner.trim().length) {
286
+ const esc = inner.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
287
+ if (new RegExp(`(?:^|[\\s#%/:+=(\\-{"'])${esc}(?=$|[\\s}/)"';|])`).test(String(code))) return true;
288
+ }
289
+ const cut = /…$/.test(inner);
290
+ const w = textSkeleton(inner.replace(/…$/, ''), true);
291
+ const key = `${open ? 1 : 0}${code}`;
292
+ let c = SKELETON_CACHE.get(key);
293
+ if (c === undefined) { if (SKELETON_CACHE.size > 5000) SKELETON_CACHE.clear(); c = `\u0002${textSkeleton(code, false, open)}\u0002`; SKELETON_CACHE.set(key, c); }
294
+ const parts = w.split('\u0001');
295
+ const B = '[\u0001\u0002"\'`\\s=(,;:\\[|]', E = '[\u0001\u0002"\'`\\s),;:\\]|]';
296
+ for (let i = 0; i < parts.length; i++) {
297
+ const f = parts[i].trim();
298
+ if (!f) continue;
299
+ const esc = f.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
300
+ const lead = i === 0 ? B : '[\u0001"\'`\\s,|]';
301
+ const tail = i === parts.length - 1 ? (cut ? '' : E) : '[\u0001"\'`\\s,]';
302
+ const src = `${lead}${esc}${tail ? `(?=${tail})` : ''}`;
303
+ let re = FRAG_RE.get(src);
304
+ if (!re) { if (FRAG_RE.size > 5000) FRAG_RE.clear(); re = new RegExp(src); FRAG_RE.set(src, re); }
305
+ if (!re.test(c) && !(f.length > 12 && c.includes(f))) return false;
306
+ }
307
+ return true;
308
+ }
309
+
310
+ const STATUS_NAMES = { 400: 'badrequest', 401: 'unauthorized', 402: 'paymentrequired', 403: 'forbidden', 404: 'notfound', 405: 'methodnotallowed', 409: 'conflict', 410: 'gone', 413: 'payloadtoolarge', 415: 'unsupportedmediatype', 422: 'unprocessable', 429: 'toomanyrequests', 500: 'internalservererror', 501: 'notimplemented', 502: 'badgateway', 503: 'serviceunavailable' };
311
+ /** An HTTP status the code writes by name (`Abort(.notFound)`, `NotFoundException`). */
312
+ const statusNamed = (n, text) => !!STATUS_NAMES[n] && String(text).toLowerCase().replace(/[^a-z]/g, '').includes(STATUS_NAMES[n]);
313
+
314
+ const ORDER_WORDS = { '>': /\b(?:more|greater|longer|later|bigger|larger) than\b|\bafter\b/g, '>=': /\bat least\b/g, '<': /\b(?:less|fewer|shorter|earlier|smaller) than\b|\bbefore\b/g, '<=': /\bat most\b/g };
315
+ const FLIP = { '>': '<', '<': '>', '>=': '<=', '<=': '>=' };
316
+
317
+ /** Ordering comparisons in a tree, by kind (a comparison under a `not` is turned round: not (a < b) is a >= b). */
318
+ function orderCounts(tree) {
319
+ const c = { '>': 0, '>=': 0, '<': 0, '<=': 0 };
320
+ for (const n of nodesOf(tree)) {
321
+ if (n.kind === 'compare' && c[n.op] != null) c[n.op]++;
322
+ else if (n.kind === 'chain') for (const op of n.ops) if (c[op] != null) c[op]++;
323
+ }
324
+ return c;
325
+ }
326
+ function orderWords(said) {
327
+ const c = {};
328
+ for (const [op, re] of Object.entries(ORDER_WORDS)) c[op] = (said.match(re) || []).length;
329
+ return c;
330
+ }
331
+ /** True when the words name each kind of ordering comparison as often as the code has it (or its mirror). */
332
+ function orderingKept(tree, said) {
333
+ const t = orderCounts(tree), w = orderWords(claimText(said));
334
+ const total = (o) => o['>'] + o['>='] + o['<'] + o['<='];
335
+ if (total(t) !== total(w)) return false;
336
+ // `a < b` may be read "b is more than a": each kind matches itself or its mirror image.
337
+ return (t['>'] + t['<'] === w['>'] + w['<']) && (t['>='] + t['<='] === w['>='] + w['<=']);
338
+ }
339
+
340
+ /** Negations in the words, without the ones a form is written with. */
341
+ const NEG_TOKEN = /^(?:not|no|non|never|cannot|nt)$/;
342
+ const saidNegations = (said) => splitWords(claimText(said).replace(FORM_NEGATIONS, ' ').replace(/n't\b/g, ' nt')).filter((w) => NEG_TOKEN.test(w)).length;
343
+ const NULL_NAME = /^(?:NULL|nullptr|nil|None|null|undefined|Nothing)$/;
344
+ const isNullish = (x) => x && ((x.kind === 'literal' && x.type === 'null') || (x.kind === 'name' && NULL_NAME.test(x.name)));
345
+
346
+ /** Negations in a tree (as the faithfulness gate counts them). */
347
+ const isCmpCall = (x) => x?.kind === 'call' && /^(?:str|strn|mem|wcs|wcsn)(?:case)?cmp$|^_?str(?:n)?icmp$/.test(x.callee?.name ?? '');
348
+ const isZero = (x) => x?.kind === 'literal' && String(x.value) === '0';
349
+ function treeNegations(tree, skipArgs = false) {
350
+ let neg = 0;
351
+ const names = [];
352
+ const walk = (n) => {
353
+ if (!n || typeof n !== 'object') return;
354
+ if (Array.isArray(n)) { n.forEach(walk); return; }
355
+ if (n.kind === 'not' && !isCmpCall(n.value)) neg++;
356
+ else if (n.kind === 'call' && /^(?:reject|reject!|delete_if|filterNot|filterNotNull|exclude|without|dropWhile|drop_while)$/.test(n.callee?.property ?? n.callee?.name ?? '') && n.args?.some((a) => a.kind === 'lambda')) neg++;
357
+ else if (n.kind === 'compare' && /^(?:!=|!==|<>|is not|not in|!is|!in|-ne)$/.test(n.op) && !(isCmpCall(n.left) && isZero(n.right)) && !(n.op !== '!==' && [n.left, n.right].some(isNullish))) neg++;
358
+ else if (n.kind === 'if' && n.negate) neg++;
359
+ if (n.kind === 'name') names.push(n.name);
360
+ else if (n.kind === 'member') names.push(n.property);
361
+ if (n.kind === 'lambda') return;
362
+ for (const k of Object.keys(n)) {
363
+ if (skipArgs && n.kind === 'call' && k === 'args') continue;
364
+ const v = n[k];
365
+ if (v && typeof v === 'object') walk(v);
366
+ }
367
+ };
368
+ walk(tree);
369
+ // Negative words inside names ("notFound", "WSA_NOT_ENOUGH_MEMORY") are read as words on both sides.
370
+ for (const x of names) for (const w of splitWords(x)) if (/^(?:not|no|non|never|cannot)$/.test(w)) neg++;
371
+ return neg;
372
+ }
373
+
374
+ /** "a new Command": the value makes a new value of that type. */
375
+ function newThing(v, says) {
376
+ const m = / a new ([\w ]+?)(?: as [\w ]+)?(?:,|$)/.exec(says);
377
+ if (!m) return false;
378
+ let c = coreOf(v);
379
+ if (c?.kind === 'unary' && c.op === '&') c = coreOf(c.value);
380
+ const type = c?.kind === 'object' ? c.type : c?.kind === 'call' ? (c.callee.kind === 'name' ? c.callee.name : c.callee.kind === 'member' ? (/^(?:new|New)$/.test(c.callee.property) ? (c.callee.object.name ?? c.callee.object.property) : c.callee.property) : null) : null;
381
+ return !!type && sameWords(String(type).replace(/<.*$/, '').split(/::|\./).pop(), m[1]);
382
+ }
383
+
384
+ const ARITH = new Set(['+', '-', '*', '/', '%', '**', '//', '<<', '>>', '>>>', '&', '|', '^', '&^']);
385
+ const arithCount = (tree) => { let n = 0; for (const x of nodesOf(tree)) if (x.kind === 'binary' && ARITH.has(x.op)) n++; return n; };
386
+ // (A C pointer cast `(T *)p` changes how a value is read, not the value; it is not counted.)
387
+ const castCount = (tree) => { let n = 0; for (const x of nodesOf(tree)) if (x.kind === 'cast' && x.form !== 'nonnull' && !(x.form === 'c' && /\*\s*$/.test(String(x.type)))) n++; return n; };
388
+
389
+ // Names a reader says by what they stand for.
390
+ const SAID_AS = {
391
+ process: / setting /, env: / setting | environment /, environ: / setting /, os: / setting /, getenv: / setting /, ENV: / setting /,
392
+ headers: / header /, header: / header /, req: / header | request | parameter | query | body | cookie /, request: / header | request | parameter | query | body | cookie /,
393
+ params: / parameter | request /, query: / query | parameter | request /, body: / body | request /, cookies: / cookie /,
394
+ str: / text /, string: / text /, bytes: / text | bytes /, basestring: / text /, unicode: / text /, 'string type': / text /,
395
+ int: / number | whole /, float: / number /, number: / number /, numeric: / number /, integer: / number /,
396
+ list: / list /, array: / list | array /, tuple: / list | tuple /, dict: / table | lookup | dictionary /, map: / table | lookup | map /, hash: / table | lookup | hash /,
397
+ 'to s': / text /, 'to string': / text /, 'to str': / text /, 'to i': / number /, 'to f': / number /, 'to int': / number /, 'to sym': / symbol /, 'to a': / list /, 'to h': / table | lookup /,
398
+ dup: / copy /, clone: / copy /, copy: / copy /, deepcopy: / copy /,
399
+ bool: / yes | true | false /, boolean: / yes | true | false /, null: / set | nothing | null | missing /, none: / set | nothing | none | missing /,
400
+ };
401
+
402
+ /** Every name and value of a tree is in the words (as words). */
403
+ function namesKept(tree, said) {
404
+ const norm = (t) => t.replace(/ have /g, ' has ').replace(/ are /g, ' is ').replace(/ does /g, ' ');
405
+ const base = ` ${splitWords(claimText(said)).join(' ')} ${splitWords(said).join(' ')} `;
406
+ // "is not X" for `!isX()`: the name is matched with the negation words taken out (negations are counted apart).
407
+ const sw = norm(`${base} ${base.replace(/ (?:not|no|does not|doesn t) /g, ' ')} `);
408
+ const has = (x) => {
409
+ const w = splitWords(x).join(' ');
410
+ if (!w || /^(?:self|this|it|super)$/.test(w) || sw.includes(` ${w} `) || sw.includes(` ${w.replace(/s$/, '')} `) || sw.includes(` ${w}s `)) return true;
411
+ // Names a reader says by what they stand for: the request's parts, settings, and types ("is text" for `str`).
412
+ const say = SAID_AS[w];
413
+ if (say && say.test(sw)) return true;
414
+ // `is_array(x)` / `isString(x)`: "x is an array", "x is not text".
415
+ const isX = /^is (.+)$/.exec(w);
416
+ if (isX) { const t = isX[1]; const as = SAID_AS[t]; return new RegExp(` is (?:not )?(?:an? )?${t} `).test(sw) || (!!as && / is /.test(sw) && as.test(sw)); }
417
+ return false;
418
+ };
419
+ const rawSaid = String(said);
420
+ const howMany = / how many | length | size | count | number of /.test(sw);
421
+ const isA = / is | are /.test(sw);
422
+ const setWords = / set | empty | nothing | missing | null | nil | none | undefined | given | there | exists? /.test(sw);
423
+ const ok = (n) => {
424
+ if (!n || typeof n !== 'object') return true;
425
+ if (Array.isArray(n)) return n.every(ok);
426
+ switch (n.kind) {
427
+ case 'name': return n.type === true || (NULL_NAME.test(n.name) ? setWords : has(n.name));
428
+ case 'literal': if (n.type === 'text') return rawSaid.includes(String(n.value)) || String(n.value).length === 0 || rawSaid.includes(String(n.raw ?? '').slice(1, -1)) || n.interpolated || /\\\(|\$\{|#\{|\{\w/.test(String(n.raw ?? n.value)) || (SAID_AS[String(n.value).toLowerCase()]?.test(sw) ?? false);
429
+ return n.type === 'null' ? setWords : n.type === 'bool' ? true : n.type === 'number' ? sw.includes(` ${String(n.raw ?? n.value).replace(/[^\w]+/g, ' ').trim().toLowerCase()} `) || has(String(n.value)) || /^[01]$/.test(String(n.value)) : true;
430
+ case 'member': {
431
+ if (/^(?:length|size|count|len|Length|Count|Size)$/.test(n.property) && howMany) return ok(n.object);
432
+ // A constant on a type or namespace (`numeric_system::standard`, `PixelOpacity.TRANSLUCENT`): its own name is enough.
433
+ const obj = n.object;
434
+ if (n.static || (obj?.kind === 'name' && /^[A-Z]/.test(obj.name)) || (obj?.kind === 'member' && /^[A-Z]/.test(obj.property))) return has(n.property);
435
+ return has(n.property) && ok(obj);
436
+ }
437
+ case 'call': {
438
+ const c = n.callee;
439
+ const name = c?.kind === 'member' ? c.property : c?.kind === 'name' ? c.name : null;
440
+ // Calls that only walk a collection (`enumerate(xs)`, `d.items()`), or read an entry (`m.get(k)` as "the k entry in m").
441
+ const own = c?.kind === 'member' && !(c.object?.kind === 'name' && /^[A-Z]/.test(c.object.name)) ? c.object : null;
442
+ if (name && /^(?:enumerate|iter|iter_mut|into_iter|items|entries|values|stream|ToList|toList|AsEnumerable|toArray|asList|each_with_index|with_index|indices|withIndex|Values|Keys|keys)$/.test(name)) return ok(own) && ok(n.args);
443
+ // C's string compare: `!strcmp(a, "x")` is "a is "x"".
444
+ if (name && /^(?:str|strn|mem|wcs|wcsn)(?:case)?cmp$|^_?str(?:n)?icmp$/.test(name) && / is /.test(sw)) return ok(n.args);
445
+ if (name && /^(?:get|Get|fetch|at|get_or_default|getOrDefault|GetValueOrDefault|TryGetValue|getOrNull|Item)$/.test(name) && / entry | entries /.test(sw)) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
446
+ // "the result of X": the call is named, what it is given is one level down.
447
+ if (name && has(name) && sw.includes(` result of ${splitWords(name).join(' ')} `)) return true;
448
+ if (name && /^(?:new|New|create|of|from|make)$/.test(name) && / new /.test(sw) && c.kind === 'member') return ok(c.object);
449
+ // Questions about a collection said in words: "any item in xs matches", "every …", "the first … that matches".
450
+ if (name && /^(?:any|some|all|every|none|find|first|filter|where|select|detect|find_index|findIndex|includes|include\?|contains|Contains|any\?|all\?|none\?|exists|Any|All|Exists|in_array|has|hasOwnProperty|has_key|key\?|containsKey|ContainsKey|startswith|endswith|startsWith|endsWith|StartsWith|EndsWith|start_with\?|end_with\?)$/.test(name) && / (?:any|every|all|no|first|matches|match|in|has|contains|starts|ends|one of) /.test(sw)) return ok(own) && n.args.every((a) => a.kind === 'lambda' || ok(a));
451
+ if (name && /^(?:len|length|size|count|nrow|NROW|Count|sizeof|strlen|wcslen|mb_strlen|nchar|str_length|lengths|Length)$/.test(name) && howMany) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
452
+ if (name && /^(?:isinstance|is_a\??|kind_of\??|instance_of\??|inherits|is)$/.test(name) && isA) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
453
+ if (name && /^(?:is\.null|is_null|isNull|is\.na|isset|empty|is_none|isNone|isNil|is_nil|nil\?|null\?|blank\?|present\?|empty\?|isEmpty|IsNullOrEmpty|IsNullOrWhiteSpace|isBlank|isNotEmpty|isNotBlank|any\?|none\?)$/.test(name) && setWords) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
454
+ return (name == null || has(name)) && (c?.kind !== 'member' || ok(c.object) || /^[A-Z]/.test(c.object?.name ?? '')) && ok(n.args);
455
+ }
456
+ case 'cast': return ok(n.value);
457
+ case 'pattern': return (n.names || []).every(has);
458
+ case 'lambda': return true;
459
+ case 'comprehension': return n.clauses.every((c) => ok(c.iter));
460
+ case 'binary': if (/ built from its parts /.test(sw) && /^(?:\+|\.|\.\.|<>|\|\|)$/.test(n.op)) return true; return ok(n.left) && ok(n.right);
461
+ case 'template': return n.parts.every((x) => typeof x === 'string' || ok(x.expr));
462
+ default:
463
+ for (const k of Object.keys(n)) { const v = n[k]; if (v && typeof v === 'object' && !ok(v)) return false; }
464
+ return true;
465
+ }
466
+ };
467
+ return ok(tree);
468
+ }
469
+
470
+ // ── Forms ───────────────────────────────────────────────────────────────────────────────────────────────────
471
+
472
+ // Words that start a statement but are not functions: "Calls unsafe" is never true.
473
+ const KEYWORD_CALLEE = /^(?:use|unsafe|using|foreach|for|type|return|pub|public|private|protected|internal|static|final|var|let|const|val|if|while|switch|match|case|new|await|async|yield|throw|raise|def|fn|func|function|class|struct|enum|interface|impl|do|else|try|catch|lock|fixed|checked|unchecked|goto|typedef|template|typename|constexpr|sizeof|defer|go|select|when|loop|override|virtual|abstract|sealed|readonly|extern|inline|volatile|register|auto|signed|unsigned|operator|delegate|event|where|from|import|export|package|module|namespace|begin|end|unless|until|elsif|then|ensure|rescue|lambda|proc|mut|ref|out|in|is|as|not|and|or)$/;
474
+
475
+ const coreOf = (e) => {
476
+ let c = e;
477
+ while (c && ((c.kind === 'unary' && (c.op === 'await' || c.op === '?' || c.op === '!!')) || (c.kind === 'cast' && c.form === 'nonnull'))) c = c.value;
478
+ return c;
479
+ };
480
+ /** The names of the calls along a value's receiver chain: a.b().c() -> [b, c]. */
481
+ function chainCallees(e) {
482
+ const out = [];
483
+ let c = coreOf(e);
484
+ while (c) {
485
+ if (c.kind === 'call') {
486
+ const cal = c.callee;
487
+ if (cal.kind === 'member') { out.push(cal.property); c = coreOf(cal.object); continue; }
488
+ if (cal.kind === 'name') out.push(cal.name);
489
+ if (cal.kind === 'index' && cal.object?.kind === 'name') out.push(cal.object.name);
490
+ if (cal.kind === 'index' && cal.object?.kind === 'member') { out.push(cal.object.property); c = coreOf(cal.object.object); continue; }
491
+ break;
492
+ }
493
+ if ((c.kind === 'logic' && c.op === 'or') || (c.kind === 'binary' && (c.op === '??' || c.op === '?:'))) {
494
+ for (const x of c.operands ?? [c.left, c.right]) out.push(...chainCallees(x));
495
+ }
496
+ if (c.kind === 'member' || c.kind === 'index') { c = coreOf(c.object); continue; }
497
+ break;
498
+ }
499
+ return out;
500
+ }
501
+ const sameWords = (a, b) => splitWords(a).join('') === splitWords(b).join('');
502
+
503
+ /** Language keywords that begin the statement (the step's code). */
504
+ const leadingWord = (code) => (String(code).trim().match(/^[A-Za-z_]+/) || [''])[0];
505
+
506
+ const ENDING_CODE = /(?:^|[;&|]\s*)(?:exit|return|exec)\b|^\s*(?:return\b|yield\b|throw\b|raise\b|exit\b|die\b|abort\b|panic!?|halt\b|fail\b|Exit\b|exit\(|_exit\(|os\.Exit\(|sys\.exit\(|process\.exit\(|System\.exit\(|stop\(|Throw-|throw\(|break\b|Write-Error\b.*-ErrorAction\s+Stop|quit\(|q\()/i;
507
+ const IMPLICIT_RETURN_LANGS = new Set(['ruby', 'rust', 'kotlin', 'scala', 'swift', 'r', 'elixir', 'typescript', 'javascript', 'csharp', 'java', 'powershell', 'shell', 'python', 'go', 'php', 'cpp', 'c', 'sql']);
508
+
509
+ /**
510
+ * Check one worded step. Returns null when its words are accounted for, else the reason it is shown as code.
511
+ * `ctx`: { lang, last (the last thing the function does), only (the function's only step) }.
512
+ */
513
+ function checkStep(step, ctx) {
514
+ const says = String(step.says ?? '');
515
+ const code = String(step.code ?? '');
516
+ currentLang = ctx.lang;
517
+ // The words' values and names are checked against the whole statement (the display copy can be cut short).
518
+ let full = `${sourceOf(step, ctx)}${ctx.valueTarget ? `\n${ctx.valueTarget}` : ''}`;
519
+ // A shell helper that always exits (`die() { …; exit 3; }`): its exit code is written in its own body, in this file.
520
+ if (ctx.lang === 'shell' && step.kind === 'fail' && ctx.lines) {
521
+ const callee = (/^\s*([\w-]+)/.exec(code) || [])[1];
522
+ const def = callee && ctx.helperExits?.get(callee);
523
+ if (def) full += `\nexit ${def}`;
524
+ }
525
+ const e = step.expr;
526
+ const lang = ctx.lang;
527
+ const tree = e && e.kind !== 'code' ? e : null;
528
+ const hasTreeLang = !['shell', 'powershell', 'r', 'sql'].includes(lang);
529
+
530
+ // A tree the reader could not parse: only a fixed safe form, checked against the text.
531
+ if (hasTreeLang && (!e || e.kind === 'code') && step.kind !== 'try' && step.kind !== 'check' && !/^(?:Otherwise|Leaves the|Skips to the next|Stops here$|Tries |Runs the next steps|If anything goes wrong)/.test(says)) {
532
+ const why = safeForm(step, says, /…$/.test(code) ? full.replace(/\s*\n\s*/g, ' ') : code, lang);
533
+ if (why) return why;
534
+ // A safe form was matched against the text: only the checks on values and words below apply.
535
+ var safeOk = true;
536
+ }
537
+
538
+ LIBRARY_STEP = !!step.library;
539
+ // A library phrase ("Checks that x is set; otherwise stops with …") for a call of a name this file defines itself
540
+ // (`require(byteCount)` in okio is its own method) is not that library's call.
541
+ if (step.library && ctx.ownFunctions) {
542
+ const callee = (/^\s*(?:return\s+)?(?:await\s+)?(?:(?:this|self)\s*\.\s*)?([A-Za-z_]\w*)\s*\(/.exec(code) || [])[1];
543
+ if (callee && ctx.ownFunctions.has(callee)) return WHY.form;
544
+ }
545
+ // Values, sources, ambiguity: every form.
546
+ if (inventedValue(says, full)) return WHY.value;
547
+ const u = unsourcedWord(says, full);
548
+ if (u) return `${WHY.words} ("${u}" has no source in the code)`;
549
+ if (ambiguousName(says, full)) return WHY.ambiguous;
550
+ const said0 = claimText(says);
551
+ // Shell here-strings (`<<<"$x"`) feed text to a command; the readers do not tell that apart from running it.
552
+ if (lang === 'shell' && /<<</.test(`${code}\n${full}`)) return WHY.form;
553
+ // Words with a token that is only punctuation ("--", "?", "-") put a flag or a symbol where a name should be.
554
+ if (/(?:^|\s)(?:--|\?)(?:\s|$)/.test(claimText(says).replace(/\s+\?$/, ''))) return WHY.words;
555
+ if (lang === 'shell') {
556
+ // Brace expansion (`mkdir "$d/"{a,b}`) makes several words from one; `-` alone means standard input.
557
+ if (/\{[^{}\s"'$]*,[^{}\s"']*\}/.test(stripQuoted(full).replace(/\$\{[^}]*\}/g, ''))) return WHY.form;
558
+ if (/"-"/.test(says) && /(?:^|\s)-(?:\s|$)/.test(full)) return WHY.form;
559
+ }
560
+ // PowerShell `Get-ChildItem -File` / `-Directory` gets only files / only folders.
561
+ if (lang === 'powershell' && /files and folders/.test(says) && /-(?:File|Directory)\b/i.test(full)) return WHY.meaning;
562
+ // A PowerShell switch changes what a command does (`-File`, `-Recurse`, `-Raw`, `-Unique`): the words name it, or
563
+ // the switch is one that does not change the result (`-Force`, `-ErrorAction`, `-Verbose`).
564
+ if (lang === 'powershell' && step.kind !== 'branch' && step.kind !== 'loop') {
565
+ const said = ` ${splitWords(says).join(' ')} `;
566
+ // (Only a cmdlet's switches: `Get-ChildItem -File`; an outside program's flags, `git branch -r`, are its own.)
567
+ const cmdletParts = stripQuoted(code).split('|').filter((p) => /^\s*(?:\$[\w:]+\s*=\s*)?(?:&\s*)?[A-Z][a-z]+-[A-Z]\w*/.test(p)).join(' | ');
568
+ for (const m of `${cmdletParts} `.matchAll(/(?:^|\s)-([A-Za-z][A-Za-z]+)(?=\s+-|\s*$|\s*[|;)}])/g)) {
569
+ const sw = m[1];
570
+ if (/^(?:Force|ErrorAction|WarningAction|InformationAction|Verbose|Debug|Confirm|WhatIf|NoNewline|ForegroundColor|BackgroundColor|OutVariable|ErrorVariable|Scope|Global|Script|Not|Contains|NotContains|Match|NotMatch|Like|NotLike|And|Or|Eq|Ne|Gt|Lt|Ge|Le|Is|IsNot|In|NotIn|Replace|Split|Join|F|As|Band|Bor|PassThru|Mandatory|Online|NoElement|NoTypeInformation)$/i.test(sw)) continue;
571
+ const map = { recurse: / everything | all | recursive| and every /, raw: / whole | as one | raw /, unique: / unique | once | duplicate /, file: / files? /, directory: / folders? /, leaf: / last part | leaf /, parent: / parent | folder /, descending: / descending | highest | largest | last /, first: / first /, last: / last /, sum: / total | sum /, count: / how many | count /, resolve: / full /, literalpath: / path /, encoding: / encoding /, append: / adds? | append /, nonewline: / /, quiet: / quiet /, simplematch: / plain text | as text /, casesensitive: / case /, asplaintext: / plain /, aspath: / path /, include: / including /, exclude: / except | excluding | without /, skip: / skip /, wait: / wait /, nowait: / without waiting /, nologo: / /, noprofile: / without the profile /, hidden: / hidden /, wrap: / wrap /, autosize: / size /, expandproperty: / /, property: / /, typename: / type /, list: / list /, all: / all /, tail: / last /, totalcount: / first /, delimiter: / separated /, header: / header /, noclobber: / not overwrite | replace nothing /, depth: / deep | depth /, compress: / compact | compress /, asjob: / background /, isvalid: / valid /, pathtype: / folder | file /, erroraction: / / };
572
+ const key = sw.toLowerCase();
573
+ if (said.includes(` ${splitWords(sw).join(' ')} `) || (map[key] && map[key].test(said))) continue;
574
+ return WHY.meaning;
575
+ }
576
+ }
577
+ // "x, or y when that has no value" is a default; `||` gives back yes or no in PHP, Java, C#, Go, Rust, C and C++.
578
+ if (tree && /when (?:that|it) has no value/.test(says) && [...nodesOf(tree)].some((n) => n.kind === 'logic' && n.op === 'or') && !/^(?:javascript|typescript|python|ruby|r|shell|powershell|perl|lua)$/.test(lang)) return WHY.meaning;
579
+ // `this.options` read as "the options" while the function also has its own `options`.
580
+ if (tree && ctx.ownNames && /\b(?:this|self)\b/.test(code) && [...nodesOf(tree)].some((n) => n.kind === 'member' && n.object?.kind === 'name' && /^(?:this|self)$/.test(n.object.name) && ctx.ownNames.has(n.property)) && !/\b(?:this|self|its own|it is given)\b/.test(says)) return WHY.ambiguous;
581
+ // "whether …" says yes or no: the value must be a comparison, a negation, and/or, or a yes/no call (`x as T` and
582
+ // `a << 17` are not).
583
+ if (tree && /\bwhether\b/.test(says)) {
584
+ const v = coreOf(tree.kind === 'assign' ? tree.value : tree.kind === 'return' ? tree.value : tree);
585
+ const yn = (n) => n && (n.kind === 'compare' || n.kind === 'chain' || n.kind === 'not' || (n.kind === 'logic' && n.operands.every(yn)) || (n.kind === 'literal' && n.type === 'bool') || (n.kind === 'call' && /^(?:is|has|can|should|does|contains|includes|exists|matches|match|fnmatch|equals|starts|ends|any|all|every|some|isinstance|[a-z_]+\?)/i.test(String(n.callee?.property ?? n.callee?.name ?? ''))) || (n.kind === 'name' && /^(?:is|has|can|should)[A-Z_]/.test(n.name)) || (n.kind === 'member' && /^(?:is|has|can|should)[A-Z_]/.test(n.property)));
586
+ if (v && !yn(v)) return M('whether-not-yes-no');
587
+ }
588
+ // Java compares text with `==` by reference: `s == "true"` is not "s is true".
589
+ if (lang === 'java' && tree && [...nodesOf(tree)].some((n) => n.kind === 'compare' && /^[!=]=$/.test(n.op) && [n.left, n.right].some((x) => x?.kind === 'literal' && x.type === 'text'))) return WHY.meaning;
590
+ // "or y when that has no value" is a default (`??`, `?:`); `||` / `or` also skip false, 0, and "", so it is not that.
591
+ if (tree && /when (?:that|it) has no value/.test(says) && [...nodesOf(tree)].some((n) => n.kind === 'logic' && n.op === 'or') && ![...nodesOf(tree)].some((n) => n.kind === 'binary' && (n.op === '??' || n.op === '?:'))) return WHY.meaning;
592
+ // `kwargs.setdefault(k, v)` / `putIfAbsent` set only when nothing is there yet.
593
+ if (tree && [...nodesOf(tree)].some((n) => n.kind === 'call' && /^(?:setdefault|putIfAbsent|computeIfAbsent|getOrPut|get_or_insert|get_or_insert_with|or_insert|or_insert_with|TryAdd|GetOrAdd)$/.test(n.callee?.property ?? n.callee?.name ?? '')) && !/\b(?:if|unless|yet|missing|not there|nothing)\b/.test(said0)) return WHY.meaning;
594
+ // A name split into one-letter pieces (`NaN` as "na n") is not a name a reader can use.
595
+ if (claimWords(says).some((w) => w.length === 1)) for (const id of String(full).match(/\b[A-Za-z][a-z]*[A-Z][A-Za-z]*\b/g) || []) {
596
+ if (id.length > 4) continue;
597
+ const parts = splitWords(id);
598
+ if (parts.some((p) => p.length === 1) && ` ${claimWords(says).join(' ')} `.includes(` ${parts.join(' ')} `) && !String(says).includes(id)) return WHY.words;
599
+ }
600
+ // A `static` local (C, C++) is set once, not every time the function runs.
601
+ if ((lang === 'c' || lang === 'cpp') && /^\s*(?:const\s+)?static\b/.test(code) && /^Sets |^Works out /.test(says)) return WHY.form;
602
+ // "the items in x that match" is a filter: the call must be given a test (a function), not columns or names.
603
+ if (tree && /\bthe items in\b.*\b(?:that|where)\b|\bonly those where\b/.test(says)) {
604
+ const calls = [...nodesOf(tree)].filter((n) => n.kind === 'call');
605
+ if (calls.length && !calls.some((c) => (c.args || []).some((a) => a.kind === 'lambda' || a.kind === 'name' || a.kind === 'member'))) return WHY.meaning;
606
+ }
607
+ // Ruby's "hands control to the given block" is Ruby's yield; Python's and JavaScript's yield give back values.
608
+ if (lang !== 'ruby' && /given block/.test(says)) return WHY.form;
609
+ // An idiom inside code written in the words (`p[how many p-1]`) is garbled: neither words nor code.
610
+ if (/\[[^\]]*\b(?:how many|the|is|of|whether)\b[^\]]*\]/.test(claimText(says))) return WHY.words;
611
+ // Words with a bracket left open are garbled.
612
+ if (!bracketsClosed(claimText(says))) return WHY.words;
613
+ // "Sets x to x" is a real self-assignment, or it hides where the value comes from.
614
+ const self = /^Sets (.+?) to (.+?)$/.exec(says);
615
+ if (self && sameWords(self[1], self[2]) && self[1] !== self[2] && /^[a-z]/.test(self[2].replace(/^the /, '')) && !/^\s*(?:[\w.]+)\s*=\s*\1\s*;?$/.test(code)) return WHY.ambiguous;
616
+ if (self && self[1] === self[2] && !new RegExp(`^\\s*(?:\\S+\\s+)?([\\w.$]+)\\s*=\\s*\\$?\\{?\\1\\}?\\s*;?$`).test(code)) return WHY.ambiguous;
617
+
618
+
619
+ if (safeOk) return null;
620
+ const said = claimText(says);
621
+ switch (step.kind) {
622
+ case 'branch': {
623
+ if (/^(?:Chooses by|Checks these cases)/.test(says)) {
624
+ if (tree && tree.kind === 'switch' && tree.subject && !namesKept(tree.subject, says)) return M('L285');
625
+ return null;
626
+ }
627
+ if (/^(?:Waits for whichever of these is ready first|Checks which of these is ready, without waiting)/.test(says)) return /^\s*select\b/.test(code) ? null : WHY.form;
628
+ // Kotlin `x?.let { … }`: "If x is set".
629
+ const letM = /^\s*([\w.]+)\?\.(?:let|also|run|apply)\s*\{/.exec(code);
630
+ if (letM) { const w = /^If (.+?) is set(?: \(\d+ steps? inside\))?$/.exec(says); return w && sameWords(w[1].replace(/^the (?:[\w ]+'s )?/, ''), letM[1].split('.').pop()) ? null : WHY.form; }
631
+ if (!/^If\b/.test(says)) return /^(?:When|Unless)\b/.test(says) ? null : WHY.form;
632
+ return conditionKept(step, tree, says, code, lang);
633
+ }
634
+ case 'loop': ctx_full = full; return loopKept(step, tree, says, code, lang);
635
+ case 'check': {
636
+ if (/^(?:Otherwise|Default|If none)/.test(says)) return null;
637
+ if (/^\s*case\b.*<-/.test(code) && /^When /.test(says)) return null;
638
+ if (tree && tree.kind === 'case' && tree.patterns && !tree.patterns.every((p) => namesKept(p, says))) return M('L294');
639
+ if (tree && tree.kind === 'case' && /\bis (?:set|not|empty)\b|\b(?:more|less) than\b|\bat (?:least|most)\b/.test(said) && !tree.patterns?.some((p) => [...nodesOf(p)].some((n) => n.kind === 'compare' || n.kind === 'not' || isNullish(n)))) return M('case-claim');
640
+ if (tree && tree.kind === 'call' && /^Checks that /.test(says)) return conditionCore(tree.args?.[0] ?? tree, says, code, lang);
641
+ return null;
642
+ }
643
+ case 'return': {
644
+ const response = /^\s*(?:return\s+)?(?:res|reply|response|ctx|c)\s*\.\s*(?:status\([^)]*\)\s*\.\s*)?(?:json|send|end|render|redirect|sendStatus|sendFile|JSON|String|HTML)\s*\(/.test(code) || (/^\s*next\s*\(/.test(code) && ctx.last);
645
+ if (!response && !ENDING_CODE.test(code) && !implicitReturnOk(step, ctx, code)) return WHY.ending;
646
+ if (/^Stops here\b/.test(says)) return (tree && tree.kind === 'return' && tree.value) || !/^\s*(?:return|exit|exit\s+0)?\s*;?\s*$/.test(code.replace(/^\s*return\b/, '')) ? M('stops-not-bare') : null;
647
+ if (/^Returns whether |^Gives back whether /.test(says)) return conditionCore(tree?.kind === 'return' ? tree.value : tree, says.replace(/^\w+ (?:back )?whether /, ''), code, lang);
648
+ return valueKept(tree?.kind === 'return' ? tree.value : tree, says, code, lang);
649
+ }
650
+ case 'fail': {
651
+ if (!ENDING_CODE.test(code) && !/^\s*(?:Write-Error|errors\.New|Err\(|return\s+Err|abort|die|bail!|ensure!|stop\(|rlang::abort|cli::cli_abort|assert)/.test(code)) {
652
+ // A fail that is not a throw is shown as code unless its code is a recognized error return.
653
+ // (A call of a function whose name says it stops: `t.Fatal(…)`, `log.Fatalf`, `_exiterr "…"`, `abort(…)`.)
654
+ const callee = (/^\s*([A-Za-z_][\w.:-]*)/.exec(code) || [])[1] ?? '';
655
+ const response = /\b(?:res|reply|response|ctx|c|w|resp)\s*\.\s*(?:status|code|sendStatus|WriteHeader|JSON|String|AbortWithStatus\w*)\s*\(\s*(?:[45]\d\d|http\.Status\w+)|\babort\(\s*[45]\d\d|HTTPException\(|Http\w*Exception|ResponseStatusException|halt\b|error\(\s*[45]\d\d/.test(code);
656
+ if (!response)
657
+ if (!/(?:^|[._:-])(?:fail|fatal|fatalf|fatalln|panic|panicf|abort|die|exit|exiterr|error|raise|throw|bail|stop|halt|err|reject|crash|terminate|quit)\w*$/i.test(callee)) return WHY.ending;
658
+ }
659
+ if (tree && saidNegations(says) > treeNegations(tree) + 1) return M('L309');
660
+ return null;
661
+ }
662
+ case 'try': return /^\s*(?:try\b|begin\b|do\s*\{|do$|\$\{?|tryCatch|withCallingHandlers|catch\b|rescue\b)/.test(code) || /^(?:Tries|Runs the next steps)/.test(says) ? null : WHY.form;
663
+ default: break;
664
+ }
665
+
666
+ // A call's argument that the words name is named whole: `free(history[j])` is not "Frees history".
667
+ if (tree) {
668
+ const core = coreOf(tree.kind === 'return' ? tree.value : tree);
669
+ if (core?.kind === 'call') {
670
+ const w = ` ${splitWords(says).join(' ')} `;
671
+ for (const a of core.args || []) {
672
+ if (a.kind !== 'index' && !(a.kind === 'member' && a.object?.kind === 'index')) continue;
673
+ let root = a; while (root && (root.kind === 'index' || root.kind === 'member')) root = root.object;
674
+ const rn = root?.kind === 'name' ? root.name : root?.kind === 'member' ? root.property : null;
675
+ if (rn && w.includes(` ${splitWords(rn).join(' ')} `) && !namesKept(a, says)) return M('arg-part');
676
+ }
677
+ }
678
+ }
679
+ // "Adds X to Y" (a push, an append, an add): what is added is said in full (`push(items[0])` is not "Adds items").
680
+ const adds = /^Adds (.+?) to (?:the end of )?(.+?)(?: \(.*\))?$/.exec(says);
681
+ if (adds && tree) {
682
+ // (The call that adds: along a chain such as `self.add(name).expect(MSG)`, the add.)
683
+ let core = coreOf(tree.kind === 'assign' ? tree.value : tree);
684
+ for (let c = core; c && c.kind === 'call'; c = c.callee?.kind === 'member' ? coreOf(c.callee.object) : null) {
685
+ if (/^(?:add|push|append|insert|extend|concat|Add|AddRange|put|unshift|prepend|push_back|emplace_back|merge)$/.test(c.callee?.property ?? c.callee?.name ?? '')) { core = c; break; }
686
+ }
687
+ if (tree.kind === 'assign' && tree.op !== '=' && tree.op !== ':=') { if (!namesKept(tree.value, adds[1])) return M('adds-value'); }
688
+ else if (core?.kind === 'call' && core.args?.length && !core.args.some((a) => namesKept(a, adds[1]))) return M('adds-value');
689
+ else if (core?.kind === 'call' && core.args?.some((a) => a.kind === 'index') && !core.args.every((a) => namesKept(a, adds[1]) || a.kind === 'name')) return M('adds-value');
690
+ }
691
+ // Calls, settings, and everything else: the words must not drop a negation, a comparison, or and/or in the tree.
692
+ if (/^Calls /.test(says)) return callKept(step, tree, says, code, lang);
693
+ if (tree) {
694
+ const summary = /^(?:Works out|Calls|Runs|Defines|Creates|Writes|Adds to|Takes|Declares|Starts with|Makes|Stores the result of)\b| the result of /.test(says);
695
+ const neg = treeNegations(tree, summary), w = saidNegations(says);
696
+ if (w !== neg && !(w < neg && /^(?:Works out|Calls|Runs|Defines|Creates|Writes|Adds to|Takes|Declares|Starts with|Makes)\b/.test(says) && !/\b(?:whether|if|when)\b/.test(said))) return M('L320');
697
+ if (w > neg) return M('L321');
698
+ // A value stated in full ("Sets x to a plus b") must keep every operator; a summary ("Works out x from f") says
699
+ // only what it names, and the rest is one level down in Details.
700
+ if (/^Sets .+ to /.test(says)) {
701
+ const v = tree.kind === 'assign' ? tree.value : null;
702
+ if (v) {
703
+ if (!newThing(v, says) && !namesKept(v, says)) return M('L327');
704
+ if (castCount(v) && !/\bas\b|\bcopy\b|\bconverted\b|\bturned\b/.test(said)) return M('L328');
705
+ if (!orderingKept(v, says)) return M('L329');
706
+ }
707
+ }
708
+ if (/^Works out (.+?) from (.+)$/.test(says) && tree.kind === 'assign') {
709
+ const m = /^Works out (.+?) from ([\w ]+)$/.exec(says);
710
+ const callees = chainCallees(tree.value);
711
+ if (m && callees.length && !callees.some((c) => sameWords(c, m[2]))) return M('L335');
712
+ }
713
+ if (/\bif\b.*\botherwise\b/.test(said) && ![...nodesOf(tree)].some((n) => n.kind === 'conditional' || n.kind === 'if')) return WHY.form;
714
+ }
715
+ return null;
716
+ }
717
+
718
+ /** "Calls X": the code calls X (its last name), and X is not a keyword. */
719
+ function callKept(step, tree, says, code, lang) {
720
+ const m = /^Calls ([^,:(]+?)(?: with these steps| on each| for each|,|:| \(| —|$)/.exec(says);
721
+ if (!m) return WHY.form;
722
+ const named = m[1].trim();
723
+ const first = splitWords(named)[0] ?? '';
724
+ if (KEYWORD_CALLEE.test(first) && splitWords(named).length === 1 && !new RegExp(`(?:[.>:]|^)\\s*${named.replace(/\W/g, '')}\\s*\\(`).test(code.trim())) return WHY.form;
725
+ const lead = leadingWord(code);
726
+ if (KEYWORD_CALLEE.test(lead) && !/^(?:new|await|go|defer|yield|return|try|do|lock|using|fixed|checked|unchecked|if|unless|when)$/.test(lead) && sameWords(lead, named) && !new RegExp(`^\\s*${lead}\\s*\\(`).test(code)) return WHY.form;
727
+ if (tree) {
728
+ const core = coreOf(tree.kind === 'return' ? tree.value : tree);
729
+ if (!core) return WHY.form;
730
+ const callees = [];
731
+ for (const n of nodesOf(core)) if (n.kind === 'call') { const c = n.callee; if (c.kind === 'member') callees.push(c.property); else if (c.kind === 'name') callees.push(c.name); }
732
+ // Ruby and Go call without brackets: a bare name or member statement is a call of it.
733
+ if (core.kind === 'name' && (lang === 'ruby' || lang === 'go' || lang === 'perl')) callees.push(core.name);
734
+ if (core.kind === 'member' && lang === 'ruby') callees.push(core.property);
735
+ if (!callees.length) return WHY.form;
736
+ const objects = [];
737
+ for (const n of nodesOf(core)) if (n.kind === 'call' && n.callee.kind === 'member' && n.callee.object?.kind === 'name') objects.push(n.callee.object.name);
738
+ if (!callees.some((c) => sameWords(c, named) || splitWords(c).join(' ').endsWith(splitWords(named).join(' '))) && !objects.some((o) => sameWords(o, named))) return M('L360');
739
+ // The words name the statement's main call: a call written inside a negation or condition is not "Calls X".
740
+ if (core.kind === 'logic' || core.kind === 'not' || core.kind === 'compare' || core.kind === 'conditional') return WHY.form;
741
+ } else if (!['shell', 'powershell', 'r', 'sql'].includes(lang) || lang === 'r') {
742
+ const re = new RegExp(`(?:^|[^\\w$])${splitWords(named).map((w) => `${w}`).join('[_\\s-]*')}\\s*\\(`, 'i');
743
+ if (!re.test(code.replace(/::/g, '.'))) return WHY.form;
744
+ }
745
+ return null;
746
+ }
747
+
748
+ /** A condition (question, loop test, "whether"): every negation, and/or, ordering, and name is in the words. */
749
+ function conditionCore(test, says, code, lang) {
750
+ if (!test || test.kind === 'code') {
751
+ // No tree: the text gate (negations, and/or, comparisons counted on the code).
752
+ return accountsFor(code, claimText(says)) ? null : M('L374');
753
+ }
754
+ const said = claimText(says);
755
+ const tn = treeNegations(test), wn = saidNegations(says);
756
+ if (tn !== wn) return M('L378');
757
+ let logic = 0; for (const n of nodesOf(test)) if (n.kind === 'logic') logic += n.operands.length - 1;
758
+ const wl = (said.match(/\band\b|\bor\b/g) || []).length;
759
+ if (logic !== wl) return M('L381');
760
+ if (!orderingKept(test, says)) return M('L382');
761
+ if (arithCount(test) > (said.match(/\b(?:plus|minus|times|divided|multiplied|remainder|shifted|bits?|mod|modulo)\b|[-+*/%&|^~]|<<|>>/g) || []).length + (/\bhow many\b/.test(said) ? 1 : 0)) return M('L383');
762
+ // A question that is one call (`if not self.can_borrow(…)`, "If cannot borrow") names the call; what it is given is
763
+ // one level down, as for "Calls X".
764
+ const one = test.kind === 'not' ? test.value : test;
765
+ if (one?.kind === 'call') {
766
+ const name = one.callee?.kind === 'member' ? one.callee.property : one.callee?.name;
767
+ const w = ` ${splitWords(said).join(' ')} `;
768
+ if (name && w.replace(/ (?:not|cannot|can t) /g, ' ').includes(` ${splitWords(name).join(' ').replace(/^(?:is|can|has|should|does) /, '')} `)) return null;
769
+ }
770
+ if (!namesKept(test, says)) return M('L384');
771
+ return null;
772
+ }
773
+
774
+ function conditionKept(step, tree, says, code, lang) {
775
+ if (isCodeWords(says.replace(/^If (?:not: )?/, '').replace(/ \(\d+ steps? inside\)$/, ''))) return null;
776
+ const words = says.replace(/^If (?:not: )?/, '').replace(/ \(\d+ steps? inside\)$/, '');
777
+ const not = /^If not: /.test(says);
778
+ if (tree && tree.kind === 'if') {
779
+ if (tree.init) {
780
+ const fails = /^If (.+?) fails$/.exec(says);
781
+ const v = tree.init.kind === 'assign' ? coreOf(tree.init.value) : null;
782
+ const t = tree.test;
783
+ const errTest = t?.kind === 'compare' && t.op === '!=' && t.left?.kind === 'name' && /^err\w*$/i.test(t.left.name) && isNullish(t.right);
784
+ const target = tree.init.target;
785
+ const assignsErr = target && [...nodesOf(target)].some((n) => n.kind === 'name' && n.name === t?.left?.name);
786
+ if (fails && errTest && assignsErr && v?.kind === 'call' && chainCallees(v).some((c) => sameWords(c, fails[1]))) return null;
787
+ return WHY.form;
788
+ }
789
+ // An `unless` / `if not` written by the reader as "If not:" carries the negation in the form.
790
+ const test = tree.negate && not ? tree.test : tree.negate ? { kind: 'not', value: tree.test } : tree.test;
791
+ if (not && !tree.negate) return conditionCore({ kind: 'not', value: test }, `not ${words}`, code, lang);
792
+ return conditionCore(test, words, code, lang);
793
+ }
794
+ if (tree) return WHY.form;
795
+ // PowerShell and R gate their own conditions (their operators are words: -not, -eq, !is.null); shell is checked here.
796
+ if (lang === 'powershell' || lang === 'r' || lang === 'sql') return null;
797
+ if (lang === 'shell') return shellConditionKept(code, says);
798
+ const cond = String(step.cond ?? code);
799
+ if (!accountsFor(cond, `${not ? 'not ' : ''}${claimText(words)}`)) return M('L402');
800
+ return null;
801
+ }
802
+
803
+ /**
804
+ * A shell condition: every `!`, `!=`, `-ne`, and `grep -v` in the code is a "not" / "fails" in the words, and every
805
+ * `&&` / `||` an "and" / "or". (A command's failure is a negation: "If running x fails" is `! x`.)
806
+ */
807
+ function shellConditionKept(code, says) {
808
+ const keyword = /^\s*(?:if|elif|while|until)\s/.test(String(code));
809
+ let c = stripQuoted(String(code).replace(/^\s*(?:if|elif|while|until)\s+/, '').replace(/;\s*(?:then|do)\s*$/, ''));
810
+ if (/<<<|<<-?\s*['"]?\w/.test(c)) return M('shell-heredoc');
811
+ // `a || body` / `a && body`: the last `||` / `&&` joins the question to its body (`||`: the body runs when it fails).
812
+ let connectorNeg = 0;
813
+ if (!keyword) {
814
+ const br = /^\s*(\[\[?)/.exec(c);
815
+ const endBr = br ? c.indexOf(br[1] === '[[' ? ']]' : ' ]') : -1;
816
+ const after = endBr > 0 ? /^\s*(\|\||&&)/.exec(c.slice(endBr + 2)) : null;
817
+ const at = after ? endBr + 2 + after.index + after[0].indexOf(after[1]) : Math.max(c.lastIndexOf('||'), c.lastIndexOf('&&'));
818
+ if (at < 0) return M('shell-form');
819
+ connectorNeg = c.slice(at, at + 2) === '||' ? 1 : 0;
820
+ c = c.slice(0, at);
821
+ }
822
+ const neg = connectorNeg + (c.match(/(?:^|\s)!(?=\s)|!=|-ne\b/g) || []).length + (c.match(/\bgrep\b(?:\s+-\w+)*\s+-[a-zA-Z]*v/g) || []).length;
823
+ const said = claimText(says).replace(FORM_NEGATIONS, ' ');
824
+ const wneg = splitWords(said.replace(/n't\b/g, ' nt')).filter((w) => NEG_TOKEN.test(w) || w === 'fails' || w === 'failed').length;
825
+ if (/^If that failed$/.test(says)) return /\|\|/.test(c) ? null : M('shell-failed');
826
+ const logic = (c.match(/&&|\|\|/g) || []).length + (/\[\s|\btest\s/.test(c) ? (c.match(/\s-a\s|\s-o\s/g) || []).length : 0);
827
+ const wl = (said.match(/\band\b|\bor\b/g) || []).length;
828
+ // `a && b || c`: "If a fails or b fails" (the body runs when either part fails).
829
+ const terms = c.split('&&');
830
+ if (connectorNeg && !/\|\||(?:^|\s)!(?=\s)/.test(c) && terms.length > 1 && wneg === terms.length && (said.match(/\bor\b/g) || []).length >= terms.length - 1) return null;
831
+ if (neg !== wneg) return M('shell-neg');
832
+ if (wl < logic) return M('shell-logic');
833
+ if (/\bgrep\b/.test(c) && /\bcontains?\b|\bmatch/.test(said) && /\s-[a-zA-Z]*v/.test(c) && !/\bnot\b|n't/.test(said)) return M('shell-grep-v');
834
+ return null;
835
+ }
836
+
837
+ let ctx_full = '';
838
+ /** "Repeats N times": N is in the code, with a repeat construct (`range(N)`, `N.times`, `repeat(N)`, `1..N`). */
839
+ function repeatsKept(says, full) {
840
+ const n = /^Repeats (\w+) times/.exec(says)[1];
841
+ return new RegExp(`\\b${n}\\b`).test(full) && /\b(?:times|range|repeat|for|Repeat|seq|upto)\b|\.\./.test(full);
842
+ }
843
+ /** `do { … } while (cond)`: the condition is on the block's last line. */
844
+ function doWhileKept(says, full, lang) {
845
+ const w = /^Runs once, then repeats (while|until) (.+?)(?: \(\d+ steps? inside\))?$/.exec(says);
846
+ const m = /\b(while|until)\s*\((.*)\)\s*;?\s*$/.exec(String(full).split('\n').pop() ?? '') || /\b(while|until)\s+(.*?)\s*;?\s*$/.exec(String(full).split('\n').pop() ?? '');
847
+ if (!w || !m || w[1] !== m[1]) return WHY.form;
848
+ const test = parseExpr(m[2], lang);
849
+ return conditionCore(test, w[2], m[2], lang);
850
+ }
851
+
852
+ function loopKept(step, tree, says, code, lang) {
853
+ if (/^Runs once, then repeats/.test(says)) return doWhileKept(says, ctx_full, lang);
854
+ if (/^Repeats (\w+) times/.test(says)) return repeatsKept(says, ctx_full) ? null : WHY.form;
855
+ if (/^`/.test(says) || /^Repeats (?:for|while) `/.test(says)) return null;
856
+ if (tree && tree.kind === 'loop') {
857
+ if (tree.form === 'each') {
858
+ const m = /^For each (.+?) in (.+?)(?:, only those where .*)?(?: \(\d+ steps? inside\))?$/.exec(says);
859
+ if (/^(?:For each item in|Repeats once for each item in)/.test(says)) return iterableKept(tree.iterable, says.replace(/^.*? in /, '').replace(/ \(\d+ steps? inside\)$/, '')) ? null : M('L411');
860
+ if (!m) return WHY.form;
861
+ for (const t of tree.targets) if (!namesKept(t, m[1])) return M('L413');
862
+ return iterableKept(tree.iterable, m[2]) ? null : M('L416');
863
+ }
864
+ if (tree.form === 'while' || tree.form === 'until') {
865
+ if (/^Repeats until (?:something|a step) inside/.test(says)) return tree.test?.kind === 'literal' && (tree.test.value === true || tree.test.value === 1) ? null : WHY.form;
866
+ const m = /^(?:Repeats while|Runs once, then repeats while|Repeats until) (.+?)(?: \(\d+ steps? inside\))?$/.exec(says);
867
+ if (!m) return WHY.form;
868
+ const neg = /^Repeats until/.test(says) !== (tree.form === 'until');
869
+ return conditionCore(neg ? { kind: 'not', value: tree.test } : tree.test, m[1], code, lang);
870
+ }
871
+ if (tree.form === 'for') {
872
+ const m = /^Counts (\w[\w ]*?) from (.+?) while (.+?)(?:, (?:adding|in steps of|going) (.+?))?(?: \(\d+ steps? inside\))?$/.exec(says);
873
+ if (!m) return /^Repeats until (?:something|a step) inside/.test(says) && !tree.test ? null : WHY.form;
874
+ const init = tree.init, upd = tree.update;
875
+ const v = init?.kind === 'assign' ? init.target : null;
876
+ if (!v || v.kind !== 'name' || !sameWords(v.name, m[1])) return M('L429');
877
+ if (!upd || !(upd.kind === 'unary' && /^(?:\+\+|--)$/.test(upd.op) && upd.value.kind === 'name' && upd.value.name === v.name)) {
878
+ if (!m[4]) return M('L431');
879
+ } else if (upd.op === '--' && !/\bdown\b|\bsubtract/.test(says)) return M('L432');
880
+ if (!namesKept(init.value, m[2]) && !/^-?\d+$/.test(m[2].trim())) return M('L433');
881
+ return conditionCore(tree.test, m[3], code, lang);
882
+ }
883
+ if (tree.form === 'forever') return /^Repeats until/.test(says) ? null : WHY.form;
884
+ if (/^Repeats (\w+) times/.test(says)) return repeatsKept(says, ctx_full) ? null : WHY.form;
885
+ return WHY.form;
886
+ }
887
+ if (tree) return /^(?:For each|Repeats once for each) /.test(says) && tree.kind === 'call' ? callLoopKept(tree, says) : WHY.form;
888
+ // Script languages: the loop's own words against its code.
889
+ if (/^Repeats while |^Repeats until /.test(says)) return accountsFor(code.replace(/^\s*(?:while|until)\b/, ''), says.replace(/^Repeats (?:while|until) /, '').replace(/ \(\d+ steps? inside\)$/, '')) ? null : M('L441');
890
+ // `while read a b c` reads several values per pass: shown as code.
891
+ if (/\bwhile\b[^;]*\bread\b(?:\s+-\w+)*\s+\w+\s+\w+/.test(code) || /;\s*read\b/.test(code)) return WHY.form;
892
+ return null;
893
+ }
894
+
895
+ /** A loop's collection in words: every name in it, or the last name of its path (`order.items` as "items"), or its call. */
896
+ function iterableKept(it, words) {
897
+ if (!it) return false;
898
+ if (namesKept(it, words)) return true;
899
+ const w = ` ${splitWords(words).join(' ')} `;
900
+ let c = coreOf(it);
901
+ if (c?.kind === 'member' && w.includes(` ${splitWords(c.property).join(' ')} `) && splitWords(words).length <= splitWords(c.property).length + 1) return true;
902
+ return chainCallees(it).some((x) => sameWords(x, words) || w.includes(` ${splitWords(x).join(' ')} `));
903
+ }
904
+
905
+ /** `items.each do |x|`, `list.forEach(x => …)` read as a loop. */
906
+ function callLoopKept(tree, says) {
907
+ const callees = chainCallees(tree);
908
+ if (!callees.some((c) => /^(?:each|forEach|for_each|each_with_index|each_pair|each_key|each_value|times|map|ForEach|foreach|forEachIndexed|iter|for_each_entry|apply|lapply|sapply|walk|upto|downto|step|each_line|each_char|loop)$/i.test(c))) return WHY.form;
909
+ return null;
910
+ }
911
+
912
+ /** A value said in full ("Returns a plus b") keeps every name and operator; "the result of X" names X's call. */
913
+ function valueKept(v, says, code, lang) {
914
+ if (!v) return /^(?:Returns|Gives back)(?: nothing| an? (?:empty|new|computed)| this\b| itself| the same)/.test(says) || !/^(?:Returns|Gives back)/.test(says) ? null : null;
915
+ const said = claimText(says);
916
+ const tn = treeNegations(v, / the result of /.test(says)), wn = saidNegations(says);
917
+ if (wn > tn) return M('L459');
918
+ if (wn < tn && !/the result of|the items|a new|computed/.test(said)) return M('L460');
919
+ const m = /^(?:Returns|Gives back) the result of ([\w ]+?)(?:,|$| with| on| from)/.exec(says);
920
+ if (m) {
921
+ const callees = chainCallees(v);
922
+ if (!callees.some((c) => sameWords(c, m[1]))) return M('L464');
923
+ return null;
924
+ }
925
+ const cond = coreOf(v);
926
+ const iff = /^(?:Returns|Gives back) (.+) if (.+), otherwise (.+)$/.exec(says);
927
+ if (cond?.kind === 'conditional' && iff) {
928
+ const side = (node, phrase) => (/^a new /.test(phrase) ? newThing(node, ` ${phrase}`) : /^the result of /.test(phrase) ? chainCallees(node).some((c) => sameWords(c, phrase.replace(/^the result of /, ''))) : namesKept(node, phrase));
929
+ if (!side(cond.then, iff[1]) || !side(cond.else, iff[3])) return M('cond-side');
930
+ return conditionCore(cond.test, iff[2], code, lang);
931
+ }
932
+ if (/^(?:Returns|Gives back) a new /.test(says)) return newThing(v, says) || coreOf(v)?.kind === 'call' || coreOf(v)?.kind === 'object' || coreOf(v)?.kind === 'array' ? null : M('L467');
933
+ if (castCount(v) && !/\bas\b|\bconverted\b|\bturned\b/.test(said)) return M('L468');
934
+ if (!orderingKept(v, says)) return M('L469');
935
+ // A plain value (a name, a member, a literal, an operator over them): every name in it is in the words.
936
+ const core = coreOf(v);
937
+ if (core && /^(?:name|member|literal|binary|compare|logic|not|unary|index)$/.test(core.kind) && !namesKept(core, says)) return M('L472');
938
+ // A returned call (`return warning("…" + x)`) is named by the words; its arguments are not what is given back.
939
+ if (core?.kind === 'call' && !/^(?:Returns|Gives back) (?:the result of|a new|whether|one for each|the items|the first|a copy|what)\b/.test(says)) {
940
+ const name = core.callee?.kind === 'member' ? core.callee.property : core.callee?.name;
941
+ // (Responses, wrappers, and conversions name what they give back: `res.json(user)`, `Ok(n)`, `w.ToString()`.)
942
+ const wrapper = chainCallees(core).some((c) => /^(?:ConfigureAwait|unwrap|expect|await|get|Result)$/.test(c) && chainCallees(core).some((d) => ` ${splitWords(says).join(' ')} `.includes(` ${splitWords(d).join(' ')} `))) || /^(?:json|send|end|render|redirect|status|sendStatus|JSON|String|Ok|Some|Err|None|Success|Failure|Result|ToString|toString|to_s|to_str|str|repr|String|next|resolve|reject|of|from|wrap|just|pure|Task|FromResult|Promise)$/.test(String(name)) || /\bas text\b/.test(says);
943
+ if (name && !wrapper && !` ${splitWords(says).join(' ')} `.includes(` ${splitWords(name).join(' ')} `) && !LIBRARY_STEP) return M('return-call');
944
+ }
945
+ if (core && core.kind === 'binary' && ARITH.has(core.op) && arithCount(core) > (said.match(/\b(?:plus|minus|times|divided|multiplied|remainder|shifted|joined|followed|added|bits?|mod)\b|[-+*/%&|^~]|<<|>>/g) || []).length + (/\bbuilt from its parts\b|\btext\b/.test(said) ? 9 : 0)) return M('L473');
946
+ return null;
947
+ }
948
+
949
+ /**
950
+ * A statement whose tree was not parsed: only fixed safe forms, checked against its text. Returns null (keep) or why.
951
+ */
952
+ const SAFE_PATH = String.raw`[A-Za-z_][\w]*(?:\s*(?:\.|->|::)\s*[A-Za-z_][\w]*)*`;
953
+ const SAFE_CALL = new RegExp(String.raw`^\s*(?:await\s+)?(?:\(void\)\s*)?(${SAFE_PATH})\s*\(`);
954
+ const SAFE_ASSIGN = new RegExp(String.raw`^\s*(?:(?:const|static|unsigned|signed|struct|enum|volatile|register|auto|let|var|val|final|mut)\s+)*(?:[A-Za-z_][\w:<>,\s]*?[\s*&]+)?\**\s*(${SAFE_PATH})\s*=(?!=)\s*(?:\([A-Za-z_][\w\s*]*\)\s*)?(?:await\s+)?(${SAFE_PATH})\s*\(`);
955
+ function balancedTail(code, open) {
956
+ // The call's brackets close at the end of the statement (`f(a)(b)` or `f(a) + 1` are not one plain call).
957
+ let d = 0;
958
+ for (let i = open; i < code.length; i++) {
959
+ const ch = code[i];
960
+ if (ch === '"' || ch === "'") { const q = ch; for (i++; i < code.length && code[i] !== q; i++) if (code[i] === '\\') i++; continue; }
961
+ if (ch === '(') d++;
962
+ else if (ch === ')') { d--; if (d === 0) return /^\s*;?\s*(?:\/\/.*|\/\*.*\*\/\s*)?$/.test(code.slice(i + 1)); }
963
+ }
964
+ return false;
965
+ }
966
+ // Languages where `name { … }` passes a closure to a call (elsewhere `Name { … }` builds a value: a Rust struct, a Go literal).
967
+ const TRAILING_CLOSURE = new Set(['swift', 'kotlin', 'ruby', 'scala', 'groovy']);
968
+
969
+ function safeForm(step, says, code, lang = '') {
970
+ const trailing = TRAILING_CLOSURE.has(lang);
971
+ if (!trailing && /\{\s*$/.test(String(code).trim()) && /^(?:Calls|Returns the result of) /.test(says) && !/\)\s*\{\s*$/.test(String(code).trim())) return WHY.unparsed;
972
+ let c = String(code).replace(/\s*\{\s*$/, '').trim().replace(/^(?:try[?!]?\s+)?(?:await\s+)?(?=[A-Za-z_])/, '');
973
+ c = c.replace(/(?<![=!<>])=(?!=)\s*(?:try[?!]?\s+)?(?:await\s+)?/, '= ');
974
+ // An implicit return (`try await send(…)` as a one-expression body) is read like `return send(…)`.
975
+ if (step.kind === 'return' && !/^return\b/.test(c)) c = `return ${c.replace(/^(?:try[?!]?\s+)?(?:await\s+)?/, '')}`;
976
+ c = c.replace(/^return\s+(?:try[?!]?\s+)?(?:await\s+)?/, 'return ');
977
+ // A trailing closure (`write { … }`, `items.map { … }`) is a call.
978
+ if (trailing && /^(?:return\s+)?[A-Za-z_][\w.]*\s*\{/.test(c) && /^(?:Calls|Returns the result of) /.test(says)) c = c.replace(/^((?:return\s+)?[A-Za-z_][\w.]*)\s*\{.*$/, '$1()');
979
+ if (/^(?:return\s+)?[A-Za-z_][\w.]*\s*\(.*\)\s*\{.*$/.test(c) && /^(?:Calls|Returns the result of) /.test(says) && step.children?.length) c = c.replace(/\)\s*\{.*$/, ')');
980
+ const lastName = (p) => p.split(/\s*(?:\.|->|::|\?\.)\s*/).pop();
981
+ let m;
982
+ if (/^defer\b/.test(c) && /^At the end/.test(says)) return null;
983
+ // `return Type(…)` / `Type.init(…)` / `new Type(…)`: "Returns a new Type".
984
+ if (step.kind === 'return' && (m = /^return\s+(?:new\s+)?([A-Z][\w]*)(?:\.init)?\s*[({]/.exec(c))) return new RegExp(`^Returns a new ${m[1]}$`, 'i').test(says) || sameWords(says.replace(/^Returns a new /, ''), m[1]) ? null : WHY.unparsed;
985
+ // A call whose steps are inside it (a trailing closure): its last call is named.
986
+ if (trailing && step.children?.length && /^(?:Calls (.+) with these steps|Returns the result of (.+))$/.test(says)) {
987
+ const header = String(code).replace(/\{\s*(?:\[[^\]]*\]\s*)?(?:\(?[\w\s,$]*\)?\s+in)?\s*$/, '').trim();
988
+ const last = /([A-Za-z_]\w*)\s*(?:\((?:[^()]|\([^()]*\))*\))?\s*$/.exec(header)?.[1];
989
+ const named = says.replace(/^Calls (.+) with these steps$/, '$1').replace(/^Returns the result of /, '');
990
+ if (last && !KEYWORD_CALLEE.test(last) && sameWords(last, named)) return null;
991
+ }
992
+ // `static MSG: &str = "never fail"` / `let x = 5`: "Sets msg to "never fail"".
993
+ if ((m = /^(?:(?:let|const|static|var|val|final|readonly)\s+)?(?:mut\s+)?([A-Za-z_]\w*)\s*(?::[^=]+)?=\s*("(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?|true|false)\s*;?$/.exec(c)) && says === `Sets ${splitWords(m[1]).join(' ')} to ${m[2]}`) return null;
994
+ if ((m = /^(?:(?:let|const|static|var|val)\s+)?(?:mut\s+)?([A-Za-z_]\w*)\s*(?::[^=]+)?=\s*(?:r#*)?"(?:\\.|[^"\\])*\\?$/.exec(c)) && says === `Sets ${splitWords(m[1]).join(' ')} to a text written over several lines`) return null;
995
+ // `const { a, b } = await import('./x')`: "Loads a, b from ./x".
996
+ if ((m = /^(?:const|let|var)\s*\{([^}]*)\}\s*=\s*(?:await\s+)?(?:import|require)\(\s*['"`]([^'"`]+)['"`]\s*\)/.exec(c))) {
997
+ const w = /^Loads (.+) from (\S+)$/.exec(says);
998
+ return w && w[2] === m[2] && m[1].split(',').every((x) => x.trim() && ` ${splitWords(w[1]).join(' ')} `.includes(` ${splitWords(x.split(':').pop()).join(' ')} `)) ? null : WHY.unparsed;
999
+ }
1000
+ if (step.kind === 'loop' && (m = /^for\s+_\s+in\s+([\w.]+)$/.exec(c))) return new RegExp(`^Repeats once for each item in (?:the [\\w ]+'s )?${splitWords(m[1].split('.').pop()).join(' ')}(?: \\(\\d+ steps? inside\\))?$`).test(says) ? null : WHY.unparsed;
1001
+ if ((m = /^([\w.]+)\s*=\s*\.(\w+)$/.exec(c))) { const w = /^Sets (?:the [\w ]+'s )?(.+?) to (.+)$/.exec(says); return w && sameWords(w[1], m[1].split('.').pop()) && sameWords(w[2], m[2]) ? null : WHY.unparsed; }
1002
+ if (step.kind === 'return' && /^Returns the result of /.test(says) && /^return\s+[\w.]+(?:\s*\((?:[^()]|\([^()]*\))*\)\s*\.?\s*[\w.]*)*$/.test(c)) {
1003
+ const last = /([A-Za-z_]\w*)\s*(?:\((?:[^()]|\([^()]*\))*\))?\s*$/.exec(c)?.[1];
1004
+ if (last && !KEYWORD_CALLEE.test(last) && sameWords(last, says.replace(/^Returns the result of /, ''))) return null;
1005
+ }
1006
+ // A label (`done:`): "The "done" part starts here".
1007
+ if ((m = /^([A-Za-z_]\w*)\s*:$/.exec(c)) && says === `The "${m[1]}" part starts here`) return null;
1008
+ // Swift `for i in 0..<3` / `0...2`: "Counts i from 0 to 2".
1009
+ if (step.kind === 'loop' && (m = /^for\s+(\w+)\s+in\s+(-?\d+)\s*(\.\.<|\.\.\.)\s*(-?\d+)$/.exec(c))) {
1010
+ const hi = m[3] === '..<' ? Number(m[4]) - 1 : Number(m[4]);
1011
+ return new RegExp(`^Counts ${splitWords(m[1]).join(' ')} from ${m[2]} to ${hi}(?: \\(\\d+ steps? inside\\))?$`).test(says) ? null : WHY.unparsed;
1012
+ }
1013
+
1014
+ if (step.kind === 'return' && /^return\s*;?$/.test(c)) return /^Stops here$/.test(says) ? null : WHY.unparsed;
1015
+ if ((m = /^Handles (GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|ALL) (\S+) with these steps$/.exec(says)) && new RegExp(`\\.(?:${m[1].toLowerCase()}|${m[1]}|route|all|use)\\s*\\(`).test(c)) {
1016
+ // Every part of the path is written in the code (`app.get("orders", ":id")` is /orders/:id).
1017
+ const parts = m[2].split('/').filter(Boolean);
1018
+ return parts.every((x) => c.includes(x)) ? null : WHY.unparsed;
1019
+ }
1020
+ // Swift `guard cond else`: "If not: cond".
1021
+ if (step.kind === 'branch' && (m = /^guard\s+(?!let\b|var\b|case\b)(.+?)\s+else(?:\s*\{.*)?$/.exec(c))) {
1022
+ const w = /^If not: (.+?)(?: \(\d+ steps? inside\))?$/.exec(says);
1023
+ const test = w && parseExpr(m[1], 'swift');
1024
+ return test ? conditionCore(test, w[1], m[1], 'swift') : WHY.unparsed;
1025
+ }
1026
+ if (/^Calls .+ with these steps$/.test(says) && step.children?.length && (m = /^\s*(?:await\s+)?([A-Za-z_][\w]*(?:\s*(?:\.|->|::|\?\.)\s*[A-Za-z_][\w]*)*)\s*[({]/.exec(c))) {
1027
+ const named = /^Calls (.+?) with these steps$/.exec(says)[1];
1028
+ if (!KEYWORD_CALLEE.test(lastName(m[1])) && sameWords(lastName(m[1].replace(/\?\./g, '.')), named)) return null;
1029
+ }
1030
+ if (/^Calls /.test(says) && (m = SAFE_CALL.exec(c)) && balancedTail(c, c.indexOf('(', m.index + m[0].length - 1))) {
1031
+ const named = /^Calls (.+?)(?: \(only in builds where.*\))?$/.exec(says)?.[1] ?? '';
1032
+ return !KEYWORD_CALLEE.test(lastName(m[1])) && sameWords(lastName(m[1]), named) ? null : WHY.unparsed;
1033
+ }
1034
+ if (/^Works out /.test(says) && (m = SAFE_ASSIGN.exec(c)) && balancedTail(c, c.indexOf('(', m.index + m[0].length - 1))) {
1035
+ const w = /^Works out (.+?)(?: from (.+?))?(?: \(only in builds where.*\))?$/.exec(says);
1036
+ const target = lastName(m[1]);
1037
+ if (!w || KEYWORD_CALLEE.test(lastName(m[2]))) return WHY.unparsed;
1038
+ const tw = w[1].replace(/^the (?:[\w ]+?'s )?/, '');
1039
+ if (!sameWords(target, tw) && !sameWords(m[1].replace(/->/g, '.'), w[1])) return WHY.unparsed;
1040
+ if (w[2] && !sameWords(lastName(m[2]), w[2])) return WHY.unparsed;
1041
+ return null;
1042
+ }
1043
+ if (step.kind === 'return' && (m = /^return\s+(?:\([A-Za-z_][\w\s*]*\)\s*)?(?:await\s+)?([A-Za-z_][\w]*(?:\s*(?:\.|->|::)\s*[A-Za-z_][\w]*)*)\s*(\()?/.exec(c))) {
1044
+ const name = lastName(m[1]);
1045
+ if (m[2] && balancedTail(c, c.indexOf('(', m.index + m[0].length - 1))) return new RegExp(`^Returns the result of ${splitWords(name).join(' ')}(?: \\(only in builds where.*\\))?$`).test(says) && !KEYWORD_CALLEE.test(name) ? null : WHY.unparsed;
1046
+ if (!m[2] && /^return\s+[A-Za-z_][\w]*\s*;?$/.test(c)) return new RegExp(`^Returns ${splitWords(name).join(' ')}(?: \\(only in builds where.*\\))?$`).test(says) ? null : WHY.unparsed;
1047
+ }
1048
+ if (step.kind === 'return' && (m = /^return\s+(-?\d+|true|false|null|NULL|nil|nullptr)\s*;?$/.exec(c))) return says === `Returns ${m[1]}` || new RegExp(`^Returns ${m[1]}\\b`).test(says) ? null : WHY.unparsed;
1049
+ if (step.kind === 'fail' && /^(?:throw|raise)\b/.test(c)) return null;
1050
+ // Swift `if let x = y` / `guard let x = y else`: "If (not:) x is set".
1051
+ if (step.kind === 'branch' && (m = /^(guard)\s+(?:let|var)\s+(\w+)(?:\s*=\s*(.+?))?\s+(else\b.*)$/.exec(c) || /^(if)\s+(?:let|var)\s+(\w+)(?:\s*=\s*([^,{]+?))?\s*()$/.exec(c))) {
1052
+ const w = /^If (not: )?(.+?) is set(?: \(\d+ steps? inside\))?$/.exec(says);
1053
+ if (!w || !!w[1] !== (m[1] === 'guard')) return WHY.unparsed;
1054
+ return sameWords(w[2], m[2]) || (m[3] && /^[\w.]+$/.test(m[3]) && sameWords(w[2], m[3].split('.').pop())) ? null : WHY.unparsed;
1055
+ }
1056
+ if (/^(?:goto)\s+\w+\s*;?$/.test(c) && /^Jumps to the "\w+" part$/.test(says)) return null;
1057
+ if (/^(?:break|continue)\s*;?$/.test(c)) return null;
1058
+ return WHY.unparsed;
1059
+ }
1060
+
1061
+ /** An implicit return (no `return` written): only the last thing a function does, in a language where it returns. */
1062
+ function implicitReturnOk(step, ctx, code) {
1063
+ if (!IMPLICIT_RETURN_LANGS.has(ctx.lang)) return false;
1064
+ // Expression bodies (`=> x`, `fun f() = x`, Swift single expression): the function's only step.
1065
+ if (ctx.only) return !/\b(?:unless|if|while|until)\b/.test(code) || ctx.lang === 'kotlin' || ctx.lang === 'rust' || ctx.lang === 'scala';
1066
+ if (!ctx.last) return false;
1067
+ if (ctx.exprValue) return true;
1068
+ // Swift: an if / switch that is the whole body gives back each side's value (an if-expression); a bare value among
1069
+ // other statements is a result-builder part, not a return.
1070
+ if (ctx.lang === 'swift') return !!ctx.singleTop;
1071
+ if (!/^(?:ruby|rust|scala|r|elixir|powershell)$/.test(ctx.lang) && !(ctx.lang === 'kotlin' && ctx.inLambda)) return false;
1072
+ // Ruby/Rust: a modifier form (`x unless y`) or a statement ending in `;` (Rust) is not the value of the function.
1073
+ if (ctx.lang === 'ruby' && /\s(?:unless|if|while|until|rescue)\s/.test(code)) return false;
1074
+ if (ctx.lang === 'rust' && /;\s*$/.test(code)) return false;
1075
+ return true;
1076
+ }
1077
+
1078
+ // ── Structure ───────────────────────────────────────────────────────────────────────────────────────────────
1079
+
1080
+ /** A step's own code, whole: its lines in the source (a block's header only); the display copy can be cut short. */
1081
+ function sourceOf(step, ctx) {
1082
+ const short = String(step.code ?? '');
1083
+ const sp = step.span;
1084
+ if (!sp || !ctx.lines || step.kind === 'check') return short;
1085
+ if (isBlock(step) || step.nested || step.children?.length) {
1086
+ // The header (it can run over a few lines, up to the line that opens the block) and the block's last line.
1087
+ let head = short;
1088
+ if (sp.startLine >= 1 && !/[{:]\s*$|\b(?:then|do)\s*$/.test(String(ctx.lines[sp.startLine - 1] ?? ''))) {
1089
+ const hl = [];
1090
+ for (let l = sp.startLine; l <= Math.min(sp.endLine, sp.startLine + 5); l++) { const t = ctx.lines[l - 1] ?? ''; hl.push(t); if (/[{:]\s*$|\b(?:then|do)\s*$/.test(t)) break; }
1091
+ head = hl.join('\n');
1092
+ }
1093
+ const last = ctx.lines[(sp.endLine ?? 0) - 1];
1094
+ return last != null && sp.endLine > sp.startLine ? `${head}\n${last}` : head;
1095
+ }
1096
+ const a = sp.startLine, b = sp.endLine;
1097
+ if (!(a >= 1 && b >= a && b - a < 8)) return short;
1098
+ const text = ctx.lines.slice(a - 1, b).join('\n');
1099
+ const head = short.replace(/…$/, '').replace(/\s+/g, ' ').trim().slice(0, 40);
1100
+ return text.replace(/\s+/g, ' ').includes(head) ? text : short;
1101
+ }
1102
+
1103
+ const lineOf = (s) => s?.line ?? s?.span?.startLine ?? null;
1104
+ const endOf = (s) => s?.span?.endLine ?? s?.line ?? null;
1105
+ const isEnding = (s) => s.kind === 'return' || s.kind === 'fail' || s.jump === 'break' || s.jump === 'continue';
1106
+ const isBlock = (s) => s.kind === 'branch' || s.kind === 'loop' || s.kind === 'try';
1107
+
1108
+ /** Steps (and their own steps) in reading order. */
1109
+ function* everyStep(list) {
1110
+ for (const s of list || []) {
1111
+ yield s;
1112
+ yield* everyStep(s.children); yield* everyStep(s.otherwise);
1113
+ for (const h of s.handlers || []) yield* everyStep(h.steps);
1114
+ if (s.always) yield* everyStep(s.always.steps);
1115
+ }
1116
+ }
1117
+
1118
+ /**
1119
+ * Is a block's structure certain? Its own steps lie inside its lines, in order; nothing follows an ending in the
1120
+ * same list; a question has something inside it.
1121
+ */
1122
+ function structureProblem(s, lang, srcLines) {
1123
+ const a = lineOf(s), b = endOf(s);
1124
+ const inner = [...(s.children || []), ...(s.otherwise || [])];
1125
+ if (s.kind === 'branch' && !inner.length && !s.unread && !/^(?:Chooses by|Checks these cases)/.test(String(s.says))) return true;
1126
+ // A case with nothing in it, where cases cannot fall through (Swift, Kotlin, Rust, Go, Scala): its body was lost.
1127
+ if (s.kind === 'branch' && /^(?:swift|kotlin|rust|go|scala)$/.test(lang) && s.children?.length && s.children.every((c) => c.kind === 'check' && c.caseLabel) && s.children.some((c) => !c.children?.length && !/fall/i.test(String(c.says)) && !/(?:=>|->)\s*(?:\{\s*\}|\(\s*\)|Unit)\s*,?\s*$|\bbreak\b/.test(String(c.code ?? '')))) return true;
1128
+ // A switch whose case labels were read as steps inside another case: its cases were folded together.
1129
+ if (s.kind === 'branch' && s.children?.length && s.children.every((c) => c.kind === 'check' && c.caseLabel)) {
1130
+ for (const arm of s.children) for (const k of everyStep(arm.children)) if (!k.nested && /^\s*(?:case\b|default\s*:|when\b)/.test(String(k.code ?? ''))) return true;
1131
+ }
1132
+ // (A span of the header line alone, as an else-if has, says nothing about where its body ends.)
1133
+ if (a != null && b != null && b > a) {
1134
+ for (const k of everyStep(s.children)) { const l = lineOf(k); if (l != null && (l < a || l > b + 0)) return true; }
1135
+ }
1136
+ // Brace languages: a header that opens a block on its own line ends where its brace closes.
1137
+ if (srcLines && a != null && b != null && /\{\s*(?:\/\/.*|\/\*.*\*\/)?$/.test(String(srcLines[a - 1] ?? '')) && isBlock(s) && !['python', 'ruby', 'shell', 'powershell', 'r', 'sql'].includes(lang)) {
1138
+ const close = braceClose(srcLines, a);
1139
+ if (close != null) for (const k of everyStep(s.children)) { const l = lineOf(k); if (l != null && l > close) return true; }
1140
+ }
1141
+ return false;
1142
+ }
1143
+
1144
+ /** The line where the block opened by the last `{` on line `at` closes (quote- and comment-aware), or null. */
1145
+ function braceClose(lines, at) {
1146
+ // Depth after the header line is the block's own depth (a `{…}` closed on the header line, such as a composite
1147
+ // literal, does not count); the block closes where the depth drops below it.
1148
+ let depth = 0, base = null;
1149
+ for (let l = at - 1; l < lines.length && l < at + 2000; l++) {
1150
+ const t = lines[l] ?? '';
1151
+ for (let i = 0; i < t.length; i++) {
1152
+ const ch = t[i];
1153
+ if (ch === '/' && t[i + 1] === '/') break;
1154
+ if (ch === '"' || ch === "'" || ch === '`') { const q = ch; for (i++; i < t.length && t[i] !== q; i++) if (t[i] === '\\') i++; continue; }
1155
+ if (ch === '{') depth++;
1156
+ else if (ch === '}') { depth--; if (base != null && depth < base) return l + 1; }
1157
+ }
1158
+ if (base == null) { if (depth <= 0) return null; base = depth; }
1159
+ }
1160
+ return null;
1161
+ }
1162
+
1163
+ // ── Showing a step as code ──────────────────────────────────────────────────────────────────────────────────
1164
+
1165
+ /** Turn a step into "code, not explained", keeping its kind's place in the flow (a question stays a question). */
1166
+ const keepOriginal = (s) => { if (!('origSays' in s)) Object.defineProperty(s, 'origSays', { value: s.says, enumerable: false }); };
1167
+ const PAREN_IF = new Set(['c', 'cpp', 'java', 'csharp', 'javascript', 'typescript', 'php', 'kotlin', 'scala', 'dart', 'r', 'powershell']);
1168
+ let currentLines = null;
1169
+ const squash = (t) => String(t).replace(/\s+/g, '');
1170
+ /**
1171
+ * The code a step shows must be the code: a reader's own copy can be normalized (`set(x as S, true)` kept as `set(x)`,
1172
+ * `gsub!` as `gsub`, a here-string's `<<<` dropped). When the copy is not in the source line, the source line is shown.
1173
+ */
1174
+ function exactCode(s) {
1175
+ const sp = s.span;
1176
+ if (!currentLines || !sp?.startLine) return;
1177
+ const end = Math.min(sp.endLine ?? sp.startLine, sp.startLine + 7);
1178
+ const text = currentLines.slice(sp.startLine - 1, end).join(' ');
1179
+ const short = String(s.code ?? '').replace(/…$/, '');
1180
+ const block = isBlock(s) || s.children?.length;
1181
+ // A block's header over several lines (`if a\n && b {`): the whole header, never its first line alone.
1182
+ if (block && short.trim()) {
1183
+ let head = '';
1184
+ for (let l = sp.startLine; l <= Math.min(end, sp.startLine + 5); l++) { const t = String(currentLines[l - 1] ?? ''); head += ` ${t}`; if (/[{:]\s*$|\b(?:then|do)\s*$/.test(t)) break; }
1185
+ if (squash(head).includes(squash(short)) && squash(head).length > squash(short).length + 2 && !/[{:]\s*$|\b(?:then|do)\s*$/.test(String(currentLines[sp.startLine - 1] ?? ''))) { s.code = head.replace(/\s+/g, ' ').trim(); return; }
1186
+ }
1187
+ if (!short.trim() || squash(text).includes(squash(short))) return;
1188
+ // (A block's header: its lines up to the one that opens the block.)
1189
+ let head = '';
1190
+ if (block) for (let l = sp.startLine; l <= Math.min(end, sp.startLine + 5); l++) { const t = String(currentLines[l - 1] ?? ''); head += ` ${t}`; if (/[{:]\s*$|\b(?:then|do)\s*$/.test(t)) break; }
1191
+ s.code = (block ? head : text).replace(/\s+/g, ' ').trim();
1192
+ }
1193
+ function asCode(s, why) {
1194
+ keepOriginal(s);
1195
+ exactCode(s);
1196
+ s.explained = false;
1197
+ s.notExplainedWhy = why;
1198
+ const code = String(s.code ?? s.says ?? '').replace(/\s+/g, ' ').trim();
1199
+ if (s.kind === 'branch' && !(s.children?.length && s.children.every((c) => c.kind === 'check' && c.caseLabel))) {
1200
+ const head = code.replace(/\s*\{\s*$/, '').replace(/\s*(?:then|do|:)\s*$/, '');
1201
+ const m = /^(?:\}\s*)?(?:else\s*)?(if|elif|elsif|else if|while|unless|guard)\s*(.*)$/.exec(head);
1202
+ if (m && m[2]) {
1203
+ let cond = m[2].trim();
1204
+ // Languages whose `if` needs brackets: the condition is the bracketed group (what follows it is a one-line body).
1205
+ // Elsewhere (Swift, Go, Rust, Python, Ruby) `(a) || (b)` is all condition.
1206
+ if (PAREN_IF.has(currentLang) && /^\(/.test(cond) && closeIdx(cond, 0) > 0) cond = cond.slice(1, closeIdx(cond, 0)).trim();
1207
+ // A guard's steps (its else) run when its condition does not hold; so do an unless's.
1208
+ const neg = m[1] === 'unless' || m[1] === 'guard';
1209
+ if (m[1] === 'guard') cond = cond.replace(/\s+else\b[^]*$/, '');
1210
+ s.says = `If ${neg ? 'not: ' : ''}${asCodeWords(cond)}`;
1211
+ } else {
1212
+ // Not a plain if: the whole region is code.
1213
+ s.kind = 'other'; s.says = asCodeWords(code);
1214
+ }
1215
+ return;
1216
+ }
1217
+ if (s.kind === 'branch') { s.says = asCodeWords(code); s.codeWords = true; return; }
1218
+ if (s.kind === 'check') { s.says = asCodeWords(code.replace(/\s*\{\s*$/, '')); s.codeWords = true; return; }
1219
+ if (s.kind === 'loop') { s.says = `Repeats: ${asCodeWords(code.replace(/\s*\{\s*$/, ''))}`; s.codeWords = true; return; }
1220
+ if (s.kind === 'return' && why !== WHY.ending) { s.restates = true; s.says = asCodeWords(code); return; }
1221
+ if (s.kind === 'fail' && why !== WHY.ending) { s.says = `Fails with ${asCodeWords(code)}`; s.codeWords = true; return; }
1222
+ if (s.kind === 'try') { s.says = asCodeWords(code); s.codeWords = true; return; }
1223
+ s.kind = 'other';
1224
+ s.says = asCodeWords(code);
1225
+ }
1226
+ function closeIdx(s, open) {
1227
+ let d = 0;
1228
+ for (let i = open; i < s.length; i++) { if (s[i] === '(') d++; else if (s[i] === ')' && --d === 0) return i; }
1229
+ return -1;
1230
+ }
1231
+
1232
+ /** A whole region (a block whose structure is uncertain) shown as one piece of code. */
1233
+ function regionAsCode(s, why) {
1234
+ keepOriginal(s);
1235
+ const head = String(s.code ?? s.says ?? '').replace(/\s+/g, ' ').trim();
1236
+ for (const k of ['children', 'otherwise', 'handlers', 'always']) delete s[k];
1237
+ s.kind = 'other';
1238
+ s.says = asCodeWords(head);
1239
+ s.explained = false;
1240
+ s.notExplainedWhy = why;
1241
+ delete s.jump;
1242
+ if (DEBUG) console.error(`[say-less] ${why} | ${s.origSays} | ${String(s.code).slice(0, 120)}`);
1243
+ }
1244
+
1245
+ const alreadyCode = (s) => s.kind === 'other' || s.restates || s.codeWords || isCodeWords(String(s.says ?? '').replace(/^(?:If (?:not: )?|Repeats: |Fails with )/, '').replace(/ \(\d+ steps? inside\)$/, ''));
1246
+
1247
+ // ── The pass ────────────────────────────────────────────────────────────────────────────────────────────────
1248
+
1249
+ /**
1250
+ * A length in words, one way everywhere: "the length of password" (for `password.length`, `len(p)`, `s.size()`), never
1251
+ * "how many password" for a text in one reading and "password.length" in another. Quoted text and code are untouched.
1252
+ */
1253
+ function lengthWords(says, tree) {
1254
+ if (!/\bhow many\b|\.length\b|\.Length\b/.test(String(says))) return says;
1255
+ const lengths = new Set();
1256
+ for (const n of nodesOf(tree)) {
1257
+ if (n.kind === 'member' && /^(?:length|Length|size|Count|count)$/.test(n.property)) lengths.add(splitWords(sayFullName(n.object)).join(' '));
1258
+ if (n.kind === 'call' && /^(?:len|length|size|count|nchar|strlen|Count|Length)$/.test(n.callee?.property ?? n.callee?.name ?? '')) { const o = n.callee?.kind === 'member' ? n.callee.object : n.args?.[0]; if (o) lengths.add(splitWords(sayFullName(o)).join(' ')); }
1259
+ }
1260
+ if (!lengths.size) return says;
1261
+ return String(says).split(/("(?:\\.|[^"\\])*"|`[^`]*`|«[^»]*»)/).map((part, i) => (i % 2 ? part : part
1262
+ .replace(/\bhow many ((?:the [\w ]+?'s )?[\w ]+?)(?= is\b| are\b| has\b|,|$| and\b| or\b| plus\b| minus\b| to\b| from\b| times\b|\))/g, (m, x) => (lengths.has(splitWords(x.replace(/^the /, '').replace(/'s /g, ' ')).join(' ')) || lengths.has(splitWords(x).join(' ')) ? `the length of ${x}` : m))
1263
+ .replace(/\b([A-Za-z_][\w]*)\.(?:length|Length)\b(?!\s*\()/g, (m, x) => `the length of ${x}`))).join('');
1264
+ }
1265
+ const sayFullName = (n) => (n?.kind === 'name' ? n.name : n?.kind === 'member' ? `${sayFullName(n.object)} ${n.property}` : '');
1266
+
1267
+ /** The name a chooser's cases set (`val grade = when (…)`, `x = switch …`), as text, or null. */
1268
+ function valueTarget(s) {
1269
+ if (typeof s.valueOf === 'string') return s.valueOf;
1270
+ if (s.kind !== 'branch') return null;
1271
+ const m = /^\s*(?:(?:val|var|let|const|auto|my|local)\s+)?([A-Za-z_$][\w$.]*)\s*(?::[^=]+)?=\s*(?:when|switch|match|case|if|select)\b/.exec(String(s.code ?? ''));
1272
+ return m ? m[1] : null;
1273
+ }
1274
+
1275
+ function sayLessList(list, ctx, depth, top) {
1276
+ let ended = false, endedImplicit = false;
1277
+ for (let i = 0; i < (list?.length ?? 0); i++) {
1278
+ const s = list[i];
1279
+ // A label (`err:`) is reached by a jump: steps after it are not after the ending.
1280
+ if (ended && (/^\s*[A-Za-z_]\w*\s*:\s*$/.test(String(s.code ?? '')) || /^The "\w+" part starts here$/.test(String(s.says)))) ended = false;
1281
+ if (ended && s.kind === 'return' && /^Stops here$/.test(String(s.says)) && /^\s*return\s*;?\s*$/.test(String(s.code ?? ''))) { s.explained = true; continue; }
1282
+ if (ended && /^Defines (?:a helper|how)\b/.test(String(s.says))) ended = false;
1283
+ // A one-expression function (`const f = (x) => x * 2`) ends with its value: steps after it at the top belong to the
1284
+ // function around it (the reader took too much), so they are not this function's at all.
1285
+ if (ended && top && endedImplicit) { list.length = i; break; }
1286
+ if (ended) { regionAsCode(s, WHY.structure); continue; }
1287
+ // An `else` / `catch` / `finally` read as a step of its own: the block before it was misread.
1288
+ if (/^\s*\}?\s*(?:else|elseif|elsif|elif|catch|finally|rescue|ensure)\b(?!\s*(?:->|=>|:\s*$))/.test(String(s.code ?? '')) && s.kind !== 'branch' && s.kind !== 'check' && !s.caseLabel) {
1289
+ regionAsCode(s, WHY.structure);
1290
+ const prev = list[i - 1];
1291
+ if (prev && prev.kind === 'branch' && prev.explained !== false) regionAsCode(prev, WHY.structure);
1292
+ continue;
1293
+ }
1294
+ // Blocks first: when their structure is uncertain, the whole region is code.
1295
+ if (isBlock(s) && structureProblem(s, ctx.lang, ctx.lines)) {
1296
+ const empty = s.kind === 'branch' && !s.children?.length && !s.otherwise?.length;
1297
+ regionAsCode(s, WHY.structure);
1298
+ // A question whose body was not attached (`if constexpr (…)` then `return …;`): the next step is probably its
1299
+ // body, so it is not drawn as something that always happens.
1300
+ if (empty && list[i + 1]) { regionAsCode(list[i + 1], WHY.structure); i++; }
1301
+ continue;
1302
+ }
1303
+ const last = top && i === list.length - 1;
1304
+ if (!alreadyCode(s)) {
1305
+ lastTag = null;
1306
+ const sc = Object.create(ctx);
1307
+ sc.last = last || (ctx.lastPath && i === list.length - 1); sc.only = top && list.length === 1;
1308
+ const why = checkStep(s, sc);
1309
+ if (why) {
1310
+ asCode(s, why);
1311
+ if (lastTag) Object.defineProperty(s, 'whyTag', { value: lastTag, enumerable: false });
1312
+ if (DEBUG) console.error(`[say-less] ${why}${lastTag ? ` ${lastTag}` : ""} | ${s.origSays} | ${String(s.code).slice(0, 120)}`);
1313
+ }
1314
+ else { s.explained = true; s.says = lengthWords(s.says, s.expr); }
1315
+ } else {
1316
+ s.explained = false;
1317
+ const before = s.code;
1318
+ exactCode(s);
1319
+ if (s.code !== before && (s.kind === 'other' || s.restates)) s.says = asCodeWords(s.code);
1320
+ if (!s.notExplainedWhy) s.notExplainedWhy = s.restates && s.kind === 'return' && s.expr && s.expr.kind !== 'code' ? WHY.form : s.expr?.kind === 'code' ? WHY.unparsed : WHY.form;
1321
+ }
1322
+ // The last thing a function does: the last step, and (inside it) the last step of each of its sides and cases.
1323
+ // `return when (x) { … }` / `return x switch { … }`: each case's value is what the function gives back.
1324
+ if (!s.children && !s.otherwise && !s.handlers && !s.always) { if (isEnding(s) && s.kind !== 'other') { ended = true; endedImplicit = i === 0 && s.kind === 'return' && !/^\s*return\b/.test(String(s.code ?? '')); } continue; }
1325
+ const valueOf = /^\s*return\s+(?:when|switch|match|if|case)\b|^\s*return\s+\S.*\b(?:switch|match)\s*\{|^\s*=\s*(?:when|if)\b/.test(String(s.code ?? ''));
1326
+ const lastPath = ((ctx.lastPath || top) && i === list.length - 1) || (s.kind === 'check' && s.caseLabel && ctx.armsLast) || valueOf;
1327
+ const armsLast = s.kind === 'branch' && lastPath;
1328
+ const inner = { ...ctx, lastPath, armsLast, exprValue: ctx.exprValue || valueOf, ...(valueTarget(s) ? { valueTarget: valueTarget(s) } : {}) };
1329
+ // A "loop" that is a call with a callback (`lapply(files, function(path) …)`, `items.forEach(…)`): a return inside
1330
+ // it ends the callback, not the function, so it is not drawn as the function's ending.
1331
+ if (s.kind === 'loop' && !/^\s*(?:for|foreach|while|until|do|loop|repeat)\b/.test(String(s.code ?? '')) && s.children) {
1332
+ for (const k of everyStep(s.children)) if ((k.kind === 'return' || k.kind === 'fail') && !k.nested) regionAsCode(k, WHY.structure);
1333
+ }
1334
+ // An inner function (a callback, a lambda) is a function of its own: its last step is its own value.
1335
+ if (s.children) sayLessList(s.children, s.nested ? { ...ctx, lastPath: false, armsLast: false, exprValue: false, inLambda: true } : inner, depth + 1, !!s.nested);
1336
+ if (s.otherwise) sayLessList(s.otherwise, inner, depth + 1, false);
1337
+ for (const h of s.handlers || []) sayLessList(h.steps, inner, depth + 1, false);
1338
+ if (s.always) sayLessList(s.always.steps, { ...ctx, lastPath: false }, depth + 1, false);
1339
+ // Nothing follows an ending in the same list (a step after `return` means the structure was misread).
1340
+ if (isEnding(s) && s.kind !== 'other') ended = true;
1341
+ }
1342
+ }
1343
+
1344
+ // Infrastructure and delivery files are read by their own readers (infra-*.mjs) into fixed forms; their steps are marked.
1345
+ const INFRA = new Set(['dockerfile', 'github-actions', 'terraform', 'bicep', 'kubernetes', 'docker-compose']);
1346
+
1347
+ function markOnly(list) {
1348
+ for (const s of everyStep(list)) {
1349
+ if (alreadyCode(s)) { s.explained = false; s.notExplainedWhy ??= WHY.form; } else s.explained = true;
1350
+ }
1351
+ }
1352
+
1353
+ /**
1354
+ * True when a condition is certainly yes or no: comparisons, negations, yes/no values, calls named as questions
1355
+ * (is…, has…, can…), and and/or of those. In JavaScript, TypeScript, Python, and Ruby `a || b` gives back a or b, so
1356
+ * an and/or of plain values is not a yes/no answer there.
1357
+ */
1358
+ export function certainlyYesNo(text, lang) {
1359
+ const valueLogic = /^(?:javascript|typescript|python|ruby)$/.test(lang);
1360
+ const t = parseExpr(String(text ?? ''), lang);
1361
+ // (Where and/or always give back yes or no, a condition the tree reader cannot parse keeps the reader's call.)
1362
+ if (!t) return !valueLogic;
1363
+ const yesNo = (n) => {
1364
+ if (!n) return false;
1365
+ switch (n.kind) {
1366
+ case 'compare': case 'chain': case 'not': return true;
1367
+ case 'literal': return n.type === 'bool';
1368
+ case 'logic': return valueLogic ? n.operands.every(yesNo) : true;
1369
+ case 'call': { const name = n.callee?.kind === 'member' ? n.callee.property : n.callee?.name; return /^(?:is|has|can|should|does|did|was|are|needs?|contains|includes|exists|matches|equals|starts|ends|any|all|every|some|isinstance|is_a\?|kind_of\?|[a-z_]+\?)/i.test(String(name ?? '')) || /\?$/.test(String(name ?? '')); }
1370
+ case 'name': case 'member': { const w = n.kind === 'name' ? n.name : n.property; return !valueLogic && /^(?:is|has|can|should)[A-Z_]/.test(String(w)); }
1371
+ default: return false;
1372
+ }
1373
+ };
1374
+ return yesNo(t);
1375
+ }
1376
+
1377
+ /** Inputs: only names written as parameters in the function's own signature, never a macro, type, or lifetime. */
1378
+ function checkInputs(item, lang, srcLines) {
1379
+ if (!item.inputs?.length || ['shell', 'sql'].includes(lang)) return;
1380
+ const ids = new Set();
1381
+ const take = (a, b) => { for (const id of stripQuoted(srcLines.slice(a, b).join('\n')).match(/[A-Za-z_][\w.]*/g) || []) { ids.add(id); if (id.includes('.')) for (const part of id.split('.')) ids.add(part); } };
1382
+ const at = Math.max(0, (item.line ?? 1) - 1);
1383
+ take(at, at + 3);
1384
+ // (A signature over many lines: read further only when a name was not found in the first lines.)
1385
+ if (item.inputs.some((p) => !ids.has(String(p.name ?? '').replace(/^[$@&*]+/, '').replace(/\.\.\.$/, '')))) take(at + 3, at + 13);
1386
+ item.inputs = item.inputs.filter((p) => {
1387
+ const n = String(p.name ?? '');
1388
+ const bare = n.replace(/^[$@&*]+/, '').replace(/\.\.\.$/, '');
1389
+ // A destructured parameter (`{ userId, name }`): every name in it is in the signature.
1390
+ if (/^[{[(][^]*[}\])]$/.test(bare)) { const names = bare.match(/[A-Za-z_]\w*/g) || []; if (names.length && names.every((x) => ids.has(x))) return true; item.inputsDropped = (item.inputsDropped ?? 0) + 1; return false; }
1391
+ if (!/^[A-Za-z_][\w.]*$/.test(bare)) { item.inputsDropped = (item.inputsDropped ?? 0) + 1; return false; }
1392
+ if ((lang === 'c' || lang === 'cpp') && /^[A-Z][A-Z0-9_]{2,}$/.test(bare)) { item.inputsDropped = (item.inputsDropped ?? 0) + 1; return false; }
1393
+ if (!ids.has(bare)) { item.inputsDropped = (item.inputsDropped ?? 0) + 1; return false; }
1394
+ return true;
1395
+ });
1396
+ }
1397
+
1398
+ /**
1399
+ * Apply the allowlist to a reading (readCode's result): every step is checked and marked explained or not.
1400
+ * Returns the same reading.
1401
+ */
1402
+ export function sayLess(reading, source) {
1403
+ const lang = reading?.language;
1404
+ if (!reading?.items || !lang) return reading;
1405
+ const lines = String(source ?? '').split('\n');
1406
+ // The functions this file defines (a call of one of them is that function, not a library's of the same name).
1407
+ const ownFunctions = new Set(reading.items.filter((it) => it.kind === 'function' || it.kind === 'decision').map((it) => it.name));
1408
+ // Shell helpers that end with `exit N` (one-line definitions), by name.
1409
+ const helperExits = new Map();
1410
+ if (lang === 'shell') for (const m of String(source ?? '').matchAll(/^\s*(?:function\s+)?([\w-]+)\s*\(\)\s*\{[^}\n]*\bexit\s+(\d+)\s*;?\s*\}/gm)) helperExits.set(m[1], m[2]);
1411
+ for (const it of reading.items) {
1412
+ if (it.kind !== 'function' && it.kind !== 'decision') continue;
1413
+ if (!INFRA.has(lang)) checkInputs(it, lang, lines);
1414
+ if (!it.steps?.length) continue;
1415
+ // SQL is read by its own reader, which already shows what its gate cannot account for as code (sql-proc.mjs):
1416
+ // its steps are only marked here.
1417
+ currentLines = lines; currentLang = lang;
1418
+ if (lang === 'sql' || INFRA.has(lang)) markOnly(it.steps);
1419
+ else {
1420
+ const ownNames = new Set((it.inputs || []).map((p) => String(p.name).replace(/^[$@&*]+/, '')));
1421
+ const collect = (l) => { for (const s of l || []) { const e = s.expr; if (e?.kind === 'assign' && e.declare && e.target?.kind === 'name') ownNames.add(e.target.name); if (s.children) collect(s.children); if (s.otherwise) collect(s.otherwise); } };
1422
+ collect(it.steps);
1423
+ sayLessList(it.steps, { lang, lines, helperExits, ownNames, ownFunctions, singleTop: it.steps.length === 1 }, 0, true);
1424
+ }
1425
+ let total = 0, explained = 0;
1426
+ for (const s of everyStep(it.steps)) { total++; if (s.explained !== false) explained++; }
1427
+ it.totalSteps = total;
1428
+ it.explainedSteps = explained;
1429
+ if (it.stepsReadable != null) it.stepsReadable = Math.round((it.steps.filter((x) => x.explained !== false).length / it.steps.length) * 100) / 100;
1430
+ }
1431
+ return reading;
1432
+ }