@skillstech/thunderlang 1.0.4 → 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.
- package/CHANGELOG.md +140 -0
- package/dist/core.cjs +2568 -462
- package/dist/index.cjs +7562 -5084
- package/dist/learn.cjs +1963 -315
- package/intent-graph.schema.json +11 -0
- package/package.json +6 -2
- package/src/cli.mjs +141 -58
- package/src/codegen.mjs +145 -55
- package/src/conformance.mjs +15 -6
- package/src/core/check.mjs +725 -0
- package/src/core/cli.mjs +133 -0
- package/src/core/diagnostics.mjs +81 -0
- package/src/core/format.mjs +20 -0
- package/src/core/from-python.mjs +645 -0
- package/src/core/index.mjs +38 -0
- package/src/core/lexer.mjs +115 -0
- package/src/core/parser.mjs +742 -0
- package/src/core/project.mjs +167 -0
- package/src/core/round-trip.mjs +150 -0
- package/src/core/runtime-python.mjs +801 -0
- package/src/core/target-python.mjs +486 -0
- package/src/core.d.ts +5 -2
- package/src/core.mjs +5 -2
- package/src/data-schema.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/evidence.mjs +1 -1
- package/src/expr.mjs +81 -4
- package/src/form-words.mjs +2 -0
- package/src/index.d.ts +8 -1
- package/src/index.mjs +5 -1
- package/src/intent-schema.mjs +1 -0
- package/src/mcp.mjs +23 -0
- package/src/meaning.mjs +45 -6
- package/src/model.d.mts +7 -3
- package/src/model.mjs +19 -6
- package/src/money.d.mts +18 -0
- package/src/money.mjs +124 -0
- package/src/plain-contract.mjs +18 -2
- package/src/read.d.mts +11 -0
- package/src/read.mjs +40 -6
- package/src/review-comment.d.mts +16 -0
- package/src/review-comment.mjs +145 -0
- package/src/say-less.mjs +1432 -0
- package/src/system.mjs +153 -44
- package/src/target-cs.mjs +39 -34
- package/src/target-elixir.mjs +40 -30
- package/src/target-go.mjs +41 -36
- package/src/target-java.mjs +34 -27
- package/src/target-kotlin.mjs +43 -35
- package/src/target-py.mjs +57 -55
- package/src/target-result.d.mts +48 -0
- package/src/target-result.mjs +112 -0
- package/src/target-rust.mjs +42 -38
- package/src/target-scala.mjs +45 -35
- package/src/target-ts.mjs +37 -45
- package/src/target-types.mjs +41 -5
- package/src/target-util.mjs +55 -2
- package/src/trace-cli.mjs +58 -0
- package/src/trace-fs.mjs +76 -0
- package/src/trace.mjs +261 -0
- package/src/translate.d.mts +3 -0
- package/src/translate.mjs +62 -32
- package/src/why-cli.mjs +31 -0
- package/src/why.d.mts +28 -0
- package/src/why.mjs +532 -0
- package/src/write-steps.mjs +22 -5
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
|
+
}
|
package/src/plain-contract.mjs
CHANGED
|
@@ -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
|
-
|
|
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.`);
|
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,6 +10,7 @@
|
|
|
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 { sayLess, certainlyYesNo } from './say-less.mjs';
|
|
13
14
|
import { sqlItems, sqlTemplateReason } from './sql.mjs';
|
|
14
15
|
import { readDockerfile } from './infra-docker.mjs';
|
|
15
16
|
import { readWorkflow } from './infra-gha.mjs';
|
|
@@ -1110,8 +1111,10 @@ function leadingDoc(lines, fnLine, language) {
|
|
|
1110
1111
|
}
|
|
1111
1112
|
if (/\*\/\s*$/.test(lines[k])) {
|
|
1112
1113
|
const end = k;
|
|
1113
|
-
|
|
1114
|
-
|
|
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;
|
|
1115
1118
|
return cleanDoc(lines.slice(k, end + 1).join('\n').replace(/^\s*\/\*\*/, '').replace(/\*\/\s*$/, ''));
|
|
1116
1119
|
}
|
|
1117
1120
|
const lineDoc = language === 'go' || language === 'c' || language === 'cpp' ? /^\s*\/\/(?!\/)|^\s*\/\/\/(?!\/)/ : language === 'ruby' ? /^\s*#(?![!{])/ : /^\s*\/\/\//;
|
|
@@ -1120,6 +1123,29 @@ function leadingDoc(lines, fnLine, language) {
|
|
|
1120
1123
|
return got.length ? cleanDoc(got.join('\n')) : null;
|
|
1121
1124
|
}
|
|
1122
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
|
+
|
|
1123
1149
|
/** Mark functions that a decorator or annotation binds to an HTTP route. */
|
|
1124
1150
|
function annotateRoutes(fns, src) {
|
|
1125
1151
|
// Decorated handlers: @app.get("/x") / @router.post (Python), @GetMapping (Spring), [HttpGet] (ASP.NET), @Get() (NestJS).
|
|
@@ -1134,9 +1160,9 @@ function annotateRoutes(fns, src) {
|
|
|
1134
1160
|
let m;
|
|
1135
1161
|
if ((m = l.match(/^@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]*)['"]/i))) { fn.route = { method: m[1].toUpperCase(), path: m[2] }; break; }
|
|
1136
1162
|
if ((m = l.match(/^@\w+\.route\(\s*['"]([^'"]*)['"](?:.*methods\s*=\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'GET').toUpperCase(), path: m[1] }; break; }
|
|
1137
|
-
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: m[2] || '
|
|
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; }
|
|
1138
1164
|
if ((m = l.match(/^#\[Route\(\s*(?:path:\s*)?['"]([^'"]*)['"](?:.*methods:\s*\[\s*['"](\w+)['"])?/))) { fn.route = { method: (m[2] || 'ANY').toUpperCase(), path: m[1] }; break; }
|
|
1139
|
-
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; }
|
|
1140
1166
|
if ((m = l.match(/^@(Get|Post|Put|Patch|Delete)\(\s*(?:['"]([^'"]*)['"])?\s*\)/))) { fn.route = { method: m[1].toUpperCase(), path: m[2] || '' }; break; }
|
|
1141
1167
|
if (!/^(@|\[|\/\/|#|\*|\/\*)/.test(l) && l) break;
|
|
1142
1168
|
}
|
|
@@ -2678,7 +2704,13 @@ function functionSteps(fn, lang, code, names, srcLines = []) {
|
|
|
2678
2704
|
return r;
|
|
2679
2705
|
}
|
|
2680
2706
|
|
|
2681
|
-
export function readCode(source,
|
|
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 } = {}) {
|
|
2682
2714
|
const src = String(source ?? '');
|
|
2683
2715
|
if (src.length > 400000) throw new Error('Source is larger than 400 KB. Read one file or module at a time.');
|
|
2684
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')
|
|
@@ -2709,7 +2741,9 @@ export function readCode(source, { language, file = '', allSteps = false } = {})
|
|
|
2709
2741
|
// an implicit last value) reads as "true when <expression>, otherwise false".
|
|
2710
2742
|
if (!read.rules.length && !read.otherwise) {
|
|
2711
2743
|
const pred = readPredicate(fn, lang, names, code);
|
|
2712
|
-
|
|
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 = []; }
|
|
2713
2747
|
}
|
|
2714
2748
|
// A rule is drawn only when every statement was read into it; a body with other steps (a loop, an assignment, a
|
|
2715
2749
|
// later check) is read as steps instead, so no check is silently left out of the picture.
|
|
@@ -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;
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// The pull request comment for a Thunder review (thunder-review-v1, see review.mjs): what the change does, in plain
|
|
2
|
+
// sentences, grouped by the action, rule, or function it changed, with the risks first and honest counts of what was
|
|
3
|
+
// explained in sentences, what is only shown as code, and what a person has to check because Thunder cannot.
|
|
4
|
+
//
|
|
5
|
+
// Pure and browser-safe, with no imports, so the GitHub Action (action/thunder-review.mjs) can render a review made by
|
|
6
|
+
// any published compiler version. The wording comes from the review itself: this file never says "safe" or "same";
|
|
7
|
+
// it only repeats what the review showed and counts it.
|
|
8
|
+
|
|
9
|
+
export const REVIEW_MARKER = '<!-- thunder-review -->';
|
|
10
|
+
/** GitHub rejects comment bodies over 65,536 characters; stay under it with room for the marker and footer. */
|
|
11
|
+
export const GITHUB_COMMENT_LIMIT = 65536;
|
|
12
|
+
export const COMMENT_TITLE = 'Thunder review: what this change does, in plain sentences';
|
|
13
|
+
/** When a member no longer fits in full, at most this many of its sentences are shown. */
|
|
14
|
+
const COMPACT_SENTENCES = 3;
|
|
15
|
+
const DOCS_URL = 'https://thunderlang.dev/docs/github-action';
|
|
16
|
+
const SITE_URL = 'https://thunderlang.dev';
|
|
17
|
+
|
|
18
|
+
// What a person has to check because Thunder could not read or does not read it.
|
|
19
|
+
const CANNOT_CHECK = new Set(['unreadable', 'infrastructure', 'not-read']);
|
|
20
|
+
// Changes Thunder shows as the code before and after, rather than explaining in sentences.
|
|
21
|
+
const SHOWN_AS_CODE = new Set(['hidden', 'outside']);
|
|
22
|
+
|
|
23
|
+
/** How an item reached the reviewer: 'explained' (in sentences), 'code' (shown as code), or 'person' (cannot check). */
|
|
24
|
+
export function itemHow(x) {
|
|
25
|
+
if (CANNOT_CHECK.has(x.kind) || (x.kind === 'added' && x.severity === 'risk')) return 'person';
|
|
26
|
+
if (SHOWN_AS_CODE.has(x.kind)) return 'code';
|
|
27
|
+
return 'explained';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
31
|
+
|
|
32
|
+
/** Honest counts for the comment's second line. Each item counts once, as in the review's own summary. */
|
|
33
|
+
export function reviewCounts(r) {
|
|
34
|
+
const c = { explained: 0, code: 0, person: 0, notRead: r.notRead?.length ?? 0 };
|
|
35
|
+
for (const x of r.items) c[itemHow(x)]++;
|
|
36
|
+
return c;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function countsLine(c) {
|
|
40
|
+
const parts = [`${plural(c.explained, 'change')} explained in sentences`, `${c.code} shown as code (Thunder did not put ${c.code === 1 ? 'it' : 'them'} into words)`];
|
|
41
|
+
parts.push(`${c.person} Thunder cannot check (check ${c.person === 1 ? 'it' : 'them'} yourself)`);
|
|
42
|
+
if (c.notRead) parts.push(`${plural(c.notRead, 'file')} Thunder does not read`);
|
|
43
|
+
return `${parts.join(' · ')}.`;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const esc = (s) => String(s).replace(/[<>]/g, (ch) => (ch === '<' ? '<' : '>'));
|
|
47
|
+
const fence = (lines) => ['```', ...lines.map((l) => l.replace(/```/g, "'''")), '```'];
|
|
48
|
+
const cutLines = (lines, max) => (lines.length > max ? [...lines.slice(0, max), `… ${lines.length - max} more lines`] : lines);
|
|
49
|
+
|
|
50
|
+
function evidence(ev, maxLines) {
|
|
51
|
+
if (!ev) return [];
|
|
52
|
+
const out = [];
|
|
53
|
+
if (ev.counterexample) out.push(`Tried on both versions: when ${ev.counterexample.facts}, before: **${ev.counterexample.before}**, after: **${ev.counterexample.after}**.`, '');
|
|
54
|
+
if (ev.before?.length) out.push('Before:', ...fence(cutLines(ev.before, maxLines)));
|
|
55
|
+
if (ev.after?.length) out.push('After:', ...fence(cutLines(ev.after, maxLines)));
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const HEADINGS = {
|
|
60
|
+
risk: ['Needs a careful look', 'A Stop removed or under new conditions, a new address, something that now reaches outside the program, or code Thunder cannot check.'],
|
|
61
|
+
meaning: ['Changes in meaning', 'Anything else that changes what the code does.'],
|
|
62
|
+
form: ['Only the form changed', 'Shown, not guessed: the same code apart from spacing, comments, or names it declares itself, or a rule with the same answer on every edge case.'],
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Render a thunder-review-v1 review as one sticky pull request comment.
|
|
67
|
+
* options: { maxChars (default 60000, under GITHUB_COMMENT_LIMIT; pass more for a job summary), fileUrl(file, line) => url|null,
|
|
68
|
+
* notes: string[] (shown as quotes under the counts), footer, evidenceLines (per before or after block) }
|
|
69
|
+
* Returns the Markdown; it always starts with REVIEW_MARKER and is never longer than maxChars: members that do not fit
|
|
70
|
+
* are left out whole and counted ("N more not shown"), so no code block or <details> is cut in half.
|
|
71
|
+
*/
|
|
72
|
+
export function renderReviewComment(r, { maxChars = 60000, fileUrl = null, notes = [], footer = '', evidenceLines = 40 } = {}) {
|
|
73
|
+
const where = (w) => {
|
|
74
|
+
const label = `\`${esc(w.file)}:${w.line}\``;
|
|
75
|
+
const url = fileUrl?.(w.file, w.line);
|
|
76
|
+
return url ? `[${label}](${url})` : label;
|
|
77
|
+
};
|
|
78
|
+
const head = [REVIEW_MARKER, `### ${COMMENT_TITLE}`, '', `**${r.says}**`, '', countsLine(reviewCounts(r)), ''];
|
|
79
|
+
for (const n of notes.filter(Boolean)) head.push(`> ${n}`, '');
|
|
80
|
+
|
|
81
|
+
// One block per changed action, rule, or function (a "member"), in the review's order of importance.
|
|
82
|
+
const blocks = [];
|
|
83
|
+
for (const sev of ['risk', 'meaning', 'form']) {
|
|
84
|
+
const list = r.items.filter((x) => x.severity === sev);
|
|
85
|
+
if (!list.length) continue;
|
|
86
|
+
const members = new Map();
|
|
87
|
+
for (const x of list) {
|
|
88
|
+
const k = `${x.where.file}\u0000${x.subject}`;
|
|
89
|
+
if (!members.has(k)) members.set(k, []);
|
|
90
|
+
members.get(k).push(x);
|
|
91
|
+
}
|
|
92
|
+
const [title, why] = HEADINGS[sev];
|
|
93
|
+
const open = sev === 'form' ? [`<details><summary>${title} (${list.length})</summary>`, '', `_${why}_`, ''] : [`#### ${title} (${list.length})`, '', `_${why}_`, ''];
|
|
94
|
+
const close = sev === 'form' ? ['</details>', ''] : [];
|
|
95
|
+
// Each member twice: in full, and compact (its first sentences, without the code) for when the full one no longer fits.
|
|
96
|
+
const memberBlocks = [...members.values()].map((xs) => {
|
|
97
|
+
const render = (compact) => {
|
|
98
|
+
const lines = [`- **${esc(xs[0].subject)}** · ${where(xs[0].where)}`];
|
|
99
|
+
const list = compact ? xs.slice(0, COMPACT_SENTENCES) : xs;
|
|
100
|
+
for (const x of list) {
|
|
101
|
+
const ev = sev === 'form' ? [] : evidence(x.evidence, evidenceLines);
|
|
102
|
+
const at = x.where.line !== xs[0].where.line || x.where.file !== xs[0].where.file ? ` (${where(x.where)})` : '';
|
|
103
|
+
lines.push(` - ${esc(x.says)}${at}${compact && (ev.length || x.also?.length) ? ' _(Before and after, and other places: in the job summary.)_' : ''}`);
|
|
104
|
+
if (compact) continue;
|
|
105
|
+
if (ev.length) lines.push('', ` <details><summary>Before and after</summary>`, '', ...ev.map((l) => (l ? ` ${l}` : '')), '', ' </details>', '');
|
|
106
|
+
if (x.also?.length) {
|
|
107
|
+
lines.push('', ` <details><summary>The same in ${x.also.length} more</summary>`, '', ...x.also.slice(0, 50).map((a) => ` - **${esc(a.subject)}** · ${where(a.where)}`),
|
|
108
|
+
...(x.also.length > 50 ? [` - and ${x.also.length - 50} more`] : []), '', ' </details>', '');
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (list.length < xs.length) lines.push(` - _…and ${xs.length - list.length} more changes to it, in the job summary._`);
|
|
112
|
+
return { lines, items: list.length };
|
|
113
|
+
};
|
|
114
|
+
return { full: render(false), compact: render(true) };
|
|
115
|
+
});
|
|
116
|
+
blocks.push({ open, close, members: memberBlocks });
|
|
117
|
+
}
|
|
118
|
+
const tail = [];
|
|
119
|
+
if (r.notRead?.length) tail.push(`Also changed, not read by Thunder (check ${r.notRead.length === 1 ? 'it' : 'them'} yourself if ${r.notRead.length === 1 ? 'it matters' : 'they matter'}): ${r.notRead.slice(0, 20).map((f) => `\`${esc(f.path)}\``).join(', ')}${r.notRead.length > 20 ? `, and ${r.notRead.length - 20} more` : ''}.`, '');
|
|
120
|
+
const foot = ['---', `<sub>Read from the code by the Thunder compiler, with no AI and without running the code. "Only the form changed" is said only when it is shown. Thunder describes the change; a person still decides whether it is right. [How this works](${DOCS_URL}) · [thunderlang.dev](${SITE_URL})${footer ? ` · ${footer}` : ''}</sub>`, ''];
|
|
121
|
+
|
|
122
|
+
// Fill blocks in order of importance. A member that does not fit in full is shown compact (its sentences); when
|
|
123
|
+
// even that does not fit, stop there and say how many were left out.
|
|
124
|
+
const size = (lines) => lines.join('\n').length + 1;
|
|
125
|
+
const total = r.items.length;
|
|
126
|
+
const moreLine = (n) => [`**${n} more not shown** to stay under GitHub's comment size limit. The job summary and \`thunder review\` on your computer have all of them.`, ''];
|
|
127
|
+
const reserve = size(head) + size(tail) + size(foot) + size(moreLine(total)) + 64;
|
|
128
|
+
if (reserve > maxChars) throw new Error(`maxChars ${maxChars} is too small for the comment header and footer.`);
|
|
129
|
+
let used = reserve, shown = 0, full = true;
|
|
130
|
+
const body = [];
|
|
131
|
+
for (const b of blocks) {
|
|
132
|
+
if (!full) break;
|
|
133
|
+
const opened = size(b.open) + size(b.close);
|
|
134
|
+
if (used + opened + (b.members[0] ? size(b.members[0].compact.lines) : 0) > maxChars) { full = false; break; }
|
|
135
|
+
body.push(...b.open); used += opened;
|
|
136
|
+
for (const m of b.members) {
|
|
137
|
+
const pick = used + size(m.full.lines) <= maxChars ? m.full : used + size(m.compact.lines) <= maxChars ? m.compact : null;
|
|
138
|
+
if (!pick) { full = false; break; }
|
|
139
|
+
body.push(...pick.lines); used += size(pick.lines); shown += pick.items;
|
|
140
|
+
}
|
|
141
|
+
body.push('', ...b.close);
|
|
142
|
+
}
|
|
143
|
+
const out = [...head, ...body, ...(shown < total ? moreLine(total - shown) : []), ...tail, ...foot];
|
|
144
|
+
return out.join('\n');
|
|
145
|
+
}
|