@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
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// thunder replay: the Thunder Time Machine. Step forward and back through a recording made with
|
|
2
|
+
// `thunder run --record <file>`: each statement as it ran, the values it changed, what it printed, what a function
|
|
3
|
+
// gave back, and where a choice or a loop went. It replays a recording: going back shows an earlier moment and never
|
|
4
|
+
// undoes anything the program did.
|
|
5
|
+
// thunder replay <file> [--step n] [--json]
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { createInterface } from 'node:readline';
|
|
8
|
+
import { paint, paintThunderLine, useColor } from './term.mjs';
|
|
9
|
+
|
|
10
|
+
const SCHEMA = 'thunder-time-machine-v1';
|
|
11
|
+
const USAGE = `usage: thunder replay <recording.json> [--step n] [--json]
|
|
12
|
+
Step through a recording made with: thunder run <program> --record <recording.json>
|
|
13
|
+
Keys: Enter or n for the next step, b to go back, j and a number to jump (j 7), q to quit.`;
|
|
14
|
+
|
|
15
|
+
/** The text of a Thunder line from the recording's copy of the program. */
|
|
16
|
+
const lineText = (trace, file, line) => {
|
|
17
|
+
const src = trace.files?.[file] ?? Object.values(trace.files ?? {})[0];
|
|
18
|
+
return src ? (src.split('\n')[line - 1] ?? '').trim() : '';
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Where a choice or a loop went, in words. For When / Otherwise when / Otherwise, the arm whose lines hold the next
|
|
23
|
+
* step answers it: the first arm is "yes"; a later one is "no", then that arm.
|
|
24
|
+
*/
|
|
25
|
+
function branchText(trace, s) {
|
|
26
|
+
if (s.next == null) return s.kind === 'if' ? ' → no, so nothing inside ran' : ' → the steps inside did not run';
|
|
27
|
+
if (s.kind !== 'if') return ` → goes on to line ${s.next}`;
|
|
28
|
+
const src = (trace.files?.[s.file] ?? '').split('\n');
|
|
29
|
+
const indent = (l) => l.match(/^\s*/)[0].length;
|
|
30
|
+
const base = indent(src[s.line - 1] ?? '');
|
|
31
|
+
const arms = [{ line: s.line, text: (src[s.line - 1] ?? '').trim() }];
|
|
32
|
+
for (let k = s.line; k < src.length; k++) {
|
|
33
|
+
const l = src[k];
|
|
34
|
+
if (!l.trim()) continue;
|
|
35
|
+
if (indent(l) < base || (indent(l) === base && !/^\s*Otherwise\b/.test(l))) break;
|
|
36
|
+
if (indent(l) === base) arms.push({ line: k + 1, text: l.trim() });
|
|
37
|
+
}
|
|
38
|
+
const arm = [...arms].reverse().find((x) => x.line < s.next) ?? arms[0];
|
|
39
|
+
if (arm === arms[0]) return ' → yes';
|
|
40
|
+
if (/^Otherwise:$/.test(arm.text)) return ` → no, so the Otherwise steps (line ${arm.line})`;
|
|
41
|
+
return ` → no; then: ${arm.text.replace(/^Otherwise\s+(when|if)\s+/i, '').replace(/:$/, '')} → yes (line ${arm.line})`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** One step as a few lines of plain text. */
|
|
45
|
+
export function renderStep(trace, i) {
|
|
46
|
+
const steps = trace.steps;
|
|
47
|
+
const s = steps[i];
|
|
48
|
+
if (!s) return `There is no step ${i + 1}. This recording has ${steps.length} step${steps.length === 1 ? '' : 's'}.`;
|
|
49
|
+
const where = s.fn ? `inside "${s.fn.replace(/_/g, ' ')}"` : 'in the program';
|
|
50
|
+
const L = [`⏱ Step ${s.n} of ${steps.length} · ${s.file}, line ${s.line} · ${where}`, ` ${paintThunderLine(lineText(trace, s.file, s.line), useColor())}`];
|
|
51
|
+
// A call: the steps deeper than this one, right after it, belong to the function it called.
|
|
52
|
+
let j = i + 1;
|
|
53
|
+
while (j < steps.length && steps[j].depth > s.depth) j++;
|
|
54
|
+
const calls = j > i + 1 && !('next' in s) ? steps[i + 1] : null;
|
|
55
|
+
if (calls) L.push(` Calls "${(calls.fn ?? 'a function').replace(/_/g, ' ')}" (step${j - i - 1 === 1 ? '' : 's'} ${i + 2}${j - i - 1 > 1 ? `–${j}` : ''}), then:`);
|
|
56
|
+
if ('next' in s) L.push(branchText(trace, s));
|
|
57
|
+
for (const c of s.changes ?? []) L.push(` ${c.name}: ${c.before != null ? `${c.before} → ` : '→ '}${c.after}`);
|
|
58
|
+
if (s.gives != null) L.push(` gives back ${s.gives}`);
|
|
59
|
+
if (s.said) for (const line of s.said.replace(/\n$/, '').split('\n')) L.push(` says: ${line}`);
|
|
60
|
+
if (s.failed && !('next' in s)) L.push(` ✗ stopped here${trace.stderr ? `: ${trace.stderr.trim().replace(/^.*?: /, '')}` : ''}`);
|
|
61
|
+
if (!s.changes && s.gives == null && !s.said && !('next' in s) && !s.failed && !calls) L.push(' (nothing changed)');
|
|
62
|
+
return L.join('\n');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function replayMain(argv, { input = process.stdin, output = process.stdout } = {}) {
|
|
66
|
+
const a = { _: [], step: null, json: false };
|
|
67
|
+
for (let i = 0; i < argv.length; i++) {
|
|
68
|
+
const x = argv[i];
|
|
69
|
+
if (x === '--step') a.step = argv[++i];
|
|
70
|
+
else if (x === '--json') a.json = true;
|
|
71
|
+
else if (x === '--help' || x === '-h') { console.log(USAGE); return Promise.resolve(0); }
|
|
72
|
+
else if (x.startsWith('--')) { console.error(`thunder replay: there is no option ${x}.\n${USAGE}`); return Promise.resolve(2); }
|
|
73
|
+
else a._.push(x);
|
|
74
|
+
}
|
|
75
|
+
if (a._.length !== 1) { console.error(`thunder replay: name one recording.\n${USAGE}`); return Promise.resolve(2); }
|
|
76
|
+
let trace;
|
|
77
|
+
try { trace = JSON.parse(readFileSync(a._[0], 'utf8')); }
|
|
78
|
+
catch (e) { console.error(`thunder replay: couldn't read ${a._[0]}${e.code === 'ENOENT' ? ': there is no such file' : ': it is not a recording'}. Make one with: thunder run <program> --record ${a._[0]}`); return Promise.resolve(2); }
|
|
79
|
+
if (trace?.schema !== SCHEMA || !Array.isArray(trace.steps)) { console.error(`thunder replay: ${a._[0]} is not a Thunder recording. Make one with: thunder run <program> --record ${a._[0]}`); return Promise.resolve(2); }
|
|
80
|
+
const total = trace.steps.length;
|
|
81
|
+
const say = (s = '') => output.write(`${paint(s, useColor(output))}\n`);
|
|
82
|
+
if (!total) { say('This recording has no steps (the program had nothing to run).'); return Promise.resolve(0); }
|
|
83
|
+
if (a.step != null) {
|
|
84
|
+
const n = Number(a.step);
|
|
85
|
+
if (!Number.isInteger(n) || n < 1 || n > total) { console.error(`thunder replay: --step needs a number from 1 to ${total}.`); return Promise.resolve(2); }
|
|
86
|
+
say(a.json ? JSON.stringify(trace.steps[n - 1], null, 2) : renderStep(trace, n - 1));
|
|
87
|
+
return Promise.resolve(0);
|
|
88
|
+
}
|
|
89
|
+
if (a.json) { say(JSON.stringify(trace, null, 2)); return Promise.resolve(0); }
|
|
90
|
+
|
|
91
|
+
// Step through: one step at a time, from the terminal or from piped lines.
|
|
92
|
+
say(`⚡ Replaying ${trace.program}: ${total} step${total === 1 ? '' : 's'}, recorded with Thunder™ ${trace.thunder}.`);
|
|
93
|
+
say('This replays a recording. Going back shows an earlier moment; it never undoes anything the program did.');
|
|
94
|
+
say('');
|
|
95
|
+
const rl = createInterface({ input, terminal: false });
|
|
96
|
+
const it = rl[Symbol.asyncIterator]();
|
|
97
|
+
let i = 0;
|
|
98
|
+
const show = () => { say(renderStep(trace, i)); };
|
|
99
|
+
const ask = async () => {
|
|
100
|
+
output.write(`\n ${i + 1 < total ? 'Enter/n next' : 'last step'} · b back · j N jump · q quit > `);
|
|
101
|
+
const r = await it.next();
|
|
102
|
+
if (r.done) return null;
|
|
103
|
+
if (!input.isTTY) output.write(`${r.value}\n`);
|
|
104
|
+
return r.value.trim();
|
|
105
|
+
};
|
|
106
|
+
return (async () => {
|
|
107
|
+
show();
|
|
108
|
+
for (;;) {
|
|
109
|
+
const c = await ask();
|
|
110
|
+
if (c == null || /^q/i.test(c)) break;
|
|
111
|
+
if (c === '' || /^n/i.test(c)) { if (i + 1 < total) i++; else { say('\nThat was the last step.'); continue; } }
|
|
112
|
+
else if (/^b/i.test(c)) { if (i > 0) i--; else { say('\nThis is the first step.'); continue; } }
|
|
113
|
+
else if (/^j\s*\d+$/i.test(c)) { const n = Number(c.replace(/\D/g, '')); if (n >= 1 && n <= total) i = n - 1; else { say(`\nJump to a step from 1 to ${total}.`); continue; } }
|
|
114
|
+
else { say('\nType Enter or n (next), b (back), j and a number (jump), or q (quit).'); continue; }
|
|
115
|
+
say('');
|
|
116
|
+
show();
|
|
117
|
+
}
|
|
118
|
+
rl.close();
|
|
119
|
+
say('');
|
|
120
|
+
if (trace.status !== 0) say(`The program stopped with a problem: ${trace.stderr.trim()}`);
|
|
121
|
+
return 0;
|
|
122
|
+
})();
|
|
123
|
+
}
|
package/src/review.mjs
CHANGED
|
@@ -376,14 +376,15 @@ function valueChanges(o, n) {
|
|
|
376
376
|
return ` (values ${onlyA.length ? `${onlyA.slice(0, 4).join(', ')} removed` : ''}${onlyA.length && onlyB.length ? ', ' : ''}${onlyB.length ? `${onlyB.slice(0, 4).join(', ')} added` : ''})`;
|
|
377
377
|
}
|
|
378
378
|
|
|
379
|
-
function compareMember(o, n, items) {
|
|
379
|
+
function compareMember(o, n, items, { extracted = false } = {}) {
|
|
380
380
|
const subject = subjectOf(n);
|
|
381
381
|
const sameCode = sameTokens(o.tokens, n.tokens);
|
|
382
382
|
const sameThunder = o.sig === n.sig;
|
|
383
383
|
const renamedOrMoved = [];
|
|
384
384
|
if (o.m.file !== n.m.file) renamedOrMoved.push(`moved from ${o.m.file} to ${n.m.file}`);
|
|
385
385
|
// A route handler is named after its address: a new address is said once, as the address.
|
|
386
|
-
|
|
386
|
+
// (Steps moved into a new function are not a rename: the old function is still there and runs the new one.)
|
|
387
|
+
if (!extracted && nameKey(o.m.name) !== nameKey(n.m.name) && (o.m.route ?? '') === (n.m.route ?? '')) renamedOrMoved.push(`renamed from ${o.m.label} to ${n.m.label}`);
|
|
387
388
|
const moveKind = o.m.file !== n.m.file && nameKey(o.m.name) === nameKey(n.m.name) ? 'moved' : 'renamed';
|
|
388
389
|
const formOnly = (why) => items.push(item(renamedOrMoved.length ? moveKind : 'form', 'form', subject, whereOf(n),
|
|
389
390
|
`${renamedOrMoved.length ? `${cap(renamedOrMoved.join(' and '))}. ` : ''}Only the form changed: ${why}`));
|
|
@@ -520,6 +521,18 @@ function enclosingName(lines, line) {
|
|
|
520
521
|
* pass only the files that changed (and, for a moved file, both paths) or whole trees. Returns
|
|
521
522
|
* { schema, summary, items, notRead, unchanged } with items ordered by importance (risk, then meaning, then form).
|
|
522
523
|
*/
|
|
524
|
+
/** Whether most of `a`'s code tokens (by count) are also in `b`: three out of four or more, ignoring punctuation. */
|
|
525
|
+
function mostlyIn(a, b) {
|
|
526
|
+
const words = (ts) => ts.map((t) => t.t).filter((t) => /\w/.test(t));
|
|
527
|
+
const have = new Map();
|
|
528
|
+
for (const t of words(b)) have.set(t, (have.get(t) || 0) + 1);
|
|
529
|
+
const want = words(a);
|
|
530
|
+
if (want.length < 12) return false;
|
|
531
|
+
let hit = 0;
|
|
532
|
+
for (const t of want) { const c = have.get(t) || 0; if (c) { hit++; have.set(t, c - 1); } }
|
|
533
|
+
return hit / want.length >= 0.75;
|
|
534
|
+
}
|
|
535
|
+
|
|
523
536
|
export function thunderReview(oldFiles, newFiles) {
|
|
524
537
|
detailsCache = new WeakMap();
|
|
525
538
|
const A = side(oldFiles || []), B = side(newFiles || []);
|
|
@@ -551,8 +564,23 @@ export function thunderReview(oldFiles, newFiles) {
|
|
|
551
564
|
|| (o.m.rule && e.m.rule && !o.m.rule.partial && !e.m.rule.partial && comparePlainRules(o.m.rule, e.m.rule).same)));
|
|
552
565
|
if (n) { used.add(n); pairs.push([o, n]); o.paired = true; }
|
|
553
566
|
}
|
|
567
|
+
// 5. Steps moved into a new function: the function now runs a new one in the same file, and most of its old code
|
|
568
|
+
// is there. Its old steps are compared with the new function (what really changed in them), and the function
|
|
569
|
+
// itself is said to run it, instead of "no longer gives back …" for every step that only moved.
|
|
570
|
+
const movedInto = new Map();
|
|
571
|
+
for (const [o, n] of pairs) {
|
|
572
|
+
const named = new Set(n.tokens.map((t) => t.t));
|
|
573
|
+
const target = leftB().find((b) => b.m.file === n.m.file && b.m.kind !== 'not-read' && named.has(b.m.name) && b.m.name !== n.m.name && mostlyIn(o.tokens, b.tokens));
|
|
574
|
+
if (target) { used.add(target); movedInto.set(o, target); }
|
|
575
|
+
}
|
|
554
576
|
let unchanged = 0;
|
|
555
|
-
for (const [o, n] of pairs)
|
|
577
|
+
for (const [o, n] of pairs) {
|
|
578
|
+
const into = movedInto.get(o);
|
|
579
|
+
if (!into) { if (compareMember(o, n, items) === 'unchanged') unchanged++; continue; }
|
|
580
|
+
const now = n.text.slice(1).map((l) => l.trim()).filter(Boolean);
|
|
581
|
+
items.push(item('moved-into', 'meaning', subjectOf(n), whereOf(n), `Its steps moved to ${subjectOf(into)}, a new function it now runs; what changed in them is listed under ${subjectOf(into)}.`, { before: null, after: now }));
|
|
582
|
+
compareMember(o, into, items, { extracted: true });
|
|
583
|
+
}
|
|
556
584
|
for (const o of leftA()) items.push(item('removed', 'meaning', subjectOf(o), whereOf(o), `Removed ${KIND_WORD[o.m.kind] ?? 'function'}: ${subjectOf(o)}.`, { before: o.text, after: null }));
|
|
557
585
|
for (const n of leftB()) items.push(item('added', n.m.kind === 'not-read' ? 'risk' : 'meaning', subjectOf(n), whereOf(n),
|
|
558
586
|
n.m.kind === 'not-read' ? "New function that Thunder cannot read yet: check the code itself." : `New ${KIND_WORD[n.m.kind] ?? 'function'}: ${subjectOf(n)}${summaryOf(n)}.`, { before: null, after: n.text }));
|
package/src/say-less.mjs
CHANGED
|
@@ -50,7 +50,7 @@ function nodesOf(tree) {
|
|
|
50
50
|
return out;
|
|
51
51
|
}
|
|
52
52
|
import { FORM_WORDS } from './form-words.mjs';
|
|
53
|
-
import { asCodeWords, isCodeWords, stripQuoted, codeCounts, wordCounts, accountsFor } from './faithful.mjs';
|
|
53
|
+
import { asCodeWords, isCodeWords, stripQuoted, codeCounts, wordCounts, accountsFor, pythonImportSays, sliceWords } from './faithful.mjs';
|
|
54
54
|
|
|
55
55
|
export const WHY = {
|
|
56
56
|
form: 'the reader did not recognize this form',
|
|
@@ -166,6 +166,14 @@ function codeWordSet(code) {
|
|
|
166
166
|
}
|
|
167
167
|
|
|
168
168
|
/** The first word that has no source: not in the code, not a fixed word, and not an idiom with its trigger. */
|
|
169
|
+
// Words a Python import is read with ("Loads x from the y module" / "from this package" / ", called z here"): they
|
|
170
|
+
// add to what a word may stand for and never take away (a word with its usual meaning is still checked as before).
|
|
171
|
+
const IDIOM_EXTRA = new Set([
|
|
172
|
+
[/^(?:module|loads)$/, /^\s*(?:from\s+\S+\s+)?import\s/],
|
|
173
|
+
[/^package$/, /^\s*from\s+\.\w*\s+import\s/],
|
|
174
|
+
[/^(?:called|here)$/, /^\s*(?:from\s+\S+\s+)?import\s.*\bas\b/],
|
|
175
|
+
]);
|
|
176
|
+
IDIOM.push(...IDIOM_EXTRA);
|
|
169
177
|
const IDIOM_OF = new Map();
|
|
170
178
|
function unsourcedWord(says, code) {
|
|
171
179
|
let have = null;
|
|
@@ -178,7 +186,7 @@ function unsourcedWord(says, code) {
|
|
|
178
186
|
if (/^\d+$/.test(w)) continue;
|
|
179
187
|
let idiom = IDIOM_OF.get(w);
|
|
180
188
|
if (idiom === undefined) { idiom = IDIOM.find(([re]) => re.test(w)) ?? null; IDIOM_OF.set(w, idiom); }
|
|
181
|
-
if (idiom) { if (idiom[1].test(code) || inCode(w)) continue; return w; }
|
|
189
|
+
if (idiom) { if (idiom[1].test(code) || inCode(w)) continue; if (!IDIOM_EXTRA.has(idiom)) return w; }
|
|
182
190
|
if (GLUE.has(w) || FORM_WORDS.has(w)) continue;
|
|
183
191
|
if (/ing$/.test(w)) { const st = w.slice(0, -3); if ([`${st}s`, `${st}es`, `${st}e`, `${st.slice(0, -1)}s`].some((x) => FORM_WORDS.has(x))) continue; }
|
|
184
192
|
if (inCode(w)) continue;
|
|
@@ -236,7 +244,7 @@ function inventedValue(says, code) {
|
|
|
236
244
|
const text = String(code);
|
|
237
245
|
for (const num of said.replace(/"(?:\\.|[^"\\])*"/g, ' ').match(/(?<![\w.«])-?\d+(?:\.\d+)?(?![\w.»])/g) || []) {
|
|
238
246
|
const n = num.replace(/^-/, '');
|
|
239
|
-
if (!text.includes(n) && !/^[01]$/.test(n) && !statusNamed(n, text) && !text.includes(`..<${Number(n) + 1}`) && !new RegExp(
|
|
247
|
+
if (!text.includes(n) && !/^[01]$/.test(n) && !statusNamed(n, text) && !text.includes(`..<${Number(n) + 1}`) && !new RegExp(`\\.\\.<?\\s*${Number(n) + 1}\\b`).test(text) && !new RegExp(`\\brange\\((?:\\s*\\d+\\s*,)?\\s*${Number(n) + 1}\\s*\\)`).test(text)) return num;
|
|
240
248
|
}
|
|
241
249
|
for (const q of String(says).replace(/^(?:If (?:not: )?|Repeats: |Fails with )?`[^]*`$/, '').match(/"(?:\\.|[^"\\])*"/g) || []) {
|
|
242
250
|
if (!exactText(q.slice(1, -1), text)) return q;
|
|
@@ -266,7 +274,7 @@ function textSkeleton(t, words = false, open = false) {
|
|
|
266
274
|
}
|
|
267
275
|
if (c === '$' && /[A-Za-z_]/.test(n ?? '')) { let j = i + 1; while (j < s.length && /\w/.test(s[j])) j++; out += '\u0001'; i = j - 1; continue; }
|
|
268
276
|
if (c === '$' && /[0-9*@#?!$-]/.test(n ?? '')) { out += '\u0001'; i++; continue; }
|
|
269
|
-
if (c === '%' &&
|
|
277
|
+
if (c === '%' && /^[-+ #0-9.]*[sdifgxXoucpqvT]/.test(s.slice(i + 1, i + 6))) { const m = /^[-+ #0-9.]*[a-zA-Z]/.exec(s.slice(i + 1)); out += '\u0001'; i += m[0].length; continue; }
|
|
270
278
|
if (c === '\\' && /["'`\\]/.test(n ?? '')) { out += n; i++; continue; }
|
|
271
279
|
out += c;
|
|
272
280
|
}
|
|
@@ -377,6 +385,15 @@ function newThing(v, says) {
|
|
|
377
385
|
if (!m) return false;
|
|
378
386
|
let c = coreOf(v);
|
|
379
387
|
if (c?.kind === 'unary' && c.op === '&') c = coreOf(c.value);
|
|
388
|
+
// "a new random ID" for the calls that make one (crypto.randomUUID(), uuid.uuid4(), Guid.NewGuid(), …), and for
|
|
389
|
+
// its text form (`.ToString()`, `.hex`).
|
|
390
|
+
if (m[1] === 'random ID') {
|
|
391
|
+
let x = c;
|
|
392
|
+
if (x?.kind === 'call' && x.callee?.kind === 'member' && /^(?:ToString|toString)$/.test(x.callee.property)) x = x.callee.object;
|
|
393
|
+
if (x?.kind === 'member' && x.property === 'hex') x = x.object;
|
|
394
|
+
const name = x?.kind === 'call' ? (x.callee?.kind === 'member' ? x.callee.property : x.callee?.name) : null;
|
|
395
|
+
return /^(?:randomUUID|uuid4|NewGuid|uuidv4|v4|new_v4)$/.test(name ?? '') && !(x.args?.length);
|
|
396
|
+
}
|
|
380
397
|
const type = c?.kind === 'object' ? c.type : c?.kind === 'call' ? (c.callee.kind === 'name' ? c.callee.name : c.callee.kind === 'member' ? (/^(?:new|New)$/.test(c.callee.property) ? (c.callee.object.name ?? c.callee.object.property) : c.callee.property) : null) : null;
|
|
381
398
|
return !!type && sameWords(String(type).replace(/<.*$/, '').split(/::|\./).pop(), m[1]);
|
|
382
399
|
}
|
|
@@ -440,16 +457,36 @@ function namesKept(tree, said) {
|
|
|
440
457
|
// Calls that only walk a collection (`enumerate(xs)`, `d.items()`), or read an entry (`m.get(k)` as "the k entry in m").
|
|
441
458
|
const own = c?.kind === 'member' && !(c.object?.kind === 'name' && /^[A-Z]/.test(c.object.name)) ? c.object : null;
|
|
442
459
|
if (name && /^(?:enumerate|iter|iter_mut|into_iter|items|entries|values|stream|ToList|toList|AsEnumerable|toArray|asList|each_with_index|with_index|indices|withIndex|Values|Keys|keys)$/.test(name)) return ok(own) && ok(n.args);
|
|
460
|
+
// Rust `s.chars()` / `text.lines()` / `data.bytes()`: "the characters of s".
|
|
461
|
+
if (name && /^(?:chars|lines|bytes)$/.test(name) && own && sw.includes(` ${{ chars: 'characters', lines: 'lines', bytes: 'bytes' }[name]} of `)) return ok(own) && ok(n.args);
|
|
443
462
|
// C's string compare: `!strcmp(a, "x")` is "a is "x"".
|
|
444
463
|
if (name && /^(?:str|strn|mem|wcs|wcsn)(?:case)?cmp$|^_?str(?:n)?icmp$/.test(name) && / is /.test(sw)) return ok(n.args);
|
|
445
464
|
if (name && /^(?:get|Get|fetch|at|get_or_default|getOrDefault|GetValueOrDefault|TryGetValue|getOrNull|Item)$/.test(name) && / entry | entries /.test(sw)) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
|
|
465
|
+
// `d.get("k")` as "the "k" value from d"; `d.get("k", x)` as "…, or x if it has none" (the fallback said).
|
|
466
|
+
if (name === 'get' && c?.kind === 'member' && n.args?.[0]?.kind === 'literal' && n.args[0].type === 'text' && / value from /.test(sw) && (n.args.length === 1 || (n.args.length === 2 && / if it has none /.test(sw)))) return ok(c.object) && ok(n.args);
|
|
446
467
|
// "the result of X": the call is named, what it is given is one level down.
|
|
447
468
|
if (name && has(name) && sw.includes(` result of ${splitWords(name).join(' ')} `)) return true;
|
|
448
469
|
if (name && /^(?:new|New|create|of|from|make)$/.test(name) && / new /.test(sw) && c.kind === 'member') return ok(c.object);
|
|
470
|
+
// Everyday JavaScript calls said by what they give back (steps.mjs sayCommon): the words name every argument.
|
|
471
|
+
const onType = c?.kind === 'member' && c.object?.kind === 'name' ? c.object.name : null;
|
|
472
|
+
if (onType === 'Math' && /^(?:max|min)$/.test(name) && / (?:largest|smallest) /.test(sw)) return ok(n.args);
|
|
473
|
+
if (onType === 'Math' && /^(?:round|floor|ceil|abs|trunc)$/.test(name) && / (?:rounded|absolute|fraction) /.test(sw)) return ok(n.args);
|
|
474
|
+
if (onType === 'Date' && name === 'parse' && / time written /.test(sw)) return ok(n.args);
|
|
475
|
+
if (name === 'exec' && / first match of /.test(sw)) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
|
|
476
|
+
if (name === 'parse' && onType && /^[A-Z]/.test(onType) && / checked and read by /.test(sw) && has(onType)) return ok(n.args);
|
|
477
|
+
if (name === 'from' && onType && / made from /.test(sw)) return ok(n.args);
|
|
478
|
+
// Everyday Python: a list/tuple/set made from a value, sorted, reversed, and a position found with .index().
|
|
479
|
+
if (c?.kind === 'name' && /^(?:list|tuple)$/.test(name) && / as a (?:list|tuple) /.test(sw)) return ok(n.args);
|
|
480
|
+
if (c?.kind === 'name' && /^(?:set|frozenset)$/.test(name) && / different values in /.test(sw)) return ok(n.args);
|
|
481
|
+
if (c?.kind === 'name' && name === 'sorted' && / sorted /.test(sw)) return ok(n.args);
|
|
482
|
+
if (c?.kind === 'name' && name === 'reversed' && / reverse order /.test(sw)) return ok(n.args);
|
|
483
|
+
if (name === 'index' && c?.kind === 'member' && / position of /.test(sw)) return ok(c.object) && ok(n.args);
|
|
449
484
|
// Questions about a collection said in words: "any item in xs matches", "every …", "the first … that matches".
|
|
450
485
|
if (name && /^(?:any|some|all|every|none|find|first|filter|where|select|detect|find_index|findIndex|includes|include\?|contains|Contains|any\?|all\?|none\?|exists|Any|All|Exists|in_array|has|hasOwnProperty|has_key|key\?|containsKey|ContainsKey|startswith|endswith|startsWith|endsWith|StartsWith|EndsWith|start_with\?|end_with\?)$/.test(name) && / (?:any|every|all|no|first|matches|match|in|has|contains|starts|ends|one of) /.test(sw)) return ok(own) && n.args.every((a) => a.kind === 'lambda' || ok(a));
|
|
451
486
|
if (name && /^(?:len|length|size|count|nrow|NROW|Count|sizeof|strlen|wcslen|mb_strlen|nchar|str_length|lengths|Length)$/.test(name) && howMany) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
|
|
452
487
|
if (name && /^(?:isinstance|is_a\??|kind_of\??|instance_of\??|inherits|is)$/.test(name) && isA) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
|
|
488
|
+
// (C#'s String.IsNullOrEmpty(x) is a question about x: the type it is asked on is not a value.)
|
|
489
|
+
if (name && /^IsNullOr(?:Empty|WhiteSpace)$/.test(name) && c?.kind === 'member' && /^[Ss]tring$/.test(c.object?.name ?? '') && setWords) return ok(n.args);
|
|
453
490
|
if (name && /^(?:is\.null|is_null|isNull|is\.na|isset|empty|is_none|isNone|isNil|is_nil|nil\?|null\?|blank\?|present\?|empty\?|isEmpty|IsNullOrEmpty|IsNullOrWhiteSpace|isBlank|isNotEmpty|isNotBlank|any\?|none\?)$/.test(name) && setWords) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
|
|
454
491
|
return (name == null || has(name)) && (c?.kind !== 'member' || ok(c.object) || /^[A-Z]/.test(c.object?.name ?? '')) && ok(n.args);
|
|
455
492
|
}
|
|
@@ -474,7 +511,9 @@ const KEYWORD_CALLEE = /^(?:use|unsafe|using|foreach|for|type|return|pub|public|
|
|
|
474
511
|
|
|
475
512
|
const coreOf = (e) => {
|
|
476
513
|
let c = e;
|
|
477
|
-
|
|
514
|
+
// (.NET: a get-or-add of a Lazy, `byKey.GetOrAdd(k, _ => new Lazy<T>(…)).Value`, gives the entry's value: the call is the core.)
|
|
515
|
+
while (c && ((c.kind === 'unary' && (c.op === 'await' || c.op === '?' || c.op === '!!')) || (c.kind === 'cast' && c.form === 'nonnull')
|
|
516
|
+
|| (c.kind === 'member' && c.property === 'Value' && c.object?.kind === 'call' && c.object.callee?.property === 'GetOrAdd'))) c = c.kind === 'member' ? c.object : c.value;
|
|
478
517
|
return c;
|
|
479
518
|
};
|
|
480
519
|
/** The names of the calls along a value's receiver chain: a.b().c() -> [b, c]. */
|
|
@@ -499,6 +538,22 @@ function chainCallees(e) {
|
|
|
499
538
|
return out;
|
|
500
539
|
}
|
|
501
540
|
const sameWords = (a, b) => splitWords(a).join('') === splitWords(b).join('');
|
|
541
|
+
/**
|
|
542
|
+
* The name a step gives a call: its own name, or (for a name that ends on a preposition, `changeApprovalFor`) its name
|
|
543
|
+
* followed by its first argument, which must be a name in the code ("change approval for x"), or its name without
|
|
544
|
+
* the preposition ("change approval"). See callWords in steps.mjs.
|
|
545
|
+
*/
|
|
546
|
+
const PREPOSITION_END = /(?:for|from|to|of|with|by|in|on|at|about|into|as|via)$/i;
|
|
547
|
+
function callNamed(callee, said, code) {
|
|
548
|
+
if (sameWords(callee, said)) return true;
|
|
549
|
+
const cw = splitWords(callee);
|
|
550
|
+
if (!cw.length || !PREPOSITION_END.test(cw[cw.length - 1])) return false;
|
|
551
|
+
const sw = splitWords(said);
|
|
552
|
+
if (sw.join('') === cw.slice(0, -1).join('')) return true;
|
|
553
|
+
if (sw.length <= cw.length || sw.slice(0, cw.length).join('') !== cw.join('')) return false;
|
|
554
|
+
const rest = sw.slice(cw.length).join('');
|
|
555
|
+
return splitWords(String(code)).some((w, i, all) => all.slice(i, i + sw.length - cw.length).join('') === rest);
|
|
556
|
+
}
|
|
502
557
|
|
|
503
558
|
/** Language keywords that begin the statement (the step's code). */
|
|
504
559
|
const leadingWord = (code) => (String(code).trim().match(/^[A-Za-z_]+/) || [''])[0];
|
|
@@ -684,31 +739,59 @@ function checkStep(step, ctx) {
|
|
|
684
739
|
for (let c = core; c && c.kind === 'call'; c = c.callee?.kind === 'member' ? coreOf(c.callee.object) : null) {
|
|
685
740
|
if (/^(?:add|push|append|insert|extend|concat|Add|AddRange|put|unshift|prepend|push_back|emplace_back|merge)$/.test(c.callee?.property ?? c.callee?.name ?? '')) { core = c; break; }
|
|
686
741
|
}
|
|
742
|
+
// An entry named by its fields ("an entry (title, rows, …)": each one a key of the object, in order) and a quoted
|
|
743
|
+
// text (its exact words are checked as values, above) say what is added without its inner values.
|
|
744
|
+
const entryNamed = (a) => {
|
|
745
|
+
if (a?.kind !== 'object') return false;
|
|
746
|
+
const keys = (a.entries || []).map((e) => (e.key?.kind === 'literal' ? String(e.key.value) : null));
|
|
747
|
+
if (/^an empty entry$/.test(adds[1])) return keys.length === 0;
|
|
748
|
+
if (/^an entry$/.test(adds[1])) return keys.length > 0;
|
|
749
|
+
const listed = /^an entry \(([^)]*)\)/.exec(adds[1]);
|
|
750
|
+
if (!listed) return false;
|
|
751
|
+
const named = listed[1].split(', ').filter((k) => k !== '…');
|
|
752
|
+
return named.length > 0 && named.every((k, i) => keys[i] != null && splitWords(keys[i]).join(' ') === splitWords(k).join(' '));
|
|
753
|
+
};
|
|
754
|
+
// (A quoted text may itself hold " to ", so the phrase may stop inside it: it starts with the quote.)
|
|
755
|
+
const textNamed = (a) => ((a?.kind === 'literal' && a.type === 'text') || a?.kind === 'template') && /^"/.test(adds[1]);
|
|
756
|
+
const kept = (a) => namesKept(a, adds[1]) || entryNamed(a) || textNamed(a) || /^several values$/.test(adds[1]);
|
|
687
757
|
if (tree.kind === 'assign' && tree.op !== '=' && tree.op !== ':=') { if (!namesKept(tree.value, adds[1])) return M('adds-value'); }
|
|
688
|
-
else if (core?.kind === 'call' && core.args?.length && !core.args.some(
|
|
758
|
+
else if (core?.kind === 'call' && core.args?.length && !core.args.some(kept)) return M('adds-value');
|
|
689
759
|
else if (core?.kind === 'call' && core.args?.some((a) => a.kind === 'index') && !core.args.every((a) => namesKept(a, adds[1]) || a.kind === 'name')) return M('adds-value');
|
|
690
760
|
}
|
|
691
761
|
// Calls, settings, and everything else: the words must not drop a negation, a comparison, or and/or in the tree.
|
|
692
762
|
if (/^Calls /.test(says)) return callKept(step, tree, says, code, lang);
|
|
693
763
|
if (tree) {
|
|
694
|
-
|
|
764
|
+
// ("Adds an entry (…)" and "Adds several values" name what is added, not the values inside it: summaries too.)
|
|
765
|
+
// (A quoted text whose «…» holds a worked-out value names that value as a placeholder only.)
|
|
766
|
+
const summary = /^(?:Works out|Calls|Runs|Defines|Creates|Writes|Adds to|Adds an entry\b|Adds an empty entry\b|Adds several values\b|Takes|Declares|Starts with|Makes|Stores the result of)\b| the result of |«…»/.test(says);
|
|
695
767
|
const neg = treeNegations(tree, summary), w = saidNegations(says);
|
|
696
|
-
if (w !== neg && !(w < neg && /^(?:Works out|Calls|Runs|Defines|Creates|Writes|Adds to|Takes|Declares|Starts with|Makes)\b/.test(says) && !/\b(?:whether|if|when)\b/.test(said))) return M('L320');
|
|
768
|
+
if (w !== neg && !(w < neg && (/^(?:Works out|Calls|Runs|Defines|Creates|Writes|Adds to|Adds an entry\b|Adds an empty entry\b|Adds several values\b|Takes|Declares|Starts with|Makes)\b/.test(says) || /«…»/.test(says)) && !/\b(?:whether|if|when)\b/.test(said))) return M('L320');
|
|
697
769
|
if (w > neg) return M('L321');
|
|
698
770
|
// A value stated in full ("Sets x to a plus b") must keep every operator; a summary ("Works out x from f") says
|
|
699
771
|
// only what it names, and the rest is one level down in Details.
|
|
700
772
|
if (/^Sets .+ to /.test(says)) {
|
|
701
773
|
const v = tree.kind === 'assign' ? tree.value : null;
|
|
702
774
|
if (v) {
|
|
703
|
-
|
|
775
|
+
// A slice said by its ends ("the first 3 of xs"): the exact phrase for this slice, with the list's own name.
|
|
776
|
+
const sl = sliceOf(v);
|
|
777
|
+
if (sl) { if (!sliceSaid(sl, says)) return M('L327s'); }
|
|
778
|
+
// A template said as its text with «…» for a value worked out inside it: the text is checked as exact (values
|
|
779
|
+
// and quoted text above); what is inside a «…» is one level down, as in any summary.
|
|
780
|
+
else if (v.kind === 'template' && /^Sets [^"]+ to "[^"]*«…»[^"]*"$/.test(says)) { /* summary */ }
|
|
781
|
+
else if (!newThing(v, says) && !namesKept(v, says)) return M('L327');
|
|
704
782
|
if (castCount(v) && !/\bas\b|\bcopy\b|\bconverted\b|\bturned\b/.test(said)) return M('L328');
|
|
705
783
|
if (!orderingKept(v, says)) return M('L329');
|
|
706
784
|
}
|
|
707
785
|
}
|
|
786
|
+
// Rust `let y = f(x)?;`: the words say it stops there when f fails (and only when the code has the ?).
|
|
787
|
+
if (lang === 'rust' && tree.kind === 'assign' && /^(?:Works out|Sets) /.test(says)) {
|
|
788
|
+
const q = tree.value?.kind === 'unary' && tree.value.op === '?';
|
|
789
|
+
if (q !== / and stops here if that fails$/.test(says)) return M('rust-q');
|
|
790
|
+
}
|
|
708
791
|
if (/^Works out (.+?) from (.+)$/.test(says) && tree.kind === 'assign') {
|
|
709
|
-
const m = /^Works out (.+?) from ([\w ]
|
|
792
|
+
const m = /^Works out (.+?) from ([\w ]+?)(?:, and stops here if that fails)?$/.exec(says);
|
|
710
793
|
const callees = chainCallees(tree.value);
|
|
711
|
-
if (m && callees.length && !callees.some((c) =>
|
|
794
|
+
if (m && callees.length && !callees.some((c) => callNamed(c, m[2], code))) return M('L335');
|
|
712
795
|
}
|
|
713
796
|
if (/\bif\b.*\botherwise\b/.test(said) && ![...nodesOf(tree)].some((n) => n.kind === 'conditional' || n.kind === 'if')) return WHY.form;
|
|
714
797
|
}
|
|
@@ -754,7 +837,8 @@ function conditionCore(test, says, code, lang) {
|
|
|
754
837
|
const said = claimText(says);
|
|
755
838
|
const tn = treeNegations(test), wn = saidNegations(says);
|
|
756
839
|
if (tn !== wn) return M('L378');
|
|
757
|
-
|
|
840
|
+
// (String.IsNullOrEmpty(x) asks "null, or empty": the "or" is in its name; see accountsFor.)
|
|
841
|
+
let logic = 0; for (const n of nodesOf(test)) if (n.kind === 'logic') logic += n.operands.length - 1; else if (n.kind === 'call' && /^IsNullOr(?:Empty|WhiteSpace)$/.test(n.callee?.property ?? '')) logic++;
|
|
758
842
|
const wl = (said.match(/\band\b|\bor\b/g) || []).length;
|
|
759
843
|
if (logic !== wl) return M('L381');
|
|
760
844
|
if (!orderingKept(test, says)) return M('L382');
|
|
@@ -835,6 +919,55 @@ function shellConditionKept(code, says) {
|
|
|
835
919
|
}
|
|
836
920
|
|
|
837
921
|
let ctx_full = '';
|
|
922
|
+
/** `xs[1:]` / `self.rows[-1]`: the list's path and the slice's words (sliceWords), or null. */
|
|
923
|
+
function sliceOf(v) {
|
|
924
|
+
if (v?.kind !== 'index' || currentLang !== 'python') return null;
|
|
925
|
+
const path = (n) => (n?.kind === 'name' ? n.name : n?.kind === 'member' ? (path(n.object) ? `${path(n.object)}.${n.property}` : null) : null);
|
|
926
|
+
const p = path(v.object);
|
|
927
|
+
const num = (x) => (x == null ? undefined : x.kind === 'literal' && x.type === 'number' ? String(x.raw ?? x.value) : x.kind === 'unary' && x.op === '-' && x.value?.kind === 'literal' ? `-${x.value.raw ?? x.value.value}` : NaN);
|
|
928
|
+
const ix = v.index;
|
|
929
|
+
let t = null;
|
|
930
|
+
if (ix?.kind === 'slice' && !ix.step) { const a = num(ix.start), b = num(ix.end); if (!Number.isNaN(a) && !Number.isNaN(b)) t = sliceWords(a, b); }
|
|
931
|
+
else if (ix) { const k = num(ix); if (k === '-1') t = sliceWords(undefined, undefined, '-1'); }
|
|
932
|
+
return p && t ? { path: p, words: t } : null;
|
|
933
|
+
}
|
|
934
|
+
function sliceSaid(sl, said) {
|
|
935
|
+
const [pre, post] = sl.words.split('{x}').map((x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
|
936
|
+
// (The value is everything after the first " to ": "Sets h to items without the first 1".)
|
|
937
|
+
const at = said.indexOf(' to ');
|
|
938
|
+
const m = at >= 0 && new RegExp(`^${pre}(?:the ([\\w ]+)'s )?([\\w ]+?)${post}$`).exec(said.slice(at + 4));
|
|
939
|
+
return !!m && pathSaid(sl.path, m[1], m[2]);
|
|
940
|
+
}
|
|
941
|
+
/** A plain path said as "the owner's last" (or just "last" with no owner other than self/this). */
|
|
942
|
+
function pathSaid(path, owner, last) {
|
|
943
|
+
const parts = String(path).split('.').filter((x) => !/^(?:self|this)$/.test(x));
|
|
944
|
+
if (!parts.length || !sameWords(parts[parts.length - 1], last)) return false;
|
|
945
|
+
return parts.length > 1 ? !!owner && sameWords(parts[parts.length - 2], owner) : !owner;
|
|
946
|
+
}
|
|
947
|
+
/** A Python `range(…)` loop's words: the counter, where it starts, and where it stops (the end itself not included). */
|
|
948
|
+
function pythonRangeKept(v, argText, says) {
|
|
949
|
+
const args = argText.split(',').map((x) => x.trim());
|
|
950
|
+
const tail = '(?: \\(\\d+ steps? inside\\))?$';
|
|
951
|
+
const P = "(?:the ([\\w ]+)'s )?([\\w ]+)";
|
|
952
|
+
let w;
|
|
953
|
+
if (args.length === 1 && v === '_') return new RegExp(`^Repeats ${args[0]} times${tail}`).test(says) && /^\w+$/.test(args[0]);
|
|
954
|
+
const len = args.length === 1 && /^len\(\s*([A-Za-z_][\w.]*)\s*\)$/.exec(args[0]);
|
|
955
|
+
if (len) return !!(w = new RegExp(`^For each position (.+?) in ${P}${tail}`).exec(says)) && sameWords(w[1], v) && pathSaid(len[1], w[2], w[3]);
|
|
956
|
+
// `range(a, n + 1)`: "Counts i from a to n" (n included).
|
|
957
|
+
if (args.length === 2 && /^[A-Za-z_][\w.]*\s*\+\s*1$/.test(args[1]) && /^(?:\d+|[A-Za-z_][\w.]*)$/.test(args[0])) {
|
|
958
|
+
w = new RegExp(`^Counts (.+?) from (.+?) to ${P}${tail}`).exec(says);
|
|
959
|
+
if (!w || !sameWords(w[1], v) || / up to /.test(says)) return false;
|
|
960
|
+
const from = /^\d+$/.test(args[0]) ? w[2] === args[0] : (() => { const p = new RegExp(`^${P}$`).exec(w[2]); return !!p && pathSaid(args[0], p[1], p[2]); })();
|
|
961
|
+
return from && pathSaid(args[1].replace(/\s*\+\s*1$/, ''), w[3], w[4]);
|
|
962
|
+
}
|
|
963
|
+
const [a, b] = args.length === 1 ? ['0', args[0]] : args;
|
|
964
|
+
if (args.length > 2 || !/^(?:\d+|[A-Za-z_][\w.]*)$/.test(a) || !/^(?:\d+|[A-Za-z_][\w.]*)$/.test(b)) return false;
|
|
965
|
+
if (/^\d+$/.test(a) && /^\d+$/.test(b)) return !!(w = new RegExp(`^Counts (.+?) from (\\d+) to (\\d+)${tail}`).exec(says)) && sameWords(w[1], v) && w[2] === a && Number(w[3]) === Number(b) - 1 && Number(b) > Number(a);
|
|
966
|
+
w = new RegExp(`^Counts (.+?) from (.+?) up to (.+?) \\(not (.+?) itself\\)${tail}`).exec(says);
|
|
967
|
+
if (!w || !sameWords(w[1], v) || w[3] !== w[4]) return false;
|
|
968
|
+
const side = (code, said) => { if (/^\d+$/.test(code)) return said === code; const p = new RegExp(`^${P}$`).exec(said); return !!p && pathSaid(code, p[1], p[2]); };
|
|
969
|
+
return side(a, w[2]) && side(b, w[3]);
|
|
970
|
+
}
|
|
838
971
|
/** "Repeats N times": N is in the code, with a repeat construct (`range(N)`, `N.times`, `repeat(N)`, `1..N`). */
|
|
839
972
|
function repeatsKept(says, full) {
|
|
840
973
|
const n = /^Repeats (\w+) times/.exec(says)[1];
|
|
@@ -853,6 +986,23 @@ function loopKept(step, tree, says, code, lang) {
|
|
|
853
986
|
if (/^Runs once, then repeats/.test(says)) return doWhileKept(says, ctx_full, lang);
|
|
854
987
|
if (/^Repeats (\w+) times/.test(says)) return repeatsKept(says, ctx_full) ? null : WHY.form;
|
|
855
988
|
if (/^`/.test(says) || /^Repeats (?:for|while) `/.test(says)) return null;
|
|
989
|
+
let m;
|
|
990
|
+
// Python counting loops, checked against their own code: range(N), range(a, b), range(len(xs)), enumerate(xs).
|
|
991
|
+
if (lang === 'python' && (m = /^for\s+(\w+)\s+in\s+range\((.*)\)\s*:$/.exec(String(code).trim()))) return pythonRangeKept(m[1], m[2], says) ? null : WHY.unparsed;
|
|
992
|
+
if (lang === 'python' && (m = /^for\s+\(?\s*(\w+)\s*,\s*(\w+)\s*\)?\s+in\s+enumerate\(\s*([A-Za-z_][\w.]*)\s*\)\s*:$/.exec(String(code).trim()))) {
|
|
993
|
+
const w = /^For each (.+?) in (?:the ([\w ]+)'s )?([\w ]+), with its position (.+?) \(from 0\)(?: \(\d+ steps? inside\))?$/.exec(says);
|
|
994
|
+
return w && sameWords(w[1], m[2]) && sameWords(w[4], m[1]) && pathSaid(m[3], w[2], w[3]) ? null : WHY.unparsed;
|
|
995
|
+
}
|
|
996
|
+
// Rust ranges: `for i in 0..n` "Counts i from 0 up to n (not n itself)", `a..=b` "from a to b".
|
|
997
|
+
if (lang === 'rust' && (m = /^for\s+(\w+)\s+in\s+(\d+|[A-Za-z_][\w.]*)\s*\.\.(=?)\s*(\d+|[A-Za-z_][\w.]*)\s*\{?$/.exec(String(code).trim()))) {
|
|
998
|
+
const [, v, a, inc, b] = m;
|
|
999
|
+
const P = "(?:the ([\\w ]+)'s )?([\\w ]+)";
|
|
1000
|
+
const side = (c, said) => { if (/^\d+$/.test(c)) return said === c; const p = new RegExp(`^${P}$`).exec(said); return !!p && pathSaid(c, p[1], p[2]); };
|
|
1001
|
+
const tail = '(?: \\(\\d+ steps? inside\\))?$';
|
|
1002
|
+
if (/^\d+$/.test(a) && /^\d+$/.test(b) && !inc) { const w = new RegExp(`^Counts (.+?) from (\\d+) to (\\d+)${tail}`).exec(says); return w && sameWords(w[1], v) && w[2] === a && Number(w[3]) === Number(b) - 1 ? null : WHY.unparsed; }
|
|
1003
|
+
const w = inc ? new RegExp(`^Counts (.+?) from (.+?) to (.+?)${tail}`).exec(says) : new RegExp(`^Counts (.+?) from (.+?) up to (.+?) \\(not (.+?) itself\\)${tail}`).exec(says);
|
|
1004
|
+
return w && sameWords(w[1], v) && (inc ? !/ up to /.test(says) : w[3] === w[4]) && side(a, w[2]) && side(b, w[3]) ? null : WHY.unparsed;
|
|
1005
|
+
}
|
|
856
1006
|
if (tree && tree.kind === 'loop') {
|
|
857
1007
|
if (tree.form === 'each') {
|
|
858
1008
|
const m = /^For each (.+?) in (.+?)(?:, only those where .*)?(?: \(\d+ steps? inside\))?$/.exec(says);
|
|
@@ -895,6 +1045,9 @@ function loopKept(step, tree, says, code, lang) {
|
|
|
895
1045
|
/** A loop's collection in words: every name in it, or the last name of its path (`order.items` as "items"), or its call. */
|
|
896
1046
|
function iterableKept(it, words) {
|
|
897
1047
|
if (!it) return false;
|
|
1048
|
+
// "the result of X": X is the call that gives the collection (the outermost one), not a call inside it.
|
|
1049
|
+
const ro = /^the result of ([\w ]+)$/.exec(words);
|
|
1050
|
+
if (ro) { const c = coreOf(it); const n = c?.kind === 'call' ? (c.callee.kind === 'member' ? c.callee.property : c.callee.name) : null; return !!n && sameWords(n, ro[1]); }
|
|
898
1051
|
if (namesKept(it, words)) return true;
|
|
899
1052
|
const w = ` ${splitWords(words).join(' ')} `;
|
|
900
1053
|
let c = coreOf(it);
|
|
@@ -992,6 +1145,8 @@ function safeForm(step, says, code, lang = '') {
|
|
|
992
1145
|
// `static MSG: &str = "never fail"` / `let x = 5`: "Sets msg to "never fail"".
|
|
993
1146
|
if ((m = /^(?:(?:let|const|static|var|val|final|readonly)\s+)?(?:mut\s+)?([A-Za-z_]\w*)\s*(?::[^=]+)?=\s*("(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?|true|false)\s*;?$/.exec(c)) && says === `Sets ${splitWords(m[1]).join(' ')} to ${m[2]}`) return null;
|
|
994
1147
|
if ((m = /^(?:(?:let|const|static|var|val)\s+)?(?:mut\s+)?([A-Za-z_]\w*)\s*(?::[^=]+)?=\s*(?:r#*)?"(?:\\.|[^"\\])*\\?$/.exec(c)) && says === `Sets ${splitWords(m[1]).join(' ')} to a text written over several lines`) return null;
|
|
1148
|
+
// A Python import inside a function: the words name every name it loads and the module, as written.
|
|
1149
|
+
if (lang === 'python' && /^(?:from|import)\s/.test(c)) return pythonImportSays(c) === says ? null : WHY.unparsed;
|
|
995
1150
|
// `const { a, b } = await import('./x')`: "Loads a, b from ./x".
|
|
996
1151
|
if ((m = /^(?:const|let|var)\s*\{([^}]*)\}\s*=\s*(?:await\s+)?(?:import|require)\(\s*['"`]([^'"`]+)['"`]\s*\)/.exec(c))) {
|
|
997
1152
|
const w = /^Loads (.+) from (\S+)$/.exec(says);
|
|
@@ -1037,7 +1192,7 @@ function safeForm(step, says, code, lang = '') {
|
|
|
1037
1192
|
if (!w || KEYWORD_CALLEE.test(lastName(m[2]))) return WHY.unparsed;
|
|
1038
1193
|
const tw = w[1].replace(/^the (?:[\w ]+?'s )?/, '');
|
|
1039
1194
|
if (!sameWords(target, tw) && !sameWords(m[1].replace(/->/g, '.'), w[1])) return WHY.unparsed;
|
|
1040
|
-
if (w[2] && !
|
|
1195
|
+
if (w[2] && !callNamed(lastName(m[2]), w[2], c)) return WHY.unparsed;
|
|
1041
1196
|
return null;
|
|
1042
1197
|
}
|
|
1043
1198
|
if (step.kind === 'return' && (m = /^return\s+(?:\([A-Za-z_][\w\s*]*\)\s*)?(?:await\s+)?([A-Za-z_][\w]*(?:\s*(?:\.|->|::)\s*[A-Za-z_][\w]*)*)\s*(\()?/.exec(c))) {
|