@skillstech/thunderlang 0.4.2 → 0.5.2
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 +28 -0
- package/dist/core.cjs +6082 -3970
- package/dist/index.cjs +2798 -384
- package/package.json +1 -1
- package/src/cli.mjs +130 -4
- package/src/core.d.ts +9 -0
- package/src/core.mjs +5 -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/lift.mjs +7 -0
- package/src/mcp.mjs +120 -22
- package/src/promote.d.mts +6 -0
- package/src/promote.mjs +165 -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 +1485 -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 +62 -0
- package/src/target-util.mjs +1 -59
- package/src/translate.d.mts +5 -0
- package/src/translate.mjs +126 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Elixir target adapter. Like the Python adapter, this compiles each decision into an executable
|
|
2
|
+
// function using the SAME expression translator the codegen uses (exprToElixir), then runs the test
|
|
3
|
+
// cases through a real `elixir` child process and returns actual outputs, so a live Elixir run
|
|
4
|
+
// grades real executed code. Elixir function names must start lowercase, so each decision `Foo`
|
|
5
|
+
// becomes `d_Foo`. Returns null (skip cleanly) when the elixir runtime is unavailable.
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { exprToElixir } from './expr.mjs';
|
|
11
|
+
import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
|
|
12
|
+
|
|
13
|
+
// Write `source` to a .exs file in `dir` and run it. Returns stdout, or null on any failure.
|
|
14
|
+
function elixirRun(dir, source) {
|
|
15
|
+
const f = join(dir, 'main.exs');
|
|
16
|
+
writeFileSync(f, source);
|
|
17
|
+
const env = { ...process.env };
|
|
18
|
+
const r = spawnSync('elixir', [f], { encoding: 'utf8', timeout: 120000, env });
|
|
19
|
+
if (r.status !== 0) return null;
|
|
20
|
+
return r.stdout;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// The emitted Elixir source (also usable for display / `gen`-parity).
|
|
24
|
+
export function emitElixirModule(ast, cases = buildCases(ast)) {
|
|
25
|
+
const L = ['defmodule ThunderTarget do'];
|
|
26
|
+
const typesByDec = {};
|
|
27
|
+
for (const d of ast.decisions || []) {
|
|
28
|
+
const names = inputNames(d);
|
|
29
|
+
typesByDec[d.name] = inferInputTypes(ast, d);
|
|
30
|
+
L.push(` def d_${d.name}(${names.join(', ')}) do`);
|
|
31
|
+
L.push(' cond do');
|
|
32
|
+
for (const r of d.rules || []) {
|
|
33
|
+
let cond; try { cond = exprToElixir(r.when, { inputs: names }); } catch { cond = 'false'; }
|
|
34
|
+
L.push(` ${cond} -> ${strLit(r.result)}`);
|
|
35
|
+
}
|
|
36
|
+
L.push(` true -> ${d.default == null ? 'nil' : strLit(d.default)}`);
|
|
37
|
+
L.push(' end');
|
|
38
|
+
L.push(' end');
|
|
39
|
+
}
|
|
40
|
+
L.push('end');
|
|
41
|
+
L.push('');
|
|
42
|
+
L.push('pairs = [');
|
|
43
|
+
cases.forEach((c) => {
|
|
44
|
+
const dec = (ast.decisions || []).find((d) => d.name === c.fn);
|
|
45
|
+
if (!dec) return;
|
|
46
|
+
const types = typesByDec[c.fn];
|
|
47
|
+
const argList = inputNames(dec).map((n) => litFor(types[n], c.given[n])).join(', ');
|
|
48
|
+
L.push(` {${strLit(c.key)}, ThunderTarget.d_${c.fn}(${argList})},`);
|
|
49
|
+
});
|
|
50
|
+
L.push(']');
|
|
51
|
+
// inspect/1 renders a binary as a valid JSON string for ordinary content (quotes/backslashes/
|
|
52
|
+
// newlines escaped); nil becomes JSON null. parseLastJsonObject then reads the printed line.
|
|
53
|
+
L.push('json = "{" <> Enum.map_join(pairs, ",", fn {k, v} -> inspect(k) <> ":" <> (if is_nil(v), do: "null", else: inspect(v)) end) <> "}"');
|
|
54
|
+
L.push('IO.puts(json)');
|
|
55
|
+
return L.join('\n');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function elixirAvailable() {
|
|
59
|
+
return cachedSmoke('elixir', () => {
|
|
60
|
+
const dir = mkdtempSync(join(tmpdir(), 'tl-ex-smoke-'));
|
|
61
|
+
try {
|
|
62
|
+
const src = 'IO.puts("{\\"ok\\":\\"1\\"}")';
|
|
63
|
+
const out = elixirRun(dir, src);
|
|
64
|
+
return !!out && /"ok"/.test(out);
|
|
65
|
+
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Run every decision test case through generated, executed Elixir. Returns { "Test / case": actual }
|
|
70
|
+
// or null when the elixir runtime is not present.
|
|
71
|
+
export function runElixirTarget(ast) {
|
|
72
|
+
if (!elixirAvailable()) return null;
|
|
73
|
+
const cases = buildCases(ast);
|
|
74
|
+
const dir = mkdtempSync(join(tmpdir(), 'tl-ex-'));
|
|
75
|
+
try {
|
|
76
|
+
const out = elixirRun(dir, emitElixirModule(ast, cases));
|
|
77
|
+
return out == null ? null : parseLastJsonObject(out);
|
|
78
|
+
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
79
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Go target adapter. Emits a self-contained `package main` that defines each decision as a typed
|
|
2
|
+
// func (using the same exprToGo translator the codegen uses), calls every test case with typed
|
|
3
|
+
// literal arguments, and prints the results as one JSON line. It runs through `go run`, so a live
|
|
4
|
+
// Go run grades real compiled + executed code. Returns null (skip cleanly) when no usable Go
|
|
5
|
+
// toolchain exists.
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { exprToGo } from './expr.mjs';
|
|
11
|
+
import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
|
|
12
|
+
|
|
13
|
+
const GO_TYPE = { number: 'float64', bool: 'bool', string: 'string' };
|
|
14
|
+
|
|
15
|
+
// Write `source` to main.go in `dir` and `go run` it. Returns stdout, or null on any failure.
|
|
16
|
+
// GO111MODULE=off runs a single stdlib-only file with no go.mod; GOTOOLCHAIN=local avoids network.
|
|
17
|
+
function goRun(dir, source) {
|
|
18
|
+
const f = join(dir, 'main.go');
|
|
19
|
+
writeFileSync(f, source);
|
|
20
|
+
const env = { ...process.env, GO111MODULE: 'off', GOTOOLCHAIN: 'local', GOCACHE: join(dir, '.gocache'), GOFLAGS: '' };
|
|
21
|
+
const r = spawnSync('go', ['run', f], { encoding: 'utf8', timeout: 180000, env });
|
|
22
|
+
if (r.status !== 0) return null;
|
|
23
|
+
return r.stdout;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The emitted Go source (also usable for display / `gen`-parity).
|
|
27
|
+
export function emitGoModule(ast, cases = buildCases(ast)) {
|
|
28
|
+
const L = [
|
|
29
|
+
'package main',
|
|
30
|
+
'',
|
|
31
|
+
'import (',
|
|
32
|
+
'\t"encoding/json"',
|
|
33
|
+
'\t"fmt"',
|
|
34
|
+
'\t"strings"',
|
|
35
|
+
')',
|
|
36
|
+
'',
|
|
37
|
+
];
|
|
38
|
+
const typesByDec = {};
|
|
39
|
+
for (const d of ast.decisions || []) {
|
|
40
|
+
const names = inputNames(d);
|
|
41
|
+
const types = inferInputTypes(ast, d);
|
|
42
|
+
typesByDec[d.name] = types;
|
|
43
|
+
const params = names.map((n) => `${n} ${GO_TYPE[types[n]] || 'string'}`).join(', ');
|
|
44
|
+
L.push(`func ${d.name}(${params}) string {`);
|
|
45
|
+
for (const r of d.rules || []) {
|
|
46
|
+
let cond; try { cond = exprToGo(r.when, { inputs: names }); } catch { cond = 'false'; }
|
|
47
|
+
L.push(`\tif ${cond} {`, `\t\treturn ${strLit(r.result)}`, '\t}');
|
|
48
|
+
}
|
|
49
|
+
L.push(`\treturn ${d.default == null ? '""' : strLit(d.default)}`, '}', '');
|
|
50
|
+
}
|
|
51
|
+
// JSON-escape a string via the standard library, so the object we build is valid JSON.
|
|
52
|
+
L.push('func j(s string) string {');
|
|
53
|
+
L.push('\tb, _ := json.Marshal(s)');
|
|
54
|
+
L.push('\treturn string(b)');
|
|
55
|
+
L.push('}');
|
|
56
|
+
L.push('');
|
|
57
|
+
L.push('func main() {');
|
|
58
|
+
L.push('\tvar sb strings.Builder');
|
|
59
|
+
L.push('\tsb.WriteString("{")');
|
|
60
|
+
cases.forEach((c, idx) => {
|
|
61
|
+
const dec = (ast.decisions || []).find((d) => d.name === c.fn);
|
|
62
|
+
if (!dec) return;
|
|
63
|
+
const types = typesByDec[c.fn];
|
|
64
|
+
const argList = inputNames(dec).map((n) => litFor(types[n], c.given[n])).join(', ');
|
|
65
|
+
const sep = idx === 0 ? '' : ',';
|
|
66
|
+
L.push(`\tsb.WriteString(${JSON.stringify(sep)} + j(${strLit(c.key)}) + ":" + j(${c.fn}(${argList})))`);
|
|
67
|
+
});
|
|
68
|
+
L.push('\tsb.WriteString("}")');
|
|
69
|
+
L.push('\tfmt.Println(sb.String())');
|
|
70
|
+
L.push('}');
|
|
71
|
+
return L.join('\n');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function goAvailable() {
|
|
75
|
+
return cachedSmoke('go', () => {
|
|
76
|
+
const dir = mkdtempSync(join(tmpdir(), 'tl-go-smoke-'));
|
|
77
|
+
try {
|
|
78
|
+
const src = 'package main\n\nimport "fmt"\n\nfunc main() {\n\tfmt.Println("{\\"ok\\":\\"1\\"}")\n}';
|
|
79
|
+
const out = goRun(dir, src);
|
|
80
|
+
return !!out && /"ok"/.test(out);
|
|
81
|
+
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Run every decision test case through generated, compiled Go. Returns { "Test / case": actual }
|
|
86
|
+
// or null when no usable Go toolchain is present.
|
|
87
|
+
export function runGoTarget(ast) {
|
|
88
|
+
if (!goAvailable()) return null;
|
|
89
|
+
const cases = buildCases(ast);
|
|
90
|
+
const dir = mkdtempSync(join(tmpdir(), 'tl-go-'));
|
|
91
|
+
try {
|
|
92
|
+
const out = goRun(dir, emitGoModule(ast, cases));
|
|
93
|
+
return out == null ? null : parseLastJsonObject(out);
|
|
94
|
+
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
95
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Kotlin target adapter. Emits a self-contained Kotlin script (.kts) that defines each decision as
|
|
2
|
+
// a typed fun (using the same exprToKotlin translator the codegen uses), calls every test case with
|
|
3
|
+
// typed literal arguments, and prints the results as one JSON line. It runs through the Kotlin
|
|
4
|
+
// script runner (`kotlinc -script`), so a live Kotlin run grades real compiled + executed code.
|
|
5
|
+
// Returns null (skip cleanly) when no usable Kotlin toolchain exists.
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { exprToKotlin } from './expr.mjs';
|
|
11
|
+
import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
|
|
12
|
+
|
|
13
|
+
const KOTLIN_TYPE = { number: 'Double', bool: 'Boolean', string: 'String' };
|
|
14
|
+
// Double params reject bare integer literals, so numeric args carry an explicit decimal.
|
|
15
|
+
const kotlinLit = (type, v) => (type === 'number' ? `${v == null ? 0 : v}${Number.isInteger(Number(v)) ? '.0' : ''}` : litFor(type, v));
|
|
16
|
+
|
|
17
|
+
// Write `source` to a .kts file in `dir` and run it with the Kotlin script runner. Returns stdout,
|
|
18
|
+
// or null on any failure.
|
|
19
|
+
function kotlinRun(dir, source) {
|
|
20
|
+
const f = join(dir, 'main.kts');
|
|
21
|
+
writeFileSync(f, source);
|
|
22
|
+
const env = { ...process.env };
|
|
23
|
+
const r = spawnSync('kotlinc', ['-script', f], { encoding: 'utf8', timeout: 300000, env });
|
|
24
|
+
if (r.status !== 0) return null;
|
|
25
|
+
return r.stdout;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// The emitted Kotlin source (also usable for display / `gen`-parity).
|
|
29
|
+
export function emitKotlinModule(ast, cases = buildCases(ast)) {
|
|
30
|
+
const L = [];
|
|
31
|
+
const typesByDec = {};
|
|
32
|
+
for (const d of ast.decisions || []) {
|
|
33
|
+
const names = inputNames(d);
|
|
34
|
+
const types = inferInputTypes(ast, d);
|
|
35
|
+
typesByDec[d.name] = types;
|
|
36
|
+
const params = names.map((n) => `${n}: ${KOTLIN_TYPE[types[n]] || 'String'}`).join(', ');
|
|
37
|
+
L.push(`fun ${d.name}(${params}): String {`);
|
|
38
|
+
for (const r of d.rules || []) {
|
|
39
|
+
let cond; try { cond = exprToKotlin(r.when, { inputs: names }); } catch { cond = 'false'; }
|
|
40
|
+
L.push(` if (${cond}) return ${strLit(r.result)}`);
|
|
41
|
+
}
|
|
42
|
+
L.push(` return ${d.default == null ? '""' : strLit(d.default)}`, '}', '');
|
|
43
|
+
}
|
|
44
|
+
L.push('fun j(s: String?): String {');
|
|
45
|
+
L.push(' if (s == null) return "null"');
|
|
46
|
+
L.push(' val b = StringBuilder("\\"")');
|
|
47
|
+
L.push(' for (c in s) {');
|
|
48
|
+
L.push(' if (c == \'"\' || c == \'\\\\\') { b.append(\'\\\\\'); b.append(c) }');
|
|
49
|
+
L.push(' else if (c == \'\\n\') { b.append("\\\\n") }');
|
|
50
|
+
L.push(' else { b.append(c) }');
|
|
51
|
+
L.push(' }');
|
|
52
|
+
L.push(' b.append(\'"\')');
|
|
53
|
+
L.push(' return b.toString()');
|
|
54
|
+
L.push('}');
|
|
55
|
+
L.push('');
|
|
56
|
+
L.push('val sb = StringBuilder("{")');
|
|
57
|
+
cases.forEach((c, idx) => {
|
|
58
|
+
const dec = (ast.decisions || []).find((d) => d.name === c.fn);
|
|
59
|
+
if (!dec) return;
|
|
60
|
+
const types = typesByDec[c.fn];
|
|
61
|
+
const argList = inputNames(dec).map((n) => kotlinLit(types[n], c.given[n])).join(', ');
|
|
62
|
+
const sep = idx === 0 ? '' : ',';
|
|
63
|
+
L.push(`sb.append(${JSON.stringify(sep)}).append(j(${strLit(c.key)})).append(":").append(j(${c.fn}(${argList})))`);
|
|
64
|
+
});
|
|
65
|
+
L.push('sb.append("}")');
|
|
66
|
+
L.push('println(sb.toString())');
|
|
67
|
+
return L.join('\n');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function kotlinAvailable() {
|
|
71
|
+
return cachedSmoke('kotlin', () => {
|
|
72
|
+
const dir = mkdtempSync(join(tmpdir(), 'tl-kt-smoke-'));
|
|
73
|
+
try {
|
|
74
|
+
const src = 'println("{\\"ok\\":\\"1\\"}")';
|
|
75
|
+
const out = kotlinRun(dir, src);
|
|
76
|
+
return !!out && /"ok"/.test(out);
|
|
77
|
+
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Run every decision test case through generated, compiled Kotlin. Returns { "Test / case": actual }
|
|
82
|
+
// or null when no usable Kotlin toolchain is present.
|
|
83
|
+
export function runKotlinTarget(ast) {
|
|
84
|
+
if (!kotlinAvailable()) return null;
|
|
85
|
+
const cases = buildCases(ast);
|
|
86
|
+
const dir = mkdtempSync(join(tmpdir(), 'tl-kt-'));
|
|
87
|
+
try {
|
|
88
|
+
const out = kotlinRun(dir, emitKotlinModule(ast, cases));
|
|
89
|
+
return out == null ? null : parseLastJsonObject(out);
|
|
90
|
+
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
91
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Rust target adapter. Emits a self-contained single-file program that defines each decision as a
|
|
2
|
+
// typed fn (using the same exprToRust translator the codegen uses), calls every test case with
|
|
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. Returns null
|
|
5
|
+
// (skip cleanly) when no usable Rust toolchain exists.
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { exprToRust } from './expr.mjs';
|
|
11
|
+
import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
|
|
12
|
+
|
|
13
|
+
const RUST_TYPE = { number: 'f64', bool: 'bool', string: '&str' };
|
|
14
|
+
// f64 params reject bare integer literals, so numeric args carry an explicit f64 suffix.
|
|
15
|
+
const rustLit = (type, v) => (type === 'number' ? `${v == null ? 0 : v}f64` : litFor(type, v));
|
|
16
|
+
|
|
17
|
+
// Compile `source` with rustc and run the binary. Returns stdout, or null on any failure.
|
|
18
|
+
function rustcRun(dir, source) {
|
|
19
|
+
const src = join(dir, 'main.rs');
|
|
20
|
+
const bin = join(dir, process.platform === 'win32' ? 'main.exe' : 'main_bin');
|
|
21
|
+
writeFileSync(src, source);
|
|
22
|
+
const env = { ...process.env };
|
|
23
|
+
const c = spawnSync('rustc', ['-O', src, '-o', bin], { encoding: 'utf8', timeout: 180000, env });
|
|
24
|
+
if (c.status !== 0) return null;
|
|
25
|
+
const r = spawnSync(bin, [], { encoding: 'utf8', timeout: 60000, env });
|
|
26
|
+
if (r.status !== 0) return null;
|
|
27
|
+
return r.stdout;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// The emitted Rust source (also usable for display / `gen`-parity).
|
|
31
|
+
export function emitRustModule(ast, cases = buildCases(ast)) {
|
|
32
|
+
const L = [
|
|
33
|
+
'#![allow(non_snake_case, unused_parens, dead_code, unused_variables)]',
|
|
34
|
+
'',
|
|
35
|
+
];
|
|
36
|
+
const typesByDec = {};
|
|
37
|
+
for (const d of ast.decisions || []) {
|
|
38
|
+
const names = inputNames(d);
|
|
39
|
+
const types = inferInputTypes(ast, d);
|
|
40
|
+
typesByDec[d.name] = types;
|
|
41
|
+
const params = names.map((n) => `${n}: ${RUST_TYPE[types[n]] || '&str'}`).join(', ');
|
|
42
|
+
L.push(`fn ${d.name}(${params}) -> &'static str {`);
|
|
43
|
+
for (const r of d.rules || []) {
|
|
44
|
+
let cond; try { cond = exprToRust(r.when, { inputs: names }); } catch { cond = 'false'; }
|
|
45
|
+
L.push(` if ${cond} { return ${strLit(r.result)}; }`);
|
|
46
|
+
}
|
|
47
|
+
L.push(` return ${d.default == null ? '""' : strLit(d.default)};`, '}', '');
|
|
48
|
+
}
|
|
49
|
+
L.push('fn j(s: &str) -> String {');
|
|
50
|
+
L.push(' let mut out = String::from("\\"");');
|
|
51
|
+
L.push(' for c in s.chars() {');
|
|
52
|
+
L.push(' match c {');
|
|
53
|
+
L.push(' \'"\' | \'\\\\\' => { out.push(\'\\\\\'); out.push(c); }');
|
|
54
|
+
L.push(' \'\\n\' => out.push_str("\\\\n"),');
|
|
55
|
+
L.push(' _ => out.push(c),');
|
|
56
|
+
L.push(' }');
|
|
57
|
+
L.push(' }');
|
|
58
|
+
L.push(' out.push(\'"\');');
|
|
59
|
+
L.push(' out');
|
|
60
|
+
L.push('}');
|
|
61
|
+
L.push('');
|
|
62
|
+
L.push('fn main() {');
|
|
63
|
+
L.push(' let mut sb = String::from("{");');
|
|
64
|
+
cases.forEach((c, idx) => {
|
|
65
|
+
const dec = (ast.decisions || []).find((d) => d.name === c.fn);
|
|
66
|
+
if (!dec) return;
|
|
67
|
+
const types = typesByDec[c.fn];
|
|
68
|
+
const argList = inputNames(dec).map((n) => rustLit(types[n], c.given[n])).join(', ');
|
|
69
|
+
const sep = idx === 0 ? '' : ',';
|
|
70
|
+
L.push(` sb.push_str(&format!("{}{}:{}", ${JSON.stringify(sep)}, j(${strLit(c.key)}), j(${c.fn}(${argList}))));`);
|
|
71
|
+
});
|
|
72
|
+
L.push(' sb.push_str("}");');
|
|
73
|
+
L.push(' println!("{}", sb);');
|
|
74
|
+
L.push('}');
|
|
75
|
+
return L.join('\n');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function rustAvailable() {
|
|
79
|
+
return cachedSmoke('rust', () => {
|
|
80
|
+
const dir = mkdtempSync(join(tmpdir(), 'tl-rust-smoke-'));
|
|
81
|
+
try {
|
|
82
|
+
const src = 'fn main() {\n println!("{}", "{\\"ok\\":\\"1\\"}");\n}';
|
|
83
|
+
const out = rustcRun(dir, src);
|
|
84
|
+
return !!out && /"ok"/.test(out);
|
|
85
|
+
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Run every decision test case through generated, compiled Rust. Returns { "Test / case": actual }
|
|
90
|
+
// or null when no usable Rust toolchain is present.
|
|
91
|
+
export function runRustTarget(ast) {
|
|
92
|
+
if (!rustAvailable()) return null;
|
|
93
|
+
const cases = buildCases(ast);
|
|
94
|
+
const dir = mkdtempSync(join(tmpdir(), 'tl-rust-'));
|
|
95
|
+
try {
|
|
96
|
+
const out = rustcRun(dir, emitRustModule(ast, cases));
|
|
97
|
+
return out == null ? null : parseLastJsonObject(out);
|
|
98
|
+
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
99
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Scala target adapter. Emits a self-contained Scala script that defines each decision as a typed
|
|
2
|
+
// def (using the same exprToScala translator the codegen uses), calls every test case with typed
|
|
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. Returns null (skip
|
|
5
|
+
// cleanly) when no usable Scala toolchain exists.
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { exprToScala } from './expr.mjs';
|
|
11
|
+
import { inputNames, inferInputTypes, buildCases, parseLastJsonObject, cachedSmoke, strLit, litFor } from './target-util.mjs';
|
|
12
|
+
|
|
13
|
+
const SCALA_TYPE = { number: 'Double', bool: 'Boolean', string: 'String' };
|
|
14
|
+
// Which runner worked during the smoke, so run reuses it: [cmd, argsFor(file)].
|
|
15
|
+
let SCALA_RUNNER = null;
|
|
16
|
+
|
|
17
|
+
// Write `source` to a .scala file in `dir` and run it. Prefers `scala` (script mode); falls back to
|
|
18
|
+
// `scala-cli run`. Returns stdout, or null on any failure.
|
|
19
|
+
function scalaRun(dir, source) {
|
|
20
|
+
const f = join(dir, 'Main.scala');
|
|
21
|
+
writeFileSync(f, source);
|
|
22
|
+
const env = { ...process.env };
|
|
23
|
+
const runners = SCALA_RUNNER ? [SCALA_RUNNER] : [['scala', (p) => [p]], ['scala-cli', (p) => ['run', p]]];
|
|
24
|
+
for (const [cmd, argsFor] of runners) {
|
|
25
|
+
const r = spawnSync(cmd, argsFor(f), { encoding: 'utf8', timeout: 300000, env });
|
|
26
|
+
if (r.status === 0 && r.stdout) { SCALA_RUNNER = [cmd, argsFor]; return r.stdout; }
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// The emitted Scala source (also usable for display / `gen`-parity).
|
|
32
|
+
export function emitScalaModule(ast, cases = buildCases(ast)) {
|
|
33
|
+
const L = [];
|
|
34
|
+
const typesByDec = {};
|
|
35
|
+
for (const d of ast.decisions || []) {
|
|
36
|
+
const names = inputNames(d);
|
|
37
|
+
const types = inferInputTypes(ast, d);
|
|
38
|
+
typesByDec[d.name] = types;
|
|
39
|
+
const params = names.map((n) => `${n}: ${SCALA_TYPE[types[n]] || 'String'}`).join(', ');
|
|
40
|
+
L.push(`def ${d.name}(${params}): String = {`);
|
|
41
|
+
for (const r of d.rules || []) {
|
|
42
|
+
let cond; try { cond = exprToScala(r.when, { inputs: names }); } catch { cond = 'false'; }
|
|
43
|
+
L.push(` if (${cond}) return ${strLit(r.result)}`);
|
|
44
|
+
}
|
|
45
|
+
L.push(` return ${d.default == null ? 'null' : strLit(d.default)}`, '}', '');
|
|
46
|
+
}
|
|
47
|
+
L.push('def j(s: String): String = {');
|
|
48
|
+
L.push(' if (s == null) return "null"');
|
|
49
|
+
L.push(' val b = new StringBuilder("\\"")');
|
|
50
|
+
L.push(' for (c <- s) {');
|
|
51
|
+
L.push(' if (c == \'"\' || c == \'\\\\\') { b.append(\'\\\\\'); b.append(c) }');
|
|
52
|
+
L.push(' else if (c == \'\\n\') b.append("\\\\n")');
|
|
53
|
+
L.push(' else b.append(c)');
|
|
54
|
+
L.push(' }');
|
|
55
|
+
L.push(' b.append(\'"\').toString');
|
|
56
|
+
L.push('}');
|
|
57
|
+
L.push('');
|
|
58
|
+
L.push('val sb = new StringBuilder("{")');
|
|
59
|
+
cases.forEach((c, idx) => {
|
|
60
|
+
const dec = (ast.decisions || []).find((d) => d.name === c.fn);
|
|
61
|
+
if (!dec) return;
|
|
62
|
+
const types = typesByDec[c.fn];
|
|
63
|
+
const argList = inputNames(dec).map((n) => litFor(types[n], c.given[n])).join(', ');
|
|
64
|
+
const sep = idx === 0 ? '' : ',';
|
|
65
|
+
L.push(`sb.append(${JSON.stringify(sep)}).append(j(${strLit(c.key)})).append(":").append(j(${c.fn}(${argList})))`);
|
|
66
|
+
});
|
|
67
|
+
L.push('sb.append("}")');
|
|
68
|
+
L.push('println(sb.toString)');
|
|
69
|
+
return L.join('\n');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function scalaAvailable() {
|
|
73
|
+
return cachedSmoke('scala', () => {
|
|
74
|
+
const dir = mkdtempSync(join(tmpdir(), 'tl-scala-smoke-'));
|
|
75
|
+
try {
|
|
76
|
+
const src = 'println("{\\"ok\\":\\"1\\"}")';
|
|
77
|
+
const out = scalaRun(dir, src);
|
|
78
|
+
return !!out && /"ok"/.test(out);
|
|
79
|
+
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Run every decision test case through generated, compiled Scala. Returns { "Test / case": actual }
|
|
84
|
+
// or null when no usable Scala toolchain is present.
|
|
85
|
+
export function runScalaTarget(ast) {
|
|
86
|
+
if (!scalaAvailable()) return null;
|
|
87
|
+
const cases = buildCases(ast);
|
|
88
|
+
const dir = mkdtempSync(join(tmpdir(), 'tl-scala-'));
|
|
89
|
+
try {
|
|
90
|
+
const out = scalaRun(dir, emitScalaModule(ast, cases));
|
|
91
|
+
return out == null ? null : parseLastJsonObject(out);
|
|
92
|
+
} finally { try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } }
|
|
93
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Browser-safe helpers shared by the target adapters and the in-browser translator.
|
|
2
|
+
// No Node imports here, so the website can bundle this file.
|
|
3
|
+
|
|
4
|
+
export const inputNames = (dec) => (dec.inputs || []).map((i) => String(i).split(':')[0].trim()).filter(Boolean);
|
|
5
|
+
|
|
6
|
+
export function coerceVal(v) {
|
|
7
|
+
if (v == null || typeof v !== 'string') return v;
|
|
8
|
+
const s = v.trim();
|
|
9
|
+
if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
|
|
10
|
+
if (s === 'true') return true;
|
|
11
|
+
if (s === 'false') return false;
|
|
12
|
+
return v;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Every case-call we will emit, in a stable order: { key, fn, given: {name: coercedValue} }.
|
|
16
|
+
export function buildCases(ast) {
|
|
17
|
+
const cases = [];
|
|
18
|
+
for (const t of ast.tests || []) {
|
|
19
|
+
const dec = (ast.decisions || []).find((d) => d.name === t.name);
|
|
20
|
+
if (!dec) continue;
|
|
21
|
+
const names = inputNames(dec);
|
|
22
|
+
for (const c of t.cases || []) {
|
|
23
|
+
const given = {};
|
|
24
|
+
for (const n of names) given[n] = coerceVal((c.given || {})[n]);
|
|
25
|
+
cases.push({ key: `${t.name} / ${c.name || 'case'}`, fn: t.name, given });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return cases;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Infer one type per input for a decision, scanning every case that targets it. Numeric usage
|
|
32
|
+
// wins (a relational comparison must compile), then boolean, else string. Falls back to 'string'.
|
|
33
|
+
export function inferInputTypes(ast, dec) {
|
|
34
|
+
const names = inputNames(dec);
|
|
35
|
+
const types = {};
|
|
36
|
+
for (const n of names) {
|
|
37
|
+
let t = 'string';
|
|
38
|
+
for (const test of (ast.tests || []).filter((x) => x.name === dec.name)) {
|
|
39
|
+
for (const c of test.cases || []) {
|
|
40
|
+
const raw = (c.given || {})[n];
|
|
41
|
+
if (raw == null) continue;
|
|
42
|
+
const cv = coerceVal(raw);
|
|
43
|
+
if (typeof cv === 'number') { t = 'number'; break; }
|
|
44
|
+
if (typeof cv === 'boolean' && t !== 'number') t = 'bool';
|
|
45
|
+
}
|
|
46
|
+
if (t === 'number') break;
|
|
47
|
+
}
|
|
48
|
+
types[n] = t;
|
|
49
|
+
}
|
|
50
|
+
return types;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// A source literal for a value at an inferred type. JSON string escaping is valid in Java and C#
|
|
54
|
+
// string literals too, so we reuse JSON.stringify for the string case.
|
|
55
|
+
export const strLit = (s) => JSON.stringify(String(s));
|
|
56
|
+
export function litFor(type, v) {
|
|
57
|
+
if (v == null) return type === 'string' ? '""' : type === 'bool' ? 'false' : '0';
|
|
58
|
+
if (type === 'number') return String(v);
|
|
59
|
+
if (type === 'bool') return v === true || v === 'true' ? 'true' : 'false';
|
|
60
|
+
return strLit(v);
|
|
61
|
+
}
|
|
62
|
+
|
package/src/target-util.mjs
CHANGED
|
@@ -2,55 +2,7 @@
|
|
|
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
|
-
|
|
6
|
-
export const inputNames = (dec) => (dec.inputs || []).map((i) => String(i).split(':')[0].trim()).filter(Boolean);
|
|
7
|
-
|
|
8
|
-
export function coerceVal(v) {
|
|
9
|
-
if (v == null || typeof v !== 'string') return v;
|
|
10
|
-
const s = v.trim();
|
|
11
|
-
if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
|
|
12
|
-
if (s === 'true') return true;
|
|
13
|
-
if (s === 'false') return false;
|
|
14
|
-
return v;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
// Every case-call we will emit, in a stable order: { key, fn, given: {name: coercedValue} }.
|
|
18
|
-
export function buildCases(ast) {
|
|
19
|
-
const cases = [];
|
|
20
|
-
for (const t of ast.tests || []) {
|
|
21
|
-
const dec = (ast.decisions || []).find((d) => d.name === t.name);
|
|
22
|
-
if (!dec) continue;
|
|
23
|
-
const names = inputNames(dec);
|
|
24
|
-
for (const c of t.cases || []) {
|
|
25
|
-
const given = {};
|
|
26
|
-
for (const n of names) given[n] = coerceVal((c.given || {})[n]);
|
|
27
|
-
cases.push({ key: `${t.name} / ${c.name || 'case'}`, fn: t.name, given });
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
return cases;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// Infer one type per input for a decision, scanning every case that targets it. Numeric usage
|
|
34
|
-
// wins (a relational comparison must compile), then boolean, else string. Falls back to 'string'.
|
|
35
|
-
export function inferInputTypes(ast, dec) {
|
|
36
|
-
const names = inputNames(dec);
|
|
37
|
-
const types = {};
|
|
38
|
-
for (const n of names) {
|
|
39
|
-
let t = 'string';
|
|
40
|
-
for (const test of (ast.tests || []).filter((x) => x.name === dec.name)) {
|
|
41
|
-
for (const c of test.cases || []) {
|
|
42
|
-
const raw = (c.given || {})[n];
|
|
43
|
-
if (raw == null) continue;
|
|
44
|
-
const cv = coerceVal(raw);
|
|
45
|
-
if (typeof cv === 'number') { t = 'number'; break; }
|
|
46
|
-
if (typeof cv === 'boolean' && t !== 'number') t = 'bool';
|
|
47
|
-
}
|
|
48
|
-
if (t === 'number') break;
|
|
49
|
-
}
|
|
50
|
-
types[n] = t;
|
|
51
|
-
}
|
|
52
|
-
return types;
|
|
53
|
-
}
|
|
5
|
+
export { inputNames, coerceVal, buildCases, inferInputTypes, strLit, litFor } from './target-types.mjs';
|
|
54
6
|
|
|
55
7
|
// Pick the last line of stdout that parses as a JSON object , build/tool chatter may precede it.
|
|
56
8
|
export function parseLastJsonObject(stdout) {
|
|
@@ -75,16 +27,6 @@ export function cachedSmoke(key, fn) {
|
|
|
75
27
|
return ok;
|
|
76
28
|
}
|
|
77
29
|
|
|
78
|
-
// A source literal for a value at an inferred type. JSON string escaping is valid in Java and C#
|
|
79
|
-
// string literals too, so we reuse JSON.stringify for the string case.
|
|
80
|
-
export const strLit = (s) => JSON.stringify(String(s));
|
|
81
|
-
export function litFor(type, v) {
|
|
82
|
-
if (v == null) return type === 'string' ? '""' : type === 'bool' ? 'false' : '0';
|
|
83
|
-
if (type === 'number') return String(v);
|
|
84
|
-
if (type === 'bool') return v === true || v === 'true' ? 'true' : 'false';
|
|
85
|
-
return strLit(v);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
30
|
export function toolOnPath(cmd, args = ['--version']) {
|
|
89
31
|
try {
|
|
90
32
|
const r = spawnSync(cmd, args, { encoding: 'utf8', timeout: 15000 });
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { IntentAst } from './index.js';
|
|
2
|
+
export type TranslateLanguage = 'typescript' | 'python' | 'go' | 'rust' | 'csharp' | 'java';
|
|
3
|
+
export const TRANSLATE_LANGUAGES: Array<{ key: TranslateLanguage; label: string }>;
|
|
4
|
+
/** Translate every decision in a parsed ThunderLang AST into readable, typed source. Deterministic. */
|
|
5
|
+
export function translateDecisions(ast: IntentAst, lang: TranslateLanguage): string;
|