@skillstech/thunderlang 1.0.3 → 1.1.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 (74) hide show
  1. package/CHANGELOG.md +207 -0
  2. package/dist/core.cjs +13779 -10043
  3. package/dist/index.cjs +28500 -24392
  4. package/dist/learn.cjs +12853 -9579
  5. package/intent-graph.schema.json +11 -0
  6. package/package.json +6 -2
  7. package/src/cli.mjs +141 -58
  8. package/src/codegen.mjs +145 -55
  9. package/src/conformance.mjs +15 -6
  10. package/src/core/check.mjs +725 -0
  11. package/src/core/cli.mjs +133 -0
  12. package/src/core/diagnostics.mjs +81 -0
  13. package/src/core/format.mjs +20 -0
  14. package/src/core/from-python.mjs +645 -0
  15. package/src/core/index.mjs +38 -0
  16. package/src/core/lexer.mjs +115 -0
  17. package/src/core/parser.mjs +742 -0
  18. package/src/core/project.mjs +167 -0
  19. package/src/core/round-trip.mjs +150 -0
  20. package/src/core/runtime-python.mjs +801 -0
  21. package/src/core/target-python.mjs +486 -0
  22. package/src/core.d.ts +5 -2
  23. package/src/core.mjs +5 -2
  24. package/src/data-schema.mjs +8 -1
  25. package/src/emit.mjs +1 -1
  26. package/src/evidence.mjs +1 -1
  27. package/src/expr.mjs +81 -4
  28. package/src/form-words.mjs +2 -0
  29. package/src/index.d.ts +8 -1
  30. package/src/index.mjs +5 -1
  31. package/src/intent-schema.mjs +1 -0
  32. package/src/libraries.mjs +2 -2
  33. package/src/mcp.mjs +23 -0
  34. package/src/meaning.mjs +47 -7
  35. package/src/model.d.mts +7 -3
  36. package/src/model.mjs +30 -9
  37. package/src/money.d.mts +18 -0
  38. package/src/money.mjs +124 -0
  39. package/src/plain-contract.mjs +18 -2
  40. package/src/powershell.mjs +24 -5
  41. package/src/read-repo.mjs +1 -0
  42. package/src/read.d.mts +11 -0
  43. package/src/read.mjs +121 -13
  44. package/src/review-comment.d.mts +16 -0
  45. package/src/review-comment.mjs +145 -0
  46. package/src/rlang.mjs +10 -3
  47. package/src/say-less.mjs +1432 -0
  48. package/src/shell.mjs +45 -8
  49. package/src/sql-proc.mjs +1198 -0
  50. package/src/sql.mjs +87 -119
  51. package/src/steps.mjs +188 -37
  52. package/src/system.mjs +153 -44
  53. package/src/target-cs.mjs +39 -34
  54. package/src/target-elixir.mjs +40 -30
  55. package/src/target-go.mjs +41 -36
  56. package/src/target-java.mjs +34 -27
  57. package/src/target-kotlin.mjs +43 -35
  58. package/src/target-py.mjs +57 -55
  59. package/src/target-result.d.mts +48 -0
  60. package/src/target-result.mjs +112 -0
  61. package/src/target-rust.mjs +42 -38
  62. package/src/target-scala.mjs +45 -35
  63. package/src/target-ts.mjs +37 -45
  64. package/src/target-types.mjs +41 -5
  65. package/src/target-util.mjs +55 -2
  66. package/src/trace-cli.mjs +58 -0
  67. package/src/trace-fs.mjs +76 -0
  68. package/src/trace.mjs +261 -0
  69. package/src/translate.d.mts +3 -0
  70. package/src/translate.mjs +62 -32
  71. package/src/why-cli.mjs +31 -0
  72. package/src/why.d.mts +28 -0
  73. package/src/why.mjs +532 -0
  74. package/src/write-steps.mjs +22 -5
@@ -0,0 +1,18 @@
1
+ /** Thunder Money: an exact decimal amount in minor units, never binary floating point. */
2
+ export class MoneyError extends Error {}
3
+ export const MONEY_DEFAULT_MINOR_UNITS: 2;
4
+ /** Minor units for an ISO 4217 code (2 when unknown or absent): JPY 0, USD 2, KWD 3. */
5
+ export function minorUnitsFor(currency?: string | null): number;
6
+ /** Minor units when `type` is `Money` or `Money(XXX)`, else null. */
7
+ export function moneyTypeMinorUnits(type: string): number | null;
8
+ /** Parse "12.30" (or "$12.30" with allowDollar) to exact minor units. Extra precision throws; nothing is rounded. */
9
+ export function parseMoney(text: string | number, opts?: { minorUnits?: number; allowDollar?: boolean }): bigint;
10
+ /** Render minor units as a decimal string with exactly `minorUnits` places. */
11
+ export function formatMoney(minor: bigint | number, opts?: { minorUnits?: number }): string;
12
+ /** Round half up (a half goes away from zero, as in Thunder Core) to `minorUnits` places. Use only where a spec asks for rounding. */
13
+ export function roundHalfUp(text: string | number, opts?: { minorUnits?: number }): bigint;
14
+ export function numberToDecimalText(n: number): string;
15
+ /** The exact Money literal for a target dialect, or null when the target has none wired up. */
16
+ export function moneyLiteral(dialect: string, text: string | number, minorUnits?: number): string | null;
17
+ export const MONEY_TYPES: Record<string, string>;
18
+ export function moneyCompare(dialect: string, op: string, a: string, b: string): string;
package/src/money.mjs ADDED
@@ -0,0 +1,124 @@
1
+ // Thunder Money: an exact decimal amount, never binary floating point. Browser-safe, no deps.
2
+ //
3
+ // Semantics (see docs/spec.md, "Money"):
4
+ // - A Money value is a decimal with a fixed number of minor units: 2 by default (cents), or the
5
+ // currency's own when the type names one (Money(JPY) has 0, Money(KWD) has 3).
6
+ // - Parsing is string-exact. An amount with more decimal places than the minor units is an error,
7
+ // never silently rounded. Rounding happens only where a spec explicitly asks for it, and then it
8
+ // is round half up, a half going away from zero (roundHalfUp below), the same rule as Thunder Core's
9
+ // `round`: 2.345 is 2.35, -2.345 is -2.35.
10
+ // - Each target uses an exact representation: TypeScript/JavaScript bigint minor units, Python
11
+ // decimal.Decimal, Java java.math.BigDecimal, C# decimal, Go int64 minor units, Rust i64 minor
12
+ // units. A target with no exact representation wired up refuses (IL-GEN-001), it never falls back
13
+ // to a float.
14
+
15
+ export class MoneyError extends Error {}
16
+
17
+ export const MONEY_DEFAULT_MINOR_UNITS = 2;
18
+
19
+ // ISO 4217 currencies whose minor units differ from 2. Everything else uses 2.
20
+ const MINOR_UNITS = {
21
+ BIF: 0, CLP: 0, DJF: 0, GNF: 0, ISK: 0, JPY: 0, KMF: 0, KRW: 0, PYG: 0, RWF: 0, UGX: 0,
22
+ UYI: 0, VND: 0, VUV: 0, XAF: 0, XOF: 0, XPF: 0,
23
+ BHD: 3, IQD: 3, JOD: 3, KWD: 3, LYD: 3, OMR: 3, TND: 3,
24
+ CLF: 4, UYW: 4,
25
+ };
26
+
27
+ /** Minor units for a currency code (2 when unknown or absent). */
28
+ export function minorUnitsFor(currency) {
29
+ if (!currency) return MONEY_DEFAULT_MINOR_UNITS;
30
+ const code = String(currency).trim().toUpperCase();
31
+ return Object.prototype.hasOwnProperty.call(MINOR_UNITS, code) ? MINOR_UNITS[code] : MONEY_DEFAULT_MINOR_UNITS;
32
+ }
33
+
34
+ /** If `type` is a Money type (`Money`, `Money(USD)`), its minor units; otherwise null. */
35
+ export function moneyTypeMinorUnits(type) {
36
+ const m = String(type ?? '').trim().match(/^Money(?:\s*\(\s*([A-Za-z]{3})\s*\))?$/);
37
+ return m ? minorUnitsFor(m[1]) : null;
38
+ }
39
+
40
+ const DECIMAL = /^([+-])?(\d+)(?:\.(\d+))?$/;
41
+
42
+ /**
43
+ * Parse a decimal amount ("12.30", "-0.1", "$1,234.5" with allowDollar) into exact minor units.
44
+ * Returns a bigint. Throws MoneyError for anything that is not an exact amount at these minor units.
45
+ */
46
+ export function parseMoney(text, { minorUnits = MONEY_DEFAULT_MINOR_UNITS, allowDollar = false } = {}) {
47
+ let t = typeof text === 'number' ? numberToDecimalText(text) : String(text ?? '').trim();
48
+ if (allowDollar) {
49
+ const d = t.replace(/,/g, '').match(/^(-?)\$(-?)(\d+(?:\.\d+)?)$/);
50
+ if (d) t = `${d[1] || d[2] ? '-' : ''}${d[3]}`;
51
+ }
52
+ const m = t.match(DECIMAL);
53
+ if (!m) throw new MoneyError(`"${text}" is not an amount. Write digits with an optional decimal point, such as 12.30.`);
54
+ const frac = m[3] || '';
55
+ const extra = frac.slice(minorUnits);
56
+ if (/[1-9]/.test(extra)) throw new MoneyError(`${t} has more decimal places than Money's ${minorUnits} minor unit${minorUnits === 1 ? '' : 's'}; Thunder will not round it silently.`);
57
+ const minor = BigInt(m[2] + frac.slice(0, minorUnits).padEnd(minorUnits, '0'));
58
+ return m[1] === '-' ? -minor : minor;
59
+ }
60
+
61
+ /** Render exact minor units as a decimal string with exactly `minorUnits` places ("12.30"). */
62
+ export function formatMoney(minor, { minorUnits = MONEY_DEFAULT_MINOR_UNITS } = {}) {
63
+ const v = BigInt(minor);
64
+ const neg = v < 0n;
65
+ const digits = (neg ? -v : v).toString().padStart(minorUnits + 1, '0');
66
+ const whole = minorUnits ? digits.slice(0, -minorUnits) : digits;
67
+ const frac = minorUnits ? `.${digits.slice(-minorUnits)}` : '';
68
+ return `${neg ? '-' : ''}${whole}${frac}`;
69
+ }
70
+
71
+ /**
72
+ * Round a decimal string to `minorUnits` places, half up: a half goes away from zero (2.345 is 2.35, -2.345 is
73
+ * -2.35), the rule people learn in school and the one Thunder Core's `round` uses in every target.
74
+ * Use only where a spec explicitly asks for rounding. Returns exact minor units (bigint).
75
+ */
76
+ export function roundHalfUp(text, { minorUnits = MONEY_DEFAULT_MINOR_UNITS } = {}) {
77
+ const t = typeof text === 'number' ? numberToDecimalText(text) : String(text).trim();
78
+ const m = t.match(DECIMAL);
79
+ if (!m) throw new MoneyError(`"${text}" is not an amount.`);
80
+ const frac = m[3] || '';
81
+ let minor = BigInt(m[2] + frac.slice(0, minorUnits).padEnd(minorUnits, '0'));
82
+ const rest = frac.slice(minorUnits);
83
+ if (rest && rest[0] >= '5') minor += 1n; // the magnitude rounds up; the sign is put back after
84
+ return m[1] === '-' ? -minor : minor;
85
+ }
86
+
87
+ /** A JS number as plain decimal text, refusing exponent forms that cannot be an exact amount. */
88
+ export function numberToDecimalText(n) {
89
+ if (typeof n !== 'number' || !Number.isFinite(n)) throw new MoneyError(`${n} is not a finite amount.`);
90
+ const s = String(n);
91
+ if (/e/i.test(s)) throw new MoneyError(`${s} is too large or too small to be an exact amount.`);
92
+ return s;
93
+ }
94
+
95
+ /**
96
+ * The exact Money literal for a target, from decimal text. `dialect` matches expr.mjs dialect names.
97
+ * Returns null when the target has no exact Money representation wired up.
98
+ */
99
+ export function moneyLiteral(dialect, text, minorUnits = MONEY_DEFAULT_MINOR_UNITS) {
100
+ const minor = parseMoney(text, { minorUnits });
101
+ const dec = formatMoney(minor, { minorUnits });
102
+ switch (dialect) {
103
+ case 'js': return `${minor}n`;
104
+ case 'python': return `Decimal(${JSON.stringify(dec)})`;
105
+ case 'csharp': return `${dec}m`;
106
+ case 'java': return `new java.math.BigDecimal(${JSON.stringify(dec)})`;
107
+ case 'go': return `int64(${minor})`;
108
+ case 'rust': return `${minor}i64`;
109
+ default: return null;
110
+ }
111
+ }
112
+
113
+ /** Exact Money type per target dialect (null when the target has none wired up). */
114
+ export const MONEY_TYPES = {
115
+ js: 'bigint', python: 'Decimal', csharp: 'decimal', java: 'java.math.BigDecimal', go: 'int64', rust: 'i64',
116
+ };
117
+
118
+ /** Render a Money comparison for a dialect from already-rendered operands. */
119
+ export function moneyCompare(dialect, op, a, b) {
120
+ if (dialect === 'java') return `(${a}.compareTo(${b}) ${op} 0)`;
121
+ if (dialect === 'js' && op === '==') return `(${a} === ${b})`;
122
+ if (dialect === 'js' && op === '!=') return `(${a} !== ${b})`;
123
+ return `(${a} ${op} ${b})`;
124
+ }
@@ -7,6 +7,7 @@ import { parseIntent } from './parse.mjs';
7
7
  import { compileExpr } from './expr.mjs';
8
8
  import { runTests } from './testing.mjs';
9
9
  import { evaluateDecision } from './runtime.mjs';
10
+ import { parseMoney, formatMoney, MoneyError } from './money.mjs';
10
11
 
11
12
  export const PLAIN_SCHEMA = 'thunder-plain-v1';
12
13
 
@@ -33,16 +34,31 @@ const RESERVED = new Set(['and', 'or', 'not', 'in', 'true', 'false', 'case', 'ex
33
34
  export function formatValue(input, value) {
34
35
  if (input.kind === 'yesno') return value ? input.yes : input.no;
35
36
  if (input.kind === 'text') return value === '' ? 'empty' : JSON.stringify(String(value));
36
- if (input.kind === 'dollars') return `${value < 0 ? '-' : ''}$${Math.abs(value)}`;
37
+ if (input.kind === 'dollars') return `${value < 0 ? '-' : ''}$${dollarText(Math.abs(value))}`;
37
38
  return String(value);
38
39
  }
39
40
 
41
+ // Dollars read exactly from cents: $12.30 (not $12.3), whole dollars stay $100.
42
+ function dollarText(value) {
43
+ try {
44
+ const minor = parseMoney(value);
45
+ return minor % 100n === 0n ? String(minor / 100n) : formatMoney(minor);
46
+ } catch { return String(value); }
47
+ }
48
+
40
49
  function parseNumber(text, input, line) {
41
50
  const t = text.trim().replace(/,/g, '');
42
51
  const dollars = t.match(/^(-?)\$(-?)(\d+(?:\.\d+)?)$/);
43
52
  if (input.kind === 'dollars') {
44
53
  if (!dollars) fail(line, `${input.label} is in dollars. Write an amount such as $100.`);
45
- return Number(`${dollars[1] || dollars[2] ? '-' : ''}${dollars[3]}`);
54
+ // Thunder Money: the amount is read as exact cents from its text (never through a float), and an
55
+ // amount finer than a cent is an error instead of being rounded. The decision engine then
56
+ // compares the amount at cent precision, where every comparison is exact.
57
+ let minor;
58
+ try { minor = parseMoney(t, { allowDollar: true }); }
59
+ catch (e) { if (e instanceof MoneyError) fail(line, `${input.label} is in dollars and cents. ${t} is finer than a cent; write at most two decimal places, such as $12.30.`); throw e; }
60
+ if (minor > BigInt(Number.MAX_SAFE_INTEGER) || -minor > BigInt(Number.MAX_SAFE_INTEGER)) fail(line, `${t} is too large to compare exactly.`);
61
+ return Number(formatMoney(minor));
46
62
  }
47
63
  if (dollars) fail(line, `${input.label} is a plain number, not dollars. Write it without $.`);
48
64
  if (!/^-?\d+(?:\.\d+)?$/.test(t)) fail(line, `Write a number for ${input.label}, such as 18.`);
@@ -35,6 +35,8 @@ function skipParen(s, i) {
35
35
  let d = 0;
36
36
  for (let j = i; j < s.length; j++) {
37
37
  const c = s[j];
38
+ // (A backtick escapes the next character, as in `"Apps$(if($q) { `" matching`"})"`.)
39
+ if (c === '`') { j++; continue; }
38
40
  if (c === "'" || c === '"') { j = skipString(s, j) - 1; continue; }
39
41
  if (c === '(') d++;
40
42
  else if (c === ')' && --d === 0) return j + 1;
@@ -205,7 +207,8 @@ function singleInsert(tok) {
205
207
  }
206
208
  /** A message: quoted text as it is; any other value in words, never inside quotes it does not have. */
207
209
  const messageOf = (v) => (v == null || v === '' ? '' : v);
208
- const quoteText = (t) => `"${t.length > 100 ? `${t.slice(0, 99)}…` : t}"`;
210
+ // (Shortened only between placeholders: a «value» is never cut in half.)
211
+ const quoteText = (t) => { if (t.length <= 100) return `"${t}"`; let cut = 99; const open = t.lastIndexOf('«', cut); if (open >= 0 && t.indexOf('»', open) >= cut) cut = open; return `"${t.slice(0, cut)}…"`; };
209
212
 
210
213
  const at0 = (toks) => toks.filter((t) => t.t !== 'nl' && t.t !== 'comment');
211
214
  /** Tokens grouped at the top level: each item is one token, or a bracket with everything inside it. */
@@ -251,9 +254,10 @@ function sayValue(toks, plain = false) {
251
254
  if (g.length === 1 && first.length > 1) {
252
255
  const open = first[0].text;
253
256
  const inner = first.slice(1, -1);
254
- if (open === '@(') return inner.length ? `the list ${listWords(splitCommas(inner).map((x) => sayValue(x) ?? 'a value').slice(0, 6))}` : 'an empty list';
257
+ // (Every item is counted: a list said with fewer items than it has would be a different list.)
258
+ if (open === '@(') { if (!inner.length) return 'an empty list'; const items = splitCommas(inner).map((x) => sayValue(x) ?? 'a value'); if (items.length === 1 && items[0] === 'a value') return 'a list of what the commands inside give'; return items.length > 6 ? `a list of ${items.length} items: ${items.slice(0, 5).join(', ')}, and ${items.length - 5} more` : `the list ${listWords(items)}`; }
255
259
  if (open === '{') return 'a set of steps to run later (a script block)';
256
- if (open === '@{') { const keys = at0(inner).filter((t, k, a) => (t.t === 'word' || t.t === 'str') && a[k + 1]?.text === '=').map((t) => words(t.t === 'str' ? t.body : t.text)); return keys.length ? `a table of ${listWords(keys.slice(0, 6))}` : 'an empty table'; }
260
+ if (open === '@{') { const ks = groups(at0(inner)).map((g) => g[0]).filter((t, k, a) => (t.t === 'word' || t.t === 'str' || t.t === 'var') && a[k + 1]?.text === '=').map((t) => (t.t === 'var' ? `the key in ${varWords(t.name)}` : words(t.t === 'str' ? t.body : t.text))); const keys = ks.length > 6 ? [...ks.slice(0, 5), `${ks.length - 5} more`] : ks; return keys.length ? `a table of ${listWords(keys)}` : at0(inner).some((t) => t.t !== 'nl' && t.t !== 'comment') ? 'a table' : 'an empty table'; }
257
261
  if ((open === '(' || open === '$(') && first[0].match != null) {
258
262
  const all = first[0].all;
259
263
  const st = splitStatements(all, first[0].i + 1, first[0].match);
@@ -328,7 +332,8 @@ function sayValue(toks, plain = false) {
328
332
  }
329
333
  // Several values separated by commas are a list.
330
334
  if (g.some((x) => x.length === 1 && x[0].text === ',')) { const items = splitCommas(toks).map((x) => sayValue(x, true)); if (items.every(Boolean)) return `the list ${listWords(items.slice(0, 6))}${items.length > 6 ? ', …' : ''}`; }
331
- if (!plain && g.some((x) => x.length === 1 && x[0].t === 'op')) { const c = condWords(toks, false); if (c) return `whether ${c}`; }
335
+ // (A pipeline is the values it gives: `-Match` after `Where-Object` is that command's switch, not a yes/no.)
336
+ if (!plain && !g.some((x) => x.length === 1 && x[0].text === '|') && g.some((x) => x.length === 1 && x[0].t === 'op')) { const c = condWords(toks, false); if (c) return `whether ${c}`; }
332
337
  const cmd = toks[0].t === 'word' || toks[0].text === '&' ? pipelineWords(toks) : null;
333
338
  if (cmd?.command) return `the result of ${gerund(cmd.says)}`;
334
339
  return null;
@@ -653,6 +658,19 @@ function pipelineWords(toks) {
653
658
  const lower = name.toLowerCase();
654
659
  const blockG = groups(p.slice(1)).find((x) => x[0].text === '{');
655
660
  const block = blockG?.[0];
661
+ // `Where-Object Name -Match "x"` / `Where-Object -Property Name -Value "x" -Match` (no script block).
662
+ if (lower === 'where-object' && !blockG) {
663
+ const opTok = p.slice(1).find((t) => t.t === 'op');
664
+ const a = argsOf(p.slice(1).filter((t) => t !== opTok));
665
+ if (opTok) a.switches.add(opTok.text.slice(1).toLowerCase());
666
+ const prop = at0(a.named.property ?? a.pos[0] ?? []);
667
+ const val = a.named.value ?? a.pos[1];
668
+ const OPS = { match: 'matches the pattern', notmatch: 'does not match the pattern', eq: 'is', ne: 'is not', like: 'is like', notlike: 'is not like', gt: 'is more than', ge: 'is at least', lt: 'is less than', le: 'is at most', contains: 'contains', in: 'is one of' };
669
+ const op = [...a.switches].map((x) => String(x).toLowerCase().replace(/^c|^i(?=[a-z]{2})/, '')).find((x) => OPS[x]);
670
+ const v = val ? sayValue(val) : null;
671
+ if (prop.length === 1 && prop[0].t === 'word' && op && v) { said.push(`keeps only those whose ${words(prop[0].text)} ${OPS[op]} ${v}`); command = true; continue; }
672
+ return null;
673
+ }
656
674
  if (lower === 'where-object') {
657
675
  const ct = blockG ? blockG.slice(1, -1) : p.slice(1);
658
676
  const c = gated(ct, condWords(ct, false));
@@ -682,7 +700,8 @@ function pipelineWords(toks) {
682
700
  if (lower === 'out-null') continue;
683
701
  if (lower === 'select-object') { const a = argsOf(p.slice(1)); const first = a.named.first ? sayValue(a.named.first) : null; const props = a.named.property ?? a.pos[0]; const xp = a.named.expandproperty ? at0(a.named.expandproperty) : null; said.push(xp?.length === 1 ? `takes each one's ${words(xp[0].text)}` : first ? `takes the first ${first}` : a.named.last ? `takes the last ${sayValue(a.named.last)}` : a.switches.has('unique') ? 'keeps one of each' : props ? `picks ${listWords(splitCommas(props).map((x) => words(at0(x)[0]?.text ?? '')))}` : 'picks some of them'); command = true; continue; }
684
702
  if (lower === 'sort-object') { const a = argsOf(p.slice(1)); const by = a.named.property ?? a.pos[0]; said.push(`sorts them${by ? ` by ${listWords(splitCommas(by).map((x) => words(at0(x)[0]?.text ?? '')))}` : ''}${a.switches.has('descending') ? ', highest first' : ''}`); command = true; continue; }
685
- if (lower === 'measure-object') { said.push('counts them'); command = true; continue; }
703
+ // (`Measure-Object -Property Length -Sum` adds up their lengths; with no -Sum / -Average / … it counts them.)
704
+ if (lower === 'measure-object') { const a = argsOf(p.slice(1)); const prop = at0(a.named.property ?? a.pos[0] ?? []); const what = prop.length === 1 && prop[0].t === 'word' ? words(prop[0].text) : null; const kinds = ['sum', 'average', 'maximum', 'minimum'].filter((k) => [...a.switches].some((x) => String(x).toLowerCase() === k)); said.push(kinds.length ? `works out the ${listWords(kinds.map((k) => ({ sum: 'total', average: 'average', maximum: 'largest', minimum: 'smallest' }[k])))} of ${what ? `their ${what}` : 'them'}` : 'counts them'); command = true; continue; }
686
705
  if (lower === 'group-object') { const a = argsOf(p.slice(1)); const by = a.named.property ?? a.pos[0]; said.push(`groups them${by ? ` by ${words(at0(by)[0]?.text ?? '')}` : ''}`); command = true; continue; }
687
706
  if (lower === 'format-table' || lower === 'format-list') { said.push(`shows them as a ${lower === 'format-table' ? 'table' : 'list'}`); command = true; continue; }
688
707
  if (lower === 'tee-object') { said.push('keeps a copy as it goes'); command = true; continue; }
package/src/read-repo.mjs CHANGED
@@ -98,6 +98,7 @@ export function readRepo(files, { maxFileBytes = 400000, maxFiles = 5000 } = {})
98
98
  let reading;
99
99
  try { reading = readCode(source, { language, file: path }); }
100
100
  catch (e) { skipped.push({ path, reason: e instanceof Error ? e.message : 'Could not be read.' }); continue; }
101
+ if (reading.skipped) { skipped.push({ path, reason: reading.skipped }); continue; }
101
102
  for (const it of reading.items) items.push({ ...it, id: `${path}#${it.id}`, file: path, language });
102
103
  fileSummaries.push({ path, language, counts: reading.counts });
103
104
  }
package/src/read.d.mts CHANGED
@@ -33,6 +33,10 @@ export interface ReadItem {
33
33
  steps?: ReadStep[]; stepsMore?: number;
34
34
  /** Share of steps that explain the code: not `other` and not `restates`. */
35
35
  stepsReadable?: number;
36
+ /** How sure: steps put into words (`explained: true`), of every step at every depth (`totalSteps`). */
37
+ explainedSteps?: number; totalSteps?: number;
38
+ /** Inputs left out because they were not written as parameters in the signature (a macro, a type, a lifetime). */
39
+ inputsDropped?: number;
36
40
  }
37
41
  /** One plain step of a function (thunder-steps-v1). */
38
42
  export interface ReadStep {
@@ -51,6 +55,13 @@ export interface ReadStep {
51
55
  * of the statement, or `{ kind: 'code', text }` when it is not fully understood. Never guessed.
52
56
  */
53
57
  expr?: Expr;
58
+ /**
59
+ * Say less (say-less.mjs): true when the words are Thunder's own and account for the code; false when the step is
60
+ * shown as code, "code, not explained" (its `says` is then the code in backticks). Set on every step.
61
+ */
62
+ explained?: boolean;
63
+ /** When `explained` is false: why, in a few plain words ("the reader did not recognize this form", "block structure uncertain"). */
64
+ notExplainedWhy?: string;
54
65
  }
55
66
  export interface Reading {
56
67
  schema: 'thunder-reading-v1'; language: string; detected: boolean; items: ReadItem[];
package/src/read.mjs CHANGED
@@ -10,7 +10,8 @@
10
10
  // return cond ? X : Y (nested ternaries) Python: return X if cond else Y
11
11
  // Rust/Go tail forms: if cond { X } else { Y }, if cond { return X }
12
12
  // Conditions may use comparisons, &&/||/!, and/or/not, parentheses, literals, and inputs or fields.
13
- import { sqlItems } from './sql.mjs';
13
+ import { sayLess, certainlyYesNo } from './say-less.mjs';
14
+ import { sqlItems, sqlTemplateReason } from './sql.mjs';
14
15
  import { readDockerfile } from './infra-docker.mjs';
15
16
  import { readWorkflow } from './infra-gha.mjs';
16
17
  import { readTerraform } from './infra-terraform.mjs';
@@ -152,6 +153,13 @@ function skipString(src, i) {
152
153
  while (/\w/.test(src[j] || '')) j++;
153
154
  if (src[j] !== '\'') return i;
154
155
  }
156
+ // Rust text runs over lines until its closing quote; a raw string `r#"…"#` ends at the quote followed by its hashes.
157
+ if (q === '"' && READING_RUST) {
158
+ const raw = /\br(#*)$/.exec(src.slice(Math.max(0, i - 8), i));
159
+ if (raw) { const e = src.indexOf(`"${raw[1]}`, i + 1); return e < 0 ? src.length : e + raw[1].length; }
160
+ for (let j = i + 1; j < src.length; j++) { if (src[j] === '\\') { j++; continue; } if (src[j] === q) return j; }
161
+ return src.length;
162
+ }
155
163
  for (let j = i + 1; j < src.length; j++) {
156
164
  if (src[j] === '\\') { j++; continue; }
157
165
  if (src[j] === q) return j;
@@ -180,7 +188,7 @@ function parseParams(raw, language) {
180
188
  let pendingGo = [];
181
189
  for (let p of parts.map((x) => x.trim()).filter(Boolean)) {
182
190
  p = p.replace(/=.*$/, '').trim();
183
- if (/^&?\s*(mut\s+)?self$|^self$|^cls$|^this$/.test(p)) continue;
191
+ if (/^&?\s*(?:'\w+\s+)?(mut\s+)?self$|^self$|^cls$|^this$/.test(p)) continue;
184
192
  if (language === 'ruby') {
185
193
  if (/^&/.test(p)) continue; // a block argument
186
194
  out.push({ name: p.replace(/^\*+/, '').replace(/:.*$/, '').trim(), type: null });
@@ -1103,8 +1111,10 @@ function leadingDoc(lines, fnLine, language) {
1103
1111
  }
1104
1112
  if (/\*\/\s*$/.test(lines[k])) {
1105
1113
  const end = k;
1106
- while (k >= 0 && !/\/\*\*/.test(lines[k])) k--;
1107
- if (k < 0) return null;
1114
+ // (The block that ends here starts at the nearest /*; a plain /* … */ such as /*#__PURE__*/ is not a doc, and
1115
+ // a doc comment further up belongs to something else.)
1116
+ while (k >= 0 && !/\/\*/.test(lines[k])) k--;
1117
+ if (k < 0 || !/^\s*\/\*\*(?!\/)/.test(lines[k])) return null;
1108
1118
  return cleanDoc(lines.slice(k, end + 1).join('\n').replace(/^\s*\/\*\*/, '').replace(/\*\/\s*$/, ''));
1109
1119
  }
1110
1120
  const lineDoc = language === 'go' || language === 'c' || language === 'cpp' ? /^\s*\/\/(?!\/)|^\s*\/\/\/(?!\/)/ : language === 'ruby' ? /^\s*#(?![!{])/ : /^\s*\/\/\//;
@@ -1113,6 +1123,29 @@ function leadingDoc(lines, fnLine, language) {
1113
1123
  return got.length ? cleanDoc(got.join('\n')) : null;
1114
1124
  }
1115
1125
 
1126
+ /**
1127
+ * A controller's route prefix joined to a method's path: ASP.NET `[Route("api/[controller]")]` on the class (with
1128
+ * [controller] the class name less "Controller") or Spring `@RequestMapping("/api")` on the class. A method path
1129
+ * that starts at the root (`/x`, or `~/x` in ASP.NET) keeps no prefix. With neither, the method's own path, from "/".
1130
+ */
1131
+ function withClassPrefix(lines, fnLine, path, style) {
1132
+ // ASP.NET: a method template starting at the root (/x or ~/x) replaces the controller's. Spring always joins them.
1133
+ if (style === 'aspnet' && /^~?\//.test(path)) return '/' + path.replace(/^~?\/+/, '');
1134
+ let prefix = '';
1135
+ for (let i = fnLine - 2; i >= 0; i--) {
1136
+ const c = lines[i].match(/\bclass\s+(\w+)/);
1137
+ if (!c) continue;
1138
+ for (let j = i - 1; j >= Math.max(0, i - 6); j--) {
1139
+ const t = lines[j].trim();
1140
+ const r = style === 'aspnet' ? t.match(/^\[(?:Route|RoutePrefix)\(\s*"([^"]*)"/) : t.match(/^@RequestMapping\(\s*(?:value\s*=\s*|path\s*=\s*)?(?:\{\s*)?["']([^"']*)["']/);
1141
+ if (r) { prefix = r[1].replace(/\[controller\]/gi, c[1].replace(/Controller$/, '')); break; }
1142
+ if (t && !/^(\[|@|\/\/|\*|\/\*)/.test(t)) break;
1143
+ }
1144
+ break;
1145
+ }
1146
+ return '/' + [prefix, path].map((x) => x.replace(/^\/+|\/+$/g, '')).filter(Boolean).join('/');
1147
+ }
1148
+
1116
1149
  /** Mark functions that a decorator or annotation binds to an HTTP route. */
1117
1150
  function annotateRoutes(fns, src) {
1118
1151
  // Decorated handlers: @app.get("/x") / @router.post (Python), @GetMapping (Spring), [HttpGet] (ASP.NET), @Get() (NestJS).
@@ -1127,9 +1160,9 @@ function annotateRoutes(fns, src) {
1127
1160
  let m;
1128
1161
  if ((m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i))) { fn.route = { method: m[1].toUpperCase(), path: m[2] }; break; }
1129
1162
  if ((m = l.match(/^@\w+\.route\(\s*['"]([^'"]*)['"](?:.*methods\s*=\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'GET').toUpperCase(), path: m[1] }; break; }
1130
- if ((m = l.match(/^@(Get|Post|Put|Patch|Delete|Request)Mapping(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?["']([^"']*)["'])?/))) { fn.route = { method: m[1] === 'Request' ? 'ANY' : m[1].toUpperCase(), path: m[2] || '/' }; break; }
1163
+ if ((m = l.match(/^@(Get|Post|Put|Patch|Delete|Request)Mapping(?:\(\s*(?:value\s*=\s*|path\s*=\s*)?(?:\{\s*)?["']([^"']*)["'])?/))) { fn.route = { method: m[1] === 'Request' ? 'ANY' : m[1].toUpperCase(), path: withClassPrefix(lines, fn.line, m[2] || '', 'spring') }; break; }
1131
1164
  if ((m = l.match(/^#\[Route\(\s*(?:path:\s*)?['"]([^'"]*)['"](?:.*methods:\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'ANY').toUpperCase(), path: m[1] }; break; }
1132
- if ((m = l.match(/^\[Http(Get|Post|Put|Patch|Delete)(?:\(\s*"([^"]*)")?/))) { fn.route = { method: m[1].toUpperCase(), path: m[2] || '' }; break; }
1165
+ if ((m = l.match(/^\[Http(Get|Post|Put|Patch|Delete)(?:\(\s*"([^"]*)")?/))) { fn.route = { method: m[1].toUpperCase(), path: withClassPrefix(lines, fn.line, m[2] || '', 'aspnet') }; break; }
1133
1166
  if ((m = l.match(/^@(Get|Post|Put|Patch|Delete)\(\s*(?:['"]([^'"]*)['"])?\s*\)/))) { fn.route = { method: m[1].toUpperCase(), path: m[2] || '' }; break; }
1134
1167
  if (!/^(@|\[|\/\/|#|\*|\/\*)/.test(l) && l) break;
1135
1168
  }
@@ -1329,7 +1362,9 @@ function lex(text) {
1329
1362
  return out;
1330
1363
  }
1331
1364
 
1332
- const unquote = (t) => t.slice(1, -1);
1365
+ // The text a quoted literal stands for: `'\t'` is a tab, not a backslash and a t (written back with JSON escapes).
1366
+ const ESCAPES = { t: '\t', n: '\n', r: '\r', 0: '\0', '\\': '\\', '"': '"', "'": "'", '`': '`' };
1367
+ const unquote = (t) => t.slice(1, -1).replace(/\\([tnr0\\"'`])/g, (m, c) => ESCAPES[c]);
1333
1368
 
1334
1369
  /** Convert a condition to ThunderLang, or return null with nothing guessed. */
1335
1370
  export function toThunderCondition(text, inputs = []) {
@@ -1794,6 +1829,8 @@ function splitStatements(body, baseLine) {
1794
1829
  } else if (c === ';' && depth === 0) {
1795
1830
  // Go: `if err := open(); err != nil {` and `for i := 0; i < n; i++ {` keep their header together.
1796
1831
  if (/^\s*(?:if|for|switch|else\s+if)\b/.test(src.slice(start, i)) && !src.slice(start, i).includes('{') && /\{/.test(src.slice(i, src.indexOf('\n', i) < 0 ? undefined : src.indexOf('\n', i)))) continue;
1832
+ // (Go: the condition after `;` can go on over lines, `if w, ok := f(); !ok ||\n g() {`.)
1833
+ if (/^\s*(?:if|switch|else\s+if)\b/.test(src.slice(start, i)) && !src.slice(start, i).includes('{') && /(?:\|\||&&|[,(])\s*\n[^;{}]*\{/.test(src.slice(i, i + 600))) { const nb = src.indexOf('{', i), ns = src.indexOf(';', i + 1); if (nb > 0 && (ns < 0 || nb < ns)) continue; }
1797
1834
  i++; break;
1798
1835
  }
1799
1836
  else if (c === '\n' && depth === 0) {
@@ -1812,8 +1849,9 @@ function splitStatements(body, baseLine) {
1812
1849
  if (/^(?:(?:\}\s*)?else\s+if|if|for|foreach|while|using|lock|fixed)\s*\(/.test(before) && headerClosed(before)) continue;
1813
1850
  // (Nested: `for (…)\n if (…)\n return 1;` is one statement: the last line is itself a brace-less header.)
1814
1851
  const lastLine = before.slice(before.lastIndexOf('\n') + 1).trim();
1815
- if (lastLine !== before && /^(?:(?:\}\s*)?else\s+if|if|for|foreach|while|using|lock|fixed)\s*\(/.test(before) && /^(?:if|for|foreach|while)\s*\(/.test(lastLine) && headerClosed(lastLine)) continue;
1816
- if (/^(?:\}\s*)?else$/.test(before)) continue;
1852
+ if (lastLine !== before && /^(?:(?:\}\s*)?else\s+if|if|for|foreach|while|using|lock|fixed)\s*\(/.test(before) && /^(?:(?:\}\s*)?else\s+if|if|for|foreach|while)\s*\(/.test(lastLine) && headerClosed(lastLine.replace(/^(?:\}\s*)?else\s+/, ''))) continue;
1853
+ // (`} else if (x)` / `} else` closing a braced if, with its one statement on the next line.)
1854
+ if (/^(?:\}\s*)?else$/.test(before) || (lastLine !== before && /^(?:if|else)\b/.test(before) && /^(?:\}\s*)?else$/.test(lastLine))) continue;
1817
1855
  // (`i++` / `n--` at the end of a line is a whole statement, not an operator waiting for more.)
1818
1856
  // (`do { … }` with its `while (…)` on the next line, Allman style, is one statement.)
1819
1857
  if (before && (!/[,(\[{+\-*/%&|^=<>?:.!]$/.test(before) || /[\w)\]](?:\+\+|--)$/.test(before)) && !/^[.)\]}{+\-*/%&|^=<>?:,]/.test(after) && !/^(?:else|catch|finally)\b/.test(after) && !(/^(?:do|repeat)\b/.test(before) && /\}$/.test(before) && /^while\b/.test(after))) { i++; break; }
@@ -1860,6 +1898,7 @@ function stripCommentsKeepLayout(s) {
1860
1898
  if (c === '"' || c === "'" || c === '`') {
1861
1899
  // A quote is a string only when it closes (on the same line, except template and raw strings).
1862
1900
  let j = i + 1;
1901
+ if (c === '"' && READING_RUST) { const e = skipString(s, i); if (e < s.length) i = e; continue; }
1863
1902
  for (; j < s.length; j++) { if (s[j] === '\\') { j++; continue; } if (s[j] === c || (s[j] === '\n' && c !== '`')) break; }
1864
1903
  if (j < s.length && s[j] === c) i = j;
1865
1904
  continue;
@@ -2452,6 +2491,10 @@ function readPredicate(fn, lang, names, code) {
2452
2491
  // (C and C++ yes/no functions often return int, so only Swift is held to its declared type.)
2453
2492
  if (lang === 'swift' && fn.returns && !/^(?:Bool|bool|_Bool|boolean)\??$/.test(String(fn.returns).trim())) return null;
2454
2493
  if (/^(?:c|cpp)$/.test(lang) && fn.returns && /^(?:string|char\*|const char\*)$/.test(String(fn.returns).trim())) return null;
2494
+ // (C/C++ yes/no functions return bool or int; one that returns an enum or a class gives back that value.)
2495
+ if (/^(?:c|cpp)$/.test(lang) && fn.returns && !/^(?:(?:static\s+|inline\s+|const\s+)*(?:bool|_Bool|int|BOOL|\w*_bool|gboolean|unsigned|long|short|char))$/.test(String(fn.returns).trim())) return null;
2496
+ // (`p->style()` is a field of a pointer, not a comparison.)
2497
+ expr = expr.replace(/->/g, '.');
2455
2498
  if (/^(?:swift|c|cpp)$/.test(lang) && !BOOL_RETURN.test(String(fn.returns || '').trim()) && !/^Bool\??$/.test(String(fn.returns || '').trim()) && !LOGIC_OR_COMPARE.test(expr.replace(/"(?:\\.|[^"\\])*"/g, 'Q'))) return null;
2456
2499
  if (!(BOOL_RETURN.test(String(fn.returns || '').trim()) || LOGIC_OR_COMPARE.test(expr) || /\?$/.test(fn.name))) return null;
2457
2500
  const when = toThunderCondition(expr.replace(/\?$/, ''), names);
@@ -2513,14 +2556,28 @@ function markBuildOnlySteps(steps, fn, lang, code, srcLines) {
2513
2556
  // (A question or a loop keeps its own words, which the views turn into "Ask: …?"; the steps under it say it.)
2514
2557
  const holds = st.kind === 'branch' || st.kind === 'loop' || st.kind === 'try';
2515
2558
  if (label && label !== outer && !holds) st.says = `${st.says} (only in builds where \`${label}\`)`;
2559
+ // A loop header inside `#if … #endif` with its body outside it (`#if X\n while (…) {\n #endif`): the loop is
2560
+ // only in those builds; the steps inside are in every build. (Steps under a header are never given its label:
2561
+ // each says its own, from its own line.)
2562
+ if (label && label !== outer && st.kind === 'loop') st.says = `${st.says} (the loop only in builds where \`${label}\`${(st.children || []).some((k) => !only.has(k.line)) ? '; the steps inside are in every build' : ''})`;
2516
2563
  const inner = holds ? outer : label || outer;
2517
- if (st.children) walk(st.children.map((k) => (holds && label && !only.has(k.line) ? (only.set(k.line, label), k) : k)), inner);
2564
+ if (st.children) walk(st.children, inner);
2518
2565
  for (const h of st.handlers || []) if (h.steps) walk(h.steps, inner);
2519
2566
  }
2520
2567
  };
2521
2568
  walk(steps, null);
2522
2569
  }
2523
2570
 
2571
+ /** Go named results: `(head, tail string, err error)` -> ['head', 'tail', 'err']; [] when they have no names. */
2572
+ function goResultNames(returns) {
2573
+ const r = String(returns || '').trim();
2574
+ if (!/^\(.*\)$/.test(r)) return [];
2575
+ const parts = splitTop(r.slice(1, -1), ',').map((x) => x.trim()).filter(Boolean);
2576
+ // Named when the last part is "name type"; then each part's first word is a name.
2577
+ if (!parts.length || !/^[A-Za-z_]\w*\s+\S/.test(parts[parts.length - 1])) return [];
2578
+ return parts.map((p) => p.split(/\s+/)[0]).filter((n) => /^[A-Za-z_]\w*$/.test(n) && n !== '_').map((n) => displayLabel(n).toLowerCase());
2579
+ }
2580
+
2524
2581
  function functionSteps(fn, lang, code, names, srcLines = []) {
2525
2582
  let stmts = [];
2526
2583
  try {
@@ -2534,8 +2591,31 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
2534
2591
  // So does one that is a single call or expression when the function says it gives something back
2535
2592
  // (`func base32Bytes() -> [UInt8] { Base32.default.encode(…) }` gives back what encode makes).
2536
2593
  if (lang === 'swift' && stmts.length === 1 && ((!stmts[0].children?.length && swiftImplicitValue(stmts[0].text)) || swiftImplicitResult(stmts[0].text, fn.returns || (fn.route ? 'a response' : null)))) stmts[0] = { ...stmts[0], implicitReturn: true };
2594
+ // Rust gives back the value of its last expression (written without `;`): `Ok(n)` at the end is what comes back.
2595
+ let rustTail = null;
2596
+ if (lang === 'rust' && fn.returns && !/^\(\s*\)$/.test(String(fn.returns).trim())) {
2597
+ const last = stmts[stmts.length - 1];
2598
+ const ends = last && last.end != null ? /^\s*;/.test(fn.body.slice(last.end)) : true;
2599
+ if (last && !ends) {
2600
+ if (/^(?:match|if)\b/.test(String(last.text).trim())) rustTail = last;
2601
+ else if (!/^(?:let|for|while|loop|return|break|continue|const|static|use|fn|impl|struct|enum)\b|^[\w.\[\]*]+\s*(?:[-+*/%|&^]|<<|>>)?=(?!=)|!\s*\(|^[a-z_][\w:]*!/.test(String(last.text).trim()) || /^(?:vec|format|matches)!/.test(String(last.text).trim())) stmts[stmts.length - 1] = { ...last, implicitReturn: true };
2602
+ }
2603
+ }
2537
2604
  const r = withLanguage(lang, () => withFunctionContext({ params: fn.params || [], language: lang, route: !!fn.route }, () => {
2538
2605
  const out = stepsFrom(stmts);
2606
+ // Rust: a `match` / `if` that ends the function gives back what each arm or side ends with.
2607
+ if (rustTail) {
2608
+ const tail = out.steps[out.steps.length - 1];
2609
+ const giveBack = (list) => {
2610
+ const k = list?.[list.length - 1];
2611
+ if (!k) return;
2612
+ if (k.caseLabel || (k.kind === 'branch' && /^(?:match|if)\b/.test(String(k.code || '')))) { for (const arm of k.caseLabel ? [k] : []) giveBack(arm.children); if (!k.caseLabel) { for (const arm of (k.children || []).filter((c) => c.caseLabel)) giveBack(arm.children); if (!(k.children || []).some((c) => c.caseLabel)) giveBack(k.children); giveBack(k.otherwise); } return; }
2613
+ if (!/^(?:call|other)$/.test(k.kind) || k.jump || !k.code || /;\s*$/.test(k.code) || /^[\w.\[\]*]+\s*(?:[-+*/%|&^]|<<|>>)?=(?!=)|^(?:let|for|while|loop|unsafe)\b|^(?:panic|unreachable|todo|unimplemented)!/.test(String(k.code).replace(/,\s*$/, ''))) return;
2614
+ const v = classifyStatement(`return ${String(k.code).replace(/,\s*$/, '')}`);
2615
+ if (v.kind === 'return' || v.kind === 'fail') { list[list.length - 1] = { ...k, ...v, code: k.code }; delete list[list.length - 1].callee; delete list[list.length - 1].restates; }
2616
+ };
2617
+ if (tail) { if (tail.kind === 'branch' && (tail.children || []).some((c) => c.caseLabel)) for (const arm of tail.children.filter((c) => c.caseLabel)) giveBack(arm.children); else if (tail.kind === 'branch') { giveBack(tail.children); giveBack(tail.otherwise); } }
2618
+ }
2539
2619
  // Ruby gives back its last value: in a yes/no method (`def accepts?`) or a last line that is a comparison or
2540
2620
  // and/or, that value is the answer, not a call made for its effect.
2541
2621
  const last = out.steps[out.steps.length - 1];
@@ -2544,9 +2624,23 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
2544
2624
  if (v.kind === 'return') out.steps[out.steps.length - 1] = { ...last, ...v, code: last.code, ...(/^Returns (?:a computed value|a value)$/.test(v.says) ? { restates: true } : {}) };
2545
2625
  delete out.steps[out.steps.length - 1].callee;
2546
2626
  }
2627
+ // Ruby, otherwise: a last line that is a value (shown as code, or read) is what the method gives back
2628
+ // (`cache[input].dup`), so the ending is never hidden. (Not `initialize` or a setter, whose value is not used.)
2629
+ else if (lang === 'ruby' && last && (last.kind === 'other' || (last.kind === 'call' && /^Reads /.test(last.says || ''))) && !last.jump && !last.children?.length && !/^(?:initialize|\w+=)$/.test(fn.name) && !/^[@$]?[\w.\[\]:]+\s*(?:[-+*/|&]{0,2})=(?![=~])|^(?:puts|print|p|pp|raise|fail|yield|super|require|include|extend|attr_\w+|private|protected|public|alias\w*|define_method)\b/.test(String(last.code || '').trim())) {
2630
+ const v = classifyStatement(`return ${String(last.code || '').trim()}`);
2631
+ if (v.kind === 'return') { out.steps[out.steps.length - 1] = { ...last, ...v, code: last.code, ...(/^Returns (?:a computed value|a value)$/.test(v.says) ? { restates: true } : {}) }; delete out.steps[out.steps.length - 1].callee; }
2632
+ }
2547
2633
  return out;
2548
2634
  }));
2549
2635
  if (lang === 'c' || lang === 'cpp') markBuildOnlySteps(r.steps, fn, lang, code, srcLines);
2636
+ // Go: a bare `return` in a function with named results gives back those results as they are then.
2637
+ if (lang === 'go') {
2638
+ const named = goResultNames(fn.returns);
2639
+ if (named.length) {
2640
+ const walk = (list) => { for (const st of list || []) { if (st.nested) continue; if (st.kind === 'return' && st.says === 'Stops here' && /^return\s*;?$/.test(String(st.code || '').trim())) st.says = `Returns ${named.length > 1 ? `${named.slice(0, -1).join(', ')} and ${named.at(-1)}` : named[0]}`; walk(st.children); walk(st.otherwise); for (const h of st.handlers || []) walk(h.steps); } };
2641
+ walk(r.steps);
2642
+ }
2643
+ }
2550
2644
  // A Swift `switch` that is the whole body of a function that gives something back: each case's one expression is
2551
2645
  // what comes back (`case .key(let key): String(reflecting: key)` gives back that text; it is not just a call).
2552
2646
  // So does an if / else if / else that is the whole body (Swift if-expressions).
@@ -2610,7 +2704,13 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
2610
2704
  return r;
2611
2705
  }
2612
2706
 
2613
- export function readCode(source, { language, file = '', allSteps = false } = {}) {
2707
+ export function readCode(source, opts = {}) {
2708
+ const reading = readCodeAsIs(source, opts);
2709
+ // Say less (say-less.mjs): a step stays in words only when the words account for its code; the rest is code.
2710
+ return opts.sayEverything ? reading : sayLess(reading, String(source ?? ''));
2711
+ }
2712
+
2713
+ function readCodeAsIs(source, { language, file = '', allSteps = false } = {}) {
2614
2714
  const src = String(source ?? '');
2615
2715
  if (src.length > 400000) throw new Error('Source is larger than 400 KB. Read one file or module at a time.');
2616
2716
  const lang = String(language || detectLanguage(src, file)).toLowerCase().replace(/^ts$/, 'typescript').replace(/^js$/, 'javascript').replace(/^py$/, 'python').replace(/^(cs|c#)$/, 'csharp').replace(/^rs$/, 'rust').replace(/^golang$/, 'go').replace(/^kts?$/, 'kotlin').replace(/^rb$/, 'ruby').replace(/^(postgres(ql)?|pgsql|plpgsql|mysql|sqlite|tsql|t-sql|mssql)$/, 'sql').replace(/^(docker|containerfile)$/, 'dockerfile').replace(/^(gha|github[ -]?actions?|workflow)$/, 'github-actions').replace(/^(tf|hcl|opentofu|tofu)$/, 'terraform').replace(/^(k8s|kube|kubectl)$/, 'kubernetes').replace(/^(compose|docker[ -]?compose)$/, 'docker-compose').replace(/^(c\+\+|cxx|cc|hpp|hxx|hh)$/, 'cpp').replace(/^h$/, 'c')
@@ -2641,11 +2741,15 @@ export function readCode(source, { language, file = '', allSteps = false } = {})
2641
2741
  // an implicit last value) reads as "true when <expression>, otherwise false".
2642
2742
  if (!read.rules.length && !read.otherwise) {
2643
2743
  const pred = readPredicate(fn, lang, names, code);
2644
- if (pred) { read.rules.push(pred.rule); read.otherwise = { result: 'false', line: pred.rule.line }; read.unread = []; }
2744
+ // (Only when the answer is certainly yes or no: a declared boolean result, a name asked as a question, or an
2745
+ // expression that is a comparison; `state.copy_ || state.base_` gives back an object.)
2746
+ if (pred && (certainlyYesNo(pred.rule.when, lang) || /^(?:bool|boolean|Bool|Boolean|BOOL|_Bool)$/.test(String(simpleType(fn.returns) ?? '').trim()) || /\?$/.test(fn.name))) { read.rules.push(pred.rule); read.otherwise = { result: 'false', line: pred.rule.line }; read.unread = []; }
2645
2747
  }
2646
2748
  // A rule is drawn only when every statement was read into it; a body with other steps (a loop, an assignment, a
2647
2749
  // later check) is read as steps instead, so no check is silently left out of the picture.
2648
- const isDecision = read.rules.length > 0 && !!read.otherwise && !read.unread.length;
2750
+ // (A check that returns or stops before the rules — `if shape != Line { return shape }` — is part of the answer: with
2751
+ // one, the body is read as steps, so no rule card claims fewer answers than the code can give.)
2752
+ const isDecision = read.rules.length > 0 && !!read.otherwise && !read.unread.length && !(read.guards || []).length;
2649
2753
  const guards = read.guards || [];
2650
2754
  // In a function that is not a pure decision, early fixed returns are still rules worth reading.
2651
2755
  if (!isDecision) {
@@ -2726,6 +2830,9 @@ export function searchReading(reading, { query = '', kinds = [], status = [] } =
2726
2830
 
2727
2831
  /** A reading of a SQL file in the same shape as every other language's. */
2728
2832
  function sqlReading(src) {
2833
+ // A dbt / Jinja template is listed as skipped with the reason: its SQL is not known until the template is filled in.
2834
+ const template = sqlTemplateReason(src);
2835
+ if (template) return { schema: READ_SCHEMA, language: 'sql', detected: false, items: [], counts: { decision: 0, function: 0, error: 0, test: 0, partial: 0, guarded: 0, route: 0 }, skipped: template, limitations: [template] };
2729
2836
  const items = sqlItems(src);
2730
2837
  for (const it of items) it.completeness = completenessOf(it);
2731
2838
  const counts = { decision: 0, function: items.length, error: 0, test: 0, partial: 0, guarded: 0, route: 0 };
@@ -2734,6 +2841,7 @@ function sqlReading(src) {
2734
2841
  limitations: [
2735
2842
  'Read by pattern, not by running it on a database. PostgreSQL first; other dialects where their syntax agrees.',
2736
2843
  'Tables are drawn as Data or Things; CHECK and UNIQUE as rules the database enforces; views, functions, procedures, and triggers as steps.',
2844
+ 'Routine bodies (PL/pgSQL, MySQL stored programs, T-SQL) are read block by block; a statement Thunder cannot say exactly is shown as code, and a body whose blocks do not match is shown as not read.',
2737
2845
  ],
2738
2846
  };
2739
2847
  }
@@ -0,0 +1,16 @@
1
+ // The pull request comment for a Thunder review (see src/review-comment.mjs).
2
+ import type { Review, ReviewItem } from './review.mjs';
3
+ export const REVIEW_MARKER: '<!-- thunder-review -->';
4
+ export const GITHUB_COMMENT_LIMIT: 65536;
5
+ export const COMMENT_TITLE: string;
6
+ /** explained: put into sentences; code: shown as the code before and after; person: Thunder cannot check it. */
7
+ export function itemHow(item: ReviewItem): 'explained' | 'code' | 'person';
8
+ export function reviewCounts(review: Review): { explained: number; code: number; person: number; notRead: number };
9
+ export function countsLine(counts: { explained: number; code: number; person: number; notRead: number }): string;
10
+ export function renderReviewComment(review: Review, options?: {
11
+ maxChars?: number;
12
+ fileUrl?: ((file: string, line: number) => string | null) | null;
13
+ notes?: string[];
14
+ footer?: string;
15
+ evidenceLines?: number;
16
+ }): string;