@mark1russell7/vex 0.3.0 → 0.5.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
@@ -50,8 +50,19 @@ const CODE_OF = {
50
50
  threw: "#CALC!",
51
51
  "undefined-result": "#CALC!",
52
52
  args: "#ARGS",
53
- cycle: "#CYCLE!"
53
+ cycle: "#CYCLE!",
54
+ depth: "#DEPTH!"
54
55
  };
56
+ /**
57
+ * This function tells if an exception is the report of the engine that the call stack is full. V8 and JavaScriptCore
58
+ * throw a `RangeError`. SpiderMonkey throws an `InternalError` ("too much recursion").
59
+ */
60
+ function isStackOverflow(thrown) {
61
+ if (!(thrown instanceof Error)) return false;
62
+ return thrown instanceof RangeError && /call stack/i.test(thrown.message) || thrown.name === "InternalError" && /recursion/i.test(thrown.message);
63
+ }
64
+ /** This function tells if an error is `#DEPTH!`. `ifError` and the reductions that skip errors do not hide it (EVAL.DEPTH). */
65
+ const isDepthError = (e) => e.kind === "depth";
55
66
  /** This function gives the code of an error kind. */
56
67
  const codeOf = (kind) => CODE_OF[kind];
57
68
  /** This function makes a `VexError`. */
@@ -113,12 +124,22 @@ const rec = (fields) => ({
113
124
  tag: "rec",
114
125
  fields
115
126
  });
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
- });
127
+ /**
128
+ * This function evaluates `body` once for each target of `axis`. The result is a list. With `at`, the axis finds its
129
+ * targets from the key of that address, not from the focus.
130
+ */
131
+ function each(axis, body, at) {
132
+ return at === void 0 || at.length === 0 ? {
133
+ tag: "each",
134
+ axis,
135
+ body
136
+ } : {
137
+ tag: "each",
138
+ axis,
139
+ body,
140
+ at
141
+ };
142
+ }
122
143
  /** This function makes an expression of an extension kind. */
123
144
  const ext = (kind, data) => ({
124
145
  tag: "ext",
@@ -189,37 +210,87 @@ function isMove(u) {
189
210
  default: return false;
190
211
  }
191
212
  }
192
- /** This function tells if a value is a valid axis. */
213
+ /** This function tells if a value is a valid axis. It checks the tests of `where` too. */
193
214
  function isAxis(u) {
194
- if (!isObject(u)) return false;
195
- switch (u["t"]) {
196
- case "all":
197
- case "others":
198
- case "other":
199
- case "children":
200
- case "ancestors":
201
- case "descendants":
202
- case "siblings": return true;
203
- case "neighbors": return u["n"] === 4 || u["n"] === 8;
204
- case "where": return isAxis(u["axis"]) && isExpr(u["test"]);
205
- default: return false;
206
- }
215
+ return validTree([{
216
+ axis: true,
217
+ u
218
+ }]);
207
219
  }
208
- const isExprRecord = (u) => isObject(u) && !Array.isArray(u) && Object.values(u).every((e) => isExpr(e));
209
220
  /** This function tells if a value is a valid expression. It checks the whole tree. */
210
221
  function isExpr(u) {
211
- if (!isObject(u)) return false;
212
- switch (u["tag"]) {
213
- case "lit": return "value" in u;
214
- case "ref": return isStringArray(u["path"]) && (u["at"] === void 0 || Array.isArray(u["at"]) && u["at"].every(isMove));
215
- case "app": return typeof u["op"] === "string" && Array.isArray(u["args"]) && u["args"].every((a) => isExpr(a));
216
- case "let": return isExprRecord(u["bind"]) && isExpr(u["body"]);
217
- case "var": return typeof u["name"] === "string";
218
- case "rec": return isExprRecord(u["fields"]);
219
- case "each": return isAxis(u["axis"]) && isExpr(u["body"]);
220
- case "ext": return typeof u["kind"] === "string" && "data" in u;
221
- default: return false;
222
+ return validTree([{
223
+ axis: false,
224
+ u
225
+ }]);
226
+ }
227
+ const isAddr = (u) => u === void 0 || Array.isArray(u) && u.every(isMove);
228
+ /**
229
+ * This function checks a tree of expressions and axes. It uses a stack, not recursion, so the input can be deep. For
230
+ * example, a deep JSON file from a stranger does not need a deep call stack (EVAL.NESTING).
231
+ */
232
+ function validTree(todo) {
233
+ const push = (axis, values) => {
234
+ for (const u of values) todo.push({
235
+ axis,
236
+ u
237
+ });
238
+ };
239
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
240
+ const { u } = item;
241
+ if (!isObject(u)) return false;
242
+ if (item.axis) {
243
+ const t = u["t"];
244
+ if (t === "neighbors") {
245
+ if (u["n"] !== 4 && u["n"] !== 8) return false;
246
+ } else if (t === "where") {
247
+ push(true, [u["axis"]]);
248
+ push(false, [u["test"]]);
249
+ } else if (![
250
+ "all",
251
+ "others",
252
+ "other",
253
+ "children",
254
+ "ancestors",
255
+ "descendants",
256
+ "siblings"
257
+ ].includes(t)) return false;
258
+ continue;
259
+ }
260
+ switch (u["tag"]) {
261
+ case "lit":
262
+ if (!("value" in u)) return false;
263
+ break;
264
+ case "ref":
265
+ if (!isStringArray(u["path"]) || !isAddr(u["at"])) return false;
266
+ break;
267
+ case "app":
268
+ if (typeof u["op"] !== "string" || !Array.isArray(u["args"])) return false;
269
+ push(false, u["args"]);
270
+ break;
271
+ case "let":
272
+ if (!isObject(u["bind"]) || Array.isArray(u["bind"])) return false;
273
+ push(false, [...Object.values(u["bind"]), u["body"]]);
274
+ break;
275
+ case "var":
276
+ if (typeof u["name"] !== "string") return false;
277
+ break;
278
+ case "rec":
279
+ if (!isObject(u["fields"]) || Array.isArray(u["fields"])) return false;
280
+ push(false, Object.values(u["fields"]));
281
+ break;
282
+ case "each":
283
+ if (!isAddr(u["at"])) return false;
284
+ push(true, [u["axis"]]);
285
+ push(false, [u["body"]]);
286
+ break;
287
+ case "ext":
288
+ if (typeof u["kind"] !== "string" || !("data" in u)) return false;
289
+ break;
290
+ default: return false;
291
+ }
222
292
  }
293
+ return true;
223
294
  }
224
295
  /** This function gives the child expressions of an expression, in the order of their child index. */
225
296
  function children(e) {
@@ -234,8 +305,11 @@ function children(e) {
234
305
  case "ext": return [];
235
306
  }
236
307
  }
308
+ /** This function gives the tests of the `where` axes of an axis, from the inside out. It uses a loop, not recursion. */
237
309
  function whereTests(a) {
238
- return a.t === "where" ? [...whereTests(a.axis), a.test] : [];
310
+ const out = [];
311
+ for (let x = a; x.t === "where"; x = x.axis) out.unshift(x.test);
312
+ return out;
239
313
  }
240
314
  //#endregion
241
315
  //#region src/space.ts
@@ -399,6 +473,15 @@ function applyMove(s, at, m) {
399
473
  return ok(at.focus === a ? b ?? at.focus : a ?? at.focus);
400
474
  }
401
475
  case "offset": {
476
+ const parentOf = s.parentOf?.bind(s);
477
+ const childrenOf = s.childrenOf?.bind(s);
478
+ if (parentOf !== void 0 && childrenOf !== void 0 && m.d.length === 1) {
479
+ const p = parentOf(at.focus);
480
+ const group = p === void 0 ? s.keys.filter((k) => parentOf(k) === void 0) : childrenOf(p);
481
+ const i = group.indexOf(at.focus);
482
+ const k = i < 0 ? void 0 : group[i + (m.d[0] ?? 0)];
483
+ return k === void 0 ? refError("out-of-bounds", `the offset [${m.d.join(",")}] from "${at.focus}" is outside its siblings`) : ok(k);
484
+ }
402
485
  const c = s.coords(at.focus);
403
486
  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
487
  /* v8 ignore next -- @preserve */
@@ -602,8 +685,27 @@ const isSpecialForm = (op) => SPECIAL_FORMS.has(op);
602
685
  * This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
603
686
  * because `evaluate` uses it too.
604
687
  */
688
+ /** The deepest nesting of an expression that `compile` accepts (EVAL.NESTING). */
689
+ const MAX_NESTING = 500;
690
+ const DEPTH_MESSAGE = "the evaluation is too deep for the call stack of the engine";
691
+ /** This function gives the number of nodes on the longest path from the root of `e`. It uses a stack, not recursion. */
692
+ function nestingOf(e) {
693
+ let deepest = 0;
694
+ const todo = [[e, 1]];
695
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
696
+ const [x, d] = item;
697
+ if (d > deepest) deepest = d;
698
+ for (const child of children(x)) todo.push([child, d + 1]);
699
+ }
700
+ return deepest;
701
+ }
605
702
  function compile(expr, opts = {}) {
606
- const root = new Compiler(opts).node(expr, []);
703
+ const nesting = nestingOf(expr);
704
+ const root = nesting > 500 ? (f) => fail(vexError("bad-expression", `the expression is nested ${nesting} levels deep, and the limit is 500`, {
705
+ path: [],
706
+ origin: f.pos.origin,
707
+ focus: f.pos.focus
708
+ })) : new Compiler(opts).node(expr, []);
607
709
  const run = (r) => {
608
710
  const { space, origin } = r;
609
711
  if (!space.has(origin)) return fail(vexError("unknown-key", `the space has no key "${origin}"`, {
@@ -623,6 +725,11 @@ function compile(expr, opts = {}) {
623
725
  trace: r.trace
624
726
  });
625
727
  } catch (thrown) {
728
+ if (isStackOverflow(thrown)) return fail(vexError("depth", DEPTH_MESSAGE, {
729
+ origin,
730
+ focus: origin,
731
+ thrown
732
+ }));
626
733
  return fail(vexError("threw", "the evaluation threw an exception", {
627
734
  origin,
628
735
  focus: origin,
@@ -773,12 +880,19 @@ var Compiler = class {
773
880
  try {
774
881
  return run();
775
882
  } catch (thrown) {
776
- return this.#err("threw", `"${op}" threw an exception`, f, path, {
777
- op,
778
- thrown
779
- });
883
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
780
884
  }
781
885
  }
886
+ /** This method gives the error of an exception: `#DEPTH!` for a full call stack, and `#CALC!` for each other exception. */
887
+ #threw(thrown, message, f, path, extra = {}) {
888
+ return isStackOverflow(thrown) ? this.#err("depth", DEPTH_MESSAGE, f, path, {
889
+ ...extra,
890
+ thrown
891
+ }) : this.#err("threw", message, f, path, {
892
+ ...extra,
893
+ thrown
894
+ });
895
+ }
782
896
  #ref(e, info) {
783
897
  const { path } = info;
784
898
  const segs = e.path;
@@ -812,7 +926,7 @@ var Compiler = class {
812
926
  try {
813
927
  value = Reflect.get(value, seg);
814
928
  } catch (thrown) {
815
- return failed(this.#err("threw", `reading "${where}" at "${key}" threw an exception`, f, path, { thrown }));
929
+ return failed(this.#threw(thrown, `reading "${where}" at "${key}" threw an exception`, f, path));
816
930
  }
817
931
  if (value === void 0 || value === null) return missing(where);
818
932
  }
@@ -835,14 +949,32 @@ var Compiler = class {
835
949
  else (errors ??= [first]).push(r.error);
836
950
  }
837
951
  if (first === void 0) return ok(values);
952
+ const depth = [first, ...errors ?? []].find(isDepthError);
953
+ if (depth !== void 0) return fail(depth);
838
954
  return errors === void 0 ? fail(first) : this.#err("args", `${errors.length} ${what} failed`, f, path, { causes: errors });
839
955
  }
840
956
  #each(e, info) {
841
957
  const { path } = info;
958
+ const at = e.at ?? [];
842
959
  const targets = this.#targets(e.axis, path, { next: 1 });
843
960
  const body = this.node(e.body, [...path, 0]);
844
961
  return (f, c) => {
845
- const ts = targets(f, c);
962
+ let from = f;
963
+ if (at.length > 0) {
964
+ const where = resolveAddr(c.space, f.pos, at);
965
+ if (!where.ok) return this.#emit(c, info, f, fail({
966
+ ...where.error,
967
+ path
968
+ }));
969
+ from = {
970
+ pos: {
971
+ origin: f.pos.origin,
972
+ focus: where.value
973
+ },
974
+ env: f.env
975
+ };
976
+ }
977
+ const ts = targets(from, c);
846
978
  if (!ts.ok) return this.#emit(c, info, f, ts);
847
979
  const items = ts.value.map(({ key, test }) => {
848
980
  if (test !== void 0 && !test.ok) return {
@@ -959,7 +1091,7 @@ var Compiler = class {
959
1091
  }
960
1092
  case "ifError": return (f, c) => {
961
1093
  const first = arg(0, f, c);
962
- return this.#emit(c, info, f, first.ok ? first : arg(1, f, c));
1094
+ return this.#emit(c, info, f, first.ok || isDepthError(first.error) ? first : arg(1, f, c));
963
1095
  };
964
1096
  }
965
1097
  }
@@ -986,10 +1118,7 @@ var Compiler = class {
986
1118
  try {
987
1119
  return ok(run());
988
1120
  } catch (thrown) {
989
- return this.#err("threw", `"${op}" threw an exception`, f, path, {
990
- op,
991
- thrown
992
- });
1121
+ return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
993
1122
  }
994
1123
  }
995
1124
  /** This method checks the value that an op gave: no `undefined`, finite numbers, and valid domain values. */
@@ -1005,17 +1134,17 @@ var Compiler = class {
1005
1134
  try {
1006
1135
  valid = d.valid(value);
1007
1136
  } catch (thrown) {
1008
- return this.#err("threw", `the "valid" check of "${d.name}" threw an exception`, f, path, {
1009
- ...extra,
1010
- thrown
1011
- });
1137
+ return this.#threw(thrown, `the "valid" check of "${d.name}" threw an exception`, f, path, extra);
1012
1138
  }
1013
1139
  if (!valid) return this.#err("invalid-value", `"${op}" gave a value that is not a valid ${d.name}`, f, path, extra);
1014
1140
  }
1015
1141
  return r;
1016
1142
  }
1017
1143
  #listOp(op, list, rest, f, path) {
1018
- const strict = (op === "reduce" ? rest[1] : rest[0])?.strict === true;
1144
+ const optsArg = op === "reduce" ? rest[1] : rest[0];
1145
+ const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
1146
+ if (depth !== void 0 && !depth.ok) return fail(depth.error);
1147
+ const strict = optsArg?.strict === true;
1019
1148
  const firstError = list.items.find((it) => !it.result.ok)?.result;
1020
1149
  if (strict && firstError !== void 0 && !firstError.ok) return fail(firstError.error);
1021
1150
  const okValues = list.items.flatMap((it) => it.result.ok ? [it.result.value] : []);
@@ -1059,18 +1188,26 @@ var Compiler = class {
1059
1188
  if (op === "all") return ok(b.value.every((x) => x));
1060
1189
  return ok(!b.value.some((x) => x));
1061
1190
  }
1062
- case "reduce": return this.#reduce(rest[0], okValues, f, path);
1191
+ case "reduce": return this.#reduce(rest[0], okValues, f, path, optsArg);
1063
1192
  }
1064
1193
  }
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) {
1194
+ /**
1195
+ * This method folds the values with a domain op, from the left. An empty list gives the identity of the op, if one
1196
+ * domain has an identity for the op (LIST.EMPTY). The option `domain` names that domain when more domains have one.
1197
+ */
1198
+ #reduce(opName, values, f, path, opts) {
1067
1199
  if (typeof opName !== "string") return this.#err("kind-mismatch", `"reduce" needs an op name, but got a ${describeType(opName)}`, f, path, { op: "reduce" });
1068
1200
  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);
1201
+ const named = opts?.domain;
1202
+ const candidates = this.#domains.filter((d) => Object.hasOwn(d.ops, opName) && d.ops[opName].identity !== void 0 && (named === void 0 || d.name === named));
1203
+ 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 });
1204
+ const [only, second] = candidates;
1205
+ if (only === void 0) return this.#err("empty", `"reduce" with "${opName}" has no values and the op has no identity`, f, path, { op: opName });
1206
+ if (second !== void 0) {
1207
+ const names = candidates.map((d) => d.name).join(", ");
1208
+ 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
1209
  }
1073
- return this.#err("empty", `"reduce" with "${opName}" has no values and the op has no identity`, f, path, { op: opName });
1210
+ return this.#invoke(only.ops[opName].identity, opName, f, path);
1074
1211
  }
1075
1212
  let acc = values[0];
1076
1213
  for (let i = 1; i < values.length; i++) {
@@ -1127,10 +1264,21 @@ function labelOf(e) {
1127
1264
  case "let": return `let ${Object.keys(e.bind).join(", ")}`;
1128
1265
  case "var": return e.name;
1129
1266
  case "rec": return `{ ${Object.keys(e.fields).join(", ")} }`;
1130
- case "each": return `each ${e.axis.t}`;
1267
+ case "each": return e.at === void 0 ? `each ${e.axis.t}` : `each ${e.axis.t} from ${e.at.map(moveText).join(".")}`;
1131
1268
  case "ext": return e.kind;
1132
1269
  }
1133
1270
  }
1271
+ /** This function gives a short text for a move, for the label of an axis with an address. */
1272
+ function moveText(m) {
1273
+ switch (m.t) {
1274
+ case "key": return `key(${m.key})`;
1275
+ case "index": return `index(${m.i})`;
1276
+ case "offset": return `offset(${m.d.join(", ")})`;
1277
+ case "other":
1278
+ case "origin":
1279
+ case "parent": return m.t;
1280
+ }
1281
+ }
1134
1282
  /** This function gives a short text for a value. */
1135
1283
  function previewValue(u) {
1136
1284
  if (typeof u === "number") return String(u);
@@ -1176,86 +1324,209 @@ const sizeOf = (e) => 1 + children(e).reduce((s, c) => s + sizeOf(c), 0);
1176
1324
  */
1177
1325
  function deps(e) {
1178
1326
  const out = [];
1179
- const walk = (x, axes) => {
1327
+ const todo = [{
1328
+ x: e,
1329
+ axes: [],
1330
+ axisAt: []
1331
+ }];
1332
+ for (let item = todo.pop(); item !== void 0; item = todo.pop()) {
1333
+ const { x } = item;
1180
1334
  if (x.tag === "ref") {
1181
1335
  out.push({
1182
1336
  at: x.at ?? [],
1183
1337
  path: x.path,
1184
- axes
1338
+ axes: item.axes,
1339
+ axisAt: item.axisAt
1185
1340
  });
1186
- return;
1187
- }
1188
- if (x.tag === "each") {
1189
- const inner = [...axes, x.axis.t];
1190
- children(x).forEach((c) => walk(c, inner));
1191
- return;
1341
+ continue;
1192
1342
  }
1193
- children(x).forEach((c) => walk(c, axes));
1194
- };
1195
- walk(e, []);
1343
+ const axes = x.tag === "each" ? [...item.axes, x.axis.t] : item.axes;
1344
+ const axisAt = x.tag === "each" ? [...item.axisAt, x.at ?? []] : item.axisAt;
1345
+ for (const child of children(x).toReversed()) todo.push({
1346
+ x: child,
1347
+ axes,
1348
+ axisAt
1349
+ });
1350
+ }
1196
1351
  return out;
1197
1352
  }
1198
1353
  //#endregion
1199
1354
  //#region src/json.ts
1200
- const isPlainJson = (u) => {
1201
- if (u === null || typeof u === "string" || typeof u === "boolean") return true;
1202
- if (typeof u === "number") return Number.isFinite(u);
1203
- if (Array.isArray(u)) return u.every(isPlainJson);
1204
- if (typeof u === "object") {
1205
- const proto = Object.getPrototypeOf(u);
1206
- return (proto === Object.prototype || proto === null) && Object.values(u).every(isPlainJson);
1355
+ const isRecord = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
1356
+ const isPlainRecord = (u) => {
1357
+ if (!isRecord(u)) return false;
1358
+ const proto = Object.getPrototypeOf(u);
1359
+ return proto === Object.prototype || proto === null;
1360
+ };
1361
+ /** This function gives the JSON form of a value, or the reason why the value has no JSON form. */
1362
+ function encodeValue(u, domains) {
1363
+ if (u === null || typeof u === "string" || typeof u === "boolean") return ok(u);
1364
+ if (typeof u === "number") {
1365
+ if (Object.is(u, -0)) return ok({
1366
+ $vex: "number",
1367
+ value: "-0"
1368
+ });
1369
+ return Number.isFinite(u) ? ok(u) : ok({
1370
+ $vex: "number",
1371
+ value: Number.isNaN(u) ? "NaN" : u > 0 ? "Infinity" : "-Infinity"
1372
+ });
1373
+ }
1374
+ if (Array.isArray(u)) {
1375
+ const out = [];
1376
+ for (const x of u) {
1377
+ const r = encodeValue(x, domains);
1378
+ if (!r.ok) return r;
1379
+ out.push(r.value);
1380
+ }
1381
+ return ok(out);
1207
1382
  }
1208
- return false;
1383
+ if (isPlainRecord(u)) {
1384
+ const out = {};
1385
+ for (const [k, x] of Object.entries(u)) {
1386
+ const r = encodeValue(x, domains);
1387
+ if (!r.ok) return r;
1388
+ out[k] = r.value;
1389
+ }
1390
+ return ok(Object.hasOwn(u, "$vex") ? {
1391
+ $vex: "escape",
1392
+ value: out
1393
+ } : out);
1394
+ }
1395
+ const d = domains.find((dom) => dom.encode !== void 0 && dom.is(u));
1396
+ if (d?.encode !== void 0) return ok({
1397
+ $vex: "domain",
1398
+ domain: d.name,
1399
+ value: d.encode(u)
1400
+ });
1401
+ return fail(vexError("bad-expression", "a literal value is not JSON data and no domain encodes it"));
1402
+ }
1403
+ const NUMBERS = {
1404
+ "-0": -0,
1405
+ NaN: NaN,
1406
+ Infinity: Number.POSITIVE_INFINITY,
1407
+ "-Infinity": Number.NEGATIVE_INFINITY
1209
1408
  };
1409
+ /** This function reads a value from its JSON form. */
1410
+ function decodeValue(u, domains) {
1411
+ if (Array.isArray(u)) {
1412
+ const out = [];
1413
+ for (const x of u) {
1414
+ const r = decodeValue(x, domains);
1415
+ if (!r.ok) return r;
1416
+ out.push(r.value);
1417
+ }
1418
+ return ok(out);
1419
+ }
1420
+ if (!isRecord(u)) return ok(u);
1421
+ const fields = (record) => {
1422
+ const out = {};
1423
+ for (const [k, x] of Object.entries(record)) {
1424
+ const r = decodeValue(x, domains);
1425
+ if (!r.ok) return r;
1426
+ out[k] = r.value;
1427
+ }
1428
+ return ok(out);
1429
+ };
1430
+ const kind = u["$vex"];
1431
+ if (kind === "escape" && isRecord(u["value"])) return fields(u["value"]);
1432
+ if (kind === "number" && typeof u["value"] === "string" && Object.hasOwn(NUMBERS, u["value"])) return ok(NUMBERS[u["value"]]);
1433
+ if (kind === "domain" && typeof u["domain"] === "string") {
1434
+ const name = u["domain"];
1435
+ const d = domains.find((dom) => dom.name === name);
1436
+ if (d?.decode === void 0) return fail(vexError("bad-expression", `no domain "${name}" decodes a literal`));
1437
+ return ok(d.decode(u["value"]));
1438
+ }
1439
+ return fields(u);
1440
+ }
1441
+ /** This function applies `f` to each literal value of a JSON tree of an expression. */
1442
+ function mapValues(u, f) {
1443
+ if (!isRecord(u)) return ok(u);
1444
+ const out = { ...u };
1445
+ const child = (key) => {
1446
+ const r = mapValues(u[key], f);
1447
+ if (r.ok) out[key] = r.value;
1448
+ return r.ok ? void 0 : r;
1449
+ };
1450
+ const each = (key) => {
1451
+ const list = u[key];
1452
+ if (Array.isArray(list)) {
1453
+ const items = [];
1454
+ for (const x of list) {
1455
+ const r = mapValues(x, f);
1456
+ if (!r.ok) return r;
1457
+ items.push(r.value);
1458
+ }
1459
+ out[key] = items;
1460
+ } else if (isRecord(list)) {
1461
+ const rec = {};
1462
+ for (const [k, x] of Object.entries(list)) {
1463
+ const r = mapValues(x, f);
1464
+ if (!r.ok) return r;
1465
+ rec[k] = r.value;
1466
+ }
1467
+ out[key] = rec;
1468
+ }
1469
+ };
1470
+ const axis = (a) => {
1471
+ if (!isRecord(a) || a["t"] !== "where") return ok(a);
1472
+ const inner = axis(a["axis"]);
1473
+ if (!inner.ok) return inner;
1474
+ const test = mapValues(a["test"], f);
1475
+ return test.ok ? ok({
1476
+ ...a,
1477
+ axis: inner.value,
1478
+ test: test.value
1479
+ }) : test;
1480
+ };
1481
+ switch (u["tag"]) {
1482
+ case "lit": {
1483
+ if (!Object.hasOwn(u, "value")) return ok(out);
1484
+ const r = f(u["value"]);
1485
+ if (!r.ok) return r;
1486
+ out["value"] = r.value;
1487
+ return ok(out);
1488
+ }
1489
+ case "app": return each("args") ?? ok(out);
1490
+ case "let": return each("bind") ?? child("body") ?? ok(out);
1491
+ case "rec": return each("fields") ?? ok(out);
1492
+ case "each": {
1493
+ const a = axis(u["axis"]);
1494
+ if (!a.ok) return a;
1495
+ out["axis"] = a.value;
1496
+ return child("body") ?? ok(out);
1497
+ }
1498
+ default: return ok(out);
1499
+ }
1500
+ }
1210
1501
  /**
1211
- * This function gives the JSON text of an expression. A literal that is a domain value needs a domain with
1212
- * `encode`. A literal that is not JSON data and has no such domain gives the error `#VALUE!`.
1502
+ * This function gives the JSON text of an expression. A literal value that is a domain value needs a domain with
1503
+ * `encode`. A literal value that is not JSON data and has no such domain gives the error `#VALUE!`.
1213
1504
  */
1214
1505
  function serialize(e, domains = []) {
1215
- const failure = [];
1216
- const replacer = function(k, value) {
1217
- const holder = this;
1218
- if (k !== "value" || holder["tag"] !== "lit") return value;
1219
- if (isPlainJson(value)) return value;
1220
- const d = domains.find((dom) => dom.encode !== void 0 && dom.is(value));
1221
- if (d?.encode !== void 0) return {
1222
- $vex: "domain",
1223
- domain: d.name,
1224
- value: d.encode(value)
1225
- };
1226
- failure.push({ message: `a literal value is not JSON data and no domain encodes it` });
1227
- return null;
1228
- };
1229
- let text;
1230
1506
  try {
1231
- text = JSON.stringify(e, replacer);
1507
+ const tree = mapValues(e, (v) => encodeValue(v, domains));
1508
+ return tree.ok ? ok(JSON.stringify(tree.value)) : fail(tree.error);
1232
1509
  } catch (thrown) {
1510
+ if (isStackOverflow(thrown)) return fail(vexError("depth", "the expression is too deep for the call stack of the engine", { thrown }));
1233
1511
  return fail(vexError("threw", "the expression has no JSON form", { thrown }));
1234
1512
  }
1235
- const first = failure[0];
1236
- return first === void 0 ? ok(text) : fail(vexError("bad-expression", first.message));
1237
1513
  }
1238
- const isEncoded = (u) => u?.$vex === "domain" && typeof u.domain === "string";
1239
1514
  /** This function reads an expression from JSON text. It checks the whole tree. */
1240
1515
  function parse(text, domains = []) {
1241
1516
  let raw;
1242
- const failure = [];
1243
1517
  try {
1244
- raw = JSON.parse(text, (_k, value) => {
1245
- if (!isEncoded(value)) return value;
1246
- const d = domains.find((dom) => dom.name === value.domain);
1247
- if (d?.decode === void 0) {
1248
- failure.push(`no domain "${value.domain}" decodes a literal`);
1249
- return value;
1250
- }
1251
- return d.decode(value.value);
1252
- });
1518
+ raw = JSON.parse(text);
1253
1519
  } catch (thrown) {
1254
1520
  return fail(vexError("bad-expression", "the text is not JSON", { thrown }));
1255
1521
  }
1256
- const first = failure[0];
1257
- if (first !== void 0) return fail(vexError("bad-expression", first));
1258
- return isExpr(raw) ? ok(raw) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
1522
+ try {
1523
+ const tree = mapValues(raw, (v) => decodeValue(v, domains));
1524
+ if (!tree.ok) return fail(tree.error);
1525
+ return isExpr(tree.value) ? ok(tree.value) : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
1526
+ } catch (thrown) {
1527
+ if (isStackOverflow(thrown)) return fail(vexError("depth", "the JSON is too deep for the call stack of the engine", { thrown }));
1528
+ return fail(vexError("threw", "a decoder of a domain threw an exception", { thrown }));
1529
+ }
1259
1530
  }
1260
1531
  //#endregion
1261
1532
  //#region src/traversal.ts
@@ -1362,10 +1633,34 @@ const cycleError = (column, key) => fail(vexError("cycle", `the cell "${column}"
1362
1633
  origin: key,
1363
1634
  focus: key
1364
1635
  }));
1636
+ /** The id of a cell. */
1637
+ const idOf = (column, key) => `${column}\u0000${key}`;
1638
+ /**
1639
+ * The budget of the stack for the recursion of a run, in estimated frames. Each engine has more stack than this, so
1640
+ * the recursion of a run cannot fill the stack (SHEET.DEEP).
1641
+ */
1642
+ const STACK_BUDGET = 3e3;
1643
+ /**
1644
+ * One run of a sheet. It keeps the result of each cell that it evaluated. The space does not change, so a cell has
1645
+ * one result in a run.
1646
+ *
1647
+ * The run is a depth-first search with the algorithm of Tarjan for strongly connected components. A cell finishes
1648
+ * when its component finishes. Each cell of a component with two or more cells, or with a reference to itself,
1649
+ * gives `#CYCLE!`. A read of a cell that is not finished gives `#CYCLE!` too. Thus the order of the evaluations
1650
+ * does not change a result, also when `ifError` catches the error of a cycle.
1651
+ *
1652
+ * The search does not depend on the call stack of the engine (SHEET.DEEP). A read of a cell evaluates that cell
1653
+ * with recursion while the stack of the run stays in a budget. When a read is over the budget, the run starts the
1654
+ * cell, and the cell that reads it pauses. A paused evaluation reads no other cell and changes no state of the
1655
+ * search. The run then evaluates the started cell from its own list, and it evaluates the paused cell again after
1656
+ * that cell. A formula is pure (EVAL.PURE), so the second evaluation gives the result of one evaluation.
1657
+ */
1365
1658
  var SheetRun = class {
1366
1659
  #columns;
1367
1660
  #opts;
1368
1661
  #done = /* @__PURE__ */ new Map();
1662
+ #warmed = /* @__PURE__ */ new Map();
1663
+ #index;
1369
1664
  #visits = /* @__PURE__ */ new Map();
1370
1665
  #stack = [];
1371
1666
  #top = {
@@ -1375,11 +1670,18 @@ var SheetRun = class {
1375
1670
  index: -1,
1376
1671
  low: -1,
1377
1672
  reread: false,
1378
- result: cycleError("", "")
1673
+ result: cycleError("", ""),
1674
+ paused: false,
1675
+ need: void 0
1379
1676
  };
1380
1677
  #next = 0;
1381
- constructor(columns, opts) {
1678
+ #used = 0;
1679
+ #cost = /* @__PURE__ */ new Map();
1680
+ #budget;
1681
+ /** `budget` is the budget of the stack in estimated frames. A test can make it small, so the run pauses often. */
1682
+ constructor(columns, opts, budget = STACK_BUDGET) {
1382
1683
  this.#columns = columns;
1684
+ this.#budget = budget;
1383
1685
  this.#opts = {
1384
1686
  ...opts,
1385
1687
  extensions: {
@@ -1395,50 +1697,135 @@ var SheetRun = class {
1395
1697
  ...where.error,
1396
1698
  path: ctx.path
1397
1699
  });
1398
- return this.cell(data.column, where.value);
1700
+ return this.#read(data.column, where.value);
1399
1701
  };
1400
- /** This method gives the result of one cell: the column `column` at the key `key`. */
1702
+ /**
1703
+ * This method gives the result of one cell: the column `column` at the key `key`. A read from a host first evaluates
1704
+ * the column at the keys before `key`, in key order. Thus a recurrence over the keys reads finished cells.
1705
+ */
1401
1706
  cell(column, key) {
1402
- const id = `${column}\u0000${key}`;
1403
- const done = this.#done.get(id);
1404
- if (done !== void 0) return done;
1405
- const caller = this.#top;
1406
- const seen = this.#visits.get(id);
1407
- if (seen !== void 0) {
1408
- caller.low = Math.min(caller.low, seen.index);
1409
- seen.reread = true;
1410
- return cycleError(column, key);
1707
+ if (this.#top.index >= 0) return this.#read(column, key);
1708
+ this.#warmTo(column, key);
1709
+ return this.#drive(column, key);
1710
+ }
1711
+ /** This method evaluates the column `column` at each key before `key` that it did not evaluate before, in key order. */
1712
+ #warmTo(column, key) {
1713
+ if (!this.#columns.has(column)) return;
1714
+ const keys = this.#opts.space.keys;
1715
+ this.#index ??= new Map(keys.map((k, i) => [k, i]));
1716
+ const end = this.#index.get(key) ?? 0;
1717
+ const start = this.#warmed.get(column) ?? 0;
1718
+ for (let i = start; i < end; i++) this.#drive(column, keys[i] ?? key);
1719
+ if (end > start) this.#warmed.set(column, end);
1720
+ }
1721
+ /** This method gives the estimated frames of the stack that one evaluation of a cell of `column` uses. */
1722
+ #costOf(column, program) {
1723
+ let cost = this.#cost.get(column);
1724
+ if (cost === void 0) {
1725
+ cost = 3 * nestingOf(program) + 16;
1726
+ this.#cost.set(column, cost);
1411
1727
  }
1412
- const program = this.#columns.get(column);
1413
- if (program === void 0) return fail(vexError("unbound", `the sheet has no column "${column}"`, {
1414
- origin: key,
1415
- focus: key
1416
- }));
1728
+ return cost;
1729
+ }
1730
+ /** This method puts a new cell on the stack of the search. */
1731
+ #start(column, key) {
1417
1732
  const n = this.#next++;
1418
1733
  const visit = {
1419
- id,
1734
+ id: idOf(column, key),
1420
1735
  column,
1421
1736
  key,
1422
1737
  index: n,
1423
1738
  low: n,
1424
1739
  reread: false,
1425
- result: cycleError(column, key)
1740
+ result: cycleError(column, key),
1741
+ paused: false,
1742
+ need: void 0
1426
1743
  };
1427
- this.#visits.set(id, visit);
1744
+ this.#visits.set(visit.id, visit);
1428
1745
  this.#stack.push(visit);
1746
+ return visit;
1747
+ }
1748
+ /** This method evaluates the formula of a cell once. When the evaluation pauses, the result of the cell does not change. */
1749
+ #evaluate(visit, program) {
1750
+ const caller = this.#top;
1751
+ const cost = this.#costOf(visit.column, program);
1752
+ visit.paused = false;
1753
+ visit.need = void 0;
1429
1754
  this.#top = visit;
1430
- visit.result = evaluate(program, {
1755
+ this.#used += cost;
1756
+ const result = evaluate(program, {
1431
1757
  ...this.#opts,
1432
- origin: key
1758
+ origin: visit.key
1433
1759
  });
1760
+ this.#used -= cost;
1434
1761
  this.#top = caller;
1762
+ if (!visit.paused) visit.result = result;
1763
+ }
1764
+ /** This method ends a cell whose evaluation did not pause: it finishes its component, or it gives its low to the caller. */
1765
+ #end(visit, caller) {
1435
1766
  if (visit.low === visit.index) this.#finish(visit);
1436
- else caller.low = Math.min(caller.low, visit.low);
1767
+ else if (caller !== void 0) caller.low = Math.min(caller.low, visit.low);
1768
+ }
1769
+ /** This method reads a cell from the formula of the cell at the top. */
1770
+ #read(column, key) {
1771
+ const id = idOf(column, key);
1772
+ const done = this.#done.get(id);
1773
+ if (done !== void 0) return done;
1774
+ const caller = this.#top;
1775
+ if (caller.paused) return cycleError(column, key);
1776
+ const seen = this.#visits.get(id);
1777
+ if (seen !== void 0) {
1778
+ caller.low = Math.min(caller.low, seen.index);
1779
+ seen.reread = true;
1780
+ return cycleError(column, key);
1781
+ }
1782
+ const program = this.#columns.get(column);
1783
+ if (program === void 0) return fail(vexError("unbound", `the sheet has no column "${column}"`, {
1784
+ origin: key,
1785
+ focus: key
1786
+ }));
1787
+ const visit = this.#start(column, key);
1788
+ if (this.#used + this.#costOf(column, program) > this.#budget) {
1789
+ caller.paused = true;
1790
+ caller.need = visit;
1791
+ return cycleError(column, key);
1792
+ }
1793
+ this.#evaluate(visit, program);
1794
+ if (visit.paused) {
1795
+ caller.paused = true;
1796
+ caller.need = visit;
1797
+ return cycleError(column, key);
1798
+ }
1799
+ this.#end(visit, caller);
1800
+ return this.#done.get(id) ?? cycleError(column, key);
1801
+ }
1802
+ /** This method evaluates a cell from the top level. The cells that pause go on a list, not on the call stack. */
1803
+ #drive(column, key) {
1804
+ const id = idOf(column, key);
1805
+ const done = this.#done.get(id);
1806
+ if (done !== void 0) return done;
1807
+ if (!this.#columns.has(column)) return fail(vexError("unbound", `the sheet has no column "${column}"`, {
1808
+ origin: key,
1809
+ focus: key
1810
+ }));
1811
+ const work = [this.#start(column, key)];
1812
+ for (let visit = work.at(-1); visit !== void 0; visit = work.at(-1)) {
1813
+ const program = this.#columns.get(visit.column);
1814
+ /* v8 ignore next -- @preserve: a visit exists only for a column with a program */
1815
+ if (program === void 0) break;
1816
+ this.#evaluate(visit, program);
1817
+ if (visit.paused) {
1818
+ for (let need = visit.need; need !== void 0; need = need.need) work.push(need);
1819
+ continue;
1820
+ }
1821
+ work.pop();
1822
+ this.#end(visit, work.at(-1));
1823
+ }
1437
1824
  return this.#done.get(id) ?? cycleError(column, key);
1438
1825
  }
1439
1826
  /** This method takes the component of `root` from the stack, and sets the final result of each of its cells. */
1440
1827
  #finish(root) {
1441
- const members = this.#stack.splice(this.#stack.indexOf(root));
1828
+ const members = this.#stack.splice(this.#stack.lastIndexOf(root));
1442
1829
  const cyclic = members.length > 1 || root.reread;
1443
1830
  for (const m of members) {
1444
1831
  this.#visits.delete(m.id);
@@ -1463,13 +1850,10 @@ var SheetRun = class {
1463
1850
  }
1464
1851
  /**
1465
1852
  * This method evaluates the column `column` at each key before `key`, in key order. A recurrence over the keys,
1466
- * for example a running total, then reads finished cells and does not go deep into the call stack.
1853
+ * for example a running total, then reads finished cells.
1467
1854
  */
1468
1855
  warm(column, key) {
1469
- for (const k of this.#opts.space.keys) {
1470
- if (k === key) return;
1471
- this.cell(column, k);
1472
- }
1856
+ this.#warmTo(column, key);
1473
1857
  }
1474
1858
  };
1475
1859
  //#endregion
@@ -1526,14 +1910,7 @@ var ChainImpl = class ChainImpl {
1526
1910
  } });
1527
1911
  }
1528
1912
  #opts(k) {
1529
- const { env } = this.#s;
1530
- return {
1531
- space: env.space,
1532
- origin: k,
1533
- domains: env.domains,
1534
- ...env.options.fns === void 0 ? {} : { fns: env.options.fns },
1535
- ...env.options.extensions === void 0 ? {} : { extensions: env.options.extensions }
1536
- };
1913
+ return evalOptions(this.#s, k);
1537
1914
  }
1538
1915
  result(k) {
1539
1916
  return evaluate(this.#s.expr, this.#opts(k));
@@ -1590,6 +1967,12 @@ var ChainImpl = class ChainImpl {
1590
1967
  expr: app(name, this.#s.expr, ...args.map((a) => toExpr(a, this.#s.addr)))
1591
1968
  });
1592
1969
  }
1970
+ if(then, otherwise) {
1971
+ return new ChainImpl({
1972
+ ...this.#s,
1973
+ expr: app("if", this.#s.expr, toExpr(then, this.#s.addr), toExpr(otherwise, this.#s.addr))
1974
+ });
1975
+ }
1593
1976
  ifError(fallback) {
1594
1977
  return new ChainImpl({
1595
1978
  ...this.#s,
@@ -1649,7 +2032,7 @@ var ChainImpl = class ChainImpl {
1649
2032
  };
1650
2033
  return new ListChainImpl({
1651
2034
  ...this.#s,
1652
- expr: let_({ [name]: this.#s.expr }, each(axis, inner.program))
2035
+ expr: let_({ [name]: this.#s.expr }, each(axis, inner.program, this.#s.addr))
1653
2036
  });
1654
2037
  }
1655
2038
  others(body, opts) {
@@ -1677,6 +2060,17 @@ var ChainImpl = class ChainImpl {
1677
2060
  return this.#axis({ t: "siblings" }, body, opts);
1678
2061
  }
1679
2062
  };
2063
+ /** This function gives the options of an evaluation of a chain or a list chain at the origin `k`. */
2064
+ function evalOptions(s, k) {
2065
+ const { env } = s;
2066
+ return {
2067
+ space: env.space,
2068
+ origin: k,
2069
+ domains: env.domains,
2070
+ ...env.options.fns === void 0 ? {} : { fns: env.options.fns },
2071
+ ...env.options.extensions === void 0 ? {} : { extensions: env.options.extensions }
2072
+ };
2073
+ }
1680
2074
  var ListChainImpl = class {
1681
2075
  kind = "vex.list-chain";
1682
2076
  #s;
@@ -1687,7 +2081,11 @@ var ListChainImpl = class {
1687
2081
  return this.#s.expr;
1688
2082
  }
1689
2083
  #op(op, extra, opts) {
1690
- const args = opts?.strict === true ? [...extra, lit({ strict: true })] : extra;
2084
+ const options = {
2085
+ ...opts?.strict === true ? { strict: true } : {},
2086
+ ...opts?.domain === void 0 ? {} : { domain: opts.domain }
2087
+ };
2088
+ const args = Object.keys(options).length > 0 ? [...extra, lit(options)] : extra;
1691
2089
  return new ChainImpl({
1692
2090
  ...this.#s,
1693
2091
  expr: app(op, this.#s.expr, ...args)
@@ -1720,12 +2118,27 @@ var ListChainImpl = class {
1720
2118
  values(opts) {
1721
2119
  return this.#op("values", [], opts);
1722
2120
  }
2121
+ keys(opts) {
2122
+ return this.#op("keys", [], opts);
2123
+ }
2124
+ errors() {
2125
+ return this.#op("errors", []);
2126
+ }
1723
2127
  first(opts) {
1724
2128
  return this.#op("first", [], opts);
1725
2129
  }
1726
2130
  reduce(op, opts) {
1727
2131
  return this.#op("reduce", [lit(op)], opts);
1728
2132
  }
2133
+ result(k) {
2134
+ return evaluate(this.#s.expr, evalOptions(this.#s, k));
2135
+ }
2136
+ at(k) {
2137
+ return toOptional(this.result(k));
2138
+ }
2139
+ explain(k) {
2140
+ return explain(this.#s.expr, evalOptions(this.#s, k));
2141
+ }
1729
2142
  };
1730
2143
  var RootImpl = class {
1731
2144
  #env;
@@ -1845,6 +2258,6 @@ function vex(...domains) {
1845
2258
  };
1846
2259
  }
1847
2260
  //#endregion
1848
- export { CELL_KIND, LIST_OPS, SPECIAL_FORMS, SheetRun, app, applyMove, axes, axisTargets, cell, chainResult, children, codeOf, compile, defineDomain, deps, describeType, domainOf, each, evaluate, explain, ext, fail, findMethod, formatError, formatTrace, getOr, index, isAxis, isExpr, isListOp, isMove, isNone, isOpName, isSome, isVexList, key, labelOf, let_, liftsAt, lit, mapResult, monoids, none, offset, ok, origin, other, parent, parse, previewValue, rec, ref, resolveAddr, resolveOp, serialize, sizeOf, some, space, toOptional, toPath, traversal, v, vex, vexError, vexList };
2261
+ export { CELL_KIND, LIST_OPS, MAX_NESTING, SPECIAL_FORMS, SheetRun, app, applyMove, axes, axisTargets, cell, chainResult, children, codeOf, compile, defineDomain, deps, describeType, domainOf, each, evaluate, explain, ext, fail, findMethod, formatError, formatTrace, getOr, index, isAxis, isDepthError, isExpr, isListOp, isMove, isNone, isOpName, isSome, isStackOverflow, isVexList, key, labelOf, let_, liftsAt, lit, mapResult, monoids, nestingOf, none, offset, ok, origin, other, parent, parse, previewValue, rec, ref, resolveAddr, resolveOp, serialize, sizeOf, some, space, toOptional, toPath, traversal, v, vex, vexError, vexList };
1849
2262
 
1850
2263
  //# sourceMappingURL=index.js.map