@skillstech/thunderlang 1.1.0 → 1.3.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 +212 -0
- package/README.md +4 -1
- package/dist/core.cjs +2080 -278
- package/dist/index.cjs +12742 -10943
- package/dist/learn.cjs +12976 -3598
- package/package.json +2 -2
- package/src/cli-home.mjs +242 -0
- package/src/cli.mjs +135 -41
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +208 -17
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -0
- package/src/core/engine-core.mjs +855 -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 +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +3 -1
- package/src/core/java/thunder/T.java +6 -0
- package/src/core/java/thunder/ThunderRuntime.java +1374 -0
- package/src/core/java-run.mjs +89 -0
- package/src/core/parser.mjs +331 -5
- package/src/core/project.mjs +43 -8
- package/src/core/react-run.mjs +96 -0
- package/src/core/runtime-go/thunder_runtime.go +3038 -0
- package/src/core/runtime-react.mjs +133 -0
- package/src/core/runtime-typescript.mjs +119 -0
- package/src/core/rust/thunder_runtime.rs +1645 -0
- package/src/core/rust-run.mjs +192 -0
- package/src/core/screen-values.mjs +30 -0
- package/src/core/target-csharp.mjs +484 -0
- package/src/core/target-go.mjs +555 -0
- package/src/core/target-java.mjs +587 -0
- package/src/core/target-python.mjs +2 -1
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +466 -0
- package/src/core/typescript-run.mjs +114 -0
- package/src/core.d.ts +18 -0
- package/src/core.mjs +1 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +30 -0
- package/src/learn-lessons.mjs +245 -1
- package/src/learn.d.mts +8 -0
- package/src/learn.mjs +40 -4
- package/src/libraries.mjs +10 -3
- package/src/model.mjs +50 -8
- package/src/read-level.mjs +192 -0
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +28 -5
- package/src/replay-cli.mjs +123 -0
- package/src/say-less.mjs +152 -11
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +430 -19
- package/src/term.mjs +132 -0
- package/src/try-cli.mjs +225 -0
- package/src/why-cli.mjs +17 -7
- package/src/why.d.mts +17 -7
- package/src/why.mjs +114 -33
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// Writing compiled Java to disk, compiling it with javac, and running it.
|
|
2
|
+
//
|
|
3
|
+
// Layout of a build (generated/java/): app/<Class>.java for every Thunder file and app/RunTests.java, the runtime in
|
|
4
|
+
// thunder/ (ThunderRuntime.java and T.java), and the compiled classes in classes/. Running needs a JDK 17 or newer:
|
|
5
|
+
// Thunder looks in THUNDER_JAVA_HOME, then JAVA_HOME, then the PATH. Without one it says plainly what to install.
|
|
6
|
+
import { writeFileSync, mkdirSync, readFileSync, rmSync, existsSync } from 'node:fs';
|
|
7
|
+
import { join, delimiter } from 'node:path';
|
|
8
|
+
import { spawnSync } from 'node:child_process';
|
|
9
|
+
import { toJava, javaTestRunner, javaClassName } from './target-java.mjs';
|
|
10
|
+
import { pythonOnlyUses } from './target-typescript.mjs';
|
|
11
|
+
import { diag } from './diagnostics.mjs';
|
|
12
|
+
|
|
13
|
+
const RUNTIME_DIR = new URL('./java/thunder/', import.meta.url);
|
|
14
|
+
/** The Java runtime, written next to compiled Java: { 'thunder/ThunderRuntime.java': text, 'thunder/T.java': text }. */
|
|
15
|
+
export const JAVA_RUNTIME = Object.fromEntries(['ThunderRuntime.java', 'T.java'].map((f) => [`thunder/${f}`, readFileSync(new URL(f, RUNTIME_DIR), 'utf8')]));
|
|
16
|
+
|
|
17
|
+
/** The names a src file gives a test file (its records, functions, and kept values). */
|
|
18
|
+
const exportedNames = (r) => [...r.info.records, ...r.info.funcs, ...r.info.consts].filter((s) => !r.info.imported?.has(s)).map((s) => s.py);
|
|
19
|
+
|
|
20
|
+
/** TC405 for every Use in a file: Python modules exist only for the Python target. */
|
|
21
|
+
export function javaDiagnostics(result) {
|
|
22
|
+
return pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
23
|
+
`"${u.module}" is a Python module, and this program is compiled to Java, which cannot use it.`,
|
|
24
|
+
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Compile checked results to Java: { 'app/<Class>.java': text, 'app/RunTests.java': text }. */
|
|
28
|
+
export function compileJava(results, { pkg = 'app' } = {}) {
|
|
29
|
+
const src = results.filter((r) => r.kind !== 'test');
|
|
30
|
+
const out = {};
|
|
31
|
+
for (const r of results) {
|
|
32
|
+
const imports = r.kind === 'test' ? src.map((s) => ({ module: s.module, names: exportedNames(s) })) : [];
|
|
33
|
+
out[`${pkg}/${javaClassName(r.module)}.java`] = toJava(r.program, r.info, { source: r.file, module: r.module, imports, pkg });
|
|
34
|
+
}
|
|
35
|
+
out[`${pkg}/RunTests.java`] = javaTestRunner(results, pkg);
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Write the Java for every result and the runtime into outDir. Gives back the files written (relative paths). */
|
|
40
|
+
export function writeJava(results, outDir, { pkg = 'app' } = {}) {
|
|
41
|
+
const files = { ...compileJava(results, { pkg }), ...JAVA_RUNTIME };
|
|
42
|
+
rmSync(join(outDir, pkg), { recursive: true, force: true }); // a file removed from the project leaves no stale class
|
|
43
|
+
for (const [rel, text] of Object.entries(files)) {
|
|
44
|
+
mkdirSync(join(outDir, rel, '..'), { recursive: true });
|
|
45
|
+
writeFileSync(join(outDir, rel), text);
|
|
46
|
+
}
|
|
47
|
+
return Object.keys(files);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const exe = (name) => (process.platform === 'win32' ? `${name}.exe` : name);
|
|
51
|
+
const works = (cmd) => { try { const r = spawnSync(cmd, ['-version'], { encoding: 'utf8' }); return r.status === 0; } catch { return false; } };
|
|
52
|
+
|
|
53
|
+
/** Where the JDK is: { javac, java } or { error }. THUNDER_JAVA_HOME, then JAVA_HOME, then the PATH. */
|
|
54
|
+
export function findJava({ env = process.env } = {}) {
|
|
55
|
+
for (const home of [env.THUNDER_JAVA_HOME, env.JAVA_HOME].filter(Boolean)) {
|
|
56
|
+
const javac = join(home, 'bin', exe('javac')), java = join(home, 'bin', exe('java'));
|
|
57
|
+
if (existsSync(javac) && existsSync(java) && works(javac)) return { javac, java };
|
|
58
|
+
}
|
|
59
|
+
for (const dir of String(env.PATH ?? '').split(delimiter).filter(Boolean)) {
|
|
60
|
+
const javac = join(dir, exe('javac')), java = join(dir, exe('java'));
|
|
61
|
+
if (existsSync(javac) && existsSync(java) && works(javac)) return { javac, java };
|
|
62
|
+
}
|
|
63
|
+
return { error: 'Running Java needs a JDK 17 or newer (javac and java), and none was found. Install one (for example from https://adoptium.net) and put it on the PATH, or set JAVA_HOME. "thunder build --target java" works without it.' };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** javac every source in outDir into outDir/classes. { ok, output }. */
|
|
67
|
+
export function compileJavaSources(outDir, jdk, files) {
|
|
68
|
+
const classes = join(outDir, 'classes');
|
|
69
|
+
rmSync(classes, { recursive: true, force: true });
|
|
70
|
+
mkdirSync(classes, { recursive: true });
|
|
71
|
+
const r = spawnSync(jdk.javac, ['--release', '17', '-encoding', 'UTF-8', '-nowarn', '-d', classes, ...files.map((f) => join(outDir, f))], { encoding: 'utf8' });
|
|
72
|
+
return { ok: r.status === 0, output: `${r.stdout ?? ''}${r.stderr ?? ''}`.trim() };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Options that make a short program start fast. */
|
|
76
|
+
export const JAVA_FAST = ['-XX:+UseSerialGC', '-XX:TieredStopAtLevel=1', '-Xshare:auto'];
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Compile the Java in outDir and run one class (`main` is a Thunder module, or 'RunTests'), in the folder `cwd`.
|
|
80
|
+
* Returns spawnSync's result ({ status, stdout, stderr }), or { status: 2, stderr, error } when Java cannot run here.
|
|
81
|
+
*/
|
|
82
|
+
export function runJava(outDir, files, main, { cwd = outDir, stdio = 'pipe', pkg = 'app' } = {}) {
|
|
83
|
+
const jdk = findJava();
|
|
84
|
+
if (jdk.error) return { status: 2, stdout: '', stderr: `${jdk.error}\n`, error: jdk.error };
|
|
85
|
+
const c = compileJavaSources(outDir, jdk, files.filter((f) => f.endsWith('.java')));
|
|
86
|
+
if (!c.ok) return { status: 2, stdout: '', stderr: `javac could not compile the generated Java (a bug in Thunder):\n${c.output}\n`, error: c.output };
|
|
87
|
+
const cls = main === 'RunTests' ? 'RunTests' : javaClassName(main);
|
|
88
|
+
return spawnSync(jdk.java, [...JAVA_FAST, '-cp', join(outDir, 'classes'), `${pkg}.${cls}`], { cwd, stdio, encoding: 'utf8' });
|
|
89
|
+
}
|
package/src/core/parser.mjs
CHANGED
|
@@ -132,23 +132,53 @@ function collectNames(nodes, names) {
|
|
|
132
132
|
if (andAt >= 0) { add('var', head.slice(0, andAt)); add('var', head.slice(andAt + 1)); } else add('var', head);
|
|
133
133
|
} else if (w0 === 'to' && isSym(ts[ts.length - 1], ':')) {
|
|
134
134
|
add('func', ts.slice(1, -1));
|
|
135
|
+
// Its inputs, in order (for a call written with names): every Receive line at the top of the block.
|
|
136
|
+
const inputs = [];
|
|
137
|
+
for (const c of n.children) {
|
|
138
|
+
if (!isWord(c.tokens[0], 'receive')) break;
|
|
139
|
+
for (const p of paramGroups(c.tokens.slice(1))) inputs.push({ key: keyOf(p.words), text: p.words.map((x) => x.text).join(' '), defaultTokens: p.defaultTokens });
|
|
140
|
+
}
|
|
141
|
+
names.funcInputs.set(keyOf(ts.slice(1, -1)), inputs);
|
|
135
142
|
} else if ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has')) {
|
|
136
143
|
const words = ts.slice(1, -2);
|
|
137
144
|
add('record', words);
|
|
145
|
+
const own = [];
|
|
138
146
|
for (const c of n.children) {
|
|
139
147
|
const k = c.tokens.findIndex((t) => isWord(t, 'is'));
|
|
140
|
-
if (k > 0 && !isWord(c.tokens[0], 'never')) names.fields.add(keyOf(c.tokens.slice(0, k)));
|
|
148
|
+
if (k > 0 && !isWord(c.tokens[0], 'never')) { names.fields.add(keyOf(c.tokens.slice(0, k))); own.push(keyOf(c.tokens.slice(0, k))); }
|
|
141
149
|
}
|
|
150
|
+
names.recordFields.set(keyOf(words), own);
|
|
151
|
+
names.recordText.set(keyOf(words), words.map((x) => x.text).join(' '));
|
|
142
152
|
} else if (w0 === 'use') {
|
|
143
153
|
const k = ts.findIndex((t) => isWord(t, 'as'));
|
|
144
154
|
if (k > 0) add('module', ts.slice(k + 1)); else if (ts[1]?.t === 'word') add('module', [ts[1]]);
|
|
145
155
|
} else if (w0 === 'if' && keyOf(ts.slice(0, 3)) === 'if this fails') {
|
|
146
156
|
add('var', [{ lower: 'error' }]);
|
|
157
|
+
} else if (w0 === 'screen' && isSym(ts[ts.length - 1], ':')) {
|
|
158
|
+
// A screen: its name (for "Show <screen>" and "opens <screen>") and its inputs, in order.
|
|
159
|
+
const inputs = [];
|
|
160
|
+
for (const c of n.children) {
|
|
161
|
+
if (!isWord(c.tokens[0], 'receive')) break;
|
|
162
|
+
for (const p of paramGroups(c.tokens.slice(1))) inputs.push({ key: keyOf(p.words), text: p.words.map((x) => x.text).join(' '), defaultTokens: p.defaultTokens });
|
|
163
|
+
}
|
|
164
|
+
const words = stripArticle(ts.slice(1, -1));
|
|
165
|
+
names.screens.set(keyOf(words), { text: words.map((x) => x.text).join(' '), inputs });
|
|
166
|
+
} else if (w0 === 'remember') {
|
|
167
|
+
add('var', rememberName(ts.slice(1)));
|
|
168
|
+
} else if (w0 === 'show' && keyOf(ts.slice(1, 5)) === 'a list with each') {
|
|
169
|
+
const k = splitTop(ts, (t) => isWord(t, 'in'));
|
|
170
|
+
add('var', ts.slice(5, k < 0 ? ts.length : k));
|
|
147
171
|
}
|
|
148
172
|
collectNames(n.children, names);
|
|
149
173
|
}
|
|
150
174
|
}
|
|
151
175
|
|
|
176
|
+
// "coupon as text, starting at \"\"" / "count starting at 0": the name a Remember line declares.
|
|
177
|
+
function rememberName(ts) {
|
|
178
|
+
const end = ts.findIndex((t) => isWord(t, 'as') || isWord(t, 'starting') || isSym(t, ','));
|
|
179
|
+
return stripArticle(end < 0 ? ts : ts.slice(0, end));
|
|
180
|
+
}
|
|
181
|
+
|
|
152
182
|
// "total and member", "total as money, member as yes/no", "price and rate (7% if not given)"
|
|
153
183
|
function paramGroups(ts) {
|
|
154
184
|
const groups = [];
|
|
@@ -462,7 +492,9 @@ export class ExprParser {
|
|
|
462
492
|
fields.push({ name: keyOf(fr.slice(0, fk)), text: fr.slice(0, fk).map((x) => x.text).join(' '), e: this.expr(s, { noAnd: true }), line });
|
|
463
493
|
} while ((isSym(s.peek(), ',') || isWord(s.peek(), 'and')) && this.fieldAhead(s, 1) && s.next());
|
|
464
494
|
}
|
|
465
|
-
|
|
495
|
+
const node = { k: 'new', record: name, fields, line };
|
|
496
|
+
if (!fields.length && this.open) this.open.push(node); // a block of "field: value" lines may fill it
|
|
497
|
+
return node;
|
|
466
498
|
}
|
|
467
499
|
off = 0;
|
|
468
500
|
// a field taken from each item: "prices from orders"
|
|
@@ -478,7 +510,9 @@ export class ExprParser {
|
|
|
478
510
|
if (this.names.known.get(key) === 'func') {
|
|
479
511
|
if (isSym(s.peek(), '(')) return { k: 'call', name: key, text, args: this.parenArgs(s), line };
|
|
480
512
|
if (s.word('with')) return { k: 'call', name: key, text, args: this.withArgs(s), line };
|
|
481
|
-
|
|
513
|
+
const node = { k: 'call', name: key, text, args: [], line, bare: true };
|
|
514
|
+
if (this.open) this.open.push(node); // a block of "input: value" lines may fill it
|
|
515
|
+
return node;
|
|
482
516
|
}
|
|
483
517
|
return { k: 'name', name: key, text, line };
|
|
484
518
|
}
|
|
@@ -494,7 +528,7 @@ export class ExprParser {
|
|
|
494
528
|
export function parseCore(source, { seed = null } = {}) {
|
|
495
529
|
const { lines, diagnostics } = lex(source);
|
|
496
530
|
const tree = buildBlocks(lines, diagnostics);
|
|
497
|
-
const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []) };
|
|
531
|
+
const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []), recordFields: new Map(seed?.recordFields ?? []), funcInputs: new Map(seed?.funcInputs ?? []), recordText: new Map(), screens: new Map() };
|
|
498
532
|
collectNames(tree, names);
|
|
499
533
|
const ep = new ExprParser(names);
|
|
500
534
|
const body = parseBlock(tree, ep, names, diagnostics, { top: true });
|
|
@@ -505,6 +539,18 @@ function parseBlock(nodes, ep, names, diagnostics, ctx) {
|
|
|
505
539
|
const out = [];
|
|
506
540
|
for (const n of nodes) {
|
|
507
541
|
try {
|
|
542
|
+
const lines = fieldBlock(n, diagnostics);
|
|
543
|
+
if (lines) {
|
|
544
|
+
// A record or a call written as a block: "Set trade to a Trade:" / "Set profit to calculate profit:", with
|
|
545
|
+
// one "name: value" line each under it. The head is read as usual; its record (or call) gets the values.
|
|
546
|
+
ep.open = [];
|
|
547
|
+
let st, open;
|
|
548
|
+
try { st = parseStatement({ ...n, tokens: n.tokens.slice(0, -1), raw: n.raw.replace(/\s*:\s*(#.*)?$/, ''), children: [] }, ep, names, diagnostics, ctx, out); }
|
|
549
|
+
finally { open = ep.open; ep.open = null; }
|
|
550
|
+
fillBlock(open, lines, n, ep, names);
|
|
551
|
+
if (st) out.push(st);
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
508
554
|
const st = parseStatement(n, ep, names, diagnostics, ctx, out);
|
|
509
555
|
if (st) out.push(st);
|
|
510
556
|
} catch (e) {
|
|
@@ -514,6 +560,82 @@ function parseBlock(nodes, ep, names, diagnostics, ctx) {
|
|
|
514
560
|
return out;
|
|
515
561
|
}
|
|
516
562
|
|
|
563
|
+
// Statements whose ":" opens a block of statements (never a block of "name: value" lines).
|
|
564
|
+
const BLOCK_STATEMENTS = new Set(['when', 'if', 'otherwise', 'for', 'repeat', 'to', 'test', 'receive', 'never', 'use', 'screen']);
|
|
565
|
+
|
|
566
|
+
/** The "name: value" lines under a statement that is not itself a block statement, or null. */
|
|
567
|
+
function fieldBlock(n, diagnostics = []) {
|
|
568
|
+
const ts = n.tokens;
|
|
569
|
+
if (!n.children.length || !isSym(ts[ts.length - 1], ':')) return null;
|
|
570
|
+
const w0 = ts[0]?.t === 'word' ? ts[0].lower : '';
|
|
571
|
+
if (BLOCK_STATEMENTS.has(w0) || ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has'))) return null;
|
|
572
|
+
return n.children.map((c) => {
|
|
573
|
+
const colon = c.tokens.findIndex((t) => isSym(t, ':'));
|
|
574
|
+
const nameTs = colon > 0 ? c.tokens.slice(0, colon) : [];
|
|
575
|
+
if (colon <= 0 || !allWords(nameTs) || c.children.length) {
|
|
576
|
+
throw new CoreError(diag('TC113', c.line, `Each line under "${n.raw.trim()}" should be "name: value", like: quantity: 10.`, c.children.length ? 'A value under a block cannot open a block of its own.' : 'Put the name, then ":", then the value.'));
|
|
577
|
+
}
|
|
578
|
+
const valueTs = c.tokens.slice(colon + 1);
|
|
579
|
+
if (!valueTs.length) {
|
|
580
|
+
// (The block reader also said this line opens nothing; one message is enough.)
|
|
581
|
+
for (let i = diagnostics.length - 1; i >= 0; i--) if (diagnostics[i].code === 'TC103' && diagnostics[i].line === c.line) diagnostics.splice(i, 1);
|
|
582
|
+
throw new CoreError(diag('TC113', c.line, `"${nameTs.map((x) => x.text).join(' ')}:" has no value after it.`, `Write the value after the ":", like: ${nameTs.map((x) => x.text).join(' ')}: 10.`));
|
|
583
|
+
}
|
|
584
|
+
return { key: keyOf(nameTs), text: nameTs.map((x) => x.text).join(' '), valueTs, line: c.line };
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** Give the record (or the call) on the head line the values from its "name: value" lines. */
|
|
589
|
+
function fillBlock(open, lines, n, ep, names) {
|
|
590
|
+
const target = open[open.length - 1];
|
|
591
|
+
if (!target) {
|
|
592
|
+
throw new CoreError(diag('TC117', n.line, `"${n.raw.trim()}" ends with ":", but there is no record or function call at its end to give the lines under it to.`,
|
|
593
|
+
'Lines like "quantity: 10" give values to a record (Set trade to a Trade:) or to a function (Set profit to calculate profit:).'));
|
|
594
|
+
}
|
|
595
|
+
const seen = new Map();
|
|
596
|
+
for (const l of lines) {
|
|
597
|
+
if (seen.has(l.key)) throw new CoreError(diag('TC114', l.line, `"${l.text}" is given twice (also on line ${seen.get(l.key)}).`, 'Give each value once.'));
|
|
598
|
+
seen.set(l.key, l.line);
|
|
599
|
+
}
|
|
600
|
+
// Values are read as on one line, and keep the head's line, so the program is exactly the one-line form.
|
|
601
|
+
const value = (l) => ep.parse(l.valueTs, n.line);
|
|
602
|
+
if (target.k === 'new') {
|
|
603
|
+
const own = names.recordFields.get(target.record);
|
|
604
|
+
for (const l of lines) {
|
|
605
|
+
if (own && !own.includes(l.key)) {
|
|
606
|
+
const near = closest(l.key, own);
|
|
607
|
+
const rec = names.recordText.get(target.record) ?? target.record;
|
|
608
|
+
throw new CoreError(diag('TC206', l.line, `${/^[aeiouAEIOU]/.test(rec) ? 'An' : 'A'} ${rec} has no field "${l.text}".${near ? ` Did you mean "${near}"?` : ''}`, own.length ? `Its fields: ${own.join(', ')}.` : null));
|
|
609
|
+
}
|
|
610
|
+
target.fields.push({ name: l.key, text: l.text, e: value(l), line: n.line });
|
|
611
|
+
}
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
// A call written with names: the values go in the order of the function's inputs.
|
|
615
|
+
const inputs = names.funcInputs.get(target.name);
|
|
616
|
+
if (!inputs) throw new CoreError(diag('TC115', n.line, `I don't know the inputs of "${target.text}" here, so it can't be called with names.`, `Give the values in order: ${target.text} with … and …`));
|
|
617
|
+
const keys = inputs.map((p) => p.key);
|
|
618
|
+
for (const l of lines) {
|
|
619
|
+
if (!keys.includes(l.key)) {
|
|
620
|
+
const near = closest(l.key, keys);
|
|
621
|
+
throw new CoreError(diag('TC115', l.line, `"${target.text}" has no input called "${l.text}".${near ? ` Did you mean "${near}"?` : ''}`, keys.length ? `Its inputs: ${keys.join(', ')}.` : `"${target.text}" receives no inputs.`));
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
const last = Math.max(...lines.map((l) => keys.indexOf(l.key)));
|
|
625
|
+
const args = [];
|
|
626
|
+
for (let i = 0; i <= last; i++) {
|
|
627
|
+
const given = lines.find((l) => l.key === keys[i]);
|
|
628
|
+
if (given) args.push(value(given));
|
|
629
|
+
else if (inputs[i].defaultTokens) args.push(ep.parse(inputs[i].defaultTokens, n.line)); // left out: its default
|
|
630
|
+
else throw new CoreError(diag('TC116', n.line, `"${target.text}" needs "${inputs[i].text}", but it is not given.`, `Add a line: ${inputs[i].text}: …`));
|
|
631
|
+
}
|
|
632
|
+
for (let i = last + 1; i < inputs.length; i++) {
|
|
633
|
+
if (!inputs[i].defaultTokens) throw new CoreError(diag('TC116', n.line, `"${target.text}" needs "${inputs[i].text}", but it is not given.`, `Add a line: ${inputs[i].text}: …`));
|
|
634
|
+
}
|
|
635
|
+
target.args = args;
|
|
636
|
+
delete target.bare;
|
|
637
|
+
}
|
|
638
|
+
|
|
517
639
|
function nameWords(ts, line, what) {
|
|
518
640
|
const words = stripArticle(ts);
|
|
519
641
|
if (!words.length) throw new CoreError(diag('TC108', line, `${what} is missing a name.`));
|
|
@@ -619,7 +741,17 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
619
741
|
bodyNodes = kids.slice(r);
|
|
620
742
|
return { k: 'func', name, text, params, body: parseBlock(bodyNodes, ep, names, diagnostics, { inFunc: true }), line };
|
|
621
743
|
}
|
|
622
|
-
if (w0 === 'receive') fail('TC111', '"Receive" must be the first line inside a "To" block.');
|
|
744
|
+
if (w0 === 'receive') fail('TC111', '"Receive" must be the first line inside a "To" block or a "Screen".');
|
|
745
|
+
if (w0 === 'screen' && isSym(ts[ts.length - 1], ':')) {
|
|
746
|
+
if (!ctx.top) fail('TC402', 'A "Screen" must be written at the left edge, not inside another block.');
|
|
747
|
+
return parseScreen(n, ep, names, diagnostics);
|
|
748
|
+
}
|
|
749
|
+
if (w0 === 'open' && ctx.inPress) {
|
|
750
|
+
const { name, text } = nameWords(rest, line, '"Open"');
|
|
751
|
+
return { k: 'open', name, text, line };
|
|
752
|
+
}
|
|
753
|
+
if (w0 === 'remember') fail('TC119', '"Remember" goes at the top of a "Screen", after its "Receive" lines.', 'A function keeps nothing between calls; a screen remembers values while it is shown.');
|
|
754
|
+
if (w0 === 'show') fail('TC118', '"Show" is used inside a "Screen" (a screen shows things). In a program, write: Say …');
|
|
623
755
|
if ((w0 === 'a' || w0 === 'an') && isWord(ts[ts.length - 2], 'has') && isSym(ts[ts.length - 1], ':')) {
|
|
624
756
|
if (!ctx.top) fail('TC402', 'A record ("A … has:") must be written at the left edge, not inside another block.');
|
|
625
757
|
const { name, text } = nameWords(ts.slice(1, -2), line, 'A record');
|
|
@@ -739,4 +871,198 @@ function parseNever(ts, line, ep) {
|
|
|
739
871
|
return { k: 'never', text, cond: ep.parse(r, line), line };
|
|
740
872
|
}
|
|
741
873
|
|
|
874
|
+
// ---------------------------------------------------------------- screens
|
|
875
|
+
|
|
876
|
+
// Screen Cart:
|
|
877
|
+
// Receive items as a list of Item, title as text ("Your cart" if not given)
|
|
878
|
+
// Remember coupon as text, starting at ""
|
|
879
|
+
// Show a heading: title
|
|
880
|
+
// When items is empty:
|
|
881
|
+
// Show "Your cart is empty"
|
|
882
|
+
// Otherwise:
|
|
883
|
+
// Show a list with each item in items:
|
|
884
|
+
// Show "{item's name}: {item's price}"
|
|
885
|
+
// Show a text box "Coupon code" for coupon
|
|
886
|
+
// Show a button "Checkout" (off when items is empty):
|
|
887
|
+
// When pressed:
|
|
888
|
+
// …steps…
|
|
889
|
+
// Show a button "Back" that opens Home
|
|
890
|
+
//
|
|
891
|
+
// A screen is a description of what is shown, not a list of steps: its lines are elements. Only the steps under
|
|
892
|
+
// "When pressed:" run, one press at a time.
|
|
893
|
+
export const SCREEN_ELEMENTS = ['a heading', 'text', 'a list with each … in …', 'a row', 'a text box', 'a number box', 'a button', 'another screen'];
|
|
894
|
+
|
|
895
|
+
function parseScreen(n, ep, names, diagnostics) {
|
|
896
|
+
const line = n.line;
|
|
897
|
+
const { name, text } = nameWords(n.tokens.slice(1, -1), line, 'A screen');
|
|
898
|
+
const params = [], remember = [];
|
|
899
|
+
let k = 0;
|
|
900
|
+
const kids = n.children;
|
|
901
|
+
while (kids[k] && isWord(kids[k].tokens[0], 'receive')) {
|
|
902
|
+
const kid = kids[k];
|
|
903
|
+
try {
|
|
904
|
+
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords(p.words, kid.line, '"Receive"'), type: p.typeTokens ? typeOf(ep, p.typeTokens, kid.line) : null, dflt: p.defaultTokens ? ep.parse(p.defaultTokens, kid.line) : null, line: kid.line })));
|
|
905
|
+
} catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
|
|
906
|
+
k++;
|
|
907
|
+
}
|
|
908
|
+
while (kids[k] && isWord(kids[k].tokens[0], 'remember')) {
|
|
909
|
+
try { remember.push(parseRemember(kids[k], ep)); } catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
|
|
910
|
+
k++;
|
|
911
|
+
}
|
|
912
|
+
const body = parseElements(kids.slice(k), ep, names, diagnostics, name);
|
|
913
|
+
return { k: 'screen', name, text, params, remember, body, line };
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// Remember coupon as text, starting at "" | Remember count starting at 0
|
|
917
|
+
function parseRemember(c, ep) {
|
|
918
|
+
const ts = c.tokens.slice(1);
|
|
919
|
+
const line = c.line;
|
|
920
|
+
const at = splitTop(ts, (t, i) => isWord(t, 'starting') && isWord(ts[i + 1], 'at'));
|
|
921
|
+
if (at < 0) throw new CoreError(diag('TC108', line, '"Remember" needs a starting value: Remember count starting at 0.', 'A screen shows its remembered values right away, so each one starts somewhere.'));
|
|
922
|
+
let head = ts.slice(0, at);
|
|
923
|
+
if (isSym(head[head.length - 1], ',')) head = head.slice(0, -1);
|
|
924
|
+
const asAt = head.findIndex((t) => isWord(t, 'as'));
|
|
925
|
+
const nm = nameWords(asAt < 0 ? head : head.slice(0, asAt), line, '"Remember"');
|
|
926
|
+
const type = asAt < 0 ? null : typeOf(ep, head.slice(asAt + 1), line);
|
|
927
|
+
const valueTs = ts.slice(at + 2);
|
|
928
|
+
if (!valueTs.length) throw new CoreError(diag('TC108', line, `"Remember ${nm.text}" has no starting value after "starting at".`));
|
|
929
|
+
return { ...nm, type, e: ep.parse(valueTs, line), line };
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function parseElements(nodes, ep, names, diagnostics, screen) {
|
|
933
|
+
const out = [];
|
|
934
|
+
for (const c of nodes) {
|
|
935
|
+
try {
|
|
936
|
+
const el = parseElement(c, ep, names, diagnostics, screen, out);
|
|
937
|
+
if (el) out.push(el);
|
|
938
|
+
} catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
|
|
939
|
+
}
|
|
940
|
+
return out;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
function parseElement(c, ep, names, diagnostics, screen, siblings) {
|
|
944
|
+
const ts = c.tokens;
|
|
945
|
+
const line = c.line;
|
|
946
|
+
const fail = (code, msg, hint) => { throw new CoreError(diag(code, line, msg, hint)); };
|
|
947
|
+
const w0 = ts[0]?.t === 'word' ? ts[0].lower : '';
|
|
948
|
+
const opens = isSym(ts[ts.length - 1], ':');
|
|
949
|
+
const noBlock = (what) => { if (c.children.length) fail('TC118', `${what} has nothing inside it, so the lines under it don't belong to it.`, 'Remove the ":" and the indented lines, or move them out.'); };
|
|
950
|
+
if (w0 === 'when' || w0 === 'if') {
|
|
951
|
+
if (!opens) fail('TC108', 'This line should end with ":".');
|
|
952
|
+
return { k: 'when', branches: [{ cond: ep.parse(ts.slice(1, -1), line), body: parseElements(c.children, ep, names, diagnostics, screen), line }], otherwise: null, line };
|
|
953
|
+
}
|
|
954
|
+
if (w0 === 'otherwise') {
|
|
955
|
+
const prev = siblings[siblings.length - 1];
|
|
956
|
+
if (!prev || prev.k !== 'when' || prev.otherwise) fail('TC109', '"Otherwise" must come right after a "When" or "If" block (at the same indentation).');
|
|
957
|
+
if (!opens) fail('TC108', 'This line should end with ":".');
|
|
958
|
+
const h = ts.slice(0, -1);
|
|
959
|
+
if (h.length === 1) { prev.otherwise = parseElements(c.children, ep, names, diagnostics, screen); return null; }
|
|
960
|
+
if (!isWord(h[1], 'when') && !isWord(h[1], 'if')) fail('TC108', 'Write "Otherwise:" or "Otherwise when <condition>:".');
|
|
961
|
+
prev.branches.push({ cond: ep.parse(h.slice(2), line), body: parseElements(c.children, ep, names, diagnostics, screen), line });
|
|
962
|
+
return null;
|
|
963
|
+
}
|
|
964
|
+
if (w0 === 'receive' || w0 === 'remember') fail('TC119', `"${ts[0].text}" goes at the top of a screen: first the Receive lines, then the Remember lines, then what it shows.`);
|
|
965
|
+
if (w0 !== 'show') {
|
|
966
|
+
// (Swapped letters count too: "Shwo" is "Show".)
|
|
967
|
+
const same = (a, b) => [...a].sort().join('') === [...b].sort().join('');
|
|
968
|
+
const near = closest(w0, ['show', 'when', 'otherwise']) ?? ['show', 'when', 'otherwise'].find((w) => same(w, w0)) ?? null;
|
|
969
|
+
fail('TC118', `A screen shows things, so each line in it starts with "Show" (or is a "When … :" choice). "${c.raw.trim()}" isn't something a screen can show.`,
|
|
970
|
+
near && near !== w0 ? `Did you mean "${near[0].toUpperCase()}${near.slice(1)}"?` : 'Steps that change something go under a button: Show a button "Save": then When pressed: and the steps.');
|
|
971
|
+
}
|
|
972
|
+
const r = opens ? ts.slice(1, -1) : ts.slice(1);
|
|
973
|
+
const key = (i, j) => keyOf(r.slice(i, j));
|
|
974
|
+
const label = (at, what) => {
|
|
975
|
+
if (r[at]?.t !== 'str') fail('TC108', `${what} needs its words in quotes, like: Show ${what.toLowerCase()} "Save".`);
|
|
976
|
+
return ep.parse([r[at]], line);
|
|
977
|
+
};
|
|
978
|
+
// Show a heading: <text> | Show a heading "Welcome"
|
|
979
|
+
if (key(0, 2) === 'a heading') {
|
|
980
|
+
noBlock('A heading');
|
|
981
|
+
let v = r.slice(2);
|
|
982
|
+
if (isSym(v[0], ':')) v = v.slice(1);
|
|
983
|
+
if (!v.length) fail('TC108', 'A heading needs its words: Show a heading "Welcome", or Show a heading: title.');
|
|
984
|
+
return { k: 'heading', e: ep.parse(v, line), line };
|
|
985
|
+
}
|
|
986
|
+
// Show a list with each item in items: (the lines under it are shown once for each item)
|
|
987
|
+
if (key(0, 4) === 'a list with each') {
|
|
988
|
+
const inAt = splitTop(r, (t) => isWord(t, 'in'));
|
|
989
|
+
if (inAt < 0) fail('TC108', 'Write "Show a list with each item in items:".');
|
|
990
|
+
if (!opens || !c.children.length) fail('TC103', `"${c.raw.trim()}" needs the lines to show for each item, indented under it.`, `For example:\n Show "{${r.slice(4, inAt).map((x) => x.text).join(' ') || 'item'}}"`);
|
|
991
|
+
const v = nameWords(r.slice(4, inAt), line, 'The list');
|
|
992
|
+
return { k: 'list', v, iter: ep.parse(r.slice(inAt + 1), line), body: parseElements(c.children, ep, names, diagnostics, screen), line };
|
|
993
|
+
}
|
|
994
|
+
if (key(0, 2) === 'a list') fail('TC108', 'A list names each item: Show a list with each item in items:', 'Then indent what to show for each item under it.');
|
|
995
|
+
// Show a row: (the lines under it, side by side)
|
|
996
|
+
if (key(0, 2) === 'a row') {
|
|
997
|
+
if (r.length > 2) fail('TC112', 'Write "Show a row:" and put what it holds on the lines under it.');
|
|
998
|
+
if (!opens || !c.children.length) fail('TC103', '"Show a row:" needs the things to put side by side, indented under it.');
|
|
999
|
+
return { k: 'row', body: parseElements(c.children, ep, names, diagnostics, screen), line };
|
|
1000
|
+
}
|
|
1001
|
+
// Show a text box "Coupon code" for coupon | Show a number box "Quantity" for quantity
|
|
1002
|
+
if (key(0, 3) === 'a text box' || key(0, 3) === 'a number box') {
|
|
1003
|
+
noBlock('A box');
|
|
1004
|
+
const kind = r[1].lower === 'text' ? 'textbox' : 'numberbox';
|
|
1005
|
+
const what = kind === 'textbox' ? 'A text box' : 'A number box';
|
|
1006
|
+
const lab = label(3, what);
|
|
1007
|
+
if (!isWord(r[4], 'for')) fail('TC108', `${what} says which remembered value it changes: Show ${what.toLowerCase()} "${lab.parts?.join('') ?? '…'}" for <name>.`);
|
|
1008
|
+
const target = nameWords(r.slice(5), line, what);
|
|
1009
|
+
return { k: kind, label: lab, target: { k: 'name', ...target, line }, line };
|
|
1010
|
+
}
|
|
1011
|
+
// Show a button "Checkout" (off when items is empty) that opens Home:
|
|
1012
|
+
// When pressed:
|
|
1013
|
+
// …steps…
|
|
1014
|
+
if (key(0, 2) === 'a button') {
|
|
1015
|
+
const lab = label(2, 'A button');
|
|
1016
|
+
let i = 3, off = null, opensScreen = null;
|
|
1017
|
+
if (isSym(r[i], '(')) {
|
|
1018
|
+
let d = 0, close = -1;
|
|
1019
|
+
for (let j = i; j < r.length; j++) { if (isSym(r[j], '(')) d++; if (isSym(r[j], ')')) { d--; if (d === 0) { close = j; break; } } }
|
|
1020
|
+
const inner = r.slice(i + 1, close < 0 ? r.length : close);
|
|
1021
|
+
if (!(isWord(inner[0], 'off') && isWord(inner[1], 'when')) || inner.length < 3) fail('TC108', 'In parentheses after a button, say when it is off: (off when items is empty).');
|
|
1022
|
+
off = ep.parse(inner.slice(2), line);
|
|
1023
|
+
i = close + 1;
|
|
1024
|
+
}
|
|
1025
|
+
if (isWord(r[i], 'that') && isWord(r[i + 1], 'opens')) {
|
|
1026
|
+
opensScreen = { ...nameWords(r.slice(i + 2), line, '"opens"'), line };
|
|
1027
|
+
i = r.length;
|
|
1028
|
+
}
|
|
1029
|
+
if (i < r.length) fail('TC112', `I understood the button up to "${show(r[i])}", but not after it.`, 'A button is: Show a button "Label", then (off when …) or that opens <screen>, if needed.');
|
|
1030
|
+
let press = null;
|
|
1031
|
+
if (opens) {
|
|
1032
|
+
for (const k2 of c.children) {
|
|
1033
|
+
if (keyOf(k2.tokens.slice(0, 2)) !== 'when pressed' || !isSym(k2.tokens[k2.tokens.length - 1], ':') || k2.tokens.length !== 3) {
|
|
1034
|
+
throw new CoreError(diag('TC118', k2.line, `Under a button goes one "When pressed:" with the steps to run, but this line is "${k2.raw.trim()}".`, 'Write:\n When pressed:\n <the steps>'));
|
|
1035
|
+
}
|
|
1036
|
+
if (press) throw new CoreError(diag('TC118', k2.line, 'This button already has a "When pressed:" block. Put all its steps in one.'));
|
|
1037
|
+
press = { body: parseBlock(k2.children, ep, names, diagnostics, { inFunc: true, inPress: true }), line: k2.line };
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
if (!press && !opensScreen) fail('TC118', `The button ${c.raw.trim().replace(/^Show a button\s*/i, '').replace(/:$/, '')} does nothing when it is pressed.`, 'Add "that opens <screen>", or end the line with ":" and put "When pressed:" and its steps under it.');
|
|
1041
|
+
return { k: 'button', label: lab, off, opens: opensScreen, press, line };
|
|
1042
|
+
}
|
|
1043
|
+
// Show Summary | Show Summary: (with one "input: value" line each)
|
|
1044
|
+
const scrWords = stripArticle(r);
|
|
1045
|
+
if (allWords(scrWords) && names.screens.has(keyOf(scrWords))) {
|
|
1046
|
+
const target = { name: keyOf(scrWords), text: names.screens.get(keyOf(scrWords)).text };
|
|
1047
|
+
const given = [];
|
|
1048
|
+
if (opens) {
|
|
1049
|
+
for (const k2 of c.children) {
|
|
1050
|
+
const colon = k2.tokens.findIndex((t) => isSym(t, ':'));
|
|
1051
|
+
const nameTs = colon > 0 ? k2.tokens.slice(0, colon) : [];
|
|
1052
|
+
if (colon <= 0 || !allWords(nameTs) || k2.children.length || colon === k2.tokens.length - 1) {
|
|
1053
|
+
throw new CoreError(diag('TC113', k2.line, `Each line under "${c.raw.trim()}" gives the screen one input, as "name: value", like: total: 10.`));
|
|
1054
|
+
}
|
|
1055
|
+
given.push({ name: keyOf(nameTs), text: nameTs.map((x) => x.text).join(' '), e: ep.parse(k2.tokens.slice(colon + 1), k2.line), line: k2.line });
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
return { k: 'child', screen: target, given, line };
|
|
1059
|
+
}
|
|
1060
|
+
if (opens || c.children.length) {
|
|
1061
|
+
const near = closest(keyOf(scrWords), [...names.screens.keys()]);
|
|
1062
|
+
fail('TC118', `"${c.raw.trim()}" ends with ":", but ${allWords(scrWords) ? `there is no screen called "${scrWords.map((x) => x.text).join(' ')}"` : 'only a list, a row, a button, or another screen holds lines under it'}.`, near ? `Did you mean "${names.screens.get(near).text}"?` : null);
|
|
1063
|
+
}
|
|
1064
|
+
// Show <text or a value>
|
|
1065
|
+
return { k: 'text', e: ep.parse(r, line), line };
|
|
1066
|
+
}
|
|
1067
|
+
|
|
742
1068
|
export { closest };
|
package/src/core/project.mjs
CHANGED
|
@@ -8,6 +8,19 @@ import { join, dirname, relative, resolve, basename } from 'node:path';
|
|
|
8
8
|
import { spawnSync } from 'node:child_process';
|
|
9
9
|
import { compileCore } from './index.mjs';
|
|
10
10
|
import { PYTHON_RUNTIME } from './runtime-python.mjs';
|
|
11
|
+
import { writeTypeScript, typescriptDiagnostics } from './typescript-run.mjs';
|
|
12
|
+
import { writeCSharp, csharpDiagnostics } from './csharp-run.mjs';
|
|
13
|
+
import { writeRust, rustDiagnostics } from './rust-run.mjs';
|
|
14
|
+
import { writeGo, goDiagnostics } from './go-run.mjs';
|
|
15
|
+
import { writeJava, javaDiagnostics } from './java-run.mjs';
|
|
16
|
+
import { writeReact, reactDiagnostics } from './react-run.mjs';
|
|
17
|
+
import { hasScreens } from './target-react.mjs';
|
|
18
|
+
import { diag } from './diagnostics.mjs';
|
|
19
|
+
|
|
20
|
+
/** The languages a Thunder Core project can be compiled to. */
|
|
21
|
+
export const TARGETS = ['python', 'typescript', 'csharp', 'rust', 'go', 'java', 'react'];
|
|
22
|
+
/** How a target is named to people. */
|
|
23
|
+
export const TARGET_NAMES = { python: 'Python', typescript: 'TypeScript', csharp: 'C#', rust: 'Rust', go: 'Go', java: 'Java', react: 'React' };
|
|
11
24
|
|
|
12
25
|
export const PROJECT_FILE = 'thunder.toml';
|
|
13
26
|
|
|
@@ -44,7 +57,7 @@ export function loadProject(root) {
|
|
|
44
57
|
const toml = parseToml(readFileSync(join(root, PROJECT_FILE), 'utf8'));
|
|
45
58
|
const build = toml.build ?? {};
|
|
46
59
|
const target = String(build.target ?? 'python');
|
|
47
|
-
if (target
|
|
60
|
+
if (!TARGETS.includes(target)) throw new Error(`thunder.toml: target "${target}" is not supported yet. Thunder Core builds ${TARGETS.map((t) => `${TARGET_NAMES[t] ?? t} (target = "${t}")`).join(', ')}.`);
|
|
48
61
|
return {
|
|
49
62
|
root,
|
|
50
63
|
name: toml.project?.name ?? basename(root),
|
|
@@ -52,7 +65,7 @@ export function loadProject(root) {
|
|
|
52
65
|
target,
|
|
53
66
|
src: build.source ?? 'src',
|
|
54
67
|
tests: build.tests ?? 'tests',
|
|
55
|
-
out: build.output ??
|
|
68
|
+
out: build.output ?? `generated/${target}`,
|
|
56
69
|
entry: build.entry ?? null,
|
|
57
70
|
};
|
|
58
71
|
}
|
|
@@ -72,13 +85,16 @@ export function moduleNameFor(file) {
|
|
|
72
85
|
* Compile a project (or a single file when `single` is given). Writes generated/python/<module>.py for every
|
|
73
86
|
* file plus thunder_runtime.py. Returns { ok, results: [{ file, module, ok, diagnostics }], outDir, entryModule }.
|
|
74
87
|
*/
|
|
75
|
-
export function buildProject({ root, single = null, includeTests = false, write = true, config = null }) {
|
|
88
|
+
export function buildProject({ root, single = null, includeTests = false, write = true, config = null, target = null, refuseScreens = false }) {
|
|
76
89
|
const cfg = config ?? (single && !findProjectRoot(single) ? null : loadProject(root));
|
|
77
90
|
const base = cfg ? cfg.root : dirname(resolve(single));
|
|
91
|
+
// --target overrides thunder.toml; a different target than the project's builds into generated/<target>.
|
|
92
|
+
const tgt = target ?? cfg?.target ?? 'python';
|
|
93
|
+
if (!TARGETS.includes(tgt)) throw new Error(`there is no target "${tgt}". Thunder Core builds ${TARGETS.join(', ')} (python is the default).`);
|
|
78
94
|
const srcFiles = cfg ? thunderFiles(join(cfg.root, cfg.src)) : [];
|
|
79
95
|
if (single && !srcFiles.includes(resolve(single))) srcFiles.unshift(resolve(single));
|
|
80
96
|
const testFiles = includeTests && cfg ? thunderFiles(join(cfg.root, cfg.tests)) : [];
|
|
81
|
-
const outDir = join(base, cfg ? cfg.out :
|
|
97
|
+
const outDir = join(base, cfg && (target == null || target === cfg.target) ? cfg.out : `generated/${tgt}`);
|
|
82
98
|
const results = [];
|
|
83
99
|
const used = new Set();
|
|
84
100
|
const uniqueModule = (f, prefix = '') => { let n = prefix + moduleNameFor(f); let k = 2; while (used.has(n)) n = `${prefix}${moduleNameFor(f)}_${k++}`; used.add(n); return n; };
|
|
@@ -93,8 +109,26 @@ export function buildProject({ root, single = null, includeTests = false, write
|
|
|
93
109
|
const r = compileCore(readFileSync(f, 'utf8'), { file: rel, imported: srcOk, srcModules: srcOk.map((x) => x.module) });
|
|
94
110
|
results.push({ ...r, path: f, rel, module: uniqueModule(f, 'tests_'), kind: 'test' });
|
|
95
111
|
}
|
|
112
|
+
// A Python module (Use) cannot be compiled to TypeScript: refuse it before anything is written (TC405).
|
|
113
|
+
if (tgt === 'typescript') for (const r of results.filter((x) => x.ok)) { const d = typescriptDiagnostics(r); if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
114
|
+
if (tgt === 'csharp') for (const r of results.filter((x) => x.ok)) { const d = csharpDiagnostics(r); if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
115
|
+
if (tgt === 'rust') for (const r of results.filter((x) => x.ok)) { const d = rustDiagnostics(r); if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
116
|
+
if (tgt === 'go') for (const r of results.filter((x) => x.ok)) { const d = goDiagnostics(r); if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
117
|
+
// The same for Java: Python modules exist only for the Python target.
|
|
118
|
+
if (tgt === 'java') for (const r of results.filter((x) => x.ok)) { const d = javaDiagnostics(r); if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
119
|
+
const entryPath = single ? resolve(single) : cfg?.entry ? join(cfg.root, cfg.entry) : join(base, cfg?.src ?? '.', 'main.thunder');
|
|
120
|
+
const entry = results.find((r) => r.path === entryPath) ?? results.find((r) => r.kind === 'src');
|
|
121
|
+
// Screens are built for React; building one for another target would leave them out, so it is refused (TC406).
|
|
122
|
+
if (tgt === 'react') for (const r of results.filter((x) => x.ok && x.kind !== 'test')) { const d = reactDiagnostics(r, { entry: r === entry }); if (d.length) { r.diagnostics = [...r.diagnostics, ...d]; r.ok = false; } }
|
|
123
|
+
else if (refuseScreens) for (const r of results.filter((x) => x.ok && hasScreens(x.info))) {
|
|
124
|
+
r.diagnostics = [...r.diagnostics, diag('TC406', r.info.screens[0].line, `"${r.info.screens[0].text}" is a screen, and screens are built as a React app, not for ${TARGET_NAMES[tgt]}.`, 'Build it with: thunder build --target react. thunder run shows the screen as an outline.')];
|
|
125
|
+
r.ok = false;
|
|
126
|
+
}
|
|
96
127
|
const ok = results.every((r) => r.ok);
|
|
97
|
-
if (ok && write)
|
|
128
|
+
if (ok && write && tgt === 'typescript') writeTypeScript(results, outDir);
|
|
129
|
+
if (ok && write && tgt === 'react') writeReact(results, outDir, { entry });
|
|
130
|
+
if (ok && write && tgt === 'java') writeJava(results, outDir);
|
|
131
|
+
if (ok && write && tgt === 'python') {
|
|
98
132
|
mkdirSync(outDir, { recursive: true });
|
|
99
133
|
writeFileSync(join(outDir, 'thunder_runtime.py'), PYTHON_RUNTIME);
|
|
100
134
|
for (const r of results) writeFileSync(join(outDir, `${r.module}.py`), r.python);
|
|
@@ -107,9 +141,10 @@ export function buildProject({ root, single = null, includeTests = false, write
|
|
|
107
141
|
'',
|
|
108
142
|
].join('\n'));
|
|
109
143
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
144
|
+
if (ok && write && tgt === 'csharp') writeCSharp(results, outDir, { entry });
|
|
145
|
+
if (ok && write && tgt === 'rust') writeRust(results, outDir, { entryModule: entry?.module ?? null });
|
|
146
|
+
if (ok && write && tgt === 'go') writeGo(results, outDir, { entry: entry?.module ?? null });
|
|
147
|
+
return { ok, results, outDir, base, entryModule: entry?.module ?? null, entry, config: cfg, target: tgt };
|
|
113
148
|
}
|
|
114
149
|
|
|
115
150
|
/** The local Python 3.10+: $THUNDER_PYTHON, then python3, then python. Returns { cmd, version } or { error }. */
|