@skillstech/thunderlang 0.5.4 → 0.5.6
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 +112 -0
- package/README.md +3 -0
- package/dist/core.cjs +2240 -424
- package/dist/index.cjs +1247 -113
- package/dist/learn.cjs +6066 -0
- package/package.json +10 -1
- package/src/cli.mjs +45 -2
- package/src/core.d.ts +14 -0
- package/src/core.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/learn-lessons.mjs +458 -0
- package/src/learn.d.mts +34 -0
- package/src/learn.mjs +77 -0
- package/src/model.d.mts +18 -0
- package/src/model.mjs +456 -0
- package/src/read.d.mts +25 -1
- package/src/read.mjs +280 -23
- package/src/same.d.mts +10 -0
- package/src/same.mjs +160 -0
- package/src/steps.mjs +351 -49
- package/src/thunder-repo.mjs +1 -1
- 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/steps.mjs
CHANGED
|
@@ -18,10 +18,52 @@ const KNOWN_CALLS = [
|
|
|
18
18
|
{ re: /^(?:log|logger|console|logging|fmt|Log|System\.out|println|print|puts|echo|printf)\b/i, say: () => 'Writes a log or message' },
|
|
19
19
|
];
|
|
20
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
|
+
|
|
21
27
|
/** A condition as words when it can't be fully translated: c.ctx == nil -> "c.ctx is empty". */
|
|
22
28
|
export function sayCodeCondition(cond) {
|
|
23
|
-
let c = String(cond).trim().replace(/\s*(\{|:|then|do)\s*$/, '').trim();
|
|
29
|
+
let c = plainEnums(String(cond)).trim().replace(/\s*(\{|:|then|do)\s*$/, '').trim();
|
|
24
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
|
+
}
|
|
25
67
|
return clip(c
|
|
26
68
|
.replace(/\s*(===|==)\s*(nil|null|None|undefined|""|'')(?=\s|\)|$)/g, ' is empty')
|
|
27
69
|
.replace(/\s*(!==|!=)\s*(""|'')(?=\s|\)|$)/g, ' is not empty')
|
|
@@ -29,6 +71,10 @@ export function sayCodeCondition(cond) {
|
|
|
29
71
|
.replace(/\bis not None\b/g, 'is set').replace(/\bis None\b/g, 'is empty')
|
|
30
72
|
.replace(/\s*(===|==)\s*/g, ' is ').replace(/\s*(!==|!=)\s*/g, ' is not ')
|
|
31
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 ')
|
|
32
78
|
.replace(/(^|[\s(])!(?=[\w(])/g, '$1not ').replace(/\s+/g, ' '), 70);
|
|
33
79
|
}
|
|
34
80
|
function matchingClose(str, open) {
|
|
@@ -39,13 +85,13 @@ function matchingClose(str, open) {
|
|
|
39
85
|
const lastWords = (path) => words(String(path).split('.').pop());
|
|
40
86
|
/** "cmd.commandCalledAs.called" -> "called on command called as"; "this.count" -> "count". */
|
|
41
87
|
function targetWords(path) {
|
|
42
|
-
const parts = String(path).replace(
|
|
88
|
+
const parts = String(path).replace(/^[@$]+/, '').replace(/#/g, '').replace(/\[.*$/, '').split('.').filter((p) => !/^(this|self)$/.test(p));
|
|
43
89
|
if (parts.length <= 1) return words(parts[0] || path);
|
|
44
|
-
return
|
|
90
|
+
return `the ${words(parts[parts.length - 2])}'s ${words(parts[parts.length - 1])}`;
|
|
45
91
|
}
|
|
46
92
|
|
|
47
93
|
function callee(text) {
|
|
48
|
-
const m = String(text).match(/^(?:await\s+|try\s+|yield\s+|void\s+)?(?:new\s+)?([A-Za-z_$#@][\w$#]*(?:<[^()]*?>)?(?:(?:\.|::|->)[A-Za-z_$#][\w$#]*(?:<[^()]*?>)?(?:\(\))?)*)!?\s*\(/);
|
|
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*\(/);
|
|
49
95
|
return m ? m[1].replace(/<[^()]*?>/g, '').replace(/\(\)/g, '').replace(/::|->/g, '.').replace(/#/g, '') : null;
|
|
50
96
|
}
|
|
51
97
|
function sayCall(name, args) {
|
|
@@ -62,7 +108,12 @@ function firstArgs(text) {
|
|
|
62
108
|
}
|
|
63
109
|
|
|
64
110
|
function sayValue(expr) {
|
|
65
|
-
|
|
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;
|
|
66
117
|
if (/^["'`].*["'`]$/.test(e)) return `"${clip(e.slice(1, -1), 40)}"`;
|
|
67
118
|
if (/^-?\d+(\.\d+)?$/.test(e) || /^(true|false|True|False|nil|null|None|undefined)$/.test(e)) return e;
|
|
68
119
|
const c = callee(e);
|
|
@@ -70,10 +121,88 @@ function sayValue(expr) {
|
|
|
70
121
|
if (/^new\s/.test(e)) return `a new ${c.split('.').pop()}`;
|
|
71
122
|
return `the result of ${lastWords(c)}`;
|
|
72
123
|
}
|
|
73
|
-
if (/^[A-Za-z_$][\w$.]*$/.test(e)) return words(e.split('.').pop());
|
|
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);
|
|
74
126
|
return null;
|
|
75
127
|
}
|
|
76
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
|
+
|
|
77
206
|
/** Classify one statement (its first line or header). Returns { kind, says, code } where code is the original text. */
|
|
78
207
|
const CHAIN = [
|
|
79
208
|
{ re: /\.(?:map|Select|flatMap|SelectMany|map_values|collect\{)\s*[({]/, say: (src) => `one for each item in ${src}` },
|
|
@@ -98,15 +227,34 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
98
227
|
const text = String(raw).trim();
|
|
99
228
|
// TypeScript-only syntax that changes nothing for a reader: casts, non-null assertions, optional calls.
|
|
100
229
|
const head = text.split('\n')[0].trim()
|
|
101
|
-
.replace(/\(\s*([\w$#.]+)\s+as\s+[^)]+\)/g, '$1').replace(/([\w$\])])!(?=[.(\[])/g, '$1').replace(/\?\.(?=[\w(\[])/g, '.').replace(/\.\(/g, '(').replace(/^\(\*+(self|this)\)\./, '$1.')
|
|
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');
|
|
102
233
|
const code = clip(head, 90);
|
|
103
234
|
let m;
|
|
104
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 };
|
|
105
252
|
// Failures
|
|
106
253
|
if ((m = head.match(/^(?:throw|raise)\s+(?:new\s+)?([A-Za-z_][\w.]*)?/)) || /^panic!?\s*\(/.test(head)) {
|
|
107
254
|
const name = m?.[1] ? m[1].split('.').pop() : null;
|
|
108
255
|
const msg = (head.match(/["'`]([^"'`]{1,60})["'`]/) || [])[1];
|
|
109
|
-
|
|
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 } : {}) };
|
|
110
258
|
}
|
|
111
259
|
// Returns (Go/Rust error returns read as failures)
|
|
112
260
|
if ((m = head.match(/^return\b\s*(.*)$/))) {
|
|
@@ -123,13 +271,22 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
123
271
|
}
|
|
124
272
|
const chain = sayChain(expr);
|
|
125
273
|
if (chain) return { kind: 'return', says: `Returns ${chain}`, code };
|
|
126
|
-
if (
|
|
274
|
+
if (/^\(?\s*\{/.test(expr)) return { kind: 'return', says: 'Returns an object', code };
|
|
127
275
|
if (/^\(?\s*</.test(expr)) return { kind: 'return', says: 'Returns what to show on screen', code };
|
|
128
|
-
const v = sayValue(expr);
|
|
276
|
+
const v = sayValue(expr) || sayWhether(expr);
|
|
129
277
|
return { kind: 'return', says: v ? `Returns ${v}` : 'Returns a computed value', code, ...(v ? {} : { value: clip(expr, 60) }) };
|
|
130
278
|
}
|
|
131
279
|
// Loops
|
|
132
|
-
|
|
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*$/))) {
|
|
133
290
|
return { kind: 'loop', says: `For each ${words(m[1].split(',').pop().trim())} in ${words(stripTail(m[2]).split('.').pop().replace(/\(\)$/, ''))}${innerNote}`, code };
|
|
134
291
|
}
|
|
135
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 };
|
|
@@ -137,8 +294,11 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
137
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 };
|
|
138
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 };
|
|
139
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 };
|
|
140
|
-
if ((m = head.match(/^(?:while|until|loop)\b\s*\(?(.*?)\)?\s*(?:\{|:|do)?\s*$/))) return { kind: 'loop', says: m[1] ? `Repeats while ${
|
|
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 };
|
|
141
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 }; }
|
|
142
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) }; }
|
|
143
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 };
|
|
144
304
|
if (/^(?:try|begin)\b/.test(head)) return { kind: 'try', says: `Tries the next steps and handles any error${innerNote}`, code };
|
|
@@ -174,6 +334,8 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
174
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*(.*)$/))) {
|
|
175
335
|
const value = stripTail(m[3]); const target = words(m[2]);
|
|
176
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 };
|
|
177
339
|
if (c) {
|
|
178
340
|
const known = sayCall(c, firstArgs(value));
|
|
179
341
|
if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
|
|
@@ -184,11 +346,19 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
184
346
|
return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
|
|
185
347
|
}
|
|
186
348
|
// Assignment (not comparisons)
|
|
187
|
-
if ((m = head.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)) {
|
|
188
|
-
const target = m[1].split(/\s*,\s*/).map(targetWords).join(', ');
|
|
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]);
|
|
189
351
|
const value = stripTail(m[3]);
|
|
190
|
-
|
|
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;
|
|
191
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 };
|
|
192
362
|
const c = callee(value);
|
|
193
363
|
if (c) {
|
|
194
364
|
const known = sayCall(c, firstArgs(value));
|
|
@@ -197,11 +367,24 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
197
367
|
return { kind: 'set', says: `Works out ${target} from ${lastWords(c)}`, code, callee: c };
|
|
198
368
|
}
|
|
199
369
|
if (!value) return { kind: 'set', says: `Works out ${target}`, code };
|
|
200
|
-
if (m[2] === '+=' || m[2] === '-=') return { kind: 'set', says: `${m[2] === '+=' ? 'Adds to' : 'Subtracts from'} ${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 }; }
|
|
201
371
|
const v = sayValue(value);
|
|
202
372
|
return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
|
|
203
373
|
}
|
|
204
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
|
+
}
|
|
205
388
|
const c = callee(head);
|
|
206
389
|
if (c) {
|
|
207
390
|
const known = sayCall(c, firstArgs(head));
|
|
@@ -210,7 +393,8 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
210
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])) {
|
|
211
394
|
if (/^assert/.test(m[1])) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
|
|
212
395
|
const known = sayCall(m[1], m[2]);
|
|
213
|
-
|
|
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] };
|
|
214
398
|
}
|
|
215
399
|
return { kind: 'other', says: clip(head, 70), code };
|
|
216
400
|
}
|
|
@@ -218,42 +402,167 @@ export function classifyStatement(raw, { inner = 0 } = {}) {
|
|
|
218
402
|
/** Steps for a function body. `statements` are top-level [{ text, line, inner? }]. */
|
|
219
403
|
const spanOf = (s) => ({ startLine: s.line, endLine: s.endLine ?? s.line, ...(s.start != null && s.end != null ? { start: s.start, end: s.end } : {}) });
|
|
220
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
|
+
|
|
221
441
|
export function stepsFrom(statements) {
|
|
222
442
|
const steps = [];
|
|
223
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;
|
|
224
447
|
for (const s of statements) {
|
|
225
|
-
|
|
226
|
-
if (!
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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; }
|
|
230
481
|
const step = { ...classifyStatement(s.text, { inner: s.inner || 0 }), line: s.line, span: spanOf(s) };
|
|
231
482
|
if (s.children?.length && ['branch', 'loop', 'try'].includes(step.kind)) {
|
|
232
|
-
const kids = stepsFrom(s.children
|
|
483
|
+
const kids = stepsFrom(s.children).steps;
|
|
233
484
|
if (kids.length) { step.children = kids; step.says = step.says.replace(/ \(\d+ steps? inside\)$/, ''); }
|
|
234
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);
|
|
235
489
|
steps.push(step);
|
|
236
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);
|
|
237
493
|
// Every step is kept (anchoring needs all of them); `more` tells a view how many to fold away.
|
|
238
494
|
const more = Math.max(0, steps.length - MAX_STEPS);
|
|
239
|
-
|
|
495
|
+
for (const st of steps) if (restates(st)) st.restates = true;
|
|
496
|
+
return { steps, more, skipped, readable: readableShare(steps) };
|
|
240
497
|
}
|
|
241
498
|
|
|
242
|
-
/**
|
|
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
|
+
*/
|
|
243
531
|
export function braceStatements(stmts, split = null) {
|
|
244
532
|
return stmts.map((s) => {
|
|
245
|
-
const
|
|
246
|
-
|
|
247
|
-
|
|
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 = [];
|
|
248
545
|
if (open >= 0) {
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
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
|
+
}
|
|
252
564
|
}
|
|
253
|
-
|
|
254
|
-
const base = s.start != null && open >= 0 ? s.start + open + 1 : null;
|
|
255
|
-
const children = body && split ? split(body, s.line).map((c) => ({ text: c.text, line: c.line, endLine: c.endLine, ...(base != null && c.start != null ? { start: base + c.start, end: base + c.end } : {}) })) : [];
|
|
256
|
-
return { text: s.text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children };
|
|
565
|
+
return { text, line: s.line, endLine: s.endLine, start: s.start, end: s.end, inner, children, ...(clauses.length ? { clauses } : {}) };
|
|
257
566
|
});
|
|
258
567
|
}
|
|
259
568
|
|
|
@@ -278,20 +587,13 @@ export function indentStatements(body, { depthKey = 'indent' } = {}) {
|
|
|
278
587
|
for (let i = 0; i < body.length; i++) {
|
|
279
588
|
const l = body[i];
|
|
280
589
|
if ((l[depthKey] ?? 0) !== base) continue;
|
|
281
|
-
let
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
const d = body[k][depthKey] ?? 0;
|
|
288
|
-
if (childDepth === null) childDepth = d;
|
|
289
|
-
if (d === childDepth) children.push({ text: body[k].text, line: body[k].line });
|
|
290
|
-
last = body[k].line;
|
|
291
|
-
}
|
|
292
|
-
// A child statement runs until the line before the next child (or the end of the block).
|
|
293
|
-
children.forEach((c, n) => { const next = children[n + 1]; const nextIdx = next ? body.findIndex((x) => x.line === next.line) : -1; const until = next ? body[nextIdx - 1]?.line ?? c.line : last; c.endLine = Math.max(c.line, until); });
|
|
294
|
-
out.push({ text: l.text, line: l.line, endLine: last, inner, children });
|
|
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 });
|
|
295
596
|
}
|
|
296
597
|
return out;
|
|
297
598
|
}
|
|
599
|
+
|
package/src/thunder-repo.mjs
CHANGED
|
@@ -21,7 +21,7 @@ export function parseGitHub(target) {
|
|
|
21
21
|
return { owner: m[1], repo: m[2], url: `https://github.com/${m[1]}/${m[2]}.git` };
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
function cloneGitHub(gh, { timeoutMs = 120000 } = {}) {
|
|
24
|
+
export function cloneGitHub(gh, { timeoutMs = 120000 } = {}) {
|
|
25
25
|
const dir = mkdtempSync(join(tmpdir(), 'thunder-repo-'));
|
|
26
26
|
const res = spawnSync('git', ['clone', '--depth', '1', '--quiet', '--no-tags', gh.url, join(dir, 'repo')], {
|
|
27
27
|
timeout: timeoutMs, encoding: 'utf8', env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// thunderize-v1: a whole app written in Thunder Text (see src/thunderize.mjs).
|
|
2
|
+
export const THUNDERIZE_SCHEMA: 'thunderize-v1';
|
|
3
|
+
export const THUNDER_TEXT_EXT: '.thunder-text';
|
|
4
|
+
export interface ThunderizedFile {
|
|
5
|
+
path: string; language: string; out: string; text: string;
|
|
6
|
+
counts: { actions: number; rules: number; functions: number; notReadYet: number; failures: number };
|
|
7
|
+
items: { name: string; line: number; element: string; title: string; route?: string }[];
|
|
8
|
+
}
|
|
9
|
+
export function thunderizeFile(path: string, source: string, language?: string): ThunderizedFile;
|
|
10
|
+
export function thunderizeFiles(files: { path: string; source: string; size?: number }[], options?: { name?: string }): {
|
|
11
|
+
schema: 'thunderize-v1'; name: string; languages: string[]; index: string; files: ThunderizedFile[];
|
|
12
|
+
counts: { files: number; actions: number; rules: number; functions: number; notReadYet: number };
|
|
13
|
+
skipped: { path: string; reason: string }[];
|
|
14
|
+
};
|