@skillstech/thunderlang 1.6.1 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +121 -0
- package/README.md +10 -3
- package/dist/core.cjs +264 -47
- package/dist/index.cjs +9118 -1077
- package/dist/learn.cjs +1419 -90
- package/package.json +1 -1
- package/src/ai.mjs +2 -1
- package/src/atlas.mjs +2 -1
- package/src/behaviour.mjs +246 -0
- package/src/cli-main.mjs +3015 -0
- package/src/cli.mjs +9 -2799
- package/src/conflict.mjs +0 -0
- package/src/core/ThunderDotnet.cs +195 -0
- package/src/core/check.mjs +316 -10
- package/src/core/cli.mjs +67 -10
- package/src/core/csharp-run.mjs +29 -8
- package/src/core/diagnostics.mjs +12 -1
- package/src/core/engine-core.mjs +161 -20
- package/src/core/engine-values.mjs +1 -0
- package/src/core/engine.mjs +131 -7
- package/src/core/go-run.mjs +3 -2
- package/src/core/index.mjs +6 -2
- package/src/core/java-run.mjs +3 -3
- package/src/core/kind.mjs +45 -0
- package/src/core/lexer.mjs +16 -2
- package/src/core/parser.mjs +254 -22
- package/src/core/project-root.mjs +18 -0
- package/src/core/project.mjs +18 -18
- package/src/core/react-run.mjs +3 -3
- package/src/core/runtime-go/thunder_runtime.go +269 -1
- package/src/core/runtime-npm.mjs +79 -0
- package/src/core/runtime-python.mjs +365 -3
- package/src/core/runtime-react.mjs +2 -1
- package/src/core/runtime-typescript.mjs +155 -6
- package/src/core/rust-run.mjs +3 -2
- package/src/core/serving.mjs +12 -0
- package/src/core/store-format.mjs +110 -0
- package/src/core/target-csharp.mjs +5 -1
- package/src/core/target-go.mjs +11 -4
- package/src/core/target-python.mjs +39 -6
- package/src/core/target-rust.mjs +1 -1
- package/src/core/target-typescript.mjs +95 -7
- package/src/core/typescript-run.mjs +14 -7
- package/src/core-changes-fs.mjs +28 -0
- package/src/core-changes.d.mts +67 -0
- package/src/core-changes.mjs +603 -0
- package/src/core-rules.mjs +146 -0
- package/src/core-services.d.mts +4 -0
- package/src/core-services.mjs +49 -0
- package/src/decision.mjs +2 -1
- package/src/distributed.mjs +2 -1
- package/src/emit.mjs +2 -2
- package/src/evidence.mjs +28 -0
- package/src/examples.d.mts +21 -0
- package/src/examples.mjs +175 -0
- package/src/focus.mjs +2 -1
- package/src/index.d.ts +4 -0
- package/src/index.mjs +4 -0
- package/src/intent-atlas.mjs +4 -3
- package/src/mcp.mjs +52 -6
- package/src/passport-fs.mjs +2 -1
- package/src/passport.mjs +2 -1
- package/src/privacy.mjs +2 -1
- package/src/program.d.mts +4 -0
- package/src/program.mjs +4 -0
- package/src/read-repo-fs.mjs +2 -1
- package/src/read-repo.mjs +3 -2
- package/src/report.mjs +3 -2
- package/src/review.mjs +71 -4
- package/src/select.mjs +2 -1
- package/src/semantic-diff.mjs +7 -6
- package/src/system.mjs +3 -2
- package/src/text-order.mjs +6 -0
- package/src/thunderize.mjs +2 -1
- package/src/trace-cli.mjs +8 -3
- package/src/trace-data.mjs +3 -2
- package/src/trace-fs.mjs +29 -3
- package/src/trace.mjs +27 -10
- package/src/write-across-cli.mjs +22 -4
- package/src/write-across.mjs +2 -1
- package/syntaxes/thunder.tmLanguage.json +196 -0
package/dist/learn.cjs
CHANGED
|
@@ -17187,6 +17187,9 @@ function sha256hex(input) {
|
|
|
17187
17187
|
}
|
|
17188
17188
|
var sha256 = (s) => `sha256:${sha256hex(String(s))}`;
|
|
17189
17189
|
|
|
17190
|
+
// src/text-order.mjs
|
|
17191
|
+
var byText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
17192
|
+
|
|
17190
17193
|
// src/style.mjs
|
|
17191
17194
|
var TOKEN_PATHS = [
|
|
17192
17195
|
"color.primary",
|
|
@@ -17250,7 +17253,7 @@ var SEMANTIC_TYPES = Object.keys(SEMANTIC);
|
|
|
17250
17253
|
var PRIMITIVE_TYPES = Object.keys(PRIMITIVE);
|
|
17251
17254
|
|
|
17252
17255
|
// src/emit.mjs
|
|
17253
|
-
var COMPILER_VERSION = "1.
|
|
17256
|
+
var COMPILER_VERSION = "1.8.0";
|
|
17254
17257
|
|
|
17255
17258
|
// src/lift.mjs
|
|
17256
17259
|
var IR_SCHEMA_VERSION = "0.1.0";
|
|
@@ -21970,16 +21973,16 @@ function powershellReading(src, file = "") {
|
|
|
21970
21973
|
KNOWN_FNS2 = /* @__PURE__ */ new Set();
|
|
21971
21974
|
return out;
|
|
21972
21975
|
}
|
|
21973
|
-
function psThings(src, file, { words: w, kindWords:
|
|
21976
|
+
function psThings(src, file, { words: w, kindWords: kindWords4, startValue: startValue2 }) {
|
|
21974
21977
|
const { things } = powershellReading(src, file);
|
|
21975
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"');
|
|
21976
21979
|
const kind = (t) => {
|
|
21977
21980
|
const x = String(t ?? "").toLowerCase();
|
|
21978
21981
|
if (!x) return null;
|
|
21979
|
-
if (/\[\]$/.test(x)) return
|
|
21982
|
+
if (/\[\]$/.test(x)) return kindWords4(`List<${String(t).slice(0, -2).replace(/^string$/i, "string").replace(/^int$/i, "int")}>`);
|
|
21980
21983
|
if (/(?:arraylist|list|collection|hashset)(?:\[|$)/.test(x)) return "a list";
|
|
21981
21984
|
if (/^(?:hashtable|dictionary|ordered)/.test(x)) return "a lookup table";
|
|
21982
|
-
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());
|
|
21983
21986
|
};
|
|
21984
21987
|
return things.map((t) => ({
|
|
21985
21988
|
kind: t.kind,
|
|
@@ -23548,7 +23551,7 @@ function rReading(src, file = "") {
|
|
|
23548
23551
|
KNOWN_FNS3 = /* @__PURE__ */ new Set();
|
|
23549
23552
|
return { fns, things: r.things.map(({ _methods, ...t }) => t), errors: [...r.errors].map(([name, line]) => ({ name, line })), tests: r.tests };
|
|
23550
23553
|
}
|
|
23551
|
-
function rThings(src, file, { words: w, kindWords:
|
|
23554
|
+
function rThings(src, file, { words: w, kindWords: kindWords4, startValue: startValue2 }) {
|
|
23552
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"');
|
|
23553
23556
|
return rReading(src, file).things.map((t) => ({
|
|
23554
23557
|
kind: t.kind,
|
|
@@ -23558,7 +23561,7 @@ function rThings(src, file, { words: w, kindWords: kindWords3, startValue: start
|
|
|
23558
23561
|
...t.doc ? { doc: t.doc } : {},
|
|
23559
23562
|
choices: t.choices,
|
|
23560
23563
|
memberRanges: t.memberRanges,
|
|
23561
|
-
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 }))
|
|
23562
23565
|
}));
|
|
23563
23566
|
}
|
|
23564
23567
|
|
|
@@ -28453,9 +28456,9 @@ function goDoc(src, at2, name) {
|
|
|
28453
28456
|
const t = d.replace(new RegExp(`^${name}\\s+(?:is|holds|represents)\\s+`), "").replace(new RegExp(`^${name}\\s+`), "");
|
|
28454
28457
|
return t.charAt(0).toUpperCase() + t.slice(1);
|
|
28455
28458
|
}
|
|
28456
|
-
function makeThingReaders({ words: words13, kindWords:
|
|
28459
|
+
function makeThingReaders({ words: words13, kindWords: kindWords4, startValue: startValue2 }) {
|
|
28457
28460
|
const know = (name, type, start, params, line = null) => {
|
|
28458
|
-
const kind = type ?
|
|
28461
|
+
const kind = type ? kindWords4(type) : null;
|
|
28459
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;
|
|
28460
28463
|
return { name, label: words13(name.replace(/^[_$]+|_$/g, "")), kind, start: said, line };
|
|
28461
28464
|
};
|
|
@@ -30060,7 +30063,7 @@ function callsSummary(model) {
|
|
|
30060
30063
|
else p.calls++;
|
|
30061
30064
|
if (p.examples.length < 3) p.examples.push({ from: a.id, to: b.id, says: l.kind === "sends-to" ? `${a.label} sends ${l.method ? `${l.method} ${l.path}` : l.event ? `the event ${l.event}` : `a task`} to ${b.label}` : `${a.label} calls ${b.label}` });
|
|
30062
30065
|
}
|
|
30063
|
-
return [...pairs2.values()].sort((x, y) => y.calls + y.sends - (x.calls + x.sends) || x.from
|
|
30066
|
+
return [...pairs2.values()].sort((x, y) => y.calls + y.sends - (x.calls + x.sends) || byText(x.from, y.from) || byText(x.to, y.to));
|
|
30064
30067
|
}
|
|
30065
30068
|
|
|
30066
30069
|
// src/flow/ts-parse.mjs
|
|
@@ -35301,12 +35304,25 @@ function lev(a, b) {
|
|
|
35301
35304
|
}
|
|
35302
35305
|
|
|
35303
35306
|
// src/core/lexer.mjs
|
|
35304
|
-
var SYMS = ["==", "!=", "<>", "<=", ">=", "+", "-", "*", "/", "(", ")", "[", "]", ",", ":", ".", "=", "<", ">"];
|
|
35307
|
+
var SYMS = ["==", "!=", "<>", "<=", ">=", "+", "-", "*", "/", "(", ")", "[", "]", ",", ":", ".", "=", "<", ">", "?"];
|
|
35305
35308
|
var WORD_START = /[\p{L}_]/u;
|
|
35306
35309
|
var WORD_CHAR = /[\p{L}\p{N}_]/u;
|
|
35307
35310
|
function tokenizeLine(text2, line, colOffset = 0) {
|
|
35308
35311
|
const toks2 = [];
|
|
35309
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
|
+
}
|
|
35310
35326
|
const at2 = (k = 0) => text2[i + k];
|
|
35311
35327
|
while (i < text2.length) {
|
|
35312
35328
|
const c = at2();
|
|
@@ -35611,6 +35627,9 @@ function collectNames(nodes, names) {
|
|
|
35611
35627
|
} else if (w0 === "keep") {
|
|
35612
35628
|
const k = splitTop4(ts, (t) => isWord(t, "at"));
|
|
35613
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)));
|
|
35614
35633
|
} else if (w0 === "receive") {
|
|
35615
35634
|
for (const p of paramGroups(ts.slice(1))) add2("var", p.words);
|
|
35616
35635
|
} else if (w0 === "for" && isWord(ts[1], "each")) {
|
|
@@ -35629,6 +35648,29 @@ function collectNames(nodes, names) {
|
|
|
35629
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 });
|
|
35630
35649
|
}
|
|
35631
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);
|
|
35632
35674
|
} else if ((w0 === "a" || w0 === "an") && isWord(ts[ts.length - 2], "has")) {
|
|
35633
35675
|
const words13 = ts.slice(1, -2);
|
|
35634
35676
|
add2("record", words13);
|
|
@@ -35669,6 +35711,10 @@ function rememberName(ts) {
|
|
|
35669
35711
|
const end2 = ts.findIndex((t) => isWord(t, "as") || isWord(t, "starting") || isSym(t, ","));
|
|
35670
35712
|
return stripArticle(end2 < 0 ? ts : ts.slice(0, end2));
|
|
35671
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
|
+
}
|
|
35672
35718
|
function paramGroups(ts) {
|
|
35673
35719
|
const groups3 = [];
|
|
35674
35720
|
let cur = [];
|
|
@@ -35704,7 +35750,8 @@ function paramGroups(ts) {
|
|
|
35704
35750
|
}
|
|
35705
35751
|
}
|
|
35706
35752
|
const k = g.findIndex((t) => isWord(t, "as"));
|
|
35707
|
-
|
|
35753
|
+
const raw = k < 0 ? g : g.slice(0, k);
|
|
35754
|
+
return { words: stripArticle(raw), raw, typeTokens: k < 0 ? null : g.slice(k + 1), defaultTokens };
|
|
35708
35755
|
});
|
|
35709
35756
|
}
|
|
35710
35757
|
var Stream = class {
|
|
@@ -35830,6 +35877,15 @@ var ExprParser = class {
|
|
|
35830
35877
|
}
|
|
35831
35878
|
if (s.word("in")) return wrap2({ k: "contains", l: this.add(s, o), r: l, line });
|
|
35832
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
|
+
}
|
|
35833
35889
|
return { k: "cmp", op: neg2 ? "!=" : "==", l, r: this.add(s, o), line };
|
|
35834
35890
|
}
|
|
35835
35891
|
return l;
|
|
@@ -35984,9 +36040,50 @@ var ExprParser = class {
|
|
|
35984
36040
|
const key = keyOf(run.slice(0, k));
|
|
35985
36041
|
return { k: "record", name: this.names.records.has(key) ? key : key.replace(/s$/, "") };
|
|
35986
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
|
+
}
|
|
35987
36057
|
primary(s, o) {
|
|
35988
36058
|
const t = s.peek();
|
|
35989
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
|
+
}
|
|
35990
36087
|
if (!t) s.fail("A value is missing at the end of this line.", null, "TC108");
|
|
35991
36088
|
if (t.t === "num") {
|
|
35992
36089
|
s.next();
|
|
@@ -36006,6 +36103,13 @@ var ExprParser = class {
|
|
|
36006
36103
|
s.next();
|
|
36007
36104
|
return { k: "str", parts: t.parts.map((p) => typeof p === "string" ? p : { e: this.parse(p.tokens, line), source: p.source }), line };
|
|
36008
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
|
+
}
|
|
36009
36113
|
if (isSym(t, "(")) {
|
|
36010
36114
|
s.next();
|
|
36011
36115
|
const e = this.expr(s, {});
|
|
@@ -36091,22 +36195,31 @@ var ExprParser = class {
|
|
|
36091
36195
|
}
|
|
36092
36196
|
if (RESERVED2.has(w)) s.fail(`"${t.text}" is a Thunder word and can't start a value here.`, null, "TC105");
|
|
36093
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
|
+
}
|
|
36094
36216
|
let off = run[0]?.lower === "new" && run.length > 1 ? 1 : 0;
|
|
36095
36217
|
const recK = this.longest(run.slice(off), (key) => this.names.records.has(key));
|
|
36096
36218
|
const wantsRecord = o.article || off || isWord(s.peek(), "with") || !this.longest(run, (key) => this.names.known.has(key));
|
|
36097
36219
|
if (recK && wantsRecord && recK + off === run.length) {
|
|
36098
36220
|
s.i -= run.length - off - recK;
|
|
36099
36221
|
const name = keyOf(run.slice(off, off + recK));
|
|
36100
|
-
const fields =
|
|
36101
|
-
if (s.word("with")) {
|
|
36102
|
-
do {
|
|
36103
|
-
const fr = this.wordRun(s);
|
|
36104
|
-
if (!fr.length) s.fail(`I expected a field name after "with" (for example: with name "Ann").`, null, "TC108");
|
|
36105
|
-
const fk2 = this.longest(fr, (key) => this.names.fields.has(key)) || fr.length;
|
|
36106
|
-
s.i -= fr.length - fk2;
|
|
36107
|
-
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 });
|
|
36108
|
-
} while ((isSym(s.peek(), ",") || isWord(s.peek(), "and")) && this.fieldAhead(s, 1) && s.next());
|
|
36109
|
-
}
|
|
36222
|
+
const fields = this.recordFields(s, line);
|
|
36110
36223
|
const node = { k: "new", record: name, fields, line };
|
|
36111
36224
|
if (!fields.length && this.open) this.open.push(node);
|
|
36112
36225
|
return node;
|
|
@@ -36141,7 +36254,7 @@ var ExprParser = class {
|
|
|
36141
36254
|
function parseCore(source, { seed = null } = {}) {
|
|
36142
36255
|
const { lines, diagnostics } = lex3(source);
|
|
36143
36256
|
const tree = buildBlocks(lines, diagnostics);
|
|
36144
|
-
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 ?? []) };
|
|
36145
36258
|
collectNames(tree, names);
|
|
36146
36259
|
const ep = new ExprParser(names);
|
|
36147
36260
|
const body2 = parseBlock(tree, ep, names, diagnostics, { top: true });
|
|
@@ -36174,12 +36287,12 @@ function parseBlock(nodes, ep, names, diagnostics, ctx) {
|
|
|
36174
36287
|
}
|
|
36175
36288
|
return out;
|
|
36176
36289
|
}
|
|
36177
|
-
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"]);
|
|
36178
36291
|
function fieldBlock(n, diagnostics = []) {
|
|
36179
36292
|
const ts = n.tokens;
|
|
36180
36293
|
if (!n.children.length || !isSym(ts[ts.length - 1], ":")) return null;
|
|
36181
36294
|
const w0 = ts[0]?.t === "word" ? ts[0].lower : "";
|
|
36182
|
-
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;
|
|
36183
36296
|
return n.children.map((c) => {
|
|
36184
36297
|
const colon = c.tokens.findIndex((t) => isSym(t, ":"));
|
|
36185
36298
|
const nameTs = colon > 0 ? c.tokens.slice(0, colon) : [];
|
|
@@ -36247,7 +36360,11 @@ function fillBlock(open, lines, n, ep, names) {
|
|
|
36247
36360
|
}
|
|
36248
36361
|
function nameWords2(ts, line, what) {
|
|
36249
36362
|
const words13 = stripArticle(ts);
|
|
36250
|
-
if (!words13.length)
|
|
36363
|
+
if (!words13.length) {
|
|
36364
|
+
const only = ts.length === 1 && ts[0].t === "word" ? ts[0].text : null;
|
|
36365
|
+
if (only) throw new CoreError(diag("TC108", line, `"${only}" can't be a name on its own: Thunder skips "a", "an", and "the" in names ("the total" is "total").`, `Use a word that says what it holds, like "first number" or "amount".`));
|
|
36366
|
+
throw new CoreError(diag("TC108", line, `${what} is missing a name.`));
|
|
36367
|
+
}
|
|
36251
36368
|
for (const t of words13) {
|
|
36252
36369
|
if (t.t !== "word") throw new CoreError(diag("TC105", line, `A name can only use words, but "${show(t)}" is not a word.`));
|
|
36253
36370
|
if (RESERVED2.has(t.lower)) throw new CoreError(diag("TC202", line, `A name can't contain the word "${t.text}", because it belongs to Thunder.`, `Try a name without "${t.text}".`));
|
|
@@ -36268,6 +36385,26 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36268
36385
|
};
|
|
36269
36386
|
const w0 = ts[0].t === "word" ? ts[0].lower : "";
|
|
36270
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
|
+
}
|
|
36271
36408
|
if (w0 === "say" || w0 === "print") return { k: "say", e: E(rest2), line };
|
|
36272
36409
|
if (w0 === "set") {
|
|
36273
36410
|
const at2 = splitTop4(rest2, (t) => isWord(t, "to"));
|
|
@@ -36278,20 +36415,37 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36278
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.");
|
|
36279
36416
|
return { k: "set", target, e: E(rest2.slice(at2 + 1)), line };
|
|
36280
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
|
+
}
|
|
36281
36425
|
if (w0 === "keep") {
|
|
36282
36426
|
const at2 = splitTop4(rest2, (t) => isWord(t, "at"));
|
|
36283
36427
|
if (at2 < 0) fail2("TC108", '"Keep" needs "at": Keep tax rate at 7%.');
|
|
36284
36428
|
return { k: "keep", ...nameWords2(rest2.slice(0, at2), line, '"Keep"'), e: E(rest2.slice(at2 + 1)), line };
|
|
36285
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
|
+
};
|
|
36286
36438
|
if (w0 === "give") {
|
|
36287
36439
|
let r = rest2;
|
|
36288
36440
|
if (isWord(r[0], "back")) r = r.slice(1);
|
|
36289
|
-
|
|
36441
|
+
const st = statusAt(r, "with");
|
|
36442
|
+
return { k: "give", e: st.r.length ? E(st.r) : { k: "nothing", line }, status: st.status, line };
|
|
36290
36443
|
}
|
|
36291
36444
|
if (w0 === "stop") {
|
|
36292
36445
|
let r = rest2;
|
|
36293
36446
|
if (isWord(r[0], "with") || isSym(r[0], ":")) r = r.slice(1);
|
|
36294
|
-
|
|
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 };
|
|
36295
36449
|
}
|
|
36296
36450
|
if (w0 === "if" && keyOf(ts.slice(0, 3)) === "if this fails") {
|
|
36297
36451
|
header();
|
|
@@ -36300,6 +36454,28 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36300
36454
|
siblings.pop();
|
|
36301
36455
|
return { k: "tryFail", stmt: prev, handler: children(), line };
|
|
36302
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
|
+
}
|
|
36303
36479
|
if (w0 === "when" || w0 === "if") {
|
|
36304
36480
|
const cond = E(header().slice(1));
|
|
36305
36481
|
return { k: "if", branches: [{ cond, body: children(), line }], otherwise: null, line };
|
|
@@ -36349,7 +36525,7 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36349
36525
|
let r = 0;
|
|
36350
36526
|
while (kids2[r] && isWord(kids2[r].tokens[0], "receive")) {
|
|
36351
36527
|
const kid = kids2[r];
|
|
36352
|
-
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords2(p.
|
|
36528
|
+
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 })));
|
|
36353
36529
|
r++;
|
|
36354
36530
|
}
|
|
36355
36531
|
bodyNodes = kids2.slice(r);
|
|
@@ -36366,6 +36542,33 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36366
36542
|
}
|
|
36367
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.");
|
|
36368
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
|
+
}
|
|
36369
36572
|
if ((w0 === "a" || w0 === "an") && isWord(ts[ts.length - 2], "has") && isSym(ts[ts.length - 1], ":")) {
|
|
36370
36573
|
if (!ctx.top) fail2("TC402", 'A record ("A \u2026 has:") must be written at the left edge, not inside another block.');
|
|
36371
36574
|
const { name, text: text2 } = nameWords2(ts.slice(1, -2), line, "A record");
|
|
@@ -36391,11 +36594,48 @@ function parseStatement2(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
36391
36594
|
if (w0 === "use") {
|
|
36392
36595
|
if (!ctx.top) fail2("TC402", '"Use" must be written at the left edge of the file.');
|
|
36393
36596
|
const asAt = rest2.findIndex((t) => isWord(t, "as"));
|
|
36394
|
-
|
|
36597
|
+
let modTs = asAt < 0 ? rest2 : rest2.slice(0, asAt);
|
|
36598
|
+
const fromAt = modTs.findIndex((t) => isWord(t, "from"));
|
|
36599
|
+
let ecosystem = "python";
|
|
36600
|
+
if (fromAt >= 0) {
|
|
36601
|
+
const eco = modTs.slice(fromAt + 1);
|
|
36602
|
+
const plain = (t) => t && typeof t.parts === "undefined" ? null : t && t.parts.every((x) => typeof x === "string") ? t.parts.join("") : null;
|
|
36603
|
+
const word0 = eco[0]?.t === "word" ? eco[0].text.toLowerCase() : "";
|
|
36604
|
+
let said = eco.length === 1 && eco[0].t === "word" ? word0 : "";
|
|
36605
|
+
if (eco.length === 2 && eco[0].t === "sym" && eco[0].text === "." && eco[1].t === "word" && eco[1].text.toLowerCase() === "net") said = "dotnet";
|
|
36606
|
+
if (word0 === "nuget") {
|
|
36607
|
+
const pkg = eco[1]?.t === "str" ? plain(eco[1]) : null;
|
|
36608
|
+
const ver2 = isWord(eco[2], "version") && eco[3]?.t === "str" ? plain(eco[3]) : null;
|
|
36609
|
+
if (!pkg || !ver2 || eco.length !== 4 || !/^[A-Za-z0-9_.-]+$/.test(pkg) || !/^\d+(\.\d+){1,3}([-+][\w.-]+)?$/.test(ver2)) fail2("TC108", 'Name the NuGet package and its version: Use "Humanizer.NumberToWordsExtension" from NuGet "Humanizer.Core" version "2.14.1" as words.');
|
|
36610
|
+
said = "nuget";
|
|
36611
|
+
modTs = modTs.slice(0, fromAt);
|
|
36612
|
+
ecosystem = said;
|
|
36613
|
+
var nuget = { package: pkg, version: ver2 };
|
|
36614
|
+
} else {
|
|
36615
|
+
if (!["python", "npm", "dotnet"].includes(said)) fail2("TC108", `A library comes from Python, npm, .NET, or NuGet, for example: Use csv from Python as csv, Use "date-fns" from npm as dates, or Use "System.IO.Path" from .NET as paths.`);
|
|
36616
|
+
ecosystem = said;
|
|
36617
|
+
modTs = modTs.slice(0, fromAt);
|
|
36618
|
+
}
|
|
36619
|
+
}
|
|
36620
|
+
if (ecosystem === "dotnet" || ecosystem === "nuget") {
|
|
36621
|
+
const t = modTs[0];
|
|
36622
|
+
const type = modTs.length === 1 && t.t === "str" && t.parts.every((x) => typeof x === "string") ? t.parts.join("") : null;
|
|
36623
|
+
if (type == null || !/^[A-Za-z_]\w*(\.[A-Za-z_]\w*)+$/.test(type)) fail2("TC108", 'Write a .NET type with its namespace, in quotes, for example: Use "System.IO.Path" from .NET as paths.');
|
|
36624
|
+
if (asAt < 0) fail2("TC108", `Give the type a name to use in Thunder: Use "${type}" from ${ecosystem === "nuget" ? "NuGet" : ".NET"} \u2026 as <name>.`);
|
|
36625
|
+
return { k: "use", module: type, ecosystem, ...ecosystem === "nuget" ? nuget : {}, ...nameWords2(rest2.slice(asAt + 1), line, '"Use"'), line };
|
|
36626
|
+
}
|
|
36627
|
+
if (ecosystem === "npm" || modTs[0]?.t === "str") {
|
|
36628
|
+
const t = modTs[0];
|
|
36629
|
+
const pkg = modTs.length === 1 && t.t === "str" && t.parts.every((x) => typeof x === "string") ? t.parts.join("") : null;
|
|
36630
|
+
if (pkg == null || !/^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(\/[\w.-]+)*$|^node:[a-z_/]+$/i.test(pkg)) fail2("TC108", 'Write an npm package in quotes, for example: Use "date-fns" from npm as dates.');
|
|
36631
|
+
if (ecosystem !== "npm") fail2("TC108", `Say where "${pkg}" comes from: Use "${pkg}" from npm as <name>.`);
|
|
36632
|
+
if (asAt < 0) fail2("TC108", `Give the package a name to use in Thunder: Use "${pkg}" from npm as <name>.`);
|
|
36633
|
+
return { k: "use", module: pkg, ecosystem, ...nameWords2(rest2.slice(asAt + 1), line, '"Use"'), line };
|
|
36634
|
+
}
|
|
36395
36635
|
const module2 = modTs.map((t) => t.t === "word" ? t.text : t.t === "sym" && t.text === "." ? "." : "\0").join("");
|
|
36396
|
-
if (!module2 || module2.includes("\0") || !/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$/.test(module2)) fail2("TC108", 'Write "Use <python module> as <name>", for example: Use csv as csv.');
|
|
36636
|
+
if (!module2 || module2.includes("\0") || !/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$/.test(module2)) fail2("TC108", 'Write "Use <python module> as <name>", for example: Use csv as csv. For npm: Use "date-fns" from npm as dates.');
|
|
36397
36637
|
const alias = asAt < 0 ? { name: module2.split(".")[0].toLowerCase(), text: module2.split(".")[0] } : nameWords2(rest2.slice(asAt + 1), line, '"Use"');
|
|
36398
|
-
return { k: "use", module: module2, ...alias, line };
|
|
36638
|
+
return { k: "use", module: module2, ecosystem, ...alias, line };
|
|
36399
36639
|
}
|
|
36400
36640
|
if (w0 === "test") {
|
|
36401
36641
|
if (!ctx.top) fail2("TC402", 'A "Test" block must be written at the left edge of the file.');
|
|
@@ -36507,7 +36747,7 @@ function parseScreen(n, ep, names, diagnostics) {
|
|
|
36507
36747
|
while (kids2[k] && isWord(kids2[k].tokens[0], "receive")) {
|
|
36508
36748
|
const kid = kids2[k];
|
|
36509
36749
|
try {
|
|
36510
|
-
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords2(p.
|
|
36750
|
+
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 })));
|
|
36511
36751
|
} catch (e) {
|
|
36512
36752
|
if (e instanceof CoreError) diagnostics.push(e.diagnostic);
|
|
36513
36753
|
else throw e;
|
|
@@ -36719,7 +36959,7 @@ var typeWords4 = (t) => {
|
|
|
36719
36959
|
case "optional":
|
|
36720
36960
|
return `${typeWords4(t.of)} or nothing`;
|
|
36721
36961
|
case "module":
|
|
36722
|
-
return "a
|
|
36962
|
+
return "a library";
|
|
36723
36963
|
default:
|
|
36724
36964
|
return "a value";
|
|
36725
36965
|
}
|
|
@@ -36765,8 +37005,9 @@ var Checker = class {
|
|
|
36765
37005
|
this.rules = [];
|
|
36766
37006
|
this.mainNames = /* @__PURE__ */ new Map();
|
|
36767
37007
|
this.elem = [];
|
|
36768
|
-
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 };
|
|
36769
37009
|
this.screens = /* @__PURE__ */ new Map();
|
|
37010
|
+
this.narrow = [];
|
|
36770
37011
|
}
|
|
36771
37012
|
err(code3, line, msg, hint) {
|
|
36772
37013
|
this.d.push(diag(code3, line, msg, hint));
|
|
@@ -36789,14 +37030,14 @@ var Checker = class {
|
|
|
36789
37030
|
this.info.imported.add(k);
|
|
36790
37031
|
}
|
|
36791
37032
|
for (const m of inf.modules) {
|
|
36792
|
-
this.global.vars.set(m.name, { kind: "module", line: m.line, name: m.name, text: m.text, py: m.py, type: T("module") });
|
|
37033
|
+
this.global.vars.set(m.name, { kind: "module", line: m.line, name: m.name, text: m.text, py: m.py, ecosystem: m.ecosystem, type: T("module") });
|
|
36793
37034
|
this.info.imported.add(m);
|
|
36794
37035
|
}
|
|
36795
37036
|
}
|
|
36796
37037
|
for (const s of top) {
|
|
36797
37038
|
if (s.k === "record") this.declare(s, "record", s.line, { py: pyName(s.name, "pascal"), stmt: s });
|
|
36798
37039
|
else if (s.k === "func") this.declare(s, "func", s.line, { py: pyName(s.name), stmt: s, ret: UNKNOWN });
|
|
36799
|
-
else if (s.k === "use") this.declare(s, "module", s.line, { py: pyName(s.name), module: s.module, type: T("module") });
|
|
37040
|
+
else if (s.k === "use") this.declare(s, "module", s.line, { py: pyName(s.name), module: s.module, ecosystem: s.ecosystem, type: T("module") });
|
|
36800
37041
|
else if (s.k === "screen") {
|
|
36801
37042
|
const prev = this.screens.get(s.name);
|
|
36802
37043
|
if (prev) this.err("TC203", s.line, `There is already a screen called "${s.text}" (line ${prev.line}).`, "Give one of them a different name.");
|
|
@@ -36808,6 +37049,7 @@ var Checker = class {
|
|
|
36808
37049
|
}
|
|
36809
37050
|
}
|
|
36810
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 ?? [])];
|
|
36811
37053
|
collectMainNames(top, this.mainNames);
|
|
36812
37054
|
for (const s of top) {
|
|
36813
37055
|
if (s.k !== "keep") continue;
|
|
@@ -36815,6 +37057,24 @@ var Checker = class {
|
|
|
36815
37057
|
this.declare(s, "const", s.line, { py: pyName(s.name, "upper"), type: t });
|
|
36816
37058
|
this.info.consts.push(s);
|
|
36817
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
|
+
}
|
|
36818
37078
|
for (const s of top) if (s.k === "never") this.addRule(s, null);
|
|
36819
37079
|
for (const r of this.records.values()) for (const rule of r.rules) this.addRule(rule, r);
|
|
36820
37080
|
for (const s of top) if (s.k === "func") this.checkFunc(s);
|
|
@@ -36832,7 +37092,7 @@ var Checker = class {
|
|
|
36832
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).`);
|
|
36833
37093
|
const main = new Scope2(this.global, "main");
|
|
36834
37094
|
this.mainScope = main;
|
|
36835
|
-
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));
|
|
36836
37096
|
this.block(mainBody, main, {});
|
|
36837
37097
|
this.p.main = mainBody;
|
|
36838
37098
|
this.info.records = [...this.records.values()];
|
|
@@ -36873,6 +37133,98 @@ var Checker = class {
|
|
|
36873
37133
|
this.resolveType(f.type, f.line);
|
|
36874
37134
|
r.fieldMap.set(f.name, f);
|
|
36875
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" } };
|
|
36876
37228
|
}
|
|
36877
37229
|
resolveType(t, line) {
|
|
36878
37230
|
if (!t) return;
|
|
@@ -36939,7 +37291,90 @@ var Checker = class {
|
|
|
36939
37291
|
rulesFor(key) {
|
|
36940
37292
|
return this.rules.filter((r) => r.watchesVar && r.subject === key);
|
|
36941
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
|
+
}
|
|
36942
37376
|
checkFunc(f) {
|
|
37377
|
+
if (f.endpoint) this.checkEndpoint(f);
|
|
36943
37378
|
const sc = new Scope2(this.global, "func");
|
|
36944
37379
|
sc.func = f;
|
|
36945
37380
|
f.gives = [];
|
|
@@ -37002,15 +37437,25 @@ var Checker = class {
|
|
|
37002
37437
|
}
|
|
37003
37438
|
const t = this.ex(s.e, sc);
|
|
37004
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");
|
|
37005
37441
|
return;
|
|
37006
37442
|
}
|
|
37007
37443
|
case "stop":
|
|
37008
37444
|
this.ex(s.e, sc);
|
|
37445
|
+
if (s.status != null) this.checkStatus(s.status, line, [400, 599], "Stop \u2026 and status");
|
|
37009
37446
|
return;
|
|
37447
|
+
case "depending":
|
|
37448
|
+
return this.depending(s, sc, ctx);
|
|
37010
37449
|
case "if":
|
|
37011
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;
|
|
37012
37452
|
this.cond(b.cond, sc);
|
|
37013
|
-
|
|
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
|
+
}
|
|
37014
37459
|
}
|
|
37015
37460
|
if (s.otherwise) this.block(s.otherwise, sc, ctx);
|
|
37016
37461
|
return;
|
|
@@ -37277,6 +37722,10 @@ var Checker = class {
|
|
|
37277
37722
|
const tgt = s.target;
|
|
37278
37723
|
if (tgt.k === "name") {
|
|
37279
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
|
+
}
|
|
37280
37729
|
if (g && g.kind === "const") {
|
|
37281
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.");
|
|
37282
37731
|
return;
|
|
@@ -37307,6 +37756,7 @@ var Checker = class {
|
|
|
37307
37756
|
}
|
|
37308
37757
|
} else {
|
|
37309
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.");
|
|
37310
37760
|
this.lvalue(tgt, sc, line);
|
|
37311
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)}.`);
|
|
37312
37762
|
}
|
|
@@ -37405,6 +37855,46 @@ var Checker = class {
|
|
|
37405
37855
|
return T("nothing");
|
|
37406
37856
|
case "hole":
|
|
37407
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
|
+
}
|
|
37408
37898
|
case "today":
|
|
37409
37899
|
case "date":
|
|
37410
37900
|
return T("date");
|
|
@@ -37432,6 +37922,19 @@ var Checker = class {
|
|
|
37432
37922
|
case "field": {
|
|
37433
37923
|
const ot = this.ex(e.obj, sc, o);
|
|
37434
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
|
+
}
|
|
37435
37938
|
if (r) {
|
|
37436
37939
|
const f = r.fieldMap.get(e.name);
|
|
37437
37940
|
if (!f) {
|
|
@@ -37516,7 +38019,7 @@ var Checker = class {
|
|
|
37516
38019
|
}
|
|
37517
38020
|
case "dot": {
|
|
37518
38021
|
const ot = this.ex(e.obj, sc, o);
|
|
37519
|
-
if (ot.k !== "module") this.err("TC402", line, `"${e.attr}" with a dot reaches into a
|
|
38022
|
+
if (ot.k !== "module") this.err("TC402", line, `"${e.attr}" with a dot reaches into a library brought in with "Use". ${e.obj.k === "name" ? `"${e.obj.text}"` : "This"} is not one.`, 'Write "Use <module> as <name>" (Python) or Use "<package>" from npm as <name> at the top of the file first.');
|
|
37520
38023
|
for (const a of e.args ?? []) this.ex(a, sc, o);
|
|
37521
38024
|
return UNKNOWN;
|
|
37522
38025
|
}
|
|
@@ -37585,7 +38088,13 @@ var Checker = class {
|
|
|
37585
38088
|
return this.arith(e.op, l, r, line);
|
|
37586
38089
|
}
|
|
37587
38090
|
case "cmp": {
|
|
37588
|
-
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);
|
|
37589
38098
|
this.comparable(l, r, line, e.op);
|
|
37590
38099
|
return T("bool");
|
|
37591
38100
|
}
|
|
@@ -37622,6 +38131,11 @@ var Checker = class {
|
|
|
37622
38131
|
if (el) {
|
|
37623
38132
|
const r = el.type.k === "record" ? this.records.get(el.type.name) : null;
|
|
37624
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
|
+
}
|
|
37625
38139
|
const f = r.fieldMap.get(e.name);
|
|
37626
38140
|
e.ref = { kind: "elemField", py: f.py };
|
|
37627
38141
|
return f.type;
|
|
@@ -37672,6 +38186,9 @@ var Checker = class {
|
|
|
37672
38186
|
return UNKNOWN;
|
|
37673
38187
|
}
|
|
37674
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
|
+
});
|
|
37675
38192
|
const ts = e.args.map((a) => this.ex(a, sc, o));
|
|
37676
38193
|
const required = f.params.filter((p) => !p.dflt).length;
|
|
37677
38194
|
if (ts.length < required || ts.length > f.params.length) {
|
|
@@ -37687,6 +38204,81 @@ var Checker = class {
|
|
|
37687
38204
|
});
|
|
37688
38205
|
return entry3?.ret ?? UNKNOWN;
|
|
37689
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
|
+
}
|
|
37690
38282
|
newRecord(e, sc, o) {
|
|
37691
38283
|
const r = this.records.get(e.record);
|
|
37692
38284
|
if (!r) {
|
|
@@ -37694,9 +38286,11 @@ var Checker = class {
|
|
|
37694
38286
|
return UNKNOWN;
|
|
37695
38287
|
}
|
|
37696
38288
|
e.py = r.py;
|
|
38289
|
+
if (r.altMap) return this.newAlternative(e, r, sc, o);
|
|
37697
38290
|
const given = /* @__PURE__ */ new Set();
|
|
37698
38291
|
for (const f of e.fields) {
|
|
37699
38292
|
const def = r.fieldMap.get(f.name);
|
|
38293
|
+
if (f.e.k === "draftHole" && !f.e.want && def?.type) f.e.expected = def.type;
|
|
37700
38294
|
const t = this.ex(f.e, sc, o);
|
|
37701
38295
|
if (!def) {
|
|
37702
38296
|
const g = closest(f.name, [...r.fieldMap.keys()]);
|
|
@@ -37987,6 +38581,12 @@ var Gen = class {
|
|
|
37987
38581
|
this.blank();
|
|
37988
38582
|
for (const k of consts) this.emit(`${k.py} = ${this.x(k.e).c}`, k.line);
|
|
37989
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
|
+
}
|
|
37990
38590
|
const tests = this.info.tests;
|
|
37991
38591
|
for (const t of tests) {
|
|
37992
38592
|
this.blank();
|
|
@@ -38001,16 +38601,29 @@ var Gen = class {
|
|
|
38001
38601
|
for (const t of tests) this.emit(` (${py(t.title)}, ${t.py}, ${t.line}),`);
|
|
38002
38602
|
this.emit("]");
|
|
38003
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
|
+
}
|
|
38004
38616
|
const main = this.p.main ?? [];
|
|
38005
38617
|
this.blank();
|
|
38006
|
-
if (main.length) {
|
|
38618
|
+
if (main.length || endpoints.length) {
|
|
38007
38619
|
this.emit("def main():");
|
|
38008
38620
|
this.ind++;
|
|
38009
|
-
this.block(main);
|
|
38621
|
+
if (main.length) this.block(main);
|
|
38622
|
+
else this.emit("pass");
|
|
38010
38623
|
this.ind--;
|
|
38011
38624
|
this.blank();
|
|
38012
38625
|
this.emit('if __name__ == "__main__":');
|
|
38013
|
-
this.emit(` ${this.R("run")}(main, __file__)`);
|
|
38626
|
+
this.emit(` ${this.R("run")}(main, __file__${endpoints.length ? ", routes=THUNDER_ROUTES" : ""})`);
|
|
38014
38627
|
}
|
|
38015
38628
|
body2.push(...this.out);
|
|
38016
38629
|
const head = [
|
|
@@ -38022,7 +38635,7 @@ var Gen = class {
|
|
|
38022
38635
|
if (this.needDataclass) head.push("from dataclasses import dataclass, field");
|
|
38023
38636
|
if (this.needDate) head.push("from datetime import date");
|
|
38024
38637
|
if (this.needDecimal) head.push("from decimal import Decimal");
|
|
38025
|
-
for (const m of this.info.modules.filter(own)) head.push(m.module === m.py || m.module.split(".")[0] === m.py && !m.module.includes(".") ? `import ${m.module}` : `import ${m.module} as ${m.py}`);
|
|
38638
|
+
for (const m of this.info.modules.filter((x) => own(x) && (x.ecosystem ?? "python") === "python")) head.push(m.module === m.py || m.module.split(".")[0] === m.py && !m.module.includes(".") ? `import ${m.module}` : `import ${m.module} as ${m.py}`);
|
|
38026
38639
|
head.push(`from thunder_runtime import ${[...this.rt].sort().join(", ")}`);
|
|
38027
38640
|
for (const m of srcModules) head.push(`from ${m} import *`);
|
|
38028
38641
|
head.push("", `THUNDER_SOURCE = ${py(this.source)}`, "", "");
|
|
@@ -38044,6 +38657,7 @@ ${body2.join("\n").replace(/\n{4,}/g, "\n\n\n")}
|
|
|
38044
38657
|
this.emit(`${f.py}: ${t}${dflt}`, f.line);
|
|
38045
38658
|
}
|
|
38046
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);
|
|
38047
38661
|
const rules = r.rulesToCheck ?? [];
|
|
38048
38662
|
if (rules.length) {
|
|
38049
38663
|
this.out.push("");
|
|
@@ -38142,11 +38756,14 @@ ${body2.join("\n").replace(/\n{4,}/g, "\n\n\n")}
|
|
|
38142
38756
|
return;
|
|
38143
38757
|
}
|
|
38144
38758
|
case "give":
|
|
38759
|
+
if (s.status != null) this.emit(`${this.R("answer_status")}(${s.status})`, L);
|
|
38145
38760
|
this.emit(s.e.k === "nothing" ? "return None" : `return ${this.x(s.e).c}`, L);
|
|
38146
38761
|
return;
|
|
38147
|
-
case "stop":
|
|
38148
|
-
|
|
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);
|
|
38149
38765
|
return;
|
|
38766
|
+
}
|
|
38150
38767
|
case "if":
|
|
38151
38768
|
s.branches.forEach((b, k) => {
|
|
38152
38769
|
this.emit(`${k === 0 ? "if" : "elif"} ${this.yn(b.cond).c}:`, b.line);
|
|
@@ -38374,6 +38991,12 @@ ${body2.join("\n").replace(/\n{4,}/g, "\n\n\n")}
|
|
|
38374
38991
|
return A("None");
|
|
38375
38992
|
case "paren":
|
|
38376
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
|
+
}
|
|
38377
39000
|
case "today":
|
|
38378
39001
|
this.needDate = true;
|
|
38379
39002
|
return A("date.today()");
|
|
@@ -39328,7 +39951,8 @@ def _callers(tb):
|
|
|
39328
39951
|
|
|
39329
39952
|
|
|
39330
39953
|
def describe_error(error):
|
|
39331
|
-
|
|
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__)
|
|
39332
39956
|
message = explain(error)
|
|
39333
39957
|
code = _code(error)
|
|
39334
39958
|
# Any error Thunder has no words for came from Python code reached through "Use" (TC508), even when that
|
|
@@ -39343,15 +39967,376 @@ def describe_error(error):
|
|
|
39343
39967
|
return "%s: %s [%s]" % (where, message, code)
|
|
39344
39968
|
|
|
39345
39969
|
|
|
39346
|
-
|
|
39347
|
-
|
|
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()
|
|
39348
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
|
|
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()
|
|
39349
40331
|
main()
|
|
40332
|
+
_save_stores()
|
|
39350
40333
|
except KeyboardInterrupt:
|
|
39351
40334
|
raise
|
|
39352
40335
|
except Exception as error: # noqa: BLE001 - every error is reported in Thunder words
|
|
39353
40336
|
print(describe_error(error), file=sys.stderr)
|
|
39354
40337
|
sys.exit(1)
|
|
40338
|
+
if routes:
|
|
40339
|
+
_serve(routes)
|
|
39355
40340
|
|
|
39356
40341
|
|
|
39357
40342
|
def run_tests(modules):
|
|
@@ -39381,13 +40366,17 @@ function compileCore(source, { file = "main.thunder", imported = [], srcModules
|
|
|
39381
40366
|
fields: imported.flatMap((r) => [...r.program.names.fields]),
|
|
39382
40367
|
records: imported.flatMap((r) => [...r.program.names.records]),
|
|
39383
40368
|
recordFields: imported.flatMap((r) => [...r.program.names.recordFields ?? []]),
|
|
39384
|
-
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 ?? []])
|
|
39385
40372
|
} : null;
|
|
39386
40373
|
const program = parseCore(source, { seed });
|
|
39387
40374
|
const { diagnostics, info } = checkCore(program, { imported: imported.map((r) => r.info) });
|
|
39388
40375
|
const ok = diagnostics.length === 0;
|
|
39389
40376
|
const python = ok ? toPython(program, info, { source: file, imports: srcModules }) : null;
|
|
39390
|
-
|
|
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 };
|
|
39391
40380
|
}
|
|
39392
40381
|
|
|
39393
40382
|
// src/core/engine-values.mjs
|
|
@@ -39406,6 +40395,7 @@ var KindMismatch = (m) => new ThunderErr("TC506", m, "TypeError");
|
|
|
39406
40395
|
var ConversionFailed = (m) => new ThunderErr("TC509", m, "ValueError");
|
|
39407
40396
|
var MissingValue = (m) => new ThunderErr("TC503", m, "LookupError");
|
|
39408
40397
|
var DividedByZero = (m) => new ThunderErr("TC501", m, "ZeroDivisionError");
|
|
40398
|
+
var CallFailed = (m) => new ThunderErr("TC510", m, "CallFailed");
|
|
39409
40399
|
var PyErr = class extends Error {
|
|
39410
40400
|
constructor(pyType2, message2, args) {
|
|
39411
40401
|
super(message2);
|
|
@@ -40572,6 +41562,120 @@ function stripPunct(w) {
|
|
|
40572
41562
|
return a.slice(i, j).join("");
|
|
40573
41563
|
}
|
|
40574
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
|
+
|
|
40575
41679
|
// src/core/engine-core.mjs
|
|
40576
41680
|
var Return = class {
|
|
40577
41681
|
constructor(v) {
|
|
@@ -40587,17 +41691,21 @@ var nativeOverflow = (e) => {
|
|
|
40587
41691
|
};
|
|
40588
41692
|
var NeedsDeeperStack = class extends Error {
|
|
40589
41693
|
};
|
|
41694
|
+
var OutOfSteps = class extends Error {
|
|
41695
|
+
};
|
|
40590
41696
|
var MAX_FRAMES2 = MAX_FRAMES;
|
|
40591
41697
|
var CONTAINER_KINDS = /* @__PURE__ */ new Set(["if", "each", "range", "times", "while", "tryFail"]);
|
|
40592
41698
|
var MAX_RECORDED = 2e4;
|
|
40593
41699
|
function pythonModulesUsed(results) {
|
|
40594
41700
|
const out = [];
|
|
40595
|
-
for (const r of results) for (const m of r.info.modules) if (!r.info.imported?.has(m)) out.push({ file: r.file, module: m.module, name: m.text ?? m.name, line: m.line });
|
|
41701
|
+
for (const r of results) for (const m of r.info.modules) if (!r.info.imported?.has(m)) out.push({ file: r.file, module: m.module, name: m.text ?? m.name, line: m.line, ecosystem: m.ecosystem ?? "python" });
|
|
40596
41702
|
return out;
|
|
40597
41703
|
}
|
|
40598
41704
|
function refusalText(uses) {
|
|
40599
41705
|
const u = uses[0];
|
|
40600
41706
|
const more = uses.length > 1 ? ` (and ${uses.length - 1} more)` : "";
|
|
41707
|
+
if (u.ecosystem === "dotnet" || u.ecosystem === "nuget") return `This program uses the .NET type "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it as C#: --target csharp.`;
|
|
41708
|
+
if (u.ecosystem === "npm") return `This program uses the npm package "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it as TypeScript: --target typescript.`;
|
|
40601
41709
|
return `This program uses the Python module "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it with Python: leave out --engine thunder.`;
|
|
40602
41710
|
}
|
|
40603
41711
|
var Module = class {
|
|
@@ -40611,13 +41719,19 @@ var Engine = class {
|
|
|
40611
41719
|
// readText(path, cwd): the text of a file the program reads, or throws with .code 'ENOENT' / 'EISDIR'. Without it
|
|
40612
41720
|
// (a browser), reading a file is reported as a missing file.
|
|
40613
41721
|
// record: keep a step-by-step recording of the run (the Thunder Time Machine; see recordedRun below).
|
|
40614
|
-
|
|
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;
|
|
40615
41728
|
this.cwd = cwd;
|
|
40616
41729
|
this.rec = record ? { steps: [], truncated: false } : null;
|
|
40617
41730
|
this.readText = readText;
|
|
40618
41731
|
this.deeper = deeper;
|
|
40619
41732
|
this.frames = [];
|
|
40620
41733
|
this.out = [];
|
|
41734
|
+
this.budget = null;
|
|
40621
41735
|
}
|
|
40622
41736
|
// ── loading ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
40623
41737
|
load(result, imports = []) {
|
|
@@ -40626,6 +41740,12 @@ var Engine = class {
|
|
|
40626
41740
|
for (const m of imports) for (const [k, v] of m.globals) mod.globals.set(k, v);
|
|
40627
41741
|
for (const r of result.info.records.filter(own)) mod.globals.set(r.py, this.recordClass(r, mod));
|
|
40628
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);
|
|
40629
41749
|
const consts = result.info.consts.filter(own);
|
|
40630
41750
|
if (consts.length) {
|
|
40631
41751
|
const frame = { file: mod.file, line: 0 };
|
|
@@ -40645,7 +41765,8 @@ var Engine = class {
|
|
|
40645
41765
|
const f = r.fieldMap.get(rule.subject);
|
|
40646
41766
|
(rules.get(f.py) ?? rules.set(f.py, []).get(f.py)).push(rule);
|
|
40647
41767
|
}
|
|
40648
|
-
|
|
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 };
|
|
40649
41770
|
}
|
|
40650
41771
|
// ── frames, lines, errors ───────────────────────────────────────────────────────────────────────────────────
|
|
40651
41772
|
withFrame(frame, fn) {
|
|
@@ -40654,7 +41775,7 @@ var Engine = class {
|
|
|
40654
41775
|
try {
|
|
40655
41776
|
return fn();
|
|
40656
41777
|
} catch (e) {
|
|
40657
|
-
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
41778
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
|
|
40658
41779
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
40659
41780
|
const err = asPyErr(e);
|
|
40660
41781
|
if (!err.where) err.where = this.frames.map((f) => ({ file: f.file, line: f.line }));
|
|
@@ -40681,7 +41802,7 @@ var Engine = class {
|
|
|
40681
41802
|
const locals = /* @__PURE__ */ new Map();
|
|
40682
41803
|
const env = { mod, locals, frame };
|
|
40683
41804
|
f.params.forEach((p, i) => {
|
|
40684
|
-
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;
|
|
40685
41806
|
if (v === void 0) throw TypeErr(`${f.py}() missing 1 required positional argument: '${p.py}'`);
|
|
40686
41807
|
locals.set(p.py, v);
|
|
40687
41808
|
});
|
|
@@ -40702,6 +41823,36 @@ var Engine = class {
|
|
|
40702
41823
|
return null;
|
|
40703
41824
|
});
|
|
40704
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
|
+
}
|
|
40705
41856
|
never(rule, value, env) {
|
|
40706
41857
|
never(this.x(rule.rule.cond, env, { subject: value }), rule.text, rule.line, value);
|
|
40707
41858
|
}
|
|
@@ -40755,6 +41906,7 @@ var Engine = class {
|
|
|
40755
41906
|
}
|
|
40756
41907
|
}
|
|
40757
41908
|
stmt(s, env) {
|
|
41909
|
+
if (this.budget !== null && --this.budget < 0) throw new OutOfSteps();
|
|
40758
41910
|
if (this.rec) return this.recordStep(s, env);
|
|
40759
41911
|
return this.runStmt(s, env);
|
|
40760
41912
|
}
|
|
@@ -40843,11 +41995,16 @@ var Engine = class {
|
|
|
40843
41995
|
this.storeAt(t, v, env);
|
|
40844
41996
|
return;
|
|
40845
41997
|
}
|
|
40846
|
-
case "give":
|
|
40847
|
-
|
|
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
|
+
}
|
|
40848
42003
|
case "stop": {
|
|
40849
42004
|
const v = this.x(s.e, env);
|
|
40850
|
-
|
|
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;
|
|
40851
42008
|
}
|
|
40852
42009
|
case "if":
|
|
40853
42010
|
for (const b of s.branches) {
|
|
@@ -40950,7 +42107,7 @@ var Engine = class {
|
|
|
40950
42107
|
try {
|
|
40951
42108
|
this.stmt(s.stmt, env);
|
|
40952
42109
|
} catch (e) {
|
|
40953
|
-
if (e instanceof Return || e instanceof NeedsDeeperStack) throw e;
|
|
42110
|
+
if (e instanceof Return || e instanceof NeedsDeeperStack || e instanceof OutOfSteps) throw e;
|
|
40954
42111
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
40955
42112
|
const err = asPyErr(e);
|
|
40956
42113
|
fr.line = L;
|
|
@@ -40999,6 +42156,7 @@ var Engine = class {
|
|
|
40999
42156
|
}
|
|
41000
42157
|
if (s.mode === "fail") {
|
|
41001
42158
|
const msg = s.msg ? this.x(s.msg, env) : null;
|
|
42159
|
+
let outOfSteps = null;
|
|
41002
42160
|
expectFailure(() => {
|
|
41003
42161
|
try {
|
|
41004
42162
|
this.x(s.e, env);
|
|
@@ -41006,9 +42164,11 @@ var Engine = class {
|
|
|
41006
42164
|
if (e instanceof Return) return;
|
|
41007
42165
|
if (e instanceof NeedsDeeperStack) throw e;
|
|
41008
42166
|
if (this.deeper && nativeOverflow(e)) throw new NeedsDeeperStack();
|
|
42167
|
+
if (e instanceof OutOfSteps) outOfSteps = e;
|
|
41009
42168
|
throw e;
|
|
41010
42169
|
}
|
|
41011
42170
|
}, text2, msg);
|
|
42171
|
+
if (outOfSteps) throw outOfSteps;
|
|
41012
42172
|
return;
|
|
41013
42173
|
}
|
|
41014
42174
|
const actual = this.x(s.e, env);
|
|
@@ -41106,6 +42266,8 @@ var Engine = class {
|
|
|
41106
42266
|
return null;
|
|
41107
42267
|
case "paren":
|
|
41108
42268
|
return sub2(e.e);
|
|
42269
|
+
case "httpCall":
|
|
42270
|
+
return this.httpCall(e, env);
|
|
41109
42271
|
case "today":
|
|
41110
42272
|
return PyDate.today();
|
|
41111
42273
|
case "date": {
|
|
@@ -41269,17 +42431,37 @@ var Engine = class {
|
|
|
41269
42431
|
// ── running a program or its tests ──────────────────────────────────────────────────────────────────────────
|
|
41270
42432
|
runMain(mod) {
|
|
41271
42433
|
const main = mod.r.program.main ?? [];
|
|
41272
|
-
|
|
41273
|
-
|
|
41274
|
-
|
|
41275
|
-
|
|
41276
|
-
|
|
41277
|
-
|
|
41278
|
-
|
|
41279
|
-
|
|
41280
|
-
|
|
41281
|
-
|
|
41282
|
-
|
|
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));
|
|
41283
42465
|
}
|
|
41284
42466
|
runTest(mod, t) {
|
|
41285
42467
|
const frame = { file: mod.file, line: t.line };
|
|
@@ -41294,11 +42476,21 @@ var Engine = class {
|
|
|
41294
42476
|
});
|
|
41295
42477
|
}
|
|
41296
42478
|
};
|
|
41297
|
-
function
|
|
42479
|
+
function notCompiled(results) {
|
|
42480
|
+
const bad = results.filter((r) => r && r.ok === false);
|
|
42481
|
+
if (!bad.length) return null;
|
|
42482
|
+
const lines = bad.flatMap((r) => (r.diagnostics ?? []).filter((d) => d.severity !== "warning").map((d) => `${r.file ?? "main.thunder"}, line ${d.line ?? "?"}: ${d.message} [${d.code}]`));
|
|
42483
|
+
return { status: 2, stdout: "", stderr: `${lines.join("\n") || "The program has problems"}
|
|
42484
|
+
Nothing was run: fix the problems first.
|
|
42485
|
+
`, notCompiled: true, steps: [] };
|
|
42486
|
+
}
|
|
42487
|
+
function runInProcess({ entry: entry3, cwd, deeper = false, readText = null, store = null, http = null } = {}) {
|
|
42488
|
+
const broken = notCompiled([entry3]);
|
|
42489
|
+
if (broken) return broken;
|
|
41298
42490
|
const uses = pythonModulesUsed([entry3]);
|
|
41299
42491
|
if (uses.length) return { status: 2, stdout: "", stderr: `${refusalText(uses)}
|
|
41300
42492
|
`, refused: uses };
|
|
41301
|
-
const eng = new Engine({ cwd, deeper, readText });
|
|
42493
|
+
const eng = new Engine({ cwd, deeper, readText, store, http });
|
|
41302
42494
|
let stderr = "", status = 0;
|
|
41303
42495
|
try {
|
|
41304
42496
|
const mod = eng.load(entry3);
|
|
@@ -41314,11 +42506,13 @@ function runInProcess({ entry: entry3, cwd, deeper = false, readText = null } =
|
|
|
41314
42506
|
}
|
|
41315
42507
|
return { status, stdout: eng.out.join(""), stderr };
|
|
41316
42508
|
}
|
|
41317
|
-
function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
|
|
42509
|
+
function testInProcess({ results, cwd, deeper = false, readText = null, http = null } = {}) {
|
|
42510
|
+
const broken = notCompiled(results);
|
|
42511
|
+
if (broken) return broken;
|
|
41318
42512
|
const uses = pythonModulesUsed(results);
|
|
41319
42513
|
if (uses.length) return { status: 2, stdout: "", stderr: `${refusalText(uses)}
|
|
41320
42514
|
`, refused: uses };
|
|
41321
|
-
const eng = new Engine({ cwd, deeper, readText });
|
|
42515
|
+
const eng = new Engine({ cwd, deeper, readText, http });
|
|
41322
42516
|
const mods = [];
|
|
41323
42517
|
const srcMods = [];
|
|
41324
42518
|
for (const r of results) {
|
|
@@ -42977,7 +44171,7 @@ function settingsIn(files) {
|
|
|
42977
44171
|
}
|
|
42978
44172
|
}
|
|
42979
44173
|
}
|
|
42980
|
-
return out.sort((a, b) => a.file
|
|
44174
|
+
return out.sort((a, b) => byText(a.file, b.file) || a.line - b.line || byText(a.key, b.key));
|
|
42981
44175
|
}
|
|
42982
44176
|
var NAME = '((?:[`"\\[]?[A-Za-z_][\\w$]*[`"\\]]?\\.){0,2}[`"\\[]?[A-Za-z_][\\w$]*[`"\\]]?)';
|
|
42983
44177
|
var NOT_TABLES = /* @__PURE__ */ new Set(["select", "set", "where", "values", "dual", "lateral", "unnest", "only", "table", "if", "exists", "not", "the", "a", "an", "my", "your", "this", "that", "each", "all", "json_table", "information_schema", "pg_catalog", "sys"]);
|
|
@@ -43047,7 +44241,7 @@ function tablesIn(files) {
|
|
|
43047
44241
|
if (seen.has(k)) return false;
|
|
43048
44242
|
seen.add(k);
|
|
43049
44243
|
return true;
|
|
43050
|
-
}).sort((a, b) => a.file
|
|
44244
|
+
}).sort((a, b) => byText(a.file, b.file) || a.line - b.line || byText(a.table, b.table));
|
|
43051
44245
|
}
|
|
43052
44246
|
var DEFINES = /* @__PURE__ */ new Set(["creates", "alters", "drops"]);
|
|
43053
44247
|
|
|
@@ -43065,22 +44259,26 @@ var end = (repo, at2, extra = {}) => ({ repo: repo.name, member: at2.member, lab
|
|
|
43065
44259
|
var distinctive = (segs) => segs.some((s) => s !== "*");
|
|
43066
44260
|
var lower2 = (segs) => segs.map((s) => s.toLowerCase());
|
|
43067
44261
|
var pathMatch = (a, b) => segsMatch(lower2(a), lower2(b));
|
|
43068
|
-
function buildTrace(repos) {
|
|
44262
|
+
function buildTrace(repos, { core = null } = {}) {
|
|
43069
44263
|
const names = /* @__PURE__ */ new Set();
|
|
43070
44264
|
const read = repos.map((r) => {
|
|
43071
44265
|
if (!r.name || names.has(r.name)) throw new Error(`Each repository needs its own name; "${r.name}" is used twice.`);
|
|
43072
44266
|
names.add(r.name);
|
|
43073
|
-
const
|
|
43074
|
-
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;
|
|
43075
44273
|
const real = (x) => !isTestFile(x.file);
|
|
43076
|
-
const data = dataFacts(
|
|
44274
|
+
const data = dataFacts(other, model);
|
|
43077
44275
|
const testItems = ["routes", "listeners", "requests", "publishes"].reduce((n, k) => n + facts[k].filter((x) => !real(x)).length, 0) + data.testItems;
|
|
43078
44276
|
return {
|
|
43079
44277
|
name: r.name,
|
|
43080
44278
|
sha: r.sha ?? null,
|
|
43081
44279
|
dirty: !!r.dirty,
|
|
43082
|
-
files: model.files.length,
|
|
43083
|
-
languages: [
|
|
44280
|
+
files: model.files.length + coreFiles,
|
|
44281
|
+
languages: [.../* @__PURE__ */ new Set([...model.files.map((f) => f.language), ...coreFiles ? ["thunder"] : []])].sort(),
|
|
43084
44282
|
routes: facts.routes.filter(real),
|
|
43085
44283
|
listeners: facts.listeners.filter(real),
|
|
43086
44284
|
requests: facts.requests.filter(real),
|
|
@@ -43192,8 +44390,8 @@ function linkRepos(read) {
|
|
|
43192
44390
|
return true;
|
|
43193
44391
|
});
|
|
43194
44392
|
};
|
|
43195
|
-
links.splice(0, links.length, ...once(links).sort((a, b) => sortKey(a)
|
|
43196
|
-
notLinked.splice(0, notLinked.length, ...once(notLinked).sort((a, b) => sortKey(a)
|
|
44393
|
+
links.splice(0, links.length, ...once(links).sort((a, b) => byText(sortKey(a), sortKey(b))));
|
|
44394
|
+
notLinked.splice(0, notLinked.length, ...once(notLinked).sort((a, b) => byText(sortKey(a), sortKey(b))));
|
|
43197
44395
|
const repos = read.map(({ unknown, ...r }) => ({ ...r, unknown: unknown ?? [], packages: pk(r), settings: r.settings ?? [], tables: tb(r) }));
|
|
43198
44396
|
const body2 = { schema: TRACE_SCHEMA, rulesVersion: TRACE_RULES_VERSION, repos, links, notLinked, shared };
|
|
43199
44397
|
return { ...body2, fingerprint: sha256(JSON.stringify(body2)) };
|
|
@@ -43341,16 +44539,112 @@ function writeRuleAcross(files, { decision, rule, when }) {
|
|
|
43341
44539
|
}
|
|
43342
44540
|
result.files[k] = source;
|
|
43343
44541
|
}
|
|
43344
|
-
result.plan.sort((a, b) => where(a)
|
|
44542
|
+
result.plan.sort((a, b) => byText(where(a), where(b)) || a.line - b.line);
|
|
43345
44543
|
if (problems.length) return { ...base2, files: {}, plan: [], rule: result.rule, notIncluded: result.notIncluded, tests: result.tests, problems: ["Nothing was changed: every implementation must be written exactly, or none is.", ...problems] };
|
|
43346
44544
|
return { ...result, ok: true };
|
|
43347
44545
|
}
|
|
43348
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
|
+
|
|
43349
44641
|
// src/review.mjs
|
|
43350
44642
|
var REVIEW_SCHEMA = "thunder-review-v1";
|
|
43351
44643
|
var SEVERITY_ORDER = ["risk", "meaning", "form"];
|
|
43352
44644
|
var KIND_ORDER = [
|
|
43353
44645
|
"unreadable",
|
|
44646
|
+
"test-fails",
|
|
44647
|
+
"callers",
|
|
43354
44648
|
"not-read",
|
|
43355
44649
|
"infrastructure",
|
|
43356
44650
|
"stop-removed",
|
|
@@ -43961,7 +45255,7 @@ function mostlyIn(a, b) {
|
|
|
43961
45255
|
}
|
|
43962
45256
|
return hit / want.length >= 0.75;
|
|
43963
45257
|
}
|
|
43964
|
-
function thunderReview(oldFiles, newFiles) {
|
|
45258
|
+
function thunderReview(oldFiles, newFiles, { core = null, context = null } = {}) {
|
|
43965
45259
|
detailsCache = /* @__PURE__ */ new WeakMap();
|
|
43966
45260
|
const A = side(oldFiles || []), B = side(newFiles || []);
|
|
43967
45261
|
const items = [];
|
|
@@ -44040,11 +45334,14 @@ function thunderReview(oldFiles, newFiles) {
|
|
|
44040
45334
|
{ before: null, after: n.text }
|
|
44041
45335
|
));
|
|
44042
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;
|
|
44043
45339
|
const paths = [.../* @__PURE__ */ new Set([...A.sources.keys(), ...B.sources.keys()])];
|
|
44044
45340
|
const notRead = [];
|
|
44045
45341
|
for (const p of paths) {
|
|
44046
45342
|
const before = A.sources.get(p), after = B.sources.get(p);
|
|
44047
45343
|
if (before === after) continue;
|
|
45344
|
+
if (corePaths.has(p)) continue;
|
|
44048
45345
|
const lang = !isInfra(p) && readableLanguage(p);
|
|
44049
45346
|
if (!lang) {
|
|
44050
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));
|
|
@@ -44106,11 +45403,43 @@ function thunderReview(oldFiles, newFiles) {
|
|
|
44106
45403
|
for (const x of rest2) items.splice(items.indexOf(x), 1);
|
|
44107
45404
|
}
|
|
44108
45405
|
for (const x of items) if (x.also) x.subject = `${x.subject} and ${x.also.length} more`;
|
|
44109
|
-
items.sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity) || KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind) || String(a.where.file)
|
|
45406
|
+
items.sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity) || KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind) || byText(String(a.where.file), String(b.where.file)) || (a.where.line ?? 0) - (b.where.line ?? 0));
|
|
44110
45407
|
const count = (s) => items.filter((x) => x.severity === s).length;
|
|
44111
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 };
|
|
44112
45409
|
const onlyNotRead = !items.length && summary.files && notRead.length === summary.files;
|
|
44113
|
-
|
|
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 };
|
|
44114
45443
|
}
|
|
44115
45444
|
var plural3 = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
44116
45445
|
function summaryLine(s) {
|
|
@@ -44173,7 +45502,7 @@ function assemblePassport({ parts, change = null, runs = [], purpose = null, ext
|
|
|
44173
45502
|
notRead.push({ part: p.name, file: u.file, line: u.line, what: owner ? `${owner.label}: ${u.why}` : u.why });
|
|
44174
45503
|
}
|
|
44175
45504
|
}
|
|
44176
|
-
const order2 = (a, b) => `${a.part}/${a.file}
|
|
45505
|
+
const order2 = (a, b) => byText(`${a.part}/${a.file}`, `${b.part}/${b.file}`) || (a.lines?.[0] ?? a.line ?? 0) - (b.lines?.[0] ?? b.line ?? 0);
|
|
44177
45506
|
behavior.sort(order2);
|
|
44178
45507
|
effects.sort(order2);
|
|
44179
45508
|
notRead.sort(order2);
|