@skillstech/thunderlang 1.7.0 → 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 +75 -0
- package/README.md +10 -3
- package/dist/core.cjs +234 -20
- package/dist/index.cjs +8853 -1045
- package/dist/learn.cjs +1339 -69
- package/package.json +1 -1
- package/src/cli-main.mjs +312 -115
- package/src/core/check.mjs +312 -6
- package/src/core/cli.mjs +60 -8
- package/src/core/csharp-run.mjs +2 -2
- package/src/core/diagnostics.mjs +9 -0
- package/src/core/engine-core.mjs +141 -19
- package/src/core/engine-values.mjs +1 -0
- package/src/core/engine.mjs +131 -7
- package/src/core/go-run.mjs +2 -2
- package/src/core/index.mjs +6 -2
- package/src/core/java-run.mjs +2 -2
- package/src/core/kind.mjs +3 -0
- package/src/core/lexer.mjs +16 -2
- package/src/core/parser.mjs +200 -15
- package/src/core/project-root.mjs +18 -0
- package/src/core/project.mjs +15 -18
- package/src/core/react-run.mjs +2 -2
- package/src/core/runtime-go/thunder_runtime.go +269 -1
- package/src/core/runtime-python.mjs +365 -3
- package/src/core/runtime-typescript.mjs +150 -5
- package/src/core/rust-run.mjs +2 -2
- package/src/core/serving.mjs +12 -0
- package/src/core/store-format.mjs +110 -0
- package/src/core/target-go.mjs +10 -3
- package/src/core/target-python.mjs +38 -5
- package/src/core/target-typescript.mjs +62 -6
- package/src/core/typescript-run.mjs +6 -4
- 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/emit.mjs +1 -1
- package/src/evidence.mjs +28 -0
- package/src/examples.d.mts +21 -0
- package/src/examples.mjs +175 -0
- package/src/index.d.ts +4 -0
- package/src/index.mjs +4 -0
- package/src/mcp.mjs +42 -3
- package/src/program.d.mts +4 -0
- package/src/program.mjs +4 -0
- package/src/read-repo-fs.mjs +2 -1
- package/src/review.mjs +69 -3
- package/src/system.mjs +1 -1
- package/src/trace-cli.mjs +8 -3
- package/src/trace-fs.mjs +29 -3
- package/src/trace.mjs +23 -7
package/src/core/diagnostics.mjs
CHANGED
|
@@ -24,6 +24,7 @@ export const CODES = {
|
|
|
24
24
|
TC117: 'Lines like "name: value" with no record or function call to give them to',
|
|
25
25
|
TC118: 'A line inside a Screen is not something a screen can show',
|
|
26
26
|
TC119: '"Receive" or "Remember" is not at the top of a Screen',
|
|
27
|
+
TC120: 'A hole (?, ?number) in a draft: the program does not run until it is filled in',
|
|
27
28
|
TC201: 'Unknown name',
|
|
28
29
|
TC202: 'A name uses a word that belongs to Thunder',
|
|
29
30
|
TC203: 'A name is defined twice',
|
|
@@ -38,6 +39,11 @@ export const CODES = {
|
|
|
38
39
|
TC212: 'Unknown screen',
|
|
39
40
|
TC213: 'An input of a screen is changed',
|
|
40
41
|
TC214: 'A screen is given an input it does not have, or is missing one it needs',
|
|
42
|
+
TC215: '"Depending on" leaves out an alternative of the data type (and has no "Otherwise")',
|
|
43
|
+
TC216: 'A field only some alternatives have, read where the alternative is not known',
|
|
44
|
+
TC217: 'An alternative a data type does not have, or a value built without saying which alternative it is',
|
|
45
|
+
TC218: 'An HTTP status (Give … with status, Stop … and status) outside an endpoint',
|
|
46
|
+
TC219: 'Inside where or sorted by, a name that is both a field of each item and a value of yours (the field wins, so your value is hidden)',
|
|
41
47
|
TC301: 'Money and a plain number are mixed',
|
|
42
48
|
TC302: 'Values of different kinds are compared',
|
|
43
49
|
TC303: 'A name changes kind',
|
|
@@ -53,6 +59,8 @@ export const CODES = {
|
|
|
53
59
|
TC407: 'A step that cannot run when a button is pressed',
|
|
54
60
|
TC408: 'An npm package ("Use … from npm") can be used only when compiling to TypeScript',
|
|
55
61
|
TC409: 'A .NET library ("Use … from .NET" or "from NuGet") can be used only when compiling to C#',
|
|
62
|
+
TC410: 'A stored list ("Store … as a list of …") runs on Python, TypeScript, Go, and the Thunder engine only, for now',
|
|
63
|
+
TC411: 'An endpoint or a call to another service in a program compiled to a target without HTTP yet',
|
|
56
64
|
TC501: 'Divided by zero (runtime)',
|
|
57
65
|
TC502: 'Nothing used where a value was needed (runtime)',
|
|
58
66
|
TC503: 'A field or entry is missing (runtime)',
|
|
@@ -62,6 +70,7 @@ export const CODES = {
|
|
|
62
70
|
TC507: 'The program stopped with a message (runtime)',
|
|
63
71
|
TC508: 'Library code used through "Use" failed (runtime)',
|
|
64
72
|
TC509: 'A value could not be converted (runtime)',
|
|
73
|
+
TC510: 'A call to another service failed: it could not be reached, or it answered with a problem (runtime)',
|
|
65
74
|
};
|
|
66
75
|
|
|
67
76
|
export class CoreError extends Error {
|
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
|
|
@@ -61,7 +64,14 @@ class Engine {
|
|
|
61
64
|
// readText(path, cwd): the text of a file the program reads, or throws with .code 'ENOENT' / 'EISDIR'. Without it
|
|
62
65
|
// (a browser), reading a file is reported as a missing file.
|
|
63
66
|
// record: keep a step-by-step recording of the run (the Thunder Time Machine; see recordedRun below).
|
|
64
|
-
|
|
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;
|
|
65
75
|
this.cwd = cwd;
|
|
66
76
|
this.rec = record ? { steps: [], truncated: false } : null;
|
|
67
77
|
this.readText = readText;
|
|
@@ -70,6 +80,7 @@ class Engine {
|
|
|
70
80
|
this.deeper = deeper;
|
|
71
81
|
this.frames = [];
|
|
72
82
|
this.out = [];
|
|
83
|
+
this.budget = null; // steps left before a call is stopped (engineForCalls); null: no limit
|
|
73
84
|
}
|
|
74
85
|
|
|
75
86
|
// ── loading ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
@@ -80,6 +91,9 @@ class Engine {
|
|
|
80
91
|
for (const m of imports) for (const [k, v] of m.globals) mod.globals.set(k, v);
|
|
81
92
|
for (const r of result.info.records.filter(own)) mod.globals.set(r.py, this.recordClass(r, mod));
|
|
82
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);
|
|
83
97
|
const consts = result.info.consts.filter(own);
|
|
84
98
|
if (consts.length) {
|
|
85
99
|
const frame = { file: mod.file, line: 0 };
|
|
@@ -94,7 +108,8 @@ class Engine {
|
|
|
94
108
|
recordClass(r, mod) {
|
|
95
109
|
const rules = new Map();
|
|
96
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); }
|
|
97
|
-
|
|
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 };
|
|
98
113
|
}
|
|
99
114
|
|
|
100
115
|
// ── frames, lines, errors ───────────────────────────────────────────────────────────────────────────────────
|
|
@@ -103,7 +118,7 @@ class Engine {
|
|
|
103
118
|
this.frames.push(frame);
|
|
104
119
|
try { return fn(); }
|
|
105
120
|
catch (e) {
|
|
106
|
-
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
121
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
|
|
107
122
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
108
123
|
const err = asPyErr(e);
|
|
109
124
|
if (!err.where) err.where = this.frames.map((f) => ({ file: f.file, line: f.line }));
|
|
@@ -130,7 +145,7 @@ class Engine {
|
|
|
130
145
|
const locals = new Map();
|
|
131
146
|
const env = { mod, locals, frame };
|
|
132
147
|
f.params.forEach((p, i) => {
|
|
133
|
-
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);
|
|
134
149
|
if (v === undefined) throw TypeErr(`${f.py}() missing 1 required positional argument: '${p.py}'`);
|
|
135
150
|
locals.set(p.py, v);
|
|
136
151
|
});
|
|
@@ -142,6 +157,34 @@ class Engine {
|
|
|
142
157
|
});
|
|
143
158
|
}
|
|
144
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
|
+
|
|
145
188
|
never(rule, value, env) { V.never(this.x(rule.rule.cond, env, { subject: value }), rule.text, rule.line, value); }
|
|
146
189
|
|
|
147
190
|
newRecord(cls, given) { return V.newRecordWith((o, k, v) => this.setAttr(o, k, v), cls, given); }
|
|
@@ -190,6 +233,7 @@ class Engine {
|
|
|
190
233
|
}
|
|
191
234
|
|
|
192
235
|
stmt(s, env) {
|
|
236
|
+
if (this.budget !== null && --this.budget < 0) throw new OutOfSteps();
|
|
193
237
|
if (this.rec) return this.recordStep(s, env);
|
|
194
238
|
return this.runStmt(s, env);
|
|
195
239
|
}
|
|
@@ -248,8 +292,8 @@ class Engine {
|
|
|
248
292
|
this.storeAt(t, v, env);
|
|
249
293
|
return;
|
|
250
294
|
}
|
|
251
|
-
case 'give':
|
|
252
|
-
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; }
|
|
253
297
|
case 'if':
|
|
254
298
|
for (const b of s.branches) {
|
|
255
299
|
fr.line = b.line;
|
|
@@ -326,7 +370,7 @@ class Engine {
|
|
|
326
370
|
case 'tryFail':
|
|
327
371
|
try { this.stmt(s.stmt, env); }
|
|
328
372
|
catch (e) {
|
|
329
|
-
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
373
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
|
|
330
374
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
331
375
|
const err = asPyErr(e);
|
|
332
376
|
fr.line = L;
|
|
@@ -364,15 +408,18 @@ class Engine {
|
|
|
364
408
|
if (s.mode === 'fail') {
|
|
365
409
|
const msg = s.msg ? this.x(s.msg, env) : null;
|
|
366
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
|
|
367
412
|
V.expectFailure(() => {
|
|
368
413
|
try { this.x(s.e, env); }
|
|
369
414
|
catch (e) {
|
|
370
415
|
if (e instanceof Return) return;
|
|
371
416
|
if (e instanceof NeedsDeeperStack) throw e;
|
|
372
417
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
418
|
+
if (e instanceof OutOfSteps) outOfSteps = e;
|
|
373
419
|
throw e;
|
|
374
420
|
}
|
|
375
421
|
}, text, msg);
|
|
422
|
+
if (outOfSteps) throw outOfSteps;
|
|
376
423
|
return;
|
|
377
424
|
}
|
|
378
425
|
const actual = this.x(s.e, env);
|
|
@@ -428,6 +475,7 @@ class Engine {
|
|
|
428
475
|
case 'bool': return !!e.v;
|
|
429
476
|
case 'nothing': case 'hole': return null;
|
|
430
477
|
case 'paren': return sub2(e.e);
|
|
478
|
+
case 'httpCall': return this.httpCall(e, env);
|
|
431
479
|
case 'today': return PyDate.today();
|
|
432
480
|
case 'date': { const d = PyDate.parse(e.text); if (!d) throw new PyErr('ValueError', `Invalid isoformat string: '${e.text}'`); return d; }
|
|
433
481
|
case 'str': return this.str(e, env, ctx);
|
|
@@ -542,12 +590,33 @@ class Engine {
|
|
|
542
590
|
// ── running a program or its tests ──────────────────────────────────────────────────────────────────────────
|
|
543
591
|
runMain(mod) {
|
|
544
592
|
const main = mod.r.program.main ?? [];
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
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));
|
|
551
620
|
}
|
|
552
621
|
|
|
553
622
|
runTest(mod, t) {
|
|
@@ -574,12 +643,12 @@ function notCompiled(results) {
|
|
|
574
643
|
}
|
|
575
644
|
|
|
576
645
|
/** The same, on the calling thread (its stack allows only a few hundred nested calls). */
|
|
577
|
-
export function runInProcess({ entry, cwd, deeper = false, readText = null } = {}) {
|
|
646
|
+
export function runInProcess({ entry, cwd, deeper = false, readText = null, store = null, http = null } = {}) {
|
|
578
647
|
const broken = notCompiled([entry]);
|
|
579
648
|
if (broken) return broken;
|
|
580
649
|
const uses = pythonModulesUsed([entry]);
|
|
581
650
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
582
|
-
const eng = new Engine({ cwd, deeper, readText });
|
|
651
|
+
const eng = new Engine({ cwd, deeper, readText, store, http });
|
|
583
652
|
let stderr = '', status = 0;
|
|
584
653
|
try {
|
|
585
654
|
const mod = eng.load(entry);
|
|
@@ -592,16 +661,37 @@ export function runInProcess({ entry, cwd, deeper = false, readText = null } = {
|
|
|
592
661
|
return { status, stdout: eng.out.join(''), stderr };
|
|
593
662
|
}
|
|
594
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
|
+
|
|
595
685
|
/**
|
|
596
686
|
* Run a program and keep a step-by-step recording of it (the Thunder Time Machine, `thunder run --record`).
|
|
597
687
|
* Gives back { status, stdout, stderr, steps, truncated }. Like runInProcess, on the calling thread.
|
|
598
688
|
*/
|
|
599
|
-
export function recordedRun({ entry, cwd, readText = null } = {}) {
|
|
689
|
+
export function recordedRun({ entry, cwd, readText = null, store = null } = {}) {
|
|
600
690
|
const broken = notCompiled([entry]);
|
|
601
691
|
if (broken) return broken;
|
|
602
692
|
const uses = pythonModulesUsed([entry]);
|
|
603
693
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses, steps: [] };
|
|
604
|
-
const eng = new Engine({ cwd, readText, record: true });
|
|
694
|
+
const eng = new Engine({ cwd, readText, record: true, store });
|
|
605
695
|
let stderr = '', status = 0;
|
|
606
696
|
try {
|
|
607
697
|
const mod = eng.load(entry);
|
|
@@ -612,13 +702,45 @@ export function recordedRun({ entry, cwd, readText = null } = {}) {
|
|
|
612
702
|
return { status, stdout: eng.out.join(''), stderr, steps: eng.rec.steps, truncated: eng.rec.truncated };
|
|
613
703
|
}
|
|
614
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
|
+
|
|
615
737
|
/** The same, on the calling thread. */
|
|
616
|
-
export function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
|
|
738
|
+
export function testInProcess({ results, cwd, deeper = false, readText = null, http = null } = {}) {
|
|
617
739
|
const broken = notCompiled(results);
|
|
618
740
|
if (broken) return broken;
|
|
619
741
|
const uses = pythonModulesUsed(results);
|
|
620
742
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
621
|
-
const eng = new Engine({ cwd, deeper, readText });
|
|
743
|
+
const eng = new Engine({ cwd, deeper, readText, http });
|
|
622
744
|
const mods = [];
|
|
623
745
|
const srcMods = [];
|
|
624
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,14 +10,14 @@ 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 } from './target-typescript.mjs';
|
|
13
|
+
import { npmRefusals, dotnetRefusals, httpRefusals } from './target-typescript.mjs';
|
|
14
14
|
import { diag } from './diagnostics.mjs';
|
|
15
15
|
|
|
16
16
|
export const GO_RUNTIME = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'runtime-go', 'thunder_runtime.go'), 'utf8');
|
|
17
17
|
|
|
18
18
|
/** TC405 for every Use in a file: Python modules exist only for the Python target. */
|
|
19
19
|
export function goDiagnostics(result) {
|
|
20
|
-
return [...npmRefusals(result.info, 'Go', diag), ...dotnetRefusals(result.info, 'Go', diag), ...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,
|
|
21
21
|
`"${u.module}" is a Python module, and this program is compiled to Go, which cannot use it.`,
|
|
22
22
|
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
|
|
23
23
|
}
|
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, npmRefusals, dotnetRefusals } 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,7 +19,7 @@ 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 [...npmRefusals(result.info, 'Java', diag), ...dotnetRefusals(result.info, 'Java', diag), ...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
24
|
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
|
|
25
25
|
}
|
package/src/core/kind.mjs
CHANGED
|
@@ -40,3 +40,6 @@ export function fileKind(source) {
|
|
|
40
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
41
|
return { kind: 'program', reason: `its first line ("${first.text.length > 40 ? `${first.text.slice(0, 40)}…` : first.text}") cannot start a mission` };
|
|
42
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';
|
package/src/core/lexer.mjs
CHANGED
|
@@ -10,11 +10,11 @@
|
|
|
10
10
|
// money $200, $0.10 { t: 'money', text }
|
|
11
11
|
// percent 20%, 12.5% { t: 'percent', text }
|
|
12
12
|
// str "Hello, {name}!" (parts: strings and { tokens } holes) { t: 'str', parts }
|
|
13
|
-
// sym + - * / ( ) [ ] , : . = == != <> < <= > >=
|
|
13
|
+
// sym + - * / ( ) [ ] , : . = == != <> < <= > >= ? { t: 'sym', text } (? is a hole: ?number)
|
|
14
14
|
|
|
15
15
|
import { diag, CoreError } from './diagnostics.mjs';
|
|
16
16
|
|
|
17
|
-
const SYMS = ['==', '!=', '<>', '<=', '>=', '+', '-', '*', '/', '(', ')', '[', ']', ',', ':', '.', '=', '<', '>'];
|
|
17
|
+
const SYMS = ['==', '!=', '<>', '<=', '>=', '+', '-', '*', '/', '(', ')', '[', ']', ',', ':', '.', '=', '<', '>', '?'];
|
|
18
18
|
const WORD_START = /[\p{L}_]/u;
|
|
19
19
|
const WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
20
20
|
|
|
@@ -22,6 +22,20 @@ const WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
|
22
22
|
export function tokenizeLine(text, line, colOffset = 0) {
|
|
23
23
|
const toks = [];
|
|
24
24
|
let i = 0;
|
|
25
|
+
// When someone calls GET /habits/{name}: the path is one token (it may hold {name} parts and other characters).
|
|
26
|
+
const ep = text.match(/^(when)(\s+)(someone)(\s+)(calls)(\s+)([A-Za-z]+)(\s+)(\/\S*?)(\s*)(:)(\s*(#.*)?)$/i);
|
|
27
|
+
if (ep) {
|
|
28
|
+
let col = colOffset + 1;
|
|
29
|
+
const out = [];
|
|
30
|
+
const parts = ep.slice(1, 12);
|
|
31
|
+
parts.forEach((part, k) => {
|
|
32
|
+
if (k === 8) out.push({ t: 'path', text: part, col, line });
|
|
33
|
+
else if (k === 10) out.push({ t: 'sym', text: ':', col, line });
|
|
34
|
+
else if (part && !/^\s*$/.test(part)) out.push({ t: 'word', text: part, lower: part.toLowerCase(), col, line });
|
|
35
|
+
col += part.length;
|
|
36
|
+
});
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
25
39
|
const at = (k = 0) => text[i + k];
|
|
26
40
|
while (i < text.length) {
|
|
27
41
|
const c = at();
|