@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/dist/learn.cjs
CHANGED
|
@@ -17253,7 +17253,7 @@ var SEMANTIC_TYPES = Object.keys(SEMANTIC);
|
|
|
17253
17253
|
var PRIMITIVE_TYPES = Object.keys(PRIMITIVE);
|
|
17254
17254
|
|
|
17255
17255
|
// src/emit.mjs
|
|
17256
|
-
var COMPILER_VERSION = "1.
|
|
17256
|
+
var COMPILER_VERSION = "1.8.0";
|
|
17257
17257
|
|
|
17258
17258
|
// src/lift.mjs
|
|
17259
17259
|
var IR_SCHEMA_VERSION = "0.1.0";
|
|
@@ -21973,16 +21973,16 @@ function powershellReading(src, file = "") {
|
|
|
21973
21973
|
KNOWN_FNS2 = /* @__PURE__ */ new Set();
|
|
21974
21974
|
return out;
|
|
21975
21975
|
}
|
|
21976
|
-
function psThings(src, file, { words: w, kindWords:
|
|
21976
|
+
function psThings(src, file, { words: w, kindWords: kindWords4, startValue: startValue2 }) {
|
|
21977
21977
|
const { things } = powershellReading(src, file);
|
|
21978
21978
|
const norm3 = (v) => String(v ?? "").trim().replace(/^@\(\s*\)$/, "[]").replace(/^@\{\s*\}$/, "{}").replace(/^\$null$/i, "null").replace(/^\$true$/i, "true").replace(/^\$false$/i, "false").replace(/^'(.*)'$/, '"$1"');
|
|
21979
21979
|
const kind = (t) => {
|
|
21980
21980
|
const x = String(t ?? "").toLowerCase();
|
|
21981
21981
|
if (!x) return null;
|
|
21982
|
-
if (/\[\]$/.test(x)) return
|
|
21982
|
+
if (/\[\]$/.test(x)) return kindWords4(`List<${String(t).slice(0, -2).replace(/^string$/i, "string").replace(/^int$/i, "int")}>`);
|
|
21983
21983
|
if (/(?:arraylist|list|collection|hashset)(?:\[|$)/.test(x)) return "a list";
|
|
21984
21984
|
if (/^(?:hashtable|dictionary|ordered)/.test(x)) return "a lookup table";
|
|
21985
|
-
return
|
|
21985
|
+
return kindWords4(/^(int|int32|int64|long|double|decimal|float)$/.test(x) ? "int" : /^(string|char)$/.test(x) ? "string" : /^(bool|boolean|switch)$/.test(x) ? "bool" : /^datetime$/.test(x) ? "DateTime" : String(t).split(".").pop());
|
|
21986
21986
|
};
|
|
21987
21987
|
return things.map((t) => ({
|
|
21988
21988
|
kind: t.kind,
|
|
@@ -23551,7 +23551,7 @@ function rReading(src, file = "") {
|
|
|
23551
23551
|
KNOWN_FNS3 = /* @__PURE__ */ new Set();
|
|
23552
23552
|
return { fns, things: r.things.map(({ _methods, ...t }) => t), errors: [...r.errors].map(([name, line]) => ({ name, line })), tests: r.tests };
|
|
23553
23553
|
}
|
|
23554
|
-
function rThings(src, file, { words: w, kindWords:
|
|
23554
|
+
function rThings(src, file, { words: w, kindWords: kindWords4, startValue: startValue2 }) {
|
|
23555
23555
|
const norm3 = (v) => String(v ?? "").trim().replace(/^(?:list|c|character|numeric|integer|logical|vector)\(\s*(?:0)?\s*\)$/, "[]").replace(/^NULL$/, "null").replace(/^NA$/, "null").replace(/^TRUE$/, "true").replace(/^FALSE$/, "false").replace(/^(\d+)L$/, "$1").replace(/^'(.*)'$/, '"$1"');
|
|
23556
23556
|
return rReading(src, file).things.map((t) => ({
|
|
23557
23557
|
kind: t.kind,
|
|
@@ -23561,7 +23561,7 @@ function rThings(src, file, { words: w, kindWords: kindWords3, startValue: start
|
|
|
23561
23561
|
...t.doc ? { doc: t.doc } : {},
|
|
23562
23562
|
choices: t.choices,
|
|
23563
23563
|
memberRanges: t.memberRanges,
|
|
23564
|
-
knows: t.knows.map((k) => ({ name: k.name, label: w(k.name.replace(/\./g, "_")), kind: k.type ?
|
|
23564
|
+
knows: t.knows.map((k) => ({ name: k.name, label: w(k.name.replace(/\./g, "_")), kind: k.type ? kindWords4(k.type) : null, start: k.start == null || k.start === "" ? null : typeof k.start === "object" ? k.start.param == null ? "given when it starts" : `${startValue2(norm3(k.start.param))?.replace(/ at first$/, "")} unless told otherwise` : startValue2(norm3(k.start)), line: k.line }))
|
|
23565
23565
|
}));
|
|
23566
23566
|
}
|
|
23567
23567
|
|
|
@@ -28456,9 +28456,9 @@ function goDoc(src, at2, name) {
|
|
|
28456
28456
|
const t = d.replace(new RegExp(`^${name}\\s+(?:is|holds|represents)\\s+`), "").replace(new RegExp(`^${name}\\s+`), "");
|
|
28457
28457
|
return t.charAt(0).toUpperCase() + t.slice(1);
|
|
28458
28458
|
}
|
|
28459
|
-
function makeThingReaders({ words: words13, kindWords:
|
|
28459
|
+
function makeThingReaders({ words: words13, kindWords: kindWords4, startValue: startValue2 }) {
|
|
28460
28460
|
const know = (name, type, start, params, line = null) => {
|
|
28461
|
-
const kind = type ?
|
|
28461
|
+
const kind = type ? kindWords4(type) : null;
|
|
28462
28462
|
const said = start != null && start !== "" ? /^new\(\)$/.test(String(start).trim()) && !/^(a list|a lookup table|a set)/.test(kind ?? "") ? "worked out when it starts" : startValue2(start, params) : null;
|
|
28463
28463
|
return { name, label: words13(name.replace(/^[_$]+|_$/g, "")), kind, start: said, line };
|
|
28464
28464
|
};
|
|
@@ -35304,12 +35304,25 @@ function lev(a, b) {
|
|
|
35304
35304
|
}
|
|
35305
35305
|
|
|
35306
35306
|
// src/core/lexer.mjs
|
|
35307
|
-
var SYMS = ["==", "!=", "<>", "<=", ">=", "+", "-", "*", "/", "(", ")", "[", "]", ",", ":", ".", "=", "<", ">"];
|
|
35307
|
+
var SYMS = ["==", "!=", "<>", "<=", ">=", "+", "-", "*", "/", "(", ")", "[", "]", ",", ":", ".", "=", "<", ">", "?"];
|
|
35308
35308
|
var WORD_START = /[\p{L}_]/u;
|
|
35309
35309
|
var WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
35310
35310
|
function tokenizeLine(text2, line, colOffset = 0) {
|
|
35311
35311
|
const toks2 = [];
|
|
35312
35312
|
let i = 0;
|
|
35313
|
+
const ep = text2.match(/^(when)(\s+)(someone)(\s+)(calls)(\s+)([A-Za-z]+)(\s+)(\/\S*?)(\s*)(:)(\s*(#.*)?)$/i);
|
|
35314
|
+
if (ep) {
|
|
35315
|
+
let col = colOffset + 1;
|
|
35316
|
+
const out = [];
|
|
35317
|
+
const parts = ep.slice(1, 12);
|
|
35318
|
+
parts.forEach((part, k) => {
|
|
35319
|
+
if (k === 8) out.push({ t: "path", text: part, col, line });
|
|
35320
|
+
else if (k === 10) out.push({ t: "sym", text: ":", col, line });
|
|
35321
|
+
else if (part && !/^\s*$/.test(part)) out.push({ t: "word", text: part, lower: part.toLowerCase(), col, line });
|
|
35322
|
+
col += part.length;
|
|
35323
|
+
});
|
|
35324
|
+
return out;
|
|
35325
|
+
}
|
|
35313
35326
|
const at2 = (k = 0) => text2[i + k];
|
|
35314
35327
|
while (i < text2.length) {
|
|
35315
35328
|
const c = at2();
|
|
@@ -35614,6 +35627,9 @@ function collectNames(nodes, names) {
|
|
|
35614
35627
|
} else if (w0 === "keep") {
|
|
35615
35628
|
const k = splitTop4(ts, (t) => isWord(t, "at"));
|
|
35616
35629
|
add2("const", stripArticle(ts.slice(1, k < 0 ? ts.length : k)));
|
|
35630
|
+
} else if (w0 === "store" && ts.some((t) => isWord(t, "as"))) {
|
|
35631
|
+
const k = splitTop4(ts, (t) => isWord(t, "as"));
|
|
35632
|
+
add2("const", stripArticle(ts.slice(1, k)));
|
|
35617
35633
|
} else if (w0 === "receive") {
|
|
35618
35634
|
for (const p of paramGroups(ts.slice(1))) add2("var", p.words);
|
|
35619
35635
|
} else if (w0 === "for" && isWord(ts[1], "each")) {
|
|
@@ -35632,6 +35648,29 @@ function collectNames(nodes, names) {
|
|
|
35632
35648
|
for (const p of paramGroups(c.tokens.slice(1))) inputs.push({ key: keyOf(p.words), text: p.words.map((x) => x.text).join(" "), defaultTokens: p.defaultTokens });
|
|
35633
35649
|
}
|
|
35634
35650
|
names.funcInputs.set(keyOf(ts.slice(1, -1)), inputs);
|
|
35651
|
+
} else if ((w0 === "a" || w0 === "an") && isOneOf(ts)) {
|
|
35652
|
+
const words13 = ts.slice(1, -4);
|
|
35653
|
+
add2("record", words13);
|
|
35654
|
+
const own = ["which"];
|
|
35655
|
+
const alts = [];
|
|
35656
|
+
for (const c of n.children) {
|
|
35657
|
+
const at2 = c.tokens.findIndex((t) => isWord(t, "with"));
|
|
35658
|
+
const altWords = stripArticle(at2 < 0 ? c.tokens : c.tokens.slice(0, at2));
|
|
35659
|
+
if (altWords.length) {
|
|
35660
|
+
alts.push(keyOf(altWords));
|
|
35661
|
+
names.alts.set(keyOf(altWords), [...names.alts.get(keyOf(altWords)) ?? [], keyOf(words13)]);
|
|
35662
|
+
}
|
|
35663
|
+
if (at2 >= 0) {
|
|
35664
|
+
for (const g of paramGroups(c.tokens.slice(at2 + 1))) if (g.words.length) {
|
|
35665
|
+
names.fields.add(keyOf(g.words));
|
|
35666
|
+
own.push(keyOf(g.words));
|
|
35667
|
+
}
|
|
35668
|
+
}
|
|
35669
|
+
}
|
|
35670
|
+
names.fields.add("which");
|
|
35671
|
+
names.recordFields.set(keyOf(words13), [...new Set(own)]);
|
|
35672
|
+
names.recordText.set(keyOf(words13), words13.map((x) => x.text).join(" "));
|
|
35673
|
+
names.altsOf.set(keyOf(words13), alts);
|
|
35635
35674
|
} else if ((w0 === "a" || w0 === "an") && isWord(ts[ts.length - 2], "has")) {
|
|
35636
35675
|
const words13 = ts.slice(1, -2);
|
|
35637
35676
|
add2("record", words13);
|
|
@@ -35672,6 +35711,10 @@ function rememberName(ts) {
|
|
|
35672
35711
|
const end2 = ts.findIndex((t) => isWord(t, "as") || isWord(t, "starting") || isSym(t, ","));
|
|
35673
35712
|
return stripArticle(end2 < 0 ? ts : ts.slice(0, end2));
|
|
35674
35713
|
}
|
|
35714
|
+
function isOneOf(ts) {
|
|
35715
|
+
const n = ts.length;
|
|
35716
|
+
return n >= 6 && isSym(ts[n - 1], ":") && isWord(ts[n - 2], "of") && isWord(ts[n - 3], "one") && isWord(ts[n - 4], "is");
|
|
35717
|
+
}
|
|
35675
35718
|
function paramGroups(ts) {
|
|
35676
35719
|
const groups3 = [];
|
|
35677
35720
|
let cur = [];
|
|
@@ -35834,6 +35877,15 @@ var ExprParser = class {
|
|
|
35834
35877
|
}
|
|
35835
35878
|
if (s.word("in")) return wrap2({ k: "contains", l: this.add(s, o), r: l, line });
|
|
35836
35879
|
if (s.done()) s.fail('Something is missing after "is".', "For example: is 10, is at least 18, is nothing, is empty.", "TC108");
|
|
35880
|
+
if (this.names.alts?.size && s.peek()?.t === "word") {
|
|
35881
|
+
const run = [];
|
|
35882
|
+
for (let j = s.i; s.ts[j]?.t === "word" && !RESERVED2.has(s.ts[j].lower); j++) run.push(s.ts[j]);
|
|
35883
|
+
const ak = this.longest(run, (key) => this.names.alts.has(key));
|
|
35884
|
+
if (ak && !this.longest(run, (key) => this.names.known.has(key))) {
|
|
35885
|
+
s.i += ak;
|
|
35886
|
+
return wrap2({ k: "isAlt", e: l, alt: keyOf(run.slice(0, ak)), text: run.slice(0, ak).map((x) => x.text).join(" "), line });
|
|
35887
|
+
}
|
|
35888
|
+
}
|
|
35837
35889
|
return { k: "cmp", op: neg2 ? "!=" : "==", l, r: this.add(s, o), line };
|
|
35838
35890
|
}
|
|
35839
35891
|
return l;
|
|
@@ -35988,9 +36040,50 @@ var ExprParser = class {
|
|
|
35988
36040
|
const key = keyOf(run.slice(0, k));
|
|
35989
36041
|
return { k: "record", name: this.names.records.has(key) ? key : key.replace(/s$/, "") };
|
|
35990
36042
|
}
|
|
36043
|
+
/** The fields a record is built with: with name "Ann" and balance $10 (none without "with"). */
|
|
36044
|
+
recordFields(s, line) {
|
|
36045
|
+
const fields = [];
|
|
36046
|
+
if (s.word("with")) {
|
|
36047
|
+
do {
|
|
36048
|
+
const fr = this.wordRun(s);
|
|
36049
|
+
if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, "TC108");
|
|
36050
|
+
const fk = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
|
|
36051
|
+
s.i -= fr.length - fk;
|
|
36052
|
+
fields.push({ name: keyOf(fr.slice(0, fk)), text: fr.slice(0, fk).map((x) => x.text).join(" "), e: this.expr(s, { noAnd: true }), line });
|
|
36053
|
+
} while ((isSym(s.peek(), ",") || isWord(s.peek(), "and")) && this.fieldAhead(s, 1) && s.next());
|
|
36054
|
+
}
|
|
36055
|
+
return fields;
|
|
36056
|
+
}
|
|
35991
36057
|
primary(s, o) {
|
|
35992
36058
|
const t = s.peek();
|
|
35993
36059
|
const line = s.line;
|
|
36060
|
+
const METHODS2 = ["get", "post", "put", "patch", "delete"];
|
|
36061
|
+
if (isWord(t, "answer") && isWord(s.peek(1), "from") && METHODS2.includes(s.peek(2)?.lower)) {
|
|
36062
|
+
s.i += 2;
|
|
36063
|
+
const method = s.next().text.toUpperCase();
|
|
36064
|
+
const url = this.primary(s, { ...o, noAnd: true });
|
|
36065
|
+
let body2 = null, as = null;
|
|
36066
|
+
if (s.word("with")) {
|
|
36067
|
+
body2 = this.expr(s, { ...o, noAnd: true });
|
|
36068
|
+
if (body2.k === "conv" && body2.type) {
|
|
36069
|
+
as = body2.type;
|
|
36070
|
+
body2 = body2.e;
|
|
36071
|
+
}
|
|
36072
|
+
}
|
|
36073
|
+
if (!as && s.word("as")) as = this.typeRef(s);
|
|
36074
|
+
return { k: "httpCall", method, url, body: body2, as, line };
|
|
36075
|
+
}
|
|
36076
|
+
if (isWord(t, "calling") && METHODS2.includes(s.peek(1)?.lower) && isSym(s.peek(2), "/")) {
|
|
36077
|
+
s.i += 2;
|
|
36078
|
+
const method = s.ts[s.i - 1].text.toUpperCase();
|
|
36079
|
+
let path = "";
|
|
36080
|
+
let prev = null;
|
|
36081
|
+
while (s.peek() && (prev === null ? isSym(s.peek(), "/") : s.peek().col === prev.col + String(prev.text).length && (isSym(s.peek(), "/") || isSym(s.peek(), "-") || s.peek().t === "word" || s.peek().t === "num"))) {
|
|
36082
|
+
prev = s.next();
|
|
36083
|
+
path += prev.text;
|
|
36084
|
+
}
|
|
36085
|
+
return { k: "callEndpoint", method, path, fields: this.recordFields(s, line), line };
|
|
36086
|
+
}
|
|
35994
36087
|
if (!t) s.fail("A value is missing at the end of this line.", null, "TC108");
|
|
35995
36088
|
if (t.t === "num") {
|
|
35996
36089
|
s.next();
|
|
@@ -36010,6 +36103,13 @@ var ExprParser = class {
|
|
|
36010
36103
|
s.next();
|
|
36011
36104
|
return { k: "str", parts: t.parts.map((p) => typeof p === "string" ? p : { e: this.parse(p.tokens, line), source: p.source }), line };
|
|
36012
36105
|
}
|
|
36106
|
+
if (isSym(t, "?")) {
|
|
36107
|
+
s.next();
|
|
36108
|
+
const next = s.peek();
|
|
36109
|
+
let want = null;
|
|
36110
|
+
if (next && next.t === "word" && t.col != null && next.col === t.col + 1) want = this.typeRef(s);
|
|
36111
|
+
return { k: "draftHole", want, line, col: t.col };
|
|
36112
|
+
}
|
|
36013
36113
|
if (isSym(t, "(")) {
|
|
36014
36114
|
s.next();
|
|
36015
36115
|
const e = this.expr(s, {});
|
|
@@ -36095,22 +36195,31 @@ var ExprParser = class {
|
|
|
36095
36195
|
}
|
|
36096
36196
|
if (RESERVED2.has(w)) s.fail(`"${t.text}" is a Thunder word and can't start a value here.`, null, "TC105");
|
|
36097
36197
|
const run = this.wordRun(s);
|
|
36198
|
+
if (o.article && this.names.alts?.size) {
|
|
36199
|
+
for (let i = 1; i < run.length; i++) {
|
|
36200
|
+
const alt = keyOf(run.slice(0, i));
|
|
36201
|
+
const recs = this.names.alts.get(alt);
|
|
36202
|
+
if (!recs) continue;
|
|
36203
|
+
const rk = this.longest(run.slice(i), (key) => recs.includes(key));
|
|
36204
|
+
if (!rk || i + rk !== run.length) continue;
|
|
36205
|
+
s.i -= run.length - i - rk;
|
|
36206
|
+
const node = { k: "new", record: keyOf(run.slice(i, i + rk)), alt, altText: run.slice(0, i).map((x) => x.text).join(" "), fields: this.recordFields(s, line), line };
|
|
36207
|
+
return node;
|
|
36208
|
+
}
|
|
36209
|
+
for (let i = 1; i < run.length; i++) {
|
|
36210
|
+
const rk = this.longest(run.slice(i), (key) => this.names.altsOf.has(key));
|
|
36211
|
+
if (!rk || i + rk !== run.length) continue;
|
|
36212
|
+
s.i -= run.length - i - rk;
|
|
36213
|
+
return { k: "new", record: keyOf(run.slice(i, i + rk)), alt: keyOf(run.slice(0, i)), altText: run.slice(0, i).map((x) => x.text).join(" "), fields: this.recordFields(s, line), line };
|
|
36214
|
+
}
|
|
36215
|
+
}
|
|
36098
36216
|
let off = run[0]?.lower === "new" && run.length > 1 ? 1 : 0;
|
|
36099
36217
|
const recK = this.longest(run.slice(off), (key) => this.names.records.has(key));
|
|
36100
36218
|
const wantsRecord = o.article || off || isWord(s.peek(), "with") || !this.longest(run, (key) => this.names.known.has(key));
|
|
36101
36219
|
if (recK && wantsRecord && recK + off === run.length) {
|
|
36102
36220
|
s.i -= run.length - off - recK;
|
|
36103
36221
|
const name = keyOf(run.slice(off, off + recK));
|
|
36104
|
-
const fields =
|
|
36105
|
-
if (s.word("with")) {
|
|
36106
|
-
do {
|
|
36107
|
-
const fr = this.wordRun(s);
|
|
36108
|
-
if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, "TC108");
|
|
36109
|
-
const fk2 = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
|
|
36110
|
-
s.i -= fr.length - fk2;
|
|
36111
|
-
fields.push({ name: keyOf(fr.slice(0, fk2)), text: fr.slice(0, fk2).map((x) => x.text).join(" "), e: this.expr(s, { noAnd: true }), line });
|
|
36112
|
-
} while ((isSym(s.peek(), ",") || isWord(s.peek(), "and")) && this.fieldAhead(s, 1) && s.next());
|
|
36113
|
-
}
|
|
36222
|
+
const fields = this.recordFields(s, line);
|
|
36114
36223
|
const node = { k: "new", record: name, fields, line };
|
|
36115
36224
|
if (!fields.length && this.open) this.open.push(node);
|
|
36116
36225
|
return node;
|
|
@@ -36145,7 +36254,7 @@ var ExprParser = class {
|
|
|
36145
36254
|
function parseCore(source, { seed = null } = {}) {
|
|
36146
36255
|
const { lines, diagnostics } = lex3(source);
|
|
36147
36256
|
const tree = buildBlocks(lines, diagnostics);
|
|
36148
|
-
const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []), recordFields: new Map(seed?.recordFields ?? []), funcInputs: new Map(seed?.funcInputs ?? []), recordText: /* @__PURE__ */ new Map(), screens: /* @__PURE__ */ new Map() };
|
|
36257
|
+
const names = { known: new Map(seed?.known ?? []), fields: new Set(seed?.fields ?? []), records: new Set(seed?.records ?? []), recordFields: new Map(seed?.recordFields ?? []), funcInputs: new Map(seed?.funcInputs ?? []), recordText: /* @__PURE__ */ new Map(), screens: /* @__PURE__ */ new Map(), alts: new Map(seed?.alts ?? []), altsOf: new Map(seed?.altsOf ?? []) };
|
|
36149
36258
|
collectNames(tree, names);
|
|
36150
36259
|
const ep = new ExprParser(names);
|
|
36151
36260
|
const body2 = parseBlock(tree, ep, names, diagnostics, { top: true });
|
|
@@ -36178,12 +36287,12 @@ function parseBlock(nodes, ep, names, diagnostics, ctx) {
|
|
|
36178
36287
|
}
|
|
36179
36288
|
return out;
|
|
36180
36289
|
}
|
|
36181
|
-
var BLOCK_STATEMENTS = /* @__PURE__ */ new Set(["when", "if", "otherwise", "for", "repeat", "to", "test", "receive", "never", "use", "screen"]);
|
|
36290
|
+
var BLOCK_STATEMENTS = /* @__PURE__ */ new Set(["when", "if", "otherwise", "for", "repeat", "to", "test", "receive", "never", "use", "screen", "depending"]);
|
|
36182
36291
|
function fieldBlock(n, diagnostics = []) {
|
|
36183
36292
|
const ts = n.tokens;
|
|
36184
36293
|
if (!n.children.length || !isSym(ts[ts.length - 1], ":")) return null;
|
|
36185
36294
|
const w0 = ts[0]?.t === "word" ? ts[0].lower : "";
|
|
36186
|
-
if (BLOCK_STATEMENTS.has(w0) || (w0 === "a" || w0 === "an") && isWord(ts[ts.length - 2], "has")) return null;
|
|
36295
|
+
if (BLOCK_STATEMENTS.has(w0) || (w0 === "a" || w0 === "an") && (isWord(ts[ts.length - 2], "has") || isOneOf(ts))) return null;
|
|
36187
36296
|
return n.children.map((c) => {
|
|
36188
36297
|
const colon = c.tokens.findIndex((t) => isSym(t, ":"));
|
|
36189
36298
|
const nameTs = colon > 0 ? c.tokens.slice(0, colon) : [];
|
|
@@ -36276,6 +36385,26 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36276
36385
|
};
|
|
36277
36386
|
const w0 = ts[0].t === "word" ? ts[0].lower : "";
|
|
36278
36387
|
const rest2 = ts.slice(1);
|
|
36388
|
+
if (w0 === "when" && isWord(ts[1], "someone") && isWord(ts[2], "calls") && ts[4]?.t === "path") {
|
|
36389
|
+
if (!ctx.top) fail2("TC402", 'An endpoint ("When someone calls \u2026") must be written at the left edge, not inside another block.');
|
|
36390
|
+
const method = ts[3].text.toUpperCase();
|
|
36391
|
+
const path = ts[4].text;
|
|
36392
|
+
const segments = path.split("/").filter(Boolean).map((seg) => {
|
|
36393
|
+
const m = seg.match(/^\{([^{}]+)\}$/);
|
|
36394
|
+
return m ? { param: m[1].trim().toLowerCase(), text: m[1].trim() } : { lit: seg };
|
|
36395
|
+
});
|
|
36396
|
+
const kids2 = n.children;
|
|
36397
|
+
const params = [];
|
|
36398
|
+
let r = 0;
|
|
36399
|
+
while (kids2[r] && isWord(kids2[r].tokens[0], "receive")) {
|
|
36400
|
+
const kid = kids2[r];
|
|
36401
|
+
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords2(p.raw, kid.line, '"Receive"'), type: p.typeTokens ? typeOf(ep, p.typeTokens, kid.line) : null, dflt: p.defaultTokens ? ep.parse(p.defaultTokens, kid.line) : null, line: kid.line })));
|
|
36402
|
+
r++;
|
|
36403
|
+
}
|
|
36404
|
+
const words13 = ["answer", method.toLowerCase(), ...segments.map((g) => g.param ? g.param : g.lit.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()).filter(Boolean)];
|
|
36405
|
+
const name = words13.join(" ");
|
|
36406
|
+
return { k: "func", name, text: `${method} ${path}`, params, body: parseBlock(kids2.slice(r), ep, names, diagnostics, { inFunc: true, inEndpoint: true }), line, endpoint: { method, path, segments, line } };
|
|
36407
|
+
}
|
|
36279
36408
|
if (w0 === "say" || w0 === "print") return { k: "say", e: E(rest2), line };
|
|
36280
36409
|
if (w0 === "set") {
|
|
36281
36410
|
const at2 = splitTop4(rest2, (t) => isWord(t, "to"));
|
|
@@ -36286,20 +36415,37 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36286
36415
|
if (!["name", "field", "at"].includes(target.k)) fail2("TC305", "Only a name, a field (customer's balance), or an entry (counts at word) can be set.");
|
|
36287
36416
|
return { k: "set", target, e: E(rest2.slice(at2 + 1)), line };
|
|
36288
36417
|
}
|
|
36418
|
+
if (w0 === "store" && rest2.some((t) => isWord(t, "as"))) {
|
|
36419
|
+
if (!ctx.top) fail2("TC402", 'A "Store" line must be written at the left edge of the file.');
|
|
36420
|
+
const as = splitTop4(rest2, (t) => isWord(t, "as"));
|
|
36421
|
+
const typeTokens = stripArticle(rest2.slice(as + 1));
|
|
36422
|
+
if (!typeTokens.length) fail2("TC108", "Write what the store holds: Store habits as a list of Habit.");
|
|
36423
|
+
return { k: "store", ...nameWords2(rest2.slice(0, as), line, '"Store"'), type: typeOf(ep, typeTokens, line), line };
|
|
36424
|
+
}
|
|
36289
36425
|
if (w0 === "keep") {
|
|
36290
36426
|
const at2 = splitTop4(rest2, (t) => isWord(t, "at"));
|
|
36291
36427
|
if (at2 < 0) fail2("TC108", '"Keep" needs "at": Keep tax rate at 7%.');
|
|
36292
36428
|
return { k: "keep", ...nameWords2(rest2.slice(0, at2), line, '"Keep"'), e: E(rest2.slice(at2 + 1)), line };
|
|
36293
36429
|
}
|
|
36430
|
+
const statusAt = (r, joiner) => {
|
|
36431
|
+
const n2 = r.length;
|
|
36432
|
+
if (n2 >= 3 && isWord(r[n2 - 3], joiner) && isWord(r[n2 - 2], "status") && r[n2 - 1].t === "num") {
|
|
36433
|
+
if (joiner === "with" && !ctx.inEndpoint) fail2("TC218", `"with status" sets the HTTP status of an endpoint's answer, so it goes inside "When someone calls \u2026".`, "Outside an endpoint, Give the value; the endpoint that gives it sets the status.");
|
|
36434
|
+
return { status: Number(r[n2 - 1].text), r: r.slice(0, -3) };
|
|
36435
|
+
}
|
|
36436
|
+
return { status: null, r };
|
|
36437
|
+
};
|
|
36294
36438
|
if (w0 === "give") {
|
|
36295
36439
|
let r = rest2;
|
|
36296
36440
|
if (isWord(r[0], "back")) r = r.slice(1);
|
|
36297
|
-
|
|
36441
|
+
const st = statusAt(r, "with");
|
|
36442
|
+
return { k: "give", e: st.r.length ? E(st.r) : { k: "nothing", line }, status: st.status, line };
|
|
36298
36443
|
}
|
|
36299
36444
|
if (w0 === "stop") {
|
|
36300
36445
|
let r = rest2;
|
|
36301
36446
|
if (isWord(r[0], "with") || isSym(r[0], ":")) r = r.slice(1);
|
|
36302
|
-
|
|
36447
|
+
const st = statusAt(r, "and");
|
|
36448
|
+
return { k: "stop", e: st.r.length ? E(st.r) : { k: "str", parts: ["Stopped"], line }, status: st.status, line };
|
|
36303
36449
|
}
|
|
36304
36450
|
if (w0 === "if" && keyOf(ts.slice(0, 3)) === "if this fails") {
|
|
36305
36451
|
header();
|
|
@@ -36308,6 +36454,28 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36308
36454
|
siblings.pop();
|
|
36309
36455
|
return { k: "tryFail", stmt: prev, handler: children(), line };
|
|
36310
36456
|
}
|
|
36457
|
+
if (w0 === "depending" && isWord(ts[1], "on")) {
|
|
36458
|
+
const subject = E(header().slice(2));
|
|
36459
|
+
const cases = [];
|
|
36460
|
+
let otherwise = null;
|
|
36461
|
+
for (const c of n.children) {
|
|
36462
|
+
try {
|
|
36463
|
+
const ct = c.tokens;
|
|
36464
|
+
if (!isSym(ct[ct.length - 1], ":") || ct.length < 2) throw new CoreError(diag("TC108", c.line, 'Under "Depending on", each case is an alternative and a colon, for example: Successful:'));
|
|
36465
|
+
const sub2 = parseBlock(c.children, ep, names, diagnostics, ctx);
|
|
36466
|
+
if (ct.length === 2 && isWord(ct[0], "otherwise")) {
|
|
36467
|
+
otherwise = sub2;
|
|
36468
|
+
continue;
|
|
36469
|
+
}
|
|
36470
|
+
const { name, text: text2 } = nameWords2(ct.slice(0, -1), c.line, "A case");
|
|
36471
|
+
cases.push({ alt: name, text: text2, body: sub2, line: c.line });
|
|
36472
|
+
} catch (e2) {
|
|
36473
|
+
if (e2 instanceof CoreError) diagnostics.push(e2.diagnostic);
|
|
36474
|
+
else throw e2;
|
|
36475
|
+
}
|
|
36476
|
+
}
|
|
36477
|
+
return { k: "depending", subject, cases, otherwise, line };
|
|
36478
|
+
}
|
|
36311
36479
|
if (w0 === "when" || w0 === "if") {
|
|
36312
36480
|
const cond = E(header().slice(1));
|
|
36313
36481
|
return { k: "if", branches: [{ cond, body: children(), line }], otherwise: null, line };
|
|
@@ -36374,6 +36542,33 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36374
36542
|
}
|
|
36375
36543
|
if (w0 === "remember") fail2("TC119", '"Remember" goes at the top of a "Screen", after its "Receive" lines.', "A function keeps nothing between calls; a screen remembers values while it is shown.");
|
|
36376
36544
|
if (w0 === "show") fail2("TC118", '"Show" is used inside a "Screen" (a screen shows things). In a program, write: Say \u2026');
|
|
36545
|
+
if ((w0 === "a" || w0 === "an") && isOneOf(ts)) {
|
|
36546
|
+
if (!ctx.top) fail2("TC402", 'A data type ("A \u2026 is one of:") must be written at the left edge, not inside another block.');
|
|
36547
|
+
const { name, text: text2 } = nameWords2(ts.slice(1, -4), line, "A data type");
|
|
36548
|
+
const alts = [];
|
|
36549
|
+
for (const c of n.children) {
|
|
36550
|
+
try {
|
|
36551
|
+
const at2 = c.tokens.findIndex((t) => isWord(t, "with"));
|
|
36552
|
+
const alt = nameWords2(at2 < 0 ? c.tokens : c.tokens.slice(0, at2), c.line, "An alternative");
|
|
36553
|
+
const fields2 = [];
|
|
36554
|
+
if (at2 >= 0) {
|
|
36555
|
+
for (const g of paramGroups(c.tokens.slice(at2 + 1))) {
|
|
36556
|
+
if (!g.typeTokens) throw new CoreError(diag("TC108", c.line, `Write each field with its kind: ${alt.text} with ${g.words.map((x) => x.text).join(" ") || "amount"} as money.`));
|
|
36557
|
+
fields2.push({ ...nameWords2(g.raw, c.line, "A field"), type: typeOf(ep, g.typeTokens, c.line), line: c.line });
|
|
36558
|
+
}
|
|
36559
|
+
}
|
|
36560
|
+
alts.push({ ...alt, fields: fields2, line: c.line });
|
|
36561
|
+
} catch (e2) {
|
|
36562
|
+
if (e2 instanceof CoreError) diagnostics.push(e2.diagnostic);
|
|
36563
|
+
else throw e2;
|
|
36564
|
+
}
|
|
36565
|
+
}
|
|
36566
|
+
if (!alts.length) fail2("TC108", `Write the alternatives under it, one per line, for example: Successful with amount as money.`);
|
|
36567
|
+
const opt2 = (t) => t.k === "optional" ? t : { k: "optional", of: t };
|
|
36568
|
+
const fields = [{ name: "which", text: "which", type: { k: "text" }, line, hidden: true }];
|
|
36569
|
+
for (const a of alts) for (const f of a.fields) if (!fields.some((x) => x.name === f.name)) fields.push({ ...f, type: opt2(f.type) });
|
|
36570
|
+
return { k: "record", name, text: text2, fields, rules: [], alts, line };
|
|
36571
|
+
}
|
|
36377
36572
|
if ((w0 === "a" || w0 === "an") && isWord(ts[ts.length - 2], "has") && isSym(ts[ts.length - 1], ":")) {
|
|
36378
36573
|
if (!ctx.top) fail2("TC402", 'A record ("A \u2026 has:") must be written at the left edge, not inside another block.');
|
|
36379
36574
|
const { name, text: text2 } = nameWords2(ts.slice(1, -2), line, "A record");
|
|
@@ -36810,8 +37005,9 @@ var Checker = class {
|
|
|
36810
37005
|
this.rules = [];
|
|
36811
37006
|
this.mainNames = /* @__PURE__ */ new Map();
|
|
36812
37007
|
this.elem = [];
|
|
36813
|
-
this.info = { records: [], funcs: [], consts: [], modules: [], tests: [], rules: [], screens: [], usesDecimal: false };
|
|
37008
|
+
this.info = { records: [], funcs: [], consts: [], stores: [], endpoints: [], usesHttp: false, modules: [], tests: [], rules: [], screens: [], usesDecimal: false };
|
|
36814
37009
|
this.screens = /* @__PURE__ */ new Map();
|
|
37010
|
+
this.narrow = [];
|
|
36815
37011
|
}
|
|
36816
37012
|
err(code3, line, msg, hint) {
|
|
36817
37013
|
this.d.push(diag(code3, line, msg, hint));
|
|
@@ -36853,6 +37049,7 @@ var Checker = class {
|
|
|
36853
37049
|
}
|
|
36854
37050
|
}
|
|
36855
37051
|
for (const s of top) if (s.k === "record") this.checkRecordShape(s);
|
|
37052
|
+
this.info.endpointsAll = [...top.filter((s) => s.k === "func" && s.endpoint), ...(this.imported ?? []).flatMap((inf) => inf.endpoints ?? [])];
|
|
36856
37053
|
collectMainNames(top, this.mainNames);
|
|
36857
37054
|
for (const s of top) {
|
|
36858
37055
|
if (s.k !== "keep") continue;
|
|
@@ -36860,6 +37057,24 @@ var Checker = class {
|
|
|
36860
37057
|
this.declare(s, "const", s.line, { py: pyName(s.name, "upper"), type: t });
|
|
36861
37058
|
this.info.consts.push(s);
|
|
36862
37059
|
}
|
|
37060
|
+
for (const s of top) {
|
|
37061
|
+
if (s.k !== "store") continue;
|
|
37062
|
+
const t = s.type;
|
|
37063
|
+
const rec = t?.k === "list" && t.of?.k === "record" ? this.records.get(t.of.name) : null;
|
|
37064
|
+
if (!rec) {
|
|
37065
|
+
this.err("TC306", s.line, `A store holds a list of records, for example: Store habits as a list of Habit.`, 'Describe the record with "A Habit has:", then store a list of it.');
|
|
37066
|
+
continue;
|
|
37067
|
+
}
|
|
37068
|
+
const plain = (ft) => ft && (["whole", "number", "money", "text", "bool", "date"].includes(ft.k) || ft.k === "optional" && plain(ft.of));
|
|
37069
|
+
const bad = rec.fields.find((f) => !plain(f.type));
|
|
37070
|
+
if (bad) {
|
|
37071
|
+
this.err("TC306", s.line, `"${rec.text ?? rec.name}" can't be stored yet: its field "${bad.text ?? bad.name}" is not a plain value.`, "A stored record's fields are whole numbers, numbers, money, text, yes/no, dates, or one of those or nothing.");
|
|
37072
|
+
continue;
|
|
37073
|
+
}
|
|
37074
|
+
s.record = rec;
|
|
37075
|
+
this.declare(s, "store", s.line, { py: pyName(s.name, "upper"), type: { k: "list", of: { k: "record", name: rec.name, text: rec.text } } });
|
|
37076
|
+
this.info.stores.push(s);
|
|
37077
|
+
}
|
|
36863
37078
|
for (const s of top) if (s.k === "never") this.addRule(s, null);
|
|
36864
37079
|
for (const r of this.records.values()) for (const rule of r.rules) this.addRule(rule, r);
|
|
36865
37080
|
for (const s of top) if (s.k === "func") this.checkFunc(s);
|
|
@@ -36877,7 +37092,7 @@ var Checker = class {
|
|
|
36877
37092
|
if (needs.length) this.err("TC214", first.line, `"${first.text}" is the first screen, where the app starts, so nothing gives it ${needs.map((p) => p.text).join(", ")}.`, `Put the screen the app starts on first, or give ${needs.length === 1 ? "the input" : "each input"} a value for when it isn't given: Receive ${needs[0].text} (\u2026 if not given).`);
|
|
36878
37093
|
const main = new Scope2(this.global, "main");
|
|
36879
37094
|
this.mainScope = main;
|
|
36880
|
-
const mainBody = top.filter((s) => !["record", "func", "use", "keep", "never", "test", "screen"].includes(s.k));
|
|
37095
|
+
const mainBody = top.filter((s) => !["record", "func", "use", "keep", "store", "never", "test", "screen"].includes(s.k));
|
|
36881
37096
|
this.block(mainBody, main, {});
|
|
36882
37097
|
this.p.main = mainBody;
|
|
36883
37098
|
this.info.records = [...this.records.values()];
|
|
@@ -36918,6 +37133,98 @@ var Checker = class {
|
|
|
36918
37133
|
this.resolveType(f.type, f.line);
|
|
36919
37134
|
r.fieldMap.set(f.name, f);
|
|
36920
37135
|
}
|
|
37136
|
+
if (r.alts) this.checkAlternatives(r);
|
|
37137
|
+
}
|
|
37138
|
+
/** A data type with alternatives: each alternative's fields, one kind per field name, and no field called "which". */
|
|
37139
|
+
/**
|
|
37140
|
+
* Depending on payment: one case per alternative (or Otherwise). A missing alternative is reported at this line.
|
|
37141
|
+
* Then it runs as If payment is successful … Otherwise if payment is declined …, with the value read once per test.
|
|
37142
|
+
*/
|
|
37143
|
+
depending(s, sc, ctx) {
|
|
37144
|
+
const line = s.line;
|
|
37145
|
+
const t = this.ex(s.subject, sc);
|
|
37146
|
+
const r = t.k === "record" ? this.records.get(t.name) : null;
|
|
37147
|
+
const name = s.subject.k === "name" ? s.subject.name : null;
|
|
37148
|
+
const bodies = () => {
|
|
37149
|
+
for (const c of s.cases) this.block(c.body, sc, ctx);
|
|
37150
|
+
if (s.otherwise) this.block(s.otherwise, sc, ctx);
|
|
37151
|
+
};
|
|
37152
|
+
if (!r?.altMap) {
|
|
37153
|
+
if (known(t)) this.err("TC305", line, `"Depending on" chooses by the alternative a value is, but this is ${typeWords4(t)}, not a data type with alternatives.`, "For other values, use When \u2026 / Otherwise when \u2026.");
|
|
37154
|
+
bodies();
|
|
37155
|
+
s.k = "if";
|
|
37156
|
+
s.branches = [];
|
|
37157
|
+
return;
|
|
37158
|
+
}
|
|
37159
|
+
if (!["name", "field"].includes(s.subject.k)) this.err("TC305", line, `"Depending on" reads its value once for each case, so give it a name first.`, `Set result to \u2026, then write: Depending on result:`);
|
|
37160
|
+
const seen = /* @__PURE__ */ new Set();
|
|
37161
|
+
for (const c of s.cases) {
|
|
37162
|
+
if (!r.altMap.has(c.alt)) {
|
|
37163
|
+
this.err("TC217", c.line, `A ${r.text} is ${this.altList(r)}; "${c.text}" isn't one of them.`);
|
|
37164
|
+
this.block(c.body, sc, ctx);
|
|
37165
|
+
continue;
|
|
37166
|
+
}
|
|
37167
|
+
if (seen.has(c.alt)) this.err("TC203", c.line, `"${c.text}" already has a case above.`);
|
|
37168
|
+
seen.add(c.alt);
|
|
37169
|
+
if (name) this.narrow.push({ name, alt: c.alt });
|
|
37170
|
+
try {
|
|
37171
|
+
this.block(c.body, sc, ctx);
|
|
37172
|
+
} finally {
|
|
37173
|
+
if (name) this.narrow.pop();
|
|
37174
|
+
}
|
|
37175
|
+
}
|
|
37176
|
+
if (s.otherwise) this.block(s.otherwise, sc, ctx);
|
|
37177
|
+
const missing = [...r.altMap.values()].filter((a) => !seen.has(a.name));
|
|
37178
|
+
if (missing.length && !s.otherwise) {
|
|
37179
|
+
const ws = missing.map((a) => a.text.toLowerCase());
|
|
37180
|
+
this.err(
|
|
37181
|
+
"TC215",
|
|
37182
|
+
line,
|
|
37183
|
+
`"Depending on ${s.subject.text ?? "this"}" doesn't say what to do when it is ${ws.length <= 2 ? ws.join(" or ") : `${ws.slice(0, -1).join(", ")}, or ${ws[ws.length - 1]}`}.`,
|
|
37184
|
+
`Add ${missing.map((a) => `"${a.text}:"`).join(" and ")} with what to do, or "Otherwise:" for every case not listed.`
|
|
37185
|
+
);
|
|
37186
|
+
}
|
|
37187
|
+
const cases = s.cases.filter((c) => r.altMap.has(c.alt));
|
|
37188
|
+
Object.assign(s, { k: "if", branches: cases.map((c) => ({ cond: this.altTest(s.subject, r, c.alt, false, c.line), body: c.body, line: c.line })), otherwise: s.otherwise });
|
|
37189
|
+
}
|
|
37190
|
+
checkAlternatives(r) {
|
|
37191
|
+
r.altMap = /* @__PURE__ */ new Map();
|
|
37192
|
+
for (const a of r.alts) {
|
|
37193
|
+
if (r.altMap.has(a.name)) this.err("TC203", a.line, `${r.text} already has an alternative "${a.text}".`);
|
|
37194
|
+
a.fieldMap = /* @__PURE__ */ new Map();
|
|
37195
|
+
for (const f of a.fields) {
|
|
37196
|
+
if (f.name === "which") {
|
|
37197
|
+
this.err("TC203", f.line, `"which" is the name Thunder gives to the alternative a ${r.text} is, so a field can't be called that.`, "Give the field another name.");
|
|
37198
|
+
continue;
|
|
37199
|
+
}
|
|
37200
|
+
if (a.fieldMap.has(f.name)) this.err("TC203", f.line, `${a.text} already has a field "${f.text}".`);
|
|
37201
|
+
f.py = pyName(f.name);
|
|
37202
|
+
this.resolveType(f.type, f.line);
|
|
37203
|
+
const shared = r.fieldMap.get(f.name);
|
|
37204
|
+
const plain = (t) => t.k === "optional" ? t.of : t;
|
|
37205
|
+
if (shared && known(f.type) && known(shared.type) && !sameKind(plain(shared.type), plain(f.type))) {
|
|
37206
|
+
this.err("TC303", f.line, `"${f.text}" is ${typeWords4(plain(shared.type))} in another alternative of ${r.text}, so here it can't be ${typeWords4(plain(f.type))}.`, "Use one kind for a field name in every alternative, or give the fields different names.");
|
|
37207
|
+
}
|
|
37208
|
+
a.fieldMap.set(f.name, f);
|
|
37209
|
+
}
|
|
37210
|
+
r.altMap.set(a.name, a);
|
|
37211
|
+
}
|
|
37212
|
+
}
|
|
37213
|
+
/** The alternatives of a data type, as a person reads them: successful, declined, or pending. */
|
|
37214
|
+
altList(r, joiner = "or") {
|
|
37215
|
+
const ws = [...r.altMap.values()].map((a) => a.text.toLowerCase());
|
|
37216
|
+
return ws.length <= 2 ? ws.join(` ${joiner} `) : `${ws.slice(0, -1).join(", ")}, ${joiner} ${ws[ws.length - 1]}`;
|
|
37217
|
+
}
|
|
37218
|
+
/** The alternative a name is known to be here (inside its case, or after "If x is …"), or null. */
|
|
37219
|
+
narrowed(e) {
|
|
37220
|
+
if (e.k !== "name") return null;
|
|
37221
|
+
for (let i = this.narrow.length - 1; i >= 0; i--) if (this.narrow[i].name === e.name) return this.narrow[i].alt;
|
|
37222
|
+
return null;
|
|
37223
|
+
}
|
|
37224
|
+
/** "x is successful", as the program runs it: x's which equals "successful". */
|
|
37225
|
+
altTest(subject, r, alt, neg2, line) {
|
|
37226
|
+
const which = { k: "field", obj: subject, name: "which", text: "which", py: "which", static: true, line, type: { k: "text" } };
|
|
37227
|
+
return { k: "cmp", op: neg2 ? "!=" : "==", l: which, r: { k: "str", parts: [alt], line, type: { k: "text" } }, line, type: { k: "bool" } };
|
|
36921
37228
|
}
|
|
36922
37229
|
resolveType(t, line) {
|
|
36923
37230
|
if (!t) return;
|
|
@@ -36984,7 +37291,90 @@ var Checker = class {
|
|
|
36984
37291
|
rulesFor(key) {
|
|
36985
37292
|
return this.rules.filter((r) => r.watchesVar && r.subject === key);
|
|
36986
37293
|
}
|
|
37294
|
+
/**
|
|
37295
|
+
* An endpoint (When someone calls GET /habits/{name}:): a known method, one per method and path, every {part} of
|
|
37296
|
+
* the path received, and inputs of kinds a request can carry (an input with no kind is text).
|
|
37297
|
+
*/
|
|
37298
|
+
checkEndpoint(f) {
|
|
37299
|
+
const ep = f.endpoint;
|
|
37300
|
+
const line = ep.line;
|
|
37301
|
+
if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(ep.method)) this.err("TC108", line, `"${ep.method}" isn't an HTTP method Thunder answers.`, "Use GET, POST, PUT, PATCH, or DELETE.");
|
|
37302
|
+
this.routes ??= /* @__PURE__ */ new Map();
|
|
37303
|
+
const key = `${ep.method} /${ep.segments.map((g) => g.param ? "{}" : g.lit).join("/")}`;
|
|
37304
|
+
if (this.routes.has(key) && this.routes.get(key).path !== ep.path) this.err("TC203", line, `${ep.method} ${ep.path} is answered already, by ${ep.method} ${this.routes.get(key).path} (line ${this.routes.get(key).line}).`, "Each method and path is answered by one endpoint.");
|
|
37305
|
+
else if (!this.routes.has(key)) this.routes.set(key, ep);
|
|
37306
|
+
const plain = (t) => t && (["whole", "number", "money", "text", "bool", "date"].includes(t.k) || t.k === "optional" && plain(t.of));
|
|
37307
|
+
for (const p of f.params) {
|
|
37308
|
+
if (!p.type) p.type = { k: "text" };
|
|
37309
|
+
if (!plain(p.type)) this.err("TC306", p.line, `"${p.text}" can't come from a request: it is ${typeWords4(p.type)}.`, "An endpoint receives whole numbers, numbers, money, text, yes/no, dates, or optional ones of those. Receive a record's fields one by one.");
|
|
37310
|
+
}
|
|
37311
|
+
for (const g of ep.segments.filter((x) => x.param)) {
|
|
37312
|
+
const p = f.params.find((x) => x.name === g.param);
|
|
37313
|
+
if (!p) this.err("TC207", line, `The path has {${g.text}}, but the endpoint doesn't receive "${g.text}".`, `Add: Receive ${g.text} as text (or the kind it is).`);
|
|
37314
|
+
else g.py = pyName(p.name);
|
|
37315
|
+
}
|
|
37316
|
+
this.info.endpoints.push(f);
|
|
37317
|
+
}
|
|
37318
|
+
/** calling GET /habits/walk with name "run": the endpoint that answers it, called directly with those inputs. */
|
|
37319
|
+
callEndpoint(e, sc, o) {
|
|
37320
|
+
const segs = e.path.split("/").filter(Boolean);
|
|
37321
|
+
const f = this.info.endpointsAll?.find((x) => x.endpoint.method === e.method && x.endpoint.segments.length === segs.length && x.endpoint.segments.every((g, i) => g.param || g.lit === segs[i]));
|
|
37322
|
+
if (!f) {
|
|
37323
|
+
const known2 = (this.info.endpointsAll ?? []).map((x) => `${x.endpoint.method} ${x.endpoint.path}`);
|
|
37324
|
+
this.err("TC207", e.line, `Nothing in this program answers ${e.method} ${e.path}.`, known2.length ? `Endpoints: ${known2.join(", ")}.` : "Write one: When someone calls GET /habits:");
|
|
37325
|
+
for (const fl of e.fields) this.ex(fl.e, sc, o);
|
|
37326
|
+
return UNKNOWN;
|
|
37327
|
+
}
|
|
37328
|
+
const given = /* @__PURE__ */ new Map();
|
|
37329
|
+
f.endpoint.segments.forEach((g, i) => {
|
|
37330
|
+
if (g.param) given.set(g.param, this.pathValue(segs[i], f.params.find((p) => p.name === g.param), e.line));
|
|
37331
|
+
});
|
|
37332
|
+
for (const fl of e.fields) {
|
|
37333
|
+
if (!f.params.some((p) => p.name === fl.name)) {
|
|
37334
|
+
this.err("TC207", e.line, `${f.endpoint.method} ${f.endpoint.path} doesn't receive "${fl.text}".`, `It receives: ${f.params.map((p) => p.text).join(", ") || "nothing"}.`);
|
|
37335
|
+
continue;
|
|
37336
|
+
}
|
|
37337
|
+
if (given.has(fl.name)) {
|
|
37338
|
+
this.err("TC203", e.line, `"${fl.text}" is already given by the path.`);
|
|
37339
|
+
continue;
|
|
37340
|
+
}
|
|
37341
|
+
given.set(fl.name, fl.e);
|
|
37342
|
+
}
|
|
37343
|
+
const args = [];
|
|
37344
|
+
const last = f.params.reduce((k, p, i) => given.has(p.name) ? i : k, -1);
|
|
37345
|
+
f.params.forEach((p, i) => {
|
|
37346
|
+
if (given.has(p.name)) {
|
|
37347
|
+
args.push(given.get(p.name));
|
|
37348
|
+
return;
|
|
37349
|
+
}
|
|
37350
|
+
if (p.dflt) {
|
|
37351
|
+
if (i < last) args.push(JSON.parse(JSON.stringify(p.dflt)));
|
|
37352
|
+
return;
|
|
37353
|
+
}
|
|
37354
|
+
if (p.type?.k === "optional") {
|
|
37355
|
+
if (i < last) args.push({ k: "nothing", line: e.line });
|
|
37356
|
+
return;
|
|
37357
|
+
}
|
|
37358
|
+
this.err("TC207", e.line, `${f.endpoint.method} ${f.endpoint.path} needs "${p.text}".`, `Give it: calling ${e.method} ${e.path} with ${p.text} \u2026.`);
|
|
37359
|
+
});
|
|
37360
|
+
Object.assign(e, { k: "call", name: f.name, text: f.text, args });
|
|
37361
|
+
return this.call(e, sc, o);
|
|
37362
|
+
}
|
|
37363
|
+
/** A part of a path written in a test (walk, 3) as the value its input receives. */
|
|
37364
|
+
pathValue(text2, p, line) {
|
|
37365
|
+
const k = p?.type?.k === "optional" ? p.type.of.k : p?.type?.k;
|
|
37366
|
+
if ((k === "whole" || k === "number") && /^-?\d+(\.\d+)?$/.test(text2)) return { k: "num", text: text2, whole: !text2.includes("."), line };
|
|
37367
|
+
if (k === "money" && /^\d+(\.\d+)?$/.test(text2)) return { k: "money", text: text2, line };
|
|
37368
|
+
if (k === "bool" && /^(yes|no|true|false)$/i.test(text2)) return { k: "bool", v: /^(yes|true)$/i.test(text2), line };
|
|
37369
|
+
if (k === "date" && /^\d{4}-\d{2}-\d{2}$/.test(text2)) return { k: "date", text: text2, line };
|
|
37370
|
+
if (k && k !== "text") this.err("TC303", line, `"${text2}" in the path isn't ${typeWords4(p.type)}, which "${p.text}" is.`);
|
|
37371
|
+
return { k: "str", parts: [decodeURIComponent(text2)], line };
|
|
37372
|
+
}
|
|
37373
|
+
checkStatus(n, line, [lo, hi], what) {
|
|
37374
|
+
if (!(n >= lo && n <= hi)) this.err("TC303", line, `${what} ${n}: ${what.startsWith("Give") ? "an answer that worked" : "a request that could not be done"} has a status from ${lo} to ${hi}.`, what.startsWith("Give") ? 'For example 200 (done) or 201 (created). To say no, use Stop with "\u2026" and status 404.' : "For example 400 (bad request), 404 (not found), or 409 (conflict).");
|
|
37375
|
+
}
|
|
36987
37376
|
checkFunc(f) {
|
|
37377
|
+
if (f.endpoint) this.checkEndpoint(f);
|
|
36988
37378
|
const sc = new Scope2(this.global, "func");
|
|
36989
37379
|
sc.func = f;
|
|
36990
37380
|
f.gives = [];
|
|
@@ -37047,15 +37437,25 @@ var Checker = class {
|
|
|
37047
37437
|
}
|
|
37048
37438
|
const t = this.ex(s.e, sc);
|
|
37049
37439
|
sc.func ? sc.func.gives.push(t) : findFunc(sc)?.gives.push(t);
|
|
37440
|
+
if (s.status != null) this.checkStatus(s.status, line, [200, 299], "Give \u2026 with status");
|
|
37050
37441
|
return;
|
|
37051
37442
|
}
|
|
37052
37443
|
case "stop":
|
|
37053
37444
|
this.ex(s.e, sc);
|
|
37445
|
+
if (s.status != null) this.checkStatus(s.status, line, [400, 599], "Stop \u2026 and status");
|
|
37054
37446
|
return;
|
|
37447
|
+
case "depending":
|
|
37448
|
+
return this.depending(s, sc, ctx);
|
|
37055
37449
|
case "if":
|
|
37056
37450
|
for (const b of s.branches) {
|
|
37451
|
+
const c = b.cond.k === "isAlt" && b.cond.e.k === "name" ? { name: b.cond.e.name, alt: b.cond.alt } : null;
|
|
37057
37452
|
this.cond(b.cond, sc);
|
|
37058
|
-
|
|
37453
|
+
if (c && b.cond.k === "cmp") this.narrow.push(c);
|
|
37454
|
+
try {
|
|
37455
|
+
this.block(b.body, sc, ctx);
|
|
37456
|
+
} finally {
|
|
37457
|
+
if (c && b.cond.k === "cmp") this.narrow.pop();
|
|
37458
|
+
}
|
|
37059
37459
|
}
|
|
37060
37460
|
if (s.otherwise) this.block(s.otherwise, sc, ctx);
|
|
37061
37461
|
return;
|
|
@@ -37322,6 +37722,10 @@ var Checker = class {
|
|
|
37322
37722
|
const tgt = s.target;
|
|
37323
37723
|
if (tgt.k === "name") {
|
|
37324
37724
|
const g = this.global.vars.get(tgt.name);
|
|
37725
|
+
if (g && g.kind === "store") {
|
|
37726
|
+
this.err("TC205", line, `"${tgt.text}" is a stored list (line ${g.line}): change its items, don't replace it.`, `Use Add \u2026 to ${tgt.text}, Remove \u2026 from ${tgt.text}, or Set ${tgt.text} at <position> to \u2026.`);
|
|
37727
|
+
return;
|
|
37728
|
+
}
|
|
37325
37729
|
if (g && g.kind === "const") {
|
|
37326
37730
|
this.err("TC205", line, `"${tgt.text}" is kept at a fixed value (line ${g.line}), so it can't be set.`, "Use a different name for a value that changes, or change the Keep line.");
|
|
37327
37731
|
return;
|
|
@@ -37352,6 +37756,7 @@ var Checker = class {
|
|
|
37352
37756
|
}
|
|
37353
37757
|
} else {
|
|
37354
37758
|
const tt = this.ex(tgt, sc);
|
|
37759
|
+
if (tgt.k === "field" && tgt.name === "which" && tgt.obj.type?.k === "record" && this.records.get(tgt.obj.type.name)?.altMap) this.err("TC205", line, `Which alternative a ${tgt.obj.type.text ?? "value"} is can't be changed.`, "Build a new one instead: Set payment to a declined Payment with \u2026.");
|
|
37355
37760
|
this.lvalue(tgt, sc, line);
|
|
37356
37761
|
if (known(tt) && known(tv) && !compatible(tt, tv)) this.err("TC303", line, `${tgt.k === "field" ? `The field "${tgt.text}"` : "This entry"} holds ${typeWords4(tt)}, so it can't be set to ${typeWords4(tv)}.`);
|
|
37357
37762
|
}
|
|
@@ -37450,6 +37855,46 @@ var Checker = class {
|
|
|
37450
37855
|
return T("nothing");
|
|
37451
37856
|
case "hole":
|
|
37452
37857
|
return e.type ?? UNKNOWN;
|
|
37858
|
+
case "draftHole":
|
|
37859
|
+
return this.draftHole(e, sc);
|
|
37860
|
+
case "callEndpoint":
|
|
37861
|
+
return this.callEndpoint(e, sc, o);
|
|
37862
|
+
case "httpCall": {
|
|
37863
|
+
this.info.usesHttp = true;
|
|
37864
|
+
const ut = this.ex(e.url, sc, o);
|
|
37865
|
+
if (known(ut) && ut.k !== "text") this.err("TC305", line, `The address to call is text ("https://\u2026"), but this is ${typeWords4(ut)}.`);
|
|
37866
|
+
if (e.body) this.ex(e.body, sc, o);
|
|
37867
|
+
if (!e.as) return T("text");
|
|
37868
|
+
this.resolveType(e.as, line);
|
|
37869
|
+
const rec = e.as.k === "record" ? this.records.get(e.as.name) : e.as.k === "list" && e.as.of?.k === "record" ? this.records.get(e.as.of.name) : null;
|
|
37870
|
+
const plain = (t) => t && (["whole", "number", "money", "text", "bool", "date"].includes(t.k) || t.k === "optional" && plain(t.of));
|
|
37871
|
+
if (!rec) {
|
|
37872
|
+
this.err("TC306", line, `An answer is read as a record or a list of records, for example: as Rate, as list of Rate.`, 'Without "as", the answer is its text.');
|
|
37873
|
+
return UNKNOWN;
|
|
37874
|
+
}
|
|
37875
|
+
const bad = rec.fields.find((f) => !plain(f.type));
|
|
37876
|
+
if (bad) {
|
|
37877
|
+
this.err("TC306", line, `An answer can't be read as ${rec.text} yet: its field "${bad.text}" is not a plain value.`);
|
|
37878
|
+
return UNKNOWN;
|
|
37879
|
+
}
|
|
37880
|
+
e.record = rec;
|
|
37881
|
+
return e.as;
|
|
37882
|
+
}
|
|
37883
|
+
case "isAlt": {
|
|
37884
|
+
const t = this.ex(e.e, sc, o);
|
|
37885
|
+
const r = t.k === "record" ? this.records.get(t.name) : null;
|
|
37886
|
+
if (!r?.altMap) {
|
|
37887
|
+
if (known(t)) this.err("TC305", line, `"is ${e.text}" asks which alternative a value is, but this is ${typeWords4(t)}, not a data type with alternatives.`);
|
|
37888
|
+
return T("bool");
|
|
37889
|
+
}
|
|
37890
|
+
if (!r.altMap.has(e.alt)) {
|
|
37891
|
+
this.err("TC217", line, `A ${r.text} is ${this.altList(r)}; "${e.text}" isn't one of them.`);
|
|
37892
|
+
return T("bool");
|
|
37893
|
+
}
|
|
37894
|
+
const neg2 = e.neg;
|
|
37895
|
+
Object.assign(e, this.altTest(e.e, r, e.alt, false, line));
|
|
37896
|
+
return T("bool");
|
|
37897
|
+
}
|
|
37453
37898
|
case "today":
|
|
37454
37899
|
case "date":
|
|
37455
37900
|
return T("date");
|
|
@@ -37477,6 +37922,19 @@ var Checker = class {
|
|
|
37477
37922
|
case "field": {
|
|
37478
37923
|
const ot = this.ex(e.obj, sc, o);
|
|
37479
37924
|
const r = ot.k === "record" ? this.records.get(ot.name) : null;
|
|
37925
|
+
if (r?.altMap && e.name !== "which" && r.fieldMap.has(e.name)) {
|
|
37926
|
+
const alt = this.narrowed(e.obj);
|
|
37927
|
+
const a = alt ? r.altMap.get(alt) : null;
|
|
37928
|
+
const owners = [...r.altMap.values()].filter((x) => x.fieldMap.has(e.name));
|
|
37929
|
+
const f = a?.fieldMap.get(e.name);
|
|
37930
|
+
e.py = r.fieldMap.get(e.name).py;
|
|
37931
|
+
e.static = true;
|
|
37932
|
+
if (f) return f.type;
|
|
37933
|
+
const who = owners.map((x) => x.text.toLowerCase()).join(" or ");
|
|
37934
|
+
if (a) this.err("TC216", line, `A ${a.text.toLowerCase()} ${r.text} has no ${e.text}; only a ${who} one does.`, `Fields of a ${a.text.toLowerCase()} ${r.text}: ${[...a.fieldMap.keys()].join(", ") || "none"}.`);
|
|
37935
|
+
else this.err("TC216", line, `Only a ${who} ${r.text} has ${/^[aeiou]/i.test(e.text) ? "an" : "a"} ${e.text}, and here it could be any of them.`, e.obj.k === "name" ? `Check which it is first: put this under "Depending on ${e.obj.text}:" in the ${owners[0]?.text ?? ""} case, or under "If ${e.obj.text} is ${owners[0]?.text.toLowerCase() ?? ""}:".` : `Set it to a name first, then check which it is with "Depending on \u2026:".`);
|
|
37936
|
+
return UNKNOWN;
|
|
37937
|
+
}
|
|
37480
37938
|
if (r) {
|
|
37481
37939
|
const f = r.fieldMap.get(e.name);
|
|
37482
37940
|
if (!f) {
|
|
@@ -37630,7 +38088,13 @@ var Checker = class {
|
|
|
37630
38088
|
return this.arith(e.op, l, r, line);
|
|
37631
38089
|
}
|
|
37632
38090
|
case "cmp": {
|
|
37633
|
-
const l = this.ex(e.l, sc, o)
|
|
38091
|
+
const l = this.ex(e.l, sc, o);
|
|
38092
|
+
const lr = l.k === "record" ? this.records.get(l.name) : null;
|
|
38093
|
+
if (lr?.altMap && e.r.k === "name" && !sc.get(e.r.name) && !this.global.vars.get(e.r.name)) {
|
|
38094
|
+
this.err("TC217", line, `A ${lr.text} is ${this.altList(lr)}; "${e.r.text}" isn't one of them.`);
|
|
38095
|
+
return T("bool");
|
|
38096
|
+
}
|
|
38097
|
+
const r = this.ex(e.r, sc, o);
|
|
37634
38098
|
this.comparable(l, r, line, e.op);
|
|
37635
38099
|
return T("bool");
|
|
37636
38100
|
}
|
|
@@ -37667,6 +38131,11 @@ var Checker = class {
|
|
|
37667
38131
|
if (el) {
|
|
37668
38132
|
const r = el.type.k === "record" ? this.records.get(el.type.name) : null;
|
|
37669
38133
|
if (r && r.fieldMap.has(e.name)) {
|
|
38134
|
+
const shadowed = sc.get(e.name);
|
|
38135
|
+
if (shadowed && ["param", "input", "var", "item", "state"].includes(shadowed.kind) && !el.reported?.has(e.name)) {
|
|
38136
|
+
(el.reported ??= /* @__PURE__ */ new Set()).add(e.name);
|
|
38137
|
+
this.err("TC219", e.line, `Here "${e.text}" means each ${r.text}'s ${e.text}, so your own "${e.text}"${shadowed.line ? ` (line ${shadowed.line})` : ""} isn't used.`, `Give your value another name, for example "wanted ${e.text}", and write: where ${e.text} is wanted ${e.text}.`);
|
|
38138
|
+
}
|
|
37670
38139
|
const f = r.fieldMap.get(e.name);
|
|
37671
38140
|
e.ref = { kind: "elemField", py: f.py };
|
|
37672
38141
|
return f.type;
|
|
@@ -37717,6 +38186,9 @@ var Checker = class {
|
|
|
37717
38186
|
return UNKNOWN;
|
|
37718
38187
|
}
|
|
37719
38188
|
e.py = f.py;
|
|
38189
|
+
e.args.forEach((a, k) => {
|
|
38190
|
+
if (a.k === "draftHole" && !a.want && f.params[k]?.type) a.expected = f.params[k].type;
|
|
38191
|
+
});
|
|
37720
38192
|
const ts = e.args.map((a) => this.ex(a, sc, o));
|
|
37721
38193
|
const required = f.params.filter((p) => !p.dflt).length;
|
|
37722
38194
|
if (ts.length < required || ts.length > f.params.length) {
|
|
@@ -37732,6 +38204,81 @@ var Checker = class {
|
|
|
37732
38204
|
});
|
|
37733
38205
|
return entry3?.ret ?? UNKNOWN;
|
|
37734
38206
|
}
|
|
38207
|
+
/**
|
|
38208
|
+
* A hole in a draft (TC120): what kind of value it needs (written, or expected where it stands) and what is
|
|
38209
|
+
* available here with that kind. Thunder asks; it never chooses a value. The hole has its kind, so nothing else on
|
|
38210
|
+
* the line is reported because of it.
|
|
38211
|
+
*/
|
|
38212
|
+
/** a successful Payment with amount $5: the alternative's own fields, all it needs, and "which" set for it. */
|
|
38213
|
+
newAlternative(e, r, sc, o) {
|
|
38214
|
+
const ty = T("record", { name: r.name, text: r.text });
|
|
38215
|
+
const a = e.alt ? r.altMap.get(e.alt) : null;
|
|
38216
|
+
if (!a) {
|
|
38217
|
+
for (const f of e.fields) this.ex(f.e, sc, o);
|
|
38218
|
+
const kinds = [...r.altMap.values()].map((x) => `a ${x.text.toLowerCase()} ${r.text}`);
|
|
38219
|
+
if (e.alt) this.err("TC217", e.line, `A ${r.text} is ${this.altList(r)}; "${e.altText}" isn't one of them.`);
|
|
38220
|
+
else this.err("TC217", e.line, `Say which ${r.text} it is: ${kinds.length <= 2 ? kinds.join(" or ") : `${kinds.slice(0, -1).join(", ")}, or ${kinds[kinds.length - 1]}`}.`, `For example: ${kinds[0]}${r.alts[0]?.fields.length ? " with \u2026" : ""}.`);
|
|
38221
|
+
return ty;
|
|
38222
|
+
}
|
|
38223
|
+
const given = /* @__PURE__ */ new Set();
|
|
38224
|
+
for (const f of e.fields) {
|
|
38225
|
+
const def = a.fieldMap.get(f.name);
|
|
38226
|
+
if (def && f.e.k === "draftHole" && !f.e.want) f.e.expected = def.type;
|
|
38227
|
+
const t = this.ex(f.e, sc, o);
|
|
38228
|
+
if (!def) {
|
|
38229
|
+
const others = [...r.altMap.values()].filter((x) => x.fieldMap.has(f.name)).map((x) => x.text.toLowerCase());
|
|
38230
|
+
this.err("TC206", e.line, `A ${a.text.toLowerCase()} ${r.text} has no field "${f.text}"${others.length ? ` (a ${others.join(" or ")} one does)` : ""}.`, `Fields of a ${a.text.toLowerCase()} ${r.text}: ${[...a.fieldMap.keys()].join(", ") || "none"}.`);
|
|
38231
|
+
continue;
|
|
38232
|
+
}
|
|
38233
|
+
f.py = def.py;
|
|
38234
|
+
if (given.has(f.name)) this.err("TC203", e.line, `The field "${f.text}" is given twice.`);
|
|
38235
|
+
given.add(f.name);
|
|
38236
|
+
if (known(def.type) && known(t) && !compatible(def.type, t)) this.err("TC303", e.line, `A ${a.text.toLowerCase()} ${r.text}'s ${def.text} is ${typeWords4(def.type)}, but ${typeWords4(t)} was given.`);
|
|
38237
|
+
}
|
|
38238
|
+
const missing = a.fields.filter((f) => !given.has(f.name) && f.type.k !== "optional" && f.type.k !== "list" && f.type.k !== "map");
|
|
38239
|
+
if (missing.length) this.err("TC210", e.line, `A ${a.text.toLowerCase()} ${r.text} needs ${missing.map((f) => f.text).join(", ")}.`, `Write: a ${a.text.toLowerCase()} ${r.text} with ${a.fields.map((f) => `${f.text} \u2026`).join(" and ")}.`);
|
|
38240
|
+
e.fields.unshift({ name: "which", text: "which", py: "which", e: { k: "str", parts: [a.name], line: e.line, type: T("text") }, line: e.line });
|
|
38241
|
+
return ty;
|
|
38242
|
+
}
|
|
38243
|
+
draftHole(e, sc) {
|
|
38244
|
+
const named2 = (t) => !t ? t : t.k === "record" ? { ...t, text: this.records.get(t.name)?.text ?? t.text } : t.of ? { ...t, of: named2(t.of) } : t;
|
|
38245
|
+
const want = named2(e.want ?? e.expected ?? null);
|
|
38246
|
+
const same = (w, t) => {
|
|
38247
|
+
if (!known(w) || !known(t)) return false;
|
|
38248
|
+
if (w.k === "optional") return t.k === "optional" ? same(w.of, t.of) : same(w.of, t);
|
|
38249
|
+
if (w.k === "number") return t.k === "number" || t.k === "whole";
|
|
38250
|
+
if (w.k !== t.k) return false;
|
|
38251
|
+
if (w.k === "record") return w.name === t.name;
|
|
38252
|
+
if (w.k === "list") return !known(w.of) || same(w.of, t.of);
|
|
38253
|
+
return true;
|
|
38254
|
+
};
|
|
38255
|
+
const fits = (t) => !want || !known(want) || same(want, t);
|
|
38256
|
+
const what = { param: "input", input: "input", var: "value", state: "remembered value", item: "item", const: "kept value", store: "stored list" };
|
|
38257
|
+
const seen = /* @__PURE__ */ new Set();
|
|
38258
|
+
const available = [];
|
|
38259
|
+
for (let at2 = sc; at2; at2 = at2.parent) {
|
|
38260
|
+
for (const [name, v] of at2.vars) {
|
|
38261
|
+
if (seen.has(name) || !what[v.kind]) continue;
|
|
38262
|
+
seen.add(name);
|
|
38263
|
+
if (fits(v.type)) available.push({ name: v.text ?? name, what: what[v.kind], kind: known(v.type) ? typeWords4(v.type) : null });
|
|
38264
|
+
}
|
|
38265
|
+
}
|
|
38266
|
+
if (want && known(want)) {
|
|
38267
|
+
for (const f of this.funcs.values()) {
|
|
38268
|
+
const ret = this.global.vars.get(f.name)?.ret;
|
|
38269
|
+
if (same(want, ret)) available.push({ name: f.text, what: "function", kind: typeWords4(ret), call: f.params.length ? `${f.text} with ${f.params.map((p) => p.text).join(" and ")}` : f.text });
|
|
38270
|
+
}
|
|
38271
|
+
}
|
|
38272
|
+
const needs = want ? typeWords4(want) : "a value";
|
|
38273
|
+
const typed = want && known(want);
|
|
38274
|
+
const shown = available.slice(0, 8).map((a) => a.what === "function" ? `${a.call} (a function)` : `${a.name} (${a.what}${!typed && a.kind ? `, ${a.kind}` : ""})`);
|
|
38275
|
+
const more = available.length > 8 ? `, and ${available.length - 8} more` : "";
|
|
38276
|
+
const hint = !available.length ? `Nothing here is ${needs} yet. Write the value, or receive it as an input.` : typed ? `Here, ${needs} could come from: ${shown.join(", ")}${more}.` : `Values here: ${shown.join(", ")}${more}. Write the kind after the ? (?number) to see only what fits.`;
|
|
38277
|
+
const d = diag("TC120", e.line, `This is a hole: it needs ${needs}, and Thunder won't choose it for you. Fill it in before the program can run.`, hint);
|
|
38278
|
+
d.hole = { col: e.col ?? null, needs: want ? needs : null, written: !!e.want, available };
|
|
38279
|
+
this.d.push(d);
|
|
38280
|
+
return want ?? UNKNOWN;
|
|
38281
|
+
}
|
|
37735
38282
|
newRecord(e, sc, o) {
|
|
37736
38283
|
const r = this.records.get(e.record);
|
|
37737
38284
|
if (!r) {
|
|
@@ -37739,9 +38286,11 @@ var Checker = class {
|
|
|
37739
38286
|
return UNKNOWN;
|
|
37740
38287
|
}
|
|
37741
38288
|
e.py = r.py;
|
|
38289
|
+
if (r.altMap) return this.newAlternative(e, r, sc, o);
|
|
37742
38290
|
const given = /* @__PURE__ */ new Set();
|
|
37743
38291
|
for (const f of e.fields) {
|
|
37744
38292
|
const def = r.fieldMap.get(f.name);
|
|
38293
|
+
if (f.e.k === "draftHole" && !f.e.want && def?.type) f.e.expected = def.type;
|
|
37745
38294
|
const t = this.ex(f.e, sc, o);
|
|
37746
38295
|
if (!def) {
|
|
37747
38296
|
const g = closest(f.name, [...r.fieldMap.keys()]);
|
|
@@ -38032,6 +38581,12 @@ var Gen = class {
|
|
|
38032
38581
|
this.blank();
|
|
38033
38582
|
for (const k of consts) this.emit(`${k.py} = ${this.x(k.e).c}`, k.line);
|
|
38034
38583
|
}
|
|
38584
|
+
const stores = (this.info.stores ?? []).filter(own);
|
|
38585
|
+
if (stores.length) {
|
|
38586
|
+
this.blank();
|
|
38587
|
+
const kind = (t) => t.k === "optional" ? `?${kind(t.of)}` : t.k;
|
|
38588
|
+
for (const s of stores) this.emit(`${s.py} = ${this.R("new_store")}(THUNDER_SOURCE, ${s.line}, ${py(s.py.toLowerCase())}, ${s.record.py}, {${s.record.fields.map((f) => `${py(f.py)}: ${py(kind(f.type))}`).join(", ")}})`, s.line);
|
|
38589
|
+
}
|
|
38035
38590
|
const tests = this.info.tests;
|
|
38036
38591
|
for (const t of tests) {
|
|
38037
38592
|
this.blank();
|
|
@@ -38046,16 +38601,29 @@ var Gen = class {
|
|
|
38046
38601
|
for (const t of tests) this.emit(` (${py(t.title)}, ${t.py}, ${t.line}),`);
|
|
38047
38602
|
this.emit("]");
|
|
38048
38603
|
}
|
|
38604
|
+
const endpoints = (this.info.endpoints ?? []).filter(own);
|
|
38605
|
+
if (endpoints.length) {
|
|
38606
|
+
this.blank();
|
|
38607
|
+
const kind = (t) => t.k === "optional" ? `?${kind(t.of)}` : t.k;
|
|
38608
|
+
this.emit("THUNDER_ROUTES = [");
|
|
38609
|
+
for (const f of endpoints) {
|
|
38610
|
+
const fromPath = new Set(f.endpoint.segments.filter((g) => g.param).map((g) => g.param));
|
|
38611
|
+
const ins = f.params.map((p) => `(${py(p.text)}, ${py(p.py)}, ${py(kind(p.type))}, ${fromPath.has(p.name) ? '"path"' : '"request"'}, ${p.dflt ? "True" : "False"})`);
|
|
38612
|
+
this.emit(` (${py(f.endpoint.method)}, ${py(f.endpoint.path)}, ${f.py}, [${ins.join(", ")}]),`, f.line);
|
|
38613
|
+
}
|
|
38614
|
+
this.emit("]");
|
|
38615
|
+
}
|
|
38049
38616
|
const main = this.p.main ?? [];
|
|
38050
38617
|
this.blank();
|
|
38051
|
-
if (main.length) {
|
|
38618
|
+
if (main.length || endpoints.length) {
|
|
38052
38619
|
this.emit("def main():");
|
|
38053
38620
|
this.ind++;
|
|
38054
|
-
this.block(main);
|
|
38621
|
+
if (main.length) this.block(main);
|
|
38622
|
+
else this.emit("pass");
|
|
38055
38623
|
this.ind--;
|
|
38056
38624
|
this.blank();
|
|
38057
38625
|
this.emit('if __name__ == "__main__":');
|
|
38058
|
-
this.emit(` ${this.R("run")}(main, __file__)`);
|
|
38626
|
+
this.emit(` ${this.R("run")}(main, __file__${endpoints.length ? ", routes=THUNDER_ROUTES" : ""})`);
|
|
38059
38627
|
}
|
|
38060
38628
|
body2.push(...this.out);
|
|
38061
38629
|
const head = [
|
|
@@ -38089,6 +38657,7 @@ ${body2.join("\n").replace(/\n{4,}/g, "\n\n\n")}
|
|
|
38089
38657
|
this.emit(`${f.py}: ${t}${dflt}`, f.line);
|
|
38090
38658
|
}
|
|
38091
38659
|
if (!r.fields.length) this.emit("pass");
|
|
38660
|
+
if (r.alts) this.emit(`__thunder_alts__ = {${r.alts.map((a) => `${py(a.name)}: (${a.fields.map((f) => `${py(f.py)}, `).join("")})`).join(", ")}}`, r.line);
|
|
38092
38661
|
const rules = r.rulesToCheck ?? [];
|
|
38093
38662
|
if (rules.length) {
|
|
38094
38663
|
this.out.push("");
|
|
@@ -38187,11 +38756,14 @@ ${body2.join("\n").replace(/\n{4,}/g, "\n\n\n")}
|
|
|
38187
38756
|
return;
|
|
38188
38757
|
}
|
|
38189
38758
|
case "give":
|
|
38759
|
+
if (s.status != null) this.emit(`${this.R("answer_status")}(${s.status})`, L);
|
|
38190
38760
|
this.emit(s.e.k === "nothing" ? "return None" : `return ${this.x(s.e).c}`, L);
|
|
38191
38761
|
return;
|
|
38192
|
-
case "stop":
|
|
38193
|
-
|
|
38762
|
+
case "stop": {
|
|
38763
|
+
const msg = s.e.type?.k === "text" ? this.x(s.e).c : `${this.R("show")}(${this.x(s.e).c})`;
|
|
38764
|
+
this.emit(s.status != null ? `raise ${this.R("stop_with")}(${msg}, ${s.status})` : `raise ${this.R("Stop")}(${msg})`, L);
|
|
38194
38765
|
return;
|
|
38766
|
+
}
|
|
38195
38767
|
case "if":
|
|
38196
38768
|
s.branches.forEach((b, k) => {
|
|
38197
38769
|
this.emit(`${k === 0 ? "if" : "elif"} ${this.yn(b.cond).c}:`, b.line);
|
|
@@ -38419,6 +38991,12 @@ ${body2.join("\n").replace(/\n{4,}/g, "\n\n\n")}
|
|
|
38419
38991
|
return A("None");
|
|
38420
38992
|
case "paren":
|
|
38421
38993
|
return sub2(e.e);
|
|
38994
|
+
// the answer from GET "…" [with …] [as Rate]: read as text, or as records of a kind (kinds as in stored lists).
|
|
38995
|
+
case "httpCall": {
|
|
38996
|
+
const kind = (t) => t.k === "optional" ? `?${kind(t.of)}` : t.k;
|
|
38997
|
+
const as = e.record ? `(${e.record.py}, {${e.record.fields.map((f) => `${py(f.py)}: ${py(kind(f.type))}`).join(", ")}}, ${e.as.k === "list" ? "True" : "False"})` : "None";
|
|
38998
|
+
return A(`${this.R("http_call")}(${py(e.method)}, ${sub2(e.url).c}, ${e.body ? sub2(e.body).c : "None"}, ${as})`);
|
|
38999
|
+
}
|
|
38422
39000
|
case "today":
|
|
38423
39001
|
this.needDate = true;
|
|
38424
39002
|
return A("date.today()");
|
|
@@ -39373,7 +39951,8 @@ def _callers(tb):
|
|
|
39373
39951
|
|
|
39374
39952
|
|
|
39375
39953
|
def describe_error(error):
|
|
39376
|
-
|
|
39954
|
+
placed = getattr(error, "thunder_where", None) # a stored list's file: its Store line
|
|
39955
|
+
src, line, from_python = (*placed, False) if placed else thunder_place(error.__traceback__)
|
|
39377
39956
|
message = explain(error)
|
|
39378
39957
|
code = _code(error)
|
|
39379
39958
|
# Any error Thunder has no words for came from Python code reached through "Use" (TC508), even when that
|
|
@@ -39388,15 +39967,376 @@ def describe_error(error):
|
|
|
39388
39967
|
return "%s: %s [%s]" % (where, message, code)
|
|
39389
39968
|
|
|
39390
39969
|
|
|
39391
|
-
|
|
39392
|
-
|
|
39970
|
+
# ── Stored lists (Store habits as a list of Habit): data/<name>.json, the format of store-format.mjs ─────────────
|
|
39971
|
+
_STORES = []
|
|
39972
|
+
_STORE_KINDS = {"whole": "a whole number", "number": "a number", "money": "money", "text": "text", "bool": "yes or no", "date": "a date"}
|
|
39973
|
+
|
|
39974
|
+
|
|
39975
|
+
def new_store(source, line, name, cls, kinds):
|
|
39976
|
+
"""A stored list: empty until the program starts (run fills it), saved when the program finishes well.
|
|
39977
|
+
A file it can't read is reported at its Store line (source, line), as on the Thunder engine and TypeScript."""
|
|
39978
|
+
items = []
|
|
39979
|
+
_STORES.append((source, line, name, cls, kinds, items))
|
|
39980
|
+
return items
|
|
39981
|
+
|
|
39982
|
+
|
|
39983
|
+
def _store_encode(v, kind):
|
|
39984
|
+
if kind.startswith("?"):
|
|
39985
|
+
return None if v is None else _store_encode(v, kind[1:])
|
|
39986
|
+
if v is None:
|
|
39987
|
+
return None
|
|
39988
|
+
if kind == "whole":
|
|
39989
|
+
return v if -(2 ** 53 - 1) <= v <= 2 ** 53 - 1 else str(v)
|
|
39990
|
+
if kind == "number":
|
|
39991
|
+
return str(v)
|
|
39992
|
+
if kind == "money":
|
|
39993
|
+
return str(v).replace("$", "")
|
|
39994
|
+
if kind == "date":
|
|
39995
|
+
return v.isoformat()
|
|
39996
|
+
return v
|
|
39997
|
+
|
|
39998
|
+
|
|
39999
|
+
def _store_decode(x, kind, where, has="the file has"):
|
|
40000
|
+
if kind.startswith("?"):
|
|
40001
|
+
return None if x is None else _store_decode(x, kind[1:], where, has)
|
|
40002
|
+
def bad():
|
|
40003
|
+
return ConversionFailed("%s should be %s, but %s %s." % (where, _STORE_KINDS.get(kind, "a value"), has, json.dumps(x)))
|
|
40004
|
+
if kind == "whole":
|
|
40005
|
+
if isinstance(x, int) and not isinstance(x, bool):
|
|
40006
|
+
return x
|
|
40007
|
+
if isinstance(x, str) and re.fullmatch(r"-?\d+", x):
|
|
40008
|
+
return int(x)
|
|
40009
|
+
raise bad()
|
|
40010
|
+
if kind == "number":
|
|
40011
|
+
if isinstance(x, int) and not isinstance(x, bool):
|
|
40012
|
+
return x
|
|
40013
|
+
if isinstance(x, str):
|
|
40014
|
+
if re.fullmatch(r"-?\d+", x):
|
|
40015
|
+
return int(x)
|
|
40016
|
+
try:
|
|
40017
|
+
return Decimal(x)
|
|
40018
|
+
except InvalidOperation:
|
|
40019
|
+
raise bad()
|
|
40020
|
+
raise bad()
|
|
40021
|
+
if kind == "money":
|
|
40022
|
+
try:
|
|
40023
|
+
return Money(Decimal(str(x)))
|
|
40024
|
+
except (InvalidOperation, ValueError):
|
|
40025
|
+
raise bad()
|
|
40026
|
+
if kind == "text":
|
|
40027
|
+
if isinstance(x, str):
|
|
40028
|
+
return x
|
|
40029
|
+
raise bad()
|
|
40030
|
+
if kind == "bool":
|
|
40031
|
+
if isinstance(x, bool):
|
|
40032
|
+
return x
|
|
40033
|
+
raise bad()
|
|
40034
|
+
if kind == "date":
|
|
40035
|
+
try:
|
|
40036
|
+
return date.fromisoformat(x)
|
|
40037
|
+
except (TypeError, ValueError):
|
|
40038
|
+
raise bad()
|
|
40039
|
+
return x
|
|
40040
|
+
|
|
40041
|
+
|
|
40042
|
+
def _store_file(name):
|
|
40043
|
+
return "data/%s.json" % name
|
|
40044
|
+
|
|
40045
|
+
|
|
40046
|
+
def _fill_stores():
|
|
40047
|
+
import os
|
|
40048
|
+
for source, line, name, cls, kinds, items in _STORES:
|
|
40049
|
+
path = _store_file(name)
|
|
40050
|
+
if not os.path.exists(path):
|
|
40051
|
+
continue
|
|
40052
|
+
try:
|
|
40053
|
+
items[:] = _read_store(path, cls, kinds)
|
|
40054
|
+
except Exception as error: # noqa: BLE001 - reported at the Store line
|
|
40055
|
+
error.thunder_where = (source, line)
|
|
40056
|
+
raise
|
|
40057
|
+
|
|
40058
|
+
|
|
40059
|
+
def _read_store(path, cls, kinds):
|
|
40060
|
+
"""The records in a store's file; a problem names the item and field."""
|
|
40061
|
+
with open(path, encoding="utf-8") as fh:
|
|
40062
|
+
text = fh.read()
|
|
40063
|
+
try:
|
|
40064
|
+
rows = json.loads(text)
|
|
40065
|
+
except ValueError as error:
|
|
40066
|
+
raise ConversionFailed("%s is not a list Thunder can read (%s)." % (path, error))
|
|
40067
|
+
if not isinstance(rows, list):
|
|
40068
|
+
raise ConversionFailed("%s should hold a list, written [ … ]." % path)
|
|
40069
|
+
return [_record_from(row, cls, kinds, "%s, item %d" % (path, i + 1)) for i, row in enumerate(rows)]
|
|
40070
|
+
|
|
40071
|
+
|
|
40072
|
+
def _record_from(row, cls, kinds, where, has="the file has"):
|
|
40073
|
+
"""A record from a JSON object, each field read by its kind; a problem names where it is and the field."""
|
|
40074
|
+
if not isinstance(row, dict):
|
|
40075
|
+
raise ConversionFailed("%s should be a record, written { … }." % where)
|
|
40076
|
+
given = {}
|
|
40077
|
+
for field_name, kind in kinds.items():
|
|
40078
|
+
if field_name not in row:
|
|
40079
|
+
if kind.startswith("?"):
|
|
40080
|
+
given[field_name] = None
|
|
40081
|
+
continue
|
|
40082
|
+
raise ConversionFailed('%s has no "%s".' % (where, field_name))
|
|
40083
|
+
given[field_name] = _store_decode(row[field_name], kind, '%s, "%s"' % (where, field_name), has)
|
|
40084
|
+
return cls(**given)
|
|
40085
|
+
|
|
40086
|
+
|
|
40087
|
+
def _save_stores():
|
|
40088
|
+
import os
|
|
40089
|
+
for source, line, name, cls, kinds, items in _STORES:
|
|
40090
|
+
path = _store_file(name)
|
|
40091
|
+
rows = [{f: _store_encode(getattr(item, f), kind) for f, kind in kinds.items()} for item in items]
|
|
40092
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
40093
|
+
with open(path + ".saving", "w", encoding="utf-8") as fh:
|
|
40094
|
+
fh.write(json.dumps(rows, indent=2, ensure_ascii=False) + "\n")
|
|
40095
|
+
os.replace(path + ".saving", path)
|
|
40096
|
+
|
|
40097
|
+
|
|
40098
|
+
# ── HTTP (When someone calls GET /habits: and the answer from GET "…"): data in the stored-list format ──────────
|
|
40099
|
+
class CallFailed(ThunderError):
|
|
40100
|
+
code = "TC510"
|
|
40101
|
+
|
|
40102
|
+
|
|
40103
|
+
_ANSWER_STATUS = [None]
|
|
40104
|
+
|
|
40105
|
+
|
|
40106
|
+
def answer_status(status):
|
|
40107
|
+
"""Give … with status 201: the status this request answers with (a direct call in a test ignores it)."""
|
|
40108
|
+
_ANSWER_STATUS[0] = status
|
|
40109
|
+
|
|
40110
|
+
|
|
40111
|
+
def stop_with(message, status):
|
|
40112
|
+
"""Stop with "…" and status 404: a Stop that an endpoint answers with that status."""
|
|
40113
|
+
error = Stop(message)
|
|
40114
|
+
error.status = status
|
|
40115
|
+
return error
|
|
40116
|
+
|
|
40117
|
+
|
|
40118
|
+
def _data_ready(v):
|
|
40119
|
+
"""A value as JSON data, written by its kind: whole numbers as numbers (text when too large), numbers and money as
|
|
40120
|
+
exact text, dates as "2026-11-28", records as objects. The same on every target."""
|
|
40121
|
+
if v is None or isinstance(v, (bool, str)):
|
|
40122
|
+
return v
|
|
40123
|
+
if isinstance(v, int):
|
|
40124
|
+
return v if -(2 ** 53 - 1) <= v <= 2 ** 53 - 1 else str(v)
|
|
40125
|
+
if isinstance(v, Decimal):
|
|
40126
|
+
return str(v)
|
|
40127
|
+
if isinstance(v, Money):
|
|
40128
|
+
return str(v).replace("$", "", 1)
|
|
40129
|
+
if isinstance(v, date):
|
|
40130
|
+
return v.isoformat()
|
|
40131
|
+
if isinstance(v, (list, tuple)):
|
|
40132
|
+
return [_data_ready(x) for x in v]
|
|
40133
|
+
if isinstance(v, dict):
|
|
40134
|
+
out = {}
|
|
40135
|
+
for k, x in v.items():
|
|
40136
|
+
if not isinstance(k, str):
|
|
40137
|
+
raise KindMismatch("A JSON object's keys are text, but one is %s." % show(k))
|
|
40138
|
+
out[k] = _data_ready(x)
|
|
40139
|
+
return out
|
|
40140
|
+
if is_dataclass(v):
|
|
40141
|
+
alts = getattr(type(v), "__thunder_alts__", None)
|
|
40142
|
+
if alts is not None: # an alternative of a data type: "which" and the fields it has
|
|
40143
|
+
keep = ("which",) + tuple(alts.get(v.which, ()))
|
|
40144
|
+
return {name: _data_ready(getattr(v, name)) for name in keep}
|
|
40145
|
+
return {f.name: _data_ready(getattr(v, f.name)) for f in fields(v)}
|
|
40146
|
+
raise KindMismatch("%s can't be sent as JSON." % show(v))
|
|
40147
|
+
|
|
40148
|
+
|
|
40149
|
+
def data_json(v):
|
|
40150
|
+
return json.dumps(_data_ready(v), ensure_ascii=False, separators=(",", ":"))
|
|
40151
|
+
|
|
40152
|
+
|
|
40153
|
+
def _unreachable_reason(error):
|
|
40154
|
+
"""Why a service could not be reached, in words that are the same on every target."""
|
|
40155
|
+
import socket
|
|
40156
|
+
reason = getattr(error, "reason", error)
|
|
40157
|
+
if isinstance(reason, (TimeoutError, socket.timeout)):
|
|
40158
|
+
return "no answer within 30 seconds"
|
|
40159
|
+
if isinstance(reason, ConnectionRefusedError):
|
|
40160
|
+
return "nothing is answering there"
|
|
40161
|
+
if isinstance(reason, socket.gaierror):
|
|
40162
|
+
return "the address could not be found"
|
|
40163
|
+
return str(reason)
|
|
40164
|
+
|
|
40165
|
+
|
|
40166
|
+
def http_call(method, url, body, read_as):
|
|
40167
|
+
"""the answer from GET "…": the answer's text, or records read from it (read_as = (record, kinds, many))."""
|
|
40168
|
+
import urllib.error
|
|
40169
|
+
import urllib.request
|
|
40170
|
+
where = "The answer from %s %s" % (method, url)
|
|
40171
|
+
data = data_json(body).encode("utf-8") if body is not None else None
|
|
40172
|
+
headers = {"Accept": "application/json"}
|
|
40173
|
+
if data is not None:
|
|
40174
|
+
headers["Content-Type"] = "application/json"
|
|
40175
|
+
request = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
40176
|
+
try:
|
|
40177
|
+
with urllib.request.urlopen(request, timeout=30) as reply:
|
|
40178
|
+
text = reply.read().decode("utf-8")
|
|
40179
|
+
except urllib.error.HTTPError as error:
|
|
40180
|
+
raise CallFailed("%s %s answered %d: %s" % (method, url, error.code, error.read().decode("utf-8", "replace").strip()[:300]))
|
|
40181
|
+
except (urllib.error.URLError, OSError, ValueError) as error:
|
|
40182
|
+
raise CallFailed("%s %s could not be reached (%s)." % (method, url, _unreachable_reason(error)))
|
|
40183
|
+
if read_as is None:
|
|
40184
|
+
return text
|
|
40185
|
+
cls, kinds, many = read_as
|
|
39393
40186
|
try:
|
|
40187
|
+
answer = json.loads(text)
|
|
40188
|
+
except ValueError:
|
|
40189
|
+
raise ConversionFailed("%s is not JSON Thunder can read." % where)
|
|
40190
|
+
if many:
|
|
40191
|
+
if not isinstance(answer, list):
|
|
40192
|
+
raise ConversionFailed("%s should be a list, written [ … ]." % where)
|
|
40193
|
+
return [_record_from(row, cls, kinds, "%s, item %d" % (where, i + 1), "it has") for i, row in enumerate(answer)]
|
|
40194
|
+
return _record_from(answer, cls, kinds, where, "it has")
|
|
40195
|
+
|
|
40196
|
+
|
|
40197
|
+
def _input_value(raw, kind, where, from_text):
|
|
40198
|
+
"""A request's input read by its kind. Path and query parts are text, so yes/no is written yes, no, true, or false."""
|
|
40199
|
+
plain = kind.lstrip("?")
|
|
40200
|
+
if from_text and plain == "bool" and isinstance(raw, str) and raw.lower() in ("yes", "no", "true", "false"):
|
|
40201
|
+
raw = raw.lower() in ("yes", "true")
|
|
40202
|
+
return _store_decode(raw, kind, where, "the request has")
|
|
40203
|
+
|
|
40204
|
+
|
|
40205
|
+
def _serve(routes):
|
|
40206
|
+
"""Answer requests on this machine, one at a time, until stopped (Ctrl+C). Stored lists are saved after each
|
|
40207
|
+
request that finishes well."""
|
|
40208
|
+
import os
|
|
40209
|
+
import urllib.parse
|
|
40210
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
40211
|
+
|
|
40212
|
+
host = os.environ.get("THUNDER_HOST", "127.0.0.1")
|
|
40213
|
+
port = int(os.environ.get("THUNDER_PORT", "8080"))
|
|
40214
|
+
table = []
|
|
40215
|
+
for method, path, handler, inputs in routes:
|
|
40216
|
+
parts = [p for p in path.split("/") if p]
|
|
40217
|
+
table.append((method, path, parts, handler, inputs))
|
|
40218
|
+
|
|
40219
|
+
def match(parts, request_parts):
|
|
40220
|
+
if len(parts) != len(request_parts):
|
|
40221
|
+
return None
|
|
40222
|
+
found = {}
|
|
40223
|
+
for want, got in zip(parts, request_parts):
|
|
40224
|
+
if want.startswith("{") and want.endswith("}"):
|
|
40225
|
+
found[want[1:-1].strip().lower()] = urllib.parse.unquote(got)
|
|
40226
|
+
elif want != got:
|
|
40227
|
+
return None
|
|
40228
|
+
return found
|
|
40229
|
+
|
|
40230
|
+
class Handler(BaseHTTPRequestHandler):
|
|
40231
|
+
server_version = "Thunder"
|
|
40232
|
+
|
|
40233
|
+
def answer(self, status, value):
|
|
40234
|
+
data = data_json(value).encode("utf-8")
|
|
40235
|
+
self.send_response(status)
|
|
40236
|
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
40237
|
+
self.send_header("Content-Length", str(len(data)))
|
|
40238
|
+
self.end_headers()
|
|
40239
|
+
self.wfile.write(data)
|
|
40240
|
+
print("%s %s -> %d" % (self.command, self.path, status), flush=True)
|
|
40241
|
+
|
|
40242
|
+
def handle_any(self):
|
|
40243
|
+
url = urllib.parse.urlsplit(self.path)
|
|
40244
|
+
request_parts = [p for p in url.path.split("/") if p]
|
|
40245
|
+
query = {k: v[-1] for k, v in urllib.parse.parse_qs(url.query).items()}
|
|
40246
|
+
chosen, methods = None, []
|
|
40247
|
+
for method, path, parts, handler, inputs in table:
|
|
40248
|
+
found = match(parts, request_parts)
|
|
40249
|
+
if found is None:
|
|
40250
|
+
continue
|
|
40251
|
+
methods.append(method)
|
|
40252
|
+
if method == self.command:
|
|
40253
|
+
chosen = (method, path, handler, inputs, found)
|
|
40254
|
+
if chosen is None:
|
|
40255
|
+
if methods:
|
|
40256
|
+
return self.answer(405, {"problem": "%s answers only %s." % (url.path, ", ".join(methods))})
|
|
40257
|
+
return self.answer(404, {"problem": "Nothing here answers %s %s." % (self.command, url.path)})
|
|
40258
|
+
method, path, handler, inputs, found = chosen
|
|
40259
|
+
body = {}
|
|
40260
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
40261
|
+
if length:
|
|
40262
|
+
try:
|
|
40263
|
+
body = json.loads(self.rfile.read(length).decode("utf-8"))
|
|
40264
|
+
except ValueError:
|
|
40265
|
+
return self.answer(400, {"problem": "The request's body is not JSON Thunder can read."})
|
|
40266
|
+
if not isinstance(body, dict):
|
|
40267
|
+
return self.answer(400, {"problem": "The request's body should be a JSON object, written { … }."})
|
|
40268
|
+
args = {}
|
|
40269
|
+
try:
|
|
40270
|
+
for text, py_name, kind, source, has_default in inputs:
|
|
40271
|
+
key = text.lower()
|
|
40272
|
+
if source == "path":
|
|
40273
|
+
args[py_name] = _input_value(found[key], kind, '"%s"' % text, True)
|
|
40274
|
+
elif key in query:
|
|
40275
|
+
args[py_name] = _input_value(query[key], kind, '"%s"' % text, True)
|
|
40276
|
+
elif py_name in query:
|
|
40277
|
+
args[py_name] = _input_value(query[py_name], kind, '"%s"' % text, True)
|
|
40278
|
+
elif text in body or key in body or py_name in body:
|
|
40279
|
+
raw = body[text] if text in body else body[key] if key in body else body[py_name]
|
|
40280
|
+
args[py_name] = _input_value(raw, kind, '"%s"' % text, False)
|
|
40281
|
+
elif not has_default:
|
|
40282
|
+
if kind.startswith("?"):
|
|
40283
|
+
args[py_name] = None
|
|
40284
|
+
else:
|
|
40285
|
+
return self.answer(400, {"problem": "%s %s needs %s (%s)." % (method, path, text, _STORE_KINDS.get(kind, kind))})
|
|
40286
|
+
except ThunderError as error:
|
|
40287
|
+
return self.answer(400, {"problem": explain(error)})
|
|
40288
|
+
_ANSWER_STATUS[0] = None
|
|
40289
|
+
try:
|
|
40290
|
+
value = handler(**args)
|
|
40291
|
+
except Stop as error:
|
|
40292
|
+
return self.answer(getattr(error, "status", 400), {"problem": explain(error)})
|
|
40293
|
+
except RuleBroken as error:
|
|
40294
|
+
return self.answer(422, {"problem": explain(error)})
|
|
40295
|
+
except Exception as error: # noqa: BLE001 - reported in Thunder words, the server keeps answering
|
|
40296
|
+
print(describe_error(error), file=sys.stderr, flush=True)
|
|
40297
|
+
return self.answer(500, {"problem": explain(error)})
|
|
40298
|
+
status = _ANSWER_STATUS[0] or 200
|
|
40299
|
+
try:
|
|
40300
|
+
_save_stores()
|
|
40301
|
+
data = data_json(value)
|
|
40302
|
+
except Exception as error: # noqa: BLE001
|
|
40303
|
+
print(describe_error(error), file=sys.stderr, flush=True)
|
|
40304
|
+
return self.answer(500, {"problem": explain(error)})
|
|
40305
|
+
self.answer(status, json.loads(data) if data != "null" else None)
|
|
40306
|
+
|
|
40307
|
+
do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = handle_any
|
|
40308
|
+
|
|
40309
|
+
def log_message(self, *args):
|
|
40310
|
+
pass
|
|
40311
|
+
|
|
40312
|
+
server = HTTPServer((host, port), Handler)
|
|
40313
|
+
print("Thunder is answering on http://%s:%d" % (host, port), flush=True)
|
|
40314
|
+
for method, path, handler, inputs in routes:
|
|
40315
|
+
print(" %s %s" % (method, path), flush=True)
|
|
40316
|
+
print("Press Ctrl+C to stop.", flush=True)
|
|
40317
|
+
try:
|
|
40318
|
+
server.serve_forever()
|
|
40319
|
+
except KeyboardInterrupt:
|
|
40320
|
+
print("Stopped answering.", flush=True)
|
|
40321
|
+
finally:
|
|
40322
|
+
server.server_close()
|
|
40323
|
+
|
|
40324
|
+
|
|
40325
|
+
def run(main, file=None, routes=None):
|
|
40326
|
+
"""Runs a generated program; an error is reported against the Thunder line, then the program exits with 1.
|
|
40327
|
+
Stored lists are filled first and saved only when the program finishes well. With endpoints, it then answers
|
|
40328
|
+
requests until stopped."""
|
|
40329
|
+
try:
|
|
40330
|
+
_fill_stores()
|
|
39394
40331
|
main()
|
|
40332
|
+
_save_stores()
|
|
39395
40333
|
except KeyboardInterrupt:
|
|
39396
40334
|
raise
|
|
39397
40335
|
except Exception as error: # noqa: BLE001 - every error is reported in Thunder words
|
|
39398
40336
|
print(describe_error(error), file=sys.stderr)
|
|
39399
40337
|
sys.exit(1)
|
|
40338
|
+
if routes:
|
|
40339
|
+
_serve(routes)
|
|
39400
40340
|
|
|
39401
40341
|
|
|
39402
40342
|
def run_tests(modules):
|
|
@@ -39426,13 +40366,17 @@ function compileCore(source, { file = "main.thunder", imported = [], srcModules
|
|
|
39426
40366
|
fields: imported.flatMap((r) => [...r.program.names.fields]),
|
|
39427
40367
|
records: imported.flatMap((r) => [...r.program.names.records]),
|
|
39428
40368
|
recordFields: imported.flatMap((r) => [...r.program.names.recordFields ?? []]),
|
|
39429
|
-
funcInputs: imported.flatMap((r) => [...r.program.names.funcInputs ?? []])
|
|
40369
|
+
funcInputs: imported.flatMap((r) => [...r.program.names.funcInputs ?? []]),
|
|
40370
|
+
alts: imported.flatMap((r) => [...r.program.names.alts ?? []]),
|
|
40371
|
+
altsOf: imported.flatMap((r) => [...r.program.names.altsOf ?? []])
|
|
39430
40372
|
} : null;
|
|
39431
40373
|
const program = parseCore(source, { seed });
|
|
39432
40374
|
const { diagnostics, info } = checkCore(program, { imported: imported.map((r) => r.info) });
|
|
39433
40375
|
const ok = diagnostics.length === 0;
|
|
39434
40376
|
const python = ok ? toPython(program, info, { source: file, imports: srcModules }) : null;
|
|
39435
|
-
|
|
40377
|
+
const holes = diagnostics.filter((d) => d.code === "TC120");
|
|
40378
|
+
const draft = holes.length > 0 && holes.length === diagnostics.length;
|
|
40379
|
+
return { ok, diagnostics, python, program, info, file, holes, draft };
|
|
39436
40380
|
}
|
|
39437
40381
|
|
|
39438
40382
|
// src/core/engine-values.mjs
|
|
@@ -39451,6 +40395,7 @@ var KindMismatch = (m) => new ThunderErr("TC506", m, "TypeError");
|
|
|
39451
40395
|
var ConversionFailed = (m) => new ThunderErr("TC509", m, "ValueError");
|
|
39452
40396
|
var MissingValue = (m) => new ThunderErr("TC503", m, "LookupError");
|
|
39453
40397
|
var DividedByZero = (m) => new ThunderErr("TC501", m, "ZeroDivisionError");
|
|
40398
|
+
var CallFailed = (m) => new ThunderErr("TC510", m, "CallFailed");
|
|
39454
40399
|
var PyErr = class extends Error {
|
|
39455
40400
|
constructor(pyType2, message2, args) {
|
|
39456
40401
|
super(message2);
|
|
@@ -40617,6 +41562,120 @@ function stripPunct(w) {
|
|
|
40617
41562
|
return a.slice(i, j).join("");
|
|
40618
41563
|
}
|
|
40619
41564
|
|
|
41565
|
+
// src/core/store-format.mjs
|
|
41566
|
+
var kindWords3 = { whole: "a whole number", number: "a number", money: "money", text: "text", bool: "yes or no", date: "a date" };
|
|
41567
|
+
function encode(v, t) {
|
|
41568
|
+
if (t.k === "optional") return v === null || v === void 0 ? null : encode(v, t.of);
|
|
41569
|
+
if (v === null || v === void 0) return null;
|
|
41570
|
+
switch (t.k) {
|
|
41571
|
+
case "whole":
|
|
41572
|
+
return typeof v === "bigint" && v <= BigInt(Number.MAX_SAFE_INTEGER) && v >= -BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : String(v);
|
|
41573
|
+
case "number":
|
|
41574
|
+
return String(v);
|
|
41575
|
+
case "money":
|
|
41576
|
+
return v instanceof Money ? v.toString().replace("$", "") : String(v);
|
|
41577
|
+
case "date":
|
|
41578
|
+
return v instanceof PyDate ? v.iso() : String(v);
|
|
41579
|
+
default:
|
|
41580
|
+
return v;
|
|
41581
|
+
}
|
|
41582
|
+
}
|
|
41583
|
+
function decode(x, t, where2, has2 = "the file has") {
|
|
41584
|
+
if (t.k === "optional") return x === null ? null : decode(x, t.of, where2, has2);
|
|
41585
|
+
const bad = () => ConversionFailed(`${where2} should be ${kindWords3[t.k] ?? "a value"}, but ${has2} ${JSON.stringify(x)}.`);
|
|
41586
|
+
switch (t.k) {
|
|
41587
|
+
case "whole":
|
|
41588
|
+
if (typeof x === "number" && Number.isInteger(x)) return BigInt(x);
|
|
41589
|
+
if (typeof x === "string" && /^-?\d+$/.test(x)) return BigInt(x);
|
|
41590
|
+
throw bad();
|
|
41591
|
+
case "number": {
|
|
41592
|
+
if (typeof x === "number" && Number.isInteger(x)) return BigInt(x);
|
|
41593
|
+
const d = typeof x === "string" ? Dec.parse(x) : null;
|
|
41594
|
+
if (!d) throw bad();
|
|
41595
|
+
return /^-?\d+$/.test(x) ? BigInt(x) : d;
|
|
41596
|
+
}
|
|
41597
|
+
case "money": {
|
|
41598
|
+
const d = typeof x === "string" ? Dec.parse(x) : typeof x === "number" ? Dec.parse(String(x)) : null;
|
|
41599
|
+
if (!d) throw bad();
|
|
41600
|
+
return new Money(d);
|
|
41601
|
+
}
|
|
41602
|
+
case "text":
|
|
41603
|
+
if (typeof x === "string") return x;
|
|
41604
|
+
throw bad();
|
|
41605
|
+
case "bool":
|
|
41606
|
+
if (typeof x === "boolean") return x;
|
|
41607
|
+
throw bad();
|
|
41608
|
+
case "date": {
|
|
41609
|
+
const d = typeof x === "string" ? PyDate.parse(x) : null;
|
|
41610
|
+
if (!d) throw bad();
|
|
41611
|
+
return d;
|
|
41612
|
+
}
|
|
41613
|
+
default:
|
|
41614
|
+
return x;
|
|
41615
|
+
}
|
|
41616
|
+
}
|
|
41617
|
+
function storeToText(list3, cls) {
|
|
41618
|
+
const rows = list3.map((rec) => Object.fromEntries(cls.fields.map((f) => [f.py, encode(rec.f.get(f.py), f.type ?? { k: "text" })])));
|
|
41619
|
+
return `${JSON.stringify(rows, null, 2)}
|
|
41620
|
+
`;
|
|
41621
|
+
}
|
|
41622
|
+
function storeFromText(text2, cls, name, make) {
|
|
41623
|
+
let rows;
|
|
41624
|
+
try {
|
|
41625
|
+
rows = JSON.parse(text2);
|
|
41626
|
+
} catch (e) {
|
|
41627
|
+
throw ConversionFailed(`${name} is not a list Thunder can read (${e.message}).`);
|
|
41628
|
+
}
|
|
41629
|
+
if (!Array.isArray(rows)) throw ConversionFailed(`${name} should hold a list, written [ \u2026 ].`);
|
|
41630
|
+
return rows.map((row, i) => recordFrom(row, cls, `${name}, item ${i + 1}`, make));
|
|
41631
|
+
}
|
|
41632
|
+
function recordFrom(row, cls, where2, make, has2 = "the file has") {
|
|
41633
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) throw ConversionFailed(`${where2} should be a record, written { \u2026 }.`);
|
|
41634
|
+
const given = /* @__PURE__ */ new Map();
|
|
41635
|
+
for (const f of cls.fields) {
|
|
41636
|
+
const t = f.type ?? { k: "text" };
|
|
41637
|
+
if (!(f.py in row)) {
|
|
41638
|
+
if (t.k === "optional") {
|
|
41639
|
+
given.set(f.py, null);
|
|
41640
|
+
continue;
|
|
41641
|
+
}
|
|
41642
|
+
throw ConversionFailed(`${where2} has no "${f.py}".`);
|
|
41643
|
+
}
|
|
41644
|
+
given.set(f.py, decode(row[f.py], t, `${where2}, "${f.py}"`, has2));
|
|
41645
|
+
}
|
|
41646
|
+
return make(given);
|
|
41647
|
+
}
|
|
41648
|
+
function dataReady(v) {
|
|
41649
|
+
if (v === null || v === void 0 || typeof v === "boolean" || typeof v === "string") return v ?? null;
|
|
41650
|
+
if (typeof v === "bigint") return v <= BigInt(Number.MAX_SAFE_INTEGER) && v >= -BigInt(Number.MAX_SAFE_INTEGER) ? Number(v) : String(v);
|
|
41651
|
+
if (v instanceof Dec) return String(v);
|
|
41652
|
+
if (v instanceof Money) return v.toString().replace("$", "");
|
|
41653
|
+
if (v instanceof PyDate) return v.iso();
|
|
41654
|
+
if (Array.isArray(v)) return v.map(dataReady);
|
|
41655
|
+
if (v instanceof Tuple) return v.items.map(dataReady);
|
|
41656
|
+
if (v instanceof PyDict) {
|
|
41657
|
+
const out = {};
|
|
41658
|
+
for (const [k, x] of v.m.values()) {
|
|
41659
|
+
if (typeof k !== "string") throw KindMismatch(`A JSON object's keys are text, but one is ${show2(k)}.`);
|
|
41660
|
+
out[k] = dataReady(x);
|
|
41661
|
+
}
|
|
41662
|
+
return out;
|
|
41663
|
+
}
|
|
41664
|
+
if (v instanceof RecordVal) {
|
|
41665
|
+
const keep = v.cls.alts ? ["which", ...v.cls.alts[v.f.get("which")] ?? []] : v.cls.fields.map((f) => f.py);
|
|
41666
|
+
return Object.fromEntries(keep.map((py2) => [py2, dataReady(v.f.get(py2))]));
|
|
41667
|
+
}
|
|
41668
|
+
throw KindMismatch(`${show2(v)} can't be sent as JSON.`);
|
|
41669
|
+
}
|
|
41670
|
+
var dataJson = (v) => JSON.stringify(dataReady(v));
|
|
41671
|
+
function unreachableReason(out) {
|
|
41672
|
+
if (out.name === "TimeoutError" || out.name === "AbortError") return "no answer within 30 seconds";
|
|
41673
|
+
if (out.error === "ECONNREFUSED") return "nothing is answering there";
|
|
41674
|
+
if (out.error === "ENOTFOUND" || out.error === "EAI_AGAIN") return "the address could not be found";
|
|
41675
|
+
return out.error;
|
|
41676
|
+
}
|
|
41677
|
+
var storeFile = (s) => `data/${s.py.toLowerCase()}.json`;
|
|
41678
|
+
|
|
40620
41679
|
// src/core/engine-core.mjs
|
|
40621
41680
|
var Return = class {
|
|
40622
41681
|
constructor(v) {
|
|
@@ -40632,6 +41691,8 @@ var nativeOverflow = (e) => {
|
|
|
40632
41691
|
};
|
|
40633
41692
|
var NeedsDeeperStack = class extends Error {
|
|
40634
41693
|
};
|
|
41694
|
+
var OutOfSteps = class extends Error {
|
|
41695
|
+
};
|
|
40635
41696
|
var MAX_FRAMES2 = MAX_FRAMES;
|
|
40636
41697
|
var CONTAINER_KINDS = /* @__PURE__ */ new Set(["if", "each", "range", "times", "while", "tryFail"]);
|
|
40637
41698
|
var MAX_RECORDED = 2e4;
|
|
@@ -40658,13 +41719,19 @@ var Engine = class {
|
|
|
40658
41719
|
// readText(path, cwd): the text of a file the program reads, or throws with .code 'ENOENT' / 'EISDIR'. Without it
|
|
40659
41720
|
// (a browser), reading a file is reported as a missing file.
|
|
40660
41721
|
// record: keep a step-by-step recording of the run (the Thunder Time Machine; see recordedRun below).
|
|
40661
|
-
|
|
41722
|
+
// http(method, url, bodyText) -> { status, text } | { error }: calls another service and waits for the answer.
|
|
41723
|
+
// Without it (a browser), "the answer from …" says it can't run here.
|
|
41724
|
+
constructor({ cwd = ".", deeper = false, readText = null, record = false, store = null, http = null } = {}) {
|
|
41725
|
+
this.http = http;
|
|
41726
|
+
this.answeredStatus = null;
|
|
41727
|
+
this.dataFiles = store;
|
|
40662
41728
|
this.cwd = cwd;
|
|
40663
41729
|
this.rec = record ? { steps: [], truncated: false } : null;
|
|
40664
41730
|
this.readText = readText;
|
|
40665
41731
|
this.deeper = deeper;
|
|
40666
41732
|
this.frames = [];
|
|
40667
41733
|
this.out = [];
|
|
41734
|
+
this.budget = null;
|
|
40668
41735
|
}
|
|
40669
41736
|
// ── loading ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
40670
41737
|
load(result, imports = []) {
|
|
@@ -40673,6 +41740,12 @@ var Engine = class {
|
|
|
40673
41740
|
for (const m of imports) for (const [k, v] of m.globals) mod.globals.set(k, v);
|
|
40674
41741
|
for (const r of result.info.records.filter(own)) mod.globals.set(r.py, this.recordClass(r, mod));
|
|
40675
41742
|
for (const f of result.info.funcs.filter(own)) mod.globals.set(f.py, { isFunc: true, f, mod });
|
|
41743
|
+
mod.stores = (result.info.stores ?? []).filter(own).map((s) => {
|
|
41744
|
+
const list3 = [];
|
|
41745
|
+
mod.globals.set(s.py, list3);
|
|
41746
|
+
return { s, list: list3, cls: mod.globals.get(s.record.py) };
|
|
41747
|
+
});
|
|
41748
|
+
for (const m of imports) for (const st of m.stores ?? []) mod.stores.push(st);
|
|
40676
41749
|
const consts = result.info.consts.filter(own);
|
|
40677
41750
|
if (consts.length) {
|
|
40678
41751
|
const frame = { file: mod.file, line: 0 };
|
|
@@ -40692,7 +41765,8 @@ var Engine = class {
|
|
|
40692
41765
|
const f = r.fieldMap.get(rule.subject);
|
|
40693
41766
|
(rules.get(f.py) ?? rules.set(f.py, []).get(f.py)).push(rule);
|
|
40694
41767
|
}
|
|
40695
|
-
|
|
41768
|
+
const alts = r.alts ? Object.fromEntries(r.alts.map((a) => [a.name, a.fields.map((f) => f.py)])) : null;
|
|
41769
|
+
return { isRecord: true, py: r.py, fields: r.fields.map((f) => ({ py: f.py, type: f.type })), rules, mod, alts };
|
|
40696
41770
|
}
|
|
40697
41771
|
// ── frames, lines, errors ───────────────────────────────────────────────────────────────────────────────────
|
|
40698
41772
|
withFrame(frame, fn) {
|
|
@@ -40701,7 +41775,7 @@ var Engine = class {
|
|
|
40701
41775
|
try {
|
|
40702
41776
|
return fn();
|
|
40703
41777
|
} catch (e) {
|
|
40704
|
-
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
41778
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
|
|
40705
41779
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
40706
41780
|
const err = asPyErr(e);
|
|
40707
41781
|
if (!err.where) err.where = this.frames.map((f) => ({ file: f.file, line: f.line }));
|
|
@@ -40728,7 +41802,7 @@ var Engine = class {
|
|
|
40728
41802
|
const locals = /* @__PURE__ */ new Map();
|
|
40729
41803
|
const env = { mod, locals, frame };
|
|
40730
41804
|
f.params.forEach((p, i) => {
|
|
40731
|
-
let v = i < args.length ? args[i] : p.dflt ? p.dflt.k === "name" ? NOT_GIVEN : this.x(p.dflt, env) : void 0;
|
|
41805
|
+
let v = i < args.length && args[i] !== NOT_GIVEN ? args[i] : p.dflt ? p.dflt.k === "name" ? NOT_GIVEN : this.x(p.dflt, env) : void 0;
|
|
40732
41806
|
if (v === void 0) throw TypeErr(`${f.py}() missing 1 required positional argument: '${p.py}'`);
|
|
40733
41807
|
locals.set(p.py, v);
|
|
40734
41808
|
});
|
|
@@ -40749,6 +41823,36 @@ var Engine = class {
|
|
|
40749
41823
|
return null;
|
|
40750
41824
|
});
|
|
40751
41825
|
}
|
|
41826
|
+
/** the answer from GET "…" [with …] [as Rate]: the answer's text, or records read from it. */
|
|
41827
|
+
httpCall(e, env) {
|
|
41828
|
+
const url = this.x(e.url, env);
|
|
41829
|
+
const body2 = e.body ? dataJson(this.x(e.body, env)) : null;
|
|
41830
|
+
if (!this.http) throw CallFailed(`${e.method} ${pyStr(url)} can't be called here: calls to other services run with the thunder command, not in the browser.`);
|
|
41831
|
+
const out = this.http(e.method, url, body2);
|
|
41832
|
+
if (out.error) throw CallFailed(`${e.method} ${url} could not be reached (${unreachableReason(out)}).`);
|
|
41833
|
+
if (out.status < 200 || out.status > 299) throw CallFailed(`${e.method} ${url} answered ${out.status}: ${out.text.trim().slice(0, 300)}`);
|
|
41834
|
+
if (!e.record) return out.text;
|
|
41835
|
+
const where2 = `The answer from ${e.method} ${url}`;
|
|
41836
|
+
let data;
|
|
41837
|
+
try {
|
|
41838
|
+
data = JSON.parse(out.text);
|
|
41839
|
+
} catch {
|
|
41840
|
+
throw ConversionFailed(`${where2} is not JSON Thunder can read.`);
|
|
41841
|
+
}
|
|
41842
|
+
const cls = env.mod.globals.get(e.record.py);
|
|
41843
|
+
const make = (given) => this.newRecord(cls, given);
|
|
41844
|
+
if (e.as.k === "list") {
|
|
41845
|
+
if (!Array.isArray(data)) throw ConversionFailed(`${where2} should be a list, written [ \u2026 ].`);
|
|
41846
|
+
return data.map((row, i) => recordFrom(row, cls, `${where2}, item ${i + 1}`, make, "it has"));
|
|
41847
|
+
}
|
|
41848
|
+
return recordFrom(data, cls, where2, make, "it has");
|
|
41849
|
+
}
|
|
41850
|
+
/** An endpoint answering one request: its value and status, or the error it stopped with. Output so far is kept. */
|
|
41851
|
+
answer(mod, f, args) {
|
|
41852
|
+
this.answeredStatus = null;
|
|
41853
|
+
const value = this.call(mod.globals.get(f.py), args);
|
|
41854
|
+
return { value, status: this.answeredStatus ?? 200 };
|
|
41855
|
+
}
|
|
40752
41856
|
never(rule, value, env) {
|
|
40753
41857
|
never(this.x(rule.rule.cond, env, { subject: value }), rule.text, rule.line, value);
|
|
40754
41858
|
}
|
|
@@ -40802,6 +41906,7 @@ var Engine = class {
|
|
|
40802
41906
|
}
|
|
40803
41907
|
}
|
|
40804
41908
|
stmt(s, env) {
|
|
41909
|
+
if (this.budget !== null && --this.budget < 0) throw new OutOfSteps();
|
|
40805
41910
|
if (this.rec) return this.recordStep(s, env);
|
|
40806
41911
|
return this.runStmt(s, env);
|
|
40807
41912
|
}
|
|
@@ -40890,11 +41995,16 @@ var Engine = class {
|
|
|
40890
41995
|
this.storeAt(t, v, env);
|
|
40891
41996
|
return;
|
|
40892
41997
|
}
|
|
40893
|
-
case "give":
|
|
40894
|
-
|
|
41998
|
+
case "give": {
|
|
41999
|
+
const v = s.e.k === "nothing" ? null : this.x(s.e, env);
|
|
42000
|
+
if (s.status != null) this.answeredStatus = s.status;
|
|
42001
|
+
throw new Return(v);
|
|
42002
|
+
}
|
|
40895
42003
|
case "stop": {
|
|
40896
42004
|
const v = this.x(s.e, env);
|
|
40897
|
-
|
|
42005
|
+
const err = Stop(s.e.type?.k === "text" ? pyStr(v) : show2(v));
|
|
42006
|
+
if (s.status != null) err.status = s.status;
|
|
42007
|
+
throw err;
|
|
40898
42008
|
}
|
|
40899
42009
|
case "if":
|
|
40900
42010
|
for (const b of s.branches) {
|
|
@@ -40997,7 +42107,7 @@ var Engine = class {
|
|
|
40997
42107
|
try {
|
|
40998
42108
|
this.stmt(s.stmt, env);
|
|
40999
42109
|
} catch (e) {
|
|
41000
|
-
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
42110
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
|
|
41001
42111
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
41002
42112
|
const err = asPyErr(e);
|
|
41003
42113
|
fr.line = L;
|
|
@@ -41046,6 +42156,7 @@ var Engine = class {
|
|
|
41046
42156
|
}
|
|
41047
42157
|
if (s.mode === "fail") {
|
|
41048
42158
|
const msg = s.msg ? this.x(s.msg, env) : null;
|
|
42159
|
+
let outOfSteps = null;
|
|
41049
42160
|
expectFailure(() => {
|
|
41050
42161
|
try {
|
|
41051
42162
|
this.x(s.e, env);
|
|
@@ -41053,9 +42164,11 @@ var Engine = class {
|
|
|
41053
42164
|
if (e instanceof Return) return;
|
|
41054
42165
|
if (e instanceof NeedsDeeperStack) throw e;
|
|
41055
42166
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
42167
|
+
if (e instanceof OutOfSteps) outOfSteps = e;
|
|
41056
42168
|
throw e;
|
|
41057
42169
|
}
|
|
41058
42170
|
}, text2, msg);
|
|
42171
|
+
if (outOfSteps) throw outOfSteps;
|
|
41059
42172
|
return;
|
|
41060
42173
|
}
|
|
41061
42174
|
const actual = this.x(s.e, env);
|
|
@@ -41153,6 +42266,8 @@ var Engine = class {
|
|
|
41153
42266
|
return null;
|
|
41154
42267
|
case "paren":
|
|
41155
42268
|
return sub2(e.e);
|
|
42269
|
+
case "httpCall":
|
|
42270
|
+
return this.httpCall(e, env);
|
|
41156
42271
|
case "today":
|
|
41157
42272
|
return PyDate.today();
|
|
41158
42273
|
case "date": {
|
|
@@ -41316,17 +42431,37 @@ var Engine = class {
|
|
|
41316
42431
|
// ── running a program or its tests ──────────────────────────────────────────────────────────────────────────
|
|
41317
42432
|
runMain(mod) {
|
|
41318
42433
|
const main = mod.r.program.main ?? [];
|
|
41319
|
-
|
|
41320
|
-
|
|
41321
|
-
|
|
41322
|
-
|
|
41323
|
-
|
|
41324
|
-
|
|
41325
|
-
|
|
41326
|
-
|
|
41327
|
-
|
|
41328
|
-
|
|
41329
|
-
|
|
42434
|
+
this.fillStores(mod);
|
|
42435
|
+
if (main.length) {
|
|
42436
|
+
const frame = { file: mod.file, line: 0 };
|
|
42437
|
+
this.withFrame(frame, () => {
|
|
42438
|
+
const env = { mod, locals: /* @__PURE__ */ new Map(), frame };
|
|
42439
|
+
try {
|
|
42440
|
+
this.block(main, env);
|
|
42441
|
+
} catch (e) {
|
|
42442
|
+
if (e instanceof Return) return;
|
|
42443
|
+
throw e;
|
|
42444
|
+
}
|
|
42445
|
+
});
|
|
42446
|
+
}
|
|
42447
|
+
this.saveStores(mod);
|
|
42448
|
+
}
|
|
42449
|
+
/** Each stored list, filled from its file (data/<name>.json); a missing file is an empty list. */
|
|
42450
|
+
fillStores(mod) {
|
|
42451
|
+
if (!this.dataFiles) return;
|
|
42452
|
+
for (const st of mod.stores ?? []) {
|
|
42453
|
+
const file = storeFile(st.s);
|
|
42454
|
+
const text2 = this.dataFiles.load(file);
|
|
42455
|
+
if (text2 == null) continue;
|
|
42456
|
+
const frame = { file: mod.file, line: st.s.line };
|
|
42457
|
+
this.withFrame(frame, () => {
|
|
42458
|
+
st.list.splice(0, st.list.length, ...storeFromText(text2, st.cls, file, (given) => this.newRecord(st.cls, given)));
|
|
42459
|
+
});
|
|
42460
|
+
}
|
|
42461
|
+
}
|
|
42462
|
+
saveStores(mod) {
|
|
42463
|
+
if (!this.dataFiles) return;
|
|
42464
|
+
for (const st of mod.stores ?? []) this.dataFiles.save(storeFile(st.s), storeToText(st.list, st.cls));
|
|
41330
42465
|
}
|
|
41331
42466
|
runTest(mod, t) {
|
|
41332
42467
|
const frame = { file: mod.file, line: t.line };
|
|
@@ -41349,13 +42484,13 @@ function notCompiled(results) {
|
|
|
41349
42484
|
Nothing was run: fix the problems first.
|
|
41350
42485
|
`, notCompiled: true, steps: [] };
|
|
41351
42486
|
}
|
|
41352
|
-
function runInProcess({ entry: entry3, cwd, deeper = false, readText = null } = {}) {
|
|
42487
|
+
function runInProcess({ entry: entry3, cwd, deeper = false, readText = null, store = null, http = null } = {}) {
|
|
41353
42488
|
const broken = notCompiled([entry3]);
|
|
41354
42489
|
if (broken) return broken;
|
|
41355
42490
|
const uses = pythonModulesUsed([entry3]);
|
|
41356
42491
|
if (uses.length) return { status: 2, stdout: "", stderr: `${refusalText(uses)}
|
|
41357
42492
|
`, refused: uses };
|
|
41358
|
-
const eng = new Engine({ cwd, deeper, readText });
|
|
42493
|
+
const eng = new Engine({ cwd, deeper, readText, store, http });
|
|
41359
42494
|
let stderr = "", status = 0;
|
|
41360
42495
|
try {
|
|
41361
42496
|
const mod = eng.load(entry3);
|
|
@@ -41371,13 +42506,13 @@ function runInProcess({ entry: entry3, cwd, deeper = false, readText = null } =
|
|
|
41371
42506
|
}
|
|
41372
42507
|
return { status, stdout: eng.out.join(""), stderr };
|
|
41373
42508
|
}
|
|
41374
|
-
function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
|
|
42509
|
+
function testInProcess({ results, cwd, deeper = false, readText = null, http = null } = {}) {
|
|
41375
42510
|
const broken = notCompiled(results);
|
|
41376
42511
|
if (broken) return broken;
|
|
41377
42512
|
const uses = pythonModulesUsed(results);
|
|
41378
42513
|
if (uses.length) return { status: 2, stdout: "", stderr: `${refusalText(uses)}
|
|
41379
42514
|
`, refused: uses };
|
|
41380
|
-
const eng = new Engine({ cwd, deeper, readText });
|
|
42515
|
+
const eng = new Engine({ cwd, deeper, readText, http });
|
|
41381
42516
|
const mods = [];
|
|
41382
42517
|
const srcMods = [];
|
|
41383
42518
|
for (const r of results) {
|
|
@@ -43124,22 +44259,26 @@ var end = (repo, at2, extra = {}) => ({ repo: repo.name, member: at2.member, lab
|
|
|
43124
44259
|
var distinctive = (segs) => segs.some((s) => s !== "*");
|
|
43125
44260
|
var lower2 = (segs) => segs.map((s) => s.toLowerCase());
|
|
43126
44261
|
var pathMatch = (a, b) => segsMatch(lower2(a), lower2(b));
|
|
43127
|
-
function buildTrace(repos) {
|
|
44262
|
+
function buildTrace(repos, { core = null } = {}) {
|
|
43128
44263
|
const names = /* @__PURE__ */ new Set();
|
|
43129
44264
|
const read = repos.map((r) => {
|
|
43130
44265
|
if (!r.name || names.has(r.name)) throw new Error(`Each repository needs its own name; "${r.name}" is used twice.`);
|
|
43131
44266
|
names.add(r.name);
|
|
43132
|
-
const
|
|
43133
|
-
const
|
|
44267
|
+
const other = r.files.filter((f) => !/\.thunder$/i.test(f.path));
|
|
44268
|
+
const model = thunderModel(other, { name: r.name });
|
|
44269
|
+
const facts = serviceFacts(model, other);
|
|
44270
|
+
const cf = r.coreFacts ?? (core ? core(r.files) : { routes: [], requests: [], unknown: [], files: 0 });
|
|
44271
|
+
for (const k of ["routes", "requests", "unknown"]) facts[k] = [...facts[k], ...cf[k]];
|
|
44272
|
+
const coreFiles = cf.files;
|
|
43134
44273
|
const real = (x) => !isTestFile(x.file);
|
|
43135
|
-
const data = dataFacts(
|
|
44274
|
+
const data = dataFacts(other, model);
|
|
43136
44275
|
const testItems = ["routes", "listeners", "requests", "publishes"].reduce((n, k) => n + facts[k].filter((x) => !real(x)).length, 0) + data.testItems;
|
|
43137
44276
|
return {
|
|
43138
44277
|
name: r.name,
|
|
43139
44278
|
sha: r.sha ?? null,
|
|
43140
44279
|
dirty: !!r.dirty,
|
|
43141
|
-
files: model.files.length,
|
|
43142
|
-
languages: [
|
|
44280
|
+
files: model.files.length + coreFiles,
|
|
44281
|
+
languages: [.../* @__PURE__ */ new Set([...model.files.map((f) => f.language), ...coreFiles ? ["thunder"] : []])].sort(),
|
|
43143
44282
|
routes: facts.routes.filter(real),
|
|
43144
44283
|
listeners: facts.listeners.filter(real),
|
|
43145
44284
|
requests: facts.requests.filter(real),
|
|
@@ -43405,11 +44544,107 @@ function writeRuleAcross(files, { decision, rule, when }) {
|
|
|
43405
44544
|
return { ...result, ok: true };
|
|
43406
44545
|
}
|
|
43407
44546
|
|
|
44547
|
+
// src/core/kind.mjs
|
|
44548
|
+
var MISSION_KEYWORDS = /* @__PURE__ */ new Set([
|
|
44549
|
+
"mission",
|
|
44550
|
+
"note",
|
|
44551
|
+
"goal",
|
|
44552
|
+
"why",
|
|
44553
|
+
"requires",
|
|
44554
|
+
"requires_skill",
|
|
44555
|
+
"demonstrates",
|
|
44556
|
+
"input",
|
|
44557
|
+
"output",
|
|
44558
|
+
"guarantees",
|
|
44559
|
+
"guarantee",
|
|
44560
|
+
"never",
|
|
44561
|
+
"constraints",
|
|
44562
|
+
"invariant",
|
|
44563
|
+
"assumptions",
|
|
44564
|
+
"risks",
|
|
44565
|
+
"target",
|
|
44566
|
+
"style",
|
|
44567
|
+
"verify",
|
|
44568
|
+
"errors",
|
|
44569
|
+
"examples",
|
|
44570
|
+
"service",
|
|
44571
|
+
"api",
|
|
44572
|
+
"event",
|
|
44573
|
+
"database",
|
|
44574
|
+
"architecture",
|
|
44575
|
+
"selection",
|
|
44576
|
+
"use",
|
|
44577
|
+
"title",
|
|
44578
|
+
"for",
|
|
44579
|
+
"persona",
|
|
44580
|
+
"customer",
|
|
44581
|
+
"problem",
|
|
44582
|
+
"evidence",
|
|
44583
|
+
"outcome",
|
|
44584
|
+
"metric",
|
|
44585
|
+
"scope",
|
|
44586
|
+
"non_goal",
|
|
44587
|
+
"owner",
|
|
44588
|
+
"unknown",
|
|
44589
|
+
"question",
|
|
44590
|
+
"assumption",
|
|
44591
|
+
"experience",
|
|
44592
|
+
"pattern",
|
|
44593
|
+
"style_intent",
|
|
44594
|
+
"decision",
|
|
44595
|
+
"property",
|
|
44596
|
+
"scenario",
|
|
44597
|
+
"evaluation",
|
|
44598
|
+
"capability",
|
|
44599
|
+
"interface",
|
|
44600
|
+
"component",
|
|
44601
|
+
"artifact",
|
|
44602
|
+
"outcome_contract",
|
|
44603
|
+
"release",
|
|
44604
|
+
"result",
|
|
44605
|
+
"learning",
|
|
44606
|
+
"test",
|
|
44607
|
+
"data",
|
|
44608
|
+
"waiver",
|
|
44609
|
+
"command",
|
|
44610
|
+
"on",
|
|
44611
|
+
"lifecycle",
|
|
44612
|
+
"always",
|
|
44613
|
+
"eventually",
|
|
44614
|
+
"until",
|
|
44615
|
+
"conflict",
|
|
44616
|
+
"implement",
|
|
44617
|
+
"requires_skills",
|
|
44618
|
+
"approval",
|
|
44619
|
+
"inferred",
|
|
44620
|
+
"maps_to",
|
|
44621
|
+
"needs_review",
|
|
44622
|
+
"source",
|
|
44623
|
+
"confidence"
|
|
44624
|
+
]);
|
|
44625
|
+
function firstCodeLine(source) {
|
|
44626
|
+
for (const raw of String(source).split(/\r?\n/)) {
|
|
44627
|
+
const line = raw.trim();
|
|
44628
|
+
if (line && !line.startsWith("#")) return { text: line, indented: raw.length > 0 && /^\s/.test(raw) };
|
|
44629
|
+
}
|
|
44630
|
+
return null;
|
|
44631
|
+
}
|
|
44632
|
+
function fileKind(source) {
|
|
44633
|
+
const first = firstCodeLine(source);
|
|
44634
|
+
if (!first) return { kind: "mission", reason: "the file has no lines yet" };
|
|
44635
|
+
const m = /^([a-z_]+)(?:\s+([A-Za-z_][\w.-]*))?\s*$/.exec(first.text);
|
|
44636
|
+
if (!first.indented && m && MISSION_KEYWORDS.has(m[1])) return { kind: "mission", reason: `its first line starts with the mission keyword "${m[1]}"` };
|
|
44637
|
+
return { kind: "program", reason: `its first line ("${first.text.length > 40 ? `${first.text.slice(0, 40)}\u2026` : first.text}") cannot start a mission` };
|
|
44638
|
+
}
|
|
44639
|
+
var isCoreProgram = (path, source) => /\.thunder$/i.test(path) && fileKind(source ?? "").kind === "program";
|
|
44640
|
+
|
|
43408
44641
|
// src/review.mjs
|
|
43409
44642
|
var REVIEW_SCHEMA = "thunder-review-v1";
|
|
43410
44643
|
var SEVERITY_ORDER = ["risk", "meaning", "form"];
|
|
43411
44644
|
var KIND_ORDER = [
|
|
43412
44645
|
"unreadable",
|
|
44646
|
+
"test-fails",
|
|
44647
|
+
"callers",
|
|
43413
44648
|
"not-read",
|
|
43414
44649
|
"infrastructure",
|
|
43415
44650
|
"stop-removed",
|
|
@@ -44020,7 +45255,7 @@ function mostlyIn(a, b) {
|
|
|
44020
45255
|
}
|
|
44021
45256
|
return hit / want.length >= 0.75;
|
|
44022
45257
|
}
|
|
44023
|
-
function thunderReview(oldFiles, newFiles) {
|
|
45258
|
+
function thunderReview(oldFiles, newFiles, { core = null, context = null } = {}) {
|
|
44024
45259
|
detailsCache = /* @__PURE__ */ new WeakMap();
|
|
44025
45260
|
const A = side(oldFiles || []), B = side(newFiles || []);
|
|
44026
45261
|
const items = [];
|
|
@@ -44099,11 +45334,14 @@ function thunderReview(oldFiles, newFiles) {
|
|
|
44099
45334
|
{ before: null, after: n.text }
|
|
44100
45335
|
));
|
|
44101
45336
|
compareThings(A, B, items);
|
|
45337
|
+
const coreRead = core ? coreReview(core, oldFiles || [], newFiles || [], context, items) : { paths: /* @__PURE__ */ new Set(), result: null };
|
|
45338
|
+
const corePaths = coreRead.paths;
|
|
44102
45339
|
const paths = [.../* @__PURE__ */ new Set([...A.sources.keys(), ...B.sources.keys()])];
|
|
44103
45340
|
const notRead = [];
|
|
44104
45341
|
for (const p of paths) {
|
|
44105
45342
|
const before = A.sources.get(p), after = B.sources.get(p);
|
|
44106
45343
|
if (before === after) continue;
|
|
45344
|
+
if (corePaths.has(p)) continue;
|
|
44107
45345
|
const lang = !isInfra(p) && readableLanguage(p);
|
|
44108
45346
|
if (!lang) {
|
|
44109
45347
|
if (isInfra(p)) items.push(item2("infrastructure", "risk", p, { file: p, line: 1 }, `${before == null ? "New" : after == null ? "Removed" : "Changed"} infrastructure or pipeline file. Thunder does not read these in this version, so check it yourself.`, before != null && after != null ? lineChanges(before.split("\n"), after.split("\n")) : null));
|
|
@@ -44169,7 +45407,39 @@ function thunderReview(oldFiles, newFiles) {
|
|
|
44169
45407
|
const count = (s) => items.filter((x) => x.severity === s).length;
|
|
44170
45408
|
const summary = { meaning: count("meaning"), risk: count("risk"), form: count("form"), unchanged, files: paths.filter((p) => A.sources.get(p) !== B.sources.get(p)).length };
|
|
44171
45409
|
const onlyNotRead = !items.length && summary.files && notRead.length === summary.files;
|
|
44172
|
-
|
|
45410
|
+
const out = { schema: REVIEW_SCHEMA, summary, says: onlyNotRead ? "Only files Thunder does not read changed." : summaryLine(summary), items, notRead };
|
|
45411
|
+
if (coreRead.result) Object.defineProperty(out, "core", { value: coreRead.result, enumerable: false });
|
|
45412
|
+
return out;
|
|
45413
|
+
}
|
|
45414
|
+
function coreKind(c) {
|
|
45415
|
+
if (c.change === "not-compiled") return "unreadable";
|
|
45416
|
+
if (c.kind === "test" && c.severity === "risk" && c.change !== "removed") return "test-fails";
|
|
45417
|
+
if (c.change === "added" || c.change === "removed" || c.change === "renamed") return c.kind === "never" && c.change === "removed" ? "stop-removed" : c.change;
|
|
45418
|
+
if (c.kind === "keep") return "rule-limit";
|
|
45419
|
+
if (c.kind === "function" && c.behaviour?.changed) return "rule-answer";
|
|
45420
|
+
if (c.kind === "never") return "stop-changed";
|
|
45421
|
+
if (c.kind === "record" || c.kind === "store") return "thing";
|
|
45422
|
+
if (c.kind === "main") return "outside";
|
|
45423
|
+
return "steps";
|
|
45424
|
+
}
|
|
45425
|
+
var CORE_SUBJECT = { keep: (c) => `${c.subject} (kept value)`, main: (c) => c.subject };
|
|
45426
|
+
function coreReview(coreChanges, oldFiles, newFiles, context, items) {
|
|
45427
|
+
const core = (fs) => fs.filter((f) => f && isCoreProgram(f.path, f.source));
|
|
45428
|
+
const merge = (changed, extra) => {
|
|
45429
|
+
const have = new Set(changed.map((f) => f.path));
|
|
45430
|
+
return [...changed, ...core(extra ?? []).filter((f) => !have.has(f.path))];
|
|
45431
|
+
};
|
|
45432
|
+
const oldCore = core(oldFiles), newCore = core(newFiles);
|
|
45433
|
+
if (!oldCore.length && !newCore.length) return { paths: /* @__PURE__ */ new Set(), result: null };
|
|
45434
|
+
const r = coreChanges(merge(oldCore, context?.old), merge(newCore, context?.new));
|
|
45435
|
+
for (const c of r.changes) {
|
|
45436
|
+
const look = (c.affects ?? []).slice(0, 6).map((x) => `${x.subject} (\`${x.file}:${x.line}\`${x.test ? `, ${x.test === "fails" ? "**fails now**" : "passes"}` : ""})`);
|
|
45437
|
+
const more = (c.affects?.length ?? 0) > 6 ? `, and ${c.affects.length - 6} more` : "";
|
|
45438
|
+
const says = look.length ? `${c.says} Look again at: ${look.join(", ")}${more}.` : c.says;
|
|
45439
|
+
const evidence = c.before || c.after ? { before: c.before, after: c.after } : null;
|
|
45440
|
+
items.push(item2(coreKind(c), c.severity, (CORE_SUBJECT[c.kind] ?? ((x) => x.subject))(c), { file: c.file, line: c.line }, says, evidence));
|
|
45441
|
+
}
|
|
45442
|
+
return { paths: new Set([...oldCore, ...newCore].map((f) => f.path)), result: r };
|
|
44173
45443
|
}
|
|
44174
45444
|
var plural3 = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
44175
45445
|
function summaryLine(s) {
|