@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/codegen.mjs
CHANGED
|
@@ -6,27 +6,59 @@
|
|
|
6
6
|
//
|
|
7
7
|
// Pure and browser-safe so the playground can render it. TypeScript first; the same adapter
|
|
8
8
|
// shape (a type map + a body walk) extends to C# / Java / Python.
|
|
9
|
+
//
|
|
10
|
+
// A rule condition a target cannot express is never replaced by `false`: the generated code calls
|
|
11
|
+
// a helper that throws with the IL-GEN-001 message, and generateWithDiagnostics() reports it.
|
|
9
12
|
|
|
10
13
|
import { exprToJs, exprToCSharp, exprToJava, exprToPython } from './expr.mjs';
|
|
11
14
|
import { subjectName } from './parse.mjs';
|
|
12
|
-
import {
|
|
15
|
+
import { planDecision } from './target-types.mjs';
|
|
13
16
|
|
|
14
17
|
// Decision inputs as plain names with one type each (declared, else from the examples, else from how the rules use
|
|
15
|
-
// them), so generated code type-checks: `amount >= 0` needs a number, not unknown or Object.
|
|
16
|
-
|
|
17
|
-
const TS_PARAM = { number: 'number', bool: 'boolean', string: 'string' };
|
|
18
|
-
const CS_PARAM = { number: 'double', bool: 'bool', string: 'string' };
|
|
19
|
-
const JAVA_PARAM = { number: 'double', bool: 'boolean', string: 'String' };
|
|
20
|
-
const PY_PARAM = { number: 'float', bool: 'bool', string: 'str' };
|
|
18
|
+
// them), so generated code type-checks: `amount >= 0` needs a number, not unknown or Object. Money inputs keep an
|
|
19
|
+
// exact type (bigint minor units, decimal, BigDecimal, Decimal), never a float.
|
|
20
|
+
const TS_PARAM = { number: 'number', bool: 'boolean', string: 'string', money: 'Money' };
|
|
21
|
+
const CS_PARAM = { number: 'double', bool: 'bool', string: 'string', money: 'decimal' };
|
|
22
|
+
const JAVA_PARAM = { number: 'double', bool: 'boolean', string: 'String', money: 'java.math.BigDecimal' };
|
|
23
|
+
const PY_PARAM = { number: 'float', bool: 'bool', string: 'str', money: 'Decimal' };
|
|
24
|
+
|
|
25
|
+
// Plan every decision for one target: params, translated conditions, and IL-GEN-001 diagnostics for any rule
|
|
26
|
+
// condition the target cannot express.
|
|
27
|
+
function planAll(ast, translate, target) {
|
|
28
|
+
const plans = (ast.decisions || []).map((d) => planDecision(ast, d, { translate, target }));
|
|
29
|
+
return { plans, diagnostics: plans.flatMap((p) => p.diagnostics) };
|
|
30
|
+
}
|
|
31
|
+
const notTranslatedNote = (code) => (code == null ? ' , IL-GEN-001 not translated' : '');
|
|
21
32
|
|
|
22
33
|
export const CODEGEN_SCHEMA = 'intent-codegen-v1';
|
|
23
34
|
|
|
35
|
+
// TypeScript Money: exact bigint minor units with two tiny helpers. Zero dependencies; needs ES2020 (bigint).
|
|
36
|
+
const TS_MONEY_HELPERS = [
|
|
37
|
+
'// Thunder Money: an exact amount in minor units (cents by default), never binary floating point.',
|
|
38
|
+
'// parseMoney("12.30") === 1230n; formatMoney(1230n) === "12.30". Extra precision is an error, not rounded.',
|
|
39
|
+
'export type Money = bigint;',
|
|
40
|
+
'export function parseMoney(text: string, minorUnits = 2): Money {',
|
|
41
|
+
' const m = /^([+-])?(\\d+)(?:\\.(\\d+))?$/.exec(text.trim());',
|
|
42
|
+
' if (!m) throw new Error(`"${text}" is not an amount`);',
|
|
43
|
+
' const frac = m[3] ?? "";',
|
|
44
|
+
' if (/[1-9]/.test(frac.slice(minorUnits))) throw new Error(`${text} has more than ${minorUnits} decimal places; Thunder Money never rounds silently`);',
|
|
45
|
+
' const minor = BigInt(m[2] + frac.slice(0, minorUnits).padEnd(minorUnits, "0"));',
|
|
46
|
+
' return m[1] === "-" ? -minor : minor;',
|
|
47
|
+
'}',
|
|
48
|
+
'export function formatMoney(minor: Money, minorUnits = 2): string {',
|
|
49
|
+
' const neg = minor < 0n;',
|
|
50
|
+
' const digits = (neg ? -minor : minor).toString().padStart(minorUnits + 1, "0");',
|
|
51
|
+
' return (neg ? "-" : "") + (minorUnits ? `${digits.slice(0, -minorUnits)}.${digits.slice(-minorUnits)}` : digits);',
|
|
52
|
+
'}',
|
|
53
|
+
'',
|
|
54
|
+
];
|
|
55
|
+
|
|
24
56
|
// Semantic type -> TypeScript type. Unknown/domain types become a named type (interface stub).
|
|
25
57
|
const TS_TYPES = {
|
|
26
58
|
Email: 'string', Url: 'string', UserId: 'string', AccountId: 'string', OrderId: 'string',
|
|
27
59
|
InvoiceId: 'string', CustomerId: 'string', PaymentId: 'string', EventId: 'string',
|
|
28
60
|
Secret: 'string', Token: 'string', Jwt: 'string', Password: 'string', IdempotencyKey: 'string',
|
|
29
|
-
Money: '
|
|
61
|
+
Money: 'Money', Currency: 'string', Percentage: 'number', Count: 'number', Duration: 'number',
|
|
30
62
|
Date: 'string', DateTime: 'string', Flag: 'boolean', TraceId: 'string', CorrelationId: 'string',
|
|
31
63
|
Version: 'string', EnvironmentName: 'string',
|
|
32
64
|
};
|
|
@@ -36,6 +68,7 @@ function tsType(type, domain) {
|
|
|
36
68
|
const list = /^List<(.+)>$/.exec(type);
|
|
37
69
|
if (list) { domain.add(list[1]); return `${tsType(list[1], domain)}[]`; }
|
|
38
70
|
const base = type.replace(/\(.*\)/, '');
|
|
71
|
+
if (base === 'Money') domain.add('Money'); // triggers the exact Money helpers
|
|
39
72
|
if (TS_TYPES[base]) return TS_TYPES[base];
|
|
40
73
|
domain.add(base); // a domain/entity type -> emit an interface stub for it
|
|
41
74
|
return base;
|
|
@@ -50,10 +83,13 @@ const fieldsIface = (name, fields, domain) => [
|
|
|
50
83
|
];
|
|
51
84
|
|
|
52
85
|
/** Generate a deterministic TypeScript scaffold from a parsed intent AST. Returns a string. */
|
|
53
|
-
export function toTypeScript(ast) {
|
|
86
|
+
export function toTypeScript(ast) { return buildTypeScript(ast).code; }
|
|
87
|
+
|
|
88
|
+
function buildTypeScript(ast) {
|
|
54
89
|
const subject = pascal(subjectName(ast) || 'Intent');
|
|
55
90
|
const domain = new Set();
|
|
56
91
|
const L = [];
|
|
92
|
+
const { plans, diagnostics } = planAll(ast, exprToJs, 'TypeScript');
|
|
57
93
|
|
|
58
94
|
L.push(
|
|
59
95
|
`// ${subject} , generated from ThunderLang (intent-codegen-v1). Deterministic, no AI.`,
|
|
@@ -64,21 +100,30 @@ export function toTypeScript(ast) {
|
|
|
64
100
|
);
|
|
65
101
|
|
|
66
102
|
// Input / output interfaces.
|
|
67
|
-
|
|
68
|
-
if ((ast.
|
|
103
|
+
const ifaces = [];
|
|
104
|
+
if ((ast.inputs || []).length) ifaces.push(...fieldsIface(`${subject}Input`, ast.inputs, domain));
|
|
105
|
+
if ((ast.outputs || []).length) ifaces.push(...fieldsIface(`${subject}Output`, ast.outputs, domain));
|
|
106
|
+
const usesMoney = domain.has('Money') || plans.some((p) => Object.keys(p.money).length);
|
|
107
|
+
domain.delete('Money');
|
|
108
|
+
if (usesMoney) L.push(...TS_MONEY_HELPERS);
|
|
109
|
+
if (diagnostics.length) {
|
|
110
|
+
L.push(
|
|
111
|
+
'// IL-GEN-001: Thunder could not translate some rule conditions. Those rules throw instead of guessing.',
|
|
112
|
+
'function thunderUntranslated(message: string): boolean { throw new Error(message); }',
|
|
113
|
+
'',
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
L.push(...ifaces);
|
|
69
117
|
|
|
70
118
|
// Decisions , real, first-hit logic (the intent already executes these).
|
|
71
|
-
for (const
|
|
72
|
-
const
|
|
73
|
-
const
|
|
74
|
-
const params = ps.map((x) => `${x.name}: ${TS_PARAM[x.type]}`).join(', ');
|
|
119
|
+
for (const p of plans) {
|
|
120
|
+
const d = p.decision;
|
|
121
|
+
const params = p.names.map((n) => `${n}: ${TS_PARAM[p.types[n]]}`).join(', ');
|
|
75
122
|
L.push(`// decision ${d.name} , first matching rule wins.`);
|
|
76
123
|
L.push(`export function ${lower(pascal(d.name))}(${params}): string {`);
|
|
77
|
-
for (const r of
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
catch { cond = `false /* TODO: could not translate "${r.when}" */`; }
|
|
81
|
-
L.push(` if (${cond}) return ${JSON.stringify(r.result)}; // rule ${r.name}`);
|
|
124
|
+
for (const { rule: r, code, message } of p.rules) {
|
|
125
|
+
const cond = code ?? `thunderUntranslated(${JSON.stringify(message)})`;
|
|
126
|
+
L.push(` if (${cond}) return ${JSON.stringify(r.result)}; // rule ${r.name}${notTranslatedNote(code)}`);
|
|
82
127
|
}
|
|
83
128
|
L.push(` return ${JSON.stringify(d.default ?? 'Undecided')}; // default`);
|
|
84
129
|
L.push('}', '');
|
|
@@ -106,7 +151,7 @@ export function toTypeScript(ast) {
|
|
|
106
151
|
L.push('');
|
|
107
152
|
}
|
|
108
153
|
|
|
109
|
-
return L.join('\n');
|
|
154
|
+
return { code: L.join('\n'), diagnostics };
|
|
110
155
|
}
|
|
111
156
|
|
|
112
157
|
// ── C# ───────────────────────────────────────────────────────────────────────
|
|
@@ -126,9 +171,12 @@ function csType(type, domain) {
|
|
|
126
171
|
}
|
|
127
172
|
|
|
128
173
|
/** Generate a deterministic C# scaffold from an intent AST. */
|
|
129
|
-
export function toCSharp(ast) {
|
|
174
|
+
export function toCSharp(ast) { return buildCSharp(ast).code; }
|
|
175
|
+
|
|
176
|
+
function buildCSharp(ast) {
|
|
130
177
|
const subject = pascal(subjectName(ast) || 'Intent');
|
|
131
178
|
const domain = new Set();
|
|
179
|
+
const { plans, diagnostics } = planAll(ast, exprToCSharp, 'C#');
|
|
132
180
|
const L = [
|
|
133
181
|
`// ${subject} , generated from ThunderLang (intent-codegen-v1). Deterministic, no AI.`,
|
|
134
182
|
'// The record contract and the decision logic are fully determined by the intent;',
|
|
@@ -145,17 +193,20 @@ export function toCSharp(ast) {
|
|
|
145
193
|
if ((ast.inputs || []).length) L.push(...rec(`${subject}Input`, ast.inputs));
|
|
146
194
|
if ((ast.outputs || []).length) L.push(...rec(`${subject}Output`, ast.outputs));
|
|
147
195
|
L.push(`public static class ${subject}`, '{');
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
196
|
+
if (diagnostics.length) {
|
|
197
|
+
L.push(' // IL-GEN-001: Thunder could not translate some rule conditions. Those rules throw instead of guessing.');
|
|
198
|
+
L.push(' private static bool ThunderUntranslated(string message) => throw new NotImplementedException(message);');
|
|
199
|
+
}
|
|
200
|
+
for (const p of plans) {
|
|
201
|
+
const d = p.decision;
|
|
151
202
|
// A C# member cannot share its class's name (CS0542): a decision named like the mission becomes Decide.
|
|
152
203
|
const method = pascal(d.name) === subject ? 'Decide' : pascal(d.name);
|
|
153
204
|
L.push(` // decision ${d.name} , first matching rule wins.`);
|
|
154
|
-
L.push(` public static string ${method}(${
|
|
205
|
+
L.push(` public static string ${method}(${p.names.map((n) => `${CS_PARAM[p.types[n]]} ${n}`).join(', ')})`);
|
|
155
206
|
L.push(' {');
|
|
156
|
-
for (const r of
|
|
157
|
-
|
|
158
|
-
L.push(` if (${cond}) return ${JSON.stringify(r.result)}; // rule ${r.name}`);
|
|
207
|
+
for (const { rule: r, code, message } of p.rules) {
|
|
208
|
+
const cond = code ?? `ThunderUntranslated(${JSON.stringify(message)})`;
|
|
209
|
+
L.push(` if (${cond}) return ${JSON.stringify(r.result)}; // rule ${r.name}${notTranslatedNote(code)}`);
|
|
159
210
|
}
|
|
160
211
|
L.push(` return ${JSON.stringify(d.default ?? 'Undecided')}; // default`, ' }');
|
|
161
212
|
}
|
|
@@ -167,7 +218,7 @@ export function toCSharp(ast) {
|
|
|
167
218
|
for (const g of ast.guarantees || []) L.push(` // GUARANTEE: ${g.statement}`);
|
|
168
219
|
L.push(' throw new NotImplementedException("TODO: implement , the intent above defines what this must do.");', ' }');
|
|
169
220
|
L.push('}', '');
|
|
170
|
-
return L.join('\n');
|
|
221
|
+
return { code: L.join('\n'), diagnostics };
|
|
171
222
|
}
|
|
172
223
|
|
|
173
224
|
// ── Java ─────────────────────────────────────────────────────────────────────
|
|
@@ -187,9 +238,12 @@ function javaType(type, domain) {
|
|
|
187
238
|
}
|
|
188
239
|
|
|
189
240
|
/** Generate a deterministic Java scaffold from an intent AST. */
|
|
190
|
-
export function toJava(ast) {
|
|
241
|
+
export function toJava(ast) { return buildJava(ast).code; }
|
|
242
|
+
|
|
243
|
+
function buildJava(ast) {
|
|
191
244
|
const subject = pascal(subjectName(ast) || 'Intent');
|
|
192
245
|
const domain = new Set();
|
|
246
|
+
const { plans, diagnostics } = planAll(ast, exprToJava, 'Java');
|
|
193
247
|
const L = [
|
|
194
248
|
`// ${subject} , generated from ThunderLang (intent-codegen-v1). Deterministic, no AI.`,
|
|
195
249
|
'// The record contract and the decision logic are fully determined by the intent;',
|
|
@@ -204,14 +258,17 @@ export function toJava(ast) {
|
|
|
204
258
|
: [];
|
|
205
259
|
if ((ast.inputs || []).length) L.push(...rec(`${subject}Input`, ast.inputs));
|
|
206
260
|
if ((ast.outputs || []).length) L.push(...rec(`${subject}Output`, ast.outputs));
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
261
|
+
if (diagnostics.length) {
|
|
262
|
+
L.push(' // IL-GEN-001: Thunder could not translate some rule conditions. Those rules throw instead of guessing.');
|
|
263
|
+
L.push(' private static boolean thunderUntranslated(String message) { throw new UnsupportedOperationException(message); }', '');
|
|
264
|
+
}
|
|
265
|
+
for (const p of plans) {
|
|
266
|
+
const d = p.decision;
|
|
210
267
|
L.push(` // decision ${d.name} , first matching rule wins.`);
|
|
211
|
-
L.push(` public static String ${lower(pascal(d.name))}(${
|
|
212
|
-
for (const r of
|
|
213
|
-
|
|
214
|
-
L.push(` if (${cond}) return ${JSON.stringify(r.result)}; // rule ${r.name}`);
|
|
268
|
+
L.push(` public static String ${lower(pascal(d.name))}(${p.names.map((n) => `${JAVA_PARAM[p.types[n]]} ${n}`).join(', ')}) {`);
|
|
269
|
+
for (const { rule: r, code, message } of p.rules) {
|
|
270
|
+
const cond = code ?? `thunderUntranslated(${JSON.stringify(message)})`;
|
|
271
|
+
L.push(` if (${cond}) return ${JSON.stringify(r.result)}; // rule ${r.name}${notTranslatedNote(code)}`);
|
|
215
272
|
}
|
|
216
273
|
L.push(` return ${JSON.stringify(d.default ?? 'Undecided')}; // default`, ' }');
|
|
217
274
|
}
|
|
@@ -223,7 +280,7 @@ export function toJava(ast) {
|
|
|
223
280
|
for (const g of ast.guarantees || []) L.push(` // GUARANTEE: ${g.statement}`);
|
|
224
281
|
L.push(' throw new UnsupportedOperationException("TODO: implement , the intent above defines what this must do.");', ' }');
|
|
225
282
|
L.push('}', '');
|
|
226
|
-
return L.join('\n');
|
|
283
|
+
return { code: L.join('\n'), diagnostics };
|
|
227
284
|
}
|
|
228
285
|
|
|
229
286
|
// ── Python ───────────────────────────────────────────────────────────────────
|
|
@@ -231,13 +288,14 @@ const PY_TYPES = {
|
|
|
231
288
|
Email: 'str', Url: 'str', UserId: 'str', AccountId: 'str', OrderId: 'str',
|
|
232
289
|
InvoiceId: 'str', CustomerId: 'str', Secret: 'str', Token: 'str', Jwt: 'str',
|
|
233
290
|
IdempotencyKey: 'str', Currency: 'str', Date: 'str', DateTime: 'str',
|
|
234
|
-
Money: '
|
|
291
|
+
Money: 'Decimal', Percentage: 'float', Count: 'int', Duration: 'int', Flag: 'bool',
|
|
235
292
|
};
|
|
236
293
|
function pyType(type, domain) {
|
|
237
294
|
if (!type) return 'object';
|
|
238
295
|
const list = /^List<(.+)>$/.exec(type);
|
|
239
296
|
if (list) return `list[${pyType(list[1], domain)}]`;
|
|
240
297
|
const base = type.replace(/\(.*\)/, '');
|
|
298
|
+
if (base === 'Money') domain.add('Money'); // triggers `from decimal import Decimal`
|
|
241
299
|
if (PY_TYPES[base]) return PY_TYPES[base];
|
|
242
300
|
domain.add(base); return base;
|
|
243
301
|
}
|
|
@@ -246,9 +304,12 @@ function pyType(type, domain) {
|
|
|
246
304
|
const snake = (s) => pascal(s).replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
|
|
247
305
|
|
|
248
306
|
/** Generate a deterministic Python scaffold from an intent AST. */
|
|
249
|
-
export function toPython(ast) {
|
|
307
|
+
export function toPython(ast) { return buildPython(ast).code; }
|
|
308
|
+
|
|
309
|
+
function buildPython(ast) {
|
|
250
310
|
const subject = pascal(subjectName(ast) || 'Intent');
|
|
251
311
|
const domain = new Set();
|
|
312
|
+
const { plans, diagnostics } = planAll(ast, exprToPython, 'Python');
|
|
252
313
|
const L = [
|
|
253
314
|
`# ${subject} , generated from ThunderLang (intent-codegen-v1). Deterministic, no AI.`,
|
|
254
315
|
'# The dataclass contract and the decision logic are fully determined by the intent;',
|
|
@@ -256,23 +317,35 @@ export function toPython(ast) {
|
|
|
256
317
|
'',
|
|
257
318
|
];
|
|
258
319
|
const hasData = (ast.inputs || []).length || (ast.outputs || []).length;
|
|
259
|
-
// Postponed annotations so a dataclass may reference a domain stub declared below it.
|
|
260
|
-
if (hasData) L.push('from __future__ import annotations', 'from dataclasses import dataclass', '');
|
|
261
320
|
const cls = (name, fields) => fields.length
|
|
262
321
|
? ['@dataclass', `class ${name}:`, ...fields.map((f) => ` ${f.name}: ${pyType(f.type, domain)}`), '']
|
|
263
322
|
: [];
|
|
264
|
-
|
|
265
|
-
if ((ast.
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
323
|
+
const body = [];
|
|
324
|
+
if ((ast.inputs || []).length) body.push(...cls(`${subject}Input`, ast.inputs));
|
|
325
|
+
if ((ast.outputs || []).length) body.push(...cls(`${subject}Output`, ast.outputs));
|
|
326
|
+
// Money is decimal.Decimal: exact, never float.
|
|
327
|
+
const usesMoney = domain.has('Money') || plans.some((p) => Object.keys(p.money).length);
|
|
328
|
+
domain.delete('Money');
|
|
329
|
+
// Postponed annotations so a dataclass may reference a domain stub declared below it.
|
|
330
|
+
if (hasData) L.push('from __future__ import annotations', 'from dataclasses import dataclass');
|
|
331
|
+
if (usesMoney) L.push('from decimal import Decimal');
|
|
332
|
+
if (hasData || usesMoney) L.push('');
|
|
333
|
+
if (diagnostics.length) {
|
|
334
|
+
L.push(
|
|
335
|
+
'# IL-GEN-001: Thunder could not translate some rule conditions. Those rules raise instead of guessing.',
|
|
336
|
+
'def _thunder_untranslated(message: str) -> bool:',
|
|
337
|
+
' raise NotImplementedError(message)',
|
|
338
|
+
'',
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
L.push(...body);
|
|
342
|
+
for (const p of plans) {
|
|
343
|
+
const d = p.decision;
|
|
269
344
|
L.push(`# decision ${d.name} , first matching rule wins.`);
|
|
270
|
-
L.push(`def ${snake(d.name)}(${
|
|
271
|
-
for (const r of
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
catch { cond = 'False'; note = ` # TODO: could not translate "${r.when}"`; }
|
|
275
|
-
L.push(` if ${cond}:${note}`);
|
|
345
|
+
L.push(`def ${snake(d.name)}(${p.names.map((n) => `${n}: ${PY_PARAM[p.types[n]]}`).join(', ')}) -> str:`);
|
|
346
|
+
for (const { rule: r, code, message } of p.rules) {
|
|
347
|
+
const cond = code ?? `_thunder_untranslated(${JSON.stringify(message)})`;
|
|
348
|
+
L.push(` if ${cond}:${code == null ? ' # IL-GEN-001 not translated' : ''}`);
|
|
276
349
|
L.push(` return ${JSON.stringify(r.result)} # rule ${r.name}`);
|
|
277
350
|
}
|
|
278
351
|
L.push(` return ${JSON.stringify(d.default ?? 'Undecided')} # default`, '');
|
|
@@ -290,7 +363,24 @@ export function toPython(ast) {
|
|
|
290
363
|
for (const t of stubs) L.push(`class ${t}: pass # TODO: fields`);
|
|
291
364
|
L.push('');
|
|
292
365
|
}
|
|
293
|
-
return L.join('\n');
|
|
366
|
+
return { code: L.join('\n'), diagnostics };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const BUILDERS = {
|
|
370
|
+
typescript: buildTypeScript, ts: buildTypeScript,
|
|
371
|
+
csharp: buildCSharp, cs: buildCSharp,
|
|
372
|
+
java: buildJava,
|
|
373
|
+
python: buildPython, py: buildPython,
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* Generate code AND the generation diagnostics for a target. `diagnostics` holds one IL-GEN-001 error
|
|
378
|
+
* per rule condition the target could not translate; the generated code throws at those rules.
|
|
379
|
+
*/
|
|
380
|
+
export function generateWithDiagnostics(ast, target) {
|
|
381
|
+
const build = BUILDERS[String(target).toLowerCase()];
|
|
382
|
+
if (!build) throw new Error(`Unknown generation target "${target}". Use one of: ${Object.keys(BUILDERS).join(', ')}.`);
|
|
383
|
+
return build(ast);
|
|
294
384
|
}
|
|
295
385
|
|
|
296
386
|
export const GENERATORS = {
|
package/src/conformance.mjs
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
|
-
// Cross-target conformance.
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// Cross-target conformance. The deterministic engine defines the canonical contract (what every
|
|
2
|
+
// target must produce for each test case); target outputs , executed live or fed via results , are
|
|
3
|
+
// graded against it. A target case that diverges is a CONFORMANCE FAILURE. Same tests, every
|
|
4
|
+
// implementation.
|
|
5
|
+
//
|
|
6
|
+
// A target result is either a plain value (fed via --results) or a structured case result from a
|
|
7
|
+
// live run ({ status: 'ok', value } | { status: 'error', kind, message }). An error is graded as
|
|
8
|
+
// 'error' with its kind and message , not translated, compile failure, crash, timeout , and counts
|
|
9
|
+
// as a failure. It is never compared as if it were a null answer.
|
|
5
10
|
import { runTests } from './testing.mjs';
|
|
11
|
+
import { isCaseResult } from './target-result.mjs';
|
|
6
12
|
|
|
7
13
|
export function buildConformance(ast, { targets = [], results = null } = {}) {
|
|
8
14
|
const sem = runTests(ast);
|
|
@@ -16,7 +22,9 @@ export function buildConformance(ast, { targets = [], results = null } = {}) {
|
|
|
16
22
|
for (const col of columns) {
|
|
17
23
|
const tr = results && results[col];
|
|
18
24
|
if (!tr || !(c.key in tr)) { t[col] = { status: 'declared' }; continue; }
|
|
19
|
-
const
|
|
25
|
+
const raw = tr[c.key];
|
|
26
|
+
if (isCaseResult(raw) && raw.status === 'error') { t[col] = { status: 'error', kind: raw.kind, message: raw.message }; continue; }
|
|
27
|
+
const actual = isCaseResult(raw) ? raw.value : raw;
|
|
20
28
|
t[col] = { status: String(actual) === String(c.expected) ? 'pass' : 'fail', actual };
|
|
21
29
|
}
|
|
22
30
|
return { ...c, targets: t };
|
|
@@ -24,7 +32,8 @@ export function buildConformance(ast, { targets = [], results = null } = {}) {
|
|
|
24
32
|
const failures = [];
|
|
25
33
|
for (const row of rows) for (const col of columns) {
|
|
26
34
|
const tr = row.targets[col];
|
|
27
|
-
if (tr.status === 'fail') failures.push({ target: col, case: row.key, expected: row.expected, actual: tr.actual });
|
|
35
|
+
if (tr.status === 'fail') failures.push({ target: col, case: row.key, expected: row.expected, actual: tr.actual, kind: 'assertion-failed' });
|
|
36
|
+
if (tr.status === 'error') failures.push({ target: col, case: row.key, expected: row.expected, kind: tr.kind, message: tr.message });
|
|
28
37
|
}
|
|
29
38
|
return {
|
|
30
39
|
schema: 'thunder-conformance-v1', mission: ast.mission,
|