@mark1russell7/vex 0.2.0 → 0.4.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
@@ -113,12 +113,22 @@ const rec = (fields) => ({
113
113
  tag: "rec",
114
114
  fields
115
115
  });
116
- /** This function evaluates `body` once for each target of `axis`. The result is a list. */
117
- const each = (axis, body) => ({
118
- tag: "each",
119
- axis,
120
- body
121
- });
116
+ /**
117
+ * This function evaluates `body` once for each target of `axis`. The result is a list. With `at`, the axis finds its
118
+ * targets from the key of that address, not from the focus.
119
+ */
120
+ function each(axis, body, at) {
121
+ return at === void 0 || at.length === 0 ? {
122
+ tag: "each",
123
+ axis,
124
+ body
125
+ } : {
126
+ tag: "each",
127
+ axis,
128
+ body,
129
+ at
130
+ };
131
+ }
122
132
  /** This function makes an expression of an extension kind. */
123
133
  const ext = (kind, data) => ({
124
134
  tag: "ext",
@@ -181,8 +191,8 @@ function isMove(u) {
181
191
  if (!isObject(u)) return false;
182
192
  switch (u["t"]) {
183
193
  case "key": return typeof u["key"] === "string";
184
- case "index": return typeof u["i"] === "number" && Number.isInteger(u["i"]);
185
- case "offset": return Array.isArray(u["d"]) && u["d"].every((n) => typeof n === "number" && Number.isInteger(n));
194
+ case "index": return Number.isInteger(u["i"]);
195
+ case "offset": return Array.isArray(u["d"]) && u["d"].every((n) => Number.isInteger(n));
186
196
  case "other":
187
197
  case "origin":
188
198
  case "parent": return true;
@@ -216,7 +226,7 @@ function isExpr(u) {
216
226
  case "let": return isExprRecord(u["bind"]) && isExpr(u["body"]);
217
227
  case "var": return typeof u["name"] === "string";
218
228
  case "rec": return isExprRecord(u["fields"]);
219
- case "each": return isAxis(u["axis"]) && isExpr(u["body"]);
229
+ case "each": return isAxis(u["axis"]) && isExpr(u["body"]) && (u["at"] === void 0 || Array.isArray(u["at"]) && u["at"].every(isMove));
220
230
  case "ext": return typeof u["kind"] === "string" && "data" in u;
221
231
  default: return false;
222
232
  }
@@ -227,7 +237,7 @@ function children(e) {
227
237
  case "app": return e.args;
228
238
  case "let": return [...Object.values(e.bind), e.body];
229
239
  case "rec": return Object.values(e.fields);
230
- case "each": return e.axis.t === "where" ? [e.body, ...whereTests(e.axis)] : [e.body];
240
+ case "each": return [e.body, ...whereTests(e.axis)];
231
241
  case "lit":
232
242
  case "ref":
233
243
  case "var":
@@ -276,7 +286,7 @@ var ArraySpace = class {
276
286
  return this.has(k) ? [Number(k)] : void 0;
277
287
  }
278
288
  keyAt(coords) {
279
- const k = coords.join(",");
289
+ const k = String(coords[0]);
280
290
  return coords.length === 1 && this.has(k) ? k : void 0;
281
291
  }
282
292
  };
@@ -306,7 +316,7 @@ var GridSpace = class {
306
316
  }
307
317
  keyAt(coords) {
308
318
  const k = coords.join(",");
309
- return coords.length === 2 && this.has(k) ? k : void 0;
319
+ return this.has(k) ? k : void 0;
310
320
  }
311
321
  };
312
322
  var TreeSpace = class {
@@ -390,7 +400,7 @@ function applyMove(s, at, m) {
390
400
  case "key": return s.has(m.key) ? ok(m.key) : refError("unknown-key", `the space has no key "${m.key}"`);
391
401
  case "index": {
392
402
  const k = s.keys[m.i];
393
- return m.i >= 0 && k !== void 0 ? ok(k) : refError("out-of-bounds", `the space has no key at index ${m.i}`);
403
+ return k !== void 0 ? ok(k) : refError("out-of-bounds", `the space has no key at index ${m.i}`);
394
404
  }
395
405
  case "other": {
396
406
  if (s.keys.length !== 2) return refError("not-a-pair", `"other" needs a space with 2 keys, but this space has ${s.keys.length}`);
@@ -399,6 +409,15 @@ function applyMove(s, at, m) {
399
409
  return ok(at.focus === a ? b ?? at.focus : a ?? at.focus);
400
410
  }
401
411
  case "offset": {
412
+ const parentOf = s.parentOf?.bind(s);
413
+ const childrenOf = s.childrenOf?.bind(s);
414
+ if (parentOf !== void 0 && childrenOf !== void 0 && m.d.length === 1) {
415
+ const p = parentOf(at.focus);
416
+ const group = p === void 0 ? s.keys.filter((k) => parentOf(k) === void 0) : childrenOf(p);
417
+ const i = group.indexOf(at.focus);
418
+ const k = i < 0 ? void 0 : group[i + (m.d[0] ?? 0)];
419
+ return k === void 0 ? refError("out-of-bounds", `the offset [${m.d.join(",")}] from "${at.focus}" is outside its siblings`) : ok(k);
420
+ }
402
421
  const c = s.coords(at.focus);
403
422
  if (c === void 0 || c.length !== m.d.length) return refError("no-offset", `an offset of length ${m.d.length} is not valid in a ${s.kind} space`);
404
423
  /* v8 ignore next -- @preserve */
@@ -524,7 +543,7 @@ const isOpName = (name) => name.length > 0 && !FORBIDDEN.has(name);
524
543
  * It stops at `Object.prototype` and `Function.prototype`, so inherited members (for example `toString`) are not ops.
525
544
  */
526
545
  function findMethod(self, name) {
527
- if (!isOpName(name) || self === null || self === void 0) return void 0;
546
+ if (!isOpName(name)) return void 0;
528
547
  if (typeof self !== "object" && typeof self !== "function") return void 0;
529
548
  let o = self;
530
549
  while (o !== null && o !== Object.prototype && o !== Function.prototype) {
@@ -569,7 +588,7 @@ const vexList = (items) => Object.freeze({
569
588
  items: Object.freeze([...items])
570
589
  });
571
590
  /** This function tells if a value is a Vex list. */
572
- const isVexList = (u) => typeof u === "object" && u !== null && u.kind === "vex.list" && Array.isArray(u.items);
591
+ const isVexList = (u) => u?.kind === "vex.list" && Array.isArray(u.items);
573
592
  /** The names of the core list ops. They apply when the first argument is a list. */
574
593
  const LIST_OPS = /* @__PURE__ */ new Set([
575
594
  "count",
@@ -744,7 +763,8 @@ var Compiler = class {
744
763
  case "app": return isSpecialForm(e.op) ? this.#special(e.op, this.#nodes(e.args, path), info) : this.#app(e.op, this.#nodes(e.args, path), info);
745
764
  case "each": return this.#each(e, info);
746
765
  case "ext": {
747
- const handler = Object.hasOwn(this.#extensions ?? {}, e.kind) ? this.#extensions?.[e.kind] : void 0;
766
+ const extensions = this.#extensions ?? {};
767
+ const handler = Object.hasOwn(extensions, e.kind) ? extensions[e.kind] : void 0;
748
768
  const { kind, data } = e;
749
769
  if (handler === void 0) return (f, c) => this.#emit(c, info, f, this.#err("unknown-op", `no handler for the extension kind "${kind}"`, f, path));
750
770
  return (f, c) => this.#emit(c, info, f, this.#locate(this.#guard(() => handler(data, {
@@ -838,10 +858,26 @@ var Compiler = class {
838
858
  }
839
859
  #each(e, info) {
840
860
  const { path } = info;
861
+ const at = e.at ?? [];
841
862
  const targets = this.#targets(e.axis, path, { next: 1 });
842
863
  const body = this.node(e.body, [...path, 0]);
843
864
  return (f, c) => {
844
- const ts = targets(f, c);
865
+ let from = f;
866
+ if (at.length > 0) {
867
+ const where = resolveAddr(c.space, f.pos, at);
868
+ if (!where.ok) return this.#emit(c, info, f, fail({
869
+ ...where.error,
870
+ path
871
+ }));
872
+ from = {
873
+ pos: {
874
+ origin: f.pos.origin,
875
+ focus: where.value
876
+ },
877
+ env: f.env
878
+ };
879
+ }
880
+ const ts = targets(from, c);
845
881
  if (!ts.ok) return this.#emit(c, info, f, ts);
846
882
  const items = ts.value.map(({ key, test }) => {
847
883
  if (test !== void 0 && !test.ok) return {
@@ -967,7 +1003,7 @@ var Compiler = class {
967
1003
  const lift = spec.liftScalar;
968
1004
  const from = domain.fromScalar;
969
1005
  let callArgs = rest;
970
- if (lift !== void 0 && lift !== false && from !== void 0) {
1006
+ if (lift && from !== void 0) {
971
1007
  const lifted = this.#invoke(() => rest.map((a, i) => typeof a === "number" && liftsAt(lift, i) ? from(a) : a), `${domain.name}.fromScalar`, f, path);
972
1008
  if (!lifted.ok) return lifted;
973
1009
  callArgs = lifted.value;
@@ -1015,7 +1051,7 @@ var Compiler = class {
1015
1051
  }
1016
1052
  #listOp(op, list, rest, f, path) {
1017
1053
  const optsArg = op === "reduce" ? rest[1] : rest[0];
1018
- const strict = isOptions(optsArg) && optsArg.strict === true;
1054
+ const strict = optsArg?.strict === true;
1019
1055
  const firstError = list.items.find((it) => !it.result.ok)?.result;
1020
1056
  if (strict && firstError !== void 0 && !firstError.ok) return fail(firstError.error);
1021
1057
  const okValues = list.items.flatMap((it) => it.result.ok ? [it.result.value] : []);
@@ -1059,18 +1095,26 @@ var Compiler = class {
1059
1095
  if (op === "all") return ok(b.value.every((x) => x));
1060
1096
  return ok(!b.value.some((x) => x));
1061
1097
  }
1062
- case "reduce": return this.#reduce(rest[0], okValues, f, path);
1098
+ case "reduce": return this.#reduce(rest[0], okValues, f, path, optsArg);
1063
1099
  }
1064
1100
  }
1065
- /** This method folds the values with a domain op, from the left. An empty list gives the identity of the op. */
1066
- #reduce(opName, values, f, path) {
1101
+ /**
1102
+ * This method folds the values with a domain op, from the left. An empty list gives the identity of the op, if one
1103
+ * domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
1104
+ */
1105
+ #reduce(opName, values, f, path, opts) {
1067
1106
  if (typeof opName !== "string") return this.#err("kind-mismatch", `"reduce" needs an op name, but got a ${describeType(opName)}`, f, path, { op: "reduce" });
1068
1107
  if (values.length === 0) {
1069
- for (const d of this.#domains) {
1070
- const id = d.ops[opName]?.identity;
1071
- if (id !== void 0 && Object.hasOwn(d.ops, opName)) return this.#invoke(id, opName, f, path);
1108
+ const named = opts?.domain;
1109
+ const candidates = this.#domains.filter((d) => Object.hasOwn(d.ops, opName) && d.ops[opName].identity !== void 0 && (named === void 0 || d.name === named));
1110
+ if (named !== void 0 && !this.#domains.some((d) => d.name === named)) return this.#err("unknown-op", `"reduce" names the domain ${JSON.stringify(named)}, but the program has no such domain`, f, path, { op: opName });
1111
+ const [only, second] = candidates;
1112
+ if (only === void 0) return this.#err("empty", `"reduce" with "${opName}" has no values and the op has no identity`, f, path, { op: opName });
1113
+ if (second !== void 0) {
1114
+ const names = candidates.map((d) => d.name).join(", ");
1115
+ return this.#err("empty", `"reduce" with "${opName}" has no values, and more domains have an identity for it (${names}). Name one with { domain }`, f, path, { op: opName });
1072
1116
  }
1073
- return this.#err("empty", `"reduce" with "${opName}" has no values and the op has no identity`, f, path, { op: opName });
1117
+ return this.#invoke(only.ops[opName].identity, opName, f, path);
1074
1118
  }
1075
1119
  let acc = values[0];
1076
1120
  for (let i = 1; i < values.length; i++) {
@@ -1098,7 +1142,6 @@ function safeIs(d, value) {
1098
1142
  return false;
1099
1143
  }
1100
1144
  }
1101
- const isOptions = (u) => typeof u === "object" && u !== null && !Array.isArray(u) && !isVexList(u);
1102
1145
  function matchesKind(kind, value, domain) {
1103
1146
  switch (kind) {
1104
1147
  case "domain": return safeIs(domain, value);
@@ -1128,14 +1171,24 @@ function labelOf(e) {
1128
1171
  case "let": return `let ${Object.keys(e.bind).join(", ")}`;
1129
1172
  case "var": return e.name;
1130
1173
  case "rec": return `{ ${Object.keys(e.fields).join(", ")} }`;
1131
- case "each": return `each ${e.axis.t}`;
1174
+ case "each": return e.at === void 0 ? `each ${e.axis.t}` : `each ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
1132
1175
  case "ext": return e.kind;
1133
1176
  }
1134
1177
  }
1178
+ /** This function gives a short text for a move, for the label of an axis with an address. */
1179
+ function moveText(m) {
1180
+ switch (m.t) {
1181
+ case "key": return `key(${m.key})`;
1182
+ case "index": return `index(${m.i})`;
1183
+ case "offset": return `offset(${m.d.join(", ")})`;
1184
+ case "other":
1185
+ case "origin":
1186
+ case "parent": return m.t;
1187
+ }
1188
+ }
1135
1189
  /** This function gives a short text for a value. */
1136
1190
  function previewValue(u) {
1137
- if (typeof u === "string") return JSON.stringify(u);
1138
- if (typeof u === "number" || typeof u === "boolean" || u === null || u === void 0) return String(u);
1191
+ if (typeof u === "number") return String(u);
1139
1192
  if (isVexList(u)) return `list(${u.items.length})`;
1140
1193
  try {
1141
1194
  const json = JSON.stringify(u);
@@ -1178,86 +1231,198 @@ const sizeOf = (e) => 1 + children(e).reduce((s, c) => s + sizeOf(c), 0);
1178
1231
  */
1179
1232
  function deps(e) {
1180
1233
  const out = [];
1181
- const walk = (x, axes) => {
1234
+ const walk = (x, axes, axisAt) => {
1182
1235
  if (x.tag === "ref") {
1183
1236
  out.push({
1184
1237
  at: x.at ?? [],
1185
1238
  path: x.path,
1186
- axes
1239
+ axes,
1240
+ axisAt
1187
1241
  });
1188
1242
  return;
1189
1243
  }
1190
1244
  if (x.tag === "each") {
1191
1245
  const inner = [...axes, x.axis.t];
1192
- children(x).forEach((c) => walk(c, inner));
1246
+ const innerAt = [...axisAt, x.at ?? []];
1247
+ children(x).forEach((c) => walk(c, inner, innerAt));
1193
1248
  return;
1194
1249
  }
1195
- children(x).forEach((c) => walk(c, axes));
1250
+ children(x).forEach((c) => walk(c, axes, axisAt));
1196
1251
  };
1197
- walk(e, []);
1252
+ walk(e, [], []);
1198
1253
  return out;
1199
1254
  }
1200
1255
  //#endregion
1201
1256
  //#region src/json.ts
1202
- const isPlainJson = (u) => {
1203
- if (u === null || typeof u === "string" || typeof u === "boolean") return true;
1204
- if (typeof u === "number") return Number.isFinite(u);
1205
- if (Array.isArray(u)) return u.every(isPlainJson);
1206
- if (typeof u === "object") {
1207
- const proto = Object.getPrototypeOf(u);
1208
- return (proto === Object.prototype || proto === null) && Object.values(u).every(isPlainJson);
1257
+ const isRecord = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
1258
+ const isPlainRecord = (u) => {
1259
+ if (!isRecord(u)) return false;
1260
+ const proto = Object.getPrototypeOf(u);
1261
+ return proto === Object.prototype || proto === null;
1262
+ };
1263
+ /** This function gives the JSON form of a value, or the reason why the value has no JSON form. */
1264
+ function encodeValue(u, domains) {
1265
+ if (u === null || typeof u === "string" || typeof u === "boolean") return ok(u);
1266
+ if (typeof u === "number") {
1267
+ if (Object.is(u, -0)) return ok({
1268
+ $vex: "number",
1269
+ value: "-0"
1270
+ });
1271
+ return Number.isFinite(u) ? ok(u) : ok({
1272
+ $vex: "number",
1273
+ value: Number.isNaN(u) ? "NaN" : u > 0 ? "Infinity" : "-Infinity"
1274
+ });
1209
1275
  }
1210
- return false;
1276
+ if (Array.isArray(u)) {
1277
+ const out = [];
1278
+ for (const x of u) {
1279
+ const r = encodeValue(x, domains);
1280
+ if (!r.ok) return r;
1281
+ out.push(r.value);
1282
+ }
1283
+ return ok(out);
1284
+ }
1285
+ if (isPlainRecord(u)) {
1286
+ const out = {};
1287
+ for (const [k, x] of Object.entries(u)) {
1288
+ const r = encodeValue(x, domains);
1289
+ if (!r.ok) return r;
1290
+ out[k] = r.value;
1291
+ }
1292
+ return ok(Object.hasOwn(u, "$vex") ? {
1293
+ $vex: "escape",
1294
+ value: out
1295
+ } : out);
1296
+ }
1297
+ const d = domains.find((dom) => dom.encode !== void 0 && dom.is(u));
1298
+ if (d?.encode !== void 0) return ok({
1299
+ $vex: "domain",
1300
+ domain: d.name,
1301
+ value: d.encode(u)
1302
+ });
1303
+ return fail(vexError("bad-expression", "a literal value is not JSON data and no domain encodes it"));
1304
+ }
1305
+ const NUMBERS = {
1306
+ "-0": -0,
1307
+ NaN: NaN,
1308
+ Infinity: Number.POSITIVE_INFINITY,
1309
+ "-Infinity": Number.NEGATIVE_INFINITY
1211
1310
  };
1311
+ /** This function reads a value from its JSON form. */
1312
+ function decodeValue(u, domains) {
1313
+ if (Array.isArray(u)) {
1314
+ const out = [];
1315
+ for (const x of u) {
1316
+ const r = decodeValue(x, domains);
1317
+ if (!r.ok) return r;
1318
+ out.push(r.value);
1319
+ }
1320
+ return ok(out);
1321
+ }
1322
+ if (!isRecord(u)) return ok(u);
1323
+ const fields = (record) => {
1324
+ const out = {};
1325
+ for (const [k, x] of Object.entries(record)) {
1326
+ const r = decodeValue(x, domains);
1327
+ if (!r.ok) return r;
1328
+ out[k] = r.value;
1329
+ }
1330
+ return ok(out);
1331
+ };
1332
+ const kind = u["$vex"];
1333
+ if (kind === "escape" && isRecord(u["value"])) return fields(u["value"]);
1334
+ if (kind === "number" && typeof u["value"] === "string" && Object.hasOwn(NUMBERS, u["value"])) return ok(NUMBERS[u["value"]]);
1335
+ if (kind === "domain" && typeof u["domain"] === "string") {
1336
+ const name = u["domain"];
1337
+ const d = domains.find((dom) => dom.name === name);
1338
+ if (d?.decode === void 0) return fail(vexError("bad-expression", `no domain "${name}" decodes a literal`));
1339
+ return ok(d.decode(u["value"]));
1340
+ }
1341
+ return fields(u);
1342
+ }
1343
+ /** This function applies `f` to each literal value of a JSON tree of an expression. */
1344
+ function mapValues(u, f) {
1345
+ if (!isRecord(u)) return ok(u);
1346
+ const out = { ...u };
1347
+ const child = (key) => {
1348
+ const r = mapValues(u[key], f);
1349
+ if (r.ok) out[key] = r.value;
1350
+ return r.ok ? void 0 : r;
1351
+ };
1352
+ const each = (key) => {
1353
+ const list = u[key];
1354
+ if (Array.isArray(list)) {
1355
+ const items = [];
1356
+ for (const x of list) {
1357
+ const r = mapValues(x, f);
1358
+ if (!r.ok) return r;
1359
+ items.push(r.value);
1360
+ }
1361
+ out[key] = items;
1362
+ } else if (isRecord(list)) {
1363
+ const rec = {};
1364
+ for (const [k, x] of Object.entries(list)) {
1365
+ const r = mapValues(x, f);
1366
+ if (!r.ok) return r;
1367
+ rec[k] = r.value;
1368
+ }
1369
+ out[key] = rec;
1370
+ }
1371
+ };
1372
+ const axis = (a) => {
1373
+ if (!isRecord(a) || a["t"] !== "where") return ok(a);
1374
+ const inner = axis(a["axis"]);
1375
+ if (!inner.ok) return inner;
1376
+ const test = mapValues(a["test"], f);
1377
+ return test.ok ? ok({
1378
+ ...a,
1379
+ axis: inner.value,
1380
+ test: test.value
1381
+ }) : test;
1382
+ };
1383
+ switch (u["tag"]) {
1384
+ case "lit": {
1385
+ if (!Object.hasOwn(u, "value")) return ok(out);
1386
+ const r = f(u["value"]);
1387
+ if (!r.ok) return r;
1388
+ out["value"] = r.value;
1389
+ return ok(out);
1390
+ }
1391
+ case "app": return each("args") ?? ok(out);
1392
+ case "let": return each("bind") ?? child("body") ?? ok(out);
1393
+ case "rec": return each("fields") ?? ok(out);
1394
+ case "each": {
1395
+ const a = axis(u["axis"]);
1396
+ if (!a.ok) return a;
1397
+ out["axis"] = a.value;
1398
+ return child("body") ?? ok(out);
1399
+ }
1400
+ default: return ok(out);
1401
+ }
1402
+ }
1212
1403
  /**
1213
- * This function gives the JSON text of an expression. A literal that is a domain value needs a domain with
1214
- * `encode`. A literal that is not JSON data and has no such domain gives the error `#VALUE!`.
1404
+ * This function gives the JSON text of an expression. A literal value that is a domain value needs a domain with
1405
+ * `encode`. A literal value that is not JSON data and has no such domain gives the error `#VALUE!`.
1215
1406
  */
1216
1407
  function serialize(e, domains = []) {
1217
- const failure = [];
1218
- const replacer = function(k, value) {
1219
- const holder = this;
1220
- if (k !== "value" || holder === null || holder["tag"] !== "lit") return value;
1221
- if (isPlainJson(value)) return value;
1222
- const d = domains.find((dom) => dom.encode !== void 0 && dom.is(value));
1223
- if (d?.encode !== void 0) return {
1224
- $vex: "domain",
1225
- domain: d.name,
1226
- value: d.encode(value)
1227
- };
1228
- failure.push({ message: `a literal value is not JSON data and no domain encodes it` });
1229
- return null;
1230
- };
1231
- let text;
1232
1408
  try {
1233
- text = JSON.stringify(e, replacer);
1409
+ const tree = mapValues(e, (v) => encodeValue(v, domains));
1410
+ return tree.ok ? ok(JSON.stringify(tree.value)) : fail(tree.error);
1234
1411
  } catch (thrown) {
1235
1412
  return fail(vexError("threw", "the expression has no JSON form", { thrown }));
1236
1413
  }
1237
- const first = failure[0];
1238
- return first === void 0 ? ok(text) : fail(vexError("bad-expression", first.message));
1239
1414
  }
1240
- const isEncoded = (u) => typeof u === "object" && u !== null && u.$vex === "domain" && typeof u.domain === "string";
1241
1415
  /** This function reads an expression from JSON text. It checks the whole tree. */
1242
1416
  function parse(text, domains = []) {
1243
1417
  let raw;
1244
- const failure = [];
1245
1418
  try {
1246
- raw = JSON.parse(text, (_k, value) => {
1247
- if (!isEncoded(value)) return value;
1248
- const d = domains.find((dom) => dom.name === value.domain);
1249
- if (d?.decode === void 0) {
1250
- failure.push(`no domain "${value.domain}" decodes a literal`);
1251
- return value;
1252
- }
1253
- return d.decode(value.value);
1254
- });
1419
+ raw = JSON.parse(text);
1255
1420
  } catch (thrown) {
1256
1421
  return fail(vexError("bad-expression", "the text is not JSON", { thrown }));
1257
1422
  }
1258
- const first = failure[0];
1259
- if (first !== void 0) return fail(vexError("bad-expression", first));
1260
- return isExpr(raw) ? ok(raw) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
1423
+ const tree = mapValues(raw, (v) => decodeValue(v, domains));
1424
+ if (!tree.ok) return fail(tree.error);
1425
+ return isExpr(tree.value) ? ok(tree.value) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
1261
1426
  }
1262
1427
  //#endregion
1263
1428
  //#region src/traversal.ts
@@ -1295,8 +1460,7 @@ function traversal(items, env, isStrict = false) {
1295
1460
  space: EMPTY_SPACE,
1296
1461
  origin: "$",
1297
1462
  domains: env.domains,
1298
- vars: { $list: list },
1299
- ...env.options?.fns === void 0 ? {} : { fns: env.options.fns }
1463
+ vars: { $list: list }
1300
1464
  });
1301
1465
  };
1302
1466
  const t = {
@@ -1304,7 +1468,7 @@ function traversal(items, env, isStrict = false) {
1304
1468
  strict: () => traversal(items, env, true),
1305
1469
  get: (k) => {
1306
1470
  const item = items.find((it) => it.key === k);
1307
- return item === void 0 ? toOptional(fail(vexError("unknown-key", `no item has the key "${k}"`))) : toOptional(item.result);
1471
+ return item === void 0 ? none() : toOptional(item.result);
1308
1472
  },
1309
1473
  values: () => items.flatMap((it) => it.result.ok ? [it.result.value] : []),
1310
1474
  keys: () => items.flatMap((it) => it.result.ok ? [it.key] : []),
@@ -1369,6 +1533,8 @@ var SheetRun = class {
1369
1533
  #columns;
1370
1534
  #opts;
1371
1535
  #done = /* @__PURE__ */ new Map();
1536
+ #warmed = /* @__PURE__ */ new Map();
1537
+ #index;
1372
1538
  #visits = /* @__PURE__ */ new Map();
1373
1539
  #stack = [];
1374
1540
  #top = {
@@ -1377,7 +1543,7 @@ var SheetRun = class {
1377
1543
  key: "",
1378
1544
  index: -1,
1379
1545
  low: -1,
1380
- selfLoop: false,
1546
+ reread: false,
1381
1547
  result: cycleError("", "")
1382
1548
  };
1383
1549
  #next = 0;
@@ -1400,8 +1566,27 @@ var SheetRun = class {
1400
1566
  });
1401
1567
  return this.cell(data.column, where.value);
1402
1568
  };
1403
- /** This method gives the result of one cell: the column `column` at the key `key`. */
1569
+ /**
1570
+ * This method gives the result of one cell: the column `column` at the key `key`. A read from a host first evaluates
1571
+ * the column at the keys before `key`, in key order. Thus a recurrence over the keys reads finished cells, and a
1572
+ * first read at the last key does not go deep into the call stack.
1573
+ */
1404
1574
  cell(column, key) {
1575
+ if (this.#top.index < 0) this.#warmTo(column, key);
1576
+ return this.#cell(column, key);
1577
+ }
1578
+ /** This method evaluates the column `column` at each key before `key` that it did not evaluate before, in key order. */
1579
+ #warmTo(column, key) {
1580
+ if (!this.#columns.has(column)) return;
1581
+ const keys = this.#opts.space.keys;
1582
+ this.#index ??= new Map(keys.map((k, i) => [k, i]));
1583
+ const end = this.#index.get(key) ?? 0;
1584
+ const start = this.#warmed.get(column) ?? 0;
1585
+ for (let i = start; i < end; i++) this.#cell(column, keys[i] ?? key);
1586
+ if (end > start) this.#warmed.set(column, end);
1587
+ }
1588
+ /** This method evaluates one cell, without the warm-up of `cell`. */
1589
+ #cell(column, key) {
1405
1590
  const id = `${column}\u0000${key}`;
1406
1591
  const done = this.#done.get(id);
1407
1592
  if (done !== void 0) return done;
@@ -1409,7 +1594,7 @@ var SheetRun = class {
1409
1594
  const seen = this.#visits.get(id);
1410
1595
  if (seen !== void 0) {
1411
1596
  caller.low = Math.min(caller.low, seen.index);
1412
- if (caller === seen) seen.selfLoop = true;
1597
+ seen.reread = true;
1413
1598
  return cycleError(column, key);
1414
1599
  }
1415
1600
  const program = this.#columns.get(column);
@@ -1424,7 +1609,7 @@ var SheetRun = class {
1424
1609
  key,
1425
1610
  index: n,
1426
1611
  low: n,
1427
- selfLoop: false,
1612
+ reread: false,
1428
1613
  result: cycleError(column, key)
1429
1614
  };
1430
1615
  this.#visits.set(id, visit);
@@ -1442,7 +1627,7 @@ var SheetRun = class {
1442
1627
  /** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
1443
1628
  #finish(root) {
1444
1629
  const members = this.#stack.splice(this.#stack.indexOf(root));
1445
- const cyclic = members.length > 1 || root.selfLoop;
1630
+ const cyclic = members.length > 1 || root.reread;
1446
1631
  for (const m of members) {
1447
1632
  this.#visits.delete(m.id);
1448
1633
  this.#done.set(m.id, cyclic ? cycleError(m.column, m.key) : m.result);
@@ -1469,10 +1654,7 @@ var SheetRun = class {
1469
1654
  * for example a running total, then reads finished cells and does not go deep into the call stack.
1470
1655
  */
1471
1656
  warm(column, key) {
1472
- for (const k of this.#opts.space.keys) {
1473
- if (k === key) return;
1474
- this.cell(column, k);
1475
- }
1657
+ this.#warmTo(column, key);
1476
1658
  }
1477
1659
  };
1478
1660
  //#endregion
@@ -1481,8 +1663,14 @@ const argToken = (expr) => ({
1481
1663
  kind: "vex.arg",
1482
1664
  expr
1483
1665
  });
1484
- const isArg = (u) => typeof u === "object" && u !== null && u.kind === "vex.arg";
1485
- const isChainLike = (u) => typeof u === "object" && u !== null && (u.kind === "vex.chain" || u.kind === "vex.list-chain");
1666
+ /** This function gives the run-time form of the options. A typed free function gets the values that the types promise. */
1667
+ const runtimeOptions = (options) => ({
1668
+ ...options.fns === void 0 ? {} : { fns: options.fns },
1669
+ ...options.extensions === void 0 ? {} : { extensions: options.extensions }
1670
+ });
1671
+ const kindOf = (u) => u?.kind;
1672
+ const isArg = (u) => kindOf(u) === "vex.arg";
1673
+ const isChainLike = (u) => kindOf(u) === "vex.chain" || kindOf(u) === "vex.list-chain";
1486
1674
  /** This function turns a builder argument into an expression. A bare string is a field reference at `addr`. */
1487
1675
  function toExpr(a, addr) {
1488
1676
  if (typeof a === "string") return ref(toPath(a), addr);
@@ -1523,14 +1711,7 @@ var ChainImpl = class ChainImpl {
1523
1711
  } });
1524
1712
  }
1525
1713
  #opts(k) {
1526
- const { env } = this.#s;
1527
- return {
1528
- space: env.space,
1529
- origin: k,
1530
- domains: env.domains,
1531
- ...env.options.fns === void 0 ? {} : { fns: env.options.fns },
1532
- ...env.options.extensions === void 0 ? {} : { extensions: env.options.extensions }
1533
- };
1714
+ return evalOptions(this.#s, k);
1534
1715
  }
1535
1716
  result(k) {
1536
1717
  return evaluate(this.#s.expr, this.#opts(k));
@@ -1581,6 +1762,18 @@ var ChainImpl = class ChainImpl {
1581
1762
  parent() {
1582
1763
  return this.#move(parent);
1583
1764
  }
1765
+ call(name, ...args) {
1766
+ return new ChainImpl({
1767
+ ...this.#s,
1768
+ expr: app(name, this.#s.expr, ...args.map((a) => toExpr(a, this.#s.addr)))
1769
+ });
1770
+ }
1771
+ if(then, otherwise) {
1772
+ return new ChainImpl({
1773
+ ...this.#s,
1774
+ expr: app("if", this.#s.expr, toExpr(then, this.#s.addr), toExpr(otherwise, this.#s.addr))
1775
+ });
1776
+ }
1584
1777
  ifError(fallback) {
1585
1778
  return new ChainImpl({
1586
1779
  ...this.#s,
@@ -1640,7 +1833,7 @@ var ChainImpl = class ChainImpl {
1640
1833
  };
1641
1834
  return new ListChainImpl({
1642
1835
  ...this.#s,
1643
- expr: let_({ [name]: this.#s.expr }, each(axis, inner.program))
1836
+ expr: let_({ [name]: this.#s.expr }, each(axis, inner.program, this.#s.addr))
1644
1837
  });
1645
1838
  }
1646
1839
  others(body, opts) {
@@ -1668,6 +1861,17 @@ var ChainImpl = class ChainImpl {
1668
1861
  return this.#axis({ t: "siblings" }, body, opts);
1669
1862
  }
1670
1863
  };
1864
+ /** This function gives the options of an evaluation of a chain or a list chain at the origin `k`. */
1865
+ function evalOptions(s, k) {
1866
+ const { env } = s;
1867
+ return {
1868
+ space: env.space,
1869
+ origin: k,
1870
+ domains: env.domains,
1871
+ ...env.options.fns === void 0 ? {} : { fns: env.options.fns },
1872
+ ...env.options.extensions === void 0 ? {} : { extensions: env.options.extensions }
1873
+ };
1874
+ }
1671
1875
  var ListChainImpl = class {
1672
1876
  kind = "vex.list-chain";
1673
1877
  #s;
@@ -1678,7 +1882,11 @@ var ListChainImpl = class {
1678
1882
  return this.#s.expr;
1679
1883
  }
1680
1884
  #op(op, extra, opts) {
1681
- const args = opts?.strict === true ? [...extra, lit({ strict: true })] : extra;
1885
+ const options = {
1886
+ ...opts?.strict === true ? { strict: true } : {},
1887
+ ...opts?.domain === void 0 ? {} : { domain: opts.domain }
1888
+ };
1889
+ const args = Object.keys(options).length > 0 ? [...extra, lit(options)] : extra;
1682
1890
  return new ChainImpl({
1683
1891
  ...this.#s,
1684
1892
  expr: app(op, this.#s.expr, ...args)
@@ -1711,12 +1919,27 @@ var ListChainImpl = class {
1711
1919
  values(opts) {
1712
1920
  return this.#op("values", [], opts);
1713
1921
  }
1922
+ keys(opts) {
1923
+ return this.#op("keys", [], opts);
1924
+ }
1925
+ errors() {
1926
+ return this.#op("errors", []);
1927
+ }
1714
1928
  first(opts) {
1715
1929
  return this.#op("first", [], opts);
1716
1930
  }
1717
1931
  reduce(op, opts) {
1718
1932
  return this.#op("reduce", [lit(op)], opts);
1719
1933
  }
1934
+ result(k) {
1935
+ return evaluate(this.#s.expr, evalOptions(this.#s, k));
1936
+ }
1937
+ at(k) {
1938
+ return toOptional(this.result(k));
1939
+ }
1940
+ explain(k) {
1941
+ return explain(this.#s.expr, evalOptions(this.#s, k));
1942
+ }
1720
1943
  };
1721
1944
  var RootImpl = class {
1722
1945
  #env;
@@ -1766,8 +1989,7 @@ var RootImpl = class {
1766
1989
  };
1767
1990
  var SheetRootImpl = class extends RootImpl {
1768
1991
  cell(column, at) {
1769
- const addr = at === void 0 ? [] : typeof at === "string" ? [key(at)] : at;
1770
- return argToken(cell(column, addr));
1992
+ return argToken(cell(column, typeof at === "string" ? [key(at)] : at));
1771
1993
  }
1772
1994
  };
1773
1995
  var SheetImpl = class SheetImpl {
@@ -1780,6 +2002,9 @@ var SheetImpl = class SheetImpl {
1780
2002
  get columns() {
1781
2003
  return Object.freeze(Object.fromEntries(this.#columns));
1782
2004
  }
2005
+ declare() {
2006
+ return this;
2007
+ }
1783
2008
  column(name, formula) {
1784
2009
  const program = formula(new SheetRootImpl(this.#env)).program;
1785
2010
  return new SheetImpl(this.#env, new Map([...this.#columns, [name, program]]));
@@ -1825,7 +2050,7 @@ function vex(...domains) {
1825
2050
  over: (s) => new RootImpl({
1826
2051
  space: s,
1827
2052
  domains,
1828
- options
2053
+ options: runtimeOptions(options)
1829
2054
  })
1830
2055
  });
1831
2056
  return {