@skillstech/thunderlang 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +190 -0
- package/dist/core.cjs +6718 -1232
- package/dist/index.cjs +17490 -12204
- package/dist/learn.cjs +5866 -497
- package/package.json +6 -2
- package/src/cli-home.mjs +1 -1
- package/src/cli.mjs +54 -6
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +148 -8
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -1
- package/src/core/engine-core.mjs +285 -2
- package/src/core/engine-values.mjs +1 -1
- package/src/core/format.mjs +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +2 -1
- package/src/core/java/thunder/T.java +6 -0
- package/src/core/java/thunder/ThunderRuntime.java +1374 -0
- package/src/core/java-run.mjs +89 -0
- package/src/core/parser.mjs +331 -5
- package/src/core/project.mjs +31 -6
- package/src/core/react-run.mjs +96 -0
- package/src/core/runtime-go/thunder_runtime.go +3038 -0
- package/src/core/runtime-react.mjs +133 -0
- package/src/core/rust/thunder_runtime.rs +1645 -0
- package/src/core/rust-run.mjs +192 -0
- package/src/core/screen-values.mjs +30 -0
- package/src/core/target-csharp.mjs +484 -0
- package/src/core/target-go.mjs +555 -0
- package/src/core/target-java.mjs +587 -0
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +2 -2
- package/src/core.d.ts +59 -0
- package/src/core.mjs +14 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +34 -1
- package/src/flow/access.mjs +1451 -0
- package/src/flow/ts-parse.mjs +772 -0
- package/src/index.d.ts +3 -0
- package/src/index.mjs +3 -0
- package/src/libraries.mjs +32 -4
- package/src/model.mjs +72 -9
- package/src/passport-cli.mjs +101 -0
- package/src/passport-fs.d.mts +9 -0
- package/src/passport-fs.mjs +180 -0
- package/src/passport.d.mts +46 -0
- package/src/passport.mjs +255 -0
- package/src/program.d.mts +31 -0
- package/src/program.mjs +14 -0
- package/src/read-level.mjs +48 -2
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +64 -5
- package/src/replay-cli.mjs +123 -0
- package/src/review.mjs +31 -3
- package/src/say-less.mjs +168 -13
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +443 -20
- package/src/term.mjs +43 -0
- package/src/things-langs.mjs +20 -3
- package/src/write-across-cli.mjs +143 -0
- package/src/write-across.mjs +168 -0
package/src/steps.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { sayLibraryCall } from './libraries.mjs';
|
|
2
|
-
import { splitLogic, wrapped, accountsFor, asCodeWords, isCodeWords, closeOf, balancedText } from './faithful.mjs';
|
|
2
|
+
import { splitLogic, wrapped, accountsFor, asCodeWords, isCodeWords, closeOf, balancedText, pythonImportSays, sliceWords } from './faithful.mjs';
|
|
3
3
|
import { parseStatement, parseExpr } from './meaning.mjs';
|
|
4
4
|
// Steps: read any function as a short list of plain steps (check, branch, loop, set, call, return, fail).
|
|
5
5
|
// Decisions become rules; everything else becomes steps. Deterministic and pattern-based, like the rest of
|
|
@@ -120,6 +120,40 @@ const KNOWN_CALLS = [
|
|
|
120
120
|
{ re: /^(?:log|logger|console|logging|fmt|Log|System\.out|println|print|puts|echo|printf|fprintf|fputs|perror|NSLog|os_log|debugPrint|syslog|std\.(?:cout|cerr|print|println))\b/i, say: () => 'Writes a log or message' },
|
|
121
121
|
];
|
|
122
122
|
|
|
123
|
+
/**
|
|
124
|
+
* Python `range(…)` in a loop, in words: `range(3)` "Counts i from 0 to 2", `range(n)` "Counts i from 0 up to n (not n
|
|
125
|
+
* itself)", `range(a, b)` "from a up to b (not b itself)", `range(len(xs))` "For each position i in xs", `_` "Repeats n
|
|
126
|
+
* times". Null for a step, or for anything but numbers and plain names.
|
|
127
|
+
*/
|
|
128
|
+
function pythonRangeWords(v, argText) {
|
|
129
|
+
const args = splitTopArgs(argText).map((x) => x.trim());
|
|
130
|
+
const plainPath = (x) => /^[A-Za-z_][\w.]*$/.test(x);
|
|
131
|
+
const num = (x) => /^\d+$/.test(x);
|
|
132
|
+
if (args.length === 1) {
|
|
133
|
+
const n = args[0];
|
|
134
|
+
if (v === '_') return /^\w+$/.test(n) ? `Repeats ${n} times` : null;
|
|
135
|
+
const len = /^len\(\s*([A-Za-z_][\w.]*)\s*\)$/.exec(n);
|
|
136
|
+
if (len) return `For each position ${words(v)} in ${possessiveWords(len[1])}`;
|
|
137
|
+
if (num(n)) return Number(n) > 0 ? `Counts ${words(v)} from 0 to ${Number(n) - 1}` : null;
|
|
138
|
+
if (plainPath(n)) return `Counts ${words(v)} from 0 up to ${possessiveWords(n)} (not ${possessiveWords(n)} itself)`;
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
// `range(1, n + 1)`: 1 to n, n included.
|
|
142
|
+
if (args.length === 2 && v !== '_' && /^(?:\d+|[A-Za-z_][\w.]*)$/.test(args[0]) && /^[A-Za-z_][\w.]*\s*\+\s*1$/.test(args[1])) {
|
|
143
|
+
const end = args[1].replace(/\s*\+\s*1$/, '');
|
|
144
|
+
return `Counts ${words(v)} from ${num(args[0]) ? args[0] : possessiveWords(args[0])} to ${possessiveWords(end)}`;
|
|
145
|
+
}
|
|
146
|
+
if (args.length === 2 && v !== '_') {
|
|
147
|
+
const [a, b] = args;
|
|
148
|
+
if (num(a) && num(b)) return Number(b) > Number(a) ? `Counts ${words(v)} from ${a} to ${Number(b) - 1}` : null;
|
|
149
|
+
if ((num(a) || plainPath(a)) && (num(b) || plainPath(b))) {
|
|
150
|
+
const say = (x) => (num(x) ? x : possessiveWords(x));
|
|
151
|
+
return `Counts ${words(v)} from ${say(a)} up to ${say(b)} (not ${say(b)} itself)`;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
|
|
123
157
|
/** entry['easy'] -> "the entry's easy"; $x->y -> "the x's y"; plain names as words. */
|
|
124
158
|
const possessiveWords = (path) => {
|
|
125
159
|
if ((C_FAMILY.has(LANG) || LANG === 'swift') && /\[/.test(String(path)) && !/\[\s*['"]/.test(String(path))) return indexedWords(String(path).replace(/->/g, '.'));
|
|
@@ -249,11 +283,11 @@ function sayCodeConditionInner(cond) {
|
|
|
249
283
|
if ((ty = c.match(/^typeof\s+([\w$.]+)\s*(===?|!==?)\s*["'](\w+)["']$/)) && TYPEOF_WORDS[ty[3]]) return `${possessiveWords(ty[1])} is ${/^!/.test(ty[2]) ? 'not ' : ''}${TYPEOF_WORDS[ty[3]]}`;
|
|
250
284
|
if ((ty = c.match(/^(!|not\s+)?\\?(is_\w+)\(\s*\$?([\w$.\[\]'">-]+)\s*\)$/)) && PHP_IS[ty[2]]) return `${possessiveWords(ty[3])} is ${ty[1] ? 'not ' : ''}${PHP_IS[ty[2]]}`;
|
|
251
285
|
// `x instanceof Foo` / `x is Foo` (Kotlin, C#) / isinstance(x, Foo): "x is a Foo".
|
|
252
|
-
if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.]+)\s+instanceof\s+([\w$.\\]+)\s*\)?$/))) return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}
|
|
253
|
-
if ((ty = c.match(/^([\w$.]+)\s+(is|!is)\s+([A-Z][\w.<>?]*)$/)) && !/^(?:True|False|None|Null|Nil|NULL)$/.test(ty[3])) return `${possessiveWords(ty[1])} is ${ty[2] === '!is' ? 'not ' : ''}
|
|
286
|
+
if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.]+)\s+instanceof\s+([\w$.\\]+)\s*\)?$/))) return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}${aWord(ty[3].split(/[.\\]/).pop())}`;
|
|
287
|
+
if ((ty = c.match(/^([\w$.]+)\s+(is|!is)\s+([A-Z][\w.<>?]*)$/)) && !/^(?:True|False|None|Null|Nil|NULL)$/.test(ty[3])) return `${possessiveWords(ty[1])} is ${ty[2] === '!is' ? 'not ' : ''}${aWord(ty[3].split('.').pop())}`;
|
|
254
288
|
// Ruby `x.is_a?(String)` / `kind_of?` / `instance_of?`: "x is a String".
|
|
255
|
-
if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.@]+)\.(?:is_a|kind_of|instance_of)\?\s*\(?\s*([A-Z][\w:]*)\s*\)?\s*\)?$/))) return `${possessiveWords(ty[2].replace(/^@/, ''))} is ${ty[1] ? 'not ' : ''}
|
|
256
|
-
if ((ty = c.match(/^(not\s+)?isinstance\(\s*([\w.]+)\s*,\s*\(?\s*([\w.]+(?:\s*,\s*[\w.]+)*)\s*\)?\s*\)$/))) { const kinds = ty[3].split(/\s*,\s*/).map((x) => x.split('.').pop()); return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}${kinds.length > 1 ? `one of ${kinds.join(', ')}` :
|
|
289
|
+
if ((ty = c.match(/^(!|not\s+)?\(?\s*([\w$.@]+)\.(?:is_a|kind_of|instance_of)\?\s*\(?\s*([A-Z][\w:]*)\s*\)?\s*\)?$/))) return `${possessiveWords(ty[2].replace(/^@/, ''))} is ${ty[1] ? 'not ' : ''}${aWord(ty[3].split('::').pop())}`;
|
|
290
|
+
if ((ty = c.match(/^(not\s+)?isinstance\(\s*([\w.]+)\s*,\s*\(?\s*([\w.]+(?:\s*,\s*[\w.]+)*)\s*\)?\s*\)$/))) { const kinds = ty[3].split(/\s*,\s*/).map((x) => x.split('.').pop()); return `${possessiveWords(ty[2])} is ${ty[1] ? 'not ' : ''}${kinds.length > 1 ? `one of ${kinds.join(', ')}` : aWord(kinds[0])}`; }
|
|
257
291
|
// A bare yes/no property reads as a sentence: `order.refunded` -> "order is refunded", `!user.isAdmin` -> "user is not admin".
|
|
258
292
|
const prop = c.match(/^(not\s+|!)?(?:self\.|this\.)?([A-Za-z_]\w*)\.([A-Za-z_]\w*)(\(\))?$/);
|
|
259
293
|
const plural = (w, call) => !call && !/ /.test(w) && /[^sui]s$/.test(w) && w.length > 3;
|
|
@@ -281,6 +315,10 @@ function sayCodeConditionInner(cond) {
|
|
|
281
315
|
if (call[2] === 'is_null') return `${what} is ${call[1] ? 'not ' : ''}null`;
|
|
282
316
|
return call[2] === 'isset' ? `${what} is ${call[1] ? 'not ' : ''}set` : `${what} is ${neg ? 'not ' : ''}empty`;
|
|
283
317
|
}
|
|
318
|
+
// C#: String.IsNullOrEmpty(x) -> "x is empty or missing"; IsNullOrWhiteSpace -> "x is blank or missing".
|
|
319
|
+
if ((call = c.match(/^(!|not\s+)?[Ss]tring\.IsNullOr(Empty|WhiteSpace)\(\s*([\w$.]+)\s*\)$/))) {
|
|
320
|
+
return `${possessiveWords(call[3])} is ${call[1] ? 'not ' : ''}${call[2] === 'Empty' ? 'empty' : 'blank'}${call[1] ? ' and is set' : ' or missing'}`;
|
|
321
|
+
}
|
|
284
322
|
// isObject(x) -> "x is object"; !isRequest(options.request) -> "the options's request is not request".
|
|
285
323
|
if ((call = c.match(/^(!|not\s+)?(?:(?:self|this)\.)?is_?([A-Z]\w*)\s*\(\s*([\w$.]+)\s*\)$/)) && !/^(?:Empty|Set|Null)$/.test(call[2])) {
|
|
286
324
|
return `${possessiveWords(call[3])} is ${call[1] ? 'not ' : ''}${words(call[2])}`;
|
|
@@ -327,6 +365,36 @@ function matchingClose(str, open) {
|
|
|
327
365
|
return -1;
|
|
328
366
|
}
|
|
329
367
|
const lastWords = (path) => words(String(path).split('.').pop());
|
|
368
|
+
/** "a" or "an" by the sound of a type's name: an Error, an OrderedDict, an HTTPError; a User, a URL. */
|
|
369
|
+
const aWord = (w) => {
|
|
370
|
+
const t = String(w);
|
|
371
|
+
const an = /^(?:[AEIOaeio]|U(?:n|m|nd|tt|pp)|u(?:n|m)|[FHLMNRSX][A-Z0-9]|[fhlmnrsx](?=[A-Z0-9]))/.test(t) && !/^(?:Eu|eu|Uni|uni|Use|use|Usu|One|one|Ur)/.test(t);
|
|
372
|
+
return `${an ? 'an' : 'a'} ${t}`;
|
|
373
|
+
};
|
|
374
|
+
/**
|
|
375
|
+
* A call's name in words, never ending on a dangling preposition: a function named after what it is for
|
|
376
|
+
* (`changeApprovalFor(x, …)`) gets its first argument when that is a plain name ("change approval for x"), and
|
|
377
|
+
* otherwise loses the preposition ("change approval"), instead of "change approval for ".
|
|
378
|
+
*/
|
|
379
|
+
const ENDS_ON_PREPOSITION = /\s(?:for|from|to|of|with|by|in|on|at|about|into|as|via)$/;
|
|
380
|
+
function callWords(c, text) {
|
|
381
|
+
const w = lastWords(c);
|
|
382
|
+
if (!ENDS_ON_PREPOSITION.test(w)) return w;
|
|
383
|
+
const args = String(text ?? '');
|
|
384
|
+
const open = args.indexOf('(');
|
|
385
|
+
if (open >= 0) {
|
|
386
|
+
let depth = 0, end = open + 1;
|
|
387
|
+
for (; end < args.length; end++) {
|
|
388
|
+
const ch = args[end];
|
|
389
|
+
if ('([{'.includes(ch)) depth++;
|
|
390
|
+
else if (')]}'.includes(ch)) { if (depth === 0) break; depth--; }
|
|
391
|
+
else if (ch === ',' && depth === 0) break;
|
|
392
|
+
}
|
|
393
|
+
const first = args.slice(open + 1, end).trim();
|
|
394
|
+
if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(first)) return `${w} ${words(first.split('.').pop())}`;
|
|
395
|
+
}
|
|
396
|
+
return w.replace(ENDS_ON_PREPOSITION, '');
|
|
397
|
+
}
|
|
330
398
|
/** "cmd.commandCalledAs.called" -> "called on command called as"; "this.count" -> "count". */
|
|
331
399
|
function targetWords(path) {
|
|
332
400
|
// (C, C++, Swift: an index keeps its place, `events[i].mask` is "the mask of events[i]", never just "events".)
|
|
@@ -356,10 +424,71 @@ function sayCall(name, args) {
|
|
|
356
424
|
for (const k of KNOWN_CALLS) if (k.re.test(name)) {
|
|
357
425
|
const target = (args.match(/^\s*["'`]([\w.\-/: ]{1,60})["'`]/) || [])[1];
|
|
358
426
|
const base = k.say(name);
|
|
427
|
+
// A message says what it writes: `console.log("Saved.")`, `print(f"Total: {t}")`, `console.error(report(x))`.
|
|
428
|
+
if (base === 'Writes a log or message' && (LANG === 'typescript' || LANG === 'javascript' || LANG === 'python')) {
|
|
429
|
+
const what = messageWhat(args);
|
|
430
|
+
if (what) return `${base}: ${what}`;
|
|
431
|
+
}
|
|
359
432
|
return target ? `${base}: ${target}` : base;
|
|
360
433
|
}
|
|
361
434
|
return null;
|
|
362
435
|
}
|
|
436
|
+
/** Shortened text ends on a whole word ("… the exact…", never "… the exact cr…"); it stays a prefix of the text. */
|
|
437
|
+
const wholeWords = (q) => (q && q.endsWith('…') && q.length > 24 ? `${q.slice(0, -1).replace(/\s+\S*$/, '').replace(/[\s,;:.-]+$/, '')}…` : q);
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* JavaScript/TypeScript template text with each value as a «placeholder» (the spec's form, as for Swift and C):
|
|
441
|
+
* `Wrote ${opts.out}.` -> `Wrote «opts.out».`. Null when it is not one whole template. Long text ends in "…".
|
|
442
|
+
*/
|
|
443
|
+
function templateWithValues(lit, n = 70) {
|
|
444
|
+
const t = String(lit).trim();
|
|
445
|
+
if (!t.startsWith('`')) return null;
|
|
446
|
+
let out = '';
|
|
447
|
+
for (let i = 1; i < t.length; i++) {
|
|
448
|
+
const c = t[i];
|
|
449
|
+
if (c === '\\') { out += t[i + 1] === '`' ? '`' : t[i + 1] === '$' ? '$' : c + (t[i + 1] ?? ''); i++; continue; }
|
|
450
|
+
if (c === '`') return i === t.length - 1 ? (out.length > n ? wholeWords(`${out.slice(0, n - 1).trimEnd()}…`) : out) : null;
|
|
451
|
+
if (c === '$' && t[i + 1] === '{') {
|
|
452
|
+
let d = 0, j = i + 1;
|
|
453
|
+
for (; j < t.length; j++) { if (t[j] === '{') d++; else if (t[j] === '}' && --d === 0) break; }
|
|
454
|
+
// (A value worked out inside the hole, `${a ? `x` : ''}`, is shown as «…»: only a name or a field is spelled.)
|
|
455
|
+
const hole = t.slice(i + 2, j).trim();
|
|
456
|
+
out += /^[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)*$/.test(hole) ? `«${hole}»` : '«…»'; i = j; continue;
|
|
457
|
+
}
|
|
458
|
+
out += c;
|
|
459
|
+
}
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** What a message call writes, from its first argument: its text, a named value, or the result of a call. */
|
|
464
|
+
function messageWhat(args) {
|
|
465
|
+
const t = String(args ?? '');
|
|
466
|
+
let depth = 0, end = 0, q = null;
|
|
467
|
+
for (; end < t.length; end++) {
|
|
468
|
+
const c = t[end];
|
|
469
|
+
if (q) { if (c === '\\') { end++; continue; } if (c === q) q = null; continue; }
|
|
470
|
+
if (c === '"' || c === "'" || c === '`') { q = c; continue; }
|
|
471
|
+
if ('([{'.includes(c)) depth++;
|
|
472
|
+
else if (')]}'.includes(c)) { if (depth === 0) break; depth--; }
|
|
473
|
+
else if (c === ',' && depth === 0) break;
|
|
474
|
+
}
|
|
475
|
+
let a = t.slice(0, end).trim();
|
|
476
|
+
if (!a) return null;
|
|
477
|
+
const more = t[end] === ',';
|
|
478
|
+
if (LANG === 'python') a = a.replace(/^[fFrR]{1,2}(?=["'])/, '');
|
|
479
|
+
if (/^["'`]/.test(a)) {
|
|
480
|
+
// (Python f-string holes stay as written, `{name}`; a JavaScript template's values become «placeholders».)
|
|
481
|
+
let text = a.startsWith('`') ? templateWithValues(a, 80) : wholeWords(firstText(a, 80));
|
|
482
|
+
// printf-style holes filled by the values after it (`"Starting job %s", job_id`) are shown as "…".
|
|
483
|
+
if (text && more) text = text.replace(/%[-+ #0-9.]*[sdifrxXeEgGcuo]|\{\}/g, '…');
|
|
484
|
+
return text && /\w/.test(text) ? `"${text}"${more && !/…/.test(text) ? ', and more' : ''}` : null;
|
|
485
|
+
}
|
|
486
|
+
const tail = more ? ', and more' : '';
|
|
487
|
+
if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(a)) return `${possessiveWords(a)}${tail}`;
|
|
488
|
+
const c = callee(a);
|
|
489
|
+
if (c && closeOf(a, a.indexOf('(')) === a.length - 1) return `the result of ${callWords(c, a)}${tail}`;
|
|
490
|
+
return null;
|
|
491
|
+
}
|
|
363
492
|
function firstArgs(text) {
|
|
364
493
|
const open = text.indexOf('(');
|
|
365
494
|
return open >= 0 ? text.slice(open + 1, open + 120) : '';
|
|
@@ -405,7 +534,7 @@ function sayValue(expr) {
|
|
|
405
534
|
if (/^new\s/.test(e)) return `a new ${c.split('.').pop()}`;
|
|
406
535
|
// Swift makes a value by calling its type: Loan(title: t) is a new Loan (so does C++: std::string(s)).
|
|
407
536
|
if ((LANG === 'swift' || LANG === 'cpp') && /^[A-Z]\w*$/.test(c) && !/^[A-Z][A-Z0-9_]+$/.test(c) && !C_STYLE_FUNCTION.test(c)) return `a new ${c}`;
|
|
408
|
-
return `the result of ${
|
|
537
|
+
return `the result of ${callWords(c, e)}`;
|
|
409
538
|
}
|
|
410
539
|
if (LANG === 'swift' && /^[A-Za-z_][\w.]*\.count$/.test(e)) return `how many ${possessiveWords(e.replace(/\.count$/, ''))}`;
|
|
411
540
|
// A path keeps its owner: `callback.call` is "the callback's call", not "call"; `Boolean.TYPE` stays as written.
|
|
@@ -495,7 +624,36 @@ function sayCommon(value) {
|
|
|
495
624
|
if ((m = e.match(/^new\s*\(\s*(?:[\w]+\.)?([A-Z]\w*)\s*\)$/))) return `a new ${m[1]}`;
|
|
496
625
|
if ((m = e.match(/^&([A-Z]\w*)$/))) return `a new ${m[1]}`;
|
|
497
626
|
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])}`;
|
|
498
|
-
|
|
627
|
+
// (A key that is another value's field keeps its owner: `touched.get(f.id)` is "the entry for f's id in touched".)
|
|
628
|
+
if ((m = e.match(/^([\w.]+)\.get\(\s*([A-Za-z_][\w.]*)\s*[,)]/)) || (m = e.match(/^([\w.]+)\[\s*([A-Za-z_][\w.]*)\s*\]$/))) return /\./.test(m[2]) && !/^(?:self|this)\./.test(m[2]) ? `the entry for ${possessiveWords(m[2])} in ${possessiveWords(m[1])}` : `the ${lastSeg(m[2])} entry in ${possessiveWords(m[1])}`;
|
|
629
|
+
// Everyday Python calls, said by what they give back (only when what they are given is a name).
|
|
630
|
+
if (LANG === 'python') {
|
|
631
|
+
const plain = (x) => (/^[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*$/.test(String(x).trim()) ? possessiveWords(String(x).trim()) : null);
|
|
632
|
+
let mm;
|
|
633
|
+
// A class called like a function makes a new object: `FontDict()` is a new FontDict.
|
|
634
|
+
if ((mm = e.match(/^([A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*)\(\s*\)$/))) return `a new ${mm[1]}`;
|
|
635
|
+
if ((mm = e.match(/^(list|tuple|set|frozenset|sorted|reversed)\(\s*([^(),]+?)\s*\)$/)) && plain(mm[2])) return { list: `${plain(mm[2])}, as a list`, tuple: `${plain(mm[2])}, as a tuple`, set: `the different values in ${plain(mm[2])}`, frozenset: `the different values in ${plain(mm[2])}`, sorted: `${plain(mm[2])}, sorted`, reversed: `${plain(mm[2])}, in reverse order` }[mm[1]];
|
|
636
|
+
if ((mm = e.match(/^([\w.]+)\.index\(\s*([^(),]+?)\s*\)$/)) && plain(mm[1]) && plain(mm[2])) return `the position of ${plain(mm[2])} in ${plain(mm[1])}`;
|
|
637
|
+
}
|
|
638
|
+
// Everyday JavaScript and TypeScript calls, said by what they give back (only when what they are given is a name).
|
|
639
|
+
if (LANG === 'typescript' || LANG === 'javascript') {
|
|
640
|
+
const plain = (x) => (/^[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)*$/.test(String(x).trim()) ? possessiveWords(String(x).trim().replace(/\?\./g, '.')) : null);
|
|
641
|
+
const one = (re) => { const mm = e.match(re); return mm ? plain(mm[1]) : null; };
|
|
642
|
+
let w;
|
|
643
|
+
if ((w = one(/^Object\.keys\(\s*([^(),]+?)\s*\)$/))) return `the keys of ${w}`;
|
|
644
|
+
if ((w = one(/^Object\.values\(\s*([^(),]+?)\s*\)$/))) return `the values in ${w}`;
|
|
645
|
+
if ((w = one(/^Object\.entries\(\s*([^(),]+?)\s*\)$/))) return `each key and value in ${w}`;
|
|
646
|
+
if ((w = one(/^Date\.parse\(\s*([^(),]+?)\s*\)$/))) return `the time written in ${w}`;
|
|
647
|
+
if ((w = one(/^Array\.from\(\s*([^(),]+?)\s*\)$/))) return `a list made from ${w}`;
|
|
648
|
+
if ((m = e.match(/^([A-Z][\w$]*)\.from\(\s*([^(),]+?)\s*\)$/)) && plain(m[2])) return `a ${m[1]} made from ${plain(m[2])}`;
|
|
649
|
+
if ((m = e.match(/^([\w$.]+)\.exec\(\s*([^(),]+?)\s*\)$/)) && plain(m[1]) && plain(m[2])) return `the first match of ${plain(m[1])} in ${plain(m[2])}`;
|
|
650
|
+
if ((m = e.match(/^([A-Z][\w$]*)\.parse\(\s*([^(),]+?)\s*\)$/)) && plain(m[2]) && m[1] !== 'JSON' && m[1] !== 'Date') return `${plain(m[2])}, checked and read by ${m[1]}`;
|
|
651
|
+
if ((m = e.match(/^Math\.(max|min)\(\s*([^()]+?)\s*\)$/))) {
|
|
652
|
+
const xs = splitTopArgs(m[2]).map(plain);
|
|
653
|
+
if (xs.length >= 2 && xs.every(Boolean)) return `the ${m[1] === 'max' ? 'largest' : 'smallest'} of ${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`;
|
|
654
|
+
}
|
|
655
|
+
if ((m = e.match(/^Math\.(round|floor|ceil|abs|trunc)\(\s*([^(),]+?)\s*\)$/)) && plain(m[2])) return { round: `${plain(m[2])} rounded`, floor: `${plain(m[2])} rounded down`, ceil: `${plain(m[2])} rounded up`, abs: `the absolute value of ${plain(m[2])}`, trunc: `${plain(m[2])} without its fraction` }[m[1]];
|
|
656
|
+
}
|
|
499
657
|
const wholeCall = (() => { const c = e.match(/^(?:new\s+)?[\w$.]+(?:<[^()]*?>)?\s*\(/); return !!c && closeOf(e, c[0].length - 1) === e.length - 1; })();
|
|
500
658
|
if (/["'`]\s*\+|\+\s*["'`]/.test(e) && !/[<>=!&|]/.test(e) && !wholeCall) return 'text built from its parts';
|
|
501
659
|
// PHP joins text with ` . ` (spaced when PHP is read): `$a . ':' . $b`.
|
|
@@ -503,8 +661,18 @@ function sayCommon(value) {
|
|
|
503
661
|
if ((m = e.match(/^[A-Za-z_][\w.]*(\s*,\s*[A-Za-z_][\w.]*)+$/))) return e.split(/\s*,\s*/).map(lastSeg).join(' and ');
|
|
504
662
|
// (`make([]string, len(m))` has len(m) items, each the empty value; only `make([]T, 0…)` is empty.)
|
|
505
663
|
if ((m = e.match(/^make\(\s*(\[\]|map\[)/))) { const a = splitTopArgs(e.slice(e.indexOf('(') + 1, -1)); if (m[1] === '[]' && a.length > 1 && !/^0$/.test(a[1].trim())) return null; return m[1] === '[]' ? 'an empty list' : 'an empty lookup table'; }
|
|
664
|
+
// A JavaScript template or a Python f-string whose values are plain names: the text kept exactly, each value a
|
|
665
|
+
// «placeholder» (as for Swift); anything worked out inside a placeholder stays a summary.
|
|
666
|
+
if (/^`/.test(e) || /^f["']/.test(e)) { const tv = templateTextWithValues(e); if (tv) return tv.length > 90 ? `${tv.slice(0, 88)}…"` : tv; }
|
|
667
|
+
// (A value worked out inside a JavaScript template is shown as «…», as in messages: the text around it is exact.)
|
|
668
|
+
if (/^`/.test(e) && /\$\{/.test(e)) { const q = templateWithValues(e, 80); if (q != null && !/"/.test(q)) return `"${q}"`; }
|
|
506
669
|
if (/^(?:f|rf|fr)["']/.test(e) || /^`[^`]*\$\{/.test(e) || /^\$"/.test(e) || /^(?:fmt\.Sprintf|String\.format|format!)\(/.test(e)) return 'text built from its parts';
|
|
507
|
-
|
|
670
|
+
// (`d.get("k", fallback)`: the fallback is said too, never dropped.)
|
|
671
|
+
if ((m = e.match(/^([\w.]+)\.get\(\s*["'`]([\w.\-: ]{1,40})["'`]\s*\)$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
|
|
672
|
+
if (LANG === 'python' && (m = e.match(/^([\w.]+)\.get\(\s*["'`]([\w.\-: ]{1,40})["'`]\s*,\s*(.+?)\s*\)$/)) && balancedText(m[3])) {
|
|
673
|
+
const d = /^[A-Za-z_][\w.]*$/.test(m[3]) && !/^(?:None|True|False)$/.test(m[3]) ? possessiveWords(m[3]) : sayValue(m[3]);
|
|
674
|
+
if (d && d.length < 40) return `the "${m[2]}" value from ${lastSeg(m[1])}, or ${d} if it has none`;
|
|
675
|
+
}
|
|
508
676
|
if ((m = e.match(/^([\w.]+)\[\s*["'`]([\w.\-: ]{1,40})["'`]\s*\]$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
|
|
509
677
|
if (FN_CONTEXT?.language === 'ruby' && (m = e.match(/^@?([\w.]+)\[\s*:(\w+)\s*\]$/))) return `the "${m[2]}" value from ${lastSeg(m[1])}`;
|
|
510
678
|
if ((m = e.match(/^([\w.]+)\.split\(\s*["'`]([^"'`]{0,10})["'`]/))) return `${lastSeg(m[1])} split at "${m[2]}"`;
|
|
@@ -517,6 +685,19 @@ function sayCommon(value) {
|
|
|
517
685
|
if (/^(?:dict|Map|HashMap|map)\(\s*\)$|^\{\s*\}$|^new (?:Map|HashMap|Dictionary)(?:<[^()]*>)?\s*(?:\(\s*\))?\s*(?:\{\s*\})?$/.test(e)) return 'an empty lookup table';
|
|
518
686
|
if (/^(?:list|Array|ArrayList|vec!?)\(?\s*\)?$|^\[\s*\]$|^new (?:ArrayList|List)(?:<[^()]*>)?\s*(?:\(\s*\))?\s*(?:\{\s*\})?$/.test(e)) return 'an empty list';
|
|
519
687
|
if ((m = e.match(/^len\(\s*([\w.]+)\s*\)$/)) || (m = e.match(/^([\w.]+)\.(?:length|size\(\)|Count|count\(\)|len\(\))$/))) return `how many ${lastSeg(m[1])}`;
|
|
688
|
+
// Python `set()` / JavaScript `new Set()`: an empty set (of different values).
|
|
689
|
+
if (/^(?:set|frozenset)\(\s*\)$|^new Set(?:<[^()]*>)?\(\s*\)$/.test(e)) return 'an empty set';
|
|
690
|
+
// A list written out of plain names, numbers, and short texts: `[a, b]` "a list of a and b".
|
|
691
|
+
if ((m = e.match(/^\[\s*(.+?)\s*,?\s*\]$/)) && !/\bfor\b/.test(m[1])) {
|
|
692
|
+
const items = splitTopArgs(m[1]).map((x) => x.trim());
|
|
693
|
+
const said = items.map((x) => (/^[A-Za-z_][\w.]*$/.test(x) && !/^(?:None|null|undefined|True|False|true|false|self|this)$/.test(x) ? possessiveWords(x) : /^-?\d+(?:\.\d+)?$/.test(x) ? x : /^(["'])[\w .:/-]{0,24}\1$/.test(x) ? `"${x.slice(1, -1)}"` : null));
|
|
694
|
+
if (items.length && items.length <= 4 && said.every(Boolean)) return items.length === 1 ? `a list with only ${said[0]}` : `a list of ${listWords(said)}`;
|
|
695
|
+
}
|
|
696
|
+
// Python slices and the last item: `xs[1:]` "xs without the first 1", `xs[:3]` "the first 3 of xs", `xs[-1]`.
|
|
697
|
+
if (LANG === 'python' && (m = e.match(/^([A-Za-z_][\w.]*)\[\s*(-?\d+)?\s*(:)?\s*(-?\d+)?\s*\]$/)) && (m[3] || m[2] === '-1')) {
|
|
698
|
+
const t = sliceWords(m[3] ? m[2] : undefined, m[3] ? m[4] : undefined, m[3] ? null : m[2]);
|
|
699
|
+
if (t) return t.replace('{x}', possessiveWords(m[1]));
|
|
700
|
+
}
|
|
520
701
|
return null;
|
|
521
702
|
}
|
|
522
703
|
/** `if (a) b else c` / `if a { b } else { c }` / `if a then b else c end` as { cond, yes, no }; null otherwise. */
|
|
@@ -993,7 +1174,8 @@ function responseOf(head) {
|
|
|
993
1174
|
// Gin / Echo: c.JSON(http.StatusOK, user), c.String(200, "ok")
|
|
994
1175
|
if ((m = expr.match(/^c\s*\.\s*(JSON|IndentedJSON|String|XML|YAML)\s*\((.*)\)$/))) { const [st, body] = callArgs(m[2]); const status = statusOf(st); if (status && status >= 300) return null; return sentStep(payloadWords(body), status === 200 ? null : status); }
|
|
995
1176
|
// ASP.NET: Ok(x), Created(uri, x), CreatedAtAction(name, routeValues, x), Accepted(x), NoContent()
|
|
996
|
-
|
|
1177
|
+
// (Rust's `Ok(x)` is a result that worked, not an HTTP answer.)
|
|
1178
|
+
if (/^return\b/.test(head) && LANG !== 'rust' && (m = expr.match(/^(Ok|Accepted|Created|CreatedAtAction|CreatedAtRoute|NoContent|Json)\s*\((.*)\)$/))) {
|
|
997
1179
|
const args = callArgs(m[2]);
|
|
998
1180
|
const status = { Ok: null, Json: null, Accepted: 202, Created: 201, CreatedAtAction: 201, CreatedAtRoute: 201, NoContent: 204 }[m[1]];
|
|
999
1181
|
return sentStep(payloadWords(args.at(-1)), status);
|
|
@@ -1056,6 +1238,39 @@ function quotedBody(lit) {
|
|
|
1056
1238
|
return t.slice(1, -1);
|
|
1057
1239
|
}
|
|
1058
1240
|
/** Swift: `"Bearer \(token)"` -> `"Bearer «token»"`. Null when the literal is not one plain "…" text. */
|
|
1241
|
+
const PLAIN_PLACEHOLDER = /^[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*|\[\d+\])*(?:\(\))?$/;
|
|
1242
|
+
/** `` `@scope/x@${version}` `` -> `"@scope/x@«version»"`; f"{n:>3} items" -> `"«n as {:>3}» items"`; null when a value
|
|
1243
|
+
* inside is worked out (an operator, a call with arguments) or the literal is not one whole piece of text. */
|
|
1244
|
+
export function templateTextWithValues(lit) {
|
|
1245
|
+
const t = String(lit).trim();
|
|
1246
|
+
const js = t[0] === '`';
|
|
1247
|
+
if (!js && !/^f(["'])/.test(t)) return null;
|
|
1248
|
+
const q = js ? '`' : t[1];
|
|
1249
|
+
if (!js && t.slice(1, 4) === q.repeat(3)) return null;
|
|
1250
|
+
let out = '', i = js ? 1 : 2, any = false;
|
|
1251
|
+
for (; i < t.length; i++) {
|
|
1252
|
+
const c = t[i];
|
|
1253
|
+
if (c === q) break;
|
|
1254
|
+
if (c === '\\') { out += c + (t[i + 1] ?? ''); i++; continue; }
|
|
1255
|
+
if (js ? c === '$' && t[i + 1] === '{' : c === '{') {
|
|
1256
|
+
if (!js && t[i + 1] === '{') { out += '{'; i++; continue; }
|
|
1257
|
+
const open = js ? i + 1 : i;
|
|
1258
|
+
const close = t.indexOf('}', open);
|
|
1259
|
+
if (close < 0) return null;
|
|
1260
|
+
let inner = t.slice(open + 1, close).trim(), spec = '';
|
|
1261
|
+
if (!js) { const m = /^([^:!]+?)\s*((?:![rsa])?(?::[^{}]*)?)$/.exec(inner); if (!m) return null; inner = m[1].trim(); spec = m[2]; }
|
|
1262
|
+
if (!PLAIN_PLACEHOLDER.test(inner)) return null;
|
|
1263
|
+
out += spec ? `«${inner} as {${spec}}»` : `«${inner}»`;
|
|
1264
|
+
any = true;
|
|
1265
|
+
i = close;
|
|
1266
|
+
continue;
|
|
1267
|
+
}
|
|
1268
|
+
if (!js && c === '}' && t[i + 1] === '}') { out += '}'; i++; continue; }
|
|
1269
|
+
if (c === '"') { out += '\\"'; continue; }
|
|
1270
|
+
out += c;
|
|
1271
|
+
}
|
|
1272
|
+
return any && i === t.length - 1 ? `"${out}"` : null;
|
|
1273
|
+
}
|
|
1059
1274
|
export function swiftTextWithValues(lit) {
|
|
1060
1275
|
const t = String(lit).trim();
|
|
1061
1276
|
if (!/^"/.test(t) || /^"""/.test(t)) return null;
|
|
@@ -1215,13 +1430,104 @@ const stripQuotedText = (s) => String(s).replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g
|
|
|
1215
1430
|
// Words that start a block or a statement: "Calls unsafe" / "Calls using" / "Calls foreach" would name a function
|
|
1216
1431
|
// that does not exist, so such a step is shown as its code instead.
|
|
1217
1432
|
const NOT_CALLED = /^Calls (unsafe|using|foreach|for|while|if|else|return|lock|fixed|checked|unchecked|try|do|switch|match|loop|static|const|let|var|val|mut|typeof|sizeof)$/;
|
|
1433
|
+
/**
|
|
1434
|
+
* TypeScript's types say nothing about what a statement does, so they are set aside before it is read (the step
|
|
1435
|
+
* still shows the original code): `(request.body ?? {}) as { a?: string }` is `request.body ?? {}`, `ctx.repo!` is
|
|
1436
|
+
* `ctx.repo`, and `const reviews: Record<string, 'a' | 'b'> = {}` is `const reviews = {}`.
|
|
1437
|
+
*/
|
|
1438
|
+
export function stripTsTypes(text) {
|
|
1439
|
+
let s = String(text);
|
|
1440
|
+
// A type after "as" or a declaration's ":" runs to the first , ; ) ] } = at depth 0 (or the end).
|
|
1441
|
+
const typeEnd = (from, stops) => {
|
|
1442
|
+
let depth = 0, q = null;
|
|
1443
|
+
for (let i = from; i < s.length; i++) {
|
|
1444
|
+
const c = s[i];
|
|
1445
|
+
if (q) { if (c === q && s[i - 1] !== '\\') q = null; continue; }
|
|
1446
|
+
if (c === "'" || c === '"' || c === '`') { q = c; continue; }
|
|
1447
|
+
if (c === '<' || c === '{' || c === '(' || c === '[') depth++;
|
|
1448
|
+
else if ((c === '>' && s[i - 1] !== '=') || c === '}' || c === ')' || c === ']') { if (depth === 0) return i; depth--; }
|
|
1449
|
+
else if (depth === 0 && stops.includes(c)) return i;
|
|
1450
|
+
}
|
|
1451
|
+
return s.length;
|
|
1452
|
+
};
|
|
1453
|
+
// `x as Type` (not inside text).
|
|
1454
|
+
for (let guard = 0; guard < 20; guard++) {
|
|
1455
|
+
const re = /\s+as\s+(?=[A-Za-z_${(\['"])/g;
|
|
1456
|
+
let m;
|
|
1457
|
+
// (Not inside text: an even number of each quote mark before it.)
|
|
1458
|
+
while ((m = re.exec(s)) && ['"', "'", '`'].some((q) => (s.slice(0, m.index).split(q).length - 1) % 2 === 1));
|
|
1459
|
+
if (!m || /\bimport\b|\bexport\b/.test(s.slice(0, m.index))) break;
|
|
1460
|
+
const end = typeEnd(m.index + m[0].length, ',;=');
|
|
1461
|
+
s = s.slice(0, m.index) + s.slice(end);
|
|
1462
|
+
}
|
|
1463
|
+
// `const name: Type = value` -> `const name = value`.
|
|
1464
|
+
const decl = /^(\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_$][\w$]*)\s*:\s*/.exec(s);
|
|
1465
|
+
if (decl) { const end = typeEnd(decl[0].length, '=;'); if (s[end] === '=') s = `${decl[1]} ${s.slice(end)}`; }
|
|
1466
|
+
// A non-null assertion `x!` (never `!=` or `!x`), and parentheses left around a plain name or member.
|
|
1467
|
+
s = s.replace(/([\w$\])])!(?![=\w(])/g, '$1').replace(/\(([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\)(?=\.)/g, '$1');
|
|
1468
|
+
// Parentheses that only held the value for its type (`= (request.body ?? {});`) are not needed once it is gone.
|
|
1469
|
+
const wrapped = /^(\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*|\s*return\s+)\(([\s\S]*)\)(\s*;?\s*)$/.exec(s);
|
|
1470
|
+
if (wrapped) {
|
|
1471
|
+
let depth = 0, whole = true;
|
|
1472
|
+
for (let i = 0; i < wrapped[2].length; i++) { const c = wrapped[2][i]; if (c === '(') depth++; else if (c === ')') { if (depth === 0) { whole = false; break; } depth--; } }
|
|
1473
|
+
if (whole && depth === 0) s = `${wrapped[1]}${wrapped[2]}${wrapped[3]}`;
|
|
1474
|
+
}
|
|
1475
|
+
return s;
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1218
1478
|
export function classifyStatement(raw, opts) {
|
|
1479
|
+
// An event handler whose body is one expression: `child.on('close', (c) => resolve(c))` -> Whenever "close" happens,
|
|
1480
|
+
// it calls resolve. (A handler with a block body is read with its steps, elsewhere.)
|
|
1481
|
+
if (LANG === 'typescript' || LANG === 'javascript') {
|
|
1482
|
+
const ev = /^\s*[\w$.]+\.(?:on|once|addEventListener|addListener)\(\s*(['"`])([\w:.\-]+)\1\s*,\s*(?:async\s*)?(?:\([^()]*\)|[\w$]+)\s*=>\s*(?!\{)([\s\S]+?)\)\s*;?\s*$/.exec(String(raw));
|
|
1483
|
+
if (ev && balancedText(ev[3])) {
|
|
1484
|
+
const body = ev[3].trim();
|
|
1485
|
+
const c = callee(body);
|
|
1486
|
+
if (c && closeOf(body, body.indexOf('(')) === body.length - 1) return { kind: 'call', says: `Whenever "${ev[2]}" happens, it calls ${callWords(c, body)}`, code: clip(String(raw).replace(/\s+/g, ' ').trim(), 90), callee: c, expr: statementExpr(raw) };
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
// Two loops on one line (`for (const r of rows) for (const f of r.files) {`): each, in order, never one mixed loop.
|
|
1490
|
+
if (LANG === 'typescript' || LANG === 'javascript') {
|
|
1491
|
+
const t = String(raw).trim();
|
|
1492
|
+
const m = /^for\s*\(/.exec(t);
|
|
1493
|
+
if (m) {
|
|
1494
|
+
let depth = 0, close = -1;
|
|
1495
|
+
for (let i = t.indexOf('('); i < t.length; i++) { if (t[i] === '(') depth++; else if (t[i] === ')' && --depth === 0) { close = i; break; } }
|
|
1496
|
+
const rest = close > 0 ? t.slice(close + 1).trim() : '';
|
|
1497
|
+
if (/^for\s*\(/.test(rest)) {
|
|
1498
|
+
const outer = classifyStatement(`${t.slice(0, close + 1)} {`, opts);
|
|
1499
|
+
const inner = classifyStatement(rest.replace(/\{?\s*$/, ' {'), opts);
|
|
1500
|
+
if (outer.kind === 'loop' && inner.kind === 'loop') {
|
|
1501
|
+
return { ...outer, says: `${outer.says.replace(/:$/, '')}, and in each, ${inner.says.charAt(0).toLowerCase()}${inner.says.slice(1)}`, code: clip(t.replace(/\s+/g, ' '), 90), nestedLoop: true };
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
// TypeScript: read the statement without its types; show the code as written.
|
|
1507
|
+
if (LANG === 'typescript' && /\sas\s|[\w$\])]!(?![=\w(])|^\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*:/.test(String(raw))) {
|
|
1508
|
+
const plain = stripTsTypes(raw);
|
|
1509
|
+
if (plain !== String(raw)) {
|
|
1510
|
+
const r = classifyStatement(plain, opts);
|
|
1511
|
+
if (r.kind !== 'other') return { ...r, code: clip(String(raw).replace(/\s+/g, ' ').trim(), 90) };
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1219
1514
|
// Rust `unsafe { f(x) }` (and `return unsafe { … }`) with one expression inside is that expression.
|
|
1220
1515
|
const un = LANG === 'rust' ? String(raw).trim().match(/^(return\s+)?unsafe\s*\{\s*([^{};]+?)\s*;?\s*\}\s*;?$/s) : null;
|
|
1221
1516
|
if (un) { const r = classifyStatement(`${un[1] ?? ''}${un[2]}`, opts); return { ...r, code: clip(String(raw).replace(/\s+/g, ' ').trim(), 90) }; }
|
|
1222
1517
|
let r = classifyWords(raw, opts);
|
|
1223
1518
|
const nc = r.kind === 'call' && String(r.says || '').match(NOT_CALLED);
|
|
1224
1519
|
if (nc && new RegExp(`^(?:#\\w+\\s+)?${nc[1]}\\b(?![.(?!])`).test(String(raw).trim().replace(/^#.*\n\s*/, ''))) r = { kind: 'other', says: clip(String(raw).trim(), 70), code: clip(String(raw).replace(/\s+/g, ' ').trim(), 90) };
|
|
1520
|
+
// Rust `let y = f(x)?;`: what `f(x)` would be, and the `?` said: it stops here (passing on the error) if that fails.
|
|
1521
|
+
let rq;
|
|
1522
|
+
if (LANG === 'rust' && r.kind === 'set' && /^Works out [\w ]+$/.test(String(r.says)) && (rq = /^(\s*let\s+(?:mut\s+)?\w+\s*(?::[^=]+)?=\s*)(.+?)\?\s*;?\s*$/.exec(String(raw))) && !/\?/.test(rq[2])) {
|
|
1523
|
+
const inner = classifyWords(`${rq[1]}${rq[2]};`, opts);
|
|
1524
|
+
if (inner.kind === 'set' && /^(?:Works out [\w ]+ from |Sets )/.test(String(inner.says)) && !/, /.test(String(inner.says))) r = { ...r, says: `${inner.says}, and stops here if that fails`, callee: inner.callee };
|
|
1525
|
+
}
|
|
1526
|
+
// `file = self.file` / `const name = this.name`: "Sets file to self.file" (the owner kept, so the two are told apart).
|
|
1527
|
+
let so;
|
|
1528
|
+
if (r.kind === 'set' && (so = /^Sets (.+) to (.+)$/.exec(String(r.says))) && so[1] === so[2] && (so = /^\s*(?:(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*=\s*(self|this)\.([A-Za-z_$][\w$]*)\s*;?\s*$/.exec(String(raw))) && so[1] === so[3]) {
|
|
1529
|
+
r = { ...r, says: `Sets ${words(so[1])} to ${so[2]}.${so[3]}` };
|
|
1530
|
+
}
|
|
1225
1531
|
if (!r.expr) r.expr = statementExpr(raw);
|
|
1226
1532
|
return r;
|
|
1227
1533
|
}
|
|
@@ -1236,6 +1542,12 @@ export function statementExpr(raw) {
|
|
|
1236
1542
|
}
|
|
1237
1543
|
const codeExpr = (text) => ({ kind: 'code', text: String(text ?? '').replace(/\s+/g, ' ').trim() });
|
|
1238
1544
|
|
|
1545
|
+
/**
|
|
1546
|
+
* A first line that opens an object as a call's argument, `fetch(url, {` / `post({`: the statement goes on to the
|
|
1547
|
+
* line that closes the call, so it is read whole. (A callback, `items.forEach((x) => {`, is a block: not this.)
|
|
1548
|
+
*/
|
|
1549
|
+
const callWithObject = (first) => /[(,]\s*\{\s*$/.test(first) && !/=>\s*\{\s*$/.test(first) && !bracketsClosed(first.replace(/\{\s*$/, ''));
|
|
1550
|
+
|
|
1239
1551
|
function classifyWords(raw, { inner = 0 } = {}) {
|
|
1240
1552
|
const text = String(raw).trim();
|
|
1241
1553
|
// A condition written over several lines (`if (\n a &&\n b\n) {`) is read whole.
|
|
@@ -1257,11 +1569,13 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1257
1569
|
const rest = c > 0 ? text.slice(c + 1).trim() : '';
|
|
1258
1570
|
if (rest && !rest.startsWith('{') && !text.slice(c + 1).split('\n')[0].trim()) first = `${text.slice(0, c + 1).replace(/\s+/g, ' ').replace(/\(\s+/g, '(').replace(/\s+\)/g, ')')} ${rest.replace(/\s+/g, ' ')}`.trim();
|
|
1259
1571
|
}
|
|
1572
|
+
// C#: `return Task.FromResult(x);` gives back x (as a finished task): read as `return x;`.
|
|
1573
|
+
if (LANG === 'csharp') first = first.replace(/^return\s+(?:Task|ValueTask)\.FromResult\((.*)\)\s*;?$/, 'return $1;');
|
|
1260
1574
|
// `return (` with JSX on the next line: what is drawn on screen.
|
|
1261
1575
|
if (/^return\s*\(\s*$/.test(first) && /^\s*</.test(text.split('\n')[1] || '')) first = `return (${text.split('\n')[1].trim()}`;
|
|
1262
1576
|
// A statement written over several lines (`return a\n && b`, `x =\n cond ? y : z`, `return (\n <div>…`) is read
|
|
1263
1577
|
// whole, so a value is never cut to its first line.
|
|
1264
|
-
else if (text.includes('\n') && !/^(?:if|else|elif|elsif|for|foreach|while|until|switch|try|catch|finally|do|match|loop|when|case|default|unless|with|def|fn|fun|func|function|class|struct|interface|enum|impl|object|begin|select|using|lock)\b/.test(first) && (!/[{:]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^(?:const|let|var|val)\s*[{[]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first)) && !/=>\s*\{?\s*$/.test(first) && text.length < 2000 && balancedText(text) && (!/\{\s*$/.test(text.split('\n')[0]) || /^(?:const|let|var|val)\s*[{[]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first))) {
|
|
1578
|
+
else if (text.includes('\n') && !/^(?:if|else|elif|elsif|for|foreach|while|until|switch|try|catch|finally|do|match|loop|when|case|default|unless|with|def|fn|fun|func|function|class|struct|interface|enum|impl|object|begin|select|using|lock)\b/.test(first) && (!/[{:]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^(?:const|let|var|val)\s*[{[]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first) || callWithObject(first)) && !/=>\s*\{?\s*$/.test(first) && text.length < 2000 && balancedText(text) && (!/\{\s*$/.test(text.split('\n')[0]) || /^(?:const|let|var|val)\s*[{[]\s*$/.test(first) || /^(?:return|throw|yield)\s*[{[(]\s*$|^[^=(]*[^=!<>]=\s*[{[]\s*$/.test(first) || callWithObject(first))) {
|
|
1265
1579
|
const lines = text.split('\n');
|
|
1266
1580
|
const joined = lines.map((l) => l.trim()).join(' ');
|
|
1267
1581
|
if (!bracketsClosed(first) || /(?:[-+*/%&|^=<>?:.,(\[]|\b(?:and|or|not|in))\s*$/.test(first) || /^\s*(?:[-+*/%&|^=<>?:.)\]]|&&|\|\||\b(?:and|or)\b)/.test(lines[1] || '')) first = joined;
|
|
@@ -1384,6 +1698,8 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1384
1698
|
return { kind: 'fail', says: `Fails${said ? ` with ${said}` : ''}${msg ? `: "${msg}"` : ''}`, code, ...(name ? { error: name } : {}), ...(msg ? { message: msg } : {}) };
|
|
1385
1699
|
}
|
|
1386
1700
|
// An HTTP error response (4xx/5xx) is a Stop: the request is refused, with a status and a message.
|
|
1701
|
+
// A Python import inside a function: "Loads the json module", "Loads a and b from the x.y module".
|
|
1702
|
+
if (LANG === 'python' && /^(?:from|import)\s/.test(head)) { const said = pythonImportSays(head); if (said) return { kind: 'set', says: said, code }; }
|
|
1387
1703
|
// Loading code at run time: const { a } = await import('./x') -> "Loads a from ./x".
|
|
1388
1704
|
let dyn;
|
|
1389
1705
|
if ((dyn = head.match(/^(?:const|let|var)\s*(?:\{([^}]*)\}|([A-Za-z_$][\w$]*))\s*=\s*(?:await\s+)?(?:import|require)\(\s*['"`]([^'"`]+)['"`]\s*\)\s*;?$/))) {
|
|
@@ -1460,6 +1776,36 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1460
1776
|
}
|
|
1461
1777
|
// A C-style loop with no counter of its own: `for (; pos < limit; i++)` / `for (;;)`.
|
|
1462
1778
|
if ((m = head.match(/^for\s*\(\s*[^;]*;\s*([^;]*?)\s*;[^)]*\)\s*\{?\s*$/))) return { kind: 'loop', says: m[1] ? `Repeats while ${sayCodeCondition(m[1])}${innerNote}` : `Repeats${innerNote}`, code };
|
|
1779
|
+
// Rust `for x in xs.iter() {` / `for (k, v) in map.iter()` / `for i in 0..n` / `for c in s.chars()`.
|
|
1780
|
+
if (LANG === 'rust' && (m = head.match(/^for\s+(\(\s*\w+\s*,\s*\w+\s*\)|\w+)\s+in\s+(.+?)\s*\{?\s*$/))) {
|
|
1781
|
+
const it = m[2].replace(/^&(?:mut\s+)?/, '');
|
|
1782
|
+
const pair = /^\(\s*(\w+)\s*,\s*(\w+)\s*\)$/.exec(m[1]);
|
|
1783
|
+
const who = pair ? `${words(pair[1])} and ${words(pair[2])}` : words(m[1]);
|
|
1784
|
+
let k;
|
|
1785
|
+
const r = !pair && rangeWords(it);
|
|
1786
|
+
if (r && m[1] !== '_') return { kind: 'loop', says: `Counts ${who} ${r.says}${innerNote}`, code };
|
|
1787
|
+
if ((k = it.match(/^([A-Za-z_][\w.]*?)(?:\.(?:iter|iter_mut|into_iter)\(\s*\))?$/)) && m[1] !== '_') return { kind: 'loop', says: `For each ${who} in ${possessiveWords(k[1])}${innerNote}`, code };
|
|
1788
|
+
if ((k = it.match(/^([A-Za-z_][\w.]*)\.(chars|lines|bytes|keys|values)\(\s*\)$/)) && m[1] !== '_') return { kind: 'loop', says: `For each ${who} in the ${{ chars: 'characters', lines: 'lines', bytes: 'bytes', keys: 'keys', values: 'values' }[k[2]]} of ${possessiveWords(k[1])}${innerNote}`, code };
|
|
1789
|
+
}
|
|
1790
|
+
// Python counting loops: `for i in range(n)`, `range(a, b)`, `range(len(xs))`, and `for i, x in enumerate(xs)`.
|
|
1791
|
+
if (LANG === 'python' && (m = head.match(/^for\s+(\w+)\s+in\s+range\((.*)\)\s*:$/))) { const r = pythonRangeWords(m[1], m[2]); if (r) return { kind: 'loop', says: `${r}${innerNote}`, code }; }
|
|
1792
|
+
if (LANG === 'python' && (m = head.match(/^for\s+\(?\s*(\w+)\s*,\s*(\w+)\s*\)?\s+in\s+enumerate\(\s*([A-Za-z_][\w.]*)\s*\)\s*:$/)) && m[1] !== '_') {
|
|
1793
|
+
return { kind: 'loop', says: `For each ${words(m[2])} in ${possessiveWords(m[3])}, with its position ${words(m[1])} (from 0)${innerNote}`, code };
|
|
1794
|
+
}
|
|
1795
|
+
// Python `for x in <collection>:` where the collection is a call: what the call gives, never a cut-off "values(".
|
|
1796
|
+
if (LANG === 'python' && (m = head.match(/^for\s+(\w+)\s+in\s+(.+?)\s*:$/)) && !/^range\(|^enumerate\(/.test(m[2])) {
|
|
1797
|
+
const it = m[2];
|
|
1798
|
+
let w = null, k;
|
|
1799
|
+
if ((k = it.match(/^([A-Za-z_][\w.]*)\.(values|keys)\(\s*\)$/))) w = `the ${k[2]} of ${possessiveWords(k[1])}`;
|
|
1800
|
+
else if ((k = it.match(/^sorted\(\s*([A-Za-z_][\w.]*)\s*\)$/))) w = `${possessiveWords(k[1])}, sorted`;
|
|
1801
|
+
else if ((k = it.match(/^reversed\(\s*([A-Za-z_][\w.]*)\s*\)$/))) w = `${possessiveWords(k[1])}, in reverse order`;
|
|
1802
|
+
else if (/^[A-Za-z_]/.test(it) && /\)$/.test(it)) {
|
|
1803
|
+
// The outermost call: the last `name(` whose bracket closes at the very end (`text.lower().split()` is split).
|
|
1804
|
+
const last = [...it.matchAll(/([A-Za-z_]\w*)\(/g)].reverse().find((x) => closeOf(it, x.index + x[0].length - 1) === it.length - 1);
|
|
1805
|
+
if (last && !/^(?:zip|map|filter|iter|list|tuple|set)$/.test(last[1]) && (last.index === 0 || it[last.index - 1] === '.') && balancedText(it)) w = `the result of ${words(last[1])}`;
|
|
1806
|
+
}
|
|
1807
|
+
if (w) return { kind: 'loop', says: `For each ${words(m[1])} in ${w}${innerNote}`, code };
|
|
1808
|
+
}
|
|
1463
1809
|
// Pairs unpacked in a loop: for (const [key, value] of entries) / for key, value in items.items() / foreach ($a as $k => $v)
|
|
1464
1810
|
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*$/))) {
|
|
1465
1811
|
const src = stripTail(m[3]).replace(/\($/, '()').replace(/^Object\.entries\((.+)\)$/, '$1').replace(/\.(?:items|entries|enumerated)\(\)$/, '');
|
|
@@ -1477,6 +1823,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1477
1823
|
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 };
|
|
1478
1824
|
// Go `for {` repeats until something inside leaves the loop (or the function).
|
|
1479
1825
|
if (/^for\s*\{$/.test(head)) return { kind: 'loop', says: `Repeats until something inside leaves the loop${innerNote}`, code };
|
|
1826
|
+
if (LANG === 'rust' && /^loop\s*\{?\s*$/.test(head)) return { kind: 'loop', says: `Repeats until a step inside stops it${innerNote}`, code };
|
|
1480
1827
|
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 };
|
|
1481
1828
|
// Branches
|
|
1482
1829
|
// Go: `if err := open(); err != nil` -> "If open fails"; `if v, ok := m[k]; ok` -> "If k is in m".
|
|
@@ -1501,7 +1848,8 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1501
1848
|
}
|
|
1502
1849
|
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) }; }
|
|
1503
1850
|
if (/^switch\s*(?:true\s*)?\{$/.test(head)) return { kind: 'branch', says: `Checks these cases in order${innerNote}`, code };
|
|
1504
|
-
|
|
1851
|
+
// (`match = re.match(x)` / `select.x` use the word as a name: a statement word is never followed by = . , or ).)
|
|
1852
|
+
if ((m = head.match(/^(?:switch|match|case|select)\b(?!\s*(?:=(?!=)|\.|,|\)|\]|[-+*/%]=))\s*\(?(.*?)\)?\s*(?:\{|:)?\s*$/))) return { kind: 'branch', says: `Chooses by ${words(clip(m[1], 40)) || 'value'}${innerNote}`, code };
|
|
1505
1853
|
if (/^(?:try|begin)\b/.test(head)) return { kind: 'try', says: `Tries the next steps and handles any error${innerNote}`, code };
|
|
1506
1854
|
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 };
|
|
1507
1855
|
if ((m = head.match(/^assert(?:_\w+|That|Equals|True|False|NotNull|Null)\b/))) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
|
|
@@ -1538,6 +1886,9 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1538
1886
|
if (((m = head.match(/^([A-Z]\w*)(?:::\w+)*\s*\{\s*$/)) || (m = head.match(/^([A-Z]\w*)\s*\{.*\}$/))) && !(closeOf(text, text.indexOf("{")) > 0 && text.slice(closeOf(text, text.indexOf("{")) + 1).trim())) return { kind: 'return', says: `Returns a new ${words(m[1])}`, code };
|
|
1539
1887
|
if ((m = head.match(/^(?:[A-Z]\w*::)+([A-Z]\w*)$/))) return { kind: 'return', says: `Returns ${m[1]}`, code };
|
|
1540
1888
|
if (/^vec!?\[/.test(head)) return { kind: 'return', says: 'Returns a list', code };
|
|
1889
|
+
// Rust: `loop {` repeats until a step inside stops it; a last `Ok(…)` / `Some(…)` is what the function gives back.
|
|
1890
|
+
if (LANG === 'rust' && /^loop\s*\{?\s*$/.test(head)) return { kind: 'loop', says: `Repeats until a step inside stops it${innerNote}`, code };
|
|
1891
|
+
if (LANG === 'rust' && /^(?:Ok|Some)\s*\(/.test(head) && closeOf(head, head.indexOf('(')) === head.length - 1) { const v = sayValue(head); if (v) return { kind: 'return', says: `Returns ${v}`, code }; }
|
|
1541
1892
|
// A bare value as a statement is an implicit return (Ruby, Rust, Kotlin/Scala expression bodies).
|
|
1542
1893
|
// Only where a last value is given back (Ruby, Rust, Kotlin, Scala, Elixir); in Python or JavaScript a bare
|
|
1543
1894
|
// `self.content` only reads the value.
|
|
@@ -1558,7 +1909,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1558
1909
|
if ((m = head.match(/^(?:const|let|var|val)\s+([{[])\s*(.*?)\s*[}\]]\s*(?::\s*[^=]+)?=\s*(.+)$/))) {
|
|
1559
1910
|
const names = m[2].split(',').map((x) => x.trim().split(/\s*[:=]\s*/)[0].replace(/^\.\.\./, '')).filter(Boolean).map(words);
|
|
1560
1911
|
const value = stripTail(m[3]); const c = callee(value);
|
|
1561
|
-
const from = c ?
|
|
1912
|
+
const from = c ? callWords(c, value) : (sayValue(value) || words(value.split('.').pop()));
|
|
1562
1913
|
return { kind: 'set', says: `Takes ${names.slice(0, 4).join(', ')}${names.length > 4 ? ', …' : ''} from ${from}`, code };
|
|
1563
1914
|
}
|
|
1564
1915
|
if ((m = head.match(/^(?:var|const)\s*\($/))) return { kind: 'set', says: 'Declares some values', code };
|
|
@@ -1575,7 +1926,7 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1575
1926
|
if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
|
|
1576
1927
|
// (C++: `Status s = FindTable(…)` calls FindTable; only `Foo f = Foo(…)` makes a new Foo.)
|
|
1577
1928
|
if (/^new\s/.test(value) || (makesType(c) && (LANG !== 'cpp' || sameType(c, m[1])))) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
|
|
1578
|
-
return { kind: 'set', says: `Works out ${target} from ${
|
|
1929
|
+
return { kind: 'set', says: `Works out ${target} from ${callWords(c, value)}`, code, callee: c };
|
|
1579
1930
|
}
|
|
1580
1931
|
const v = value ? sayValue(value) : null;
|
|
1581
1932
|
return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
|
|
@@ -1636,11 +1987,11 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1636
1987
|
const known = sayCall(c, firstArgs(value));
|
|
1637
1988
|
if (known) return { kind: 'call', says: `${known}, keeping the result as ${target}`, code, callee: c };
|
|
1638
1989
|
if (/^new\s/.test(value) || (makesType(c) && (LANG !== 'cpp' || sameType(c, declType)))) return { kind: 'set', says: `Creates a new ${c.split('.').pop()} as ${target}`, code };
|
|
1639
|
-
return { kind: 'set', says: `Works out ${target} from ${
|
|
1990
|
+
return { kind: 'set', says: `Works out ${target} from ${callWords(c, value)}`, code, callee: c };
|
|
1640
1991
|
}
|
|
1641
1992
|
if (!value) return { kind: 'set', says: `Works out ${target}`, code };
|
|
1642
1993
|
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 }; }
|
|
1643
|
-
const v = sayValue(value);
|
|
1994
|
+
const v = sayValue(value) ?? sayArithmetic(value);
|
|
1644
1995
|
return { kind: 'set', says: v ? `Sets ${target} to ${v}` : `Works out ${target}`, code };
|
|
1645
1996
|
}
|
|
1646
1997
|
// Calls
|
|
@@ -1655,15 +2006,61 @@ function classifyWords(raw, { inner = 0 } = {}) {
|
|
|
1655
2006
|
const owner = m[1].split('.').filter((p) => !/^(self|this)$/.test(p));
|
|
1656
2007
|
const where = owner.length > 1 ? `${words(owner[owner.length - 2])}'s ${words(owner[owner.length - 1])}` : words(owner[0] || m[1]);
|
|
1657
2008
|
const added = /^new\s+([A-Z]\w*)/.exec(head.slice(head.indexOf('(') + 1))?.[1];
|
|
1658
|
-
|
|
1659
|
-
const
|
|
1660
|
-
|
|
1661
|
-
|
|
2009
|
+
// The arguments may run over several lines (`out.push({\n kind: …,\n})`): read them from the whole statement.
|
|
2010
|
+
const whole = closeOf(head, head.indexOf('(')) > head.indexOf('(') ? head : text.replace(/\s+/g, ' ');
|
|
2011
|
+
const open0 = whole.indexOf('('), close0 = closeOf(whole, open0);
|
|
2012
|
+
const argText = close0 > open0 ? whole.slice(open0 + 1, close0) : '';
|
|
2013
|
+
const args = argText.trim() ? splitTopArgs(argText) : [];
|
|
2014
|
+
// What is added, in words: an entry and its fields, a text, a value's field, the result of a call, or a name.
|
|
2015
|
+
const addedWhat = (a) => {
|
|
2016
|
+
const t = String(a).trim();
|
|
2017
|
+
if (/^\{[\s\S]*\}$/.test(t)) {
|
|
2018
|
+
// (Its fields are listed only when the statement is short enough for the faithfulness check to see them all.)
|
|
2019
|
+
if (text.split('\n').length > 7) return 'an entry';
|
|
2020
|
+
const parts = splitTopArgs(t.slice(1, -1));
|
|
2021
|
+
const keys = parts.map((p) => (/^\.\.\./.test(p) ? null : (p.match(/^\s*['"]?([A-Za-z_$][\w$]*)['"]?\s*(?::|$|\()/) || [])[1])).filter(Boolean);
|
|
2022
|
+
if (!parts.length) return 'an empty entry';
|
|
2023
|
+
if (!keys.length) return null;
|
|
2024
|
+
return `an entry (${keys.slice(0, 4).map(words).join(', ')}${keys.length > 4 || keys.length < parts.length ? ', …' : ''})`;
|
|
2025
|
+
}
|
|
2026
|
+
if (/^(?:''|""|``)$/.test(t)) return '""';
|
|
2027
|
+
if (t.startsWith('`')) { const q = templateWithValues(t, 60); return q != null ? `"${q}"` : null; }
|
|
2028
|
+
if (/^["']/.test(t)) { const q = wholeWords(firstText(t, 60)); return q ? `"${q}"` : null; }
|
|
2029
|
+
if (/^new\s+[A-Z]\w*/.test(t)) return `a new ${t.match(/^new\s+([A-Z]\w*)/)[1]}`;
|
|
2030
|
+
if (/^[A-Za-z_$][\w$]*$/.test(t)) return words(t);
|
|
2031
|
+
if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(t)) return possessiveWords(t);
|
|
2032
|
+
const c = callee(t);
|
|
2033
|
+
if (c && closeOf(t, t.indexOf('(')) === t.length - 1) return `the result of ${callWords(c, t)}`;
|
|
2034
|
+
return null;
|
|
2035
|
+
};
|
|
2036
|
+
// (Only `push`/`unshift` add every argument: `list.add(index, element)` and `insert(i, x)` put one value at a place.)
|
|
2037
|
+
if (args.length > 1 && !/\.(?:push|unshift)\(/.test(whole)) return { kind: 'call', says: `Adds to ${where}`, code, callee: m[1] };
|
|
2038
|
+
if (args.length > 1) {
|
|
2039
|
+
const ws = args.map(addedWhat);
|
|
2040
|
+
const said = ws.every(Boolean) && args.length <= 3 ? `${ws.slice(0, -1).join(', ')} and ${ws[ws.length - 1]}` : null;
|
|
2041
|
+
return { kind: 'call', says: said ? `Adds ${said} to ${where}` : `Adds several values to ${where}`, code, callee: m[1] };
|
|
2042
|
+
}
|
|
2043
|
+
const one = args.length === 1 ? addedWhat(args[0]) : null;
|
|
2044
|
+
return { kind: 'call', says: added ? `Adds a new ${words(added)} to ${where}` : one ? `Adds ${one} to ${where}` : `Adds to ${where}`, code, callee: m[1] };
|
|
1662
2045
|
}
|
|
1663
2046
|
const c = callee(head);
|
|
1664
2047
|
if (c) {
|
|
1665
2048
|
const known = sayCall(c, firstArgs(head));
|
|
1666
|
-
return { kind: 'call', says: known
|
|
2049
|
+
if (known) return { kind: 'call', says: known, code, callee: c };
|
|
2050
|
+
// One argument that can be named says what the call is given, so two calls to the same function differ:
|
|
2051
|
+
// `cmd.addCommand(rulesCommand())` -> "Calls add command (with the result of rules command)".
|
|
2052
|
+
const o = head.indexOf('('), cl = o >= 0 ? closeOf(head, o) : -1;
|
|
2053
|
+
const only = cl > o && /^\s*;?\s*$/.test(head.slice(cl + 1)) ? splitTopArgs(head.slice(o + 1, cl)) : [];
|
|
2054
|
+
if ((LANG === 'typescript' || LANG === 'javascript' || LANG === 'python') && only.length === 1 && !/^\s*(?:async\s*)?(?:\(|function\b|[A-Za-z_$][\w$]*\s*=>)/.test(only[0]) && !/^(?:exec|eval|compile|__import__|execfile|Function|setTimeout|setInterval)$/.test(c)) {
|
|
2055
|
+
const t = only[0].trim();
|
|
2056
|
+
const w = t.startsWith('`') ? (templateWithValues(t, 60) ? `"${templateWithValues(t, 60)}"` : null)
|
|
2057
|
+
: /^["']/.test(t) ? (wholeWords(firstText(t, 60)) ? `"${wholeWords(firstText(t, 60))}"` : null)
|
|
2058
|
+
: /^[A-Za-z_$][\w$]*$/.test(t) ? words(t)
|
|
2059
|
+
: /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(t) ? possessiveWords(t)
|
|
2060
|
+
: callee(t) && closeOf(t, t.indexOf('(')) === t.length - 1 && !/^new\s/.test(t) ? `the result of ${callWords(callee(t), t)}` : null;
|
|
2061
|
+
if (w && !ENDS_ON_PREPOSITION.test(callWords(c, head))) return { kind: 'call', says: `Calls ${callWords(c, head)} (with ${w})`, code, callee: c };
|
|
2062
|
+
}
|
|
2063
|
+
return { kind: 'call', says: `Calls ${callWords(c, head)}`, code, callee: c };
|
|
1667
2064
|
}
|
|
1668
2065
|
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])) {
|
|
1669
2066
|
if (/^assert/.test(m[1])) return { kind: 'check', says: `Checks: ${clip(head, 60)}`, code };
|
|
@@ -2187,6 +2584,32 @@ export function stepsFrom(statements) {
|
|
|
2187
2584
|
for (let i = 0; i < steps.length - 1; i++) asCall(steps, i);
|
|
2188
2585
|
// A value chosen by if / match / when: each side's last value is what the name is set to (or what is returned).
|
|
2189
2586
|
for (const st of steps) if (Object.hasOwn(st, 'valueOf')) { const t = st.valueOf; delete st.valueOf; giveValue(st.children, t); giveValue(st.otherwise, t); }
|
|
2587
|
+
// A web route registered in place (`fastify.post('/orders', handle(async (request) => { … }))`) is its own action,
|
|
2588
|
+
// read separately ("When someone calls POST /orders"); here it is one line, not its steps a second time.
|
|
2589
|
+
if (LANG === 'typescript' || LANG === 'javascript') {
|
|
2590
|
+
for (const st of steps) {
|
|
2591
|
+
const r = /^\s*[A-Za-z_$][\w$]*\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)['"`]\s*,/.exec(String(st.code ?? ''));
|
|
2592
|
+
if (!r || !/^\//.test(r[2])) continue;
|
|
2593
|
+
st.kind = 'call';
|
|
2594
|
+
st.says = `Handles ${r[1] === 'all' ? 'every request to' : r[1].toUpperCase()} ${r[2]} (its steps are in that action)`;
|
|
2595
|
+
delete st.children; delete st.nested; delete st.restates; delete st.value;
|
|
2596
|
+
st.route = { method: r[1].toUpperCase(), path: r[2] };
|
|
2597
|
+
}
|
|
2598
|
+
}
|
|
2599
|
+
// "Calls X with these steps", said by what the call is for (JavaScript, TypeScript): a command-line command
|
|
2600
|
+
// (`program.command('check')…`), a database transaction, progress shown while it works, or the name it registers.
|
|
2601
|
+
if (LANG === 'typescript' || LANG === 'javascript') {
|
|
2602
|
+
for (const st of steps) {
|
|
2603
|
+
const said = /^Calls ([\w ]+) with these steps$/.exec(String(st.says ?? ''));
|
|
2604
|
+
if (!said) continue;
|
|
2605
|
+
const code = String(st.code ?? '');
|
|
2606
|
+
let m;
|
|
2607
|
+
if ((m = /\.command\(\s*(['"`])([\w:.\-]+)(?:\s[^'"`]*)?\1\s*\)/.exec(code))) st.says = `Defines the command "${m[2]}"; when it runs, it does these steps`;
|
|
2608
|
+
else if (/\.transaction\(\s*(?:async\s*)?\(/.test(code)) st.says = 'Does these steps in one database transaction';
|
|
2609
|
+
else if (/\.withProgress\(/.test(code)) st.says = 'Shows progress while it does these steps';
|
|
2610
|
+
else if ((m = /^\s*(?:await\s+)?[\w$.]+\(\s*(['"`])([^'"`$]{1,60})\1\s*,/.exec(code))) st.says = `Calls ${said[1]} ("${m[2]}") with these steps`;
|
|
2611
|
+
}
|
|
2612
|
+
}
|
|
2190
2613
|
// Every step is kept (anchoring needs all of them); `more` tells a view how many to fold away.
|
|
2191
2614
|
const more = Math.max(0, steps.length - MAX_STEPS);
|
|
2192
2615
|
for (const st of steps) if (restates(st)) st.restates = true;
|