@skillstech/thunderlang 0.4.2 → 0.5.4
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 +64 -0
- package/dist/core.cjs +8389 -4510
- package/dist/index.cjs +7218 -3842
- package/package.json +1 -1
- package/src/anchor.d.mts +12 -0
- package/src/anchor.mjs +127 -0
- package/src/cli.mjs +234 -42
- package/src/codegen.mjs +27 -9
- package/src/core.d.ts +19 -0
- package/src/core.mjs +16 -0
- package/src/emit.mjs +1 -1
- package/src/expr.mjs +42 -1
- package/src/human-contract.d.mts +20 -0
- package/src/human-contract.mjs +213 -0
- package/src/index.d.ts +23 -0
- package/src/index.mjs +11 -0
- package/src/lift.mjs +7 -0
- package/src/mcp.mjs +139 -54
- package/src/obligations.d.mts +9 -0
- package/src/obligations.mjs +35 -0
- package/src/plain-contract.d.mts +30 -0
- package/src/plain-contract.mjs +339 -0
- package/src/promote.d.mts +6 -0
- package/src/promote.mjs +179 -0
- package/src/read-repo-fs.mjs +29 -0
- package/src/read-repo.d.mts +21 -0
- package/src/read-repo.mjs +139 -0
- package/src/read.d.mts +29 -0
- package/src/read.mjs +1620 -0
- package/src/review-atlas.d.mts +19 -0
- package/src/review-atlas.mjs +136 -0
- package/src/steps.d.mts +2 -0
- package/src/steps.mjs +297 -0
- package/src/target-elixir.mjs +79 -0
- package/src/target-go.mjs +95 -0
- package/src/target-kotlin.mjs +91 -0
- package/src/target-rust.mjs +99 -0
- package/src/target-scala.mjs +93 -0
- package/src/target-types.mjs +97 -0
- package/src/target-util.mjs +1 -59
- package/src/testing.mjs +12 -9
- package/src/thunder-repo.mjs +96 -0
- package/src/translate.d.mts +5 -0
- package/src/translate.mjs +126 -0
- package/src/write.d.mts +24 -0
- package/src/write.mjs +263 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skillstech/thunderlang",
|
|
3
|
-
"version": "0.4
|
|
3
|
+
"version": "0.5.4",
|
|
4
4
|
"description": "Deterministic ThunderLang compiler, CLI, and Language Server. No AI required. Turns .thunder files into the canonical Intent Graph, docs, and a proof, and EXECUTES the intent: run decisions, simulate lifecycles, and check outcome contracts. Interops with DMN, BPMN, JSON Schema, and OpenAPI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
package/src/anchor.d.mts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export const ANCHOR_SCHEMA: 'thunder-anchor-v1';
|
|
2
|
+
export interface Span { startLine: number; endLine: number; start?: number; end?: number; exact: 'offset' | 'lines' }
|
|
3
|
+
export function spanRange(source: string, span: Span): [number, number];
|
|
4
|
+
export function spanText(source: string, span: Span): string;
|
|
5
|
+
export function replaceSpan(source: string, span: Span, replacement: string): string;
|
|
6
|
+
export function editStep(args: { source: string; language?: string; file?: string; functionName: string; line?: number | null; path: number[]; replacement: string }):
|
|
7
|
+
| { ok: true; source: string; problems: []; change: { startLine: number; endLine: number; before: string; after: string; startOffset: number; linesBefore: number }; reread: { kind: string; says: string } }
|
|
8
|
+
| { ok: false; source: string; problems: string[] };
|
|
9
|
+
export function anchorReport(source: string, opts?: { language?: string; file?: string }): {
|
|
10
|
+
schema: 'thunder-anchor-v1'; language: string; coverage: number;
|
|
11
|
+
functions: Array<{ name: string; line: number; coverage: number; codeLines: number; missing: number[]; steps: Array<{ path: string; kind: string; says: string; span: Span }> }>;
|
|
12
|
+
};
|
package/src/anchor.mjs
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// Lossless anchoring: every Thunder step points at its exact place in the original file, so a change made
|
|
2
|
+
// in Thunder can be written back to exactly that place and nowhere else. This is the foundation for
|
|
3
|
+
// Thunder write. Deterministic and browser-safe; it edits text only and never runs code.
|
|
4
|
+
import { readCode, pyNoComment, rbNoComment } from './read.mjs';
|
|
5
|
+
|
|
6
|
+
export const ANCHOR_SCHEMA = 'thunder-anchor-v1';
|
|
7
|
+
|
|
8
|
+
const lineStarts = (source) => { const out = [0]; for (let i = 0; i < source.length; i++) if (source[i] === '\n') out.push(i + 1); return out; };
|
|
9
|
+
|
|
10
|
+
/** [start, end) character range of a span. Offsets when exact; whole lines otherwise. */
|
|
11
|
+
export function spanRange(source, span) {
|
|
12
|
+
if (span.exact === 'offset' && span.start != null && span.end != null) return [span.start, span.end];
|
|
13
|
+
const starts = lineStarts(source);
|
|
14
|
+
const a = starts[span.startLine - 1] ?? source.length;
|
|
15
|
+
const nextLine = starts[span.endLine];
|
|
16
|
+
const b = nextLine != null ? nextLine - 1 : source.length;
|
|
17
|
+
return [a, b];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The exact original text a span covers. */
|
|
21
|
+
export function spanText(source, span) {
|
|
22
|
+
const [a, b] = spanRange(source, span);
|
|
23
|
+
return source.slice(a, b);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Replace exactly the text a span covers. Everything else is untouched, byte for byte. */
|
|
27
|
+
export function replaceSpan(source, span, replacement) {
|
|
28
|
+
const [a, b] = spanRange(source, span);
|
|
29
|
+
// Whole-line spans keep the original indentation (it carries meaning in Python and Ruby).
|
|
30
|
+
if (span.exact !== 'offset') {
|
|
31
|
+
const indent = (source.slice(a, b).match(/^[ \t]*/) || [''])[0];
|
|
32
|
+
const lines = String(replacement).replace(/\s+$/, '').split('\n');
|
|
33
|
+
const base = (lines[0].match(/^[ \t]*/) || [''])[0].length;
|
|
34
|
+
replacement = lines.map((l) => (l.trim() ? indent + l.slice(Math.min(base, (l.match(/^[ \t]*/) || [''])[0].length)) : l)).join('\n');
|
|
35
|
+
}
|
|
36
|
+
// The span ends before a statement's own ";"; don't double it.
|
|
37
|
+
if (source[b] === ';') replacement = String(replacement).replace(/;\s*$/, '');
|
|
38
|
+
return source.slice(0, a) + replacement + source.slice(b);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The trailing # comment on a Python or Ruby line, with the spaces before it; '' when there is none. */
|
|
42
|
+
function trailingComment(text, language) {
|
|
43
|
+
const strip = language === 'python' ? pyNoComment : language === 'ruby' ? rbNoComment : null;
|
|
44
|
+
if (!strip) return '';
|
|
45
|
+
const last = String(text).split('\n').pop();
|
|
46
|
+
const rest = last.slice(strip(last).replace(/\s+$/, '').length);
|
|
47
|
+
return /^\s*#/.test(rest) ? rest : '';
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Find a step by path: [3] is the 4th top-level step, [1, 0] the first step inside the 2nd. */
|
|
51
|
+
function stepAt(steps, path) {
|
|
52
|
+
let list = steps, step = null;
|
|
53
|
+
for (const i of path) { step = list?.[i]; if (!step) return null; list = step.children; }
|
|
54
|
+
return step;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function flatten(steps, path = [], out = []) {
|
|
58
|
+
steps.forEach((s, i) => { out.push({ path: [...path, i], step: s }); if (s.children) flatten(s.children, [...path, i], out); });
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Compare code ignoring indentation and a trailing ";".
|
|
63
|
+
const norm = (t) => String(t).split('\n').map((l) => l.trim()).join('\n').replace(/;\s*$/, '').trim();
|
|
64
|
+
|
|
65
|
+
function findFunction(reading, name, line) {
|
|
66
|
+
const fns = reading.items.filter((i) => i.name === name && i.steps);
|
|
67
|
+
if (!fns.length) return null;
|
|
68
|
+
if (line == null) return fns[0];
|
|
69
|
+
return fns.reduce((best, f) => (Math.abs(f.line - line) < Math.abs(best.line - line) ? f : best));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Write one step back to the original code and verify the result.
|
|
74
|
+
* Returns { ok, source, change, reread, problems }. On any problem, ok is false and `source` is the original.
|
|
75
|
+
*/
|
|
76
|
+
export function editStep({ source, language, file = '', functionName, line = null, path, replacement }) {
|
|
77
|
+
const problems = [];
|
|
78
|
+
const before = readCode(source, { language, file });
|
|
79
|
+
const fn = findFunction(before, functionName, line);
|
|
80
|
+
if (!fn) return { ok: false, source, problems: [`No function named ${functionName} with steps was found.`] };
|
|
81
|
+
const step = stepAt(fn.steps, path);
|
|
82
|
+
if (!step?.span) return { ok: false, source, problems: [`Step ${path.join('.')} does not exist in ${functionName}.`] };
|
|
83
|
+
const original = spanText(source, step.span);
|
|
84
|
+
// Whole-line spans include a trailing # comment; keep it unless the replacement brings its own.
|
|
85
|
+
const comment = step.span.exact !== 'offset' ? trailingComment(original, before.language) : '';
|
|
86
|
+
if (comment && !String(replacement).includes('#')) replacement = String(replacement).replace(/\s+$/, '') + comment;
|
|
87
|
+
const next = replaceSpan(source, step.span, replacement);
|
|
88
|
+
|
|
89
|
+
// Verify: re-read, the function is still there, the edited step reads as the new code, others unchanged.
|
|
90
|
+
let after;
|
|
91
|
+
try { after = readCode(next, { language, file }); } catch (e) { return { ok: false, source, problems: [`The changed file could not be read: ${e.message}`] }; }
|
|
92
|
+
const fn2 = findFunction(after, functionName, fn.line);
|
|
93
|
+
if (!fn2) return { ok: false, source, problems: [`${functionName} is no longer found after the change.`] };
|
|
94
|
+
const key = path.join('.');
|
|
95
|
+
// Ancestors contain the edited step and its descendants are replaced with it; every other step must be unchanged.
|
|
96
|
+
const isAncestor = (p) => key.startsWith(`${p}.`);
|
|
97
|
+
const others = flatten(fn.steps).filter((x) => { const k = x.path.join('.'); return k !== key && !k.startsWith(`${key}.`) && !isAncestor(k); });
|
|
98
|
+
const others2 = new Map(flatten(fn2.steps).map((x) => [x.path.join('.'), x.step]));
|
|
99
|
+
for (const o of others) {
|
|
100
|
+
const twin = others2.get(o.path.join('.'));
|
|
101
|
+
if (!twin) { problems.push(`Step ${o.path.join('.')} disappeared.`); continue; }
|
|
102
|
+
// Steps after the edit may have moved; compare their text, not their position.
|
|
103
|
+
if (norm(spanText(source, o.step.span)) !== norm(spanText(next, twin.span))) problems.push(`Step ${o.path.join('.')} changed unexpectedly.`);
|
|
104
|
+
}
|
|
105
|
+
const edited = stepAt(fn2.steps, path);
|
|
106
|
+
if (!edited) problems.push('The edited step is no longer read as a step.');
|
|
107
|
+
else if (norm(spanText(next, edited.span)) !== norm(replacement)) problems.push('The edited step does not match the new code exactly.');
|
|
108
|
+
if (problems.length) return { ok: false, source, problems };
|
|
109
|
+
const starts = lineStarts(source);
|
|
110
|
+
return {
|
|
111
|
+
ok: true, source: next, problems: [],
|
|
112
|
+
change: { startLine: step.span.startLine, endLine: step.span.endLine, before: original, after: replacement, startOffset: spanRange(source, step.span)[0], linesBefore: starts.length },
|
|
113
|
+
reread: { kind: edited.kind, says: edited.says },
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Anchoring report for every function: coverage and whether each step's span matches its statement. */
|
|
118
|
+
export function anchorReport(source, { language, file = '' } = {}) {
|
|
119
|
+
const reading = readCode(source, { language, file });
|
|
120
|
+
const functions = reading.items.filter((i) => i.anchor).map((f) => ({
|
|
121
|
+
name: f.name, line: f.line, coverage: f.anchor.coverage, codeLines: f.anchor.codeLines, missing: f.anchor.missing,
|
|
122
|
+
steps: flatten(f.steps).map(({ path, step }) => ({ path: path.join('.'), kind: step.kind, says: step.says, span: step.span })),
|
|
123
|
+
}));
|
|
124
|
+
const total = functions.reduce((n, f) => n + f.codeLines, 0);
|
|
125
|
+
const covered = functions.reduce((n, f) => n + Math.round(f.coverage * f.codeLines), 0);
|
|
126
|
+
return { schema: ANCHOR_SCHEMA, language: reading.language, functions, coverage: total ? Math.round((covered / total) * 1000) / 1000 : 1 };
|
|
127
|
+
}
|
package/src/cli.mjs
CHANGED
|
@@ -15,6 +15,16 @@
|
|
|
15
15
|
import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, existsSync } from 'node:fs';
|
|
16
16
|
import { basename, join, relative, dirname } from 'node:path';
|
|
17
17
|
import { parseIntent, slug, subjectName, KNOWN_LENSES } from './parse.mjs';
|
|
18
|
+
import { previewHumanContract, renderHumanContract } from './human-contract.mjs';
|
|
19
|
+
import { previewPlainContract } from './plain-contract.mjs';
|
|
20
|
+
import { thunderRepo, renderThunderRepo } from './thunder-repo.mjs';
|
|
21
|
+
import { anchorReport } from './anchor.mjs';
|
|
22
|
+
import { writeRule } from './write.mjs';
|
|
23
|
+
import { readCode, searchReading } from './read.mjs';
|
|
24
|
+
import { readRepo, searchRepo, groupByFile } from './read-repo.mjs';
|
|
25
|
+
import { promoteDecision } from './promote.mjs';
|
|
26
|
+
import { collectReadableFiles } from './read-repo-fs.mjs';
|
|
27
|
+
import { translateDecisions } from './translate.mjs';
|
|
18
28
|
import {
|
|
19
29
|
buildContractGraph, buildArchitectureGraph, buildImplementationPlan,
|
|
20
30
|
semanticDiagnostics, buildProof, sha256, COMPILER_VERSION,
|
|
@@ -41,6 +51,7 @@ import { buildMissionIndex } from './atlas.mjs';
|
|
|
41
51
|
import { parseSelection, regionMetrics, selectCandidate } from './select.mjs';
|
|
42
52
|
import { buildIntentGraph, safeGraph } from './intent-graph.mjs';
|
|
43
53
|
import { buildAtlas, searchAtlas, expandNode } from './intent-atlas.mjs';
|
|
54
|
+
import { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode } from './review-atlas.mjs';
|
|
44
55
|
import { buildFocusGraph, intentBrief, makeScope } from './focus.mjs';
|
|
45
56
|
import { comprehensionLevel, comprehensionReport, LEVELS as COMPREHENSION_LEVELS } from './comprehension.mjs';
|
|
46
57
|
import { twelveFactorReport } from './twelve-factor.mjs';
|
|
@@ -59,6 +70,11 @@ import { runTypescriptTarget } from './target-ts.mjs';
|
|
|
59
70
|
import { runPythonTarget, pythonAvailable } from './target-py.mjs';
|
|
60
71
|
import { runCSharpTarget, csharpAvailable } from './target-cs.mjs';
|
|
61
72
|
import { runJavaTarget, javaAvailable } from './target-java.mjs';
|
|
73
|
+
import { runGoTarget, goAvailable } from './target-go.mjs';
|
|
74
|
+
import { runRustTarget, rustAvailable } from './target-rust.mjs';
|
|
75
|
+
import { runKotlinTarget, kotlinAvailable } from './target-kotlin.mjs';
|
|
76
|
+
import { runScalaTarget, scalaAvailable } from './target-scala.mjs';
|
|
77
|
+
import { runElixirTarget, elixirAvailable } from './target-elixir.mjs';
|
|
62
78
|
|
|
63
79
|
// The live-target registry: one entry per canonical target that can be compiled + executed.
|
|
64
80
|
// `available()` is a (cached) toolchain probe; TypeScript/JS runs in-process so it is always live.
|
|
@@ -67,14 +83,25 @@ const LIVE_TARGETS = [
|
|
|
67
83
|
{ key: 'python', run: runPythonTarget, available: pythonAvailable },
|
|
68
84
|
{ key: 'csharp', run: runCSharpTarget, available: csharpAvailable },
|
|
69
85
|
{ key: 'java', run: runJavaTarget, available: javaAvailable },
|
|
86
|
+
{ key: 'go', run: runGoTarget, available: goAvailable },
|
|
87
|
+
{ key: 'rust', run: runRustTarget, available: rustAvailable },
|
|
88
|
+
{ key: 'kotlin', run: runKotlinTarget, available: kotlinAvailable },
|
|
89
|
+
{ key: 'scala', run: runScalaTarget, available: scalaAvailable },
|
|
90
|
+
{ key: 'elixir', run: runElixirTarget, available: elixirAvailable },
|
|
70
91
|
];
|
|
71
92
|
const LIVE_BY_KEY = new Map(LIVE_TARGETS.map((t) => [t.key, t]));
|
|
72
93
|
LIVE_BY_KEY.set('javascript', LIVE_BY_KEY.get('typescript')); // js is the same in-process runner
|
|
73
94
|
// All canonical targets available to run right now (used by --all-targets).
|
|
74
95
|
const availableLiveTargets = () => LIVE_TARGETS.filter((t) => t.available());
|
|
75
|
-
const RUNNABLE_TARGETS = new Set([
|
|
96
|
+
const RUNNABLE_TARGETS = new Set([
|
|
97
|
+
'typescript', 'ts', 'javascript', 'js', 'python', 'py', 'csharp', 'cs', 'c#', 'java',
|
|
98
|
+
'go', 'golang', 'rust', 'rs', 'kotlin', 'kt', 'scala', 'sc', 'elixir', 'ex',
|
|
99
|
+
]);
|
|
76
100
|
// Map an alias to its canonical target key + the adapter that executes it.
|
|
77
|
-
const TARGET_ALIASES = {
|
|
101
|
+
const TARGET_ALIASES = {
|
|
102
|
+
ts: 'typescript', js: 'javascript', py: 'python', cs: 'csharp', 'c#': 'csharp',
|
|
103
|
+
golang: 'go', rs: 'rust', kt: 'kotlin', sc: 'scala', ex: 'elixir',
|
|
104
|
+
};
|
|
78
105
|
const canonicalTarget = (t) => TARGET_ALIASES[String(t).toLowerCase()] || String(t).toLowerCase();
|
|
79
106
|
// Execute a live target. Returns { "Test / case": actual } or null if the target can't run
|
|
80
107
|
// (e.g. the runtime/SDK is not installed). Unknown targets return null.
|
|
@@ -84,6 +111,7 @@ function runLiveTarget(ast, target) {
|
|
|
84
111
|
}
|
|
85
112
|
import { importIntent, importReport, detectFormat, IMPORT_FORMATS } from './importers.mjs';
|
|
86
113
|
import { runTests } from './testing.mjs';
|
|
114
|
+
import { resolveObligations } from './obligations.mjs';
|
|
87
115
|
import { toEvidenceEvents, verifyDiffToEvidence, conformToEvidence, driftToEvidence } from './evidence.mjs';
|
|
88
116
|
import { evaluateOutcomes } from './outcome.mjs';
|
|
89
117
|
import { analyzeStyle } from './style.mjs';
|
|
@@ -123,6 +151,40 @@ function collectFiles(root, acc = []) {
|
|
|
123
151
|
return acc;
|
|
124
152
|
}
|
|
125
153
|
|
|
154
|
+
// `thunder read <dir>`: one searchable reading of a whole repository, grouped by file.
|
|
155
|
+
function readFolder(dir, args) {
|
|
156
|
+
const index = readRepo(collectReadableFiles(dir));
|
|
157
|
+
const items = searchRepo(index, {
|
|
158
|
+
query: args.search || '', kinds: args.kind || [], languages: args.langs || [],
|
|
159
|
+
path: args.pathPrefix || '', answer: args.answer || '', input: args.input || '',
|
|
160
|
+
});
|
|
161
|
+
if (args.json) { console.log(JSON.stringify({ ...index, items }, null, 2)); return; }
|
|
162
|
+
const c = index.counts;
|
|
163
|
+
const langs = Object.entries(index.languages).map(([l, n]) => `${l} ${n}`).join(', ') || 'none';
|
|
164
|
+
console.log(`${dir}: ${index.files.length} files read (${langs}). ${c.route} route(s), ${c.decision} decision(s), ${c.function} other function(s) (${c.guarded} with checks), ${c.error} error(s), ${c.test} test(s). Inferred from code; confirm before relying on it.`);
|
|
165
|
+
if (index.skipped.length) console.log(`${index.skipped.length} file(s) skipped: ${index.skipped.slice(0, 5).map((s) => `${s.path} (${s.reason})`).join('; ')}${index.skipped.length > 5 ? '; ...' : ''}`);
|
|
166
|
+
const filtered = items.length !== index.items.length;
|
|
167
|
+
if (!filtered && index.answers.length) {
|
|
168
|
+
console.log(`\nAnswers the code gives: ${index.answers.slice(0, 12).map((a) => `${a.name} (${a.decisions.length})`).join(', ')}`);
|
|
169
|
+
console.log('Narrow with --answer <Outcome>, --input <name>, --search <words>, --kind, --lang, or --path.');
|
|
170
|
+
}
|
|
171
|
+
if (!items.length) { console.log('\nNothing matches. Try fewer words or fewer filters.'); return; }
|
|
172
|
+
const limit = Number.isFinite(args.limit) && args.limit > 0 ? args.limit : (filtered ? Infinity : 40);
|
|
173
|
+
let shown = 0;
|
|
174
|
+
for (const g of groupByFile(items)) {
|
|
175
|
+
if (shown >= limit) break;
|
|
176
|
+
console.log(`\n${g.file} (${g.language})`);
|
|
177
|
+
for (const it of g.items) {
|
|
178
|
+
if (shown++ >= limit) break;
|
|
179
|
+
console.log(` [${it.kind}${it.status === 'partial' ? ', partly read' : ''}] ${it.name} line ${it.line}: ${it.says}`);
|
|
180
|
+
if (args.inLang && it.thunder) {
|
|
181
|
+
for (const l of translateDecisions(parseIntent(it.thunder), args.inLang).split('\n').slice(2)) console.log(` ${l}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (items.length > shown) console.log(`\n${items.length - Math.min(shown, items.length)} more. Narrow the search, or pass --limit ${items.length}.`);
|
|
186
|
+
}
|
|
187
|
+
|
|
126
188
|
// Walk a directory for authored source files (skips the .intent/ output dir).
|
|
127
189
|
function collectIntents(root, acc = []) {
|
|
128
190
|
const st = statSync(root);
|
|
@@ -136,43 +198,6 @@ function collectIntents(root, acc = []) {
|
|
|
136
198
|
return acc;
|
|
137
199
|
}
|
|
138
200
|
|
|
139
|
-
// Resolve every guarantee/never obligation against the SPECIFIC test that verifies it.
|
|
140
|
-
// Shared by `thunder test --contracts` and `thunder prove` so both agree per-claim.
|
|
141
|
-
// States: verified (proven by a passing named test), failed (its test fails), declared
|
|
142
|
-
// (a verification is named/classified but not runnable in-file), unverified (nothing).
|
|
143
|
-
function resolveObligations(ast) {
|
|
144
|
-
const t = runTests(ast);
|
|
145
|
-
const testPass = new Map();
|
|
146
|
-
for (const res of (t.results || [])) {
|
|
147
|
-
const cur = testPass.get(res.target);
|
|
148
|
-
testPass.set(res.target, cur === undefined ? !!res.pass : cur && !!res.pass);
|
|
149
|
-
}
|
|
150
|
-
const norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
151
|
-
const matchTest = (verifyText) => {
|
|
152
|
-
const v = norm(verifyText); if (!v) return null;
|
|
153
|
-
for (const [name, pass] of testPass) { const n = norm(name); if (n && (n === v || n.includes(v) || v.includes(n))) return { name, pass }; }
|
|
154
|
-
return null;
|
|
155
|
-
};
|
|
156
|
-
const build = (kind, o) => {
|
|
157
|
-
const verify = o.verify || [];
|
|
158
|
-
const kinds = [...new Set((o.verifications || []).map((v) => v.kind).filter((k) => k && k !== 'unclassified'))];
|
|
159
|
-
let status, provenBy = null;
|
|
160
|
-
if (!verify.length) status = 'unverified';
|
|
161
|
-
else {
|
|
162
|
-
let m = null;
|
|
163
|
-
for (const vt of verify) { const x = matchTest(vt); if (x) { m = x; if (!x.pass) break; } }
|
|
164
|
-
if (m) { status = m.pass ? 'verified' : 'failed'; provenBy = m.name; } else status = 'declared';
|
|
165
|
-
}
|
|
166
|
-
return { kind, id: o.id, text: o.statement, status, verify, kinds, provenBy };
|
|
167
|
-
};
|
|
168
|
-
const obligations = [
|
|
169
|
-
...ast.guarantees.map((g) => build('guarantee', g)),
|
|
170
|
-
...ast.neverRules.map((n) => build('prohibition', n)),
|
|
171
|
-
];
|
|
172
|
-
const count = (s) => obligations.filter((o) => o.status === s).length;
|
|
173
|
-
return { obligations, tests: t, verified: count('verified'), declared: count('declared'), unverified: count('unverified'), failed: count('failed') };
|
|
174
|
-
}
|
|
175
|
-
|
|
176
201
|
// Proof freshness: a proof is valid only for a specific (intent, implementation, dependencies,
|
|
177
202
|
// compiler, environment) tuple. These helpers capture that tuple so `verify` can mark a proof STALE.
|
|
178
203
|
const gitCmd = (c) => { try { return execSync(`git ${c}`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim() || null; } catch { return null; } };
|
|
@@ -219,6 +244,12 @@ function parseArgs(argv) {
|
|
|
219
244
|
else if (a === '--by') args.by = argv[++i];
|
|
220
245
|
else if (a === '--at') args.at = argv[++i];
|
|
221
246
|
else if (a === '--json') args.json = true;
|
|
247
|
+
else if (a === '--review') args.review = true;
|
|
248
|
+
else if (a === '--agent-brief') args.agentBrief = true;
|
|
249
|
+
else if (a === '--openthunder') {
|
|
250
|
+
if (!argv[i + 1] || argv[i + 1].startsWith('--')) throw new Error('--openthunder requires a JSON report path');
|
|
251
|
+
args.openthunder = argv[++i];
|
|
252
|
+
}
|
|
222
253
|
else if (a === '--targets') args.targets = (argv[++i] || '').split(',').filter(Boolean);
|
|
223
254
|
else if (a === '--product') args.product = argv[++i];
|
|
224
255
|
else if (a === '--allow-pending') args.allowPending = true;
|
|
@@ -226,12 +257,22 @@ function parseArgs(argv) {
|
|
|
226
257
|
else if (a === '--role') args.role = argv[++i];
|
|
227
258
|
else if (a === '--note') args.note = argv[++i];
|
|
228
259
|
else if (a === '--search') args.search = argv[++i];
|
|
260
|
+
else if (a === '--kind') args.kind = (argv[++i] || '').split(',').map((k) => k.trim()).filter(Boolean);
|
|
261
|
+
else if (a === '--in') args.inLang = argv[++i];
|
|
262
|
+
else if (a === '--answer') args.answer = argv[++i];
|
|
263
|
+
else if (a === '--promote') args.promote = argv[++i];
|
|
264
|
+
else if (a === '--input') args.input = argv[++i];
|
|
265
|
+
else if (a === '--lang') args.langs = (argv[++i] || '').split(',').map((k) => k.trim()).filter(Boolean);
|
|
266
|
+
else if (a === '--path') args.pathPrefix = argv[++i];
|
|
267
|
+
else if (a === '--limit') args.limit = Number(argv[++i]);
|
|
229
268
|
else if (a === '--expand') args.expand = argv[++i];
|
|
230
269
|
else if (a === '--now') args.now = argv[++i];
|
|
231
270
|
else if (a === '--format') args.format = argv[++i];
|
|
232
271
|
else if (a === '--inputs') args.inputs = argv[++i];
|
|
233
272
|
else if (a === '--events') args.events = (argv[++i] || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
234
273
|
else if (a === '--decision') args.decision = argv[++i];
|
|
274
|
+
else if (a === '--rule') args.rule = argv[++i];
|
|
275
|
+
else if (a === '--when') args.when = argv[++i];
|
|
235
276
|
else if (a === '--to') args.to = argv[++i];
|
|
236
277
|
else if (a === '--force') args.force = true;
|
|
237
278
|
else if (a === '--write' || a === '-w') args.write = true;
|
|
@@ -355,11 +396,13 @@ Inspect
|
|
|
355
396
|
docs <file> [--lens <lens>] [--out <dir>] render a mission as Markdown docs (per-audience with --lens)
|
|
356
397
|
index <dir> the Mission Atlas inventory
|
|
357
398
|
atlas <dir> [--search q | --expand id] the whole-system Atlas
|
|
399
|
+
atlas <dir> --review [--json | --agent-brief] [--openthunder report.json] [--strict]
|
|
400
|
+
execute contract cases, rank review gaps, compare OpenThunder snapshots
|
|
358
401
|
|
|
359
402
|
Run & test
|
|
360
403
|
run <file> --inputs '<json>' execute the decision(s) deterministically
|
|
361
404
|
test <file> [--contracts | --properties | --scenarios | --mutate | --evals | --changed | --coverage] [--strict]
|
|
362
|
-
test <file> --target typescript|python|csharp|java run the tests against the EXECUTED generated code
|
|
405
|
+
test <file> --target typescript|python|csharp|java|go|rust|kotlin|scala|elixir run the tests against the EXECUTED generated code
|
|
363
406
|
test <file> --all-targets run the tests against every AVAILABLE target in one pass
|
|
364
407
|
simulate <file> --events a,b,c walk the lifecycle(s) over events
|
|
365
408
|
outcomes <file> evaluate outcome contracts vs delivery results
|
|
@@ -374,7 +417,7 @@ Prove & verify intent
|
|
|
374
417
|
verify <proof.json> [src] re-check a proof; reports STALE when impl/deps/compiler moved
|
|
375
418
|
evidence <file> emit evidence-event-v1 JSON (tool_verified) for the shared proof spine
|
|
376
419
|
(also: prove/verify-diff/conform/drift accept --evidence to emit their own event)
|
|
377
|
-
conform <file> [--targets a,b] [--run typescript,python,csharp,java | --all-targets] [--results <json>] conformance matrix across targets
|
|
420
|
+
conform <file> [--targets a,b] [--run typescript,python,csharp,java,go,rust,kotlin,scala,elixir | --all-targets] [--results <json>] conformance matrix across targets
|
|
378
421
|
|
|
379
422
|
Real code vs intent (drift)
|
|
380
423
|
lift <file> [--from <lang>] lift source code into inferred intent
|
|
@@ -391,6 +434,19 @@ Real code vs intent (drift)
|
|
|
391
434
|
guard <file> [--json] preview the runtime guard (redacted fields, enforced decisions)
|
|
392
435
|
|
|
393
436
|
Graph & IR
|
|
437
|
+
human <file> [--json | --format source] experimental compact authoring and a decision reading view
|
|
438
|
+
--version print the Thunder compiler version
|
|
439
|
+
anchor <file> [--json] show every Thunder step with its exact place in the file, and line coverage
|
|
440
|
+
write <file> --decision <name> --rule <n|otherwise> [--when "<condition>"] [--answer <Outcome>] [--write] [--json]
|
|
441
|
+
Thunder write: change a number, comparison, text value, or answer in a recovered rule;
|
|
442
|
+
previews the exact code change and the cases whose answer changes; --write saves it
|
|
443
|
+
repo <owner/repo | github url | folder> [--json] [--max-files n] Thunder a whole repository (read-only; nothing is executed)
|
|
444
|
+
text <file> [--json | --format source] experimental Thunder Text rule (.thunder-plain): run its examples [alias: plain]
|
|
445
|
+
read <file|dir> [--search q] [--kind decision,function,error,test] [--in <lang>] [--from <lang>] [--json]
|
|
446
|
+
for a folder also: [--answer <Outcome>] [--input <name>] [--lang go,rust] [--path <prefix>] [--limit n]
|
|
447
|
+
--promote <decision> [--out <file>] turn a recovered decision into a contract with starter examples
|
|
448
|
+
read code you don't know: its decision rules as ThunderLang + plain English,
|
|
449
|
+
optionally rewritten in a language you know (--in typescript|python|go|rust|csharp|java)
|
|
394
450
|
graph <file> [--safe] the canonical Intent Graph (intent-graph-v1); --safe = display-safe on stdout
|
|
395
451
|
migrate <graph.json> [--to <version>] upgrade a persisted graph
|
|
396
452
|
validate <graph.json> [--json] check a graph is canonical (anti-fork)
|
|
@@ -415,10 +471,134 @@ function main() {
|
|
|
415
471
|
const [cmd, ...restArgv] = process.argv.slice(2);
|
|
416
472
|
const args = parseArgs(restArgv);
|
|
417
473
|
const file = args._[0];
|
|
474
|
+
if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
|
|
475
|
+
console.log(`thunder ${COMPILER_VERSION} (the Thunder compiler, also called ThunderLang)`);
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
418
478
|
if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') {
|
|
419
479
|
console.log(HELP);
|
|
420
480
|
process.exit(cmd ? 0 : 2);
|
|
421
481
|
}
|
|
482
|
+
if (cmd === 'read') {
|
|
483
|
+
try {
|
|
484
|
+
if (!file) throw new Error('Use thunder read <file> [--search q] [--kind decision,function,error,test] [--in <lang>] [--json].');
|
|
485
|
+
if (statSync(file).isDirectory()) { readFolder(file, args); return; }
|
|
486
|
+
if (args.promote) {
|
|
487
|
+
const items = statSync(file).isDirectory()
|
|
488
|
+
? searchRepo(readRepo(collectReadableFiles(file)), { path: args.pathPrefix || '' })
|
|
489
|
+
: readCode(readFileSync(file, 'utf8'), { language: args.from, file: basename(file) }).items.map((it) => ({ ...it, file: basename(file) }));
|
|
490
|
+
const matches = items.filter((it) => it.kind === 'decision' && it.name === args.promote);
|
|
491
|
+
if (!matches.length) throw new Error(`No decision named ${args.promote}. Run thunder read ${file} --kind decision to list them.`);
|
|
492
|
+
if (matches.length > 1) throw new Error(`${matches.length} decisions are named ${args.promote} (${matches.map((m) => m.file).join(', ')}). Narrow with --path.`);
|
|
493
|
+
const p = promoteDecision(matches[0]);
|
|
494
|
+
if (!p.ok) throw new Error(p.reason);
|
|
495
|
+
const report = previewHumanContract(p.source);
|
|
496
|
+
if (args.out) {
|
|
497
|
+
writeFileSync(args.out, p.source);
|
|
498
|
+
console.error(`Wrote ${args.out}: ${report.tests.total} examples recording what the code does today (${report.tests.passed} pass).`);
|
|
499
|
+
console.error(`Next: confirm each answer with a person, then: thunder human ${args.out} --format source > ${p.name}.thunder`);
|
|
500
|
+
} else process.stdout.write(p.source);
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
const reading = readCode(readFileSync(file, 'utf8'), { language: args.from, file: basename(file) });
|
|
504
|
+
const items = searchReading(reading, { query: args.search || '', kinds: args.kind || [] });
|
|
505
|
+
if (args.json) { console.log(JSON.stringify({ ...reading, items }, null, 2)); return; }
|
|
506
|
+
const c = reading.counts;
|
|
507
|
+
console.log(`${basename(file)} (${reading.language}${reading.detected ? ', detected' : ''}): ${c.decision} decision(s), ${c.function} other function(s), ${c.error} error(s), ${c.test} test(s). Inferred from code; confirm before relying on it.`);
|
|
508
|
+
if (!items.length) console.log('\nNothing matches. Try fewer words or remove --kind.');
|
|
509
|
+
for (const it of items) {
|
|
510
|
+
console.log(`\n[${it.kind}${it.status === 'partial' ? ', partly read' : ''}] ${it.name} (line ${it.line})`);
|
|
511
|
+
console.log(` ${it.says}`);
|
|
512
|
+
if (it.thunder) {
|
|
513
|
+
console.log('');
|
|
514
|
+
for (const l of it.thunder.split('\n')) console.log(` ${l}`);
|
|
515
|
+
if (args.inLang) {
|
|
516
|
+
const code = translateDecisions(parseIntent(it.thunder), args.inLang).split('\n').slice(2);
|
|
517
|
+
console.log(`\n In ${args.inLang}:`);
|
|
518
|
+
for (const l of code) console.log(` ${l}`);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
for (const u of it.unread || []) console.log(` not read (line ${u.line}): ${u.text} ${u.reason}`);
|
|
522
|
+
}
|
|
523
|
+
} catch (e) { console.error(`thunder read: ${e.message}`); process.exitCode = 2; }
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
if (cmd === 'write') {
|
|
527
|
+
try {
|
|
528
|
+
if (!file || !args.decision || !args.rule || (args.when == null && args.answer == null)) throw new Error('Use thunder write <file> --decision <name> --rule <n|otherwise> --when "<condition>" | --answer <Outcome> [--write].');
|
|
529
|
+
const source = readFileSync(file, 'utf8');
|
|
530
|
+
const r = writeRule({ source, language: args.from, file: basename(file), decision: args.decision, rule: args.rule === 'otherwise' ? 'otherwise' : Number(args.rule), when: args.when ?? null, answer: args.answer ?? null });
|
|
531
|
+
if (r.ok && args.write) writeFileSync(file, r.source);
|
|
532
|
+
if (args.json) { const { source: _s, ...rest } = r; console.log(JSON.stringify({ ...rest, written: !!(r.ok && args.write) }, null, 2)); if (!r.ok) process.exitCode = 1; return; }
|
|
533
|
+
if (!r.ok) {
|
|
534
|
+
console.error(`Not changed. ${file} is untouched.`);
|
|
535
|
+
for (const p of r.problems) console.error(` ${p}`);
|
|
536
|
+
process.exitCode = 1;
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
console.log(`${r.decision}, rule ${r.rule}`);
|
|
540
|
+
console.log(` was: ${r.before}`);
|
|
541
|
+
console.log(` now: ${r.after}`);
|
|
542
|
+
console.log('\nCode change (only these characters):');
|
|
543
|
+
for (const c of r.change) console.log(` line ${c.line}, column ${c.column}: ${c.before} -> ${c.after}`);
|
|
544
|
+
console.log('\nChecked by reading the file again: this rule reads as intended; every other rule and function reads exactly as before.');
|
|
545
|
+
console.log(`\n${r.cases.note}`);
|
|
546
|
+
const names = r.cases.changed[0] ? Object.keys(r.cases.changed[0].inputs) : [];
|
|
547
|
+
for (const c of r.cases.changed.slice(0, 8)) console.log(` ${names.map((n) => `${n} ${JSON.stringify(c.inputs[n])}`).join(', ')}: ${c.before} -> ${c.after}`);
|
|
548
|
+
if (r.cases.changed.length > 8) console.log(` ...and ${r.cases.changed.length - 8} more (use --json for all).`);
|
|
549
|
+
console.log(args.write ? `\nSaved ${file}. Run your tests before you commit.` : '\nPreview only; nothing was saved. Add --write to save the change.');
|
|
550
|
+
} catch (e) { console.error(`thunder write: ${e.message}`); process.exitCode = 2; }
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
if (cmd === 'anchor') {
|
|
554
|
+
try {
|
|
555
|
+
if (!file) throw new Error('Use thunder anchor <file> [--json].');
|
|
556
|
+
const r = anchorReport(readFileSync(file, 'utf8'), { language: args.from, file: basename(file) });
|
|
557
|
+
if (args.json) { console.log(JSON.stringify(r, null, 2)); return; }
|
|
558
|
+
console.log(`${basename(file)} (${r.language}): ${Math.round(r.coverage * 1000) / 10}% of code lines are anchored to a Thunder step.`);
|
|
559
|
+
for (const f of r.functions) {
|
|
560
|
+
console.log(`\n${f.name} (line ${f.line}) ${Math.round(f.coverage * 100)}% anchored${f.missing.length ? `; not yet anchored: line ${f.missing.join(', ')}` : ''}`);
|
|
561
|
+
for (const s of f.steps) console.log(` ${s.path.padEnd(5)} ${s.span.startLine === s.span.endLine ? `L${s.span.startLine}` : `L${s.span.startLine}-${s.span.endLine}`}`.padEnd(18) + `${s.kind.padEnd(7)} ${s.says}`);
|
|
562
|
+
}
|
|
563
|
+
} catch (e) { console.error(`thunder anchor: ${e.message}`); process.exitCode = 2; }
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
if (cmd === 'repo') {
|
|
567
|
+
try {
|
|
568
|
+
if (!file) throw new Error('Use thunder repo <owner/repo | https://github.com/owner/repo | folder> [--json].');
|
|
569
|
+
const report = thunderRepo(file, { maxFiles: args.maxFiles ? Number(args.maxFiles) : undefined });
|
|
570
|
+
console.log(args.json ? JSON.stringify(report, null, 2) : renderThunderRepo(report));
|
|
571
|
+
process.exitCode = report.errors.length ? 1 : 0;
|
|
572
|
+
} catch (e) { console.error(`thunder repo: ${e.message}`); process.exitCode = 2; }
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
if (cmd === 'plain' || cmd === 'text') {
|
|
576
|
+
try {
|
|
577
|
+
if (!file) throw new Error('Use thunder plain <file> [--json | --format source].');
|
|
578
|
+
if (args.format && args.format !== 'source') throw new Error('The supported format is source; omit --format to run the examples.');
|
|
579
|
+
const report = previewPlainContract(readFileSync(file, 'utf8'));
|
|
580
|
+
if (args.json) console.log(JSON.stringify(report, null, 2));
|
|
581
|
+
else if (args.format === 'source') process.stdout.write(report.canonicalSource);
|
|
582
|
+
else {
|
|
583
|
+
console.log(`${report.model.title}: ${report.tests.passed} of ${report.tests.total} examples pass. Application: not checked.`);
|
|
584
|
+
for (const r of report.tests.results) if (!r.pass) console.log(` failed: ${r.name}: expected ${r.expected}, got ${r.actual}`);
|
|
585
|
+
}
|
|
586
|
+
process.exitCode = report.tests.failed ? 1 : 0;
|
|
587
|
+
} catch (e) { console.error(`thunder plain: ${e.message}`); process.exitCode = 2; }
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if (cmd === 'human') {
|
|
591
|
+
try {
|
|
592
|
+
if (!file) throw new Error('Use thunder human <file> [--json | --format source].');
|
|
593
|
+
if (args.format && args.format !== 'source') throw new Error('The supported format is source; omit --format for the reading view.');
|
|
594
|
+
const report = previewHumanContract(readFileSync(file, 'utf8'));
|
|
595
|
+
if (args.json) console.log(JSON.stringify(report, null, 2));
|
|
596
|
+
else if (args.format === 'source') process.stdout.write(report.canonicalSource);
|
|
597
|
+
else console.log(renderHumanContract(report));
|
|
598
|
+
process.exitCode = report.tests.failed ? 1 : report.tests.total ? 0 : 2;
|
|
599
|
+
} catch (e) { console.error(`thunder human: ${e.message}`); process.exitCode = 2; }
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
422
602
|
// `schema` takes no file (it emits the canonical Intent Graph schema).
|
|
423
603
|
if (cmd === 'schema') {
|
|
424
604
|
const out = {
|
|
@@ -666,7 +846,10 @@ function main() {
|
|
|
666
846
|
const code = generate(ast);
|
|
667
847
|
if (args.outExplicit) {
|
|
668
848
|
const ext = target.startsWith('ts') || target === 'typescript' ? 'ts' : target === 'python' ? 'py' : target === 'csharp' ? 'cs' : target;
|
|
669
|
-
|
|
849
|
+
// Java requires a public class to live in a file of exactly its name (RefundDecision.java).
|
|
850
|
+
const subject = subjectName(ast) || 'intent';
|
|
851
|
+
const fileName = ext === 'java' ? `${(subject[0].toUpperCase() + subject.slice(1)).replace(/[^A-Za-z0-9]/g, '')}.java` : `${slug(subject)}.${ext}`;
|
|
852
|
+
const p = writeText(args.out, fileName, code.endsWith('\n') ? code : code + '\n');
|
|
670
853
|
console.log(`wrote ${p.replace(process.cwd() + '/', '')}`);
|
|
671
854
|
return;
|
|
672
855
|
}
|
|
@@ -1736,6 +1919,15 @@ test Example
|
|
|
1736
1919
|
// Intent Atlas: the navigable/searchable whole-system map over the Intent Graph.
|
|
1737
1920
|
if (cmd === 'atlas') {
|
|
1738
1921
|
const root = file || '.';
|
|
1922
|
+
if (args.review || args.agentBrief || args.openthunder) {
|
|
1923
|
+
if (args.search || args.expand) throw new Error('Review mode cannot be combined with graph search or expansion.');
|
|
1924
|
+
const files = collectIntents(root).map((f) => ({ path: relative(root, f) || basename(f), source: readFileSync(f, 'utf8') }));
|
|
1925
|
+
const evidence = args.openthunder ? JSON.parse(readFileSync(args.openthunder, 'utf8')) : undefined;
|
|
1926
|
+
const review = buildReviewAtlas(files, { product: args.product, evidence });
|
|
1927
|
+
console.log(args.json ? JSON.stringify(review, null, 2) : renderReviewBrief(review));
|
|
1928
|
+
process.exitCode = reviewAtlasExitCode(review, { strict: args.strict });
|
|
1929
|
+
return;
|
|
1930
|
+
}
|
|
1739
1931
|
const graphs = collectIntents(root).map((f) => buildIntentGraph(parseIntent(readFileSync(f, 'utf8'))));
|
|
1740
1932
|
const atlas = buildAtlas(graphs, { product: args.product });
|
|
1741
1933
|
if (args.search) {
|
package/src/codegen.mjs
CHANGED
|
@@ -9,6 +9,15 @@
|
|
|
9
9
|
|
|
10
10
|
import { exprToJs, exprToCSharp, exprToJava, exprToPython } from './expr.mjs';
|
|
11
11
|
import { subjectName } from './parse.mjs';
|
|
12
|
+
import { inputNames, inferInputTypes } from './target-types.mjs';
|
|
13
|
+
|
|
14
|
+
// 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
|
+
const decisionParams = (ast, d) => { const names = inputNames(d); const types = inferInputTypes(ast, d); return names.map((name) => ({ name, type: types[name] })); };
|
|
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' };
|
|
12
21
|
|
|
13
22
|
export const CODEGEN_SCHEMA = 'intent-codegen-v1';
|
|
14
23
|
|
|
@@ -60,8 +69,9 @@ export function toTypeScript(ast) {
|
|
|
60
69
|
|
|
61
70
|
// Decisions , real, first-hit logic (the intent already executes these).
|
|
62
71
|
for (const d of ast.decisions || []) {
|
|
63
|
-
const
|
|
64
|
-
const
|
|
72
|
+
const ps = decisionParams(ast, d);
|
|
73
|
+
const inputs = ps.map((x) => x.name);
|
|
74
|
+
const params = ps.map((x) => `${x.name}: ${TS_PARAM[x.type]}`).join(', ');
|
|
65
75
|
L.push(`// decision ${d.name} , first matching rule wins.`);
|
|
66
76
|
L.push(`export function ${lower(pascal(d.name))}(${params}): string {`);
|
|
67
77
|
for (const r of d.rules || []) {
|
|
@@ -78,7 +88,10 @@ export function toTypeScript(ast) {
|
|
|
78
88
|
const inName = (ast.inputs || []).length ? `${subject}Input` : 'void';
|
|
79
89
|
const outName = (ast.outputs || []).length ? `${subject}Output` : 'void';
|
|
80
90
|
const arg = inName === 'void' ? '' : `input: ${inName}`;
|
|
81
|
-
|
|
91
|
+
// A decision often shares the mission's name (RefundDecision); the mission function is then `run`, as in Java and Python.
|
|
92
|
+
const decisionFns = new Set((ast.decisions || []).map((d) => lower(pascal(d.name))));
|
|
93
|
+
const missionFn = decisionFns.has(lower(subject)) ? 'run' : lower(subject);
|
|
94
|
+
L.push(`export function ${missionFn}(${arg}): ${outName} {`);
|
|
82
95
|
for (const r of ast.requires || []) L.push(` // precondition: ${r} , TODO: validate`);
|
|
83
96
|
for (const n of ast.neverRules || []) L.push(` // NEVER: ${n.statement} , your code must not do this`);
|
|
84
97
|
for (const g of ast.guarantees || []) L.push(` // GUARANTEE: ${g.statement} , your code must uphold this${g.verify?.length ? ` (verify: ${g.verify.join(', ')})` : ''}`);
|
|
@@ -133,9 +146,12 @@ export function toCSharp(ast) {
|
|
|
133
146
|
if ((ast.outputs || []).length) L.push(...rec(`${subject}Output`, ast.outputs));
|
|
134
147
|
L.push(`public static class ${subject}`, '{');
|
|
135
148
|
for (const d of ast.decisions || []) {
|
|
136
|
-
const
|
|
149
|
+
const ps = decisionParams(ast, d);
|
|
150
|
+
const inputs = ps.map((x) => x.name);
|
|
151
|
+
// A C# member cannot share its class's name (CS0542): a decision named like the mission becomes Decide.
|
|
152
|
+
const method = pascal(d.name) === subject ? 'Decide' : pascal(d.name);
|
|
137
153
|
L.push(` // decision ${d.name} , first matching rule wins.`);
|
|
138
|
-
L.push(` public static string ${
|
|
154
|
+
L.push(` public static string ${method}(${ps.map((x) => `${CS_PARAM[x.type]} ${x.name}`).join(', ')})`);
|
|
139
155
|
L.push(' {');
|
|
140
156
|
for (const r of d.rules || []) {
|
|
141
157
|
let cond; try { cond = exprToCSharp(r.when, { inputs }); } catch { cond = `false /* TODO: could not translate "${r.when}" */`; }
|
|
@@ -189,9 +205,10 @@ export function toJava(ast) {
|
|
|
189
205
|
if ((ast.inputs || []).length) L.push(...rec(`${subject}Input`, ast.inputs));
|
|
190
206
|
if ((ast.outputs || []).length) L.push(...rec(`${subject}Output`, ast.outputs));
|
|
191
207
|
for (const d of ast.decisions || []) {
|
|
192
|
-
const
|
|
208
|
+
const ps = decisionParams(ast, d);
|
|
209
|
+
const inputs = ps.map((x) => x.name);
|
|
193
210
|
L.push(` // decision ${d.name} , first matching rule wins.`);
|
|
194
|
-
L.push(` public static String ${lower(pascal(d.name))}(${
|
|
211
|
+
L.push(` public static String ${lower(pascal(d.name))}(${ps.map((x) => `${JAVA_PARAM[x.type]} ${x.name}`).join(', ')}) {`);
|
|
195
212
|
for (const r of d.rules || []) {
|
|
196
213
|
let cond; try { cond = exprToJava(r.when, { inputs }); } catch { cond = `false /* TODO: could not translate "${r.when}" */`; }
|
|
197
214
|
L.push(` if (${cond}) return ${JSON.stringify(r.result)}; // rule ${r.name}`);
|
|
@@ -247,9 +264,10 @@ export function toPython(ast) {
|
|
|
247
264
|
if ((ast.inputs || []).length) L.push(...cls(`${subject}Input`, ast.inputs));
|
|
248
265
|
if ((ast.outputs || []).length) L.push(...cls(`${subject}Output`, ast.outputs));
|
|
249
266
|
for (const d of ast.decisions || []) {
|
|
250
|
-
const
|
|
267
|
+
const ps = decisionParams(ast, d);
|
|
268
|
+
const inputs = ps.map((x) => x.name);
|
|
251
269
|
L.push(`# decision ${d.name} , first matching rule wins.`);
|
|
252
|
-
L.push(`def ${snake(d.name)}(${
|
|
270
|
+
L.push(`def ${snake(d.name)}(${ps.map((x) => `${x.name}: ${PY_PARAM[x.type]}`).join(', ')}) -> str:`);
|
|
253
271
|
for (const r of d.rules || []) {
|
|
254
272
|
let cond, note = '';
|
|
255
273
|
try { cond = exprToPython(r.when, { inputs }); }
|