@skillstech/thunderlang 0.5.2 → 0.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +132 -0
- package/dist/core.cjs +10204 -6621
- package/dist/index.cjs +3867 -1771
- package/package.json +1 -1
- package/src/anchor.d.mts +12 -0
- package/src/anchor.mjs +127 -0
- package/src/cli.mjs +148 -39
- package/src/codegen.mjs +27 -9
- package/src/core.d.ts +24 -0
- package/src/core.mjs +19 -1
- package/src/emit.mjs +1 -1
- package/src/index.d.ts +26 -0
- package/src/index.mjs +14 -0
- package/src/mcp.mjs +19 -32
- package/src/model.d.mts +18 -0
- package/src/model.mjs +456 -0
- package/src/obligations.d.mts +9 -0
- package/src/obligations.mjs +35 -0
- package/src/plain-contract.d.mts +30 -0
- package/src/plain-contract.mjs +339 -0
- package/src/promote.mjs +19 -5
- package/src/read.d.mts +25 -1
- package/src/read.mjs +415 -23
- package/src/review-atlas.d.mts +19 -0
- package/src/review-atlas.mjs +136 -0
- package/src/same.d.mts +10 -0
- package/src/same.mjs +160 -0
- package/src/steps.d.mts +2 -0
- package/src/steps.mjs +599 -0
- package/src/target-types.mjs +39 -4
- package/src/testing.mjs +12 -9
- package/src/thunder-repo.mjs +96 -0
- package/src/thunderize.d.mts +14 -0
- package/src/thunderize.mjs +82 -0
- package/src/visual.d.mts +40 -0
- package/src/visual.mjs +304 -0
- package/src/write.d.mts +24 -0
- package/src/write.mjs +263 -0
package/src/steps.mjs
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
// Steps: read any function as a short list of plain steps (check, branch, loop, set, call, return, fail).
|
|
2
|
+
// Decisions become rules; everything else becomes steps. Deterministic and pattern-based, like the rest of
|
|
3
|
+
// the reader: a statement it does not recognize is kept as `other` with its original text, never guessed.
|
|
4
|
+
export const STEPS_SCHEMA = 'thunder-steps-v1';
|
|
5
|
+
const MAX_STEPS = 14;
|
|
6
|
+
|
|
7
|
+
const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
|
|
8
|
+
const clip = (s, n = 70) => { const t = String(s).replace(/\s+/g, ' ').trim(); return t.length > n ? `${t.slice(0, n - 1)}…` : t; };
|
|
9
|
+
const stripTail = (s) => String(s).trim().replace(/[;{]\s*$/, '').replace(/:\s*$/, '').trim();
|
|
10
|
+
|
|
11
|
+
// Calls that mean something to a reader, recognized by name. Same spirit as the Thunder map patterns.
|
|
12
|
+
const KNOWN_CALLS = [
|
|
13
|
+
{ re: /^(?:requests\.(?:get|post|put|patch|delete)|fetch|axios(?:\.\w+)?|http\.(?:Get|Post|NewRequest)|HttpClient\.\w+|client\.(?:get|post|put|delete))$/i, say: () => 'Calls another service over HTTP' },
|
|
14
|
+
{ re: /^stripe\./i, say: () => 'Calls Stripe' },
|
|
15
|
+
{ re: /^(?:send_?email|sendMail|mailer\.\w+|smtp\.\w+)$/i, say: () => 'Sends an email' },
|
|
16
|
+
{ re: /^(?:db|database|repo|repository|session|conn|cursor)\.(?:insert|save|add|create|update|execute|exec|query|delete|remove|commit)\w*$/i, say: (m) => `Writes to the database (${m.split('.').pop()})` },
|
|
17
|
+
{ re: /^(?:events?|bus|publisher|emitter|queue)\.(?:publish|emit|send|enqueue|push)$/i, say: () => 'Announces an event' },
|
|
18
|
+
{ re: /^(?:log|logger|console|logging|fmt|Log|System\.out|println|print|puts|echo|printf)\b/i, say: () => 'Writes a log or message' },
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
/** entry['easy'] -> "the entry's easy"; $x->y -> "the x's y"; plain names as words. */
|
|
22
|
+
const possessiveWords = (path) => { const parts = String(path).replace(/^\$/, '').replace(/\[\s*['"]?([\w$]+)['"]?\s*\]/g, '.$1').split(/\.|->/).filter((x) => x && !/^(self|this)$/.test(x)); return parts.length > 1 ? `the ${words(parts[parts.length - 2])}'s ${words(parts[parts.length - 1])}` : words(parts[0] || path); };
|
|
23
|
+
|
|
24
|
+
/** Enum values read as words: Status.ON_SHELF -> "on shelf", Color.RED -> "red". */
|
|
25
|
+
export const plainEnums = (text) => String(text).replace(/\b[A-Z][A-Za-z0-9]*\.([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*)\b(?!\s*\()/g, (m, v) => (v.length > 1 && v === v.toUpperCase() ? words(v) : m));
|
|
26
|
+
|
|
27
|
+
/** A condition as words when it can't be fully translated: c.ctx == nil -> "c.ctx is empty". */
|
|
28
|
+
export function sayCodeCondition(cond) {
|
|
29
|
+
let c = plainEnums(String(cond)).trim().replace(/\s*(\{|:|then|do)\s*$/, '').trim();
|
|
30
|
+
while (c.startsWith('(') && matchingClose(c, 0) === c.length - 1) c = c.slice(1, -1).trim();
|
|
31
|
+
// A bare yes/no property reads as a sentence: `order.refunded` -> "order is refunded", `!user.isAdmin` -> "user is not admin".
|
|
32
|
+
const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
|
|
33
|
+
const plural = (w, call) => !call && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
|
|
34
|
+
if (prop && plural(words(prop[3]), !!prop[4])) return `${words(prop[2])} ${prop[1] ? 'has no' : 'has'} ${words(prop[3])}`;
|
|
35
|
+
const yesNo = (w, call) => /^(is|has|can|should|was) /.test(w) || (!call && (/ed$/.test(w) || /^(active|valid|open|empty|ready|visible|available|enabled|required|admin|public|private|paid|due|overdue|eligible|blocked)$/.test(w)));
|
|
36
|
+
if (prop && yesNo(words(prop[3]), !!prop[4])) {
|
|
37
|
+
const neg = !!prop[1];
|
|
38
|
+
const w = words(prop[3]).replace(/^(is|has|can|should|was) /, (m) => m);
|
|
39
|
+
const verb = /^(is|was) /.test(w) ? w.replace(/^(is|was) /, neg ? '$1 not ' : '$1 ') : /^(has|can|should) /.test(w) ? (neg ? `does not ${w.replace(/^has /, 'have ')}` : w).replace(/^does not can /, 'cannot ').replace(/^does not should /, 'should not ') : `is ${neg ? 'not ' : ''}${w}`;
|
|
40
|
+
return `${words(prop[2])} ${verb}`;
|
|
41
|
+
}
|
|
42
|
+
// Ruby predicates: `running?` -> "it is running", `order.paid?` -> "order is paid".
|
|
43
|
+
let pred;
|
|
44
|
+
if ((pred = c.match(/^(!|not\s+)?(?:([\w$]+)\.)?([a-z_]\w*)\?$/))) return `${pred[2] ? words(pred[2]) : 'it'} is ${pred[1] ? 'not ' : ''}${words(pred[3])}`;
|
|
45
|
+
// How many: count($a) / len(a) / a.length / a.Count / a.size() -> "how many a".
|
|
46
|
+
c = c.replace(/\\?\b(?:count|len|sizeof)\(\s*\$?([\w$.\[\]'">-]+)\s*\)/g, (m0, x) => `how many ${possessiveWords(x)}`)
|
|
47
|
+
.replace(/\b([\w$]+(?:\.[\w$]+)*)\.(?:length|Length|Count|count\(\)|size\(\)|len\(\))(?![\w(])/g, (m0, x) => `how many ${possessiveWords(x)}`);
|
|
48
|
+
// PHP built-ins and yes/no calls: !empty($x) -> "x is not empty", isset($x) -> "x is set", isValid(x) -> "is valid".
|
|
49
|
+
c = c.replace(/\\(?=[a-z_]\w*\()/g, '');
|
|
50
|
+
let call;
|
|
51
|
+
if ((call = c.match(/^(!|not\s+)?(empty|isset|is_null)\(\s*\$?([\w$.\[\]'">-]+)\s*\)$/))) {
|
|
52
|
+
const neg = !!call[1] !== (call[2] === 'isset');
|
|
53
|
+
const what = possessiveWords(call[3]);
|
|
54
|
+
return call[2] === 'isset' || call[2] === 'is_null' ? `${what} is ${(call[2] === 'isset') === !call[1] ? '' : 'not '}set` : `${what} is ${neg ? 'not ' : ''}empty`;
|
|
55
|
+
}
|
|
56
|
+
if ((call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?((?:is|has|can|should|was|are|does)[A-Z_]\w*)\s*\([^()]*\)$/))) {
|
|
57
|
+
const w = words(call[2]);
|
|
58
|
+
return call[1] ? `not: ${w}` : w;
|
|
59
|
+
}
|
|
60
|
+
// A plain name or property path used as a yes/no: `if proxy` -> "proxy is set"; `not url.host` -> "the url's host is not set".
|
|
61
|
+
const bare = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)$/);
|
|
62
|
+
if (bare && !/^(true|false|True|False|None|null|nil)$/.test(bare[2])) {
|
|
63
|
+
const parts = bare[2].split('.');
|
|
64
|
+
const what = parts.length > 1 ? `the ${words(parts[0])}'s ${words(parts[1])}` : words(parts[0]);
|
|
65
|
+
return `${what} is ${bare[1] ? 'not ' : ''}set`;
|
|
66
|
+
}
|
|
67
|
+
return clip(c
|
|
68
|
+
.replace(/\s*(===|==)\s*(nil|null|None|undefined|""|'')(?=\s|\)|$)/g, ' is empty')
|
|
69
|
+
.replace(/\s*(!==|!=)\s*(""|'')(?=\s|\)|$)/g, ' is not empty')
|
|
70
|
+
.replace(/\s*(!==|!=)\s*(nil|null|None|undefined)\b/g, ' is set')
|
|
71
|
+
.replace(/\bis not None\b/g, 'is set').replace(/\bis None\b/g, 'is empty')
|
|
72
|
+
.replace(/\s*(===|==)\s*/g, ' is ').replace(/\s*(!==|!=)\s*/g, ' is not ')
|
|
73
|
+
.replace(/\s*&&\s*/g, ' and ').replace(/\s*\|\|\s*/g, ' or ')
|
|
74
|
+
// Membership: `book not in student.books` -> "book is not in student.books".
|
|
75
|
+
.replace(/\s+not\s+in\s+/g, ' is not in ').replace(/(?<!\bis(?: not)?)\s+in\s+(?=[\w$])/g, ' is in ')
|
|
76
|
+
// Comparisons as words; `->` and `=>` are never comparisons.
|
|
77
|
+
.replace(/\s+<=\s+/g, ' is at most ').replace(/\s+>=\s+/g, ' is at least ').replace(/\s+<\s+/g, ' is less than ').replace(/(?<![-=])\s+>\s+/g, ' is more than ')
|
|
78
|
+
.replace(/(^|[\s(])!(?=[\w(])/g, '$1not ').replace(/\s+/g, ' '), 70);
|
|
79
|
+
}
|
|
80
|
+
function matchingClose(str, open) {
|
|
81
|
+
let depth = 0;
|
|
82
|
+
for (let i = open; i < str.length; i++) { if (str[i] === '(') depth++; else if (str[i] === ')' && --depth === 0) return i; }
|
|
83
|
+
return -1;
|
|
84
|
+
}
|
|
85
|
+
const lastWords = (path) => words(String(path).split('.').pop());
|
|
86
|
+
/** "cmd.commandCalledAs.called" -> "called on command called as"; "this.count" -> "count". */
|
|
87
|
+
function targetWords(path) {
|
|
88
|
+
const parts = String(path).replace(/^[@$]+/, '').replace(/#/g, '').replace(/\[.*$/, '').split('.').filter((p) => !/^(this|self)$/.test(p));
|
|
89
|
+
if (parts.length <= 1) return words(parts[0] || path);
|
|
90
|
+
return `the ${words(parts[parts.length - 2])}'s ${words(parts[parts.length - 1])}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function callee(text) {
|
|
94
|
+
const m = String(text).replace(/\[[^\]]*\]/g, '').match(/^(?:await\s+|try\s+|yield\s+|void\s+)?(?:new\s+)?([A-Za-z_$#@][\w$#]*(?:<[^()]*?>)?(?:(?:\.|::|->)[A-Za-z_$#][\w$#]*(?:<[^()]*?>)?(?:\(\))?)*)!?\s*\(/);
|
|
95
|
+
return m ? m[1].replace(/<[^()]*?>/g, '').replace(/\(\)/g, '').replace(/::|->/g, '.').replace(/#/g, '') : null;
|
|
96
|
+
}
|
|
97
|
+
function sayCall(name, args) {
|
|
98
|
+
for (const k of KNOWN_CALLS) if (k.re.test(name)) {
|
|
99
|
+
const target = (args.match(/^\s*["'`]([\w.\-/: ]{1,60})["'`]/) || [])[1];
|
|
100
|
+
const base = k.say(name);
|
|
101
|
+
return target ? `${base}: ${target}` : base;
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
function firstArgs(text) {
|
|
106
|
+
const open = text.indexOf('(');
|
|
107
|
+
return open >= 0 ? text.slice(open + 1, open + 120) : '';
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function sayValue(expr) {
|
|
111
|
+
if (/^[A-Z][A-Za-z0-9]*\.[A-Z][A-Z0-9_]+$/.test(stripTail(expr))) return plainEnums(stripTail(expr));
|
|
112
|
+
const e = stripTail(expr).replace(/\s+as\s+[\w.<>\[\]|, ]+$/, '');
|
|
113
|
+
const py = sayPython(e);
|
|
114
|
+
if (py) return py;
|
|
115
|
+
const common = sayCommon(e);
|
|
116
|
+
if (common) return common;
|
|
117
|
+
if (/^["'`].*["'`]$/.test(e)) return `"${clip(e.slice(1, -1), 40)}"`;
|
|
118
|
+
if (/^-?\d+(\.\d+)?$/.test(e) || /^(true|false|True|False|nil|null|None|undefined)$/.test(e)) return e;
|
|
119
|
+
const c = callee(e);
|
|
120
|
+
if (c) {
|
|
121
|
+
if (/^new\s/.test(e)) return `a new ${c.split('.').pop()}`;
|
|
122
|
+
return `the result of ${lastWords(c)}`;
|
|
123
|
+
}
|
|
124
|
+
if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words(e.replace(/^\$/, '').split('.').pop());
|
|
125
|
+
if (/^\$?[A-Za-z_][\w$]*(?:\[\s*['"]?\w+['"]?\s*\]|->\w+|\.\w+)+$/.test(e)) return possessiveWords(e);
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Python comprehensions and the builtins that summarize a collection, said as what they produce. */
|
|
130
|
+
const PY_SUMMARY = [
|
|
131
|
+
{ re: /^any$/, say: (src, cond) => `whether any item in ${src}${cond ? ` where ${cond}` : ''} matches` },
|
|
132
|
+
{ re: /^all$/, say: (src, cond) => `whether every item in ${src}${cond ? ` where ${cond}` : ''} matches` },
|
|
133
|
+
{ re: /^sum$/, say: (src) => `a total over ${src}` },
|
|
134
|
+
{ re: /^min$/, say: (src) => `the smallest in ${src}` },
|
|
135
|
+
{ re: /^max$/, say: (src) => `the largest in ${src}` },
|
|
136
|
+
{ re: /^(?:sorted)$/, say: (src) => `${src}, sorted` },
|
|
137
|
+
];
|
|
138
|
+
const lastSeg = (x) => words(String(x).trim().replace(/\(\)$/, '').split('.').pop());
|
|
139
|
+
/** "[r for r in rules if r.active]" -> "the items in rules where active"; "any(x.ok for x in xs)" -> "whether any item in xs matches". */
|
|
140
|
+
function sayPython(value) {
|
|
141
|
+
const e = String(value).trim();
|
|
142
|
+
let m = e.match(/^\[\s*(.+?)\s+for\s+([\w, ()]+?)\s+in\s+(.+?)(?:\s+if\s+(.+?))?\s*\]$/);
|
|
143
|
+
if (m) {
|
|
144
|
+
const [, expr, v, src, cond] = m;
|
|
145
|
+
const vars = v.replace(/[()]/g, '').split(/\s*,\s*/);
|
|
146
|
+
const bareCond = cond && cond.replace(new RegExp(`\\b(?:${vars.join('|')})\\.`, 'g'), '');
|
|
147
|
+
const condSaid = cond ? (/^\w+$/.test(bareCond) ? words(bareCond) : sayCodeCondition(bareCond)) : null;
|
|
148
|
+
if (vars.includes(expr.trim())) return condSaid ? `the items in ${lastSeg(src)} where ${condSaid}` : `the items in ${lastSeg(src)}`;
|
|
149
|
+
return `one ${lastSeg(expr.replace(/\(.*$/, ''))} for each item in ${lastSeg(src)}${condSaid ? ` where ${condSaid}` : ''}`;
|
|
150
|
+
}
|
|
151
|
+
if ((m = e.match(/^\{\s*(.+?)\s*:\s*.+?\s+for\s+[\w, ()]+?\s+in\s+(.+?)(?:\s+if\s+.+?)?\s*\}$/))) return `a lookup by ${lastSeg(m[1])} built from ${lastSeg(m[2])}`;
|
|
152
|
+
if ((m = e.match(/^len\(\s*([\w.]+)\s*\)$/))) return `how many ${lastSeg(m[1])}`;
|
|
153
|
+
if ((m = e.match(/^(\w+)\(\s*(.+?)\s+for\s+([\w, ()]+?)\s+in\s+(.+?)(?:\s+if\s+(.+?))?\s*\)$/))) {
|
|
154
|
+
const hit = PY_SUMMARY.find((k) => k.re.test(m[1]));
|
|
155
|
+
if (hit) {
|
|
156
|
+
const vars = m[3].replace(/[()]/g, '').split(/\s*,\s*/);
|
|
157
|
+
const condSaid = m[5] ? sayCodeCondition(m[5].replace(new RegExp(`\\b(?:${vars.join('|')})\\.`, 'g'), '')) : null;
|
|
158
|
+
return hit.say(lastSeg(m[4]), condSaid);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if ((m = e.match(/^(any|all|sum|min|max|sorted)\(\s*([\w.]+)\s*\)$/))) return PY_SUMMARY.find((k) => k.re.test(m[1])).say(lastSeg(m[2]));
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Everyday value shapes said as what they are, the same in every language: a new object, a value looked up by
|
|
167
|
+
* key, text built from parts, a conversion. Null when the shape is not one of these.
|
|
168
|
+
*/
|
|
169
|
+
function sayCommon(value) {
|
|
170
|
+
const e = String(value).trim().replace(/\s+as\s+[\w.<>\[\]|, ]+$/, '');
|
|
171
|
+
let m;
|
|
172
|
+
// cond ? a : b -> "a if cond, otherwise b" (not TypeScript optional types or labels).
|
|
173
|
+
const side = (x) => sayValue(x) ?? possessiveWords(x.trim());
|
|
174
|
+
if ((m = e.match(/^(.+?)\s+\?\s+([^:?]+?)\s+:\s+([^:?]+)$/)) && !/^(?:[\w$]+\??\s*:)/.test(e)) return `${side(m[2])} if ${sayCodeCondition(m[1])}, otherwise ${side(m[3])}`;
|
|
175
|
+
if ((m = e.match(/^(.+?)\s+if\s+(.+?)\s+else\s+(.+)$/))) return `${side(m[1])} if ${sayCodeCondition(m[2])}, otherwise ${side(m[3])}`;
|
|
176
|
+
if ((m = e.match(/^&?([A-Z]\w*)(?:::new\s*\(|\s*\{)/)) || (m = e.match(/^(?:[\w.]+\.)?([A-Z]\w*)\{/))) return `a new ${m[1]}`;
|
|
177
|
+
if ((m = e.match(/^new\s*\(\s*(?:[\w]+\.)?([A-Z]\w*)\s*\)$/))) return `a new ${m[1]}`;
|
|
178
|
+
if ((m = e.match(/^&([A-Z]\w*)$/))) return `a new ${m[1]}`;
|
|
179
|
+
if ((m = e.match(/^[\w.]+\.(?:get|get_or_404|find|Find|findById|find_by_id)\(\s*([A-Z]\w*)\s*,\s*([\w.]+)\s*\)$/))) return `the ${m[1]} with ${lastSeg(m[2])}`;
|
|
180
|
+
if ((m = e.match(/^([\w.]+)\.get\(\s*([A-Za-z_][\w.]*)\s*[,)]/)) || (m = e.match(/^([\w.]+)\[\s*([A-Za-z_][\w.]*)\s*\]$/))) return `the ${lastSeg(m[2])} entry in ${lastSeg(m[1])}`;
|
|
181
|
+
if (/["'`]\s*\+|\+\s*["'`]/.test(e) && !/[<>=!&|]/.test(e)) return 'text built from its parts';
|
|
182
|
+
if ((m = e.match(/^[A-Za-z_][\w.]*(\s*,\s*[A-Za-z_][\w.]*)+$/))) return e.split(/\s*,\s*/).map(lastSeg).join(' and ');
|
|
183
|
+
if ((m = e.match(/^make\(\s*(\[\]|map\[)/))) return m[1] === '[]' ? 'an empty list' : 'an empty lookup table';
|
|
184
|
+
if (/^(?:f|rf|fr)["']/.test(e) || /^`[^`]*\$\{/.test(e) || /^\$"/.test(e) || /^(?:fmt\.Sprintf|String\.format|format!)\(/.test(e)) return 'text built from its parts';
|
|
185
|
+
if ((m = e.match(/^([\w.]+)\.get\(\s*["'`]([\w.\-: ]{1,40})["'`]/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
|
|
186
|
+
if ((m = e.match(/^([\w.]+)\[\s*["'`]([\w.\-: ]{1,40})["'`]\s*\]$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
|
|
187
|
+
if ((m = e.match(/^([\w.]+)\.split\(\s*["'`]([^"'`]{0,10})["'`]/))) return `${lastSeg(m[1])} split at "${m[2]}"`;
|
|
188
|
+
if ((m = e.match(/^@?([\w.]+?)(?:\.copy|\.clone|\.Clone|\.dup)(?:\(\))?$/))) return `a copy of ${lastSeg(m[1])}`;
|
|
189
|
+
if ((m = e.match(/^(?:str|String|string)\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:toString|to_s|ToString)\(\)$/))) return `${lastSeg(m[1])} as text`;
|
|
190
|
+
if ((m = e.match(/^(?:int|float|Number|parseInt|parseFloat|strconv\.Atoi|Integer\.parseInt|int\.Parse)\(\s*([\w.]+)/))) return `${lastSeg(m[1])} as a number`;
|
|
191
|
+
if ((m = e.match(/^(?:JSON\.parse|json\.loads|json\.load|JsonSerializer\.Deserialize\w*)\(\s*([\w.]+)/))) return `${lastSeg(m[1])} read as JSON`;
|
|
192
|
+
if ((m = e.match(/^(?:JSON\.stringify|json\.dumps|JsonSerializer\.Serialize)\(\s*([\w.]+)/))) return `${lastSeg(m[1])} written as JSON`;
|
|
193
|
+
if (/^(?:dict|Map|HashMap|map)\(\s*\)$|^\{\s*\}$|^new (?:Map|HashMap|Dictionary)\b/.test(e)) return 'an empty lookup table';
|
|
194
|
+
if (/^(?:list|Array|ArrayList|vec!?)\(?\s*\)?$|^\[\s*\]$|^new (?:ArrayList|List)\b/.test(e)) return 'an empty list';
|
|
195
|
+
if ((m = e.match(/^len\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:length|size\(\)|Count|count\(\)|len\(\))$/))) return `how many ${lastSeg(m[1])}`;
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
/** A boolean expression (comparison or logic), said as a yes/no question. */
|
|
199
|
+
const LOGIC = /(&&|\|\||[<>]=?|[!=]==?|\band\b|\bor\b|\bnot\b|\bis\b|^\s*!)/;
|
|
200
|
+
function sayWhether(expr) {
|
|
201
|
+
const e = String(expr).trim();
|
|
202
|
+
if (!LOGIC.test(e) || /=>|\blambda\b|\?.*:/.test(e) || e.length > 90) return null;
|
|
203
|
+
return `whether ${sayCodeCondition(e)}`;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Classify one statement (its first line or header). Returns { kind, says, code } where code is the original text. */
|
|
207
|
+
const CHAIN = [
|
|
208
|
+
{ re: /\.(?:map|Select|flatMap|SelectMany|map_values|collect\{)\s*[({]/, say: (src) => `one for each item in ${src}` },
|
|
209
|
+
{ re: /\.(?:filter|Where|filter_map|select|reject|grep)\s*[({]/, say: (src) => `the items in ${src} that match` },
|
|
210
|
+
{ re: /\.(?:find|First|FirstOrDefault|find_first|detect)\s*[({]/, say: (src) => `the first item in ${src} that matches` },
|
|
211
|
+
{ re: /\.(?:some|Any|any)\s*[({]/, say: (src) => `whether any item in ${src} matches` },
|
|
212
|
+
{ re: /\.(?:every|All|all)\s*[({]/, say: (src) => `whether every item in ${src} matches` },
|
|
213
|
+
{ re: /\.(?:reduce|Aggregate|fold|inject|sum|Sum)\s*[({]/, say: (src) => `a total over ${src}` },
|
|
214
|
+
{ re: /\.(?:sort|sorted|OrderBy|sortBy|sort_by)\s*[({]/, say: (src) => `${src}, sorted` },
|
|
215
|
+
{ re: /\.(?:join|Join|joinToString)\s*[({]/, say: (src) => `${src} joined into text` },
|
|
216
|
+
];
|
|
217
|
+
/** "items.filter(x => …).map(…)" -> "one for each item in items" (the last collection step wins). */
|
|
218
|
+
function sayChain(value) {
|
|
219
|
+
const src = (value.match(/^(?:await\s+)?([A-Za-z_$#][\w$#.]*?)(?:\.(?:iter|into_iter|stream|asSequence|values|keys|entries)\(\))?\./) || [])[1];
|
|
220
|
+
if (!src) return null;
|
|
221
|
+
let hit = null;
|
|
222
|
+
for (const c of CHAIN) { const m = value.match(c.re); if (m && (!hit || m.index > hit.index)) hit = { index: m.index, c }; }
|
|
223
|
+
return hit ? hit.c.say(words(src.split('.').pop().replace(/^#/, ''))) : null;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
227
|
+
const text = String(raw).trim();
|
|
228
|
+
// TypeScript-only syntax that changes nothing for a reader: casts, non-null assertions, optional calls.
|
|
229
|
+
const head = text.split('\n')[0].trim()
|
|
230
|
+
.replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, '$1').replace(/([\w$\])])!(?=[.(\[])/g, '$1').replace(/\?\.(?=[\w(\[])/g, '.').replace(/\.\(/g, '(').replace(/^\(\*+(self|this)\)\./, '$1.')
|
|
231
|
+
// Java/C# casts: ((JsonTreeReader) reader).promote() -> reader.promote(); (int) x -> x
|
|
232
|
+
.replace(/\(\(\s*[A-Z][\w.<>\[\]?, ]*\s*\)\s*([\w$.]+)\s*\)/g, '$1').replace(/^(\w[\w.]*\s*=\s*)\(\s*[A-Z][\w.<>\[\]?]*\s*\)\s*/, '$1');
|
|
233
|
+
const code = clip(head, 90);
|
|
234
|
+
let m;
|
|
235
|
+
const innerNote = inner ? ` (${inner} step${inner === 1 ? '' : 's'} inside)` : '';
|
|
236
|
+
// One-line ifs: `if (x) return y;` and Ruby/Perl modifiers `return unless running?`, `notify if late`.
|
|
237
|
+
let inl;
|
|
238
|
+
if ((inl = head.match(/^(if|else\s+if)\s*\((.+?)\)\s*((?:return|throw|break|continue|yield)\b.*|[\w$.]+\(.*\);?)$/)) && balanced(inl[2])) {
|
|
239
|
+
return { kind: 'branch', says: `If ${sayCodeCondition(inl[2])}`, cond: inl[2], code, inline: inl[3] };
|
|
240
|
+
}
|
|
241
|
+
if ((inl = head.match(/^(.+?)\s+(if|unless)\s+(.+)$/)) && !/\belse\b/.test(head) && !/^(?:if|unless|elsif|while|until|for|return\s+\S+\s+if\s+.+\s+else)\b/.test(head) && !/[=(]\s*$/.test(inl[1]) && !/^(?:[\w$.\[\]]+\s*=)/.test(inl[1])) {
|
|
242
|
+
const cond = sayCodeCondition(inl[3]);
|
|
243
|
+
return { kind: 'branch', says: inl[2] === 'unless' ? `If not: ${cond}` : `If ${cond}`, cond: inl[3], negate: inl[2] === 'unless', code, inline: inl[1] };
|
|
244
|
+
}
|
|
245
|
+
// A name declared with no value yet: `let sizeError: Error | undefined;` -> "Starts with no size error yet".
|
|
246
|
+
if ((inl = head.match(/^(?:let|var|const)\s+([A-Za-z_$][\w$]*)\s*(?::\s*[^=]+)?;?$/))) return { kind: 'set', says: `Starts with no ${words(inl[1])} yet`, code };
|
|
247
|
+
// A function stored under a name: `ky.create = (opts) => ...` -> "Defines how ky's create works".
|
|
248
|
+
if ((inl = head.match(/^([\w$.]+)\s*=\s*(?:async\s+)?(?:function\b|\([^()]*\)\s*(?::\s*[^=]+)?=>|[\w$]+\s*=>)/))) return { kind: 'set', says: `Defines how ${targetWords(inl[1])} works`, code };
|
|
249
|
+
// switch cases: `case X:` / `case X ->` read as "When it is X"; `default:` as "Otherwise".
|
|
250
|
+
if ((m = head.match(/^case\s+(.+?)\s*(?::|->)\s*(.*)$/))) return { kind: 'check', says: `When it is ${/^[A-Z][A-Z0-9_]+$/.test(m[1].replace(/^[A-Z]\w*\./, '')) ? words(m[1].replace(/^[A-Z]\w*\./, '')) : sayCodeCondition(plainEnums(m[1]))}`, code, caseLabel: true };
|
|
251
|
+
if (/^default\s*(?::|->)/.test(head)) return { kind: 'check', says: 'Otherwise', code, caseLabel: true };
|
|
252
|
+
// Failures
|
|
253
|
+
if ((m = head.match(/^(?:throw|raise)\s+(?:new\s+)?([A-Za-z_][\w.]*)?/)) || /^panic!?\s*\(/.test(head)) {
|
|
254
|
+
const name = m?.[1] ? m[1].split('.').pop() : null;
|
|
255
|
+
const msg = (head.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
|
|
256
|
+
const said = name && /^[a-z]/.test(name) ? `the error made by ${words(name)}` : name;
|
|
257
|
+
return { kind: 'fail', says: `Fails${said ? ` with ${said}` : ''}${msg ? `: "${msg}"` : ''}`, code, ...(name ? { error: name } : {}), ...(msg ? { message: msg } : {}) };
|
|
258
|
+
}
|
|
259
|
+
// Returns (Go/Rust error returns read as failures)
|
|
260
|
+
if ((m = head.match(/^return\b\s*(.*)$/))) {
|
|
261
|
+
const expr = stripTail(m[1]);
|
|
262
|
+
if (!expr) return { kind: 'return', says: 'Stops here', code };
|
|
263
|
+
const lastVal = expr.split(',').pop().trim();
|
|
264
|
+
if (/,/.test(expr) && /^(?:err|error|e)$|^Err[A-Z]\w*$|^\w*Error$|^errors\.New\(|^fmt\.Errorf\(/.test(lastVal)) {
|
|
265
|
+
const named = /^Err[A-Z]\w*$|^\w+Error$/.test(lastVal) ? `: ${lastVal}` : '';
|
|
266
|
+
return { kind: 'fail', says: `Returns an error to the caller${named}`, code };
|
|
267
|
+
}
|
|
268
|
+
if (/^(Err|Error)\s*\(/.test(expr) || /\berrors\.New\(|fmt\.Errorf\(/.test(expr)) {
|
|
269
|
+
const msg = (expr.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
|
|
270
|
+
return { kind: 'fail', says: `Returns an error${msg ? `: "${msg}"` : ''}`, code };
|
|
271
|
+
}
|
|
272
|
+
const chain = sayChain(expr);
|
|
273
|
+
if (chain) return { kind: 'return', says: `Returns ${chain}`, code };
|
|
274
|
+
if (/^\(?\s*\{/.test(expr)) return { kind: 'return', says: 'Returns an object', code };
|
|
275
|
+
if (/^\(?\s*</.test(expr)) return { kind: 'return', says: 'Returns what to show on screen', code };
|
|
276
|
+
const v = sayValue(expr) || sayWhether(expr);
|
|
277
|
+
return { kind: 'return', says: v ? `Returns ${v}` : 'Returns a computed value', code, ...(v ? {} : { value: clip(expr, 60) }) };
|
|
278
|
+
}
|
|
279
|
+
// Loops
|
|
280
|
+
// Counted loops: for i := 0; i < n; i++ (Go) and for (int i = 0; i < n; i++) (C-style): "Counts i from 0 while i is less than n".
|
|
281
|
+
if ((m = head.match(/^for\b\s*\(?\s*(?:(?:var|let|const|int|long|size_t|auto|\$)\s*)?\$?(\w+)\s*:?=\s*([^;]+?)\s*;\s*([^;]*?)\s*;\s*[^)]*?\)?\s*\{?\s*$/))) {
|
|
282
|
+
return { kind: 'loop', says: `Counts ${words(m[1])} from ${clip(m[2], 20)}${m[3] ? ` while ${sayCodeCondition(m[3])}` : ''}${innerNote}`, code };
|
|
283
|
+
}
|
|
284
|
+
// Pairs unpacked in a loop: for (const [key, value] of entries) / for key, value in items.items() / foreach ($a as $k => $v)
|
|
285
|
+
if ((m = head.match(/^for\b\s*\(?\s*(?:const|let|var|val)?\s*[\[{(]?\s*([\w$]+)\s*,\s*([\w$]+)\s*[\]})]?\s+(?:of|in)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/))) {
|
|
286
|
+
const src = stripTail(m[3]).replace(/\($/, '()').replace(/^Object\.entries\((.+)\)$/, '$1').replace(/\.(?:items|entries)\(\)$/, '');
|
|
287
|
+
return { kind: 'loop', says: `For each ${words(m[1])} and ${words(m[2])} in ${words(src.split('.').pop())}${innerNote}`, code };
|
|
288
|
+
}
|
|
289
|
+
if ((m = head.match(/^for\b\s*\(?\s*(?:const|let|var|val|final|auto|[\w<>\[\],? ]+?\s)?\s*\(?([\w$, _]+?)\)?\s+(?:of|in|:)\s+(.+?)\)?\s*(?:\{|:|do)?\s*$/))) {
|
|
290
|
+
return { kind: 'loop', says: `For each ${words(m[1].split(',').pop().trim())} in ${words(stripTail(m[2]).split('.').pop().replace(/\(\)$/, ''))}${innerNote}`, code };
|
|
291
|
+
}
|
|
292
|
+
if ((m = head.match(/^for\s+[\w, _]+\s*:=\s*range\s+(.+?)\s*\{?$/))) return { kind: 'loop', says: `For each item in ${words(stripTail(m[1]).split('.').pop())}${innerNote}`, code };
|
|
293
|
+
if ((m = head.match(/^foreach\s*\(\s*(?:var\s+|\w+\s+)?(\$?\w+)\s+in\s+(.+?)\)\s*\{?$/))) return { kind: 'loop', says: `For each ${words(m[1])} in ${words(m[2].split('.').pop())}${innerNote}`, code };
|
|
294
|
+
if ((m = head.match(/^foreach\s*\(\s*(.+?)\s+as\s+(?:\w+\s*=>\s*)?(\w+)\s*\)\s*\{?$/))) return { kind: 'loop', says: `For each ${words(m[2])} in ${words(m[1].split('.').pop())}${innerNote}`, code };
|
|
295
|
+
if ((m = head.match(/^([\w.]+)\.each(?:_with_index)?\s+do\s*\|(\w+)/))) return { kind: 'loop', says: `For each ${words(m[2])} in ${words(m[1].split('.').pop())}${innerNote}`, code };
|
|
296
|
+
if ((m = head.match(/^([\w.]+)\.(?:forEach|each|map|filter|for_each)\s*[({]/))) return { kind: 'loop', says: `For each item in ${words(m[1].split('.').pop())}${innerNote}`, code };
|
|
297
|
+
if ((m = head.match(/^(?:while|until|loop)\b\s*\(?(.*?)\)?\s*(?:\{|:|do)?\s*$/))) return { kind: 'loop', says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
|
|
298
|
+
// Branches
|
|
299
|
+
// Go: `if err := open(); err != nil` -> "If open fails"; `if v, ok := m[k]; ok` -> "If k is in m".
|
|
300
|
+
if ((m = head.match(/^(?:if|else\s+if)\s+(?:[\w]+\s*,\s*)?err\s*:?=\s*([\w.]+)\(.*\);\s*err\s*!=\s*nil\s*\{?\s*$/))) return { kind: 'branch', says: `If ${lastWords(m[1])} fails${innerNote}`, code };
|
|
301
|
+
if ((m = head.match(/^(?:if|else\s+if)\s+[^;{]*:=[^;{]*;\s*(.+?)\s*\{?\s*$/))) { const cond = sayCodeCondition(m[1]); return { kind: 'branch', says: `If ${cond}${innerNote}`, cond: m[1], code }; }
|
|
302
|
+
if ((m = head.match(/^(?:if|elif|else\s+if|unless|when)\b\s*(.*?)\s*(?:\{|:|then)?\s*$/))) { const cond = sayCodeCondition(m[1]); return { kind: 'branch', says: `If ${/^unless\b/.test(head) ? 'not: ' : ''}${cond}${innerNote}`, cond: m[1].replace(/^\((.*)\)$/, '$1'), code, negate: /^unless\b/.test(head) }; }
|
|
303
|
+
if ((m = head.match(/^(?:switch|match|case|select)\b\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/))) return { kind: 'branch', says: `Chooses by ${words(clip(m[1], 40)) || 'value'}${innerNote}`, code };
|
|
304
|
+
if (/^(?:try|begin)\b/.test(head)) return { kind: 'try', says: `Tries the next steps and handles any error${innerNote}`, code };
|
|
305
|
+
if ((m = head.match(/^assert\b\s*(.*?)\s*;?$/))) return { kind: 'check', says: `Checks that ${m[1] ? sayCodeCondition(m[1].replace(/,\s*["'].*$/, '')) : 'a condition holds'}`, code };
|
|
306
|
+
if ((m = head.match(/^assert(?:_\w+|That|Equals|True|False|NotNull|Null)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
|
|
307
|
+
if ((m = head.match(/^(?:expect|t\.(?:Error|Fatal|Errorf|Fatalf|Run)|require\.\w+|assert\.\w+)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
|
|
308
|
+
if ((m = head.match(/^with\s+(.+?)\s+as\s+(.+?):\s*$/))) { const what = /^open\s*\(/.test(m[1]) ? 'a file' : words(clip(stripTail(m[1]).replace(/\(.*$/, ''), 40)); return { kind: 'set', says: `Opens ${what} as ${words(m[2].replace(/[()]/g, ''))}`, code }; }
|
|
309
|
+
if ((m = head.match(/^(?:using|lock|synchronized)\s*\((.+?)\)/))) return { kind: 'set', says: `Uses ${clip(m[1], 50)}`, code };
|
|
310
|
+
if (/^defer\b/.test(head)) return { kind: 'call', says: `At the end, ${clip(head.replace(/^defer\s+/, ''), 60)}`, code };
|
|
311
|
+
if (/^super\b/.test(head)) return { kind: 'call', says: 'Runs the parent version first', code };
|
|
312
|
+
if (/^yield\b/.test(head)) return { kind: 'call', says: 'Hands control to the given block', code };
|
|
313
|
+
if ((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) return { kind: 'return', says: `Returns a new ${words(m[1])}`, code };
|
|
314
|
+
if ((m = head.match(/^(?:[A-Z]\w*::)+([A-Z]\w*)$/))) return { kind: 'return', says: `Returns ${m[1]}`, code };
|
|
315
|
+
if (/^vec!?\[/.test(head)) return { kind: 'return', says: 'Returns a list', code };
|
|
316
|
+
// A bare value as a statement is an implicit return (Ruby, Rust, Kotlin/Scala expression bodies).
|
|
317
|
+
if (/^(?:["'`].*["'`]|-?\d+(?:\.\d+)?|true|false|nil|null|None|self|[a-z_][\w.]*)$/.test(head) && !/^(?:else|end|break|next|redo|retry|pass)$/.test(head)) {
|
|
318
|
+
const v = sayValue(head);
|
|
319
|
+
return { kind: 'return', says: v ? `Returns ${v}` : 'Returns a value', code };
|
|
320
|
+
}
|
|
321
|
+
if ((m = head.match(/^(?:\+\+|--)?([@A-Za-z_$#][\w$#.]*)(\+\+|--)?;?$/)) && (/^(\+\+|--)/.test(head) || m[2])) return { kind: 'set', says: `${/\+\+/.test(head) ? 'Adds one to' : 'Subtracts one from'} ${targetWords(m[1].replace(/#/g, ''))}`, code };
|
|
322
|
+
if ((m = head.match(/^(?:export\s+)?(?:abstract\s+)?(?:class|struct|interface|enum|record|object)\s+([A-Za-z_]\w*)/))) return { kind: 'set', says: `Defines ${words(m[1])}`, code };
|
|
323
|
+
if ((m = head.match(/^(?:async\s+)?(?:function|def|fn|fun|func)\s+([A-Za-z_]\w*)/))) return { kind: 'set', says: `Defines a helper, ${words(m[1])}`, code };
|
|
324
|
+
if ((m = head.match(/^(?:const|let|var|val)\s+([A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=\s*(?:async\s+)?(?:\([^)]*\)|[A-Za-z_$]\w*)\s*(?::\s*[^=]+)?=>/))) return { kind: 'set', says: `Defines a helper, ${words(m[1])}`, code };
|
|
325
|
+
if ((m = head.match(/^(?:const|let|var|val)\s+([{[])\s*(.*?)\s*[}\]]\s*(?::\s*[^=]+)?=\s*(.+)$/))) {
|
|
326
|
+
const names = m[2].split(',').map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, '')).filter(Boolean).map(words);
|
|
327
|
+
const value = stripTail(m[3]); const c = callee(value);
|
|
328
|
+
const from = c ? lastWords(c) : (sayValue(value) || words(value.split('.').pop()));
|
|
329
|
+
return { kind: 'set', says: `Takes ${names.slice(0, 4).join(', ')}${names.length > 4 ? ', …' : ''} from ${from}`, code };
|
|
330
|
+
}
|
|
331
|
+
if ((m = head.match(/^(?:var|const)\s*\($/))) return { kind: 'set', says: 'Declares some values', code };
|
|
332
|
+
if ((m = head.match(/^var\s+([\w, ]+?)\s+[\w.*\[\]]+$/))) return { kind: 'set', says: `Declares ${m[1].split(/\s*,\s*/).map(words).join(', ')}`, code };
|
|
333
|
+
// Typed declaration: Type name = value (Java, C#, C++); the value may continue on the next line.
|
|
334
|
+
if ((m = head.match(/^(?:final\s+|static\s+|readonly\s+)*([A-Z][\w.]*(?:<[^=]*>)?(?:\[\])?|int|long|double|float|boolean|bool|char|byte|short|string|decimal|var|auto)\s+([a-zA-Z_$][\w$]*)\s*=(?!=)\s*(.*)$/))) {
|
|
335
|
+
const value = stripTail(m[3]); const target = words(m[2]);
|
|
336
|
+
const c = value ? callee(value) : null;
|
|
337
|
+
const everyday = value ? sayPython(value) || sayCommon(value) : null;
|
|
338
|
+
if (everyday) return { kind: 'set', says: `Sets ${target} to ${everyday}`, code };
|
|
339
|
+
if (c) {
|
|
340
|
+
const known = sayCall(c, firstArgs(value));
|
|
341
|
+
if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
|
|
342
|
+
if (/^new\s/.test(value)) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
|
|
343
|
+
return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
|
|
344
|
+
}
|
|
345
|
+
const v = value ? sayValue(value) : null;
|
|
346
|
+
return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
|
|
347
|
+
}
|
|
348
|
+
// Assignment (not comparisons)
|
|
349
|
+
if ((m = head.replace(/^(?:final\s+)?(?!return\b|throw\b|yield\b|await\b|new\b)[A-Z][\w.]*(?:<[^=;]*?>)?(?:\[\])*\??\s+(?=[a-z_]\w*\s*=[^=])/, '').match(/^(?:(?:const|let|var|val|final|auto|my|local)\s+)?(?:mut\s+)?([@A-Za-z_$#][\w$#.\[\]'"@]*?(?:\s*,\s*[@A-Za-z_$#][\w$#.@]*)*)(?:\s*:\s*[\w<>\[\]?, .|]+)?\s*(:=|\+=|-=|\*=|\/=|\|\|=|\?\?=|=)(?!=)\s*(.*)$/)) && !/^(?:if|for|while|return)\b/.test(head)) {
|
|
350
|
+
const target = m[1].split(/\s*,\s*/).filter((t) => t !== '_').map(targetWords).join(', ') || targetWords(m[1]);
|
|
351
|
+
const value = stripTail(m[3]);
|
|
352
|
+
// A yes/no value: `ok = proxy and scheme != "https"` -> "Works out ok: whether proxy and scheme is not https".
|
|
353
|
+
if (m[2] === '=' && !/[(?]/.test(value.replace(/^\(|\)$/g, '')) && /(&&|\|\||\band\b|\bor\b|[!=]==?|(?<![-=])[<>]=?)/.test(value.replace(/->|=>/g, '.')) && !/=>/.test(value)) return { kind: 'set', says: `Works out ${target}: whether ${sayCodeCondition(value)}`, code };
|
|
354
|
+
// self.max_books = max_books: the Thing keeps what it was given.
|
|
355
|
+
if (m[2] === '=' && /^[A-Za-z_]\w*$/.test(value) && m[1].split('.').pop() === value && /^(self|this)\./.test(m[1])) return { kind: 'set', says: `Keeps the ${words(value)} it is given`, code };
|
|
356
|
+
const chain = value ? (sayPython(value) || sayChain(value)) : null;
|
|
357
|
+
if (chain) return { kind: 'set', says: `Works out ${target}: ${chain}`, code };
|
|
358
|
+
const common = value ? sayCommon(m[3].trim().replace(/;$/, '')) || sayCommon(value) : null;
|
|
359
|
+
if (common) return { kind: 'set', says: `Sets ${target} to ${common}`, code };
|
|
360
|
+
const keyed = m[2] === '=' && m[1].match(/^([\w$.]+)\[\s*([^\]]+?)\s*\]$/);
|
|
361
|
+
if (keyed) return { kind: 'set', says: `Records ${words(keyed[2].replace(/["'`]/g, ''))} in ${targetWords(keyed[1])}`, code };
|
|
362
|
+
const c = callee(value);
|
|
363
|
+
if (c) {
|
|
364
|
+
const known = sayCall(c, firstArgs(value));
|
|
365
|
+
if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
|
|
366
|
+
if (/^new\s/.test(value)) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
|
|
367
|
+
return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
|
|
368
|
+
}
|
|
369
|
+
if (!value) return { kind: 'set', says: `Works out ${target}`, code };
|
|
370
|
+
if (m[2] === '+=' || m[2] === '-=') { const what = /^[\w.]+$/.test(value) ? `${value.split('.').filter((p) => !/^(self|this)$/.test(p)).slice(-2).map(words).join(' ')} ` : /^-?\d+(\.\d+)?$/.test(value) ? `${value} ` : ''; return { kind: 'set', says: what ? `${m[2] === '+=' ? 'Adds' : 'Subtracts'} ${what}${m[2] === '+=' ? 'to' : 'from'} ${target}` : `${m[2] === '+=' ? 'Adds to' : 'Subtracts from'} ${target}`, code }; }
|
|
371
|
+
const v = sayValue(value);
|
|
372
|
+
return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
|
|
373
|
+
}
|
|
374
|
+
// Calls
|
|
375
|
+
if ((m = head.match(/^([\w$.]+)\.(?:set|Set|put|setdefault|Add)\(\s*["'`]([\w.\-: ]{1,40})["'`]\s*,/))) return { kind: 'call', says: `Sets "${m[2]}" on ${lastSeg(m[1])}`, code, callee: `${m[1]}.set` };
|
|
376
|
+
if ((m = head.match(/^([\w$.]+)\.(?:remove|Remove|discard|delete|pop)\(\s*([\w$]+)\s*\)/)) && !/^(?:db|session|repo|conn|cursor)\b/.test(m[1])) {
|
|
377
|
+
const owner = m[1].split('.').filter((p) => !/^(self|this)$/.test(p));
|
|
378
|
+
const where = owner.length > 1 ? `${words(owner[owner.length - 2])}'s ${words(owner[owner.length - 1])}` : words(owner[0] || m[1]);
|
|
379
|
+
return { kind: 'call', says: `Removes ${words(m[2])} from ${where}`, code, callee: m[1] };
|
|
380
|
+
}
|
|
381
|
+
if ((m = head.match(/^([\w$.]+)\.(?:append|push|add|Add|insert|appendleft|extend)\(\s*([\w$.]*)\s*\)?/)) && !/^(?:db|session|repo|conn|cursor)\b/.test(m[1])) {
|
|
382
|
+
// "student.books.append(book)" -> "Adds book to student's books"
|
|
383
|
+
const owner = m[1].split('.').filter((p) => !/^(self|this)$/.test(p));
|
|
384
|
+
const where = owner.length > 1 ? `${words(owner[owner.length - 2])}'s ${words(owner[owner.length - 1])}` : words(owner[0] || m[1]);
|
|
385
|
+
const added = /^new\s+([A-Z]\w*)/.exec(head.slice(head.indexOf('(') + 1))?.[1];
|
|
386
|
+
return { kind: 'call', says: added ? `Adds a new ${words(added)} to ${where}` : m[2] && /^[A-Za-z_][\w$]*$/.test(m[2]) && m[2] !== 'new' ? `Adds ${words(m[2])} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
|
|
387
|
+
}
|
|
388
|
+
const c = callee(head);
|
|
389
|
+
if (c) {
|
|
390
|
+
const known = sayCall(c, firstArgs(head));
|
|
391
|
+
return { kind: 'call', says: known || `Calls ${lastWords(c)}`, code, callee: c };
|
|
392
|
+
}
|
|
393
|
+
if ((m = head.match(/^([a-z_][\w.]*[?!]?)\s+(?![=<>!+\-*/%]|and\b|or\b|if\b|unless\b)(.+)$/)) && !/^(?:if|for|while|return|else|elsif|when|case|def|class|module|end|not|const|let|var|val|new|await|typeof|delete|void|in|of|throw|import|export|from|as|is)$/.test(m[1])) {
|
|
394
|
+
if (/^assert/.test(m[1])) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
|
|
395
|
+
const known = sayCall(m[1], m[2]);
|
|
396
|
+
const named = /^[:'"]([\w ]+)['"]?/.exec(m[2].trim())?.[1];
|
|
397
|
+
return { kind: 'call', says: known || (named ? `Calls ${lastWords(m[1])}: ${words(named)}` : `Calls ${lastWords(m[1])}`), code, callee: m[1] };
|
|
398
|
+
}
|
|
399
|
+
return { kind: 'other', says: clip(head, 70), code };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Steps for a function body. `statements` are top-level [{ text, line, inner? }]. */
|
|
403
|
+
const spanOf = (s) => ({ startLine: s.line, endLine: s.endLine ?? s.line, ...(s.start != null && s.end != null ? { start: s.start, end: s.end } : {}) });
|
|
404
|
+
|
|
405
|
+
const BARE_CALL = /^[a-z_][\w.]*[?!]?$/;
|
|
406
|
+
const balanced = (x) => { let d = 0; for (const ch of x) { if (ch === '(') d++; else if (ch === ')' && --d < 0) return false; } return d === 0; };
|
|
407
|
+
function asCall(list, i) {
|
|
408
|
+
const st = list[i];
|
|
409
|
+
if (st?.kind === 'return' && BARE_CALL.test(st.code || '') && !/^(?:self|nil|true|false|null|none)$/i.test(st.code)) {
|
|
410
|
+
list[i] = { ...st, kind: 'call', says: `Calls ${lastWords(st.code)}`, callee: st.code };
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const CLAUSE = /^(?:elif\b|elsif\b|else\s+if\b|else\b|except\b|catch\b|rescue\b|finally\b|ensure\b)/;
|
|
415
|
+
|
|
416
|
+
/** Turn a clause (else, elif, except, catch, finally) into what it means for the step it belongs to. */
|
|
417
|
+
function attachClause(step, clause) {
|
|
418
|
+
const kw = clause.kind;
|
|
419
|
+
const kids = stepsFrom(clause.children || []).steps;
|
|
420
|
+
// Chains: the next clause belongs to the innermost else-if.
|
|
421
|
+
let target = step;
|
|
422
|
+
while (target.otherwise?.length === 1 && target.otherwise[0].elseIf) target = target.otherwise[0];
|
|
423
|
+
if (kw === 'elif') {
|
|
424
|
+
const head = clause.head.replace(/^(?:elif|elsif|else\s+if)\b/, 'if');
|
|
425
|
+
const branch = { ...classifyStatement(head), line: clause.line, span: { startLine: clause.line, endLine: clause.endLine ?? clause.line }, elseIf: true };
|
|
426
|
+
if (kids.length) branch.children = kids;
|
|
427
|
+
target.otherwise = [branch];
|
|
428
|
+
} else if (kw === 'else') {
|
|
429
|
+
target.otherwise = kids;
|
|
430
|
+
target.otherwiseLine = clause.line;
|
|
431
|
+
} else if (kw === 'catch') {
|
|
432
|
+
const what = (clause.head.replace(/\\/g, '.').replace(/\(\s*\./, '(').match(/^(?:except|catch|rescue)\s*\(?\s*(?:[\w.]+\s+)?\(?\.?([A-Z][\w.:]*(?:\s*[,|]\s*\.?[A-Z][\w.:]*)*)/) || [])[1]?.replace(/::/g, '.');
|
|
433
|
+
(step.handlers ||= []).push({ says: what ? `If ${what.split(/\s*[,|]\s*/).map((x) => x.split('.').pop()).join(' or ')} goes wrong` : 'If anything goes wrong', line: clause.line, steps: kids });
|
|
434
|
+
} else if (kw === 'finally') {
|
|
435
|
+
// Code that always runs at the end is never the value given back.
|
|
436
|
+
for (let i = 0; i < kids.length; i++) asCall(kids, i);
|
|
437
|
+
step.always = { line: clause.line, steps: kids };
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
export function stepsFrom(statements) {
|
|
442
|
+
const steps = [];
|
|
443
|
+
const skipped = [];
|
|
444
|
+
// After a clause written without its own block (Ruby: a method-level `rescue` or `ensure`), the statements that
|
|
445
|
+
// follow belong to that clause until the next clause.
|
|
446
|
+
let into = null, intoAlways = false;
|
|
447
|
+
for (const s of statements) {
|
|
448
|
+
const t0 = (s.text || '').trim();
|
|
449
|
+
if (into && !CLAUSE.test(t0) && t0 && !/^(?:end\b|#)/.test(t0)) {
|
|
450
|
+
const st = stepsFrom([s]).steps;
|
|
451
|
+
into.push(...st);
|
|
452
|
+
// Earlier lines of a handler are calls; nothing in `ensure` is the value given back.
|
|
453
|
+
for (let i = 0; i < into.length - (intoAlways ? 0 : 1); i++) asCall(into, i);
|
|
454
|
+
continue;
|
|
455
|
+
}
|
|
456
|
+
// A clause belongs to the step before it (indent languages write it as a sibling line).
|
|
457
|
+
if (CLAUSE.test(t0)) {
|
|
458
|
+
const prev = steps[steps.length - 1];
|
|
459
|
+
if (/^(?:rescue|ensure|except|finally)\b/.test(t0) && steps.length && !(prev && prev.kind === 'try')) {
|
|
460
|
+
// Ruby: `def x ... rescue ... end` with no `begin`: everything before the rescue is what is tried.
|
|
461
|
+
const tried = steps.splice(0, steps.length);
|
|
462
|
+
for (let i = 0; i < tried.length - 1; i++) asCall(tried, i);
|
|
463
|
+
steps.push({ kind: 'try', says: 'Tries these steps and handles any error', code: '(the whole method)', line: tried[0].line, span: { startLine: tried[0].span.startLine, endLine: tried[tried.length - 1].span.endLine }, children: tried });
|
|
464
|
+
}
|
|
465
|
+
const prev2 = steps[steps.length - 1];
|
|
466
|
+
if (prev2 && (prev2.kind === 'branch' || prev2.kind === 'try')) {
|
|
467
|
+
const prev = prev2;
|
|
468
|
+
const kw = /^(?:elif|elsif|else\s+if)\b/.test(t0) ? 'elif' : /^else\b/.test(t0) ? 'else' : /^(?:finally|ensure)\b/.test(t0) ? 'finally' : 'catch';
|
|
469
|
+
attachClause(prev, { kind: kw, head: t0.replace(/:\s*$/, ''), line: s.line, endLine: s.endLine, children: s.children || [] });
|
|
470
|
+
intoAlways = kw === 'finally';
|
|
471
|
+
into = s.children?.length ? null : kw === 'catch' ? prev.handlers?.[prev.handlers.length - 1]?.steps ?? null : kw === 'finally' ? prev.always?.steps ?? null : null;
|
|
472
|
+
prev.span = { ...prev.span, endLine: Math.max(prev.span.endLine, s.endLine ?? s.line) };
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
skipped.push(spanOf(s));
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (!t0 || /^(?:end\b|\}|pass$|break$|continue$|#)/.test(t0)) { if (t0 && !/^#/.test(t0)) skipped.push(spanOf(s)); continue; }
|
|
479
|
+
if (/^(?:"""|'''|r"""|\/\*\*|\*)/.test(t0)) { skipped.push(spanOf(s)); continue; } // docstrings and doc comments
|
|
480
|
+
if (/^[)\]}]+[):;,]*$/.test(t0) || /^\.\.\.$/.test(t0) || /^\.[A-Za-z_]/.test(t0) || /^@\w+(?:\(.*\))?$/.test(t0) || /^#?\[[\w:]+(?:\(.*\))?\]$/.test(t0) || /^:(?:param|rtype|return|raises|type)\b/.test(t0)) { skipped.push(spanOf(s)); continue; }
|
|
481
|
+
const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
|
|
482
|
+
if (s.children?.length && ['branch', 'loop', 'try'].includes(step.kind)) {
|
|
483
|
+
const kids = stepsFrom(s.children).steps;
|
|
484
|
+
if (kids.length) { step.children = kids; step.says = step.says.replace(/ \(\d+ steps? inside\)$/, ''); }
|
|
485
|
+
}
|
|
486
|
+
if (step.inline && !step.children) { const kid = classifyStatement(step.inline); step.children = [{ ...kid, line: s.line, span: spanOf(s) }]; delete step.inline; }
|
|
487
|
+
else delete step.inline;
|
|
488
|
+
for (const c of s.clauses || []) attachClause(step, c);
|
|
489
|
+
steps.push(step);
|
|
490
|
+
}
|
|
491
|
+
// A bare word is only a returned value when it is the last statement; before that it is a call (Ruby: `rollback`).
|
|
492
|
+
for (let i = 0; i < steps.length - 1; i++) asCall(steps, i);
|
|
493
|
+
// Every step is kept (anchoring needs all of them); `more` tells a view how many to fold away.
|
|
494
|
+
const more = Math.max(0, steps.length - MAX_STEPS);
|
|
495
|
+
for (const st of steps) if (restates(st)) st.restates = true;
|
|
496
|
+
return { steps, more, skipped, readable: readableShare(steps) };
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* A step that only puts the code's syntax into English ("Works out actives", "Returns the result of any") tells a
|
|
501
|
+
* reader nothing the code did not. It is kept, but marked `restates` and not counted as read.
|
|
502
|
+
*/
|
|
503
|
+
const GENERIC_CALLS = /^(?:get|set|run|do|call|apply|handle|process|execute|exec|make|build|create|new|init|load|fetch|parse|convert|to|from|str|int|float|bool|list|dict|set|tuple|len|any|all|map|filter|next|iter|super|format|join|split|strip|copy|update|value|values|items|keys)$/;
|
|
504
|
+
function restates(st) {
|
|
505
|
+
const s = st.says || '';
|
|
506
|
+
if (st.kind === 'other') return false;
|
|
507
|
+
if (/^Works out [^:]+$/.test(s) && !/ from /.test(s)) return true;
|
|
508
|
+
const same = s.match(/^Works out (.+) from (.+)$/);
|
|
509
|
+
if (same && same[1].trim() === same[2].trim()) return true; // "Works out licence from licence"
|
|
510
|
+
if (/^(Returns a computed value|Returns a value|Sets .+ to a computed value)$/.test(s)) return true;
|
|
511
|
+
const via = s.match(/(?:the result of|from|^Calls) ([\w ]+?)$/);
|
|
512
|
+
if (via && GENERIC_CALLS.test(via[1].trim())) return true;
|
|
513
|
+
return false;
|
|
514
|
+
}
|
|
515
|
+
const readableShare = (steps) => steps.length ? steps.filter((x) => x.kind !== 'other' && !x.restates).length / steps.length : 0;
|
|
516
|
+
|
|
517
|
+
const blockEnd = (text, open) => {
|
|
518
|
+
let depth = 0;
|
|
519
|
+
for (let i = open; i < text.length; i++) {
|
|
520
|
+
const c = text[i];
|
|
521
|
+
if (c === '"' || c === "'" || c === '`') { for (i++; i < text.length && text[i] !== c; i++) if (text[i] === '\\') i++; continue; }
|
|
522
|
+
if (c === '{') depth++; else if (c === '}' && --depth === 0) return i;
|
|
523
|
+
}
|
|
524
|
+
return -1;
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Statements of a brace body, each with its whole block read (every depth), and every clause that follows the first
|
|
529
|
+
* block: else if, else, catch, finally. Nothing is summarized away.
|
|
530
|
+
*/
|
|
531
|
+
export function braceStatements(stmts, split = null) {
|
|
532
|
+
return stmts.map((s) => {
|
|
533
|
+
const text = s.text;
|
|
534
|
+
const open = text.indexOf('{');
|
|
535
|
+
const lineAtPos = (pos) => s.line + (text.slice(0, pos).match(/\n/g) || []).length;
|
|
536
|
+
const read = (o, e) => {
|
|
537
|
+
const body = e > o ? text.slice(o + 1, e) : '';
|
|
538
|
+
const base = s.start != null ? s.start + o + 1 : null;
|
|
539
|
+
if (!body || !split) return [];
|
|
540
|
+
const kids = split(body, lineAtPos(o + 1)).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...(base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {}) }));
|
|
541
|
+
return braceStatements(kids, split);
|
|
542
|
+
};
|
|
543
|
+
let children = [], inner = 0;
|
|
544
|
+
const clauses = [];
|
|
545
|
+
if (open >= 0) {
|
|
546
|
+
const end = blockEnd(text, open);
|
|
547
|
+
const body = end > open ? text.slice(open + 1, end) : '';
|
|
548
|
+
inner = body ? body.split(/;|\n/).filter((l) => l.trim() && !/^[{}]$/.test(l.trim())).length : 0;
|
|
549
|
+
children = read(open, end);
|
|
550
|
+
let pos = end + 1;
|
|
551
|
+
while (end >= 0) {
|
|
552
|
+
const rest = text.slice(pos);
|
|
553
|
+
const m = rest.match(/^\s*(else\s+if\b|elseif\b|elsif\b|else\b|catch\b|rescue\b|finally\b|ensure\b)/);
|
|
554
|
+
if (!m) break;
|
|
555
|
+
const kw = m[1].replace(/\s+/g, ' ');
|
|
556
|
+
const o = text.indexOf('{', pos + m[0].length);
|
|
557
|
+
if (o < 0) break;
|
|
558
|
+
const e = blockEnd(text, o);
|
|
559
|
+
const clauseHead = text.slice(pos + m[0].length - m[1].length, o).trim();
|
|
560
|
+
clauses.push({ kind: /^(else if|elseif|elsif)$/.test(kw) ? 'elif' : kw === 'else' ? 'else' : kw === 'finally' || kw === 'ensure' ? 'finally' : 'catch', head: clauseHead, line: lineAtPos(pos + rest.indexOf(m[1])), children: read(o, e) });
|
|
561
|
+
if (e < 0) break;
|
|
562
|
+
pos = e + 1;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...(clauses.length ? { clauses } : {}) };
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** Top-level statements for an indentation body (Python) or depth body (Ruby). */
|
|
570
|
+
export function indentStatements(body, { depthKey = 'indent' } = {}) {
|
|
571
|
+
if (!body?.length) return [];
|
|
572
|
+
// Drop multi-line docstrings first: everything between an opening and closing triple quote.
|
|
573
|
+
const kept = [];
|
|
574
|
+
let inDoc = null, docEntry = null;
|
|
575
|
+
for (const l of body) {
|
|
576
|
+
const t = l.text.trim();
|
|
577
|
+
if (inDoc) { docEntry.endLine = l.line; if (t.includes(inDoc)) inDoc = null; continue; }
|
|
578
|
+
const q = (t.match(/^[rbuf]{0,2}("""|''')/) || [])[1];
|
|
579
|
+
// Docstrings are kept as one entry so they count as read (skipped as documentation, not dropped).
|
|
580
|
+
if (q) { const doc = { ...l, text: q, endLine: l.line }; kept.push(doc); if (t.slice(t.indexOf(q) + 3).includes(q) === false) { inDoc = q; docEntry = doc; } continue; }
|
|
581
|
+
kept.push(l);
|
|
582
|
+
}
|
|
583
|
+
body = kept;
|
|
584
|
+
if (!body.length) return [];
|
|
585
|
+
const base = Math.min(...body.map((l) => l[depthKey] ?? 0));
|
|
586
|
+
const out = [];
|
|
587
|
+
for (let i = 0; i < body.length; i++) {
|
|
588
|
+
const l = body[i];
|
|
589
|
+
if ((l[depthKey] ?? 0) !== base) continue;
|
|
590
|
+
let k = i + 1;
|
|
591
|
+
while (k < body.length && (body[k][depthKey] ?? 0) > base) k++;
|
|
592
|
+
const block = body.slice(i + 1, k);
|
|
593
|
+
// Every depth is kept: the block's own statements, each with its own block (no level is folded away).
|
|
594
|
+
const children = block.length ? indentStatements(block, { depthKey }) : [];
|
|
595
|
+
out.push({ text: l.text, line: l.line, endLine: block.length ? block[block.length - 1].line : (l.endLine ?? l.line), inner: block.length, children });
|
|
596
|
+
}
|
|
597
|
+
return out;
|
|
598
|
+
}
|
|
599
|
+
|