@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.
Files changed (61) hide show
  1. package/CHANGELOG.md +212 -0
  2. package/README.md +4 -1
  3. package/dist/core.cjs +2080 -278
  4. package/dist/index.cjs +12742 -10943
  5. package/dist/learn.cjs +12976 -3598
  6. package/package.json +2 -2
  7. package/src/cli-home.mjs +242 -0
  8. package/src/cli.mjs +135 -41
  9. package/src/core/ThunderRuntime.cs +1367 -0
  10. package/src/core/check.mjs +158 -2
  11. package/src/core/cli.mjs +208 -17
  12. package/src/core/csharp-run.mjs +184 -0
  13. package/src/core/diagnostics.mjs +13 -0
  14. package/src/core/engine-core.mjs +855 -0
  15. package/src/core/engine-values.mjs +1054 -0
  16. package/src/core/engine-worker.mjs +15 -0
  17. package/src/core/engine.mjs +63 -0
  18. package/src/core/format.mjs +191 -3
  19. package/src/core/go-run.mjs +106 -0
  20. package/src/core/index.mjs +3 -1
  21. package/src/core/java/thunder/T.java +6 -0
  22. package/src/core/java/thunder/ThunderRuntime.java +1374 -0
  23. package/src/core/java-run.mjs +89 -0
  24. package/src/core/parser.mjs +331 -5
  25. package/src/core/project.mjs +43 -8
  26. package/src/core/react-run.mjs +96 -0
  27. package/src/core/runtime-go/thunder_runtime.go +3038 -0
  28. package/src/core/runtime-react.mjs +133 -0
  29. package/src/core/runtime-typescript.mjs +119 -0
  30. package/src/core/rust/thunder_runtime.rs +1645 -0
  31. package/src/core/rust-run.mjs +192 -0
  32. package/src/core/screen-values.mjs +30 -0
  33. package/src/core/target-csharp.mjs +484 -0
  34. package/src/core/target-go.mjs +555 -0
  35. package/src/core/target-java.mjs +587 -0
  36. package/src/core/target-python.mjs +2 -1
  37. package/src/core/target-react.mjs +270 -0
  38. package/src/core/target-rust.mjs +534 -0
  39. package/src/core/target-typescript.mjs +466 -0
  40. package/src/core/typescript-run.mjs +114 -0
  41. package/src/core.d.ts +18 -0
  42. package/src/core.mjs +1 -0
  43. package/src/emit.mjs +1 -1
  44. package/src/faithful.mjs +30 -0
  45. package/src/learn-lessons.mjs +245 -1
  46. package/src/learn.d.mts +8 -0
  47. package/src/learn.mjs +40 -4
  48. package/src/libraries.mjs +10 -3
  49. package/src/model.mjs +50 -8
  50. package/src/read-level.mjs +192 -0
  51. package/src/read-repo-fs.mjs +3 -1
  52. package/src/read.mjs +28 -5
  53. package/src/replay-cli.mjs +123 -0
  54. package/src/say-less.mjs +152 -11
  55. package/src/screens.mjs +833 -0
  56. package/src/steps.mjs +430 -19
  57. package/src/term.mjs +132 -0
  58. package/src/try-cli.mjs +225 -0
  59. package/src/why-cli.mjs +17 -7
  60. package/src/why.d.mts +17 -7
  61. package/src/why.mjs +114 -33
@@ -0,0 +1,15 @@
1
+ // Runs the Thunder engine on its own thread, with a stack deep enough for the recursion Python allows (about 1000
2
+ // calls). engine.mjs starts it and waits for the answer (see runSync there).
3
+ import { workerData } from 'node:worker_threads';
4
+ import { runInProcess, testInProcess } from './engine.mjs';
5
+
6
+ const { shared, port, job } = workerData;
7
+ let result;
8
+ try {
9
+ result = job.tests ? testInProcess(job) : runInProcess(job);
10
+ } catch (e) {
11
+ result = { status: 70, stdout: '', stderr: `The Thunder engine failed: ${e?.stack ?? e}\n` };
12
+ }
13
+ port.postMessage(result);
14
+ Atomics.store(shared, 0, 1);
15
+ Atomics.notify(shared, 0);
@@ -0,0 +1,63 @@
1
+ // The Thunder engine: runs Thunder Core directly, with no Python (thunder run --engine thunder).
2
+ //
3
+ // It runs the SAME checked program the Python target compiles (compileCore -> program + info), so there is one
4
+ // meaning of Thunder, not two. The language itself lives in engine-core.mjs (no Node APIs, so it also runs in a
5
+ // browser); this file adds what a command line needs: reading files from disk, and a worker thread with a deep stack
6
+ // for programs that nest calls deeper than the calling thread allows. compiler/test/core-engine.test.mjs runs every
7
+ // Core test program on both engines and compares the output, errors included. A difference is a bug in one of them.
8
+ //
9
+ // A program that uses a Python module ("Use csv as csv") is not run here: Thunder never imitates a library.
10
+
11
+ import { readFileSync } from 'node:fs';
12
+ import { Worker, MessageChannel, receiveMessageOnPort } from 'node:worker_threads';
13
+ import { resolve as resolvePath } from 'node:path';
14
+ import { ENGINES, pythonModulesUsed, refusalText, runInProcess as runCore, testInProcess as testCore, ThunderErr, PyErr } from './engine-core.mjs';
15
+
16
+ export { ENGINES, pythonModulesUsed, refusalText, ThunderErr, PyErr };
17
+
18
+ /** Files a program reads come from disk, relative to the folder it runs in. */
19
+ const readText = (path, cwd) => readFileSync(resolvePath(cwd, path), 'utf8');
20
+
21
+ /**
22
+ * Run a program with the Thunder engine. `entry` is a compileCore result. Returns { status, stdout, stderr }, the way
23
+ * `python main.py` would end: status 0, or 1 after an error reported in Thunder words. On this thread first (fast, no
24
+ * worker); only a program that nests calls deeper than this thread's stack allows is run again on a worker with a
25
+ * deep stack. Running again is safe: the engine only collects output and reads.
26
+ */
27
+ export function runWithEngine({ entry, cwd = process.cwd() } = {}) {
28
+ const uses = pythonModulesUsed([entry]);
29
+ if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
30
+ const r = runCore({ entry, cwd, deeper: true, readText });
31
+ return r.needsDeeperStack ? runSync({ entry, cwd }) : r;
32
+ }
33
+
34
+ /** The same, on the calling thread only. */
35
+ export function runInProcess({ entry, cwd = process.cwd(), deeper = false } = {}) { return runCore({ entry, cwd, deeper, readText }); }
36
+
37
+ /** Run every Test block, the way run_tests.py does: one line per test, then the totals. */
38
+ export function testWithEngine({ results, cwd = process.cwd() } = {}) {
39
+ const uses = pythonModulesUsed(results);
40
+ if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
41
+ const r = testCore({ results, cwd, deeper: true, readText });
42
+ return r.needsDeeperStack ? runSync({ results, cwd, tests: true }) : r;
43
+ }
44
+
45
+ /** The same, on the calling thread only. */
46
+ export function testInProcess({ results, cwd = process.cwd(), deeper = false } = {}) { return testCore({ results, cwd, deeper, readText }); }
47
+
48
+ function runSync(job) {
49
+ const shared = new Int32Array(new SharedArrayBuffer(4));
50
+ const { port1, port2 } = new MessageChannel();
51
+ const worker = new Worker(new URL('./engine-worker.mjs', import.meta.url), {
52
+ workerData: { shared, port: port2, job }, transferList: [port2], resourceLimits: { stackSizeMb: 256 }, stdout: false, stderr: false,
53
+ });
54
+ try {
55
+ while (Atomics.wait(shared, 0, 0, 1000) === 'timed-out') { if (!worker.threadId) break; }
56
+ const msg = receiveMessageOnPort(port1);
57
+ return msg ? msg.message : { status: 70, stdout: '', stderr: 'The Thunder engine stopped without an answer.\n' };
58
+ } finally {
59
+ worker.terminate();
60
+ port1.close();
61
+ }
62
+ }
63
+
@@ -1,7 +1,33 @@
1
- // thunder format for Thunder Core: two spaces per block level, no trailing spaces, at most one blank line in a
2
- // row, and a newline at the end. It changes only layout, never words, so it cannot change what a program means.
1
+ // thunder format: the one way Thunder Core is written (the "Thunder style", docs/core.md).
2
+ //
3
+ // 1. Layout: two spaces per block level, no trailing spaces, at most one blank line in a row, a newline at the end.
4
+ // 2. Structure, read from the program itself (its records, their fields, its functions):
5
+ // - short stays short: a record built on one line keeps that line while it has 1 to 3 fields and fits in 100
6
+ // columns; with 4 or more fields, or past 100 columns, it becomes a block of "field: value" lines;
7
+ // - a long condition (When, If, Otherwise when, Repeat while/until) wraps before "and" / "or".
8
+ // 3. Spacing: one blank line around each function (To), record (A … has), and Test block.
9
+ //
10
+ // It never changes what a program means: a block record is the same program as the one-line form, and a wrapped
11
+ // condition is joined back into the same line when it is read. Comments stay where they are. Formatting twice gives
12
+ // the same text as formatting once. Lines that are already in the Thunder style are left exactly as they are.
3
13
 
4
- export function formatCore(source) {
14
+ import { tokenizeLine } from './lexer.mjs';
15
+ import { parseCore, RESERVED } from './parser.mjs';
16
+
17
+ export const FORMAT_WIDTH = 100;
18
+ const MAX_INLINE_FIELDS = 3;
19
+
20
+ export function formatCore(source, { width = FORMAT_WIDTH } = {}) {
21
+ let text = layout(source);
22
+ let names = null;
23
+ try { names = parseCore(text).names; } catch { /* a program that cannot be read keeps its layout only */ }
24
+ if (names) text = layout(structure(text, names, width));
25
+ return spacing(text);
26
+ }
27
+
28
+ // ── 1. layout ─────────────────────────────────────────────────────────────────────────────────────────────────
29
+
30
+ function layout(source) {
5
31
  const lines = source.replace(/\r\n?/g, '\n').split('\n');
6
32
  const out = [];
7
33
  const stack = [0]; // original indents of open blocks
@@ -18,3 +44,165 @@ export function formatCore(source) {
18
44
  }
19
45
  return out.length ? `${out.join('\n')}\n` : '';
20
46
  }
47
+
48
+ // ── 2. structure ──────────────────────────────────────────────────────────────────────────────────────────────
49
+
50
+ /** A line's code and its comment ("# …" outside text). */
51
+ function splitComment(line) {
52
+ let q = false;
53
+ for (let i = 0; i < line.length; i++) {
54
+ const c = line[i];
55
+ if (c === '"' || c === '“' || c === '”') q = !q;
56
+ else if (c === '#' && !q) return [line.slice(0, i).replace(/\s+$/, ''), line.slice(i)];
57
+ }
58
+ return [line, ''];
59
+ }
60
+
61
+ const isWord = (t, w) => t && t.t === 'word' && (w === undefined || t.lower === w);
62
+ const isSym = (t, s) => t && t.t === 'sym' && t.text === s;
63
+ const keyOf = (ts) => ts.map((t) => t.lower).join(' ');
64
+
65
+ /** Token indexes at the top level (outside parentheses and brackets) that satisfy pred. */
66
+ function topLevel(ts, pred, from = 0, to = ts.length) {
67
+ const out = [];
68
+ let depth = 0;
69
+ for (let k = from; k < to; k++) {
70
+ const t = ts[k];
71
+ if (isSym(t, '(') || isSym(t, '[')) depth++;
72
+ else if (isSym(t, ')') || isSym(t, ']')) depth--;
73
+ else if (depth === 0 && pred(t, k)) out.push(k);
74
+ }
75
+ return out;
76
+ }
77
+
78
+ /** The longest run of words starting at k whose key satisfies ok: its length, or 0. */
79
+ function longest(ts, k, ok) {
80
+ const run = [];
81
+ for (let j = k; isWord(ts[j]) && !RESERVED.has(ts[j].lower); j++) run.push(ts[j]);
82
+ for (let n = run.length; n > 0; n--) if (ok(keyOf(run.slice(0, n)))) return n;
83
+ return 0;
84
+ }
85
+
86
+ function structure(text, names, width) {
87
+ const out = [];
88
+ for (const line of text.replace(/\n$/, '').split('\n')) {
89
+ const [code, comment] = splitComment(line);
90
+ if (!code.trim()) { out.push(line); continue; }
91
+ const indent = code.match(/^ */)[0];
92
+ let ts;
93
+ try { ts = tokenizeLine(code.slice(indent.length), 1); } catch { out.push(line); continue; }
94
+ const expanded = expandRecord(code, indent, ts, comment, names, width);
95
+ if (expanded) { out.push(...expanded); continue; }
96
+ const wrapped = wrapCondition(code, indent, ts, comment, width);
97
+ if (wrapped) { out.push(...wrapped); continue; }
98
+ out.push(line);
99
+ }
100
+ return `${out.join('\n')}\n`;
101
+ }
102
+
103
+ /**
104
+ * A record built on one line, as the whole value of Set, Give, Add … to, or Expect … to, becomes a block when it is long:
105
+ * Set trade to a Trade with symbol "ACME" and quantity 10 and buy price $20.00 and sell price $40.00
106
+ * ->
107
+ * Set trade to a Trade:
108
+ * symbol: "ACME"
109
+ * …
110
+ * Fields are found exactly as the parser finds them; each value is copied from the line as written.
111
+ */
112
+ function expandRecord(code, indent, ts, comment, names, width) {
113
+ const w0 = ts[0]?.lower;
114
+ let from, to = ts.length;
115
+ if (w0 === 'set') { const k = topLevel(ts, (t) => isWord(t, 'to'))[0]; if (k == null) return null; from = k + 1; }
116
+ else if (w0 === 'give') from = 1;
117
+ else if (w0 === 'add') { const k = topLevel(ts, (t) => isWord(t, 'to')).pop(); if (k == null) return null; from = 1; to = k; }
118
+ else if (w0 === 'expect') {
119
+ // Expect <record> to be / to fail / to contain …: the record is everything before that "to".
120
+ const k = topLevel(ts, (t, j) => isWord(t, 'to') && ['be', 'fail', 'contain'].some((w) => isWord(ts[j + 1], w)))[0];
121
+ if (k == null) return null;
122
+ from = 1; to = k;
123
+ } else return null;
124
+ if (!(isWord(ts[from], 'a') || isWord(ts[from], 'an'))) return null;
125
+ const rn = longest(ts, from + 1, (key) => names.records.has(key));
126
+ if (!rn || !isWord(ts[from + 1 + rn], 'with')) return null;
127
+ const record = keyOf(ts.slice(from + 1, from + 1 + rn));
128
+ const own = names.recordFields?.get(record);
129
+ // The fields, split exactly where the parser splits them: at "and" or "," followed by a field name.
130
+ const fieldAt = (k) => longest(ts, k, (key) => names.fields.has(key));
131
+ const fields = [];
132
+ let k = from + 1 + rn + 1;
133
+ while (k < to) {
134
+ const fn = fieldAt(k);
135
+ if (!fn) return null;
136
+ const valueFrom = k + fn;
137
+ const seps = topLevel(ts, (t, j) => (isWord(t, 'and') || isSym(t, ',')) && fieldAt(j + 1) > 0, valueFrom, to);
138
+ const valueTo = seps.length ? seps[0] : to;
139
+ if (valueTo <= valueFrom) return null;
140
+ fields.push({ key: keyOf(ts.slice(k, k + fn)), text: ts.slice(k, k + fn).map((t) => t.text).join(' '), from: valueFrom, to: valueTo });
141
+ k = valueTo + 1;
142
+ }
143
+ if (!fields.length || (own && fields.some((f) => !own.includes(f.key))) || new Set(fields.map((f) => f.key)).size !== fields.length) return null;
144
+ if (fields.length <= MAX_INLINE_FIELDS && code.length + (comment ? comment.length + 2 : 0) <= width) return null;
145
+ const body = code.slice(indent.length);
146
+ const col = (j) => (j < ts.length ? ts[j].col - 1 : body.length); // where token j starts in the line (or its end)
147
+ const head = `${body.slice(0, col(from + 1 + rn)).replace(/\s+$/, '')}${w0 === 'add' || w0 === 'expect' ? ` ${body.slice(col(to)).trim()}` : ''}:`;
148
+ return [`${indent}${head}${comment ? ` ${comment}` : ''}`, ...fields.map((f) => `${indent} ${f.text}: ${body.slice(col(f.from), col(f.to)).trim()}`)];
149
+ }
150
+
151
+ /**
152
+ * A long condition wraps before each "and" / "or" that joins its parts (not the "and" of "between 1 and 10", nor
153
+ * the ones that separate a call's values):
154
+ * When member is yes
155
+ * and total is at least 100:
156
+ */
157
+ function wrapCondition(code, indent, ts, comment, width) {
158
+ if (code.length + (comment ? comment.length + 2 : 0) <= width) return null;
159
+ const lead = keyOf(ts.slice(0, 2));
160
+ const starts = isWord(ts[0], 'when') || isWord(ts[0], 'if') || lead === 'otherwise when' || lead === 'otherwise if' || lead === 'repeat while' || lead === 'repeat until';
161
+ if (!starts || !isSym(ts[ts.length - 1], ':') || keyOf(ts.slice(0, 3)) === 'if this fails') return null;
162
+ // Split points: a top-level and/or that is not owed to a "between" or to a call's "with" list.
163
+ let owed = 0, inWith = false;
164
+ const splits = [];
165
+ topLevel(ts, (t, j) => {
166
+ if (isWord(t, 'between')) owed++;
167
+ else if (isWord(t, 'with')) inWith = true;
168
+ else if (isWord(t, 'is') || isWord(t, 'are') || ['<', '>', '<=', '>=', '=', '==', '!='].some((s) => isSym(t, s))) inWith = false;
169
+ else if (isWord(t, 'and') && owed) owed--;
170
+ else if ((isWord(t, 'and') && !inWith) || isWord(t, 'or')) { splits.push(j); inWith = false; }
171
+ return false;
172
+ });
173
+ if (!splits.length) return null;
174
+ const body = code.slice(indent.length);
175
+ const parts = [];
176
+ let start = 0;
177
+ for (const j of splits) { parts.push(body.slice(start, ts[j].col - 1).trim()); start = ts[j].col - 1; }
178
+ parts.push(body.slice(start).trim());
179
+ if (parts.some((p) => !p)) return null;
180
+ return parts.map((p, i) => `${indent}${i ? ' ' : ''}${p}${i === parts.length - 1 && comment ? ` ${comment}` : ''}`);
181
+ }
182
+
183
+ // ── 3. spacing ────────────────────────────────────────────────────────────────────────────────────────────────
184
+
185
+ /** One blank line before and after each function, record, and Test block at the top level. */
186
+ function spacing(text) {
187
+ const lines = text.replace(/\n$/, '').split('\n');
188
+ if (lines.length === 1 && !lines[0]) return '';
189
+ const isDefinition = (l) => /^(?:To\b.*:|Test\b.*:|An?\b.*\bhas:)\s*(?:#.*)?$/i.test(l);
190
+ const isComment = (l) => /^\s*#/.test(l);
191
+ const out = [];
192
+ let inDefinition = false;
193
+ for (const l of lines) {
194
+ const top = l && !/^\s/.test(l);
195
+ if (top && isDefinition(l)) {
196
+ // A blank line before it, above any comment written right over it (unless that is the top of the file).
197
+ let k = out.length;
198
+ while (k > 0 && isComment(out[k - 1]) && !/^\s/.test(out[k - 1])) k--;
199
+ if (k > 0 && out[k - 1] !== '') out.splice(k, 0, '');
200
+ inDefinition = true;
201
+ } else if (top && inDefinition && !isComment(l)) {
202
+ if (out[out.length - 1] !== '') out.push('');
203
+ inDefinition = false;
204
+ }
205
+ out.push(l);
206
+ }
207
+ return `${out.join('\n').replace(/\n{3,}/g, '\n\n')}\n`;
208
+ }
@@ -0,0 +1,106 @@
1
+ // Writing compiled Go to disk, and running it.
2
+ //
3
+ // The output is one Go module: go.mod, thunder/thunder_runtime.go (the runtime, a package of its own so Go's build
4
+ // cache keeps it compiled), one <module>.go per Thunder file (package main), and two entry files picked by a build tag:
5
+ // thunder_main.go runs the program, run_tests.go (-tags thundertests) runs every Test block.
6
+ // Running needs the go toolchain (https://go.dev/dl/). Standard library only: nothing is downloaded.
7
+ import { writeFileSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
8
+ import { join, dirname } from 'node:path';
9
+ import { spawnSync } from 'node:child_process';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { tmpdir } from 'node:os';
12
+ import { toGo, pythonOnlyUses, id, goStr, goNamespaces as namespaces } from './target-go.mjs';
13
+ import { diag } from './diagnostics.mjs';
14
+
15
+ export const GO_RUNTIME = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'runtime-go', 'thunder_runtime.go'), 'utf8');
16
+
17
+ /** TC405 for every Use in a file: Python modules exist only for the Python target. */
18
+ export function goDiagnostics(result) {
19
+ return pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
20
+ `"${u.module}" is a Python module, and this program is compiled to Go, which cannot use it.`,
21
+ 'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'));
22
+ }
23
+
24
+
25
+ /** Compile checked results to Go: { [file]: text } for the module files. */
26
+ export function compileGo(results) {
27
+ const ns = namespaces(results);
28
+ const files = {};
29
+ for (const r of results) files[`${r.module}.go`] = toGo(r.program, r.info, { source: r.file, module: r.module, ns: ns.get(r.module) });
30
+ return files;
31
+ }
32
+
33
+ /**
34
+ * Write the Go module for `results` into outDir. `entry` is the module `thunder run` runs (its kept values are worked
35
+ * out first, as Python's import of it does); the tests entry works out every file's kept values, in order.
36
+ */
37
+ export function writeGo(results, outDir, { entry = null } = {}) {
38
+ mkdirSync(join(outDir, 'thunder'), { recursive: true });
39
+ const files = compileGo(results);
40
+ for (const [f, text] of Object.entries(files)) writeFileSync(join(outDir, f), text);
41
+ writeFileSync(join(outDir, 'go.mod'), 'module thunderprogram\n\ngo 1.21\n');
42
+ writeFileSync(join(outDir, 'thunder', 'thunder_runtime.go'), GO_RUNTIME);
43
+ const main = entry ?? results.find((r) => r.kind !== 'test')?.module ?? results[0]?.module;
44
+ writeFileSync(join(outDir, 'thunder_main.go'), [
45
+ '//go:build !thundertests',
46
+ '',
47
+ '// Generated by the Thunder compiler: runs the program. Build it with: go build -o program .',
48
+ 'package main',
49
+ '',
50
+ 'import T "thunderprogram/thunder"',
51
+ '',
52
+ 'func main() {',
53
+ ...(main ? [`\tkeep_${main}()`, `\tT.Run(main_${main})`] : ['\tT.Run(func() {})']),
54
+ '}',
55
+ '',
56
+ ].join('\n'));
57
+ writeFileSync(join(outDir, 'run_tests.go'), [
58
+ '//go:build thundertests',
59
+ '',
60
+ '// Generated by the Thunder compiler: runs every Test block in this project. Run it with: go run -tags thundertests .',
61
+ 'package main',
62
+ '',
63
+ 'import T "thunderprogram/thunder"',
64
+ '',
65
+ 'func main() {',
66
+ ...results.map((r) => `\tkeep_${r.module}()`),
67
+ `\tT.RunTests([]T.Suite{${results.map((r) => `{File: ${goStr(r.file)}, Tests: tests_${r.module}}`).join(', ')}})`,
68
+ '}',
69
+ '',
70
+ ].join('\n'));
71
+ return Object.keys(files);
72
+ }
73
+
74
+ /** The go toolchain here: { cmd, version } or { error }. */
75
+ export function goToolchain() {
76
+ const cmd = process.env.THUNDER_GO || 'go';
77
+ const r = spawnSync(cmd, ['version'], { encoding: 'utf8' });
78
+ if (r.status === 0 && /go version go\d/.test(r.stdout)) return { cmd, version: r.stdout.match(/go(\d+\.\d+(?:\.\d+)?)/)[1] };
79
+ return { error: 'Running Go needs the Go toolchain, version 1.21 or newer (https://go.dev/dl/), or set THUNDER_GO to its path. "thunder build --target go" works without it.' };
80
+ }
81
+
82
+ const goEnv = () => ({ ...process.env, GOTOOLCHAIN: 'local', GOFLAGS: '-mod=mod', GO111MODULE: 'on', CGO_ENABLED: '0' });
83
+
84
+ /**
85
+ * Build the Go module in outDir (the program, or with `tests` its Test blocks) and run it in the folder `cwd`.
86
+ * Returns spawnSync's result ({ status, stdout, stderr }), or { status: 2, stderr } when Go can't run here.
87
+ */
88
+ export function runGo(outDir, { tests = false, cwd = outDir, stdio = 'pipe' } = {}) {
89
+ const go = goToolchain();
90
+ if (go.error) return { status: 2, stdout: '', stderr: `${go.error}\n`, error: go.error };
91
+ const bin = join(outDir, '.run', process.platform === 'win32' ? 'program.exe' : 'program');
92
+ rmSync(dirname(bin), { recursive: true, force: true });
93
+ const args = ['build', '-trimpath', '-o', bin, ...(tests ? ['-tags', 'thundertests'] : []), '.'];
94
+ const b = spawnSync(go.cmd, args, { cwd: outDir, encoding: 'utf8', env: goEnv() });
95
+ if (b.status !== 0) return { status: 2, stdout: '', stderr: `The generated Go did not build (a bug in the Thunder compiler):\n${b.stdout}${b.stderr}`, buildFailed: true };
96
+ return spawnSync(bin, [], { cwd, stdio, encoding: 'utf8' });
97
+ }
98
+
99
+ /** Check that the generated Go builds (go vet off: generated code is not linted). { ok, output } */
100
+ export function buildGo(outDir, { tests = false } = {}) {
101
+ const go = goToolchain();
102
+ if (go.error) return { skipped: go.error };
103
+ const r = spawnSync(go.cmd, ['build', '-trimpath', '-o', join(tmpdir(), `thunder-go-check-${process.pid}`), ...(tests ? ['-tags', 'thundertests'] : []), '.'], { cwd: outDir, encoding: 'utf8', env: goEnv() });
104
+ return { ok: r.status === 0, output: `${r.stdout}${r.stderr}`.trim() };
105
+ }
106
+
@@ -13,6 +13,7 @@ import { formatDiagnostic } from './diagnostics.mjs';
13
13
  export { parseCore } from './parser.mjs';
14
14
  export { checkCore } from './check.mjs';
15
15
  export { toPython } from './target-python.mjs';
16
+ export { toTypeScript, pythonOnlyUses } from './target-typescript.mjs';
16
17
  export { PYTHON_RUNTIME, RUNTIME_VERSION } from './runtime-python.mjs';
17
18
  export { CODES, formatDiagnostic } from './diagnostics.mjs';
18
19
  export { formatCore } from './format.mjs';
@@ -25,7 +26,8 @@ export const CORE_VERSION = '0.1.0';
25
26
  * import them from.
26
27
  */
27
28
  export function compileCore(source, { file = 'main.thunder', imported = [], srcModules = [] } = {}) {
28
- const seed = imported.length ? { known: imported.flatMap((r) => [...r.program.names.known].filter(([, kind]) => kind !== 'var')), fields: imported.flatMap((r) => [...r.program.names.fields]), records: imported.flatMap((r) => [...r.program.names.records]) } : null;
29
+ const seed = imported.length ? { known: imported.flatMap((r) => [...r.program.names.known].filter(([, kind]) => kind !== 'var')), fields: imported.flatMap((r) => [...r.program.names.fields]), records: imported.flatMap((r) => [...r.program.names.records]),
30
+ recordFields: imported.flatMap((r) => [...(r.program.names.recordFields ?? [])]), funcInputs: imported.flatMap((r) => [...(r.program.names.funcInputs ?? [])]) } : null;
29
31
  const program = parseCore(source, { seed });
30
32
  const { diagnostics, info } = checkCore(program, { imported: imported.map((r) => r.info) });
31
33
  const ok = diagnostics.length === 0;
@@ -0,0 +1,6 @@
1
+ // T.java: a short name for ThunderRuntime, so compiled Java reads T.add(a, b). Written by the Thunder compiler.
2
+ package thunder;
3
+
4
+ public final class T extends ThunderRuntime {
5
+ private T() {}
6
+ }