@skillstech/thunderlang 1.6.1 → 1.8.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 +121 -0
- package/README.md +10 -3
- package/dist/core.cjs +264 -47
- package/dist/index.cjs +9118 -1077
- package/dist/learn.cjs +1419 -90
- package/package.json +1 -1
- package/src/ai.mjs +2 -1
- package/src/atlas.mjs +2 -1
- package/src/behaviour.mjs +246 -0
- package/src/cli-main.mjs +3015 -0
- package/src/cli.mjs +9 -2799
- package/src/conflict.mjs +0 -0
- package/src/core/ThunderDotnet.cs +195 -0
- package/src/core/check.mjs +316 -10
- package/src/core/cli.mjs +67 -10
- package/src/core/csharp-run.mjs +29 -8
- package/src/core/diagnostics.mjs +12 -1
- package/src/core/engine-core.mjs +161 -20
- package/src/core/engine-values.mjs +1 -0
- package/src/core/engine.mjs +131 -7
- package/src/core/go-run.mjs +3 -2
- package/src/core/index.mjs +6 -2
- package/src/core/java-run.mjs +3 -3
- package/src/core/kind.mjs +45 -0
- package/src/core/lexer.mjs +16 -2
- package/src/core/parser.mjs +254 -22
- package/src/core/project-root.mjs +18 -0
- package/src/core/project.mjs +18 -18
- package/src/core/react-run.mjs +3 -3
- package/src/core/runtime-go/thunder_runtime.go +269 -1
- package/src/core/runtime-npm.mjs +79 -0
- package/src/core/runtime-python.mjs +365 -3
- package/src/core/runtime-react.mjs +2 -1
- package/src/core/runtime-typescript.mjs +155 -6
- package/src/core/rust-run.mjs +3 -2
- package/src/core/serving.mjs +12 -0
- package/src/core/store-format.mjs +110 -0
- package/src/core/target-csharp.mjs +5 -1
- package/src/core/target-go.mjs +11 -4
- package/src/core/target-python.mjs +39 -6
- package/src/core/target-rust.mjs +1 -1
- package/src/core/target-typescript.mjs +95 -7
- package/src/core/typescript-run.mjs +14 -7
- package/src/core-changes-fs.mjs +28 -0
- package/src/core-changes.d.mts +67 -0
- package/src/core-changes.mjs +603 -0
- package/src/core-rules.mjs +146 -0
- package/src/core-services.d.mts +4 -0
- package/src/core-services.mjs +49 -0
- package/src/decision.mjs +2 -1
- package/src/distributed.mjs +2 -1
- package/src/emit.mjs +2 -2
- package/src/evidence.mjs +28 -0
- package/src/examples.d.mts +21 -0
- package/src/examples.mjs +175 -0
- package/src/focus.mjs +2 -1
- package/src/index.d.ts +4 -0
- package/src/index.mjs +4 -0
- package/src/intent-atlas.mjs +4 -3
- package/src/mcp.mjs +52 -6
- package/src/passport-fs.mjs +2 -1
- package/src/passport.mjs +2 -1
- package/src/privacy.mjs +2 -1
- package/src/program.d.mts +4 -0
- package/src/program.mjs +4 -0
- package/src/read-repo-fs.mjs +2 -1
- package/src/read-repo.mjs +3 -2
- package/src/report.mjs +3 -2
- package/src/review.mjs +71 -4
- package/src/select.mjs +2 -1
- package/src/semantic-diff.mjs +7 -6
- package/src/system.mjs +3 -2
- package/src/text-order.mjs +6 -0
- package/src/thunderize.mjs +2 -1
- package/src/trace-cli.mjs +8 -3
- package/src/trace-data.mjs +3 -2
- package/src/trace-fs.mjs +29 -3
- package/src/trace.mjs +27 -10
- package/src/write-across-cli.mjs +22 -4
- package/src/write-across.mjs +2 -1
- package/syntaxes/thunder.tmLanguage.json +196 -0
package/src/core/engine-core.mjs
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
attrErr, strMethod, splitLines, pySplit, pyStrip, jsonParse, jsonText, isInt, isNumber,
|
|
19
19
|
} from './engine-values.mjs';
|
|
20
20
|
import * as V from './engine-values.mjs';
|
|
21
|
+
import { storeFromText, storeToText, storeFile, recordFrom, dataJson, unreachableReason } from './store-format.mjs';
|
|
21
22
|
import { shownText, copyValue, typedNumber, problemText } from './screen-values.mjs';
|
|
22
23
|
import { percentDecimal } from './target-python.mjs';
|
|
23
24
|
import { firstLine } from './target-typescript.mjs';
|
|
@@ -32,6 +33,8 @@ class Return { constructor(v) { this.v = v; } }
|
|
|
32
33
|
// run is repeated on the deep-stack thread, so any RangeError (or a regular expression's "Stack overflow") counts.
|
|
33
34
|
const nativeOverflow = (e) => { try { return e instanceof RangeError || (e instanceof SyntaxError && e.message.endsWith('Stack overflow')); } catch { return true; } };
|
|
34
35
|
class NeedsDeeperStack extends Error {}
|
|
36
|
+
/** A call ran out of its steps (engineForCalls): it may never finish, so its answer is unknown, not wrong. */
|
|
37
|
+
export class OutOfSteps extends Error {}
|
|
35
38
|
|
|
36
39
|
const MAX_FRAMES = V.MAX_FRAMES;
|
|
37
40
|
const CONTAINER_KINDS = new Set(['if', 'each', 'range', 'times', 'while', 'tryFail']); // statements with steps inside
|
|
@@ -40,7 +43,7 @@ const MAX_RECORDED = 20000; // a recording stops growing here (and says so); the
|
|
|
40
43
|
/** The Python modules a program uses (Use), which this engine does not run. */
|
|
41
44
|
export function pythonModulesUsed(results) {
|
|
42
45
|
const out = [];
|
|
43
|
-
for (const r of results) for (const m of r.info.modules) if (!r.info.imported?.has(m)) out.push({ file: r.file, module: m.module, name: m.text ?? m.name, line: m.line });
|
|
46
|
+
for (const r of results) for (const m of r.info.modules) if (!r.info.imported?.has(m)) out.push({ file: r.file, module: m.module, name: m.text ?? m.name, line: m.line, ecosystem: m.ecosystem ?? 'python' });
|
|
44
47
|
return out;
|
|
45
48
|
}
|
|
46
49
|
|
|
@@ -48,6 +51,8 @@ export function pythonModulesUsed(results) {
|
|
|
48
51
|
export function refusalText(uses) {
|
|
49
52
|
const u = uses[0];
|
|
50
53
|
const more = uses.length > 1 ? ` (and ${uses.length - 1} more)` : '';
|
|
54
|
+
if (u.ecosystem === 'dotnet' || u.ecosystem === 'nuget') return `This program uses the .NET type "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it as C#: --target csharp.`;
|
|
55
|
+
if (u.ecosystem === 'npm') return `This program uses the npm package "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it as TypeScript: --target typescript.`;
|
|
51
56
|
return `This program uses the Python module "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it with Python: leave out --engine thunder.`;
|
|
52
57
|
}
|
|
53
58
|
|
|
@@ -59,7 +64,14 @@ class Engine {
|
|
|
59
64
|
// readText(path, cwd): the text of a file the program reads, or throws with .code 'ENOENT' / 'EISDIR'. Without it
|
|
60
65
|
// (a browser), reading a file is reported as a missing file.
|
|
61
66
|
// record: keep a step-by-step recording of the run (the Thunder Time Machine; see recordedRun below).
|
|
62
|
-
|
|
67
|
+
// http(method, url, bodyText) -> { status, text } | { error }: calls another service and waits for the answer.
|
|
68
|
+
// Without it (a browser), "the answer from …" says it can't run here.
|
|
69
|
+
constructor({ cwd = '.', deeper = false, readText = null, record = false, store = null, http = null } = {}) {
|
|
70
|
+
this.http = http;
|
|
71
|
+
this.answeredStatus = null; // Give … with status 201, read by the server after an endpoint answers
|
|
72
|
+
// store: { load(file) -> text | null, save(file, text) } for stored lists (Store … as a list of …). Without it,
|
|
73
|
+
// stored lists start empty and are not saved (the browser, and every test).
|
|
74
|
+
this.dataFiles = store;
|
|
63
75
|
this.cwd = cwd;
|
|
64
76
|
this.rec = record ? { steps: [], truncated: false } : null;
|
|
65
77
|
this.readText = readText;
|
|
@@ -68,6 +80,7 @@ class Engine {
|
|
|
68
80
|
this.deeper = deeper;
|
|
69
81
|
this.frames = [];
|
|
70
82
|
this.out = [];
|
|
83
|
+
this.budget = null; // steps left before a call is stopped (engineForCalls); null: no limit
|
|
71
84
|
}
|
|
72
85
|
|
|
73
86
|
// ── loading ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
@@ -78,6 +91,9 @@ class Engine {
|
|
|
78
91
|
for (const m of imports) for (const [k, v] of m.globals) mod.globals.set(k, v);
|
|
79
92
|
for (const r of result.info.records.filter(own)) mod.globals.set(r.py, this.recordClass(r, mod));
|
|
80
93
|
for (const f of result.info.funcs.filter(own)) mod.globals.set(f.py, { isFunc: true, f, mod });
|
|
94
|
+
// Stored lists: empty until the program starts (fillStores), saved when it finishes well (saveStores).
|
|
95
|
+
mod.stores = (result.info.stores ?? []).filter(own).map((s) => { const list = []; mod.globals.set(s.py, list); return { s, list, cls: mod.globals.get(s.record.py) }; });
|
|
96
|
+
for (const m of imports) for (const st of m.stores ?? []) mod.stores.push(st);
|
|
81
97
|
const consts = result.info.consts.filter(own);
|
|
82
98
|
if (consts.length) {
|
|
83
99
|
const frame = { file: mod.file, line: 0 };
|
|
@@ -92,7 +108,8 @@ class Engine {
|
|
|
92
108
|
recordClass(r, mod) {
|
|
93
109
|
const rules = new Map();
|
|
94
110
|
for (const rule of r.rulesToCheck ?? []) { const f = r.fieldMap.get(rule.subject); (rules.get(f.py) ?? rules.set(f.py, []).get(f.py)).push(rule); }
|
|
95
|
-
|
|
111
|
+
const alts = r.alts ? Object.fromEntries(r.alts.map((a) => [a.name, a.fields.map((f) => f.py)])) : null;
|
|
112
|
+
return { isRecord: true, py: r.py, fields: r.fields.map((f) => ({ py: f.py, type: f.type })), rules, mod, alts };
|
|
96
113
|
}
|
|
97
114
|
|
|
98
115
|
// ── frames, lines, errors ───────────────────────────────────────────────────────────────────────────────────
|
|
@@ -101,7 +118,7 @@ class Engine {
|
|
|
101
118
|
this.frames.push(frame);
|
|
102
119
|
try { return fn(); }
|
|
103
120
|
catch (e) {
|
|
104
|
-
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
121
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
|
|
105
122
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
106
123
|
const err = asPyErr(e);
|
|
107
124
|
if (!err.where) err.where = this.frames.map((f) => ({ file: f.file, line: f.line }));
|
|
@@ -128,7 +145,7 @@ class Engine {
|
|
|
128
145
|
const locals = new Map();
|
|
129
146
|
const env = { mod, locals, frame };
|
|
130
147
|
f.params.forEach((p, i) => {
|
|
131
|
-
let v = i < args.length ? args[i] : (p.dflt ? (p.dflt.k === 'name' ? NOT_GIVEN : this.x(p.dflt, env)) : undefined);
|
|
148
|
+
let v = i < args.length && args[i] !== NOT_GIVEN ? args[i] : (p.dflt ? (p.dflt.k === 'name' ? NOT_GIVEN : this.x(p.dflt, env)) : undefined);
|
|
132
149
|
if (v === undefined) throw TypeErr(`${f.py}() missing 1 required positional argument: '${p.py}'`);
|
|
133
150
|
locals.set(p.py, v);
|
|
134
151
|
});
|
|
@@ -140,6 +157,34 @@ class Engine {
|
|
|
140
157
|
});
|
|
141
158
|
}
|
|
142
159
|
|
|
160
|
+
/** the answer from GET "…" [with …] [as Rate]: the answer's text, or records read from it. */
|
|
161
|
+
httpCall(e, env) {
|
|
162
|
+
const url = this.x(e.url, env);
|
|
163
|
+
const body = e.body ? dataJson(this.x(e.body, env)) : null;
|
|
164
|
+
if (!this.http) throw V.CallFailed(`${e.method} ${pyStr(url)} can't be called here: calls to other services run with the thunder command, not in the browser.`);
|
|
165
|
+
const out = this.http(e.method, url, body);
|
|
166
|
+
if (out.error) throw V.CallFailed(`${e.method} ${url} could not be reached (${unreachableReason(out)}).`);
|
|
167
|
+
if (out.status < 200 || out.status > 299) throw V.CallFailed(`${e.method} ${url} answered ${out.status}: ${out.text.trim().slice(0, 300)}`);
|
|
168
|
+
if (!e.record) return out.text;
|
|
169
|
+
const where = `The answer from ${e.method} ${url}`;
|
|
170
|
+
let data;
|
|
171
|
+
try { data = JSON.parse(out.text); } catch { throw V.ConversionFailed(`${where} is not JSON Thunder can read.`); }
|
|
172
|
+
const cls = env.mod.globals.get(e.record.py);
|
|
173
|
+
const make = (given) => this.newRecord(cls, given);
|
|
174
|
+
if (e.as.k === 'list') {
|
|
175
|
+
if (!Array.isArray(data)) throw V.ConversionFailed(`${where} should be a list, written [ … ].`);
|
|
176
|
+
return data.map((row, i) => recordFrom(row, cls, `${where}, item ${i + 1}`, make, 'it has'));
|
|
177
|
+
}
|
|
178
|
+
return recordFrom(data, cls, where, make, 'it has');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** An endpoint answering one request: its value and status, or the error it stopped with. Output so far is kept. */
|
|
182
|
+
answer(mod, f, args) {
|
|
183
|
+
this.answeredStatus = null;
|
|
184
|
+
const value = this.call(mod.globals.get(f.py), args);
|
|
185
|
+
return { value, status: this.answeredStatus ?? 200 };
|
|
186
|
+
}
|
|
187
|
+
|
|
143
188
|
never(rule, value, env) { V.never(this.x(rule.rule.cond, env, { subject: value }), rule.text, rule.line, value); }
|
|
144
189
|
|
|
145
190
|
newRecord(cls, given) { return V.newRecordWith((o, k, v) => this.setAttr(o, k, v), cls, given); }
|
|
@@ -188,6 +233,7 @@ class Engine {
|
|
|
188
233
|
}
|
|
189
234
|
|
|
190
235
|
stmt(s, env) {
|
|
236
|
+
if (this.budget !== null && --this.budget < 0) throw new OutOfSteps();
|
|
191
237
|
if (this.rec) return this.recordStep(s, env);
|
|
192
238
|
return this.runStmt(s, env);
|
|
193
239
|
}
|
|
@@ -246,8 +292,8 @@ class Engine {
|
|
|
246
292
|
this.storeAt(t, v, env);
|
|
247
293
|
return;
|
|
248
294
|
}
|
|
249
|
-
case 'give':
|
|
250
|
-
case 'stop': { const v = this.x(s.e, env);
|
|
295
|
+
case 'give': { const v = s.e.k === 'nothing' ? null : this.x(s.e, env); if (s.status != null) this.answeredStatus = s.status; throw new Return(v); }
|
|
296
|
+
case 'stop': { const v = this.x(s.e, env); const err = Stop(s.e.type?.k === 'text' ? pyStr(v) : show(v)); if (s.status != null) err.status = s.status; throw err; }
|
|
251
297
|
case 'if':
|
|
252
298
|
for (const b of s.branches) {
|
|
253
299
|
fr.line = b.line;
|
|
@@ -324,7 +370,7 @@ class Engine {
|
|
|
324
370
|
case 'tryFail':
|
|
325
371
|
try { this.stmt(s.stmt, env); }
|
|
326
372
|
catch (e) {
|
|
327
|
-
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
373
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
|
|
328
374
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
329
375
|
const err = asPyErr(e);
|
|
330
376
|
fr.line = L;
|
|
@@ -362,15 +408,18 @@ class Engine {
|
|
|
362
408
|
if (s.mode === 'fail') {
|
|
363
409
|
const msg = s.msg ? this.x(s.msg, env) : null;
|
|
364
410
|
// A JavaScript stack overflow is not the program failing: let it reach the deeper-stack retry.
|
|
411
|
+
let outOfSteps = null; // running out of steps is not the failure the example expects
|
|
365
412
|
V.expectFailure(() => {
|
|
366
413
|
try { this.x(s.e, env); }
|
|
367
414
|
catch (e) {
|
|
368
415
|
if (e instanceof Return) return;
|
|
369
416
|
if (e instanceof NeedsDeeperStack) throw e;
|
|
370
417
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
418
|
+
if (e instanceof OutOfSteps) outOfSteps = e;
|
|
371
419
|
throw e;
|
|
372
420
|
}
|
|
373
421
|
}, text, msg);
|
|
422
|
+
if (outOfSteps) throw outOfSteps;
|
|
374
423
|
return;
|
|
375
424
|
}
|
|
376
425
|
const actual = this.x(s.e, env);
|
|
@@ -426,6 +475,7 @@ class Engine {
|
|
|
426
475
|
case 'bool': return !!e.v;
|
|
427
476
|
case 'nothing': case 'hole': return null;
|
|
428
477
|
case 'paren': return sub2(e.e);
|
|
478
|
+
case 'httpCall': return this.httpCall(e, env);
|
|
429
479
|
case 'today': return PyDate.today();
|
|
430
480
|
case 'date': { const d = PyDate.parse(e.text); if (!d) throw new PyErr('ValueError', `Invalid isoformat string: '${e.text}'`); return d; }
|
|
431
481
|
case 'str': return this.str(e, env, ctx);
|
|
@@ -540,12 +590,33 @@ class Engine {
|
|
|
540
590
|
// ── running a program or its tests ──────────────────────────────────────────────────────────────────────────
|
|
541
591
|
runMain(mod) {
|
|
542
592
|
const main = mod.r.program.main ?? [];
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
593
|
+
this.fillStores(mod);
|
|
594
|
+
if (main.length) {
|
|
595
|
+
const frame = { file: mod.file, line: 0 };
|
|
596
|
+
this.withFrame(frame, () => {
|
|
597
|
+
const env = { mod, locals: new Map(), frame };
|
|
598
|
+
try { this.block(main, env); } catch (e) { if (e instanceof Return) return; throw e; }
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
// Only a program that finished well is saved: one that stopped with a problem changes nothing.
|
|
602
|
+
this.saveStores(mod);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** Each stored list, filled from its file (data/<name>.json); a missing file is an empty list. */
|
|
606
|
+
fillStores(mod) {
|
|
607
|
+
if (!this.dataFiles) return;
|
|
608
|
+
for (const st of mod.stores ?? []) {
|
|
609
|
+
const file = storeFile(st.s);
|
|
610
|
+
const text = this.dataFiles.load(file);
|
|
611
|
+
if (text == null) continue;
|
|
612
|
+
const frame = { file: mod.file, line: st.s.line };
|
|
613
|
+
this.withFrame(frame, () => { st.list.splice(0, st.list.length, ...storeFromText(text, st.cls, file, (given) => this.newRecord(st.cls, given))); });
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
saveStores(mod) {
|
|
618
|
+
if (!this.dataFiles) return;
|
|
619
|
+
for (const st of mod.stores ?? []) this.dataFiles.save(storeFile(st.s), storeToText(st.list, st.cls));
|
|
549
620
|
}
|
|
550
621
|
|
|
551
622
|
runTest(mod, t) {
|
|
@@ -560,11 +631,24 @@ class Engine {
|
|
|
560
631
|
|
|
561
632
|
// ── public API ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
562
633
|
|
|
634
|
+
/**
|
|
635
|
+
* A program with problems is never run: running what did not compile could print a wrong answer, or pass a test
|
|
636
|
+
* that should fail. The CLI stops before this; this keeps every other caller (the site, OpenThunder) just as safe.
|
|
637
|
+
*/
|
|
638
|
+
function notCompiled(results) {
|
|
639
|
+
const bad = results.filter((r) => r && r.ok === false);
|
|
640
|
+
if (!bad.length) return null;
|
|
641
|
+
const lines = bad.flatMap((r) => (r.diagnostics ?? []).filter((d) => d.severity !== 'warning').map((d) => `${r.file ?? 'main.thunder'}, line ${d.line ?? '?'}: ${d.message} [${d.code}]`));
|
|
642
|
+
return { status: 2, stdout: '', stderr: `${lines.join('\n') || 'The program has problems'}\nNothing was run: fix the problems first.\n`, notCompiled: true, steps: [] };
|
|
643
|
+
}
|
|
644
|
+
|
|
563
645
|
/** The same, on the calling thread (its stack allows only a few hundred nested calls). */
|
|
564
|
-
export function runInProcess({ entry, cwd, deeper = false, readText = null } = {}) {
|
|
646
|
+
export function runInProcess({ entry, cwd, deeper = false, readText = null, store = null, http = null } = {}) {
|
|
647
|
+
const broken = notCompiled([entry]);
|
|
648
|
+
if (broken) return broken;
|
|
565
649
|
const uses = pythonModulesUsed([entry]);
|
|
566
650
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
567
|
-
const eng = new Engine({ cwd, deeper, readText });
|
|
651
|
+
const eng = new Engine({ cwd, deeper, readText, store, http });
|
|
568
652
|
let stderr = '', status = 0;
|
|
569
653
|
try {
|
|
570
654
|
const mod = eng.load(entry);
|
|
@@ -577,14 +661,37 @@ export function runInProcess({ entry, cwd, deeper = false, readText = null } = {
|
|
|
577
661
|
return { status, stdout: eng.out.join(''), stderr };
|
|
578
662
|
}
|
|
579
663
|
|
|
664
|
+
/**
|
|
665
|
+
* A program loaded and its main part run, ready to answer requests (thunder run --engine thunder with endpoints).
|
|
666
|
+
* Gives back { eng, mod, stdout } or, when it can't start, { status, stdout, stderr }.
|
|
667
|
+
*/
|
|
668
|
+
export function engineForServing({ entry, cwd, readText = null, store = null, http = null } = {}) {
|
|
669
|
+
const broken = notCompiled([entry]);
|
|
670
|
+
if (broken) return broken;
|
|
671
|
+
const uses = pythonModulesUsed([entry]);
|
|
672
|
+
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
673
|
+
const eng = new Engine({ cwd, readText, store, http });
|
|
674
|
+
try {
|
|
675
|
+
const mod = eng.load(entry);
|
|
676
|
+
eng.runMain(mod);
|
|
677
|
+
const stdout = eng.out.join('');
|
|
678
|
+
eng.out = [];
|
|
679
|
+
return { eng, mod, stdout };
|
|
680
|
+
} catch (e) {
|
|
681
|
+
return { status: 1, stdout: eng.out.join(''), stderr: `${eng.describeError(asPyErr(e))}\n` };
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
580
685
|
/**
|
|
581
686
|
* Run a program and keep a step-by-step recording of it (the Thunder Time Machine, `thunder run --record`).
|
|
582
687
|
* Gives back { status, stdout, stderr, steps, truncated }. Like runInProcess, on the calling thread.
|
|
583
688
|
*/
|
|
584
|
-
export function recordedRun({ entry, cwd, readText = null } = {}) {
|
|
689
|
+
export function recordedRun({ entry, cwd, readText = null, store = null } = {}) {
|
|
690
|
+
const broken = notCompiled([entry]);
|
|
691
|
+
if (broken) return broken;
|
|
585
692
|
const uses = pythonModulesUsed([entry]);
|
|
586
693
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses, steps: [] };
|
|
587
|
-
const eng = new Engine({ cwd, readText, record: true });
|
|
694
|
+
const eng = new Engine({ cwd, readText, record: true, store });
|
|
588
695
|
let stderr = '', status = 0;
|
|
589
696
|
try {
|
|
590
697
|
const mod = eng.load(entry);
|
|
@@ -595,11 +702,45 @@ export function recordedRun({ entry, cwd, readText = null } = {}) {
|
|
|
595
702
|
return { status, stdout: eng.out.join(''), stderr, steps: eng.rec.steps, truncated: eng.rec.truncated };
|
|
596
703
|
}
|
|
597
704
|
|
|
705
|
+
/**
|
|
706
|
+
* Compiled files loaded together, for a tool that calls one function, endpoint, or test at a time (the behaviour
|
|
707
|
+
* comparison in core-changes.mjs). Tests see the src/ files before them, as in thunder test. Nothing is run at load
|
|
708
|
+
* apart from kept values; stored lists start empty and are never saved; calls to other services and file reads are
|
|
709
|
+
* refused. Each call() gets `steps` statements, then stops with OutOfSteps.
|
|
710
|
+
* Gives back { mods, call(mod, f, args), endpoint(mod, f, args), test(mod, t), record(cls, row) } or { failed }.
|
|
711
|
+
*/
|
|
712
|
+
export function engineForCalls({ results, steps = 20000 } = {}) {
|
|
713
|
+
const broken = notCompiled(results);
|
|
714
|
+
if (broken) return { failed: broken.stderr };
|
|
715
|
+
const uses = pythonModulesUsed(results);
|
|
716
|
+
if (uses.length) return { failed: refusalText(uses) };
|
|
717
|
+
const eng = new Engine({});
|
|
718
|
+
const mods = [], srcMods = [];
|
|
719
|
+
try {
|
|
720
|
+
for (const r of results) {
|
|
721
|
+
const mod = eng.load(r, r.kind === 'test' ? srcMods : []);
|
|
722
|
+
if (r.kind !== 'test') srcMods.push(mod);
|
|
723
|
+
mods.push(mod);
|
|
724
|
+
}
|
|
725
|
+
} catch (e) { return { failed: eng.describeError(asPyErr(e)) }; }
|
|
726
|
+
const fresh = (fn) => { eng.budget = steps; eng.frames = []; eng.out = []; try { return fn(); } finally { eng.budget = null; } };
|
|
727
|
+
return {
|
|
728
|
+
mods,
|
|
729
|
+
eng,
|
|
730
|
+
call: (mod, f, args) => fresh(() => eng.call(mod.globals.get(f.py), args)),
|
|
731
|
+
endpoint: (mod, f, args) => fresh(() => eng.answer(mod, f, args)),
|
|
732
|
+
test: (mod, t) => fresh(() => eng.runTest(mod, t)),
|
|
733
|
+
record: (cls, row) => fresh(() => recordFrom(row, cls, `the ${cls.py}`, (given) => eng.newRecord(cls, given), 'it has')),
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
|
|
598
737
|
/** The same, on the calling thread. */
|
|
599
|
-
export function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
|
|
738
|
+
export function testInProcess({ results, cwd, deeper = false, readText = null, http = null } = {}) {
|
|
739
|
+
const broken = notCompiled(results);
|
|
740
|
+
if (broken) return broken;
|
|
600
741
|
const uses = pythonModulesUsed(results);
|
|
601
742
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
602
|
-
const eng = new Engine({ cwd, deeper, readText });
|
|
743
|
+
const eng = new Engine({ cwd, deeper, readText, http });
|
|
603
744
|
const mods = [];
|
|
604
745
|
const srcMods = [];
|
|
605
746
|
for (const r of results) {
|
|
@@ -23,6 +23,7 @@ export const KindMismatch = (m) => new ThunderErr('TC506', m, 'TypeError'); // a
|
|
|
23
23
|
export const ConversionFailed = (m) => new ThunderErr('TC509', m, 'ValueError');
|
|
24
24
|
export const MissingValue = (m) => new ThunderErr('TC503', m, 'LookupError');
|
|
25
25
|
export const DividedByZero = (m) => new ThunderErr('TC501', m, 'ZeroDivisionError');
|
|
26
|
+
export const CallFailed = (m) => new ThunderErr('TC510', m, 'CallFailed'); // a call to another service (HTTP)
|
|
26
27
|
|
|
27
28
|
/** An error Python itself raises (TypeError, KeyError, ...), with Python's own message. */
|
|
28
29
|
export class PyErr extends Error {
|
package/src/core/engine.mjs
CHANGED
|
@@ -8,16 +8,44 @@
|
|
|
8
8
|
//
|
|
9
9
|
// A program that uses a Python module ("Use csv as csv") is not run here: Thunder never imitates a library.
|
|
10
10
|
|
|
11
|
-
import { readFileSync } from 'node:fs';
|
|
11
|
+
import { readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs';
|
|
12
12
|
import { Worker, MessageChannel, receiveMessageOnPort } from 'node:worker_threads';
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
13
|
+
import { spawnSync } from 'node:child_process';
|
|
14
|
+
import { createServer } from 'node:http';
|
|
15
|
+
import { resolve as resolvePath, dirname } from 'node:path';
|
|
16
|
+
import { ENGINES, pythonModulesUsed, refusalText, runInProcess as runCore, testInProcess as testCore, engineForServing, ThunderErr, PyErr } from './engine-core.mjs';
|
|
17
|
+
import { asPyErr, explain, NOT_GIVEN } from './engine-values.mjs';
|
|
18
|
+
import { inputValue, dataJson } from './store-format.mjs';
|
|
15
19
|
|
|
16
20
|
export { ENGINES, pythonModulesUsed, refusalText, ThunderErr, PyErr };
|
|
17
21
|
|
|
18
22
|
/** Files a program reads come from disk, relative to the folder it runs in. */
|
|
19
23
|
const readText = (path, cwd) => readFileSync(resolvePath(cwd, path), 'utf8');
|
|
20
24
|
|
|
25
|
+
/**
|
|
26
|
+
* Stored lists (Store … as a list of …) live in files under the folder the program runs in (data/<name>.json).
|
|
27
|
+
* A save writes a new file next to the old one and then renames it, so a file is never left half written.
|
|
28
|
+
*/
|
|
29
|
+
export function nodeStore(cwd) {
|
|
30
|
+
return {
|
|
31
|
+
load(file) { try { return readFileSync(resolvePath(cwd, file), 'utf8'); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } },
|
|
32
|
+
save(file, text) {
|
|
33
|
+
const path = resolvePath(cwd, file);
|
|
34
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
35
|
+
writeFileSync(`${path}.saving`, text);
|
|
36
|
+
renameSync(`${path}.saving`, path);
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// A call to another service (the answer from GET "…") waits for its answer, as every step of a program does: Node's
|
|
42
|
+
// fetch runs in a child process and the engine reads what it printed. The same as compiled TypeScript.
|
|
43
|
+
const FETCH = "let d='';process.stdin.on('data',(c)=>d+=c).on('end',async()=>{const q=JSON.parse(d);try{const r=await fetch(q.url,{method:q.method,headers:q.body==null?{accept:'application/json'}:{accept:'application/json','content-type':'application/json'},body:q.body??undefined,signal:AbortSignal.timeout(30000)});process.stdout.write(JSON.stringify({status:r.status,text:await r.text()}))}catch(e){process.stdout.write(JSON.stringify({error:String(e.cause?.code??e.cause?.message??e.message),name:e.name}))}})";
|
|
44
|
+
export function nodeHttp(method, url, body) {
|
|
45
|
+
const r = spawnSync(process.execPath, ['-e', FETCH], { input: JSON.stringify({ method, url, body }), encoding: 'utf8' });
|
|
46
|
+
try { return JSON.parse(r.stdout); } catch { return { error: 'no answer' }; }
|
|
47
|
+
}
|
|
48
|
+
|
|
21
49
|
/**
|
|
22
50
|
* Run a program with the Thunder engine. `entry` is a compileCore result. Returns { status, stdout, stderr }, the way
|
|
23
51
|
* `python main.py` would end: status 0, or 1 after an error reported in Thunder words. On this thread first (fast, no
|
|
@@ -27,23 +55,23 @@ const readText = (path, cwd) => readFileSync(resolvePath(cwd, path), 'utf8');
|
|
|
27
55
|
export function runWithEngine({ entry, cwd = process.cwd() } = {}) {
|
|
28
56
|
const uses = pythonModulesUsed([entry]);
|
|
29
57
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
30
|
-
const r = runCore({ entry, cwd, deeper: true, readText });
|
|
58
|
+
const r = runCore({ entry, cwd, deeper: true, readText, store: nodeStore(cwd), http: nodeHttp });
|
|
31
59
|
return r.needsDeeperStack ? runSync({ entry, cwd }) : r;
|
|
32
60
|
}
|
|
33
61
|
|
|
34
62
|
/** The same, on the calling thread only. */
|
|
35
|
-
export function runInProcess({ entry, cwd = process.cwd(), deeper = false } = {}) { return runCore({ entry, cwd, deeper, readText }); }
|
|
63
|
+
export function runInProcess({ entry, cwd = process.cwd(), deeper = false } = {}) { return runCore({ entry, cwd, deeper, readText, store: nodeStore(cwd), http: nodeHttp }); }
|
|
36
64
|
|
|
37
65
|
/** Run every Test block, the way run_tests.py does: one line per test, then the totals. */
|
|
38
66
|
export function testWithEngine({ results, cwd = process.cwd() } = {}) {
|
|
39
67
|
const uses = pythonModulesUsed(results);
|
|
40
68
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
41
|
-
const r = testCore({ results, cwd, deeper: true, readText });
|
|
69
|
+
const r = testCore({ results, cwd, deeper: true, readText, http: nodeHttp });
|
|
42
70
|
return r.needsDeeperStack ? runSync({ results, cwd, tests: true }) : r;
|
|
43
71
|
}
|
|
44
72
|
|
|
45
73
|
/** The same, on the calling thread only. */
|
|
46
|
-
export function testInProcess({ results, cwd = process.cwd(), deeper = false } = {}) { return testCore({ results, cwd, deeper, readText }); }
|
|
74
|
+
export function testInProcess({ results, cwd = process.cwd(), deeper = false } = {}) { return testCore({ results, cwd, deeper, readText, http: nodeHttp }); }
|
|
47
75
|
|
|
48
76
|
function runSync(job) {
|
|
49
77
|
const shared = new Int32Array(new SharedArrayBuffer(4));
|
|
@@ -61,3 +89,99 @@ function runSync(job) {
|
|
|
61
89
|
}
|
|
62
90
|
}
|
|
63
91
|
|
|
92
|
+
|
|
93
|
+
const kindName = { whole: 'a whole number', number: 'a number', money: 'money', text: 'text', bool: 'yes or no', date: 'a date' };
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* thunder run --engine thunder for a program with endpoints: run its main part, then answer requests on this machine,
|
|
97
|
+
* one at a time, until stopped (Ctrl+C). The same answers, words, and statuses as compiled Python and TypeScript.
|
|
98
|
+
* Gives back a status only when it could not start.
|
|
99
|
+
*/
|
|
100
|
+
export function serveWithEngine({ entry, cwd = process.cwd() } = {}) {
|
|
101
|
+
const ready = engineForServing({ entry, cwd, readText, store: nodeStore(cwd), http: nodeHttp });
|
|
102
|
+
if (!ready.eng) return ready;
|
|
103
|
+
const { eng, mod } = ready;
|
|
104
|
+
if (ready.stdout) process.stdout.write(ready.stdout);
|
|
105
|
+
const own = (s) => !entry.info.imported?.has(s);
|
|
106
|
+
const routes = (entry.info.endpoints ?? []).filter(own).map((f) => {
|
|
107
|
+
const fromPath = new Set(f.endpoint.segments.filter((g) => g.param).map((g) => g.param));
|
|
108
|
+
return { f, method: f.endpoint.method, path: f.endpoint.path, parts: f.endpoint.path.split('/').filter(Boolean), inputs: f.params.map((p) => ({ text: p.text, py: p.py, type: p.type, path: fromPath.has(p.name), dflt: !!p.dflt })) };
|
|
109
|
+
});
|
|
110
|
+
const host = process.env.THUNDER_HOST || '127.0.0.1';
|
|
111
|
+
const port = Number(process.env.THUNDER_PORT || 8080);
|
|
112
|
+
const match = (parts, got) => {
|
|
113
|
+
if (parts.length !== got.length) return null;
|
|
114
|
+
const found = {};
|
|
115
|
+
for (let i = 0; i < parts.length; i++) {
|
|
116
|
+
const m = parts[i].match(/^\{(.+)\}$/);
|
|
117
|
+
if (m) found[m[1].trim().toLowerCase()] = decodeURIComponent(got[i]);
|
|
118
|
+
else if (parts[i] !== got[i]) return null;
|
|
119
|
+
}
|
|
120
|
+
return found;
|
|
121
|
+
};
|
|
122
|
+
const server = createServer((req, res) => {
|
|
123
|
+
const chunks = [];
|
|
124
|
+
req.on('data', (c) => chunks.push(c));
|
|
125
|
+
req.on('end', () => {
|
|
126
|
+
const flush = () => { if (eng.out.length) { process.stdout.write(eng.out.join('')); eng.out = []; } };
|
|
127
|
+
const send = (status, value, plain = false) => {
|
|
128
|
+
let data;
|
|
129
|
+
if (plain) data = JSON.stringify(value);
|
|
130
|
+
else { try { data = dataJson(value); } catch (e) { status = 500; data = JSON.stringify({ problem: explain(asPyErr(e)) }); } }
|
|
131
|
+
flush();
|
|
132
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(data) });
|
|
133
|
+
res.end(data);
|
|
134
|
+
process.stdout.write(`${req.method} ${req.url} -> ${status}\n`);
|
|
135
|
+
};
|
|
136
|
+
const problem = (status, text) => send(status, { problem: text }, true);
|
|
137
|
+
const url = new URL(req.url, 'http://localhost');
|
|
138
|
+
const got = url.pathname.split('/').filter(Boolean);
|
|
139
|
+
const query = Object.fromEntries(url.searchParams);
|
|
140
|
+
let chosen = null;
|
|
141
|
+
const methods = [];
|
|
142
|
+
for (const r of routes) {
|
|
143
|
+
const found = match(r.parts, got);
|
|
144
|
+
if (!found) continue;
|
|
145
|
+
methods.push(r.method);
|
|
146
|
+
if (r.method === req.method) chosen = { r, found };
|
|
147
|
+
}
|
|
148
|
+
if (!chosen) return methods.length ? problem(405, `${url.pathname} answers only ${methods.join(', ')}.`) : problem(404, `Nothing here answers ${req.method} ${url.pathname}.`);
|
|
149
|
+
const { r, found } = chosen;
|
|
150
|
+
let body = {};
|
|
151
|
+
const raw = Buffer.concat(chunks).toString('utf8');
|
|
152
|
+
if (raw) {
|
|
153
|
+
try { body = JSON.parse(raw); } catch { return problem(400, "The request's body is not JSON Thunder can read."); }
|
|
154
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return problem(400, "The request's body should be a JSON object, written { … }.");
|
|
155
|
+
}
|
|
156
|
+
const args = [];
|
|
157
|
+
try {
|
|
158
|
+
for (const inp of r.inputs) {
|
|
159
|
+
const key = inp.text.toLowerCase();
|
|
160
|
+
const where = `"${inp.text}"`;
|
|
161
|
+
if (inp.path) args.push(inputValue(found[key], inp.type, where, true));
|
|
162
|
+
else if (key in query || (inp.py && inp.py in query)) args.push(inputValue(key in query ? query[key] : query[inp.py], inp.type, where, true));
|
|
163
|
+
else if (inp.text in body || key in body || (inp.py && inp.py in body)) args.push(inputValue(inp.text in body ? body[inp.text] : key in body ? body[key] : body[inp.py], inp.type, where, false));
|
|
164
|
+
else if (inp.dflt) args.push(NOT_GIVEN);
|
|
165
|
+
else if (inp.type.k === 'optional') args.push(null);
|
|
166
|
+
else return problem(400, `${r.method} ${r.path} needs ${inp.text} (${kindName[inp.type.k] ?? inp.type.k}).`);
|
|
167
|
+
}
|
|
168
|
+
} catch (e) { return problem(400, explain(asPyErr(e))); }
|
|
169
|
+
let answer;
|
|
170
|
+
try { answer = eng.answer(mod, r.f, args); } catch (e0) {
|
|
171
|
+
const e = asPyErr(e0);
|
|
172
|
+
if (e.pyType === 'Stop') return problem(e.status ?? 400, explain(e));
|
|
173
|
+
if (e.pyType === 'RuleBroken') return problem(422, explain(e));
|
|
174
|
+
flush();
|
|
175
|
+
process.stderr.write(`${eng.describeError(e)}\n`);
|
|
176
|
+
return problem(500, explain(e));
|
|
177
|
+
}
|
|
178
|
+
try { eng.saveStores(mod); } catch (e0) { const e = asPyErr(e0); process.stderr.write(`${eng.describeError(e)}\n`); return problem(500, explain(e)); }
|
|
179
|
+
return send(answer.status, answer.value);
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
server.listen(port, host, () => {
|
|
183
|
+
process.stdout.write(`Thunder is answering on http://${host}:${port}\n${routes.map((r) => ` ${r.method} ${r.path}\n`).join('')}Press Ctrl+C to stop.\n`);
|
|
184
|
+
});
|
|
185
|
+
process.on('SIGINT', () => { process.stdout.write('Stopped answering.\n'); server.close(); process.exit(0); });
|
|
186
|
+
return null;
|
|
187
|
+
}
|
package/src/core/go-run.mjs
CHANGED
|
@@ -10,15 +10,16 @@ import { spawnSync } from 'node:child_process';
|
|
|
10
10
|
import { fileURLToPath } from 'node:url';
|
|
11
11
|
import { tmpdir } from 'node:os';
|
|
12
12
|
import { toGo, pythonOnlyUses, id, goStr, goNamespaces as namespaces } from './target-go.mjs';
|
|
13
|
+
import { npmRefusals, dotnetRefusals, httpRefusals } from './target-typescript.mjs';
|
|
13
14
|
import { diag } from './diagnostics.mjs';
|
|
14
15
|
|
|
15
16
|
export const GO_RUNTIME = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'runtime-go', 'thunder_runtime.go'), 'utf8');
|
|
16
17
|
|
|
17
18
|
/** TC405 for every Use in a file: Python modules exist only for the Python target. */
|
|
18
19
|
export function goDiagnostics(result) {
|
|
19
|
-
return pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
20
|
+
return [...npmRefusals(result.info, 'Go', diag), ...dotnetRefusals(result.info, 'Go', diag), ...httpRefusals(result.info, 'Go', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
20
21
|
`"${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
|
+
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
|
|
22
23
|
}
|
|
23
24
|
|
|
24
25
|
|
package/src/core/index.mjs
CHANGED
|
@@ -27,12 +27,16 @@ export const CORE_VERSION = '0.1.0';
|
|
|
27
27
|
*/
|
|
28
28
|
export function compileCore(source, { file = 'main.thunder', imported = [], srcModules = [] } = {}) {
|
|
29
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 ?? [])])
|
|
30
|
+
recordFields: imported.flatMap((r) => [...(r.program.names.recordFields ?? [])]), funcInputs: imported.flatMap((r) => [...(r.program.names.funcInputs ?? [])]),
|
|
31
|
+
alts: imported.flatMap((r) => [...(r.program.names.alts ?? [])]), altsOf: imported.flatMap((r) => [...(r.program.names.altsOf ?? [])]) } : null;
|
|
31
32
|
const program = parseCore(source, { seed });
|
|
32
33
|
const { diagnostics, info } = checkCore(program, { imported: imported.map((r) => r.info) });
|
|
33
34
|
const ok = diagnostics.length === 0;
|
|
34
35
|
const python = ok ? toPython(program, info, { source: file, imports: srcModules }) : null;
|
|
35
|
-
|
|
36
|
+
// A draft: holes (TC120) are its only problems. It never runs or builds, but nothing in it is wrong yet.
|
|
37
|
+
const holes = diagnostics.filter((d) => d.code === 'TC120');
|
|
38
|
+
const draft = holes.length > 0 && holes.length === diagnostics.length;
|
|
39
|
+
return { ok, diagnostics, python, program, info, file, holes, draft };
|
|
36
40
|
}
|
|
37
41
|
|
|
38
42
|
export function diagnosticsText(result) {
|
package/src/core/java-run.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import { writeFileSync, mkdirSync, readFileSync, rmSync, existsSync } from 'node
|
|
|
7
7
|
import { join, delimiter } from 'node:path';
|
|
8
8
|
import { spawnSync } from 'node:child_process';
|
|
9
9
|
import { toJava, javaTestRunner, javaClassName } from './target-java.mjs';
|
|
10
|
-
import { pythonOnlyUses } from './target-typescript.mjs';
|
|
10
|
+
import { pythonOnlyUses, npmRefusals, dotnetRefusals, storeRefusals, httpRefusals } from './target-typescript.mjs';
|
|
11
11
|
import { diag } from './diagnostics.mjs';
|
|
12
12
|
|
|
13
13
|
const RUNTIME_DIR = new URL('./java/thunder/', import.meta.url);
|
|
@@ -19,9 +19,9 @@ const exportedNames = (r) => [...r.info.records, ...r.info.funcs, ...r.info.cons
|
|
|
19
19
|
|
|
20
20
|
/** TC405 for every Use in a file: Python modules exist only for the Python target. */
|
|
21
21
|
export function javaDiagnostics(result) {
|
|
22
|
-
return pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
22
|
+
return [...npmRefusals(result.info, 'Java', diag), ...dotnetRefusals(result.info, 'Java', diag), ...storeRefusals(result.info, 'Java', diag), ...httpRefusals(result.info, 'Java', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
23
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.'));
|
|
24
|
+
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
/** Compile checked results to Java: { 'app/<Class>.java': text, 'app/RunTests.java': text }. */
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// What kind of .thunder file is this: a mission (a specification the compiler checks) or a Thunder Core program
|
|
2
|
+
// (code that runs)? Decided by a fixed rule, never by guessing, in this order:
|
|
3
|
+
// 1. thunder new, a thunder.toml in the file's folder or above it, or --core: a program (src/core/cli.mjs).
|
|
4
|
+
// 2. Otherwise the file's first line that is not blank or a comment decides. A mission always starts with one of
|
|
5
|
+
// the mission keywords, in lowercase, with at most a name after it ("mission Checkout", "service Billing",
|
|
6
|
+
// "use product"). A line that cannot start a mission ("say "Hello"", "Set total to 0", "To greet:",
|
|
7
|
+
// "A Trade has:", "Screen Today:", "Use csv as csv") means a program.
|
|
8
|
+
// 3. Anything that could be either (an empty file, or "use csv" alone) stays a mission, as before 1.7.
|
|
9
|
+
// Every mission written before this rule existed starts with a mission keyword, so none changes meaning.
|
|
10
|
+
|
|
11
|
+
/** The keywords a mission file's top-level blocks start with (the mission parser's own list, src/parse.mjs). */
|
|
12
|
+
export const MISSION_KEYWORDS = new Set([
|
|
13
|
+
'mission', 'note', 'goal', 'why', 'requires', 'requires_skill', 'demonstrates', 'input', 'output', 'guarantees',
|
|
14
|
+
'guarantee', 'never', 'constraints', 'invariant', 'assumptions', 'risks', 'target', 'style', 'verify', 'errors',
|
|
15
|
+
'examples', 'service', 'api', 'event', 'database', 'architecture', 'selection', 'use', 'title', 'for', 'persona',
|
|
16
|
+
'customer', 'problem', 'evidence', 'outcome', 'metric', 'scope', 'non_goal', 'owner', 'unknown', 'question',
|
|
17
|
+
'assumption', 'experience', 'pattern', 'style_intent', 'decision', 'property', 'scenario', 'evaluation',
|
|
18
|
+
'capability', 'interface', 'component', 'artifact', 'outcome_contract', 'release', 'result', 'learning', 'test',
|
|
19
|
+
'data', 'waiver', 'command', 'on', 'lifecycle', 'always', 'eventually', 'until', 'conflict', 'implement',
|
|
20
|
+
'requires_skills', 'approval', 'inferred', 'maps_to', 'needs_review', 'source', 'confidence',
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
/** The first line of `source` that is not blank or a comment, or null. */
|
|
24
|
+
export function firstCodeLine(source) {
|
|
25
|
+
for (const raw of String(source).split(/\r?\n/)) {
|
|
26
|
+
const line = raw.trim();
|
|
27
|
+
if (line && !line.startsWith('#')) return { text: line, indented: raw.length > 0 && /^\s/.test(raw) };
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 'mission' or 'program', from the file's text alone (rule 2 and 3 above), with the reason in words so a person
|
|
34
|
+
* can see why: { kind, reason }.
|
|
35
|
+
*/
|
|
36
|
+
export function fileKind(source) {
|
|
37
|
+
const first = firstCodeLine(source);
|
|
38
|
+
if (!first) return { kind: 'mission', reason: 'the file has no lines yet' };
|
|
39
|
+
const m = /^([a-z_]+)(?:\s+([A-Za-z_][\w.-]*))?\s*$/.exec(first.text);
|
|
40
|
+
if (!first.indented && m && MISSION_KEYWORDS.has(m[1])) return { kind: 'mission', reason: `its first line starts with the mission keyword "${m[1]}"` };
|
|
41
|
+
return { kind: 'program', reason: `its first line ("${first.text.length > 40 ? `${first.text.slice(0, 40)}…` : first.text}") cannot start a mission` };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A Thunder Core program (not a mission) by its path and text: a .thunder file, by the rule above. */
|
|
45
|
+
export const isCoreProgram = (path, source) => /\.thunder$/i.test(path) && fileKind(source ?? '').kind === 'program';
|