@skillstech/thunderlang 1.0.4 → 1.2.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 +221 -0
- package/README.md +4 -1
- package/dist/core.cjs +2568 -462
- package/dist/index.cjs +7562 -5084
- package/dist/learn.cjs +16994 -8339
- package/intent-graph.schema.json +11 -0
- package/package.json +6 -2
- package/src/cli-home.mjs +242 -0
- package/src/cli.mjs +241 -89
- package/src/codegen.mjs +145 -55
- package/src/conformance.mjs +15 -6
- package/src/core/check.mjs +725 -0
- package/src/core/cli.mjs +184 -0
- package/src/core/diagnostics.mjs +82 -0
- package/src/core/engine-core.mjs +572 -0
- package/src/core/engine-values.mjs +1054 -0
- package/src/core/engine-worker.mjs +15 -0
- package/src/core/engine.mjs +63 -0
- package/src/core/format.mjs +20 -0
- package/src/core/from-python.mjs +645 -0
- package/src/core/index.mjs +39 -0
- package/src/core/lexer.mjs +115 -0
- package/src/core/parser.mjs +742 -0
- package/src/core/project.mjs +177 -0
- package/src/core/round-trip.mjs +150 -0
- package/src/core/runtime-python.mjs +801 -0
- package/src/core/runtime-typescript.mjs +119 -0
- package/src/core/target-python.mjs +487 -0
- package/src/core/target-typescript.mjs +466 -0
- package/src/core/typescript-run.mjs +114 -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/learn-lessons.mjs +245 -1
- package/src/learn.d.mts +8 -0
- package/src/learn.mjs +40 -4
- 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-level.mjs +146 -0
- 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/term.mjs +89 -0
- 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/try-cli.mjs +225 -0
- package/src/why-cli.mjs +41 -0
- package/src/why.d.mts +38 -0
- package/src/why.mjs +613 -0
- package/src/write-steps.mjs +22 -5
package/src/target-rust.mjs
CHANGED
|
@@ -1,50 +1,50 @@
|
|
|
1
1
|
// Rust target adapter. Emits a self-contained single-file program that defines each decision as a
|
|
2
2
|
// typed fn (using the same exprToRust translator the codegen uses), calls every test case with
|
|
3
3
|
// typed literal arguments, and prints the results as one JSON line. It compiles with `rustc` and
|
|
4
|
-
// runs the produced binary, so a live Rust run grades real compiled + executed code.
|
|
5
|
-
//
|
|
6
|
-
|
|
4
|
+
// runs the produced binary, so a live Rust run grades real compiled + executed code.
|
|
5
|
+
//
|
|
6
|
+
// Results are honest (see target-result.mjs): a missing toolchain, a compile failure, a crash, or a
|
|
7
|
+
// timeout is a structured error, never a null answer; a decision with a rule Thunder cannot
|
|
8
|
+
// translate is refused ('not-translated'). Money inputs are i64 minor units, never floats.
|
|
7
9
|
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
|
8
10
|
import { join } from 'node:path';
|
|
9
11
|
import { tmpdir } from 'node:os';
|
|
10
12
|
import { exprToRust } from './expr.mjs';
|
|
11
|
-
import {
|
|
13
|
+
import { parseLastJsonObject, cachedSmoke, strLit, litFor, prepareRun, plansFor, argLit, finishRun, runFailure, classifySpawn, spawnStep } from './target-util.mjs';
|
|
12
14
|
|
|
13
|
-
const RUST_TYPE = { number: 'f64', bool: 'bool', string: '&str' };
|
|
15
|
+
const RUST_TYPE = { number: 'f64', bool: 'bool', string: '&str', money: 'i64' };
|
|
16
|
+
const RUST_RUN = { translate: exprToRust, target: 'Rust', dialect: 'rust' };
|
|
14
17
|
// f64 params reject bare integer literals, so numeric args carry an explicit f64 suffix.
|
|
15
18
|
const rustLit = (type, v) => (type === 'number' ? `${v == null ? 0 : v}f64` : litFor(type, v));
|
|
16
19
|
|
|
17
|
-
// Compile `source` with rustc and run the binary. Returns
|
|
20
|
+
// Compile `source` with rustc and run the binary. Returns { ok, stdout } or { ok: false, failure }.
|
|
18
21
|
function rustcRun(dir, source) {
|
|
19
22
|
const src = join(dir, 'main.rs');
|
|
20
23
|
const bin = join(dir, process.platform === 'win32' ? 'main.exe' : 'main_bin');
|
|
21
24
|
writeFileSync(src, source);
|
|
22
25
|
const env = { ...process.env };
|
|
23
|
-
const c =
|
|
24
|
-
if (c.
|
|
25
|
-
|
|
26
|
-
if (r.status !== 0) return null;
|
|
27
|
-
return r.stdout;
|
|
26
|
+
const c = spawnStep('rustc', ['-O', src, '-o', bin], { timeout: 180000, env }, (r) => classifySpawn(r, { tool: 'rustc', phase: 'compile' }));
|
|
27
|
+
if (!c.ok) return c;
|
|
28
|
+
return spawnStep(bin, [], { timeout: 60000, env }, (r) => classifySpawn(r, { tool: 'the compiled Rust program', phase: 'run' }));
|
|
28
29
|
}
|
|
29
30
|
|
|
30
31
|
// The emitted Rust source (also usable for display / `gen`-parity).
|
|
31
|
-
export function emitRustModule(ast, cases =
|
|
32
|
+
export function emitRustModule(ast, cases = prepareRun(ast, RUST_RUN).cases, plans = plansFor(ast, exprToRust, 'Rust')) {
|
|
32
33
|
const L = [
|
|
33
34
|
'#![allow(non_snake_case, unused_parens, dead_code, unused_variables)]',
|
|
34
35
|
'',
|
|
35
36
|
];
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const params = names.map((n) => `${n}: ${RUST_TYPE[types[n]] || '&str'}`).join(', ');
|
|
42
|
-
L.push(`fn ${
|
|
43
|
-
for (const r of
|
|
44
|
-
|
|
45
|
-
L.push(` if ${cond} { return ${strLit(r.result)}; }`);
|
|
37
|
+
if ([...plans.values()].some((p) => p.refused)) {
|
|
38
|
+
L.push('// IL-GEN-001: a rule Thunder could not translate panics instead of guessing.');
|
|
39
|
+
L.push('fn thunder_untranslated(message: &str) -> bool {', ' panic!("{}", message)', '}', '');
|
|
40
|
+
}
|
|
41
|
+
for (const p of plans.values()) {
|
|
42
|
+
const params = p.names.map((n) => `${n}: ${RUST_TYPE[p.types[n]] || '&str'}`).join(', ');
|
|
43
|
+
L.push(`fn ${p.decision.name}(${params}) -> &'static str {`);
|
|
44
|
+
for (const { rule: r, code, message } of p.rules) {
|
|
45
|
+
L.push(` if ${code ?? `thunder_untranslated(${strLit(message)})`} { return ${strLit(r.result)}; }`);
|
|
46
46
|
}
|
|
47
|
-
L.push(` return ${
|
|
47
|
+
L.push(` return ${p.decision.default == null ? '""' : strLit(p.decision.default)};`, '}', '');
|
|
48
48
|
}
|
|
49
49
|
L.push('fn j(s: &str) -> String {');
|
|
50
50
|
L.push(' let mut out = String::from("\\"");');
|
|
@@ -61,14 +61,14 @@ export function emitRustModule(ast, cases = buildCases(ast)) {
|
|
|
61
61
|
L.push('');
|
|
62
62
|
L.push('fn main() {');
|
|
63
63
|
L.push(' let mut sb = String::from("{");');
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const argList =
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
}
|
|
64
|
+
let first = true;
|
|
65
|
+
for (const c of cases) {
|
|
66
|
+
const p = plans.get(c.fn);
|
|
67
|
+
if (!p) continue;
|
|
68
|
+
const argList = p.names.map((n) => argLit(c, p, n, rustLit)).join(', ');
|
|
69
|
+
L.push(` sb.push_str(&format!("{}{}:{}", ${JSON.stringify(first ? '' : ',')}, j(${strLit(c.key)}), j(${c.fn}(${argList}))));`);
|
|
70
|
+
first = false;
|
|
71
|
+
}
|
|
72
72
|
L.push(' sb.push_str("}");');
|
|
73
73
|
L.push(' println!("{}", sb);');
|
|
74
74
|
L.push('}');
|
|
@@ -81,19 +81,23 @@ export function rustAvailable() {
|
|
|
81
81
|
try {
|
|
82
82
|
const src = 'fn main() {\n println!("{}", "{\\"ok\\":\\"1\\"}");\n}';
|
|
83
83
|
const out = rustcRun(dir, src);
|
|
84
|
-
return
|
|
84
|
+
return out.ok && /"ok"/.test(out.stdout);
|
|
85
85
|
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
86
86
|
});
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
-
// Run every decision test case through generated, compiled Rust. Returns {
|
|
90
|
-
// or
|
|
89
|
+
// Run every decision test case through generated, compiled Rust. Returns { status: 'ok', results }
|
|
90
|
+
// or a whole-run { status: 'error', kind, message }.
|
|
91
91
|
export function runRustTarget(ast) {
|
|
92
|
-
if (!rustAvailable()) return
|
|
93
|
-
const cases =
|
|
92
|
+
if (!rustAvailable()) return runFailure('missing-toolchain', 'No usable Rust toolchain (rustc) on this machine.');
|
|
93
|
+
const { plans, cases, refused } = prepareRun(ast, RUST_RUN);
|
|
94
|
+
if (!cases.length) return { status: 'ok', results: { ...refused } };
|
|
94
95
|
const dir = mkdtempSync(join(tmpdir(), 'tl-rust-'));
|
|
95
96
|
try {
|
|
96
|
-
const out = rustcRun(dir, emitRustModule(ast, cases));
|
|
97
|
-
|
|
97
|
+
const out = rustcRun(dir, emitRustModule(ast, cases, plans));
|
|
98
|
+
if (!out.ok) return out.failure;
|
|
99
|
+
const parsed = parseLastJsonObject(out.stdout);
|
|
100
|
+
if (!parsed) return runFailure('runtime-error', 'The compiled Rust program printed no results.');
|
|
101
|
+
return finishRun({ cases, parsed, refused, target: 'Rust' });
|
|
98
102
|
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
99
103
|
}
|
package/src/target-scala.mjs
CHANGED
|
@@ -1,48 +1,54 @@
|
|
|
1
1
|
// Scala target adapter. Emits a self-contained Scala script that defines each decision as a typed
|
|
2
2
|
// def (using the same exprToScala translator the codegen uses), calls every test case with typed
|
|
3
3
|
// literal arguments, and prints the results as one JSON line. It runs through `scala` (falling back
|
|
4
|
-
// to `scala-cli run`), so a live Scala run grades real compiled + executed code.
|
|
5
|
-
//
|
|
6
|
-
|
|
4
|
+
// to `scala-cli run`), so a live Scala run grades real compiled + executed code.
|
|
5
|
+
//
|
|
6
|
+
// Results are honest (see target-result.mjs): a missing toolchain, a compile failure, a crash, or a
|
|
7
|
+
// timeout is a structured error, never a null answer; a decision with a rule Thunder cannot
|
|
8
|
+
// translate is refused ('not-translated'). Scala has no exact Money wiring yet, so a rule that
|
|
9
|
+
// compares Money is refused rather than run as a Double.
|
|
7
10
|
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
|
8
11
|
import { join } from 'node:path';
|
|
9
12
|
import { tmpdir } from 'node:os';
|
|
10
13
|
import { exprToScala } from './expr.mjs';
|
|
11
|
-
import {
|
|
14
|
+
import { parseLastJsonObject, cachedSmoke, strLit, litFor, prepareRun, plansFor, argLit, finishRun, runFailure, classifySpawn, spawnStep } from './target-util.mjs';
|
|
12
15
|
|
|
13
16
|
const SCALA_TYPE = { number: 'Double', bool: 'Boolean', string: 'String' };
|
|
17
|
+
const SCALA_RUN = { translate: exprToScala, target: 'Scala', dialect: 'scala' };
|
|
18
|
+
const SCALA_RUNTIME = /Exception in thread|\n\s+at [\w.$]+\(/;
|
|
14
19
|
// Which runner worked during the smoke, so run reuses it: [cmd, argsFor(file)].
|
|
15
20
|
let SCALA_RUNNER = null;
|
|
16
21
|
|
|
17
22
|
// Write `source` to a .scala file in `dir` and run it. Prefers `scala` (script mode); falls back to
|
|
18
|
-
// `scala-cli run`. Returns
|
|
23
|
+
// `scala-cli run`. Returns { ok, stdout } or { ok: false, failure } (the last runner's failure).
|
|
19
24
|
function scalaRun(dir, source) {
|
|
20
25
|
const f = join(dir, 'Main.scala');
|
|
21
26
|
writeFileSync(f, source);
|
|
22
27
|
const env = { ...process.env };
|
|
23
28
|
const runners = SCALA_RUNNER ? [SCALA_RUNNER] : [['scala', (p) => [p]], ['scala-cli', (p) => ['run', p]]];
|
|
29
|
+
let last = { ok: false, failure: runFailure('missing-toolchain', 'Neither scala nor scala-cli is installed or on PATH.') };
|
|
24
30
|
for (const [cmd, argsFor] of runners) {
|
|
25
|
-
const r =
|
|
26
|
-
if (r.
|
|
31
|
+
const r = spawnStep(cmd, argsFor(f), { timeout: 300000, env }, (x) => classifySpawn(x, { tool: cmd, phase: 'build+run', runtimePattern: SCALA_RUNTIME }));
|
|
32
|
+
if (r.ok && r.stdout) { SCALA_RUNNER = [cmd, argsFor]; return r; }
|
|
33
|
+
if (!r.ok && (r.failure.kind !== 'missing-toolchain' || last.failure.kind === 'missing-toolchain')) last = r;
|
|
27
34
|
}
|
|
28
|
-
return
|
|
35
|
+
return last;
|
|
29
36
|
}
|
|
30
37
|
|
|
31
38
|
// The emitted Scala source (also usable for display / `gen`-parity).
|
|
32
|
-
export function emitScalaModule(ast, cases =
|
|
39
|
+
export function emitScalaModule(ast, cases = prepareRun(ast, SCALA_RUN).cases, plans = plansFor(ast, exprToScala, 'Scala')) {
|
|
33
40
|
const L = [];
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const params = names.map((n) => `${n}: ${SCALA_TYPE[types[n]] || 'String'}`).join(', ');
|
|
40
|
-
L.push(`def ${
|
|
41
|
-
for (const r of
|
|
42
|
-
|
|
43
|
-
L.push(` if (${cond}) return ${strLit(r.result)}`);
|
|
41
|
+
if ([...plans.values()].some((p) => p.refused)) {
|
|
42
|
+
L.push('// IL-GEN-001: a rule Thunder could not translate throws instead of guessing.');
|
|
43
|
+
L.push('def thunderUntranslated(message: String): Boolean = throw new UnsupportedOperationException(message)', '');
|
|
44
|
+
}
|
|
45
|
+
for (const p of plans.values()) {
|
|
46
|
+
const params = p.names.map((n) => `${n}: ${SCALA_TYPE[p.types[n]] || 'String'}`).join(', ');
|
|
47
|
+
L.push(`def ${p.decision.name}(${params}): String = {`);
|
|
48
|
+
for (const { rule: r, code, message } of p.rules) {
|
|
49
|
+
L.push(` if (${code ?? `thunderUntranslated(${strLit(message)})`}) return ${strLit(r.result)}`);
|
|
44
50
|
}
|
|
45
|
-
L.push(` return ${
|
|
51
|
+
L.push(` return ${p.decision.default == null ? 'null' : strLit(p.decision.default)}`, '}', '');
|
|
46
52
|
}
|
|
47
53
|
L.push('def j(s: String): String = {');
|
|
48
54
|
L.push(' if (s == null) return "null"');
|
|
@@ -56,14 +62,14 @@ export function emitScalaModule(ast, cases = buildCases(ast)) {
|
|
|
56
62
|
L.push('}');
|
|
57
63
|
L.push('');
|
|
58
64
|
L.push('val sb = new StringBuilder("{")');
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const argList =
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
65
|
+
let first = true;
|
|
66
|
+
for (const c of cases) {
|
|
67
|
+
const p = plans.get(c.fn);
|
|
68
|
+
if (!p) continue;
|
|
69
|
+
const argList = p.names.map((n) => argLit(c, p, n, litFor)).join(', ');
|
|
70
|
+
L.push(`sb.append(${JSON.stringify(first ? '' : ',')}).append(j(${strLit(c.key)})).append(":").append(j(${c.fn}(${argList})))`);
|
|
71
|
+
first = false;
|
|
72
|
+
}
|
|
67
73
|
L.push('sb.append("}")');
|
|
68
74
|
L.push('println(sb.toString)');
|
|
69
75
|
return L.join('\n');
|
|
@@ -75,19 +81,23 @@ export function scalaAvailable() {
|
|
|
75
81
|
try {
|
|
76
82
|
const src = 'println("{\\"ok\\":\\"1\\"}")';
|
|
77
83
|
const out = scalaRun(dir, src);
|
|
78
|
-
return
|
|
84
|
+
return out.ok && /"ok"/.test(out.stdout);
|
|
79
85
|
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
80
86
|
});
|
|
81
87
|
}
|
|
82
88
|
|
|
83
|
-
// Run every decision test case through generated, compiled Scala. Returns {
|
|
84
|
-
// or
|
|
89
|
+
// Run every decision test case through generated, compiled Scala. Returns { status: 'ok', results }
|
|
90
|
+
// or a whole-run { status: 'error', kind, message }.
|
|
85
91
|
export function runScalaTarget(ast) {
|
|
86
|
-
if (!scalaAvailable()) return
|
|
87
|
-
const cases =
|
|
92
|
+
if (!scalaAvailable()) return runFailure('missing-toolchain', 'No usable Scala toolchain (scala or scala-cli) on this machine.');
|
|
93
|
+
const { plans, cases, refused } = prepareRun(ast, SCALA_RUN);
|
|
94
|
+
if (!cases.length) return { status: 'ok', results: { ...refused } };
|
|
88
95
|
const dir = mkdtempSync(join(tmpdir(), 'tl-scala-'));
|
|
89
96
|
try {
|
|
90
|
-
const out = scalaRun(dir, emitScalaModule(ast, cases));
|
|
91
|
-
|
|
97
|
+
const out = scalaRun(dir, emitScalaModule(ast, cases, plans));
|
|
98
|
+
if (!out.ok) return out.failure;
|
|
99
|
+
const parsed = parseLastJsonObject(out.stdout);
|
|
100
|
+
if (!parsed) return runFailure('runtime-error', 'scala ran but printed no results.');
|
|
101
|
+
return finishRun({ cases, parsed, refused, target: 'Scala' });
|
|
92
102
|
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
93
103
|
}
|
package/src/target-ts.mjs
CHANGED
|
@@ -3,64 +3,56 @@
|
|
|
3
3
|
// through the generated code and returns actual outputs. This turns conformance from "grade fed
|
|
4
4
|
// results" into "grade a live target": the generated implementation is executed for real.
|
|
5
5
|
// Type annotations are erased at runtime, so running the type-stripped JS is faithful to the TS.
|
|
6
|
+
//
|
|
7
|
+
// Results are honest: every case is { status: 'ok', value } or { status: 'error', kind, message }.
|
|
8
|
+
// A decision with a rule Thunder cannot translate is refused ('not-translated'), never run with a
|
|
9
|
+
// stand-in `false`. Money inputs are exact bigint minor units, never floats.
|
|
6
10
|
import { exprToJs } from './expr.mjs';
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
function coerceVal(v) {
|
|
11
|
-
if (v == null || typeof v !== 'string') return v;
|
|
12
|
-
const s = v.trim();
|
|
13
|
-
if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
|
|
14
|
-
if (s === 'true') return true;
|
|
15
|
-
if (s === 'false') return false;
|
|
16
|
-
return v;
|
|
17
|
-
}
|
|
11
|
+
import { planDecision } from './target-types.mjs';
|
|
12
|
+
import { okResult, errorResult } from './target-result.mjs';
|
|
13
|
+
import { prepareRun } from './target-util.mjs';
|
|
18
14
|
|
|
19
15
|
// The emitted source (for display / `gen`-parity); the runtime uses new Function on the body.
|
|
20
16
|
export function emitDecisionModule(ast) {
|
|
21
17
|
const L = ['// Executable target compiled from the decision(s). Deterministic, no AI.'];
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
18
|
+
const plans = (ast.decisions || []).map((d) => planDecision(ast, d, { translate: exprToJs, target: 'TypeScript' }));
|
|
19
|
+
if (plans.some((p) => p.refused)) L.push('function thunderUntranslated(message) { throw new Error(message); }');
|
|
20
|
+
for (const p of plans) {
|
|
21
|
+
L.push(`export function ${p.decision.name}(${p.names.join(', ')}) {`);
|
|
22
|
+
for (const { rule: r, code, message } of p.rules) {
|
|
23
|
+
L.push(` if (${code ?? `thunderUntranslated(${JSON.stringify(message)})`}) return ${JSON.stringify(r.result)};`);
|
|
27
24
|
}
|
|
28
|
-
L.push(` return ${JSON.stringify(
|
|
25
|
+
L.push(` return ${JSON.stringify(p.decision.default ?? null)};`, '}');
|
|
29
26
|
}
|
|
30
27
|
return L.join('\n');
|
|
31
28
|
}
|
|
32
29
|
|
|
33
|
-
// Compile
|
|
34
|
-
function
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const body = [];
|
|
39
|
-
for (const r of d.rules || []) {
|
|
40
|
-
let cond; try { cond = exprToJs(r.when, { inputs: names }); } catch { cond = 'false'; }
|
|
41
|
-
body.push(`if (${cond}) return ${JSON.stringify(r.result)};`);
|
|
42
|
-
}
|
|
43
|
-
body.push(`return ${JSON.stringify(d.default ?? null)};`);
|
|
44
|
-
try { fns[d.name] = new Function(...names, body.join('\n')); } catch { fns[d.name] = null; }
|
|
45
|
-
}
|
|
46
|
-
return fns;
|
|
30
|
+
// Compile one planned (fully translated) decision to a runnable function.
|
|
31
|
+
function compileDecisionFn(p) {
|
|
32
|
+
const body = p.rules.map(({ rule: r, code }) => `if (${code}) return ${JSON.stringify(r.result)};`);
|
|
33
|
+
body.push(`return ${JSON.stringify(p.decision.default ?? null)};`);
|
|
34
|
+
return new Function(...p.names, body.join('\n'));
|
|
47
35
|
}
|
|
48
36
|
|
|
49
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Run every decision test case through the generated code.
|
|
39
|
+
* Returns { status: 'ok', results: { "Test / case": {status:'ok', value} | {status:'error', kind, message} } }.
|
|
40
|
+
*/
|
|
50
41
|
export function runTypescriptTarget(ast) {
|
|
51
|
-
const
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const key = `${t.name} / ${c.name || 'case'}`;
|
|
60
|
-
if (typeof fn !== 'function') { out[key] = null; continue; }
|
|
61
|
-
const args = names.map((n) => coerceVal((c.given || {})[n]));
|
|
62
|
-
try { out[key] = fn(...args); } catch { out[key] = null; }
|
|
42
|
+
const { plans, cases, refused } = prepareRun(ast, { translate: exprToJs, target: 'TypeScript', dialect: 'js-runtime' });
|
|
43
|
+
const results = { ...refused };
|
|
44
|
+
const fns = new Map();
|
|
45
|
+
for (const c of cases) {
|
|
46
|
+
const p = plans.get(c.fn);
|
|
47
|
+
if (!fns.has(c.fn)) {
|
|
48
|
+
try { fns.set(c.fn, { fn: compileDecisionFn(p) }); }
|
|
49
|
+
catch (e) { fns.set(c.fn, { error: `TypeScript could not compile the generated decision ${c.fn}: ${e.message}` }); }
|
|
63
50
|
}
|
|
51
|
+
const compiled = fns.get(c.fn);
|
|
52
|
+
if (compiled.error) { results[c.key] = errorResult('compile-failed', compiled.error); continue; }
|
|
53
|
+
const args = p.names.map((n) => (c.moneyArgs[n] != null ? c.moneyArgs[n] : c.given[n]));
|
|
54
|
+
try { results[c.key] = okResult(compiled.fn(...args)); }
|
|
55
|
+
catch (e) { results[c.key] = errorResult('runtime-error', `The generated TypeScript threw while running ${c.key}: ${e && e.message ? e.message : e}`); }
|
|
64
56
|
}
|
|
65
|
-
return
|
|
57
|
+
return { status: 'ok', results };
|
|
66
58
|
}
|
package/src/target-types.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// Browser-safe helpers shared by the target adapters and the in-browser translator.
|
|
2
2
|
// No Node imports here, so the website can bundle this file.
|
|
3
|
+
import { moneyTypeMinorUnits } from './money.mjs';
|
|
4
|
+
import { translateRule } from './target-result.mjs';
|
|
3
5
|
|
|
4
6
|
export const inputNames = (dec) => (dec.inputs || []).map((i) => String(i).split(':')[0].trim()).filter(Boolean);
|
|
5
7
|
|
|
@@ -20,18 +22,21 @@ export function buildCases(ast) {
|
|
|
20
22
|
if (!dec) continue;
|
|
21
23
|
const names = inputNames(dec);
|
|
22
24
|
for (const c of t.cases || []) {
|
|
23
|
-
const given = {};
|
|
24
|
-
for (const n of names)
|
|
25
|
-
cases.push({ key: `${t.name} / ${c.name || 'case'}`, fn: t.name, given });
|
|
25
|
+
const given = {}; const raw = {};
|
|
26
|
+
for (const n of names) { raw[n] = (c.given || {})[n]; given[n] = coerceVal(raw[n]); }
|
|
27
|
+
cases.push({ key: `${t.name} / ${c.name || 'case'}`, fn: t.name, given, raw });
|
|
26
28
|
}
|
|
27
29
|
}
|
|
28
30
|
return cases;
|
|
29
31
|
}
|
|
30
32
|
|
|
31
|
-
// A declared input type (`amount: number`, `Money`, `Flag`) as number, bool, or
|
|
32
|
-
|
|
33
|
+
// A declared input type (`amount: number`, `Money`, `Flag`) as number, bool, string, or money; null
|
|
34
|
+
// when none. Money stays its own type so no target turns it into binary floating point.
|
|
35
|
+
const NUMBER_TYPES = /^(number|int|integer|long|short|float|double|decimal|Percentage|Count|Duration)$/i;
|
|
33
36
|
const BOOL_TYPES = /^(boolean|bool|Flag)$/i;
|
|
34
37
|
export function declaredInputType(raw) {
|
|
38
|
+
const t = String(raw).includes(':') ? String(raw).slice(String(raw).indexOf(':') + 1).trim() : '';
|
|
39
|
+
if (moneyTypeMinorUnits(t) != null) return 'money';
|
|
35
40
|
const m = String(raw).match(/:\s*([A-Za-z][\w<>]*)\s*$/);
|
|
36
41
|
if (!m) return null;
|
|
37
42
|
if (NUMBER_TYPES.test(m[1])) return 'number';
|
|
@@ -95,3 +100,34 @@ export function litFor(type, v) {
|
|
|
95
100
|
return strLit(v);
|
|
96
101
|
}
|
|
97
102
|
|
|
103
|
+
|
|
104
|
+
/** Money inputs of a decision: { name: minorUnits } (Money = 2, Money(JPY) = 0, Money(KWD) = 3). */
|
|
105
|
+
export function moneyInputs(dec) {
|
|
106
|
+
const out = {};
|
|
107
|
+
for (const raw of dec.inputs || []) {
|
|
108
|
+
const s = String(raw);
|
|
109
|
+
if (!s.includes(':')) continue;
|
|
110
|
+
const units = moneyTypeMinorUnits(s.slice(s.indexOf(':') + 1).trim());
|
|
111
|
+
if (units != null) out[s.split(':')[0].trim()] = units;
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Everything a generator needs for one decision: input names and types, Money minor units, each
|
|
118
|
+
* rule's translated condition (or the IL-GEN-001 message when it cannot be translated), and
|
|
119
|
+
* `refused`: the first untranslated message, set when this decision must not be run.
|
|
120
|
+
*/
|
|
121
|
+
export function planDecision(ast, d, { translate, target }) {
|
|
122
|
+
const names = inputNames(d);
|
|
123
|
+
const types = inferInputTypes(ast, d);
|
|
124
|
+
const money = moneyInputs(d);
|
|
125
|
+
const opts = { inputs: names, money };
|
|
126
|
+
const rules = []; const diagnostics = []; let refused = null;
|
|
127
|
+
for (const r of d.rules || []) {
|
|
128
|
+
const t = translateRule(translate, r, opts, { target, decision: d.name });
|
|
129
|
+
if (t.ok) rules.push({ rule: r, code: t.code });
|
|
130
|
+
else { rules.push({ rule: r, code: null, message: t.message }); diagnostics.push(t.diagnostic); refused = refused ?? t.message; }
|
|
131
|
+
}
|
|
132
|
+
return { decision: d, names, types, money, rules, diagnostics, refused };
|
|
133
|
+
}
|
package/src/target-util.mjs
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
|
-
// Shared helpers for the compiled target adapters (Python/C#/Java). The statically typed targets
|
|
1
|
+
// Shared helpers for the compiled target adapters (Python/C#/Java/...). The statically typed targets
|
|
2
2
|
// (C#, Java) need a declared type for every decision parameter, which ThunderLang source leaves
|
|
3
3
|
// implicit, so we infer each input's type from the test-case values that will actually be passed.
|
|
4
4
|
import { spawnSync } from 'node:child_process';
|
|
5
|
-
|
|
5
|
+
import { buildCases, planDecision } from './target-types.mjs';
|
|
6
|
+
import { errorResult } from './target-result.mjs';
|
|
7
|
+
import { parseMoney, moneyLiteral } from './money.mjs';
|
|
8
|
+
export { inputNames, coerceVal, buildCases, inferInputTypes, strLit, litFor, planDecision, moneyInputs } from './target-types.mjs';
|
|
9
|
+
export { okResult, errorResult, finishRun, runFailure, classifySpawn, runValues, isCaseResult, ERROR_KINDS, GEN_UNTRANSLATED } from './target-result.mjs';
|
|
6
10
|
|
|
7
11
|
// Pick the last line of stdout that parses as a JSON object , build/tool chatter may precede it.
|
|
8
12
|
export function parseLastJsonObject(stdout) {
|
|
@@ -35,3 +39,52 @@ export function toolOnPath(cmd, args = ['--version']) {
|
|
|
35
39
|
return false;
|
|
36
40
|
}
|
|
37
41
|
}
|
|
42
|
+
|
|
43
|
+
// ── Honest runs ──────────────────────────────────────────────────────────────
|
|
44
|
+
// Plan a live run: translate every decision for the target, refuse the cases of any decision with an
|
|
45
|
+
// untranslated rule (IL-GEN-001, kind 'not-translated'), and render each Money argument with the
|
|
46
|
+
// target's exact literal ('js-runtime' gives a real bigint for the in-process runner).
|
|
47
|
+
// Returns { plans: Map(name -> plan), cases, refused }.
|
|
48
|
+
export function prepareRun(ast, { translate, target, dialect }) {
|
|
49
|
+
const plans = new Map((ast.decisions || []).map((d) => [d.name, planDecision(ast, d, { translate, target })]));
|
|
50
|
+
const refused = {};
|
|
51
|
+
const cases = [];
|
|
52
|
+
for (const c of buildCases(ast)) {
|
|
53
|
+
const p = plans.get(c.fn);
|
|
54
|
+
if (!p) continue;
|
|
55
|
+
if (p.refused) { refused[c.key] = errorResult('not-translated', p.refused); continue; }
|
|
56
|
+
// A case that gives no value for an input is never run with a made-up one ("", false, 0, $0): a typed
|
|
57
|
+
// target would answer for a value nobody wrote, and the reference engine reads "missing" differently.
|
|
58
|
+
const missing = p.names.filter((n) => c.raw[n] === undefined || c.raw[n] === null);
|
|
59
|
+
if (missing.length) {
|
|
60
|
+
refused[c.key] = errorResult('missing-input', `${c.key} gives no value for ${missing.join(', ')}, so it cannot run in ${target} without making one up. Add ${missing.length === 1 ? 'it' : 'them'} to the case's "given".`);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
const moneyArgs = {};
|
|
65
|
+
for (const [n, units] of Object.entries(p.money)) {
|
|
66
|
+
const raw = c.raw[n];
|
|
67
|
+
moneyArgs[n] = dialect === 'js-runtime' ? parseMoney(raw, { minorUnits: units }) : moneyLiteral(dialect, raw, units);
|
|
68
|
+
}
|
|
69
|
+
cases.push({ ...c, moneyArgs });
|
|
70
|
+
} catch (e) {
|
|
71
|
+
refused[c.key] = errorResult('not-translated', `Thunder could not pass the example value for ${c.key} to ${target} exactly: ${e.message}`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { plans, cases, refused };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// The source text of an argument: the exact Money literal for Money inputs, else the typed literal.
|
|
78
|
+
export const argLit = (c, plan, n, lit) => (c.moneyArgs && c.moneyArgs[n] != null ? c.moneyArgs[n] : lit(plan.types[n], c.given[n]));
|
|
79
|
+
|
|
80
|
+
// Plans for display emitters that are called without a prepared run.
|
|
81
|
+
export function plansFor(ast, translate, target) {
|
|
82
|
+
return new Map((ast.decisions || []).map((d) => [d.name, planDecision(ast, d, { translate, target })]));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Run a child process and return { ok: true, stdout } or { ok: false, failure } (a classified run failure).
|
|
86
|
+
export function spawnStep(cmd, args, opts, classify) {
|
|
87
|
+
const r = spawnSync(cmd, args, { encoding: 'utf8', ...opts });
|
|
88
|
+
if (r.status === 0 && !r.error) return { ok: true, stdout: r.stdout || '' };
|
|
89
|
+
return { ok: false, failure: classify(r) };
|
|
90
|
+
}
|
package/src/term.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Calm color for the terminal: green for what worked, red only for real problems, yellow for warnings and choices,
|
|
2
|
+
// cyan for commands to type, bold for headings. Off when the output is not a terminal (a file, a pipe, a script, an
|
|
3
|
+
// editor reading it), when NO_COLOR is set, or for TERM=dumb; FORCE_COLOR=1 turns it on. Color never carries meaning
|
|
4
|
+
// alone: every colored line also has its words and its mark (✓ ✗ !).
|
|
5
|
+
const env = (typeof process !== 'undefined' && process.env) || {};
|
|
6
|
+
|
|
7
|
+
/** Whether to color text written to `stream` (default: standard output). */
|
|
8
|
+
export function useColor(stream = typeof process !== 'undefined' ? process.stdout : null) {
|
|
9
|
+
if (env.NO_COLOR != null && env.NO_COLOR !== '') return false;
|
|
10
|
+
if (env.FORCE_COLOR != null && env.FORCE_COLOR !== '' && env.FORCE_COLOR !== '0') return true;
|
|
11
|
+
if (env.TERM === 'dumb') return false;
|
|
12
|
+
return !!stream?.isTTY;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const wrap = (open, close) => (s, on = useColor()) => (on ? `\x1b[${open}m${s}\x1b[${close}m` : String(s));
|
|
16
|
+
export const bold = wrap(1, 22);
|
|
17
|
+
export const dim = wrap(2, 22);
|
|
18
|
+
export const green = wrap(32, 39);
|
|
19
|
+
export const red = wrap(31, 39);
|
|
20
|
+
export const yellow = wrap(33, 39);
|
|
21
|
+
export const cyan = wrap(36, 39);
|
|
22
|
+
|
|
23
|
+
/** A command to type: cyan, so it stands out from the words around it. */
|
|
24
|
+
export const cmd = (s, on) => cyan(s, on);
|
|
25
|
+
/** A heading. */
|
|
26
|
+
export const head = (s, on) => bold(s, on);
|
|
27
|
+
|
|
28
|
+
/** Color the marks at the start of a line: ✓ green, ✗ red, ! yellow. */
|
|
29
|
+
export function marks(line, on = useColor()) {
|
|
30
|
+
if (!on) return line;
|
|
31
|
+
return line
|
|
32
|
+
.replace(/^(\s*)✓/, (_, s) => `${s}${green('✓', on)}`)
|
|
33
|
+
.replace(/^(\s*)✗/, (_, s) => `${s}${red('✗', on)}`)
|
|
34
|
+
.replace(/^(\s*)!(?= )/, (_, s) => `${s}${yellow('!', on)}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The words that can follow "thunder" in a command (so prose like "thunder is on your PATH" stays plain). */
|
|
38
|
+
const VERBS = 'new|run|build|test|check|format|fmt|read|try|why|help|doctor|completion|init|mission|trace|review|same|write|repo|thunderize|verify|prove|lift|drift|changes|scan|report|explain|docs|atlas|index|gen|conform|export|import|runtime|anchor|text|human|graph|focus|risks|gaps|edit|mcp|lsp';
|
|
39
|
+
const COMMAND = new RegExp(`(^|[\\s\`(:])(thunder (?:${VERBS})\\b[^\\n\`]*)`, 'g');
|
|
40
|
+
|
|
41
|
+
/** Highlight `thunder …` commands inside a line of text: up to two spaces, a semicolon, or the end. */
|
|
42
|
+
export function commands(line, on = useColor()) {
|
|
43
|
+
if (!on) return line;
|
|
44
|
+
return line.replace(COMMAND, (_, pre, rest) => {
|
|
45
|
+
let c = rest.split(/ {2,}|; /)[0];
|
|
46
|
+
const tail = rest.slice(c.length);
|
|
47
|
+
const trail = c.match(/[.?!,;)]+$/)?.[0] ?? '';
|
|
48
|
+
c = c.slice(0, c.length - trail.length);
|
|
49
|
+
return `${pre}${cyan(c, on)}${trail}${tail}`;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Remove color (for tests and for measuring width). */
|
|
54
|
+
export const plain = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, '');
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Paint a screen of text: marks (✓ ✗ ! ◆ ■ ▶), `thunder …` commands, "Label:" words at the start of a line, and
|
|
58
|
+
* headings (a line of its own with no indent). Plain text comes back unchanged when color is off.
|
|
59
|
+
*/
|
|
60
|
+
export function paint(text, on = useColor()) {
|
|
61
|
+
if (!on) return text;
|
|
62
|
+
return String(text).split('\n').map((line) => {
|
|
63
|
+
if (/^─+$/.test(line)) return dim(line, on);
|
|
64
|
+
let l = marks(line, on);
|
|
65
|
+
l = l.replace(/^(\s*)◆/, (_, s) => `${s}${yellow('◆', on)}`).replace(/^(\s*)■/, (_, s) => `${s}${green('■', on)}`).replace(/^(\s*)▶/, (_, s) => `${s}${cyan('▶', on)}`);
|
|
66
|
+
l = l.replace(/^⚡ (.+?)(?=:|$)/, (_, t) => `${yellow('⚡', on)} ${bold(t, on)}`);
|
|
67
|
+
// " Why: …", "Answer: …", "Next: …": the label in bold.
|
|
68
|
+
l = l.replace(/^(\s*)([A-Z][A-Za-z ]{1,18}:)(?=\s|$)/, (_, s, lab) => `${s}${bold(lab, on)}`);
|
|
69
|
+
// A title like "Flow · Late fee (library.py:24)".
|
|
70
|
+
if (/^[A-Z][^·]* · /.test(line)) l = bold(l, on);
|
|
71
|
+
// A heading: an unindented line with no colon-label, not a sentence that ends with a full stop.
|
|
72
|
+
if (/^[A-Z][^.:]*$/.test(plain(line)) && plain(line).length < 60) l = bold(l, on);
|
|
73
|
+
return commands(l, on);
|
|
74
|
+
}).join('\n');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The full command list: headings bold, each command name cyan, its [options] dimmed. */
|
|
78
|
+
export function paintHelp(text, on = useColor()) {
|
|
79
|
+
if (!on) return text;
|
|
80
|
+
return String(text).split('\n').map((line) => {
|
|
81
|
+
if (/^─+$/.test(line)) return dim(line, on);
|
|
82
|
+
if (/^⚡ /.test(line)) return `${yellow('⚡', on)} ${bold(line.slice(2), on)}`;
|
|
83
|
+
if (/^Advanced:/.test(line)) return yellow(line, on);
|
|
84
|
+
if (/^[A-Z][^:]*$/.test(line) && !/^usage/.test(line)) return bold(line, on);
|
|
85
|
+
const m = line.match(/^( {2})([a-z][a-z0-9-]*(?: \| [a-z][a-z0-9-]*)*)(.*)$/);
|
|
86
|
+
if (m) return `${m[1]}${cyan(m[2], on)}${m[3].replace(/(\[[^\]]*\])/g, (x) => dim(x, on))}`;
|
|
87
|
+
return line;
|
|
88
|
+
}).join('\n');
|
|
89
|
+
}
|