@skillstech/thunderlang 0.4.1 → 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.
@@ -0,0 +1,126 @@
1
+ // Browser-safe decision translator: renders each decision as a readable, typed function in a
2
+ // target language. It uses the SAME expression translators (exprTo*) and the SAME input-type
3
+ // inference as the executable target adapters (target-*.mjs), minus their test harness, so what
4
+ // a reader sees here matches what `thunder test <file> --target <lang>` compiles and runs.
5
+ // Deterministic, no AI, no Node imports.
6
+ import { exprToJs, exprToPython, exprToGo, exprToRust, exprToCSharp, exprToJava } from './expr.mjs';
7
+ import { inputNames, inferInputTypes, strLit } from './target-types.mjs';
8
+
9
+ const RELATIONAL = /^(<=|>=|<|>)$/;
10
+
11
+ /**
12
+ * Example values decide an input's type first (as the target adapters do). With no example value
13
+ * for an input, fall back to how the rules use it: a relational comparison means number, a bare
14
+ * operand of and/or/not means bool, anything else stays string.
15
+ */
16
+ function typesFor(ast, dec) {
17
+ const names = inputNames(dec);
18
+ const types = inferInputTypes(ast, dec);
19
+ const hasExample = (n) => (ast.tests || []).some((t) => t.name === dec.name && (t.cases || []).some((c) => (c.given || {})[n] != null));
20
+ // A declared type (`amount: number`, as the reader and typed contracts emit) wins outright.
21
+ const declared = {};
22
+ for (const raw of dec.inputs || []) {
23
+ const m = String(raw).match(/^\s*(\w+)\s*:\s*(number|boolean|bool|string)\s*$/);
24
+ if (m) declared[m[1]] = m[2] === 'boolean' ? 'bool' : m[2];
25
+ }
26
+ for (const n of names) {
27
+ if (declared[n]) { types[n] = declared[n]; continue; }
28
+ if (hasExample(n)) continue;
29
+ let guess = 'string';
30
+ for (const r of dec.rules || []) {
31
+ const toks = String(r.when || '').split(/\s+|(?=[()])|(?<=[()])/).filter(Boolean);
32
+ toks.forEach((t, i) => {
33
+ if (t !== n) return;
34
+ if (RELATIONAL.test(toks[i - 1] || '') || RELATIONAL.test(toks[i + 1] || '')) guess = 'number';
35
+ else if (guess === 'string' && !/^(==|!=|in)$/.test(toks[i + 1] || '') && !/^(==|!=)$/.test(toks[i - 1] || '')) guess = 'bool';
36
+ });
37
+ }
38
+ types[n] = guess;
39
+ }
40
+ return types;
41
+ }
42
+
43
+ const tryExpr = (fn, when, inputs, fallback) => { try { return fn(when, { inputs }); } catch { return fallback; } };
44
+
45
+ const LANGS = {
46
+ typescript: {
47
+ label: 'TypeScript',
48
+ types: { number: 'number', bool: 'boolean', string: 'string' },
49
+ emit(d, names, types) {
50
+ const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(', ');
51
+ const L = [`export function ${d.name}(${params}): string {`];
52
+ for (const r of d.rules || []) L.push(` if (${tryExpr(exprToJs, r.when, names, 'false')}) return ${strLit(r.result)};`);
53
+ L.push(` return ${strLit(d.default ?? '')};`, '}');
54
+ return L;
55
+ },
56
+ },
57
+ python: {
58
+ label: 'Python',
59
+ types: { number: 'float', bool: 'bool', string: 'str' },
60
+ emit(d, names, types) {
61
+ const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(', ');
62
+ const L = [`def ${d.name}(${params}) -> str:`];
63
+ for (const r of d.rules || []) L.push(` if ${tryExpr(exprToPython, r.when, names, 'False')}:`, ` return ${strLit(r.result)}`);
64
+ L.push(` return ${strLit(d.default ?? '')}`);
65
+ return L;
66
+ },
67
+ },
68
+ go: {
69
+ label: 'Go',
70
+ types: { number: 'float64', bool: 'bool', string: 'string' },
71
+ emit(d, names, types) {
72
+ const params = names.map((n) => `${n} ${this.types[types[n]]}`).join(', ');
73
+ const L = [`func ${d.name}(${params}) string {`];
74
+ for (const r of d.rules || []) L.push(`\tif ${tryExpr(exprToGo, r.when, names, 'false')} {`, `\t\treturn ${strLit(r.result)}`, '\t}');
75
+ L.push(`\treturn ${strLit(d.default ?? '')}`, '}');
76
+ return L;
77
+ },
78
+ },
79
+ rust: {
80
+ label: 'Rust',
81
+ types: { number: 'f64', bool: 'bool', string: '&str' },
82
+ emit(d, names, types) {
83
+ const params = names.map((n) => `${n}: ${this.types[types[n]]}`).join(', ');
84
+ const L = [`fn ${d.name}(${params}) -> &'static str {`];
85
+ for (const r of d.rules || []) L.push(` if ${tryExpr(exprToRust, r.when, names, 'false')} {`, ` return ${strLit(r.result)};`, ' }');
86
+ L.push(` ${strLit(d.default ?? '')}`, '}');
87
+ return L;
88
+ },
89
+ },
90
+ csharp: {
91
+ label: 'C#',
92
+ types: { number: 'double', bool: 'bool', string: 'string' },
93
+ emit(d, names, types) {
94
+ const params = names.map((n) => `${this.types[types[n]]} ${n}`).join(', ');
95
+ const L = [`public static string ${d.name}(${params})`, '{'];
96
+ for (const r of d.rules || []) L.push(` if (${tryExpr(exprToCSharp, r.when, names, 'false')}) return ${strLit(r.result)};`);
97
+ L.push(` return ${strLit(d.default ?? '')};`, '}');
98
+ return L;
99
+ },
100
+ },
101
+ java: {
102
+ label: 'Java',
103
+ types: { number: 'double', bool: 'boolean', string: 'String' },
104
+ emit(d, names, types) {
105
+ const params = names.map((n) => `${this.types[types[n]]} ${n}`).join(', ');
106
+ const L = [`public static String ${d.name}(${params}) {`];
107
+ for (const r of d.rules || []) L.push(` if (${tryExpr(exprToJava, r.when, names, 'false')}) return ${strLit(r.result)};`);
108
+ L.push(` return ${strLit(d.default ?? '')};`, '}');
109
+ return L;
110
+ },
111
+ },
112
+ };
113
+
114
+ export const TRANSLATE_LANGUAGES = Object.entries(LANGS).map(([key, l]) => ({ key, label: l.label }));
115
+
116
+ /** Translate every decision in a parsed ThunderLang AST into `lang`. Returns source text. */
117
+ export function translateDecisions(ast, lang) {
118
+ const L = LANGS[lang];
119
+ if (!L) throw new Error(`Unknown language ${lang}. Use one of: ${Object.keys(LANGS).join(', ')}.`);
120
+ const comment = lang === 'python' ? '#' : '//';
121
+ const out = [`${comment} Generated from ThunderLang. Deterministic, no AI. The first matching rule wins.`];
122
+ for (const d of ast.decisions || []) {
123
+ out.push('', ...L.emit(d, inputNames(d), typesFor(ast, d)));
124
+ }
125
+ return out.join('\n');
126
+ }