@skillstech/thunderlang 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +212 -0
  2. package/README.md +4 -1
  3. package/dist/core.cjs +2080 -278
  4. package/dist/index.cjs +12742 -10943
  5. package/dist/learn.cjs +12976 -3598
  6. package/package.json +2 -2
  7. package/src/cli-home.mjs +242 -0
  8. package/src/cli.mjs +135 -41
  9. package/src/core/ThunderRuntime.cs +1367 -0
  10. package/src/core/check.mjs +158 -2
  11. package/src/core/cli.mjs +208 -17
  12. package/src/core/csharp-run.mjs +184 -0
  13. package/src/core/diagnostics.mjs +13 -0
  14. package/src/core/engine-core.mjs +855 -0
  15. package/src/core/engine-values.mjs +1054 -0
  16. package/src/core/engine-worker.mjs +15 -0
  17. package/src/core/engine.mjs +63 -0
  18. package/src/core/format.mjs +191 -3
  19. package/src/core/go-run.mjs +106 -0
  20. package/src/core/index.mjs +3 -1
  21. package/src/core/java/thunder/T.java +6 -0
  22. package/src/core/java/thunder/ThunderRuntime.java +1374 -0
  23. package/src/core/java-run.mjs +89 -0
  24. package/src/core/parser.mjs +331 -5
  25. package/src/core/project.mjs +43 -8
  26. package/src/core/react-run.mjs +96 -0
  27. package/src/core/runtime-go/thunder_runtime.go +3038 -0
  28. package/src/core/runtime-react.mjs +133 -0
  29. package/src/core/runtime-typescript.mjs +119 -0
  30. package/src/core/rust/thunder_runtime.rs +1645 -0
  31. package/src/core/rust-run.mjs +192 -0
  32. package/src/core/screen-values.mjs +30 -0
  33. package/src/core/target-csharp.mjs +484 -0
  34. package/src/core/target-go.mjs +555 -0
  35. package/src/core/target-java.mjs +587 -0
  36. package/src/core/target-python.mjs +2 -1
  37. package/src/core/target-react.mjs +270 -0
  38. package/src/core/target-rust.mjs +534 -0
  39. package/src/core/target-typescript.mjs +466 -0
  40. package/src/core/typescript-run.mjs +114 -0
  41. package/src/core.d.ts +18 -0
  42. package/src/core.mjs +1 -0
  43. package/src/emit.mjs +1 -1
  44. package/src/faithful.mjs +30 -0
  45. package/src/learn-lessons.mjs +245 -1
  46. package/src/learn.d.mts +8 -0
  47. package/src/learn.mjs +40 -4
  48. package/src/libraries.mjs +10 -3
  49. package/src/model.mjs +50 -8
  50. package/src/read-level.mjs +192 -0
  51. package/src/read-repo-fs.mjs +3 -1
  52. package/src/read.mjs +28 -5
  53. package/src/replay-cli.mjs +123 -0
  54. package/src/say-less.mjs +152 -11
  55. package/src/screens.mjs +833 -0
  56. package/src/steps.mjs +430 -19
  57. package/src/term.mjs +132 -0
  58. package/src/try-cli.mjs +225 -0
  59. package/src/why-cli.mjs +17 -7
  60. package/src/why.d.mts +17 -7
  61. package/src/why.mjs +114 -33
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(`\\.\\.<\\s*${Number(n) + 1}\\b`).test(text)) return num;
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 === '%' && /[-+ #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; }
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
  }
@@ -440,12 +448,30 @@ function namesKept(tree, said) {
440
448
  // Calls that only walk a collection (`enumerate(xs)`, `d.items()`), or read an entry (`m.get(k)` as "the k entry in m").
441
449
  const own = c?.kind === 'member' && !(c.object?.kind === 'name' && /^[A-Z]/.test(c.object.name)) ? c.object : null;
442
450
  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);
451
+ // Rust `s.chars()` / `text.lines()` / `data.bytes()`: "the characters of s".
452
+ 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
453
  // C's string compare: `!strcmp(a, "x")` is "a is "x"".
444
454
  if (name && /^(?:str|strn|mem|wcs|wcsn)(?:case)?cmp$|^_?str(?:n)?icmp$/.test(name) && / is /.test(sw)) return ok(n.args);
445
455
  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);
456
+ // `d.get("k")` as "the "k" value from d"; `d.get("k", x)` as "…, or x if it has none" (the fallback said).
457
+ 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
458
  // "the result of X": the call is named, what it is given is one level down.
447
459
  if (name && has(name) && sw.includes(` result of ${splitWords(name).join(' ')} `)) return true;
448
460
  if (name && /^(?:new|New|create|of|from|make)$/.test(name) && / new /.test(sw) && c.kind === 'member') return ok(c.object);
461
+ // Everyday JavaScript calls said by what they give back (steps.mjs sayCommon): the words name every argument.
462
+ const onType = c?.kind === 'member' && c.object?.kind === 'name' ? c.object.name : null;
463
+ if (onType === 'Math' && /^(?:max|min)$/.test(name) && / (?:largest|smallest) /.test(sw)) return ok(n.args);
464
+ if (onType === 'Math' && /^(?:round|floor|ceil|abs|trunc)$/.test(name) && / (?:rounded|absolute|fraction) /.test(sw)) return ok(n.args);
465
+ if (onType === 'Date' && name === 'parse' && / time written /.test(sw)) return ok(n.args);
466
+ if (name === 'exec' && / first match of /.test(sw)) return ok(c.kind === 'member' ? c.object : null) && ok(n.args);
467
+ if (name === 'parse' && onType && /^[A-Z]/.test(onType) && / checked and read by /.test(sw) && has(onType)) return ok(n.args);
468
+ if (name === 'from' && onType && / made from /.test(sw)) return ok(n.args);
469
+ // Everyday Python: a list/tuple/set made from a value, sorted, reversed, and a position found with .index().
470
+ if (c?.kind === 'name' && /^(?:list|tuple)$/.test(name) && / as a (?:list|tuple) /.test(sw)) return ok(n.args);
471
+ if (c?.kind === 'name' && /^(?:set|frozenset)$/.test(name) && / different values in /.test(sw)) return ok(n.args);
472
+ if (c?.kind === 'name' && name === 'sorted' && / sorted /.test(sw)) return ok(n.args);
473
+ if (c?.kind === 'name' && name === 'reversed' && / reverse order /.test(sw)) return ok(n.args);
474
+ if (name === 'index' && c?.kind === 'member' && / position of /.test(sw)) return ok(c.object) && ok(n.args);
449
475
  // Questions about a collection said in words: "any item in xs matches", "every …", "the first … that matches".
450
476
  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
477
  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);
@@ -499,6 +525,22 @@ function chainCallees(e) {
499
525
  return out;
500
526
  }
501
527
  const sameWords = (a, b) => splitWords(a).join('') === splitWords(b).join('');
528
+ /**
529
+ * The name a step gives a call: its own name, or (for a name that ends on a preposition, `changeApprovalFor`) its name
530
+ * followed by its first argument, which must be a name in the code ("change approval for x"), or its name without
531
+ * the preposition ("change approval"). See callWords in steps.mjs.
532
+ */
533
+ const PREPOSITION_END = /(?:for|from|to|of|with|by|in|on|at|about|into|as|via)$/i;
534
+ function callNamed(callee, said, code) {
535
+ if (sameWords(callee, said)) return true;
536
+ const cw = splitWords(callee);
537
+ if (!cw.length || !PREPOSITION_END.test(cw[cw.length - 1])) return false;
538
+ const sw = splitWords(said);
539
+ if (sw.join('') === cw.slice(0, -1).join('')) return true;
540
+ if (sw.length <= cw.length || sw.slice(0, cw.length).join('') !== cw.join('')) return false;
541
+ const rest = sw.slice(cw.length).join('');
542
+ return splitWords(String(code)).some((w, i, all) => all.slice(i, i + sw.length - cw.length).join('') === rest);
543
+ }
502
544
 
503
545
  /** Language keywords that begin the statement (the step's code). */
504
546
  const leadingWord = (code) => (String(code).trim().match(/^[A-Za-z_]+/) || [''])[0];
@@ -684,31 +726,59 @@ function checkStep(step, ctx) {
684
726
  for (let c = core; c && c.kind === 'call'; c = c.callee?.kind === 'member' ? coreOf(c.callee.object) : null) {
685
727
  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
728
  }
729
+ // An entry named by its fields ("an entry (title, rows, …)": each one a key of the object, in order) and a quoted
730
+ // text (its exact words are checked as values, above) say what is added without its inner values.
731
+ const entryNamed = (a) => {
732
+ if (a?.kind !== 'object') return false;
733
+ const keys = (a.entries || []).map((e) => (e.key?.kind === 'literal' ? String(e.key.value) : null));
734
+ if (/^an empty entry$/.test(adds[1])) return keys.length === 0;
735
+ if (/^an entry$/.test(adds[1])) return keys.length > 0;
736
+ const listed = /^an entry \(([^)]*)\)/.exec(adds[1]);
737
+ if (!listed) return false;
738
+ const named = listed[1].split(', ').filter((k) => k !== '…');
739
+ return named.length > 0 && named.every((k, i) => keys[i] != null && splitWords(keys[i]).join(' ') === splitWords(k).join(' '));
740
+ };
741
+ // (A quoted text may itself hold " to ", so the phrase may stop inside it: it starts with the quote.)
742
+ const textNamed = (a) => ((a?.kind === 'literal' && a.type === 'text') || a?.kind === 'template') && /^"/.test(adds[1]);
743
+ const kept = (a) => namesKept(a, adds[1]) || entryNamed(a) || textNamed(a) || /^several values$/.test(adds[1]);
687
744
  if (tree.kind === 'assign' && tree.op !== '=' && tree.op !== ':=') { if (!namesKept(tree.value, adds[1])) return M('adds-value'); }
688
- else if (core?.kind === 'call' && core.args?.length && !core.args.some((a) => namesKept(a, adds[1]))) return M('adds-value');
745
+ else if (core?.kind === 'call' && core.args?.length && !core.args.some(kept)) return M('adds-value');
689
746
  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
747
  }
691
748
  // Calls, settings, and everything else: the words must not drop a negation, a comparison, or and/or in the tree.
692
749
  if (/^Calls /.test(says)) return callKept(step, tree, says, code, lang);
693
750
  if (tree) {
694
- const summary = /^(?:Works out|Calls|Runs|Defines|Creates|Writes|Adds to|Takes|Declares|Starts with|Makes|Stores the result of)\b| the result of /.test(says);
751
+ // ("Adds an entry (…)" and "Adds several values" name what is added, not the values inside it: summaries too.)
752
+ // (A quoted text whose «…» holds a worked-out value names that value as a placeholder only.)
753
+ 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
754
  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');
755
+ 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
756
  if (w > neg) return M('L321');
698
757
  // A value stated in full ("Sets x to a plus b") must keep every operator; a summary ("Works out x from f") says
699
758
  // only what it names, and the rest is one level down in Details.
700
759
  if (/^Sets .+ to /.test(says)) {
701
760
  const v = tree.kind === 'assign' ? tree.value : null;
702
761
  if (v) {
703
- if (!newThing(v, says) && !namesKept(v, says)) return M('L327');
762
+ // A slice said by its ends ("the first 3 of xs"): the exact phrase for this slice, with the list's own name.
763
+ const sl = sliceOf(v);
764
+ if (sl) { if (!sliceSaid(sl, says)) return M('L327s'); }
765
+ // A template said as its text with «…» for a value worked out inside it: the text is checked as exact (values
766
+ // and quoted text above); what is inside a «…» is one level down, as in any summary.
767
+ else if (v.kind === 'template' && /^Sets [^"]+ to "[^"]*«…»[^"]*"$/.test(says)) { /* summary */ }
768
+ else if (!newThing(v, says) && !namesKept(v, says)) return M('L327');
704
769
  if (castCount(v) && !/\bas\b|\bcopy\b|\bconverted\b|\bturned\b/.test(said)) return M('L328');
705
770
  if (!orderingKept(v, says)) return M('L329');
706
771
  }
707
772
  }
773
+ // Rust `let y = f(x)?;`: the words say it stops there when f fails (and only when the code has the ?).
774
+ if (lang === 'rust' && tree.kind === 'assign' && /^(?:Works out|Sets) /.test(says)) {
775
+ const q = tree.value?.kind === 'unary' && tree.value.op === '?';
776
+ if (q !== / and stops here if that fails$/.test(says)) return M('rust-q');
777
+ }
708
778
  if (/^Works out (.+?) from (.+)$/.test(says) && tree.kind === 'assign') {
709
- const m = /^Works out (.+?) from ([\w ]+)$/.exec(says);
779
+ const m = /^Works out (.+?) from ([\w ]+?)(?:, and stops here if that fails)?$/.exec(says);
710
780
  const callees = chainCallees(tree.value);
711
- if (m && callees.length && !callees.some((c) => sameWords(c, m[2]))) return M('L335');
781
+ if (m && callees.length && !callees.some((c) => callNamed(c, m[2], code))) return M('L335');
712
782
  }
713
783
  if (/\bif\b.*\botherwise\b/.test(said) && ![...nodesOf(tree)].some((n) => n.kind === 'conditional' || n.kind === 'if')) return WHY.form;
714
784
  }
@@ -835,6 +905,55 @@ function shellConditionKept(code, says) {
835
905
  }
836
906
 
837
907
  let ctx_full = '';
908
+ /** `xs[1:]` / `self.rows[-1]`: the list's path and the slice's words (sliceWords), or null. */
909
+ function sliceOf(v) {
910
+ if (v?.kind !== 'index' || currentLang !== 'python') return null;
911
+ const path = (n) => (n?.kind === 'name' ? n.name : n?.kind === 'member' ? (path(n.object) ? `${path(n.object)}.${n.property}` : null) : null);
912
+ const p = path(v.object);
913
+ 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);
914
+ const ix = v.index;
915
+ let t = null;
916
+ 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); }
917
+ else if (ix) { const k = num(ix); if (k === '-1') t = sliceWords(undefined, undefined, '-1'); }
918
+ return p && t ? { path: p, words: t } : null;
919
+ }
920
+ function sliceSaid(sl, said) {
921
+ const [pre, post] = sl.words.split('{x}').map((x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
922
+ // (The value is everything after the first " to ": "Sets h to items without the first 1".)
923
+ const at = said.indexOf(' to ');
924
+ const m = at >= 0 && new RegExp(`^${pre}(?:the ([\\w ]+)'s )?([\\w ]+?)${post}$`).exec(said.slice(at + 4));
925
+ return !!m && pathSaid(sl.path, m[1], m[2]);
926
+ }
927
+ /** A plain path said as "the owner's last" (or just "last" with no owner other than self/this). */
928
+ function pathSaid(path, owner, last) {
929
+ const parts = String(path).split('.').filter((x) => !/^(?:self|this)$/.test(x));
930
+ if (!parts.length || !sameWords(parts[parts.length - 1], last)) return false;
931
+ return parts.length > 1 ? !!owner && sameWords(parts[parts.length - 2], owner) : !owner;
932
+ }
933
+ /** A Python `range(…)` loop's words: the counter, where it starts, and where it stops (the end itself not included). */
934
+ function pythonRangeKept(v, argText, says) {
935
+ const args = argText.split(',').map((x) => x.trim());
936
+ const tail = '(?: \\(\\d+ steps? inside\\))?$';
937
+ const P = "(?:the ([\\w ]+)'s )?([\\w ]+)";
938
+ let w;
939
+ if (args.length === 1 && v === '_') return new RegExp(`^Repeats ${args[0]} times${tail}`).test(says) && /^\w+$/.test(args[0]);
940
+ const len = args.length === 1 && /^len\(\s*([A-Za-z_][\w.]*)\s*\)$/.exec(args[0]);
941
+ 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]);
942
+ // `range(a, n + 1)`: "Counts i from a to n" (n included).
943
+ if (args.length === 2 && /^[A-Za-z_][\w.]*\s*\+\s*1$/.test(args[1]) && /^(?:\d+|[A-Za-z_][\w.]*)$/.test(args[0])) {
944
+ w = new RegExp(`^Counts (.+?) from (.+?) to ${P}${tail}`).exec(says);
945
+ if (!w || !sameWords(w[1], v) || / up to /.test(says)) return false;
946
+ 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]); })();
947
+ return from && pathSaid(args[1].replace(/\s*\+\s*1$/, ''), w[3], w[4]);
948
+ }
949
+ const [a, b] = args.length === 1 ? ['0', args[0]] : args;
950
+ if (args.length > 2 || !/^(?:\d+|[A-Za-z_][\w.]*)$/.test(a) || !/^(?:\d+|[A-Za-z_][\w.]*)$/.test(b)) return false;
951
+ 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);
952
+ w = new RegExp(`^Counts (.+?) from (.+?) up to (.+?) \\(not (.+?) itself\\)${tail}`).exec(says);
953
+ if (!w || !sameWords(w[1], v) || w[3] !== w[4]) return false;
954
+ 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]); };
955
+ return side(a, w[2]) && side(b, w[3]);
956
+ }
838
957
  /** "Repeats N times": N is in the code, with a repeat construct (`range(N)`, `N.times`, `repeat(N)`, `1..N`). */
839
958
  function repeatsKept(says, full) {
840
959
  const n = /^Repeats (\w+) times/.exec(says)[1];
@@ -853,6 +972,23 @@ function loopKept(step, tree, says, code, lang) {
853
972
  if (/^Runs once, then repeats/.test(says)) return doWhileKept(says, ctx_full, lang);
854
973
  if (/^Repeats (\w+) times/.test(says)) return repeatsKept(says, ctx_full) ? null : WHY.form;
855
974
  if (/^`/.test(says) || /^Repeats (?:for|while) `/.test(says)) return null;
975
+ let m;
976
+ // Python counting loops, checked against their own code: range(N), range(a, b), range(len(xs)), enumerate(xs).
977
+ 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;
978
+ 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()))) {
979
+ const w = /^For each (.+?) in (?:the ([\w ]+)'s )?([\w ]+), with its position (.+?) \(from 0\)(?: \(\d+ steps? inside\))?$/.exec(says);
980
+ return w && sameWords(w[1], m[2]) && sameWords(w[4], m[1]) && pathSaid(m[3], w[2], w[3]) ? null : WHY.unparsed;
981
+ }
982
+ // Rust ranges: `for i in 0..n` "Counts i from 0 up to n (not n itself)", `a..=b` "from a to b".
983
+ 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()))) {
984
+ const [, v, a, inc, b] = m;
985
+ const P = "(?:the ([\\w ]+)'s )?([\\w ]+)";
986
+ 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]); };
987
+ const tail = '(?: \\(\\d+ steps? inside\\))?$';
988
+ 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; }
989
+ const w = inc ? new RegExp(`^Counts (.+?) from (.+?) to (.+?)${tail}`).exec(says) : new RegExp(`^Counts (.+?) from (.+?) up to (.+?) \\(not (.+?) itself\\)${tail}`).exec(says);
990
+ 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;
991
+ }
856
992
  if (tree && tree.kind === 'loop') {
857
993
  if (tree.form === 'each') {
858
994
  const m = /^For each (.+?) in (.+?)(?:, only those where .*)?(?: \(\d+ steps? inside\))?$/.exec(says);
@@ -895,6 +1031,9 @@ function loopKept(step, tree, says, code, lang) {
895
1031
  /** 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
1032
  function iterableKept(it, words) {
897
1033
  if (!it) return false;
1034
+ // "the result of X": X is the call that gives the collection (the outermost one), not a call inside it.
1035
+ const ro = /^the result of ([\w ]+)$/.exec(words);
1036
+ 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
1037
  if (namesKept(it, words)) return true;
899
1038
  const w = ` ${splitWords(words).join(' ')} `;
900
1039
  let c = coreOf(it);
@@ -992,6 +1131,8 @@ function safeForm(step, says, code, lang = '') {
992
1131
  // `static MSG: &str = "never fail"` / `let x = 5`: "Sets msg to "never fail"".
993
1132
  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
1133
  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;
1134
+ // A Python import inside a function: the words name every name it loads and the module, as written.
1135
+ if (lang === 'python' && /^(?:from|import)\s/.test(c)) return pythonImportSays(c) === says ? null : WHY.unparsed;
995
1136
  // `const { a, b } = await import('./x')`: "Loads a, b from ./x".
996
1137
  if ((m = /^(?:const|let|var)\s*\{([^}]*)\}\s*=\s*(?:await\s+)?(?:import|require)\(\s*['"`]([^'"`]+)['"`]\s*\)/.exec(c))) {
997
1138
  const w = /^Loads (.+) from (\S+)$/.exec(says);
@@ -1037,7 +1178,7 @@ function safeForm(step, says, code, lang = '') {
1037
1178
  if (!w || KEYWORD_CALLEE.test(lastName(m[2]))) return WHY.unparsed;
1038
1179
  const tw = w[1].replace(/^the (?:[\w ]+?'s )?/, '');
1039
1180
  if (!sameWords(target, tw) && !sameWords(m[1].replace(/->/g, '.'), w[1])) return WHY.unparsed;
1040
- if (w[2] && !sameWords(lastName(m[2]), w[2])) return WHY.unparsed;
1181
+ if (w[2] && !callNamed(lastName(m[2]), w[2], c)) return WHY.unparsed;
1041
1182
  return null;
1042
1183
  }
1043
1184
  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))) {