@mark1russell7/vex 0.9.1 → 0.11.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/build/index.js CHANGED
@@ -1,12 +1,13 @@
1
+ import { Failure, Held, STD_EXT, THING, agree, check, context, formulaDefinitions, formulaEvaluators, isEnvelope, ok as ok$1, pathMatches, prepare, ref as ref$1, reference, refsOf, sameValue, typeName, typePath, typed } from "@mark1russell7/coeval";
1
2
  //#region src/result.ts
2
- const NONE = Object.freeze({ tag: "none" });
3
+ const NONE$1 = Object.freeze({ tag: "none" });
3
4
  /** This function makes an `Optional` that holds `value`. */
4
5
  const some = (value) => ({
5
6
  tag: "some",
6
7
  value
7
8
  });
8
9
  /** This function gives the shared empty `Optional`. */
9
- const none = () => NONE;
10
+ const none = () => NONE$1;
10
11
  /** This function makes a successful `Result`. */
11
12
  const ok = (value) => ({
12
13
  ok: true,
@@ -973,7 +974,7 @@ function defineDomain(spec) {
973
974
  kind: "vex.domain"
974
975
  });
975
976
  }
976
- const FORBIDDEN = /* @__PURE__ */ new Set([
977
+ const FORBIDDEN$1 = /* @__PURE__ */ new Set([
977
978
  "constructor",
978
979
  "__proto__",
979
980
  "prototype",
@@ -983,7 +984,7 @@ const FORBIDDEN = /* @__PURE__ */ new Set([
983
984
  "__lookupSetter__"
984
985
  ]);
985
986
  /** This function tells if a name can be an op name. */
986
- const isOpName = (name) => name.length > 0 && !FORBIDDEN.has(name);
987
+ const isOpName = (name) => name.length > 0 && !FORBIDDEN$1.has(name);
987
988
  /**
988
989
  * This function finds a method on a value: an own function property, or a function on the prototype chain.
989
990
  * It stops at `Object.prototype` and `Function.prototype`, so inherited members (for example `toString`) are not ops.
@@ -1033,8 +1034,36 @@ const vexList = (items) => Object.freeze({
1033
1034
  kind: "vex.list",
1034
1035
  items: Object.freeze([...items])
1035
1036
  });
1036
- /** This function tells if a value is a Vex list. */
1037
- const isVexList = (u) => u?.kind === "vex.list" && Array.isArray(u.items);
1037
+ /** The lists that passed the check of `isVexList` and cannot change. Each list of `vexList` is frozen. */
1038
+ const CHECKED = /* @__PURE__ */ new WeakSet();
1039
+ /** This function tells if a value is an error value: a text `code`, `kind` and `message`, and a `path` (LIST.SHAPE). */
1040
+ const isErrorValue = (u) => {
1041
+ if (typeof u !== "object" || u === null) return false;
1042
+ const e = u;
1043
+ return typeof e.code === "string" && typeof e.kind === "string" && typeof e.message === "string" && Array.isArray(e.path);
1044
+ };
1045
+ /** This function tells if a value is an item of a list: a text key, and a value or an error value (LIST.SHAPE). */
1046
+ const isListItem = (u) => {
1047
+ if (typeof u !== "object" || u === null) return false;
1048
+ const { key, result } = u;
1049
+ if (typeof key !== "string" || typeof result !== "object" || result === null) return false;
1050
+ const r = result;
1051
+ return r.ok === true ? r.value !== void 0 : r.ok === false && isErrorValue(r.error);
1052
+ };
1053
+ /**
1054
+ * This function tells if a value is a Vex list (LIST.SHAPE). A list has the kind `vex.list`, and each item has a text key
1055
+ * and a result. Another value with the kind `vex.list` is a record, so no list op applies to it. A frozen
1056
+ * list passes the check once.
1057
+ */
1058
+ const isVexList = (u) => {
1059
+ if (typeof u !== "object" || u === null) return false;
1060
+ if (CHECKED.has(u)) return true;
1061
+ const { kind, items } = u;
1062
+ if (kind !== "vex.list" || !Array.isArray(items)) return false;
1063
+ for (let i = 0; i < items.length; i++) if (!isListItem(items[i])) return false;
1064
+ if (Object.isFrozen(u) && Object.isFrozen(items)) CHECKED.add(u);
1065
+ return true;
1066
+ };
1038
1067
  /** The names of the core list ops. They apply when the first argument is a list. */
1039
1068
  const LIST_OPS = /* @__PURE__ */ new Set([
1040
1069
  "count",
@@ -1052,125 +1081,16 @@ const LIST_OPS = /* @__PURE__ */ new Set([
1052
1081
  "errors",
1053
1082
  "sortBy",
1054
1083
  "take",
1055
- "nth"
1084
+ "nth",
1085
+ "drop",
1086
+ "append",
1087
+ "flat",
1088
+ "without",
1089
+ "get"
1056
1090
  ]);
1057
1091
  /** This function tells if a name is the name of a core list op. */
1058
1092
  const isListOp = (op) => LIST_OPS.has(op);
1059
1093
  //#endregion
1060
- //#region ../../node_modules/.pnpm/@mark1russell7+coeval@0.1.0/node_modules/@mark1russell7/coeval/build/index.js
1061
- /** The keys that an envelope can have. */
1062
- const ENVELOPE_KEYS = [
1063
- "type",
1064
- "value",
1065
- "name",
1066
- "own"
1067
- ];
1068
- /**
1069
- * This function tells if a value is a JSON record (not an array and not null).
1070
- *
1071
- * @param value - The value to examine.
1072
- * @returns `true` for a record.
1073
- */
1074
- function isRecord$1(value) {
1075
- return typeof value === "object" && value !== null && !Array.isArray(value);
1076
- }
1077
- /**
1078
- * This function reads a field of a record. It reads only the own fields, thus `constructor` is not a field.
1079
- *
1080
- * @param record - The record.
1081
- * @param key - The name of the field.
1082
- * @returns The value of the field, or `undefined` when the record has no such field.
1083
- */
1084
- function field(record, key) {
1085
- return Object.hasOwn(record, key) ? record[key] : void 0;
1086
- }
1087
- /**
1088
- * This function tells if a value is a key of a path: a text, or a whole number from 0.
1089
- *
1090
- * @param value - The value to examine.
1091
- * @returns `true` for a key.
1092
- */
1093
- function isKey(value) {
1094
- return typeof value === "string" || typeof value === "number" && Number.isInteger(value) && value >= 0;
1095
- }
1096
- /**
1097
- * This function tells if a value is a reference to a type. The reference is a text, a list of keys, or a document
1098
- * of type `ref` whose path starts at the root `world`.
1099
- *
1100
- * @param value - The value to examine.
1101
- * @returns `true` for a reference to a type.
1102
- */
1103
- function isTypeRef(value) {
1104
- if (typeof value === "string") return value !== "";
1105
- if (Array.isArray(value)) return value.length > 0 && value.every(isKey);
1106
- if (!isRecord$1(value)) return false;
1107
- const path = field(value, "value");
1108
- return field(value, "type") === "ref" && Array.isArray(path) && path[0] === "world";
1109
- }
1110
- /**
1111
- * This function gives the path of a reference to a type, from the root of the world.
1112
- *
1113
- * @param type - The reference.
1114
- * @returns The keys from the root of the world, or `undefined` for a computed step that has no fixed key.
1115
- */
1116
- function typePath(type) {
1117
- if (typeof type === "string") return [type];
1118
- if (Array.isArray(type)) return type;
1119
- const steps = type.value.slice(1);
1120
- return steps.every(isKey) ? steps : void 0;
1121
- }
1122
- /**
1123
- * This function gives the text of a type for a reader: its keys, joined with a dot.
1124
- *
1125
- * @param type - The reference to the type.
1126
- * @returns The text, for example `git.push`.
1127
- */
1128
- function typeName(type) {
1129
- return typePath(type)?.join(".") ?? "(computed)";
1130
- }
1131
- /**
1132
- * This function tells if a value has the form of an envelope. That form is a record with a reference to a type
1133
- * and a `value`. It has no other keys than the keys of an envelope. A contract decides where an envelope is
1134
- * expected. This function only checks the form.
1135
- *
1136
- * @param value - The value to examine.
1137
- * @returns `true` when the value has the form of an envelope.
1138
- */
1139
- function isEnvelope(value) {
1140
- if (!isRecord$1(value)) return false;
1141
- if (!isTypeRef(field(value, "type")) || !Object.hasOwn(value, "value")) return false;
1142
- const name = field(value, "name");
1143
- if (name !== void 0 && typeof name !== "string") return false;
1144
- const own = field(value, "own");
1145
- if (own !== void 0 && !isRecord$1(own)) return false;
1146
- return Object.keys(value).every((key) => ENVELOPE_KEYS.includes(key));
1147
- }
1148
- /**
1149
- * This function makes an envelope.
1150
- *
1151
- * @param type - The reference to the kind.
1152
- * @param value - The value.
1153
- * @param header - The optional name and own entries.
1154
- * @returns The envelope.
1155
- */
1156
- function typed(type, value, header = {}) {
1157
- return {
1158
- type,
1159
- value,
1160
- ...header.name === void 0 ? {} : { name: header.name },
1161
- ...header.own === void 0 ? {} : { own: header.own }
1162
- };
1163
- }
1164
- /**
1165
- * This function makes a reference document: a path from a root of the context.
1166
- *
1167
- * @param path - The steps. The first step is a root: `self`, `names`, `world`, `event` or `caps`.
1168
- * @returns The document of type `ref`.
1169
- */
1170
- function ref$1(...path) {
1171
- return typed("ref", path);
1172
- }
1173
- //#endregion
1174
1094
  //#region src/codec.ts
1175
1095
  /** This function tells if a value is a record: an object that is not an array. */
1176
1096
  const isRecord = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
@@ -1236,34 +1156,1436 @@ function decodeValue(u, domains) {
1236
1156
  if (!r.ok) return r;
1237
1157
  out.push(r.value);
1238
1158
  }
1239
- return ok(out);
1159
+ return ok(out);
1160
+ }
1161
+ if (!isRecord(u)) return ok(u);
1162
+ const fields = (record) => {
1163
+ const out = {};
1164
+ for (const [k, x] of Object.entries(record)) {
1165
+ const r = decodeValue(x, domains);
1166
+ if (!r.ok) return r;
1167
+ out[k] = r.value;
1168
+ }
1169
+ return ok(out);
1170
+ };
1171
+ const kind = u["$vex"];
1172
+ if (kind === "escape" && isRecord(u["value"])) return fields(u["value"]);
1173
+ if (kind === "number" && typeof u["value"] === "string" && Object.hasOwn(NUMBERS, u["value"])) return ok(NUMBERS[u["value"]]);
1174
+ if (kind === "domain" && typeof u["domain"] === "string") {
1175
+ const name = u["domain"];
1176
+ const d = domains.find((dom) => dom.name === name);
1177
+ if (d?.decode === void 0) return fail(vexError("bad-expression", `no domain "${name}" decodes a literal`));
1178
+ return ok(d.decode(u["value"]));
1179
+ }
1180
+ return fields(u);
1181
+ }
1182
+ //#endregion
1183
+ //#region src/same.ts
1184
+ /**
1185
+ * The comparison of the values of Vex for `agree` of the kernel (EVAL.AGREE), and the test of a Vex error. The package
1186
+ * index does not export this module: `kernel.ts` and `plan.ts` use it.
1187
+ */
1188
+ /** This function tells if a value is a Vex error: it has a code, a kind, a message and a path. */
1189
+ function isVexError(u) {
1190
+ const e = u;
1191
+ return typeof e?.code === "string" && typeof e.kind === "string" && typeof e.message === "string" && Array.isArray(e.path);
1192
+ }
1193
+ /** This function tells if a value is a value of a class: an object that is not a plain record and not an array. */
1194
+ function isInstance(u) {
1195
+ if (typeof u !== "object" || u === null || Array.isArray(u)) return false;
1196
+ const proto = Object.getPrototypeOf(u);
1197
+ return proto !== Object.prototype && proto !== null;
1198
+ }
1199
+ /**
1200
+ * This function compares two values of Vex for `agree`. Two Vex errors agree when they have the same code, because
1201
+ * only the closure compiler gives the location of an error (EVAL.LOCATION). Two values of one class agree when their
1202
+ * fields agree, for example two values of a domain from two decodes of a literal. The rules of `sameValue` compare
1203
+ * each other pair.
1204
+ */
1205
+ function sameVex(a, b) {
1206
+ if (isVexError(a) && isVexError(b)) return a.code === b.code;
1207
+ if (!isInstance(a) || !isInstance(b)) return void 0;
1208
+ return Object.getPrototypeOf(a) === Object.getPrototypeOf(b) && sameValue({ ...a }, { ...b }, sameVex);
1209
+ }
1210
+ //#endregion
1211
+ //#region src/kernel.ts
1212
+ /**
1213
+ * Vex in the kernel of coeval (decision D13 of coeval, and decision D13 of Vex in `docs/REVIEW.md`). This module gives
1214
+ * the contracts of the kinds of Vex as data, and a machine of the kernel that evaluates the documents of Vex.
1215
+ *
1216
+ * - The static kit of the kernel checks a document by these contracts (`fromDocument`, DOC.ERROR) and finds its
1217
+ * references (`deps`, DEPS.READS).
1218
+ * - The machine is the reference tier of Vex. The closure compiler and the loop compiler give its results
1219
+ * (EVAL.REFERENCE). It evaluates the shared constructs with the formula kit of the kernel, and a profile gives the
1220
+ * rules of Vex. Vex adds only what is its own: the moves, the axes, the loops and the dispatch on the domains.
1221
+ */
1222
+ /** The kinds of the terms of Vex. A part in the position of a term has one of these kinds (DOC.TERM). */
1223
+ const TERM_KINDS = [
1224
+ ["lit"],
1225
+ ["ref"],
1226
+ ["record"],
1227
+ ["let"],
1228
+ ["call"],
1229
+ ["each"],
1230
+ ["fold"],
1231
+ ["iterate"],
1232
+ ["ops"],
1233
+ ["ext"]
1234
+ ];
1235
+ /** A term: an envelope of a term kind, or a bare value, which is a literal. */
1236
+ const TERM = {
1237
+ shape: "term",
1238
+ of: "lit",
1239
+ kinds: TERM_KINDS
1240
+ };
1241
+ const TERMS$1 = {
1242
+ shape: "list",
1243
+ item: TERM
1244
+ };
1245
+ const NAMES = {
1246
+ shape: "map",
1247
+ item: TERM
1248
+ };
1249
+ const AXIS = {
1250
+ shape: "term",
1251
+ kinds: [["axes"]]
1252
+ };
1253
+ /** The address of `each` and `fold`: a reference that gives a key of the space, not a value (DOC.ADDRESS). */
1254
+ const ADDRESS = {
1255
+ shape: "term",
1256
+ kinds: [["ref"]],
1257
+ address: true
1258
+ };
1259
+ const NO_VALUE = {
1260
+ shape: "one",
1261
+ values: [null]
1262
+ };
1263
+ /** This function gives the shape of a record with these fields and no other fields (DOC.CONSTRUCT). */
1264
+ const closed = (fields, required) => ({
1265
+ shape: "record",
1266
+ fields,
1267
+ required,
1268
+ closed: true
1269
+ });
1270
+ /** The axes without parameters. */
1271
+ const PLAIN_AXES = [
1272
+ "all",
1273
+ "others",
1274
+ "other",
1275
+ "children",
1276
+ "ancestors",
1277
+ "descendants",
1278
+ "siblings",
1279
+ "successors",
1280
+ "predecessors",
1281
+ "reachable"
1282
+ ];
1283
+ /** This function gives the kind of an axis with these parameters (DOC.AXIS). */
1284
+ const axisKind = (fields) => ({
1285
+ verbs: { eval: "vex.axis" },
1286
+ parts: closed(fields, Object.keys(fields)),
1287
+ summary: "An axis of Vex: the targets of a body."
1288
+ });
1289
+ /** This function gives the kind of a move. Its document is a step of a path, and a computed key is its part (DOC.MOVE). */
1290
+ const move = (walker, parts) => ({
1291
+ verbs: {
1292
+ eval: "formula.step",
1293
+ step: walker
1294
+ },
1295
+ parts,
1296
+ summary: "A move of Vex: a step to another key of the space."
1297
+ });
1298
+ /** The scope of a loop: the names of `init`, for the steps, the test `until` and the result (LOOP.NAMES). */
1299
+ const LOOP_SCOPE = [{
1300
+ names: { keysAt: ["init"] },
1301
+ in: [
1302
+ ["step", "*"],
1303
+ ["until"],
1304
+ ["result"]
1305
+ ]
1306
+ }];
1307
+ /**
1308
+ * This function gives the world of Vex. The module uses it one time, and the annotation `__PURE__` lets a bundler
1309
+ * remove the world from a program that does not use it.
1310
+ */
1311
+ function worldOfVex() {
1312
+ /** A binding of a `let`: a term, or a function (FN.BIND). */
1313
+ const BIND = {
1314
+ shape: "term",
1315
+ of: "lit",
1316
+ kinds: [...TERM_KINDS, ["fn"]]
1317
+ };
1318
+ /** The axes that `reverse` can hold: each axis but `where`, `reverse` and `table` (AXIS.REVERSE). */
1319
+ const BASE_AXES = [
1320
+ ...PLAIN_AXES,
1321
+ "neighbors",
1322
+ "window",
1323
+ "list"
1324
+ ];
1325
+ return {
1326
+ kinds: {
1327
+ lit: {
1328
+ verbs: { eval: "vex.lit" },
1329
+ summary: "A literal: its value in the JSON form of IR.JSON."
1330
+ },
1331
+ ref: {
1332
+ verbs: { eval: "formula.ref" },
1333
+ parts: { shape: "deep" },
1334
+ summary: "A reference: the fields of self after its moves, or a name."
1335
+ },
1336
+ record: {
1337
+ verbs: { eval: "formula.record" },
1338
+ parts: NAMES,
1339
+ summary: "A record of the values of its fields."
1340
+ },
1341
+ let: {
1342
+ verbs: { eval: "formula.let" },
1343
+ parts: closed({
1344
+ bind: {
1345
+ shape: "map",
1346
+ item: BIND
1347
+ },
1348
+ body: TERM
1349
+ }, ["bind", "body"]),
1350
+ scope: [{
1351
+ names: { keysAt: ["bind"] },
1352
+ in: [["body"]]
1353
+ }],
1354
+ summary: "Names for the body. A binding does not see the other bindings."
1355
+ },
1356
+ fn: {
1357
+ verbs: { eval: "vex.fn" },
1358
+ parts: closed({
1359
+ params: {
1360
+ shape: "list",
1361
+ item: { shape: "text" },
1362
+ distinct: true
1363
+ },
1364
+ body: TERM
1365
+ }, ["params", "body"]),
1366
+ scope: [{
1367
+ names: { listAt: ["params"] },
1368
+ in: [["body"]]
1369
+ }],
1370
+ summary: "A function of a let. Its body evaluates at the position of each call."
1371
+ },
1372
+ call: {
1373
+ verbs: { eval: "vex.call" },
1374
+ parts: closed({
1375
+ fn: {
1376
+ shape: "term",
1377
+ kinds: [["ref"]]
1378
+ },
1379
+ args: TERMS$1
1380
+ }, ["fn", "args"]),
1381
+ summary: "A call of a function of a let."
1382
+ },
1383
+ each: {
1384
+ verbs: { eval: "vex.each" },
1385
+ parts: closed({
1386
+ axis: AXIS,
1387
+ body: TERM,
1388
+ at: ADDRESS
1389
+ }, ["axis", "body"]),
1390
+ summary: "The body at each target of an axis: a list."
1391
+ },
1392
+ fold: {
1393
+ verbs: { eval: "vex.fold" },
1394
+ parts: closed({
1395
+ axis: AXIS,
1396
+ init: NAMES,
1397
+ step: NAMES,
1398
+ result: TERM,
1399
+ at: ADDRESS
1400
+ }, [
1401
+ "axis",
1402
+ "init",
1403
+ "step",
1404
+ "result"
1405
+ ]),
1406
+ scope: LOOP_SCOPE,
1407
+ summary: "A step at each target of an axis, in order, and a result."
1408
+ },
1409
+ iterate: {
1410
+ verbs: { eval: "vex.iterate" },
1411
+ parts: closed({
1412
+ limit: {
1413
+ shape: "number",
1414
+ whole: true,
1415
+ min: 0,
1416
+ max: MAX_ITERATIONS
1417
+ },
1418
+ init: NAMES,
1419
+ step: NAMES,
1420
+ until: TERM,
1421
+ result: TERM
1422
+ }, [
1423
+ "limit",
1424
+ "init",
1425
+ "step",
1426
+ "result"
1427
+ ]),
1428
+ scope: LOOP_SCOPE,
1429
+ summary: "Up to limit steps, until a test is true, and a result."
1430
+ },
1431
+ ops: {
1432
+ kinds: {},
1433
+ fallback: {
1434
+ verbs: { eval: "formula.op" },
1435
+ parts: TERMS$1,
1436
+ summary: "An op, applied to the values of its arguments."
1437
+ }
1438
+ },
1439
+ ext: {
1440
+ kinds: {},
1441
+ fallback: {
1442
+ verbs: { eval: "formula.ext" },
1443
+ summary: "An extension: its handler gives the value of its data."
1444
+ }
1445
+ },
1446
+ axes: { kinds: {
1447
+ ...Object.fromEntries(PLAIN_AXES.map((name) => [name, axisKind({})])),
1448
+ neighbors: axisKind({ n: {
1449
+ shape: "one",
1450
+ values: [4, 8]
1451
+ } }),
1452
+ window: axisKind({
1453
+ from: { shape: "number" },
1454
+ to: { shape: "number" }
1455
+ }),
1456
+ table: axisKind({ name: { shape: "text" } }),
1457
+ list: axisKind({ list: TERM }),
1458
+ reverse: axisKind({ axis: {
1459
+ shape: "term",
1460
+ kinds: BASE_AXES.map((name) => ["axes", name])
1461
+ } }),
1462
+ where: axisKind({
1463
+ axis: AXIS,
1464
+ test: TERM
1465
+ })
1466
+ } },
1467
+ moves: { kinds: {
1468
+ key: move("vex.move.key", TERM),
1469
+ index: move("vex.move.index", TERM),
1470
+ offset: move("vex.move.offset", {
1471
+ shape: "list",
1472
+ item: { shape: "number" }
1473
+ }),
1474
+ other: move("vex.move.other", NO_VALUE),
1475
+ origin: move("vex.move.origin", NO_VALUE),
1476
+ parent: move("vex.move.parent", NO_VALUE)
1477
+ } }
1478
+ },
1479
+ defaults: {}
1480
+ };
1481
+ }
1482
+ /**
1483
+ * The world of Vex: the contract of each kind of a document of Vex, as data. A contract gives the shape of the parts,
1484
+ * the data of the fields and the names that the kind binds. The static kit of the kernel reads it.
1485
+ */
1486
+ const VEX_WORLD = /* @__PURE__ */ worldOfVex();
1487
+ /** The deepest nesting of documents that the machine takes. A deeper document gives `#DEPTH!` (DOC.ERROR). */
1488
+ const MAX_DOCUMENT_DEPTH = 4096;
1489
+ /** The kind of a Vex error for each code of the kernel. Another code is a document that is not valid. */
1490
+ const KIND_OF = {
1491
+ "#REF!": "unknown-key",
1492
+ "#N/A": "missing-field",
1493
+ "#VALUE!": "kind-mismatch",
1494
+ "#NAME?": "unbound",
1495
+ "#NUM!": "not-finite",
1496
+ "#CALC!": "threw",
1497
+ "#ARGS": "args",
1498
+ "#CYCLE!": "cycle",
1499
+ "#DEPTH!": "depth"
1500
+ };
1501
+ /** This function gives the error of the kernel for a Vex error. The Vex error is its cause, so no detail is lost. */
1502
+ const toKernelError = (e) => ({
1503
+ code: e.code,
1504
+ reason: e.message,
1505
+ cause: e
1506
+ });
1507
+ /** This function gives the Vex error of an error of the kernel. A code that Vex does not have gives `#VALUE!`. */
1508
+ function toVexError(e) {
1509
+ if (isVexError(e.cause)) return e.cause;
1510
+ return vexError(KIND_OF[e.code] ?? "bad-expression", e.reason, e.cause === void 0 ? {} : { thrown: e.cause });
1511
+ }
1512
+ /** This function gives the Vex result of a result of the kernel. */
1513
+ const toVexResult = (r) => r.ok ? ok(r.value) : fail(toVexError(r.error));
1514
+ /** This function makes an error of the kernel from a kind of Vex error. */
1515
+ const kernelError = (kind, message, details = {}) => toKernelError(vexError(kind, message, details));
1516
+ /** This function makes a failed result of the kernel. */
1517
+ const failed = (kind, message) => ({
1518
+ ok: false,
1519
+ error: kernelError(kind, message)
1520
+ });
1521
+ /** This function stops host code with an error of the kernel. The kernel catches the `Failure` and gives its error. */
1522
+ const stop = (kind, message) => {
1523
+ throw new Failure(kernelError(kind, message));
1524
+ };
1525
+ /** This function tells if an error is `#DEPTH!`. Some rules do not hide it (EVAL.DEPTH). */
1526
+ const isDepth = (e) => e.code === "#DEPTH!";
1527
+ /** The segments that are not fields (REF.FORBIDDEN). */
1528
+ const FORBIDDEN = /* @__PURE__ */ new Set([
1529
+ "__proto__",
1530
+ "constructor",
1531
+ "prototype"
1532
+ ]);
1533
+ /**
1534
+ * A position of an evaluation, as a host thing of the kernel: the space, the tables, the origin and the focus. It is the
1535
+ * root `self` of the context. A move gives a new position, and a field step reads the record at the focus. A move that
1536
+ * fails gives a position with the failure. The failure is the result when a reader uses the position, so the checks of
1537
+ * the computed keys come first (NAV.COMPUTED).
1538
+ */
1539
+ var Place = class Place {
1540
+ space;
1541
+ tables;
1542
+ origin;
1543
+ focus;
1544
+ failure;
1545
+ constructor(space, tables, origin, focus, failure) {
1546
+ this[THING] = true;
1547
+ this.space = space;
1548
+ this.tables = tables;
1549
+ this.origin = origin;
1550
+ this.focus = focus;
1551
+ this.failure = failure;
1552
+ }
1553
+ /** The text of the position for a trace. */
1554
+ get label() {
1555
+ return `key ${this.focus}`;
1556
+ }
1557
+ /** This method gives the position of a key of the same space, with the same origin. */
1558
+ to(focus) {
1559
+ return new Place(this.space, this.tables, this.origin, focus);
1560
+ }
1561
+ /** This method gives the position with a failure, for a move that failed. */
1562
+ failed(failure) {
1563
+ return new Place(this.space, this.tables, this.origin, this.focus, failure);
1564
+ }
1565
+ /** This method reads one field of the record at the focus. */
1566
+ deref(key) {
1567
+ return this.resolve([key])?.thing;
1568
+ }
1569
+ /**
1570
+ * This method reads the fields of a path in the record at the focus (REF.PATH). A missing field, `null` and a segment
1571
+ * that is not a field reach nothing, and the kernel gives `#N/A` (REF.MISSING, REF.FORBIDDEN). A getter that throws
1572
+ * gives `#CALC!`, because the kernel catches the exception.
1573
+ */
1574
+ resolve(keys) {
1575
+ if (this.failure !== void 0) throw new Failure(this.failure);
1576
+ let value = this.space.get(this.focus);
1577
+ if (value === void 0 || value === null) return void 0;
1578
+ for (const key of keys) {
1579
+ const seg = String(key);
1580
+ if (typeof value !== "object" && typeof value !== "function" || seg === "" || FORBIDDEN.has(seg)) return void 0;
1581
+ value = Reflect.get(value, seg);
1582
+ if (value === void 0 || value === null) return void 0;
1583
+ }
1584
+ return { thing: value };
1585
+ }
1586
+ /** This method gives the record at the focus: the value of a reference without fields. */
1587
+ toJson() {
1588
+ if (this.failure !== void 0) throw new Failure(this.failure);
1589
+ const record = this.space.get(this.focus);
1590
+ return record === void 0 || record === null ? stop("missing-field", `the record at "${this.focus}" has no value`) : record;
1591
+ }
1592
+ };
1593
+ /**
1594
+ * This function gives the root `self` of an evaluation in the kernel. It is the position at the origin of a space,
1595
+ * with the tables of the axis table (AXIS.TABLE).
1596
+ */
1597
+ function vexSelf(space, origin, tables = {}) {
1598
+ return new Place(space, tables, origin, origin);
1599
+ }
1600
+ /**
1601
+ * This function gives the walker of a kind of move. `fix` gives the fixed move of the value of the step, or the reason
1602
+ * why the value is not valid, which gives `#VALUE!` (NAV.COMPUTED).
1603
+ */
1604
+ function moveWalker(fix) {
1605
+ return ({ data, here }) => {
1606
+ if (!(here instanceof Place)) return {
1607
+ ok: false,
1608
+ reason: "a move starts at a key of a space",
1609
+ code: "#REF!"
1610
+ };
1611
+ const fixed = fix(data);
1612
+ if (typeof fixed === "string") return {
1613
+ ok: false,
1614
+ reason: fixed,
1615
+ code: "#VALUE!"
1616
+ };
1617
+ if (here.failure !== void 0) return {
1618
+ ok: true,
1619
+ thing: here
1620
+ };
1621
+ const r = applyMove(here.space, here, fixed);
1622
+ return {
1623
+ ok: true,
1624
+ thing: r.ok ? here.to(r.value) : here.failed(toKernelError(r.error))
1625
+ };
1626
+ };
1627
+ }
1628
+ /** The walkers of the moves of Vex. */
1629
+ const WALKERS = {
1630
+ "vex.move.key": /* @__PURE__ */ moveWalker((d) => typeof d === "string" ? {
1631
+ t: "key",
1632
+ key: d
1633
+ } : `the key of a move is a ${typeof d}, not a text`),
1634
+ "vex.move.index": /* @__PURE__ */ moveWalker((d) => typeof d === "number" ? {
1635
+ t: "index",
1636
+ i: d
1637
+ } : `the position of a move is a ${typeof d}, not a number`),
1638
+ "vex.move.offset": /* @__PURE__ */ moveWalker((d) => ({
1639
+ t: "offset",
1640
+ d
1641
+ })),
1642
+ "vex.move.other": /* @__PURE__ */ moveWalker(() => ({ t: "other" })),
1643
+ "vex.move.origin": /* @__PURE__ */ moveWalker(() => ({ t: "origin" })),
1644
+ "vex.move.parent": /* @__PURE__ */ moveWalker(() => ({ t: "parent" }))
1645
+ };
1646
+ /** This function gives the position of a target. In the space of the axis table, the origin is the target (AXIS.TABLE). */
1647
+ const placeOf = (axis, from, key) => axis.table === void 0 ? from.to(key) : new Place(from.space, from.tables, key, key);
1648
+ /** This function gives the parts of a record value, by name. */
1649
+ const partsOf$1 = (value) => value ?? {};
1650
+ /** This function gives the part of a field that the contract makes necessary. */
1651
+ const partAt = (value, name) => partsOf$1(value)[name];
1652
+ /** This function gives the position of a context. A context without a position gives an error. */
1653
+ function selfOf(ctx) {
1654
+ return ctx.self instanceof Place ? ctx.self : kernelError("unknown-key", "the context has no key of a space");
1655
+ }
1656
+ /** This function gives the position where an axis finds its targets: the key of the address, or the focus (AXIS.ADDRESS). */
1657
+ function startOf(at, ctx) {
1658
+ if (at === void 0) return selfOf(ctx);
1659
+ const r = at.evaluate();
1660
+ if (!r.ok) return r.error;
1661
+ const where = r.value;
1662
+ return where.failure ?? where;
1663
+ }
1664
+ /** This function gives the position in the space of the axis: the space of its table for the axis table (AXIS.TABLE). */
1665
+ function spaceOf(axis, from) {
1666
+ if (axis.table === void 0) return from;
1667
+ const space = Object.hasOwn(from.tables, axis.table) ? from.tables[axis.table] : void 0;
1668
+ return space === void 0 ? kernelError("no-table", `the evaluation has no table "${axis.table}"`) : new Place(space, from.tables, from.origin, from.focus);
1669
+ }
1670
+ /**
1671
+ * This function is the evaluator of the axes. An axis document gives a value that finds the targets from a position.
1672
+ * The list of `list` evaluates at that position, and the test of `where` at each target (AXIS.LIST, AXIS.WHERE).
1673
+ */
1674
+ const axisEvaluator = ({ typePath, value, context }) => {
1675
+ const name = String(typePath[1]);
1676
+ const fields = partsOf$1(value);
1677
+ if (name === "table") {
1678
+ const table = value.name;
1679
+ return ok$1({
1680
+ table,
1681
+ targets: (from) => ok$1(from.space.keys.map((key) => ({ key })))
1682
+ });
1683
+ }
1684
+ if (name === "list") {
1685
+ const list = fields["list"];
1686
+ return ok$1({
1687
+ table: void 0,
1688
+ targets: (from) => {
1689
+ const r = list.evaluate({
1690
+ ...context,
1691
+ self: from
1692
+ });
1693
+ if (!r.ok) return r;
1694
+ if (!isVexList(r.value)) return failed("kind-mismatch", `the axis "list" needs a list, not a ${describe(r.value)}`);
1695
+ return ok$1(r.value.items.map(({ key, result }) => result.ok ? { key } : {
1696
+ key,
1697
+ error: result.error
1698
+ }));
1699
+ }
1700
+ });
1701
+ }
1702
+ if (name === "reverse" || name === "where") {
1703
+ const r = fields["axis"].evaluate();
1704
+ if (!r.ok) return r;
1705
+ const base = r.value;
1706
+ const test = fields["test"];
1707
+ if (test === void 0) return ok$1({
1708
+ table: base.table,
1709
+ targets: (from) => {
1710
+ const ts = base.targets(from);
1711
+ return ts.ok ? ok$1(ts.value.toReversed()) : ts;
1712
+ }
1713
+ });
1714
+ return ok$1({
1715
+ table: base.table,
1716
+ targets: (from) => whereTargets(base, test, context, from)
1717
+ });
1718
+ }
1719
+ const ir = {
1720
+ t: name,
1721
+ ...value
1722
+ };
1723
+ return ok$1({
1724
+ table: void 0,
1725
+ targets: (from) => {
1726
+ const keys = axisTargets(from.space, from, ir);
1727
+ return keys.ok ? ok$1(keys.value.map((key) => ({ key }))) : {
1728
+ ok: false,
1729
+ error: toKernelError(keys.error)
1730
+ };
1731
+ }
1732
+ });
1733
+ };
1734
+ /** This function keeps the targets where the test gives `true`. A failed test, or a value that is not a boolean, gives an error item. */
1735
+ function whereTargets(base, test, ctx, from) {
1736
+ const ts = base.targets(from);
1737
+ if (!ts.ok) return ts;
1738
+ const out = [];
1739
+ for (const t of ts.value) {
1740
+ if (t.error !== void 0) {
1741
+ out.push(t);
1742
+ continue;
1743
+ }
1744
+ const r = test.evaluate({
1745
+ ...ctx,
1746
+ self: placeOf(base, from, t.key)
1747
+ });
1748
+ if (!r.ok) out.push({
1749
+ key: t.key,
1750
+ error: toVexError(r.error)
1751
+ });
1752
+ else if (r.value === true) out.push({ key: t.key });
1753
+ else if (r.value !== false) out.push({
1754
+ key: t.key,
1755
+ error: vexError("kind-mismatch", `the test of "where" gave a ${typeof r.value}, not a boolean`)
1756
+ });
1757
+ }
1758
+ return ok$1(out);
1759
+ }
1760
+ /** This function finds the targets of the axis of a loop, from the address or the focus, in the space of the axis. */
1761
+ function targetsOf(value, ctx) {
1762
+ const start = startOf(partsOf$1(value)["at"], ctx);
1763
+ if (!(start instanceof Place)) return {
1764
+ ok: false,
1765
+ error: start
1766
+ };
1767
+ const a = partAt(value, "axis").evaluate();
1768
+ if (!a.ok) return a;
1769
+ const axis = a.value;
1770
+ const from = spaceOf(axis, start);
1771
+ if (!(from instanceof Place)) return {
1772
+ ok: false,
1773
+ error: from
1774
+ };
1775
+ const ts = axis.targets(from);
1776
+ return ts.ok ? ok$1({
1777
+ axis,
1778
+ from,
1779
+ targets: ts.value
1780
+ }) : ts;
1781
+ }
1782
+ /**
1783
+ * This function sets a name of a new record of names, also the name `__proto__`. The record is new and gets each
1784
+ * name one time, so the property needs no other attributes. A later record copies it with a spread, so it is enumerable.
1785
+ */
1786
+ function setName(names, name, value) {
1787
+ Object.defineProperty(names, name, {
1788
+ value,
1789
+ enumerable: true
1790
+ });
1791
+ }
1792
+ /**
1793
+ * This function evaluates the parts of a record of names in order (LOOP.NAMES). It gives the names with their new
1794
+ * values, or the first error. Each value reads the names before the step, so the names change only after all values.
1795
+ */
1796
+ function bindAll(record, ctx, names) {
1797
+ const values = [];
1798
+ for (const [name, part] of Object.entries(partsOf$1(record))) {
1799
+ const r = part.evaluate(ctx);
1800
+ if (!r.ok) return r;
1801
+ values.push([name, r.value]);
1802
+ }
1803
+ const out = { ...names };
1804
+ for (const [name, v] of values) setName(out, name, v);
1805
+ return ok$1(out);
1806
+ }
1807
+ /** The evaluators of the loops: each, fold and iterate (LOOP.NAMES, FOLD.ORDER, ITERATE.LIMIT). */
1808
+ const LOOPS = {
1809
+ "vex.each": ({ value, context }) => {
1810
+ const found = targetsOf(value, context);
1811
+ if (!found.ok) return found;
1812
+ const { axis, from, targets } = found.value;
1813
+ const body = partAt(value, "body");
1814
+ const items = targets.map(({ key, error }) => ({
1815
+ key,
1816
+ result: error === void 0 ? toVexResult(body.evaluate({
1817
+ ...context,
1818
+ self: placeOf(axis, from, key)
1819
+ })) : fail(error)
1820
+ }));
1821
+ return ok$1(vexList(items));
1822
+ },
1823
+ "vex.fold": ({ value, context }) => {
1824
+ const { init, step } = partsOf$1(value);
1825
+ const first = bindAll(init, context, context.names);
1826
+ if (!first.ok) return first;
1827
+ let names = first.value;
1828
+ const found = targetsOf(value, context);
1829
+ if (!found.ok) return found;
1830
+ const { axis, from, targets } = found.value;
1831
+ for (const { key, error } of targets) {
1832
+ if (error !== void 0) return {
1833
+ ok: false,
1834
+ error: toKernelError(error)
1835
+ };
1836
+ const next = bindAll(step, {
1837
+ ...context,
1838
+ self: placeOf(axis, from, key),
1839
+ names
1840
+ }, names);
1841
+ if (!next.ok) return next;
1842
+ names = next.value;
1843
+ }
1844
+ return partAt(value, "result").evaluate({
1845
+ ...context,
1846
+ names
1847
+ });
1848
+ },
1849
+ "vex.iterate": ({ value, context }) => {
1850
+ const { init, step, until } = partsOf$1(value);
1851
+ const limit = value.limit;
1852
+ const first = bindAll(init, context, context.names);
1853
+ if (!first.ok) return first;
1854
+ let names = first.value;
1855
+ for (let k = 0;; k++) {
1856
+ const here = {
1857
+ ...context,
1858
+ names
1859
+ };
1860
+ if (until !== void 0) {
1861
+ const t = until.evaluate(here);
1862
+ if (!t.ok) return t;
1863
+ if (t.value === true) break;
1864
+ if (t.value !== false) return failed("kind-mismatch", `the test "until" of "iterate" gave a ${typeof t.value}, not a boolean`);
1865
+ }
1866
+ if (k === limit) {
1867
+ if (until !== void 0) return failed("limit", `"iterate" made its ${String(limit)} steps, and its test "until" is not true`);
1868
+ break;
1869
+ }
1870
+ const next = bindAll(step, here, names);
1871
+ if (!next.ok) return next;
1872
+ names = next.value;
1873
+ }
1874
+ return partAt(value, "result").evaluate({
1875
+ ...context,
1876
+ names
1877
+ });
1878
+ }
1879
+ };
1880
+ /**
1881
+ * A function of a `let` (FN.BIND). A reference to its name is an error, because a function is not a value (FN.VALUE).
1882
+ * It keeps the names of the place of its binding, and its body evaluates at the position of each call (FN.CALL).
1883
+ */
1884
+ var Bound = class extends Held {
1885
+ params;
1886
+ body;
1887
+ names;
1888
+ constructor(params, body, names) {
1889
+ super(kernelError("kind-mismatch", "the name is a function, not a value"));
1890
+ this.params = params;
1891
+ this.body = body;
1892
+ this.names = names;
1893
+ }
1894
+ };
1895
+ /** The evaluators of the functions of Vex (FN.BIND, FN.CALL, FN.ARGS). */
1896
+ const FUNCTIONS = {
1897
+ "vex.fn": ({ value, context }) => ok$1(new Bound(value.params, partAt(value, "body"), context.names)),
1898
+ "vex.call": ({ doc, value, context }) => {
1899
+ const name = String(doc.value.fn.value[1]);
1900
+ const args = partsOf$1(value)["args"];
1901
+ if (!Object.hasOwn(context.names, name)) return failed("unbound", `the function "${name}" has no binding`);
1902
+ const bound = context.names[name];
1903
+ if (!(bound instanceof Bound)) return bound instanceof Held ? {
1904
+ ok: false,
1905
+ error: bound.error
1906
+ } : failed("kind-mismatch", `the name "${name}" is a value, not a function`);
1907
+ if (bound.params.length !== args.length) return failed("bad-expression", `the function "${name}" takes ${String(bound.params.length)} arguments, not ${String(args.length)}`);
1908
+ const names = { ...bound.names };
1909
+ bound.params.forEach((p, i) => {
1910
+ const r = args[i].evaluate();
1911
+ setName(names, p, r.ok ? r.value : new Held(r.error));
1912
+ });
1913
+ return bound.body.evaluate({
1914
+ ...context,
1915
+ names
1916
+ });
1917
+ }
1918
+ };
1919
+ /** This function gives a short name for the type of a value, for a message. */
1920
+ function describe(u) {
1921
+ if (u === null) return "null";
1922
+ if (Array.isArray(u)) return "array";
1923
+ if (isVexList(u)) return "list";
1924
+ return typeof u;
1925
+ }
1926
+ /** This function applies the test of a domain to a value. A test that throws rejects the value. */
1927
+ function accepts(d, x) {
1928
+ let accepted = false;
1929
+ try {
1930
+ accepted = d.is(x);
1931
+ } catch {}
1932
+ return accepted;
1933
+ }
1934
+ /** This function finds an own method of a receiver or of its prototypes, but not of `Object` or `Function` (CALL.METHOD). */
1935
+ function methodOf(self, name) {
1936
+ if (FORBIDDEN.has(name) || typeof self !== "object" && typeof self !== "function") return void 0;
1937
+ for (let o = self; o !== null && o !== Object.prototype && o !== Function.prototype; o = Object.getPrototypeOf(o)) {
1938
+ const d = Object.getOwnPropertyDescriptor(o, name);
1939
+ if (d !== void 0) return typeof d.value === "function" ? d.value : void 0;
1940
+ }
1941
+ }
1942
+ /** This function checks the value of an op (CALL.RESULT): a value, a finite number, and a valid value of its domain. */
1943
+ function checked(x, op, domains) {
1944
+ if (x === void 0 || x === null) return stop("undefined-result", `"${op}" gave no value`);
1945
+ if (typeof x === "number" && !Number.isFinite(x)) return stop("not-finite", `"${op}" gave ${String(x)}`);
1946
+ const d = domains.find((dom) => accepts(dom, x));
1947
+ if (d?.valid !== void 0 && !d.valid(x)) return stop("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`);
1948
+ return x;
1949
+ }
1950
+ /** This function finds the op of a domain for a receiver, or `undefined` (CALL.UNKNOWN-OP). */
1951
+ function opOf(d, self, op) {
1952
+ const spec = Object.hasOwn(d.ops, op) && !FORBIDDEN.has(op) ? d.ops[op] : void 0;
1953
+ const method = spec !== void 0 || d.methods === "all" ? methodOf(self, op) : void 0;
1954
+ return spec?.fn === void 0 && method === void 0 ? void 0 : {
1955
+ domain: d,
1956
+ spec,
1957
+ method
1958
+ };
1959
+ }
1960
+ /** This function applies the op of a domain: it lifts the numbers, checks the kinds of the arguments and checks the value. */
1961
+ function callFound(found, op, self, args, domains) {
1962
+ const { domain, spec } = found;
1963
+ const lift = spec?.liftScalar;
1964
+ const from = domain.fromScalar;
1965
+ const rest = from === void 0 ? args : args.map((a, i) => typeof a === "number" && (lift === true || Array.isArray(lift) && lift[i] === true) ? from(a) : a);
1966
+ const params = spec?.params;
1967
+ if (params !== void 0) rest.forEach((a, i) => {
1968
+ const k = params[i] ?? "any";
1969
+ if (k !== "any" && !(k === "domain" ? accepts(domain, a) : typeof a === k)) stop(k === "domain" ? "not-instance" : "kind-mismatch", `argument ${String(i + 1)} of "${op}" is a ${describe(a)}, not a ${k === "domain" ? domain.name : k}`);
1970
+ });
1971
+ return checked(spec?.fn !== void 0 ? spec.fn(self, ...rest) : found.method.call(self, ...rest), op, domains);
1972
+ }
1973
+ /** The list ops with a second argument before their options: a count, a position, an op name or a list. */
1974
+ const WITH_ARGUMENT$1 = /* @__PURE__ */ new Set([
1975
+ "reduce",
1976
+ "take",
1977
+ "nth",
1978
+ "drop",
1979
+ "append",
1980
+ "without",
1981
+ "get"
1982
+ ]);
1983
+ /**
1984
+ * This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
1985
+ * error comes first (EVAL.DEPTH). With `strict`, the first error item is the result.
1986
+ */
1987
+ function goodOf(items, strict) {
1988
+ const depth = items.find((it) => !it.result.ok && it.result.error.code === "#DEPTH!");
1989
+ if (depth !== void 0 && !depth.result.ok) throw new Failure(toKernelError(depth.result.error));
1990
+ const firstBad = items.find((it) => !it.result.ok);
1991
+ if (strict && firstBad !== void 0 && !firstBad.result.ok) throw new Failure(toKernelError(firstBad.result.error));
1992
+ return items.filter((it) => it.result.ok);
1993
+ }
1994
+ /** This function gives the items of the list `other` of `append` and `without` (LIST.BUILD). Another value gives `#VALUE!`. */
1995
+ function otherOf(op, other, strict) {
1996
+ return isVexList(other) ? goodOf(other.items, strict) : stop("kind-mismatch", `"${op}" needs a list as its second argument, not a ${describe(other)}`);
1997
+ }
1998
+ /** This function joins the lists that are the values of the items, in order (LIST.FLAT). Each list follows LIST.BUILD. */
1999
+ function flat(vs, strict) {
2000
+ const out = [];
2001
+ for (const inner of vs) {
2002
+ if (!isVexList(inner)) return stop("kind-mismatch", `"flat" needs a list as the value of each item, but an item is a ${describe(inner)}`);
2003
+ out.push(...goodOf(inner.items, strict));
2004
+ }
2005
+ return vexList(out);
2006
+ }
2007
+ /** This function applies a list op (LIST.*). The error items are skipped, except with `{ strict: true }`, and except `#DEPTH!`. */
2008
+ function listOp(op, items, rest, domains) {
2009
+ const o = WITH_ARGUMENT$1.has(op) ? rest[1] : rest[0];
2010
+ const strict = o?.strict === true;
2011
+ const good = goodOf(items, strict);
2012
+ const vs = good.map((it) => it.result.ok ? it.result.value : void 0);
2013
+ const nums = () => vs.every((x) => typeof x === "number") ? vs : stop("kind-mismatch", `"${op}" needs numbers`);
2014
+ const bools = () => vs.every((x) => typeof x === "boolean") ? vs : stop("kind-mismatch", `"${op}" needs booleans`);
2015
+ const empty = () => stop("empty", `"${op}" has no values to work with`);
2016
+ switch (op) {
2017
+ case "count": return vs.length;
2018
+ case "values": return Object.freeze([...vs]);
2019
+ case "keys": return Object.freeze(good.map((it) => it.key));
2020
+ case "errors": return Object.freeze(items.flatMap((it) => it.result.ok ? [] : [it.result.error]));
2021
+ case "first": return vs.length > 0 ? vs[0] : empty();
2022
+ case "sortBy": {
2023
+ const kind = typeof vs[0];
2024
+ if (vs.some((x) => typeof x !== kind || kind !== "number" && kind !== "string" || Number.isNaN(x))) stop("kind-mismatch", "\"sortBy\" needs numbers without NaN or texts, all of one kind");
2025
+ return vexList(good.map((it, i) => ({
2026
+ it,
2027
+ i
2028
+ })).toSorted((a, b) => compare(vs[a.i], vs[b.i])).map(({ it }) => it));
2029
+ }
2030
+ case "take":
2031
+ case "drop":
2032
+ case "nth": {
2033
+ const n = rest[0];
2034
+ if (!Number.isSafeInteger(n) || n < 0) return stop("kind-mismatch", `"${op}" needs a whole number from 0`);
2035
+ if (op === "take") return vexList(good.slice(0, n));
2036
+ if (op === "drop") return vexList(good.slice(n));
2037
+ return n < vs.length ? vs[n] : stop("empty", `"nth" has no item at the position ${String(n)}`);
2038
+ }
2039
+ case "append": return vexList([...good, ...otherOf(op, rest[0], strict)]);
2040
+ case "without": {
2041
+ const gone = new Set(otherOf(op, rest[0], strict).map((it) => it.key));
2042
+ return vexList(good.filter((it) => !gone.has(it.key)));
2043
+ }
2044
+ case "flat": return flat(vs, strict);
2045
+ case "get": {
2046
+ const key = rest[0];
2047
+ if (typeof key !== "string") return stop("kind-mismatch", `"get" needs a text key, not a ${describe(key)}`);
2048
+ const i = good.findIndex((it) => it.key === key);
2049
+ return i >= 0 ? vs[i] : stop("missing-field", `the list has no item with the key ${JSON.stringify(key)}`);
2050
+ }
2051
+ case "sum": return checked(nums().reduce((s, x) => s + x, 0), op, []);
2052
+ case "mean": {
2053
+ const n = nums();
2054
+ return n.length === 0 ? empty() : checked(n.reduce((s, x) => s + x, 0) / n.length, op, []);
2055
+ }
2056
+ case "min":
2057
+ case "max": {
2058
+ const n = nums();
2059
+ return n.length === 0 ? empty() : n.reduce((best, x) => op === "min" ? Math.min(best, x) : Math.max(best, x));
2060
+ }
2061
+ case "any": return bools().some(Boolean);
2062
+ case "all": return bools().every(Boolean);
2063
+ case "none": return !bools().some(Boolean);
2064
+ default: return reduce(rest[0], vs, o, domains);
2065
+ }
2066
+ }
2067
+ /** This function compares two numbers or two texts for `sortBy`. Equal values keep their order (LIST.SORT). */
2068
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
2069
+ /** This function folds the values of a list with a domain op, from the left (LIST.REDUCE, LIST.REDUCE.EMPTY). */
2070
+ function reduce(name, vs, o, domains) {
2071
+ if (typeof name !== "string") return stop("kind-mismatch", "\"reduce\" needs an op name");
2072
+ if (vs.length === 0) {
2073
+ const named = o?.domain;
2074
+ if (named !== void 0 && !domains.some((d) => d.name === named)) return stop("unknown-op", `"reduce" names the domain ${JSON.stringify(named) ?? "?"}, but the program has no such domain`);
2075
+ const ds = domains.filter((d) => Object.hasOwn(d.ops, name) && d.ops[name].identity !== void 0 && (named === void 0 || d.name === named));
2076
+ const only = ds.length === 1 ? ds[0]?.ops[name] : void 0;
2077
+ return only === void 0 ? stop("empty", `"reduce" with "${name}" has no values, and no one identity`) : only.identity();
2078
+ }
2079
+ let acc = vs[0];
2080
+ for (const x of vs.slice(1)) {
2081
+ const found = domains.filter((d) => accepts(d, acc)).map((d) => opOf(d, acc, name)).find((f) => f !== void 0);
2082
+ if (found === void 0) return stop("unknown-op", `no domain gives "${name}" for a ${describe(acc)}`);
2083
+ acc = callFound(found, name, acc, [x], domains);
2084
+ }
2085
+ return acc;
2086
+ }
2087
+ /**
2088
+ * This function gives the op of a name: the dispatch of Vex at run time. A list op applies to a list. Else the first
2089
+ * domain that accepts the receiver and has the op applies it. Else a free function applies (CALL.FREE).
2090
+ */
2091
+ function dispatch(op, domains, fns) {
2092
+ const free = Object.hasOwn(fns, op) ? fns[op] : void 0;
2093
+ const listed = LIST_OPS.has(op);
2094
+ return (...values) => {
2095
+ const self = values[0];
2096
+ if (listed && isVexList(self)) return listOp(op, self.items, values.slice(1), domains);
2097
+ let accepted = false;
2098
+ if (values.length > 0) for (const d of domains) {
2099
+ if (!accepts(d, self)) continue;
2100
+ accepted = true;
2101
+ const found = opOf(d, self, op);
2102
+ if (found !== void 0) return callFound(found, op, self, values.slice(1), domains);
2103
+ }
2104
+ if (free !== void 0) return checked(free(...values), op, domains);
2105
+ if (accepted || values.length === 0) return stop("unknown-op", accepted ? `the domain of the receiver has no op "${op}"` : `there is no function "${op}"`);
2106
+ return stop("not-instance", `no domain accepts the receiver of "${op}" (${describe(self)})`);
2107
+ };
2108
+ }
2109
+ /** This function gives an argument of a special form. A missing argument gives `#VALUE!`. */
2110
+ const argOf = (args, i, op) => args[i]?.() ?? failed("bad-expression", `"${op}" needs argument ${String(i + 1)}`);
2111
+ /** This function gives an argument of a special form that must be a boolean (FORM.IF, FORM.AND-OR). */
2112
+ function boolOf(args, i, op) {
2113
+ const r = argOf(args, i, op);
2114
+ return !r.ok || typeof r.value === "boolean" ? r : failed("kind-mismatch", `argument ${String(i + 1)} of "${op}" is a ${describe(r.value)}, not a boolean`);
2115
+ }
2116
+ /** This function gives `and` or `or`: they stop at the first argument that decides (FORM.AND-OR). */
2117
+ const logic = (op) => (args) => {
2118
+ if (args.length === 0) return failed("bad-expression", `"${op}" needs at least 1 argument`);
2119
+ for (let i = 0; i < args.length; i++) {
2120
+ const b = boolOf(args, i, op);
2121
+ if (!b.ok || b.value === (op === "or")) return b;
2122
+ }
2123
+ return ok$1(op === "and");
2124
+ };
2125
+ /** The special forms of Vex: lazy ops of the formula kit (FORM.IF, FORM.AND-OR, FORM.IFERROR). */
2126
+ const FORMS = {
2127
+ if: (args) => {
2128
+ const c = boolOf(args, 0, "if");
2129
+ return c.ok ? argOf(args, c.value === true ? 1 : 2, "if") : c;
2130
+ },
2131
+ and: /* @__PURE__ */ logic("and"),
2132
+ or: /* @__PURE__ */ logic("or"),
2133
+ ifError: (args) => {
2134
+ const first = argOf(args, 0, "ifError");
2135
+ return first.ok || isDepth(first.error) ? first : argOf(args, 1, "ifError");
2136
+ }
2137
+ };
2138
+ /**
2139
+ * This function gives the profile of Vex for the formula kit: the dispatch of the ops, the special forms and the
2140
+ * extensions. Two or more failed arguments or fields give `#ARGS` (CALL.ARGS, REC.FIELDS).
2141
+ */
2142
+ function profileOf(opts) {
2143
+ const domains = opts.domains ?? [];
2144
+ const fns = opts.fns ?? {};
2145
+ const extensions = opts.extensions ?? {};
2146
+ const ext = Object.create(null);
2147
+ for (const name of Object.keys(STD_EXT)) ext[name] = () => failed("unknown-op", `no handler for the extension kind "${name}"`);
2148
+ for (const [name, handler] of Object.entries(extensions)) ext[name] = (data, ctx) => {
2149
+ const self = selfOf(ctx);
2150
+ if (!(self instanceof Place)) return {
2151
+ ok: false,
2152
+ error: self
2153
+ };
2154
+ const r = handler(data, {
2155
+ space: self.space,
2156
+ position: {
2157
+ origin: self.origin,
2158
+ focus: self.focus
2159
+ },
2160
+ path: []
2161
+ });
2162
+ if (r.ok) return r;
2163
+ return {
2164
+ ok: false,
2165
+ error: toKernelError(r.error.origin === void 0 ? {
2166
+ ...r.error,
2167
+ origin: self.origin,
2168
+ focus: self.focus
2169
+ } : r.error)
2170
+ };
2171
+ };
2172
+ return {
2173
+ ops: (name) => dispatch(name, domains, fns),
2174
+ lazy: FORMS,
2175
+ ext,
2176
+ combine: (errors) => errors.find(isDepth) ?? kernelError("args", `${String(errors.length)} arguments failed`, { causes: errors.map(toVexError) })
2177
+ };
2178
+ }
2179
+ /** The evaluators of the literals: the JSON form of IR.JSON, and a value of the host (DOC.LITERAL). */
2180
+ function literals(domains) {
2181
+ return {
2182
+ "vex.lit": ({ doc }) => {
2183
+ const decoded = decodeValue(doc.value, domains);
2184
+ return decoded.ok ? ok$1(decoded.value) : {
2185
+ ok: false,
2186
+ error: toKernelError(decoded.error)
2187
+ };
2188
+ },
2189
+ "vex.host": ({ doc }) => ok$1(doc.value)
2190
+ };
2191
+ }
2192
+ /**
2193
+ * The rules of the machines of Vex. The values of a space are data, so a field that has the shape of a reference stays
2194
+ * a value. A reference starts at `self` or `names`, and a document has a limit of nesting.
2195
+ */
2196
+ const RULES = {
2197
+ plain: true,
2198
+ roots: ["self", "names"],
2199
+ maxDepth: MAX_DOCUMENT_DEPTH
2200
+ };
2201
+ /**
2202
+ * This function makes the machine of the kernel for Vex: the world of Vex, and the formula kit with the profile of
2203
+ * Vex. Vex adds its evaluators and its walkers. It is the reference tier of Vex (EVAL.REFERENCE).
2204
+ */
2205
+ function vexMachine(opts = {}) {
2206
+ return {
2207
+ world: VEX_WORLD,
2208
+ evaluators: {
2209
+ ...formulaEvaluators(profileOf(opts)),
2210
+ ...literals(opts.domains ?? []),
2211
+ ...LOOPS,
2212
+ ...FUNCTIONS,
2213
+ "vex.axis": axisEvaluator
2214
+ },
2215
+ walkers: WALKERS,
2216
+ ...RULES
2217
+ };
2218
+ }
2219
+ /** The code of each evaluator and walker of the machine of the checks. A check uses only their names. */
2220
+ const NO_CODE = () => stop("bad-expression", "the machine of the checks evaluates nothing");
2221
+ /**
2222
+ * This function makes the machine of the checks (DOC.CHECK). It has the world of Vex, and the names of the evaluators
2223
+ * and the walkers of `vexMachine` without their code. The static kit of the kernel needs only the names. Thus a
2224
+ * program that only reads documents does not hold the evaluators.
2225
+ */
2226
+ function vexChecker() {
2227
+ const evaluators = {};
2228
+ const walkers = {};
2229
+ const todo = Object.values(VEX_WORLD.kinds);
2230
+ for (let x = todo.pop(); x !== void 0; x = todo.pop()) {
2231
+ const kind = x;
2232
+ const { eval: name, step } = kind.verbs ?? {};
2233
+ if (name !== void 0) evaluators[name] = NO_CODE;
2234
+ if (step !== void 0) walkers[step] = NO_CODE;
2235
+ todo.push(...Object.values(kind.kinds ?? {}), ...kind.fallback === void 0 ? [] : [kind.fallback]);
2236
+ }
2237
+ return {
2238
+ world: VEX_WORLD,
2239
+ evaluators,
2240
+ walkers,
2241
+ ...RULES
2242
+ };
2243
+ }
2244
+ /**
2245
+ * This function gives the definitions of the machine of Vex for the reference interpreter of the kernel. The formula
2246
+ * kit gets its definitions with the profile of Vex. The evaluators of Vex are functions, so they need no definition.
2247
+ */
2248
+ function vexDefinitions(opts = {}) {
2249
+ return formulaDefinitions(profileOf(opts));
2250
+ }
2251
+ //#endregion
2252
+ //#region src/write.ts
2253
+ /**
2254
+ * The writer of the documents of Vex: the coeval document of an expression (DOC.TERM). It uses a stack, not recursion,
2255
+ * so an expression of any depth has a document. The package index does not export this module: `toDocument`, `deps`
2256
+ * and `kernelPlan` use it.
2257
+ */
2258
+ /** The stop of a write: a literal without a JSON form. The caller gives its error. */
2259
+ var WriteStop = class {
2260
+ error;
2261
+ constructor(error) {
2262
+ this.error = error;
2263
+ }
2264
+ };
2265
+ const NONE = [];
2266
+ const term = (e) => ({
2267
+ t: "term",
2268
+ e
2269
+ });
2270
+ const envelope = (e) => ({
2271
+ t: "envelope",
2272
+ e
2273
+ });
2274
+ /** This function gives a record from names and the documents of their values, from an index of the documents. */
2275
+ function namesOf(names, docs, from) {
2276
+ const out = {};
2277
+ names.forEach((name, i) => {
2278
+ Object.defineProperty(out, name, {
2279
+ value: docs[from + i],
2280
+ enumerable: true,
2281
+ writable: true,
2282
+ configurable: true
2283
+ });
2284
+ });
2285
+ return out;
2286
+ }
2287
+ /** The writer of one document. */
2288
+ var Writer = class {
2289
+ #opts;
2290
+ constructor(opts) {
2291
+ this.#opts = opts;
2292
+ }
2293
+ /** This method writes the document of a job, with a stack of plans. */
2294
+ write(root) {
2295
+ const stack = [{
2296
+ plan: this.#plan(root),
2297
+ docs: []
2298
+ }];
2299
+ for (;;) {
2300
+ const top = stack[stack.length - 1];
2301
+ const next = top.plan.jobs[top.docs.length];
2302
+ if (next !== void 0) {
2303
+ stack.push({
2304
+ plan: this.#plan(next),
2305
+ docs: []
2306
+ });
2307
+ continue;
2308
+ }
2309
+ const doc = top.plan.make(top.docs);
2310
+ stack.pop();
2311
+ const parent = stack[stack.length - 1];
2312
+ if (parent === void 0) return doc;
2313
+ parent.docs.push(doc);
2314
+ }
2315
+ }
2316
+ /** This method keeps the expression of an envelope, for `deps`. */
2317
+ #keep(doc, e) {
2318
+ this.#opts.nodes?.set(doc, e);
2319
+ return doc;
2320
+ }
2321
+ /** This method gives the document of a literal: its JSON form, or a value of the host (DOC.LITERAL). */
2322
+ #literal(value, root) {
2323
+ const host = {
2324
+ type: "lit",
2325
+ value,
2326
+ own: { eval: "vex.host" }
2327
+ };
2328
+ let r;
2329
+ try {
2330
+ r = encodeValue(value, this.#opts.domains);
2331
+ } catch (thrown) {
2332
+ if (this.#opts.literals === "json") throw thrown;
2333
+ return host;
2334
+ }
2335
+ if (!r.ok) {
2336
+ if (this.#opts.literals === "json") throw new WriteStop(r.error);
2337
+ return host;
2338
+ }
2339
+ const json = r.value;
2340
+ return root || isEnvelope(json) ? typed("lit", json) : json;
2341
+ }
2342
+ #plan(job) {
2343
+ if (job.t === "axis") return this.#axis(job.a);
2344
+ if (job.t === "move") return this.#move(job.m);
2345
+ const e = job.e;
2346
+ if (e.tag === "lit") return {
2347
+ jobs: NONE,
2348
+ make: () => this.#literal(e.value, job.t === "envelope")
2349
+ };
2350
+ return this.#envelope(e);
2351
+ }
2352
+ #envelope(e) {
2353
+ const reads = this.#opts.order === "reads";
2354
+ switch (e.tag) {
2355
+ case "ref": return {
2356
+ jobs: (e.at ?? []).map((m) => ({
2357
+ t: "move",
2358
+ m
2359
+ })),
2360
+ make: (docs) => this.#keep(ref$1("self", ...docs, ...e.path), e)
2361
+ };
2362
+ case "var": return {
2363
+ jobs: NONE,
2364
+ make: () => ref$1("names", e.name)
2365
+ };
2366
+ case "app": return {
2367
+ jobs: e.args.map(term),
2368
+ make: (docs) => typed(["ops", ...e.op.split(".")], [...docs])
2369
+ };
2370
+ case "let": {
2371
+ const names = Object.keys(e.bind);
2372
+ return {
2373
+ jobs: [...Object.values(e.bind).map(term), term(e.body)],
2374
+ make: (docs) => typed("let", {
2375
+ bind: namesOf(names, docs, 0),
2376
+ body: docs[names.length]
2377
+ })
2378
+ };
2379
+ }
2380
+ case "fn": return {
2381
+ jobs: [term(e.body)],
2382
+ make: (docs) => typed("fn", {
2383
+ params: [...e.params],
2384
+ body: docs[0]
2385
+ })
2386
+ };
2387
+ case "call": return {
2388
+ jobs: e.args.map(term),
2389
+ make: (docs) => this.#keep(typed("call", {
2390
+ fn: ref$1("names", e.fn),
2391
+ args: [...docs]
2392
+ }), e)
2393
+ };
2394
+ case "rec": {
2395
+ const names = Object.keys(e.fields);
2396
+ return {
2397
+ jobs: Object.values(e.fields).map(term),
2398
+ make: (docs) => typed("record", namesOf(names, docs, 0))
2399
+ };
2400
+ }
2401
+ case "each": {
2402
+ const at = this.#at(e.at);
2403
+ return {
2404
+ jobs: [
2405
+ {
2406
+ t: "axis",
2407
+ a: e.axis
2408
+ },
2409
+ term(e.body),
2410
+ ...at.jobs
2411
+ ],
2412
+ make: (docs) => {
2413
+ const axis = docs[0];
2414
+ const body = docs[1];
2415
+ const address = at.make(docs.slice(2));
2416
+ return this.#keep(typed("each", reads ? {
2417
+ body,
2418
+ axis,
2419
+ ...address
2420
+ } : {
2421
+ axis,
2422
+ body,
2423
+ ...address
2424
+ }), e);
2425
+ }
2426
+ };
2427
+ }
2428
+ case "fold": {
2429
+ const init = Object.keys(e.init);
2430
+ const step = Object.keys(e.step);
2431
+ const at = this.#at(e.at);
2432
+ const after = 1 + init.length + step.length;
2433
+ return {
2434
+ jobs: [
2435
+ {
2436
+ t: "axis",
2437
+ a: e.axis
2438
+ },
2439
+ ...Object.values(e.init).map(term),
2440
+ ...Object.values(e.step).map(term),
2441
+ term(e.result),
2442
+ ...at.jobs
2443
+ ],
2444
+ make: (docs) => {
2445
+ const axis = docs[0];
2446
+ const names = {
2447
+ init: namesOf(init, docs, 1),
2448
+ step: namesOf(step, docs, 1 + init.length)
2449
+ };
2450
+ const result = docs[after];
2451
+ const address = at.make(docs.slice(after + 1));
2452
+ return this.#keep(typed("fold", reads ? {
2453
+ ...names,
2454
+ axis,
2455
+ ...address,
2456
+ result
2457
+ } : {
2458
+ axis,
2459
+ ...names,
2460
+ result,
2461
+ ...address
2462
+ }), e);
2463
+ }
2464
+ };
2465
+ }
2466
+ case "iterate": {
2467
+ const init = Object.keys(e.init);
2468
+ const step = Object.keys(e.step);
2469
+ const until = e.until === void 0 ? NONE : [term(e.until)];
2470
+ const after = init.length + step.length;
2471
+ return {
2472
+ jobs: [
2473
+ ...Object.values(e.init).map(term),
2474
+ ...Object.values(e.step).map(term),
2475
+ ...until,
2476
+ term(e.result)
2477
+ ],
2478
+ make: (docs) => typed("iterate", {
2479
+ limit: e.limit,
2480
+ init: namesOf(init, docs, 0),
2481
+ step: namesOf(step, docs, init.length),
2482
+ ...e.until === void 0 ? {} : { until: docs[after] },
2483
+ result: docs[after + until.length]
2484
+ })
2485
+ };
2486
+ }
2487
+ case "ext": return {
2488
+ jobs: NONE,
2489
+ make: () => typed(["ext", ...e.kind.split(".")], e.data)
2490
+ };
2491
+ }
2492
+ }
2493
+ /** This method gives the plan of the field `at` of `each` and `fold`: a reference from `self` with moves only (DOC.ADDRESS). */
2494
+ #at(at) {
2495
+ if (at === void 0 || at.length === 0) return {
2496
+ jobs: NONE,
2497
+ make: () => ({})
2498
+ };
2499
+ return {
2500
+ jobs: at.map((m) => ({
2501
+ t: "move",
2502
+ m
2503
+ })),
2504
+ make: (docs) => ({ at: ref$1("self", ...docs) })
2505
+ };
2506
+ }
2507
+ /** This method gives the plan of a move. A computed key or position is an envelope (DOC.MOVE). */
2508
+ #move(m) {
2509
+ switch (m.t) {
2510
+ case "key": return typeof m.key === "string" ? this.#fixed(["moves", "key"], m.key) : {
2511
+ jobs: [envelope(m.key)],
2512
+ make: (docs) => typed(["moves", "key"], docs[0])
2513
+ };
2514
+ case "index": return typeof m.i === "number" ? this.#fixed(["moves", "index"], m.i) : {
2515
+ jobs: [envelope(m.i)],
2516
+ make: (docs) => typed(["moves", "index"], docs[0])
2517
+ };
2518
+ case "offset": return this.#fixed(["moves", "offset"], [...m.d]);
2519
+ case "other":
2520
+ case "origin":
2521
+ case "parent": return this.#fixed(["moves", m.t], null);
2522
+ }
1240
2523
  }
1241
- if (!isRecord(u)) return ok(u);
1242
- const fields = (record) => {
1243
- const out = {};
1244
- for (const [k, x] of Object.entries(record)) {
1245
- const r = decodeValue(x, domains);
1246
- if (!r.ok) return r;
1247
- out[k] = r.value;
2524
+ #fixed(type, value) {
2525
+ return {
2526
+ jobs: NONE,
2527
+ make: () => typed(type, value)
2528
+ };
2529
+ }
2530
+ /** This method gives the plan of an axis (DOC.AXIS). */
2531
+ #axis(a) {
2532
+ const type = ["axes", a.t];
2533
+ switch (a.t) {
2534
+ case "neighbors": return this.#fixed(type, { n: a.n });
2535
+ case "window": return this.#fixed(type, {
2536
+ from: a.from,
2537
+ to: a.to
2538
+ });
2539
+ case "table": return this.#fixed(type, { name: a.name });
2540
+ case "list": return {
2541
+ jobs: [term(a.list)],
2542
+ make: (docs) => typed(type, { list: docs[0] })
2543
+ };
2544
+ case "reverse": return {
2545
+ jobs: [{
2546
+ t: "axis",
2547
+ a: a.axis
2548
+ }],
2549
+ make: (docs) => typed(type, { axis: docs[0] })
2550
+ };
2551
+ case "where": return {
2552
+ jobs: [{
2553
+ t: "axis",
2554
+ a: a.axis
2555
+ }, term(a.test)],
2556
+ make: (docs) => typed(type, {
2557
+ axis: docs[0],
2558
+ test: docs[1]
2559
+ })
2560
+ };
2561
+ case "all":
2562
+ case "others":
2563
+ case "other":
2564
+ case "children":
2565
+ case "ancestors":
2566
+ case "descendants":
2567
+ case "siblings":
2568
+ case "successors":
2569
+ case "predecessors":
2570
+ case "reachable": return this.#fixed(type, {});
1248
2571
  }
1249
- return ok(out);
1250
- };
1251
- const kind = u["$vex"];
1252
- if (kind === "escape" && isRecord(u["value"])) return fields(u["value"]);
1253
- if (kind === "number" && typeof u["value"] === "string" && Object.hasOwn(NUMBERS, u["value"])) return ok(NUMBERS[u["value"]]);
1254
- if (kind === "domain" && typeof u["domain"] === "string") {
1255
- const name = u["domain"];
1256
- const d = domains.find((dom) => dom.name === name);
1257
- if (d?.decode === void 0) return fail(vexError("bad-expression", `no domain "${name}" decodes a literal`));
1258
- return ok(d.decode(u["value"]));
1259
2572
  }
1260
- return fields(u);
2573
+ };
2574
+ /**
2575
+ * This function writes the document of a valid expression. The root is always an envelope. It throws a `WriteStop` for
2576
+ * a literal without a JSON form in the mode `"json"`, and an exception of a getter of a literal value.
2577
+ */
2578
+ function writeDocument(e, opts) {
2579
+ return new Writer(opts).write({
2580
+ t: "envelope",
2581
+ e
2582
+ });
1261
2583
  }
1262
2584
  //#endregion
1263
2585
  //#region src/document.ts
1264
2586
  /**
1265
- * The documents of Vex. A document is the form of an expression in coeval, the language base of the family. Each term
1266
- * is an envelope `{ type, value }`, and a reference is a path from a root. The rules are decision D12 of coeval:
2587
+ * The documents of Vex. A document is the form of an expression in coeval, the kernel of the family. Each term is an
2588
+ * envelope `{ type, value }`, and a reference is a path from a root. The rules are decision D12 of coeval:
1267
2589
  * <https://github.com/mark1russell7/coeval/blob/main/docs/DECISIONS.md>.
1268
2590
  *
1269
2591
  * | Expression | Document |
@@ -1284,27 +2606,12 @@ function decodeValue(u, domains) {
1284
2606
  * | an axis | `{ "type": ["axes", name], "value": { ...parameters } }` |
1285
2607
  *
1286
2608
  * The address `at` of `each` and `fold` is a reference from `self` with moves only. An empty address is no address.
2609
+ *
2610
+ * The kernel checks a document by the contracts of `VEX_WORLD` (DOC.CHECK). A contract gives the shape of a kind, the
2611
+ * data of its fields and the kinds of each position. Then `fromDocument` reads the expression. It checks only the grammar
2612
+ * of Vex: the steps of a reference, the address, the function of a call and the names of a loop.
1287
2613
  */
1288
- /** The axes without parameters. */
1289
- const PLAIN_AXES = /* @__PURE__ */ new Set([
1290
- "all",
1291
- "others",
1292
- "other",
1293
- "children",
1294
- "ancestors",
1295
- "descendants",
1296
- "siblings",
1297
- "successors",
1298
- "predecessors",
1299
- "reachable"
1300
- ]);
1301
- /** The moves without a value. */
1302
- const PLAIN_MOVES = /* @__PURE__ */ new Map([
1303
- ["other", other],
1304
- ["origin", origin],
1305
- ["parent", parent]
1306
- ]);
1307
- /** The stop of a conversion. The functions of this module throw it, and the top of the conversion gives its error. */
2614
+ /** The stop of a reading. The functions of this module throw it, and the top of the reading gives its error. */
1308
2615
  var Stop = class {
1309
2616
  error;
1310
2617
  constructor(error) {
@@ -1313,16 +2620,20 @@ var Stop = class {
1313
2620
  };
1314
2621
  /** This function gives the location of a child: a JSON Pointer, with the escapes of RFC 6901. */
1315
2622
  const into = (where, step) => `${where}/${String(step).replaceAll("~", "~0").replaceAll("/", "~1")}`;
2623
+ /** This function gives the JSON Pointer of a path of keys. */
2624
+ const pointer = (keys) => keys.reduce(into, "");
2625
+ /** This function gives the message of a document that is not valid at `where`. */
2626
+ const notValid = (where, reason) => `the document is not valid at ${where === "" ? "its root" : `"${where}"`}: ${reason}`;
1316
2627
  /** This function stops the reading of a document that is not valid at `where`. */
1317
2628
  function bad(where, reason) {
1318
- throw new Stop(vexError("bad-expression", `the document is not valid at ${where === "" ? "its root" : `"${where}"`}: ${reason}`));
2629
+ throw new Stop(vexError("bad-expression", notValid(where, reason)));
1319
2630
  }
1320
2631
  /** This function does a conversion. It gives its value, or the error of the conversion. It does not throw. */
1321
2632
  function attempt(work, threw, deep) {
1322
2633
  try {
1323
2634
  return ok(work());
1324
2635
  } catch (thrown) {
1325
- if (thrown instanceof Stop) return fail(thrown.error);
2636
+ if (thrown instanceof Stop || thrown instanceof WriteStop) return fail(thrown.error);
1326
2637
  if (isStackOverflow(thrown)) return fail(vexError("depth", deep, { thrown }));
1327
2638
  return fail(vexError("threw", threw, { thrown }));
1328
2639
  }
@@ -1342,131 +2653,41 @@ function isDocument(u) {
1342
2653
  function toDocument(e, domains = []) {
1343
2654
  const shape = shapeError(e);
1344
2655
  if (shape !== void 0) return fail(vexError("bad-expression", shape));
1345
- return attempt(() => new Writer(domains).envelope(e), "the expression has no document", "the expression is too deep for the call stack of the engine");
2656
+ const options = {
2657
+ domains,
2658
+ literals: "json",
2659
+ order: "document"
2660
+ };
2661
+ return attempt(() => writeDocument(e, options), "the expression has no document", "a literal value is too deep for the call stack of the engine");
2662
+ }
2663
+ let checker;
2664
+ /** This function gives the first problem of a document that the kernel finds by the contracts of Vex (DOC.CHECK). */
2665
+ function problemOf(doc) {
2666
+ checker ??= vexChecker();
2667
+ return check(checker, doc, {
2668
+ declaredType: "lit",
2669
+ names: "any"
2670
+ })[0];
1346
2671
  }
1347
2672
  /**
1348
- * This function reads an expression from a document (DOC.TERM). It is the inverse of `toDocument`. It checks the
1349
- * expression as `compile` does (EVAL.SHAPE). A document that is not valid gives `#VALUE!` with its location (DOC.ERROR).
2673
+ * This function reads an expression from a document (DOC.TERM). It is the inverse of `toDocument`. The kernel checks
2674
+ * the document first (DOC.CHECK). A document that is not valid gives `#VALUE!` with its location, and a document nested
2675
+ * deeper than the kernel takes gives `#DEPTH!` (DOC.ERROR). The expression of a valid document is valid (EVAL.SHAPE).
1350
2676
  */
1351
2677
  function fromDocument(doc, domains = []) {
1352
- const read = attempt(() => new Reader(domains).term(doc, ""), "a decoder of a domain threw an exception", "the document is too deep for the call stack of the engine");
1353
- if (!read.ok) return read;
1354
- const shape = shapeError(read.value);
1355
- return shape === void 0 ? read : fail(vexError("bad-expression", `the document gives an expression that is not valid: ${shape}`));
2678
+ const problem = attempt(() => problemOf(doc), "the check of the document threw an exception", "the document is too deep for the call stack of the engine");
2679
+ if (!problem.ok) return problem;
2680
+ const issue = problem.value;
2681
+ if (issue?.code === "#DEPTH!") return fail(vexError("depth", `the document is nested deeper than ${String(MAX_DOCUMENT_DEPTH)} documents`));
2682
+ if (issue !== void 0) return fail(vexError("bad-expression", notValid(pointer(issue.at ?? []), issue.reason)));
2683
+ return attempt(() => new Reader(domains).term(doc, ""), "a decoder of a domain threw an exception", "the document is too deep for the call stack of the engine");
1356
2684
  }
1357
- /** The writer of documents. Its methods throw a `Stop` for a literal without a JSON form. */
1358
- var Writer = class {
1359
- #domains;
1360
- constructor(domains) {
1361
- this.#domains = domains;
1362
- }
1363
- /** This method gives the document of a term. A literal is its JSON value, except a value with the shape of an envelope. */
1364
- term(e) {
1365
- if (e.tag !== "lit") return this.envelope(e);
1366
- const value = this.#value(e.value);
1367
- return isEnvelope(value) ? typed("lit", value) : value;
1368
- }
1369
- /** This method gives the document of a term as an envelope. Here a literal is an envelope too. */
1370
- envelope(e) {
1371
- switch (e.tag) {
1372
- case "lit": return typed("lit", this.#value(e.value));
1373
- case "ref": return ref$1("self", ...this.#moves(e.at), ...e.path);
1374
- case "var": return ref$1("names", e.name);
1375
- case "app": return typed(["ops", ...e.op.split(".")], e.args.map((a) => this.term(a)));
1376
- case "let": return typed("let", {
1377
- bind: this.#names(e.bind),
1378
- body: this.term(e.body)
1379
- });
1380
- case "fn": return typed("fn", {
1381
- params: [...e.params],
1382
- body: this.term(e.body)
1383
- });
1384
- case "call": return typed("call", {
1385
- fn: ref$1("names", e.fn),
1386
- args: e.args.map((a) => this.term(a))
1387
- });
1388
- case "rec": return typed("record", this.#names(e.fields));
1389
- case "each": return typed("each", {
1390
- axis: this.#axis(e.axis),
1391
- body: this.term(e.body),
1392
- ...this.#at(e.at)
1393
- });
1394
- case "fold": return typed("fold", {
1395
- axis: this.#axis(e.axis),
1396
- init: this.#names(e.init),
1397
- step: this.#names(e.step),
1398
- result: this.term(e.result),
1399
- ...this.#at(e.at)
1400
- });
1401
- case "iterate": return typed("iterate", {
1402
- limit: e.limit,
1403
- init: this.#names(e.init),
1404
- step: this.#names(e.step),
1405
- ...e.until === void 0 ? {} : { until: this.term(e.until) },
1406
- result: this.term(e.result)
1407
- });
1408
- case "ext": return typed(["ext", ...e.kind.split(".")], e.data);
1409
- }
1410
- }
1411
- /** This method gives the JSON form of a literal value (IR.JSON). */
1412
- #value(u) {
1413
- const r = encodeValue(u, this.#domains);
1414
- if (!r.ok) throw new Stop(r.error);
1415
- return r.value;
1416
- }
1417
- /** This method gives the documents of the terms of a record of names. */
1418
- #names(names) {
1419
- return Object.fromEntries(Object.entries(names).map(([name, x]) => [name, this.term(x)]));
1420
- }
1421
- /** This method gives the step documents of the moves of an address. */
1422
- #moves(at) {
1423
- return (at ?? []).map((m) => this.#move(m));
1424
- }
1425
- /** This method gives the step document of a move. A computed key or position is an envelope (DOC.MOVE). */
1426
- #move(m) {
1427
- switch (m.t) {
1428
- case "key": return typed(["moves", "key"], typeof m.key === "string" ? m.key : this.envelope(m.key));
1429
- case "index": return typed(["moves", "index"], typeof m.i === "number" ? m.i : this.envelope(m.i));
1430
- case "offset": return typed(["moves", "offset"], [...m.d]);
1431
- case "other":
1432
- case "origin":
1433
- case "parent": return typed(["moves", m.t], null);
1434
- }
1435
- }
1436
- /** This method gives the field `at` of `each` and `fold`: a reference from `self` with moves only, or no field. */
1437
- #at(at) {
1438
- return at === void 0 || at.length === 0 ? {} : { at: ref$1("self", ...this.#moves(at)) };
1439
- }
1440
- /** This method gives the document of an axis (DOC.AXIS). */
1441
- #axis(a) {
1442
- const name = ["axes", a.t];
1443
- switch (a.t) {
1444
- case "neighbors": return typed(name, { n: a.n });
1445
- case "window": return typed(name, {
1446
- from: a.from,
1447
- to: a.to
1448
- });
1449
- case "table": return typed(name, { name: a.name });
1450
- case "list": return typed(name, { list: this.term(a.list) });
1451
- case "reverse": return typed(name, { axis: this.#axis(a.axis) });
1452
- case "where": return typed(name, {
1453
- axis: this.#axis(a.axis),
1454
- test: this.term(a.test)
1455
- });
1456
- case "all":
1457
- case "others":
1458
- case "other":
1459
- case "children":
1460
- case "ancestors":
1461
- case "descendants":
1462
- case "siblings":
1463
- case "successors":
1464
- case "predecessors":
1465
- case "reachable": return typed(name, {});
1466
- }
1467
- }
1468
- };
1469
- /** The reader of documents. Its methods throw a `Stop` at the first part that is not valid. */
2685
+ /** The kinds of the terms, as the first key of their type. */
2686
+ const TERMS = /* @__PURE__ */ new Set(/* @__PURE__ */ TERM_KINDS.map((k) => k[0]));
2687
+ /**
2688
+ * The reader of documents. The kernel checked the document, so each kind has the shape of its contract. The reader
2689
+ * checks the grammar of Vex, and its methods throw a `Stop` at the first part that is not valid.
2690
+ */
1470
2691
  var Reader = class {
1471
2692
  #domains;
1472
2693
  constructor(domains) {
@@ -1479,65 +2700,39 @@ var Reader = class {
1479
2700
  /** This method reads a term in an envelope. */
1480
2701
  #envelope(u, where) {
1481
2702
  const at = into(where, "value");
1482
- const [head, ...rest] = this.#type(u, where);
1483
- if (rest.length > 0 && (head === "ops" || head === "ext")) {
1484
- const name = this.#name(rest, into(where, "type"));
1485
- return head === "ops" ? app(name, ...this.#list(u.value, at).map((x, i) => this.term(x, into(at, i)))) : ext(name, u.value);
2703
+ const keys = this.#type(u, where);
2704
+ const head = String(keys[0]);
2705
+ if (!TERMS.has(head)) return bad(where, `the type "${typeName(u.type)}" is not a term of Vex`);
2706
+ if (head === "ops" || head === "ext") {
2707
+ const name = this.#name(keys.slice(1), into(where, "type"));
2708
+ return head === "ops" ? app(name, ...u.value.map((x, i) => this.term(x, into(at, i)))) : ext(name, u.value);
1486
2709
  }
1487
- if (rest.length > 0) return bad(where, `the type "${typeName(u.type)}" is not a term of Vex`);
2710
+ const f = u.value;
1488
2711
  switch (head) {
1489
2712
  case "lit": return lit(this.#value(u.value, at));
1490
2713
  case "ref": return this.#ref(u.value, at);
1491
- case "let": {
1492
- const f = fields(u.value, at, ["bind", "body"]);
1493
- return let_(this.#names(f["bind"], into(at, "bind")), this.term(f["body"], into(at, "body")));
1494
- }
1495
- case "fn": {
1496
- const f = fields(u.value, at, ["params", "body"]);
1497
- const params = this.#list(f["params"], into(at, "params"));
1498
- if (!params.every((p) => typeof p === "string")) return bad(into(at, "params"), "a parameter is not a text");
1499
- return fn(params, this.term(f["body"], into(at, "body")));
1500
- }
2714
+ case "let": return let_(this.#binds(f["bind"], into(at, "bind")), this.term(f["body"], into(at, "body")));
1501
2715
  case "call": {
1502
- const f = fields(u.value, at, ["fn", "args"]);
1503
2716
  const name = this.#function(f["fn"], into(at, "fn"));
1504
- return call(name, ...this.#list(f["args"], into(at, "args")).map((x, i) => this.term(x, into(into(at, "args"), i))));
2717
+ return call(name, ...f["args"].map((x, i) => this.term(x, into(into(at, "args"), i))));
1505
2718
  }
1506
2719
  case "record": return rec(this.#names(u.value, at));
1507
- case "each": {
1508
- const f = fields(u.value, at, ["axis", "body"], ["at"]);
1509
- return each(this.#axis(f["axis"], into(at, "axis")), this.term(f["body"], into(at, "body")), this.#address(f["at"], into(at, "at")));
1510
- }
2720
+ case "each": return each(this.#axis(f["axis"], into(at, "axis")), this.term(f["body"], into(at, "body")), this.#address(f["at"], into(at, "at")));
1511
2721
  case "fold": {
1512
- const f = fields(u.value, at, [
1513
- "axis",
1514
- "init",
1515
- "step",
1516
- "result"
1517
- ], ["at"]);
1518
- return fold(this.#axis(f["axis"], into(at, "axis")), this.#names(f["init"], into(at, "init")), this.#names(f["step"], into(at, "step")), this.term(f["result"], into(at, "result")), this.#address(f["at"], into(at, "at")));
2722
+ const [init, step] = this.#loop(f, at);
2723
+ return fold(this.#axis(f["axis"], into(at, "axis")), init, step, this.term(f["result"], into(at, "result")), this.#address(f["at"], into(at, "at")));
1519
2724
  }
1520
- case "iterate": {
1521
- const f = fields(u.value, at, [
1522
- "limit",
1523
- "init",
1524
- "step",
1525
- "result"
1526
- ], ["until"]);
1527
- const init = this.#names(f["init"], into(at, "init"));
1528
- const step = this.#names(f["step"], into(at, "step"));
2725
+ default: {
2726
+ const [init, step] = this.#loop(f, at);
1529
2727
  const until = f["until"] === void 0 ? void 0 : this.term(f["until"], into(at, "until"));
1530
2728
  return iterate(f["limit"], init, step, this.term(f["result"], into(at, "result")), until);
1531
2729
  }
1532
- default: return bad(where, `the type "${typeName(u.type)}" is not a term of Vex`);
1533
2730
  }
1534
2731
  }
1535
- /** This method gives the keys of the type of an envelope. An envelope of a term has no header (DOC.TERM). */
2732
+ /** This method gives the keys of the type of an envelope. A term of Vex has no header (DOC.TERM). */
1536
2733
  #type(u, where) {
1537
2734
  if (u.name !== void 0 || u.own !== void 0) return bad(where, "a term of Vex has no name and no own entries");
1538
- const keys = typePath(u.type);
1539
- if (keys === void 0) return bad(into(where, "type"), "the type has a computed step");
1540
- return keys;
2735
+ return typePath(u.type);
1541
2736
  }
1542
2737
  /** This method gives the name of an op or an extension: its keys, joined with dots (DOC.OPS, DOC.EXT). */
1543
2738
  #name(keys, where) {
@@ -1548,20 +2743,31 @@ var Reader = class {
1548
2743
  const r = decodeValue(u, this.#domains);
1549
2744
  return r.ok ? r.value : bad(where, r.error.message);
1550
2745
  }
1551
- /** This method reads a list. */
1552
- #list(u, where) {
1553
- return Array.isArray(u) ? u : bad(where, "the value is not a list");
1554
- }
1555
2746
  /** This method reads a record of names and the term of each name. */
1556
2747
  #names(u, where) {
1557
- if (!isRecord(u)) return bad(where, "the value is not a record");
1558
2748
  return Object.fromEntries(Object.entries(u).map(([name, x]) => [name, this.term(x, into(where, name))]));
1559
2749
  }
2750
+ /** This method reads the bindings of a let. A binding can be a function (FN.BIND). */
2751
+ #binds(u, where) {
2752
+ return Object.fromEntries(Object.entries(u).map(([name, x]) => {
2753
+ const at = into(where, name);
2754
+ if (!isDocument(x) || typeName(x.type) !== "fn") return [name, this.term(x, at)];
2755
+ this.#type(x, at);
2756
+ const f = x.value;
2757
+ return [name, fn(f.params, this.term(f.body, into(into(at, "value"), "body")))];
2758
+ }));
2759
+ }
2760
+ /** This method reads the names of a loop. Each name of `step` is a name of `init` (LOOP.NAMES). */
2761
+ #loop(f, at) {
2762
+ const init = this.#names(f["init"], into(at, "init"));
2763
+ const step = this.#names(f["step"], into(at, "step"));
2764
+ const extra = Object.keys(step).find((name) => !Object.hasOwn(init, name));
2765
+ return extra === void 0 ? [init, step] : bad(into(into(at, "step"), extra), `the name "${extra}" of step is not a name of init`);
2766
+ }
1560
2767
  /** This method reads a reference: the fields of `self` after its moves, or a name of `names` (DOC.REF). */
1561
- #ref(u, where) {
1562
- const [root, ...steps] = this.#list(u, where);
2768
+ #ref(path, where) {
2769
+ const [root, ...steps] = path;
1563
2770
  if (root === "names") return steps.length === 1 && typeof steps[0] === "string" ? v(steps[0]) : bad(where, "a reference to a name has one step: the name");
1564
- if (root !== "self") return bad(into(where, 0), `Vex reads only from the roots "self" and "names", and this reference starts at ${JSON.stringify(root) ?? "nothing"}`);
1565
2771
  const moves = [];
1566
2772
  const names = [];
1567
2773
  steps.forEach((step, i) => {
@@ -1575,88 +2781,58 @@ var Reader = class {
1575
2781
  }
1576
2782
  /** This method reads the function of a call: a reference to a name (DOC.CALL). */
1577
2783
  #function(u, where) {
1578
- const e = isDocument(u) ? this.#envelope(u, where) : void 0;
1579
- return e?.tag === "var" ? e.name : bad(where, "the function of a call is a reference to a name: { \"type\": \"ref\", \"value\": [\"names\", name] }");
2784
+ const steps = u.value;
2785
+ return steps[0] === "names" && steps.length === 2 && typeof steps[1] === "string" ? steps[1] : bad(where, "the function of a call is a reference to a name: { \"type\": \"ref\", \"value\": [\"names\", name] }");
1580
2786
  }
1581
2787
  /** This method reads the field `at` of `each` and `fold`: a reference from `self` with moves only (DOC.ADDRESS). */
1582
2788
  #address(u, where) {
1583
2789
  if (u === void 0) return void 0;
1584
- const e = isDocument(u) ? this.#envelope(u, where) : void 0;
1585
- return e?.tag === "ref" && e.path.length === 0 ? e.at ?? [] : bad(where, "the address is a reference from \"self\" with moves only: { \"type\": \"ref\", \"value\": [\"self\", ...moves] }");
2790
+ const e = this.#envelope(u, where);
2791
+ return e.tag === "ref" && e.path.length === 0 ? e.at ?? [] : bad(where, "the address is a reference from \"self\" with moves only: { \"type\": \"ref\", \"value\": [\"self\", ...moves] }");
1586
2792
  }
1587
- /** This method reads a move (DOC.MOVE). A fixed key is a text, a fixed position is a number, and an envelope is a term. */
2793
+ /**
2794
+ * This method reads a move (DOC.MOVE). The value of `key` and `index` is a term: a text key and a number position are
2795
+ * fixed, and another term is computed. The check gave the other moves their values.
2796
+ */
1588
2797
  #move(u, where) {
1589
- const [head, kind, ...rest] = this.#type(u, where);
2798
+ const kind = String(this.#type(u, where)[1]);
1590
2799
  const at = into(where, "value");
1591
- if (head !== "moves" || typeof kind !== "string" || rest.length > 0) return bad(where, `Vex has no step of the type "${typeName(u.type)}"`);
1592
2800
  const value = u.value;
1593
2801
  switch (kind) {
1594
- case "key": return typeof value === "string" ? key(value) : isDocument(value) ? key(this.#envelope(value, at)) : bad(at, "the key is not a text or a term in an envelope");
1595
- case "index": return typeof value === "number" ? index(value) : isDocument(value) ? index(this.#envelope(value, at)) : bad(at, "the position is not a number or a term in an envelope");
1596
- case "offset": return Array.isArray(value) && value.every((d) => typeof d === "number") ? offset(...value) : bad(at, "the offset is not a list of numbers");
1597
- default: {
1598
- const plain = PLAIN_MOVES.get(kind);
1599
- if (plain === void 0) return bad(where, `Vex has no move "${kind}"`);
1600
- return value === null ? plain : bad(at, `the value of the move "${kind}" is not null`);
1601
- }
2802
+ case "key": return typeof value === "string" ? key(value) : key(this.term(value, at));
2803
+ case "index": return typeof value === "number" ? index(value) : index(this.term(value, at));
2804
+ case "offset": return offset(...value);
2805
+ case "other": return other;
2806
+ case "origin": return origin;
2807
+ default: return parent;
1602
2808
  }
1603
2809
  }
1604
- /** This method reads an axis (DOC.AXIS). The check of the expression tells a bad parameter. */
2810
+ /** This method reads an axis (DOC.AXIS). The check gave it the parameters of its kind. */
1605
2811
  #axis(u, where) {
1606
- if (!isDocument(u)) return bad(where, "the axis is not an envelope");
1607
- const [head, name, ...rest] = this.#type(u, where);
1608
- if (head !== "axes" || typeof name !== "string" || rest.length > 0) return bad(where, `the type "${typeName(u.type)}" is not an axis`);
2812
+ const name = String(this.#type(u, where)[1]);
1609
2813
  const at = into(where, "value");
2814
+ const f = u.value;
1610
2815
  switch (name) {
1611
- case "neighbors": return {
2816
+ case "list": return {
1612
2817
  t: name,
1613
- n: fields(u.value, at, ["n"])["n"]
2818
+ list: this.term(f["list"], into(at, "list"))
1614
2819
  };
1615
- case "window": {
1616
- const f = fields(u.value, at, ["from", "to"]);
1617
- return {
1618
- t: name,
1619
- from: f["from"],
1620
- to: f["to"]
1621
- };
1622
- }
1623
- case "table": return {
2820
+ case "reverse": return {
1624
2821
  t: name,
1625
- name: fields(u.value, at, ["name"])["name"]
2822
+ axis: this.#axis(f["axis"], into(at, "axis"))
1626
2823
  };
1627
- case "list": return {
2824
+ case "where": return {
1628
2825
  t: name,
1629
- list: this.term(fields(u.value, at, ["list"])["list"], into(at, "list"))
2826
+ axis: this.#axis(f["axis"], into(at, "axis")),
2827
+ test: this.term(f["test"], into(at, "test"))
1630
2828
  };
1631
- case "reverse": return {
2829
+ default: return {
1632
2830
  t: name,
1633
- axis: this.#axis(fields(u.value, at, ["axis"])["axis"], into(at, "axis"))
2831
+ ...f
1634
2832
  };
1635
- case "where": {
1636
- const f = fields(u.value, at, ["axis", "test"]);
1637
- return {
1638
- t: name,
1639
- axis: this.#axis(f["axis"], into(at, "axis")),
1640
- test: this.term(f["test"], into(at, "test"))
1641
- };
1642
- }
1643
- default:
1644
- if (!PLAIN_AXES.has(name)) return bad(where, `Vex has no axis "${name}"`);
1645
- fields(u.value, at, []);
1646
- return { t: name };
1647
2833
  }
1648
2834
  }
1649
2835
  };
1650
- /**
1651
- * This function reads the value of a construct: a record with each necessary field, and no field outside the necessary
1652
- * and the optional fields. Thus a wrong name of a field gives an error, and the round trip keeps each field.
1653
- */
1654
- function fields(u, where, required, optional = []) {
1655
- if (!isRecord(u)) return bad(where, "the value is not a record");
1656
- for (const name of required) if (!Object.hasOwn(u, name)) bad(where, `the value has no field "${name}"`);
1657
- for (const name of Object.keys(u)) if (!required.includes(name) && !optional.includes(name)) bad(into(where, name), `the field "${name}" is not a field of this term`);
1658
- return u;
1659
- }
1660
2836
  //#endregion
1661
2837
  //#region src/evaluate.ts
1662
2838
  /** The names of the special forms. Their arguments are not evaluated before the call. */
@@ -1758,6 +2934,7 @@ function compile(source, opts = {}) {
1758
2934
  }
1759
2935
  const CACHE = /* @__PURE__ */ new WeakMap();
1760
2936
  function compiled(expr, opts) {
2937
+ if (typeof expr !== "object" || expr === null) return compile(expr, opts);
1761
2938
  const hit = CACHE.get(expr);
1762
2939
  if (hit !== void 0 && hit.domains === opts.domains && hit.fns === opts.fns && hit.extensions === opts.extensions) return hit.program;
1763
2940
  const program = compile(expr, opts);
@@ -1783,6 +2960,8 @@ var Compiler = class {
1783
2960
  #domains;
1784
2961
  #fns;
1785
2962
  #extensions;
2963
+ /** The index of the keys of each list that `get` read (LIST.GET). A list does not change, so its index stays right. */
2964
+ #keyIndex = /* @__PURE__ */ new WeakMap();
1786
2965
  constructor(opts) {
1787
2966
  this.#domains = opts.domains ?? [];
1788
2967
  this.#fns = opts.fns;
@@ -2364,13 +3543,13 @@ var Compiler = class {
2364
3543
  return r;
2365
3544
  }
2366
3545
  #listOp(op, list, rest, f, path) {
2367
- const optsArg = op === "reduce" || op === "take" || op === "nth" ? rest[1] : rest[0];
2368
- const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
2369
- if (depth !== void 0 && !depth.ok) return fail(depth.error);
3546
+ const optsArg = WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
2370
3547
  const strict = optsArg?.strict === true;
2371
- const firstError = list.items.find((it) => !it.result.ok)?.result;
2372
- if (strict && firstError !== void 0 && !firstError.ok) return fail(firstError.error);
2373
- const okValues = list.items.flatMap((it) => it.result.ok ? [it.result.value] : []);
3548
+ if (op === "get") return this.#get(list, rest[0], strict, f, path);
3549
+ const good = goodItems(list, strict);
3550
+ if (!good.ok) return good;
3551
+ const okItems = good.value;
3552
+ const okValues = okItems.flatMap((it) => it.result.ok ? [it.result.value] : []);
2374
3553
  const numbers = () => {
2375
3554
  const bad = okValues.find((x) => typeof x !== "number");
2376
3555
  return bad === void 0 ? ok(okValues) : this.#err("kind-mismatch", `"${op}" needs numbers, but an item is a ${describeType(bad)}`, f, path, { op });
@@ -2384,13 +3563,26 @@ var Compiler = class {
2384
3563
  const n = rest[0];
2385
3564
  return Number.isSafeInteger(n) && n >= 0 ? ok(n) : this.#err("kind-mismatch", `"${op}" needs a whole number from 0, not ${describeType(n)}`, f, path, { op });
2386
3565
  };
2387
- const okItems = list.items.filter((it) => it.result.ok);
3566
+ const other = () => isVexList(rest[0]) ? goodItems(rest[0], strict) : this.#err("kind-mismatch", `"${op}" needs a list as its second argument, not a ${describeType(rest[0])}`, f, path, { op });
2388
3567
  switch (op) {
2389
3568
  case "sortBy": return this.#sortBy(okItems, okValues, f, path);
2390
- case "take": {
3569
+ case "take":
3570
+ case "drop": {
2391
3571
  const n = whole();
2392
- return n.ok ? ok(vexList(okItems.slice(0, n.value))) : n;
3572
+ if (!n.ok) return n;
3573
+ return ok(vexList(op === "take" ? okItems.slice(0, n.value) : okItems.slice(n.value)));
3574
+ }
3575
+ case "append": {
3576
+ const more = other();
3577
+ return more.ok ? ok(vexList([...okItems, ...more.value])) : more;
2393
3578
  }
3579
+ case "without": {
3580
+ const more = other();
3581
+ if (!more.ok) return more;
3582
+ const gone = new Set(more.value.map((it) => it.key));
3583
+ return ok(vexList(okItems.filter((it) => !gone.has(it.key))));
3584
+ }
3585
+ case "flat": return this.#flat(okValues, strict, f, path);
2394
3586
  case "nth": {
2395
3587
  const i = whole();
2396
3588
  if (!i.ok) return i;
@@ -2398,7 +3590,7 @@ var Compiler = class {
2398
3590
  }
2399
3591
  case "count": return ok(okValues.length);
2400
3592
  case "values": return ok(Object.freeze([...okValues]));
2401
- case "keys": return ok(Object.freeze(list.items.filter((it) => it.result.ok).map((it) => it.key)));
3593
+ case "keys": return ok(Object.freeze(okItems.map((it) => it.key)));
2402
3594
  case "errors": return ok(Object.freeze(list.items.flatMap((it) => it.result.ok ? [] : [it.result.error])));
2403
3595
  case "first": return okValues.length > 0 ? ok(okValues[0]) : empty();
2404
3596
  case "sum": {
@@ -2430,6 +3622,35 @@ var Compiler = class {
2430
3622
  }
2431
3623
  }
2432
3624
  /**
3625
+ * This method gives the value of the first item with a key (LIST.GET). LIST.LENIENT applies, so an error item is not
3626
+ * an item of the key. The program keeps the index of each list, so a step that reads each key of a list reads it once.
3627
+ */
3628
+ #get(list, key, strict, f, path) {
3629
+ let index = this.#keyIndex.get(list);
3630
+ if (index === void 0) {
3631
+ index = keyIndexOf(list);
3632
+ this.#keyIndex.set(list, index);
3633
+ }
3634
+ const stop = index.depth ?? (strict ? index.first : void 0);
3635
+ if (stop !== void 0) return fail(stop);
3636
+ if (typeof key !== "string") return this.#err("kind-mismatch", `"get" needs a text key, not a ${describeType(key)}`, f, path, { op: "get" });
3637
+ return index.values.has(key) ? ok(index.values.get(key)) : this.#err("missing-field", `the list has no item with the key ${JSON.stringify(key)}`, f, path, { op: "get" });
3638
+ }
3639
+ /**
3640
+ * This method joins the lists that are the values of the items of a list, in order (LIST.FLAT). Each list follows the
3641
+ * rules of LIST.BUILD. A value that is not a list gives `#VALUE!`.
3642
+ */
3643
+ #flat(values, strict, f, path) {
3644
+ const out = [];
3645
+ for (const inner of values) {
3646
+ if (!isVexList(inner)) return this.#err("kind-mismatch", `"flat" needs a list as the value of each item, but an item is a ${describeType(inner)}`, f, path, { op: "flat" });
3647
+ const good = goodItems(inner, strict);
3648
+ if (!good.ok) return good;
3649
+ out.push(...good.value);
3650
+ }
3651
+ return ok(vexList(out));
3652
+ }
3653
+ /**
2433
3654
  * This method sorts the items of a list by their values, from the smallest (LIST.SORT). The sort is stable. The values
2434
3655
  * are all numbers without NaN, or all texts. Texts compare by their UTF-16 code units.
2435
3656
  */
@@ -2474,6 +3695,44 @@ var Compiler = class {
2474
3695
  return ok(acc);
2475
3696
  }
2476
3697
  };
3698
+ /** The list ops with a second argument before their options: a count, a position, an op name or a list. */
3699
+ const WITH_ARGUMENT = /* @__PURE__ */ new Set([
3700
+ "reduce",
3701
+ "take",
3702
+ "nth",
3703
+ "drop",
3704
+ "append",
3705
+ "without",
3706
+ "get"
3707
+ ]);
3708
+ /**
3709
+ * This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
3710
+ * error comes first (EVAL.DEPTH). With `strict`, the first error item is the result.
3711
+ */
3712
+ function goodItems(list, strict) {
3713
+ const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
3714
+ if (depth !== void 0 && !depth.ok) return fail(depth.error);
3715
+ const firstError = list.items.find((it) => !it.result.ok)?.result;
3716
+ if (strict && firstError !== void 0 && !firstError.ok) return fail(firstError.error);
3717
+ return ok(list.items.filter((it) => it.result.ok));
3718
+ }
3719
+ /** This function makes the index of the keys of a list. An error item is not an item of its key (LIST.LENIENT). */
3720
+ function keyIndexOf(list) {
3721
+ const values = /* @__PURE__ */ new Map();
3722
+ let first;
3723
+ let depth;
3724
+ for (const it of list.items) if (it.result.ok) {
3725
+ if (!values.has(it.key)) values.set(it.key, it.result.value);
3726
+ } else {
3727
+ first ??= it.result.error;
3728
+ if (isDepthError(it.result.error)) depth ??= it.result.error;
3729
+ }
3730
+ return {
3731
+ values,
3732
+ first,
3733
+ depth
3734
+ };
3735
+ }
2477
3736
  const FORBIDDEN_FIELDS = /* @__PURE__ */ new Set([
2478
3737
  "__proto__",
2479
3738
  "constructor",
@@ -2577,90 +3836,168 @@ function formatTrace(trace, domains = []) {
2577
3836
  const sizeOf = (e) => 1 + children(e).reduce((s, c) => s + sizeOf(c), 0);
2578
3837
  //#endregion
2579
3838
  //#region src/deps.ts
2580
- /** This function gives the functions of a scope without some names: a parameter or a binding hides a function. */
2581
- const without = (fns, names) => new Map([...fns].filter(([n]) => !names.includes(n)));
2582
3839
  /**
2583
- * This function gives the functions that each child of a node sees. The names of a loop hide the functions with those
2584
- * names in its steps, its test of until and its result. The values of init, the tests of where and an address see the
2585
- * functions outside.
3840
+ * The static reads of a program (DEPS.READS). The static kit of coeval finds the references of the document of the
3841
+ * program, by the contracts of Vex (`refsOf`). Vex adds only what is its own: the axes around a read, and the reads of
3842
+ * a function at each of its calls (FN.CALL).
2586
3843
  */
2587
- function childFns(x, fns, count) {
2588
- if (x.tag !== "fold" && x.tag !== "iterate") return () => fns;
2589
- const hidden = without(fns, Object.keys(x.init));
2590
- const first = Object.keys(x.init).length;
2591
- const steps = first + Object.keys(x.step).length;
2592
- return (i) => i >= first && (i < steps || i === count - 1 || x.tag === "iterate") ? hidden : fns;
3844
+ const ROOT = {
3845
+ axes: void 0,
3846
+ axis: void 0,
3847
+ fn: void 0,
3848
+ calls: void 0
3849
+ };
3850
+ /** This function gives the items of a chain until the chain `end`, from the outside to the inside. */
3851
+ function itemsUntil(chain, end) {
3852
+ const out = [];
3853
+ for (let c = chain; c !== void 0 && c !== end; c = c.up) out.push(c.item);
3854
+ return out.toReversed();
2593
3855
  }
3856
+ /** This function gives the kind of a visit, as its keys joined with dots, for example `each` or `axes.where`. */
3857
+ const kindOf$1 = (v) => (v.typePath ?? []).join(".");
2594
3858
  /**
2595
- * This function gives the static reads of an expression. A host can use them to recompute a program only
2596
- * when a field that it reads changes. A computed move reads a key that only a run knows. Its address keeps the
2597
- * expression, and the reads of that expression are in the list too (NAV.COMPUTED).
3859
+ * This function gives the static reads of an expression. A host can use them to recompute a program only when a field
3860
+ * that it reads changes. A computed move reads a key that only a run knows. Its address keeps the expression, and the
3861
+ * reads of that expression are in the list too (DEPS.COMPUTED). The kernel walks the document with a stack, so an
3862
+ * expression of any depth works (EVAL.NESTING).
2598
3863
  */
2599
3864
  function deps(e) {
2600
- const out = [];
2601
- const todo = [{
2602
- x: e,
2603
- axes: [],
2604
- axisAt: [],
2605
- fns: /* @__PURE__ */ new Map()
2606
- }];
2607
- for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
2608
- const { x } = item;
2609
- if (x.tag === "ref") out.push({
2610
- at: x.at ?? [],
2611
- path: x.path,
2612
- axes: item.axes,
2613
- axisAt: item.axisAt
2614
- });
2615
- if (x.tag === "let") {
2616
- const names = Object.keys(x.bind);
2617
- const inner = new Map(without(item.fns, names));
2618
- for (const [name, b] of Object.entries(x.bind)) if (b.tag === "fn") inner.set(name, {
2619
- fn: b,
2620
- fns: item.fns
2621
- });
2622
- todo.push({
2623
- ...item,
2624
- x: x.body,
2625
- fns: inner
2626
- });
2627
- for (const b of Object.values(x.bind).toReversed()) if (b.tag !== "fn") todo.push({
2628
- ...item,
2629
- x: b
2630
- });
2631
- continue;
3865
+ const nodes = /* @__PURE__ */ new Map();
3866
+ const doc = writeDocument(e, {
3867
+ domains: [],
3868
+ literals: "host",
3869
+ order: "reads",
3870
+ nodes
3871
+ });
3872
+ const uses = refsOf(VEX_WORLD, doc);
3873
+ const memo = /* @__PURE__ */ new WeakMap();
3874
+ const functions = /* @__PURE__ */ new WeakMap();
3875
+ const fnVisits = /* @__PURE__ */ new Map();
3876
+ /** This function gives the function of a call: the visit of the binding of a let, or `undefined` (FN.CALL). */
3877
+ const functionOf = (call) => {
3878
+ const known = functions.get(call);
3879
+ if (known !== void 0) return known ?? void 0;
3880
+ const name = call.doc.value.fn.value[1];
3881
+ let found;
3882
+ search: for (let child = call, around = call.parent; around !== void 0; child = around, around = around.parent) for (const rule of around.kind?.scope ?? []) {
3883
+ if (!rule.in.some((pattern) => pathMatches(child.slot, pattern))) continue;
3884
+ const source = rule.names;
3885
+ const at = (source.keysAt ?? source.listAt ?? []).reduce((x, k) => x[String(k)], around.doc.value);
3886
+ if (!(source.keysAt !== void 0 ? Object.keys(at) : at).includes(name)) continue;
3887
+ found = fnVisits.get(at[name]);
3888
+ break search;
2632
3889
  }
2633
- if (x.tag === "call") {
2634
- const bound = item.fns.get(x.fn);
2635
- if (bound !== void 0) todo.push({
2636
- ...item,
2637
- x: bound.fn.body,
2638
- fns: without(bound.fns, bound.fn.params)
2639
- });
2640
- for (const a of x.args.toReversed()) todo.push({
2641
- ...item,
2642
- x: a
2643
- });
2644
- continue;
3890
+ functions.set(call, found ?? null);
3891
+ return found;
3892
+ };
3893
+ /** This function gives the context of a child from the context of its parent. */
3894
+ const step = (outer, parent, child) => {
3895
+ const kind = kindOf$1(parent);
3896
+ const head = child.slot[0];
3897
+ let { axes, fn, calls } = outer;
3898
+ let axis;
3899
+ if (outer.axis !== void 0) {
3900
+ if (head === "test") axes = {
3901
+ item: outer.axis,
3902
+ up: axes
3903
+ };
3904
+ else if (head === "axis") axis = outer.axis;
3905
+ } else if (kind === "each" || kind === "fold") {
3906
+ const node = nodes.get(parent.doc);
3907
+ const around = {
3908
+ t: node.axis.t,
3909
+ at: node.at ?? []
3910
+ };
3911
+ if (head === "body" || head === "step") axes = {
3912
+ item: around,
3913
+ up: axes
3914
+ };
3915
+ else if (head === "axis") axis = around;
2645
3916
  }
2646
- const all = children(x);
2647
- const fnsOf = childFns(x, item.fns, all.length);
2648
- const axial = x.tag === "each" || x.tag === "fold";
2649
- const first = x.tag === "fold" ? Object.keys(x.init).length : 0;
2650
- const last = axial ? all.length - addrExprs(x.at).length - (x.tag === "fold" ? 1 : 0) : 0;
2651
- const listAt = axial && listOf(x.axis) !== void 0 ? x.tag === "fold" ? first + Object.keys(x.step).length : 1 : -1;
2652
- const axes = axial ? [...item.axes, x.axis.t] : item.axes;
2653
- const axisAt = axial ? [...item.axisAt, x.at ?? []] : item.axisAt;
2654
- for (let i = all.length - 1; i >= 0; i--) {
2655
- const inside = i >= first && i < last && i !== listAt;
2656
- todo.push({
2657
- x: all[i],
2658
- axes: inside ? axes : item.axes,
2659
- axisAt: inside ? axisAt : item.axisAt,
2660
- fns: fnsOf(i)
2661
- });
3917
+ if (kind === "fn") {
3918
+ fn = parent;
3919
+ fnVisits.set(parent.doc, parent);
3920
+ }
3921
+ if (kind === "call") calls = {
3922
+ item: parent,
3923
+ up: calls
3924
+ };
3925
+ return {
3926
+ axes,
3927
+ axis,
3928
+ fn,
3929
+ calls
3930
+ };
3931
+ };
3932
+ /**
3933
+ * This function gives the context of a visit. It walks up to a known context with a loop, not with recursion. The
3934
+ * context of no visit is the context of the root.
3935
+ */
3936
+ const contextOf = (v) => {
3937
+ const todo = [];
3938
+ let x = v;
3939
+ while (x !== void 0 && !memo.has(x)) {
3940
+ todo.push(x);
3941
+ x = x.parent;
2662
3942
  }
3943
+ let ctx = x === void 0 ? ROOT : memo.get(x);
3944
+ for (let i = todo.length - 1; i >= 0; i--) {
3945
+ const child = todo[i];
3946
+ ctx = child.parent === void 0 ? ROOT : step(ctx, child.parent, child);
3947
+ memo.set(child, ctx);
3948
+ }
3949
+ return ctx;
3950
+ };
3951
+ const groups = /* @__PURE__ */ new Map();
3952
+ for (const use of uses) {
3953
+ const fn = contextOf(use.visit).fn;
3954
+ const group = groups.get(fn) ?? [];
3955
+ group.push(use);
3956
+ groups.set(fn, group);
2663
3957
  }
3958
+ const out = [];
3959
+ /** This function gives the reads of the references of a function at a call, inside the axes of the call. */
3960
+ const emit = (group, base, outside) => {
3961
+ const baseAxes = contextOf(base).axes;
3962
+ const inside = (v) => [...outside, ...itemsUntil(contextOf(v).axes, baseAxes)];
3963
+ const pending = [];
3964
+ const inCall = (v, call) => {
3965
+ for (let c = contextOf(v).calls; c !== void 0 && c.item.depth >= call.depth; c = c.up) if (c.item === call) return true;
3966
+ return false;
3967
+ };
3968
+ const flush = (until) => {
3969
+ for (;;) {
3970
+ const top = pending.at(-1);
3971
+ if (top === void 0 || inCall(until, top.call)) return;
3972
+ pending.pop();
3973
+ emit(groups.get(top.fn) ?? [], top.fn, top.axes);
3974
+ }
3975
+ };
3976
+ for (const use of group) {
3977
+ flush(use.visit);
3978
+ if (use.root === "self" && !use.address) {
3979
+ const node = nodes.get(use.visit.doc);
3980
+ const axes = inside(use.visit);
3981
+ out.push({
3982
+ at: node.at ?? [],
3983
+ path: node.path,
3984
+ axes: axes.map((a) => a.t),
3985
+ axisAt: axes.map((a) => a.at)
3986
+ });
3987
+ }
3988
+ const call = use.visit.parent;
3989
+ if (call !== void 0 && kindOf$1(call) === "call" && use.visit.slot[0] === "fn") {
3990
+ const fn = functionOf(call);
3991
+ if (fn !== void 0) pending.push({
3992
+ call,
3993
+ fn,
3994
+ axes: inside(call)
3995
+ });
3996
+ }
3997
+ }
3998
+ flush();
3999
+ };
4000
+ emit(groups.get(void 0) ?? [], void 0, []);
2664
4001
  return out;
2665
4002
  }
2666
4003
  //#endregion
@@ -2807,6 +4144,96 @@ function parse(text, domains = []) {
2807
4144
  }
2808
4145
  }
2809
4146
  //#endregion
4147
+ //#region src/plan.ts
4148
+ /**
4149
+ * The reference tier of Vex: a program as a plan of the kernel of coeval (decision D13 of coeval). The kernel evaluates
4150
+ * the document of the program with the machine of `kernel.ts`. The closure compiler and the loop compiler give its
4151
+ * results (EVAL.REFERENCE), and the test kit compares them on random programs.
4152
+ */
4153
+ /** This function gives the context of the kernel at an origin: the position of the origin, and the names of the caller. */
4154
+ const contextOf = ({ space, origin, vars, tables }) => context({
4155
+ self: vexSelf(space, origin, tables),
4156
+ names: vars ?? {}
4157
+ });
4158
+ /** This function gives the result of the kernel for a result of Vex. */
4159
+ const toOutcome = (r) => r.ok ? {
4160
+ ok: true,
4161
+ value: r.value
4162
+ } : {
4163
+ ok: false,
4164
+ error: toKernelError(r.error)
4165
+ };
4166
+ /**
4167
+ * This function gives the plan of a program in the kernel (EVAL.REFERENCE). A document stays as it is, after the check
4168
+ * of `fromDocument`. An expression gets its document: a literal has its JSON form, or the value of the host when it has
4169
+ * no JSON form. A program that is not valid gives the error of `compile` at each run (EVAL.SHAPE, EVAL.NESTING).
4170
+ */
4171
+ function kernelPlan(source, opts = {}) {
4172
+ const domains = opts.domains ?? [];
4173
+ let doc;
4174
+ let bad;
4175
+ if (isDocument(source)) {
4176
+ const read = fromDocument(source, domains);
4177
+ if (read.ok) doc = source;
4178
+ else bad = read.error;
4179
+ } else {
4180
+ const shape = shapeError(source);
4181
+ const nesting = shape === void 0 ? nestingOf(source) : 0;
4182
+ const reason = shape ?? (nesting > 500 ? `the expression is nested ${String(nesting)} levels deep, and the limit is ${String(500)}` : void 0);
4183
+ if (reason === void 0) doc = writeDocument(source, {
4184
+ domains,
4185
+ literals: "host",
4186
+ order: "document"
4187
+ });
4188
+ else bad = vexError("bad-expression", reason);
4189
+ }
4190
+ const machine = vexMachine(opts);
4191
+ const plan = prepare(machine, doc);
4192
+ const early = ({ space, origin }) => {
4193
+ if (!space.has(origin)) return {
4194
+ ok: false,
4195
+ error: toKernelError(vexError("unknown-key", `the space has no key "${origin}"`, {
4196
+ origin,
4197
+ focus: origin
4198
+ }))
4199
+ };
4200
+ return bad === void 0 ? void 0 : {
4201
+ ok: false,
4202
+ error: toKernelError(bad)
4203
+ };
4204
+ };
4205
+ const evaluate = (r) => early(r) ?? plan.evaluate(contextOf(r));
4206
+ const reference$1 = (r) => early(r) ?? reference(machine, doc, contextOf(r), { definitions: vexDefinitions(opts) });
4207
+ const agree$1 = (r, other) => {
4208
+ const tier = other === void 0 ? {} : { other: () => toOutcome(other()) };
4209
+ const first = early(r);
4210
+ if (first === void 0) return agree(machine, doc, contextOf(r), {
4211
+ definitions: vexDefinitions(opts),
4212
+ equal: sameVex,
4213
+ ...tier
4214
+ });
4215
+ const second = tier.other?.() ?? first;
4216
+ return !second.ok && second.error.code === first.error.code ? {
4217
+ ok: true,
4218
+ result: first,
4219
+ effects: []
4220
+ } : {
4221
+ ok: false,
4222
+ tier: "other",
4223
+ plan: first,
4224
+ other: second,
4225
+ reason: "The plan does not evaluate the program, and the tier gives another result."
4226
+ };
4227
+ };
4228
+ return {
4229
+ doc,
4230
+ evaluate,
4231
+ reference: reference$1,
4232
+ agree: agree$1,
4233
+ run: (r) => toVexResult(evaluate(r))
4234
+ };
4235
+ }
4236
+ //#endregion
2810
4237
  //#region src/traversal.ts
2811
4238
  /** Standard monoids. */
2812
4239
  const monoids = {
@@ -3282,7 +4709,7 @@ var SheetRun = class SheetRun {
3282
4709
  */
3283
4710
  #compiled(t, column, program) {
3284
4711
  const compile = this.#compile;
3285
- if (compile === void 0 || t.columns.get(column) !== program) return void 0;
4712
+ if (compile === void 0 || t.columns.get(column) !== program || typeof program !== "object" || program === null) return void 0;
3286
4713
  const { domains, fns, extensions } = this.#compileOptions;
3287
4714
  const hit = PROGRAMS.get(program);
3288
4715
  if (hit !== void 0 && hit.compile === compile && hit.domains === domains && hit.fns === fns && hit.extensions === extensions) return hit.program;
@@ -3426,6 +4853,11 @@ const runtimeOptions = (options) => ({
3426
4853
  const kindOf = (u) => u?.kind;
3427
4854
  const isArg = (u) => kindOf(u) === "vex.arg";
3428
4855
  const isChainLike = (u) => kindOf(u) === "vex.chain" || kindOf(u) === "vex.list-chain";
4856
+ /** This function gives the expression of the list of `append` and `without`. The list is a chain, not a literal. */
4857
+ function listProgram(op, other) {
4858
+ if (!isChainLike(other)) throw new TypeError(`${op} needs a list chain`);
4859
+ return other.program;
4860
+ }
3429
4861
  /** This function turns a builder argument into an expression. A bare string is a field reference at `addr`. */
3430
4862
  function toExpr(a, addr) {
3431
4863
  if (typeof a === "string") return ref(toPath(a), addr);
@@ -3628,12 +5060,13 @@ var ChainImpl = class ChainImpl {
3628
5060
  const name = `${n}$${depth}`;
3629
5061
  unique.set(n, name);
3630
5062
  first[name] = toExpr(a, this.#s.addr);
3631
- vars[n] = new ChainImpl({
5063
+ const s = {
3632
5064
  ...this.#s,
3633
5065
  expr: v(name),
3634
5066
  addr: [],
3635
5067
  depth: depth + 1
3636
- });
5068
+ };
5069
+ vars[n] = kindOf(a) === "vex.list-chain" ? new ListChainImpl(s) : new ChainImpl(s);
3637
5070
  }
3638
5071
  return {
3639
5072
  unique,
@@ -3645,10 +5078,11 @@ var ChainImpl = class ChainImpl {
3645
5078
  const { unique, first, vars } = this.loopNames(init);
3646
5079
  const next = stepExprs(step(vars), unique, this.#s.addr);
3647
5080
  const until = opts?.until === void 0 ? void 0 : toExpr(opts.until(vars), this.#s.addr);
3648
- return new ChainImpl({
5081
+ const r = result(vars);
5082
+ return chainOf({
3649
5083
  ...this.#s,
3650
- expr: iterate(limit, first, next, toExpr(result(vars), this.#s.addr), until)
3651
- });
5084
+ expr: iterate(limit, first, next, toExpr(r, this.#s.addr), until)
5085
+ }, r);
3652
5086
  }
3653
5087
  #axis(a, body, opts) {
3654
5088
  const { name, start } = this.#bound();
@@ -3718,6 +5152,8 @@ var ChainImpl = class ChainImpl {
3718
5152
  return this.#axis({ t: "reachable" }, body, opts);
3719
5153
  }
3720
5154
  };
5155
+ /** This function gives the chain of a loop: a list chain when its result is a list chain (BUILD.LIST.LOOP). */
5156
+ const chainOf = (s, result) => kindOf(result) === "vex.list-chain" ? new ListChainImpl(s) : new ChainImpl(s);
3721
5157
  /** This function gives the options of an evaluation of a chain or a list chain at the origin `k`. */
3722
5158
  function evalOptions(s, k) {
3723
5159
  const { env } = s;
@@ -3752,11 +5188,12 @@ var ListChainImpl = class ListChainImpl {
3752
5188
  addr: []
3753
5189
  });
3754
5190
  const next = stepExprs(step(names.vars, item), names.unique, []);
3755
- const folded = fold(loop.axis, names.first, next, toExpr(result(names.vars), this.#s.addr), loop.at);
3756
- return new ChainImpl({
5191
+ const r = result(names.vars);
5192
+ const folded = fold(loop.axis, names.first, next, toExpr(r, this.#s.addr), loop.at);
5193
+ return chainOf({
3757
5194
  ...this.#s,
3758
5195
  expr: e.tag === "let" ? let_(e.bind, folded) : folded
3759
- });
5196
+ }, r);
3760
5197
  }
3761
5198
  #op(op, extra, opts) {
3762
5199
  const options = {
@@ -3823,6 +5260,21 @@ var ListChainImpl = class ListChainImpl {
3823
5260
  nth(i, opts) {
3824
5261
  return this.#op("nth", [lit(i)], opts);
3825
5262
  }
5263
+ get(k, opts) {
5264
+ return this.#op("get", [typeof k === "string" ? lit(k) : k.program], opts);
5265
+ }
5266
+ drop(n, opts) {
5267
+ return this.#list("drop", [lit(n)], opts);
5268
+ }
5269
+ append(other, opts) {
5270
+ return this.#list("append", [listProgram("append", other)], opts);
5271
+ }
5272
+ without(other, opts) {
5273
+ return this.#list("without", [listProgram("without", other)], opts);
5274
+ }
5275
+ flat(opts) {
5276
+ return this.#list("flat", [], opts);
5277
+ }
3826
5278
  each(body, opts) {
3827
5279
  const start = new ChainImpl({
3828
5280
  ...this.#s,
@@ -3910,6 +5362,17 @@ var RootImpl = class {
3910
5362
  for (const [n, a] of Object.entries(fields)) out[n] = toExpr(a, []);
3911
5363
  return argToken(rec(out));
3912
5364
  }
5365
+ list(items = []) {
5366
+ return new ListChainImpl({
5367
+ env: this.#env,
5368
+ expr: lit(vexList(items.map(([key, value]) => ({
5369
+ key,
5370
+ result: ok(value)
5371
+ })))),
5372
+ addr: [],
5373
+ depth: 0
5374
+ });
5375
+ }
3913
5376
  };
3914
5377
  var SheetRootImpl = class extends RootImpl {
3915
5378
  cell(column, at) {
@@ -3995,6 +5458,6 @@ function vex(...domains) {
3995
5458
  };
3996
5459
  }
3997
5460
  //#endregion
3998
- export { CELL_KIND, LIST_OPS, MAX_ITERATIONS, MAX_NESTING, SPECIAL_FORMS, SheetRun, addrExprs, app, applyMove, axes, axisExprs, axisTargets, call, cell, chainResult, children, codeOf, compile, defineDomain, deps, describeType, domainOf, each, evaluate, explain, ext, fail, findMethod, fixAddr, fn, fold, formatError, formatTrace, fromDocument, getOr, index, isAxis, isDepthError, isDocument, isExpr, isFieldName, isFixedAddr, isListOp, isMove, isNone, isOpName, isSome, isStackOverflow, isVexList, iterate, key, labelOf, let_, liftsAt, listOf, lit, mapResult, matchesKind, monoids, moveExpr, nestingOf, none, offset, ok, origin, other, parent, parse, previewValue, rec, ref, resolveAddr, resolveOp, safeIs, serialize, shapeError, sizeOf, some, space, toDocument, toOptional, toPath, traversal, v, vex, vexError, vexList };
5461
+ export { CELL_KIND, LIST_OPS, MAX_DOCUMENT_DEPTH, MAX_ITERATIONS, MAX_NESTING, SPECIAL_FORMS, SheetRun, TERM_KINDS, VEX_WORLD, addrExprs, app, applyMove, axes, axisExprs, axisTargets, call, cell, chainResult, children, codeOf, compile, defineDomain, deps, describeType, domainOf, each, evaluate, explain, ext, fail, findMethod, fixAddr, fn, fold, formatError, formatTrace, fromDocument, getOr, index, isAxis, isDepthError, isDocument, isExpr, isFieldName, isFixedAddr, isListOp, isMove, isNone, isOpName, isSome, isStackOverflow, isVexList, iterate, kernelPlan, key, labelOf, let_, liftsAt, listOf, lit, mapResult, matchesKind, monoids, moveExpr, nestingOf, none, offset, ok, origin, other, parent, parse, previewValue, rec, ref, resolveAddr, resolveOp, safeIs, serialize, shapeError, sizeOf, some, space, toDocument, toKernelError, toOptional, toPath, toVexError, toVexResult, traversal, v, vex, vexChecker, vexDefinitions, vexError, vexList, vexMachine, vexSelf };
3999
5462
 
4000
5463
  //# sourceMappingURL=index.js.map