@mark1russell7/vex 0.13.4 → 0.15.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
@@ -84,7 +84,38 @@ function vexError(kind, message, details = {}) {
84
84
  }
85
85
  /** This function gives a short text for an error, for example `#REF! unknown-key: there is no key "Z"`. */
86
86
  const formatError = (e) => `${e.code} ${e.kind}: ${e.message}`;
87
+ // src/item-names.ts
88
+ /**
89
+ * The check of the names `as` of a loop over the axis `list` (AXIS.LIST.SCOPE). The package index does not export this
90
+ * module: `isExpr`, `shapeError` and `fromDocument` use it, so an expression and a document follow the same rule.
91
+ */
92
+ const isObject$1 = (u) => typeof u === "object" && u !== null;
93
+ /** This function tells if the base axis of an axis is `list`, through `where` and `reverse`. It uses a loop, not recursion. */
94
+ function isListAxis(u) {
95
+ let x = u;
96
+ while (isObject$1(x) && x["t"] === "where") x = x["axis"];
97
+ if (isObject$1(x) && x["t"] === "reverse") x = x["axis"];
98
+ return isObject$1(x) && x["t"] === "list";
99
+ }
100
+ /**
101
+ * This function gives the reason that the names `as` of a loop are not valid, or `undefined` for valid names or no
102
+ * names (AXIS.LIST.SCOPE). The names are one or two distinct texts, the axis is `list`, and no name is a name of `init`.
103
+ */
104
+ function itemNamesError(u) {
105
+ const as = u["as"];
106
+ if (as === void 0) return void 0;
107
+ if (!Array.isArray(as) || as.length === 0 || as.length > 2 || !as.every((n) => typeof n === "string")) return "\"as\" is a list of one or two names: the item, and then its index";
108
+ if (as[0] === as[1]) return `the two names of "as" are the same name "${String(as[0])}"`;
109
+ if (!isListAxis(u["axis"])) return "\"as\" needs the axis \"list\", also inside \"reverse\" and \"where\"";
110
+ const init = u["init"];
111
+ const clash = isObject$1(init) ? as.find((n) => Object.hasOwn(init, n)) : void 0;
112
+ return clash === void 0 ? void 0 : `the name "${clash}" of "as" is a name of "init" too`;
113
+ }
87
114
  // src/ir.ts
115
+ /**
116
+ * The expression IR of Vex. It is plain JSON data. Its first three kinds (`lit`, `ref`, `app`) have the same
117
+ * shape as the expressions of `render`.
118
+ */
88
119
  /** The largest number of steps of `iterate` (ITERATE.LIMIT). */
89
120
  const MAX_ITERATIONS = 1e5;
90
121
  /** This function makes a literal. */
@@ -130,38 +161,47 @@ const rec = (fields) => ({
130
161
  });
131
162
  /**
132
163
  * This function evaluates `body` once for each target of `axis`. The result is a list. With `at`, the axis finds its
133
- * targets from the key of that address, not from the focus.
164
+ * targets from the key of that address, not from the focus. With `as`, the body of a loop over the axis `list` reads the
165
+ * value of each item and its position by these names (AXIS.LIST.ITEM, AXIS.LIST.INDEX).
134
166
  */
135
- function each(axis, body, at) {
167
+ function each(axis, body, at, as) {
168
+ const named = as === void 0 ? {} : { as };
136
169
  return at === void 0 || at.length === 0 ? {
137
170
  tag: "each",
138
171
  axis,
139
- body
172
+ body,
173
+ ...named
140
174
  } : {
141
175
  tag: "each",
142
176
  axis,
143
177
  body,
144
- at
178
+ at,
179
+ ...named
145
180
  };
146
181
  }
147
182
  /**
148
183
  * This function makes a fold: a step at each target of `axis`, in order. `init` gives the names and their first
149
- * values, and `step` gives the next values. `result` gives the value from the last values (LOOP.NAMES, FOLD.ORDER).
184
+ * values, and `step` gives the next values. `result` gives the value from the last values (LOOP.NAMES, FOLD.ORDER). With
185
+ * `as`, the steps of a fold over the axis `list` read the value of each item and its position by these names
186
+ * (AXIS.LIST.ITEM, AXIS.LIST.INDEX).
150
187
  */
151
- function fold(axis, init, step, result, at) {
188
+ function fold(axis, init, step, result, at, as) {
189
+ const named = as === void 0 ? {} : { as };
152
190
  return at === void 0 || at.length === 0 ? {
153
191
  tag: "fold",
154
192
  axis,
155
193
  init,
156
194
  step,
157
- result
195
+ result,
196
+ ...named
158
197
  } : {
159
198
  tag: "fold",
160
199
  axis,
161
200
  init,
162
201
  step,
163
202
  result,
164
- at
203
+ at,
204
+ ...named
165
205
  };
166
206
  }
167
207
  /**
@@ -369,6 +409,8 @@ function shapeError(u) {
369
409
  if (bad.axis) return "the expression has an axis that is not valid";
370
410
  if (typeof tag === "string" && !TAGS.has(tag)) return `the expression has a node with the tag "${tag}", and this version of Vex does not know it`;
371
411
  if (tag === "fn") return "the expression has a function outside the bindings of a let, or a function with parameters that are not distinct names";
412
+ const named = tag === "each" || tag === "fold" ? itemNamesError(bad.u) : void 0;
413
+ if (named !== void 0) return `the expression has a node "${String(tag)}" with names "as" that are not valid: ${named}`;
372
414
  return typeof tag === "string" ? `the expression has a node "${tag}" with parts that are not valid` : "the expression has a part that is not a node";
373
415
  }
374
416
  /**
@@ -479,7 +521,7 @@ function badPart(todo, whole) {
479
521
  break;
480
522
  case "each": {
481
523
  const at = addrParts(u["at"], moveNumber);
482
- if (at === void 0) return item;
524
+ if (at === void 0 || itemNamesError(u) !== void 0) return item;
483
525
  push(true, [u["axis"]]);
484
526
  push(false, [u["body"], ...at]);
485
527
  break;
@@ -487,7 +529,7 @@ function badPart(todo, whole) {
487
529
  case "fold": {
488
530
  const at = addrParts(u["at"], moveNumber);
489
531
  const names = loopParts(u);
490
- if (at === void 0 || names === void 0) return item;
532
+ if (at === void 0 || names === void 0 || itemNamesError(u) !== void 0) return item;
491
533
  push(true, [u["axis"]]);
492
534
  push(false, [...names, ...at]);
493
535
  break;
@@ -1023,14 +1065,19 @@ function domainOf(domains, value) {
1023
1065
  }
1024
1066
  /** This function tells if the `liftScalar` setting lifts the argument at `index`. */
1025
1067
  const liftsAt = (lift, index) => lift === true || Array.isArray(lift) && lift[index] === true;
1068
+ // src/checked.ts
1069
+ /**
1070
+ * The cache of the lists that passed the check of LIST.SHAPE. `isVexList` adds each frozen list that passes its check.
1071
+ * The interpreter adds each list that it makes from the items of such lists, because these items passed the check.
1072
+ * The package index does not export this module.
1073
+ */
1074
+ const CHECKED = /* @__PURE__ */ new WeakSet();
1026
1075
  // src/list.ts
1027
1076
  /** This function makes a list. */
1028
1077
  const vexList = (items) => Object.freeze({
1029
1078
  kind: "vex.list",
1030
1079
  items: Object.freeze([...items])
1031
1080
  });
1032
- /** The lists that passed the check of `isVexList` and cannot change. Each list of `vexList` is frozen. */
1033
- const CHECKED = /* @__PURE__ */ new WeakSet();
1034
1081
  /** This function tells if a value is an error value: a text `code`, `kind` and `message`, and a `path` (LIST.SHAPE). */
1035
1082
  const isErrorValue = (u) => {
1036
1083
  if (typeof u !== "object" || u === null) return false;
@@ -1085,7 +1132,10 @@ const LIST_OPS = /* @__PURE__ */ new Set([
1085
1132
  "flat",
1086
1133
  "without",
1087
1134
  "get",
1088
- "indexOf"
1135
+ "indexOf",
1136
+ "distinct",
1137
+ "group",
1138
+ "join"
1089
1139
  ]);
1090
1140
  /** This function tells if a name is the name of a core list op. */
1091
1141
  const isListOp = (op) => LIST_OPS.has(op);
@@ -1331,6 +1381,12 @@ const LOOP_SCOPE = [{
1331
1381
  ["result"]
1332
1382
  ]
1333
1383
  }];
1384
+ /** The names of the items of a loop over the axis `list`: one or two distinct texts (AXIS.LIST.SCOPE). */
1385
+ const ITEM_NAMES = {
1386
+ shape: "list",
1387
+ item: { shape: "text" },
1388
+ distinct: true
1389
+ };
1334
1390
  /**
1335
1391
  * This function gives the world of Vex. The module uses it one time, and the annotation `__PURE__` lets a bundler
1336
1392
  * remove the world from a program that does not use it.
@@ -1411,15 +1467,21 @@ function worldOfVex() {
1411
1467
  verbs: { eval: "vex.each" },
1412
1468
  parts: closed({
1413
1469
  axis: AXIS,
1470
+ as: ITEM_NAMES,
1414
1471
  body: TERM,
1415
1472
  at: ADDRESS
1416
1473
  }, ["axis", "body"]),
1474
+ scope: [{
1475
+ names: { listAt: ["as"] },
1476
+ in: [["body"]]
1477
+ }],
1417
1478
  summary: "The body at each target of an axis: a list."
1418
1479
  },
1419
1480
  fold: {
1420
1481
  verbs: { eval: "vex.fold" },
1421
1482
  parts: closed({
1422
1483
  axis: AXIS,
1484
+ as: ITEM_NAMES,
1423
1485
  init: NAMES,
1424
1486
  step: NAMES,
1425
1487
  result: TERM,
@@ -1430,7 +1492,10 @@ function worldOfVex() {
1430
1492
  "step",
1431
1493
  "result"
1432
1494
  ]),
1433
- scope: LOOP_SCOPE,
1495
+ scope: [...LOOP_SCOPE, {
1496
+ names: { listAt: ["as"] },
1497
+ in: [["step", "*"]]
1498
+ }],
1434
1499
  summary: "A step at each target of an axis, in order, and a result."
1435
1500
  },
1436
1501
  iterate: {
@@ -1722,7 +1787,12 @@ const axisEvaluator = ({ typePath, value, context }) => {
1722
1787
  if (!r.ok) return r;
1723
1788
  const items = asList(r.value, missing);
1724
1789
  if (items === void 0) return failed("kind-mismatch", `the axis "list" needs a list, not a ${describe(r.value)}`);
1725
- return ok$1(items.items.map(({ key, result }) => result.ok ? { key } : {
1790
+ let index = 0;
1791
+ return ok$1(items.items.map(({ key, result }) => result.ok ? {
1792
+ key,
1793
+ value: result.value,
1794
+ index: index++
1795
+ } : {
1726
1796
  key,
1727
1797
  error: result.error
1728
1798
  }));
@@ -1779,7 +1849,7 @@ function whereTargets(base, test, ctx, from) {
1779
1849
  key: t.key,
1780
1850
  error: toVexError(r.error)
1781
1851
  });
1782
- else if (r.value === true) out.push({ key: t.key });
1852
+ else if (r.value === true) out.push(t);
1783
1853
  else if (r.value !== false) out.push({
1784
1854
  key: t.key,
1785
1855
  error: vexError("kind-mismatch", `the test of "where" gave a ${typeof r.value}, not a boolean`)
@@ -1834,6 +1904,20 @@ function bindAll(record, ctx, names) {
1834
1904
  for (const [name, v] of values) setName(out, name, v);
1835
1905
  return ok$1(out);
1836
1906
  }
1907
+ /**
1908
+ * This function adds the names `as` of a loop to the names of a body or of a step. The first name holds the value of
1909
+ * the item, and the second its index (AXIS.LIST.ITEM, AXIS.LIST.INDEX). A loop without `as` keeps its names.
1910
+ */
1911
+ function withItem$1(names, as, t) {
1912
+ if (as === void 0) return names;
1913
+ const out = { ...names };
1914
+ const [item, index] = as;
1915
+ setName(out, item, t.value);
1916
+ if (index !== void 0) setName(out, index, t.index);
1917
+ return out;
1918
+ }
1919
+ /** This function gives the names `as` of a loop, or `undefined` (AXIS.LIST.SCOPE). */
1920
+ const itemNamesOf = (value) => value.as;
1837
1921
  /** The evaluators of the loops: each, fold and iterate (LOOP.NAMES, FOLD.ORDER, ITERATE.LIMIT). */
1838
1922
  const LOOPS = {
1839
1923
  "vex.each": ({ value, context }) => {
@@ -1841,12 +1925,14 @@ const LOOPS = {
1841
1925
  if (!found.ok) return found;
1842
1926
  const { axis, from, targets } = found.value;
1843
1927
  const body = partAt(value, "body");
1844
- const items = targets.map(({ key, error }) => ({
1845
- key,
1846
- result: error === void 0 ? toVexResult(body.evaluate({
1928
+ const as = itemNamesOf(value);
1929
+ const items = targets.map((t) => ({
1930
+ key: t.key,
1931
+ result: t.error === void 0 ? toVexResult(body.evaluate({
1847
1932
  ...context,
1848
- self: placeOf(axis, from, key)
1849
- })) : fail(error)
1933
+ self: placeOf(axis, from, t.key),
1934
+ names: withItem$1(context.names, as, t)
1935
+ })) : fail(t.error)
1850
1936
  }));
1851
1937
  return ok$1(vexList(items));
1852
1938
  },
@@ -1858,15 +1944,16 @@ const LOOPS = {
1858
1944
  const found = targetsOf(value, context);
1859
1945
  if (!found.ok) return found;
1860
1946
  const { axis, from, targets } = found.value;
1861
- for (const { key, error } of targets) {
1862
- if (error !== void 0) return {
1947
+ const as = itemNamesOf(value);
1948
+ for (const t of targets) {
1949
+ if (t.error !== void 0) return {
1863
1950
  ok: false,
1864
- error: toKernelError(error)
1951
+ error: toKernelError(t.error)
1865
1952
  };
1866
1953
  const next = bindAll(step, {
1867
1954
  ...context,
1868
- self: placeOf(axis, from, key),
1869
- names
1955
+ self: placeOf(axis, from, t.key),
1956
+ names: withItem$1(names, as, t)
1870
1957
  }, names);
1871
1958
  if (!next.ok) return next;
1872
1959
  names = next.value;
@@ -2009,7 +2096,9 @@ const WITH_ARGUMENT$1 = /* @__PURE__ */ new Set([
2009
2096
  "append",
2010
2097
  "without",
2011
2098
  "get",
2012
- "indexOf"
2099
+ "indexOf",
2100
+ "group",
2101
+ "join"
2013
2102
  ]);
2014
2103
  /**
2015
2104
  * This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
@@ -2037,10 +2126,33 @@ function flat(vs, strict) {
2037
2126
  }
2038
2127
  return vexList(out);
2039
2128
  }
2129
+ /**
2130
+ * This function gives the groups of `group(list, keys)` (LIST.GROUP). The item at a position has the key at the same
2131
+ * position. A pair with an error item or an error key is not in a group.
2132
+ */
2133
+ function group(items, keys, strict) {
2134
+ goodOf(items, strict);
2135
+ const list = asList(keys, missing);
2136
+ if (list === void 0) return stop("kind-mismatch", `"group" needs a list of keys, not a ${describe(keys)}`);
2137
+ goodOf(list.items, strict);
2138
+ if (list.items.length !== items.length) return stop("kind-mismatch", "\"group\" needs one key for each item");
2139
+ const groups = /* @__PURE__ */ new Map();
2140
+ items.forEach((it, i) => {
2141
+ const k = list.items[i].result;
2142
+ if (!it.result.ok || !k.ok) return;
2143
+ if (typeof k.value !== "string") stop("kind-mismatch", "\"group\" needs text keys");
2144
+ groups.set(k.value, [...groups.get(k.value) ?? [], it]);
2145
+ });
2146
+ return vexList([...groups].map(([key, g]) => ({
2147
+ key,
2148
+ result: ok(vexList(g))
2149
+ })));
2150
+ }
2040
2151
  /** This function applies a list op (LIST.*). The error items are skipped, except with `{ strict: true }`, and except `#DEPTH!`. */
2041
2152
  function listOp(op, items, rest, domains) {
2042
2153
  const o = WITH_ARGUMENT$1.has(op) ? rest[1] : rest[0];
2043
2154
  const strict = o?.strict === true;
2155
+ if (op === "group") return group(items, rest[0], strict);
2044
2156
  const good = goodOf(items, strict);
2045
2157
  const vs = good.map((it) => it.result.ok ? it.result.value : void 0);
2046
2158
  const nums = () => vs.every((x) => typeof x === "number") ? vs : stop("kind-mismatch", `"${op}" needs numbers`);
@@ -2082,6 +2194,16 @@ function listOp(op, items, rest, domains) {
2082
2194
  const i = good.findIndex((it) => it.key === key);
2083
2195
  return i >= 0 ? vs[i] : stop("missing-field", `the list has no item with the key ${JSON.stringify(key)}`);
2084
2196
  }
2197
+ case "distinct": {
2198
+ if (!vs.every(isIndexValue)) return stop("kind-mismatch", "\"distinct\" needs numbers, texts or booleans");
2199
+ const keep = vs.map((x, i) => vs.indexOf(x) === i || Number.isNaN(x));
2200
+ return vexList(good.filter((_it, i) => keep[i]));
2201
+ }
2202
+ case "join": {
2203
+ const sep = rest[0];
2204
+ if (typeof sep !== "string") return stop("kind-mismatch", `"join" needs a text separator, not a ${describe(sep)}`);
2205
+ return vs.every((x) => typeof x === "string") ? vs.join(sep) : stop("kind-mismatch", "\"join\" needs texts");
2206
+ }
2085
2207
  case "indexOf": {
2086
2208
  const x = rest[0];
2087
2209
  if (!isIndexValue(x)) return stop("kind-mismatch", `"indexOf" needs a number, a text or a boolean, not a ${describe(x)}`);
@@ -2330,6 +2452,8 @@ const envelope = (e) => ({
2330
2452
  t: "envelope",
2331
2453
  e
2332
2454
  });
2455
+ /** This function gives the field `as` of a loop: a new list of its names, or no field (AXIS.LIST.SCOPE). */
2456
+ const itemsOf = (as) => as === void 0 ? {} : { as: [...as] };
2333
2457
  /** This function gives a record from names and the documents of their values, from an index of the documents. */
2334
2458
  function namesOf(names, docs, from) {
2335
2459
  const out = {};
@@ -2472,12 +2596,15 @@ var Writer = class {
2472
2596
  const axis = docs[0];
2473
2597
  const body = docs[1];
2474
2598
  const address = at.make(docs.slice(2));
2599
+ const as = itemsOf(e.as);
2475
2600
  return this.#keep(typed("each", reads ? {
2476
2601
  body,
2477
2602
  axis,
2603
+ ...as,
2478
2604
  ...address
2479
2605
  } : {
2480
2606
  axis,
2607
+ ...as,
2481
2608
  body,
2482
2609
  ...address
2483
2610
  }), e);
@@ -2508,13 +2635,16 @@ var Writer = class {
2508
2635
  };
2509
2636
  const result = docs[after];
2510
2637
  const address = at.make(docs.slice(after + 1));
2638
+ const as = itemsOf(e.as);
2511
2639
  return this.#keep(typed("fold", reads ? {
2512
2640
  ...names,
2513
2641
  axis,
2642
+ ...as,
2514
2643
  ...address,
2515
2644
  result
2516
2645
  } : {
2517
2646
  axis,
2647
+ ...as,
2518
2648
  ...names,
2519
2649
  result,
2520
2650
  ...address
@@ -2656,18 +2786,20 @@ function writeDocument(e, opts) {
2656
2786
  * | `fn` | `{ "type": "fn", "value": { "params", "body" } }` |
2657
2787
  * | `call` | `{ "type": "call", "value": { "fn": { "type": "ref", "value": ["names", name] }, "args" } }` |
2658
2788
  * | `rec` | `{ "type": "record", "value": { ...fields } }` |
2659
- * | `each` | `{ "type": "each", "value": { "axis", "body", "at"? } }` |
2660
- * | `fold` | `{ "type": "fold", "value": { "axis", "init", "step", "result", "at"? } }` |
2789
+ * | `each` | `{ "type": "each", "value": { "axis", "as"?, "body", "at"? } }` |
2790
+ * | `fold` | `{ "type": "fold", "value": { "axis", "as"?, "init", "step", "result", "at"? } }` |
2661
2791
  * | `iterate` | `{ "type": "iterate", "value": { "limit", "init", "step", "until"?, "result" } }` |
2662
2792
  * | `ext` | `{ "type": ["ext", ...keys], "value": data }` |
2663
2793
  * | a move | `{ "type": ["moves", kind], "value": v }` |
2664
2794
  * | an axis | `{ "type": ["axes", name], "value": { ...parameters } }` |
2665
2795
  *
2666
2796
  * The address `at` of `each` and `fold` is a reference from `self` with moves only. An empty address is no address.
2797
+ * The field `as` of `each` and `fold` names the item of a loop over the axis `list`, and then its index (AXIS.LIST.SCOPE).
2667
2798
  *
2668
2799
  * The kernel checks a document by the contracts of `VEX_WORLD` (DOC.CHECK). A contract gives the shape of a kind, the
2669
2800
  * data of its fields and the kinds of each position. Then `fromDocument` reads the expression. It checks only the grammar
2670
- * of Vex: the steps of a reference, the address, the function of a call and the names of a loop.
2801
+ * of Vex: the steps of a reference, the address, the function of a call and the names of a loop. It also checks the
2802
+ * names of the items.
2671
2803
  */
2672
2804
  /** The stop of a reading. The functions of this module throw it, and the top of the reading gives its error. */
2673
2805
  var Stop = class {
@@ -2775,10 +2907,16 @@ var Reader = class {
2775
2907
  return call(name, ...f["args"].map((x, i) => this.term(x, into(into(at, "args"), i))));
2776
2908
  }
2777
2909
  case "record": return rec(this.#names(u.value, at));
2778
- 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")));
2910
+ case "each": {
2911
+ const axis = this.#axis(f["axis"], into(at, "axis"));
2912
+ const as = this.#items(f, axis, at);
2913
+ return each(axis, this.term(f["body"], into(at, "body")), this.#address(f["at"], into(at, "at")), as);
2914
+ }
2779
2915
  case "fold": {
2780
2916
  const [init, step] = this.#loop(f, at);
2781
- 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")));
2917
+ const axis = this.#axis(f["axis"], into(at, "axis"));
2918
+ const as = this.#items(f, axis, at);
2919
+ return fold(axis, init, step, this.term(f["result"], into(at, "result")), this.#address(f["at"], into(at, "at")), as);
2782
2920
  }
2783
2921
  default: {
2784
2922
  const [init, step] = this.#loop(f, at);
@@ -2822,6 +2960,18 @@ var Reader = class {
2822
2960
  const extra = Object.keys(step).find((name) => !Object.hasOwn(init, name));
2823
2961
  return extra === void 0 ? [init, step] : bad(into(into(at, "step"), extra), `the name "${extra}" of step is not a name of init`);
2824
2962
  }
2963
+ /**
2964
+ * This method reads the names `as` of a loop (AXIS.LIST.SCOPE). The contract gives a list of distinct texts. The
2965
+ * grammar of Vex needs one or two names, the axis `list` and no name of `init`.
2966
+ */
2967
+ #items(f, axis, at) {
2968
+ const reason = itemNamesError({
2969
+ as: f["as"],
2970
+ axis,
2971
+ init: f["init"]
2972
+ });
2973
+ return reason === void 0 ? f["as"] : bad(into(at, "as"), reason);
2974
+ }
2825
2975
  /** This method reads a reference: the fields of `self` after its moves, or a name of `names` (DOC.REF). */
2826
2976
  #ref(path, where) {
2827
2977
  const [root, ...steps] = path;
@@ -2892,6 +3042,33 @@ var Reader = class {
2892
3042
  }
2893
3043
  };
2894
3044
  // src/evaluate.ts
3045
+ /**
3046
+ * A scope: the names of one `let`, a function, an item or a loop. It is in front of the outer names, and it does not
3047
+ * copy them. A name of a scope hides an outer name of the same name. The names of one
3048
+ * scope are distinct (FN.BIND, LOOP.NAMES, AXIS.LIST.SCOPE).
3049
+ */
3050
+ var Scope = class Scope {
3051
+ #outer;
3052
+ #names;
3053
+ #values;
3054
+ constructor(outer, names, values) {
3055
+ this.#outer = outer;
3056
+ this.#names = names;
3057
+ this.#values = values;
3058
+ }
3059
+ get(name) {
3060
+ const at = this.#names.indexOf(name);
3061
+ return at >= 0 ? this.#values[at] : this.#outer.get(name);
3062
+ }
3063
+ /** This method gives a copy of this scope with the values `values` at the positions `at` (LOOP.NAMES). */
3064
+ with(at, values) {
3065
+ const next = [...this.#values];
3066
+ at.forEach((position, i) => {
3067
+ next[position] = values[i];
3068
+ });
3069
+ return new Scope(this.#outer, this.#names, next);
3070
+ }
3071
+ };
2895
3072
  /** The names of the special forms. Their arguments are not evaluated before the call. */
2896
3073
  const SPECIAL_FORMS = /* @__PURE__ */ new Set([
2897
3074
  "if",
@@ -3013,16 +3190,50 @@ function explain(expr, opts) {
3013
3190
  }
3014
3191
  /** This function gives the axis inside the `where` axes of an axis. */
3015
3192
  const baseAxis = (a) => a.t === "where" ? baseAxis(a.axis) : a;
3193
+ /** This function evaluates the nodes in order. The first error stops it and is the result. */
3194
+ function allValues(ns, f, c) {
3195
+ const values = [];
3196
+ for (const n of ns) {
3197
+ const r = n(f, c);
3198
+ if (!r.ok) return r;
3199
+ values.push(r);
3200
+ }
3201
+ return ok(values);
3202
+ }
3203
+ /** The primitive types of KIND.PRIMITIVE. */
3204
+ const PRIMITIVE_TYPES = [
3205
+ "number",
3206
+ "string",
3207
+ "boolean"
3208
+ ];
3209
+ /** The spec of an op without an entry in the op table of a domain with `methods: "all"`. */
3210
+ const NO_SPEC = Object.freeze({});
3211
+ /**
3212
+ * This function adds the names `as` of a loop to the names of a body or of a step. The first name holds the value of
3213
+ * the item, and the second its index (AXIS.LIST.ITEM, AXIS.LIST.INDEX). A loop without `as` keeps its names.
3214
+ */
3215
+ function withItem(env, as, t) {
3216
+ return as === void 0 ? env : new Scope(env, as, [ok(t.value), ok(t.index)]);
3217
+ }
3016
3218
  var Compiler = class {
3017
3219
  #domains;
3018
3220
  #fns;
3019
3221
  #extensions;
3020
3222
  /** The index of the keys of each list that `get` read (LIST.GET). A list does not change, so its index stays right. */
3021
3223
  #keyIndex = /* @__PURE__ */ new WeakMap();
3224
+ /**
3225
+ * The domains that can accept a value of each primitive type, in order (KIND.PRIMITIVE). These are the domains of
3226
+ * that type and the domains without a primitive type.
3227
+ */
3228
+ #ofType = /* @__PURE__ */ new Map();
3229
+ /** The domains without a primitive type. Only they can accept a value of another type, for example an object. */
3230
+ #open;
3022
3231
  constructor(opts) {
3023
3232
  this.#domains = opts.domains ?? [];
3024
3233
  this.#fns = opts.fns;
3025
3234
  this.#extensions = opts.extensions;
3235
+ this.#open = this.#domains.filter((d) => d.primitive === void 0);
3236
+ for (const t of PRIMITIVE_TYPES) this.#ofType.set(t, this.#domains.filter((d) => d.primitive === void 0 || d.primitive === t));
3026
3237
  }
3027
3238
  #err(kind, message, f, path, extra = {}) {
3028
3239
  return fail(vexError(kind, message, {
@@ -3044,7 +3255,10 @@ var Compiler = class {
3044
3255
  #fill(values, f, path) {
3045
3256
  const [n, value] = values;
3046
3257
  if (!isFillCount(n)) return this.#err("kind-mismatch", `"fill" needs a whole number from 0 to 100000, not ${describeType(n)}`, f, path, { op: "fill" });
3047
- return value === void 0 ? this.#err("bad-expression", "\"fill\" needs argument 2", f, path, { op: "fill" }) : ok(fillList(n, value));
3258
+ if (value === void 0) return this.#err("bad-expression", "\"fill\" needs argument 2", f, path, { op: "fill" });
3259
+ const list = fillList(n, value);
3260
+ CHECKED.add(list);
3261
+ return ok(list);
3048
3262
  }
3049
3263
  #emit(c, info, f, result, reads) {
3050
3264
  if (c.trace !== void 0) {
@@ -3085,14 +3299,15 @@ var Compiler = class {
3085
3299
  case "fn": return this.#fn(e, path);
3086
3300
  case "call": return this.#callFn(e, info);
3087
3301
  case "let": {
3088
- const binds = Object.entries(e.bind).map(([name, be], i) => [name, this.node(be, [...path, i])]);
3302
+ const names = Object.keys(e.bind);
3303
+ const binds = this.#nodes(Object.values(e.bind), path);
3089
3304
  const body = this.node(e.body, [...path, binds.length]);
3090
3305
  return (f, c) => {
3091
- const env = new Map(f.env);
3092
- for (const [name, n] of binds) env.set(name, n(f, c));
3306
+ const values = [];
3307
+ for (const n of binds) values.push(n(f, c));
3093
3308
  return this.#emit(c, info, f, body({
3094
3309
  pos: f.pos,
3095
- env
3310
+ env: new Scope(f.env, names, values)
3096
3311
  }, c));
3097
3312
  };
3098
3313
  }
@@ -3148,11 +3363,11 @@ var Compiler = class {
3148
3363
  const callee = bound.value;
3149
3364
  if (!(callee instanceof Closure)) return this.#emit(c, info, f, this.#err("kind-mismatch", `the name "${e.fn}" is a value, not a function`, f, path));
3150
3365
  if (callee.params.length !== args.length) return this.#emit(c, info, f, this.#err("bad-expression", `the function "${e.fn}" takes ${String(callee.params.length)} arguments, not ${String(args.length)}`, f, path));
3151
- const env = new Map(callee.env);
3152
- callee.params.forEach((p, i) => env.set(p, args[i](f, c)));
3366
+ const values = [];
3367
+ for (const n of args) values.push(n(f, c));
3153
3368
  return this.#emit(c, info, f, callee.body({
3154
3369
  pos: f.pos,
3155
- env
3370
+ env: new Scope(callee.env, callee.params, values)
3156
3371
  }, c));
3157
3372
  };
3158
3373
  }
@@ -3296,7 +3511,8 @@ var Compiler = class {
3296
3511
  }
3297
3512
  const ts = targets(from, inner);
3298
3513
  if (!ts.ok) return this.#emit(c, info, f, ts);
3299
- const items = ts.value.map(({ key, test }) => {
3514
+ const items = ts.value.map((t) => {
3515
+ const { key, test } = t;
3300
3516
  if (test !== void 0 && !test.ok) return {
3301
3517
  key,
3302
3518
  result: test
@@ -3308,7 +3524,7 @@ var Compiler = class {
3308
3524
  origin: base.t === "table" ? key : f.pos.origin,
3309
3525
  focus: key
3310
3526
  },
3311
- env: f.env
3527
+ env: withItem(f.env, e.as, t)
3312
3528
  }, inner)
3313
3529
  };
3314
3530
  });
@@ -3320,28 +3536,18 @@ var Compiler = class {
3320
3536
  * functions give the first values, and the values after one step. The first error stops each of them.
3321
3537
  */
3322
3538
  #names(e, path) {
3323
- const inits = Object.entries(e.init).map(([name, x], i) => [name, this.node(x, [...path, i])]);
3324
- const steps = Object.entries(e.step).map(([name, x], i) => [name, this.node(x, [...path, inits.length + i])]);
3539
+ const names = Object.keys(e.init);
3540
+ const inits = this.#nodes(Object.values(e.init), path);
3541
+ const steps = Object.values(e.step).map((x, i) => this.node(x, [...path, inits.length + i]));
3542
+ const at = Object.keys(e.step).map((name) => names.indexOf(name));
3325
3543
  return {
3326
3544
  first: (f, c) => {
3327
- const env = new Map(f.env);
3328
- for (const [name, n] of inits) {
3329
- const r = n(f, c);
3330
- if (!r.ok) return r;
3331
- env.set(name, r);
3332
- }
3333
- return ok(env);
3545
+ const values = allValues(inits, f, c);
3546
+ return values.ok ? ok(new Scope(f.env, names, values.value)) : values;
3334
3547
  },
3335
- next: (f, c) => {
3336
- const values = [];
3337
- for (const [name, n] of steps) {
3338
- const r = n(f, c);
3339
- if (!r.ok) return r;
3340
- values.push([name, r]);
3341
- }
3342
- const env = new Map(f.env);
3343
- for (const [name, r] of values) env.set(name, r);
3344
- return ok(env);
3548
+ next: (f, c, scope) => {
3549
+ const values = allValues(steps, f, c);
3550
+ return values.ok ? ok(scope.with(at, values.value)) : values;
3345
3551
  }
3346
3552
  };
3347
3553
  }
@@ -3385,15 +3591,16 @@ var Compiler = class {
3385
3591
  }
3386
3592
  const ts = targets(from, inner);
3387
3593
  if (!ts.ok) return this.#emit(c, info, f, ts);
3388
- for (const { key, test } of ts.value) {
3594
+ for (const t of ts.value) {
3595
+ const { key, test } = t;
3389
3596
  if (test !== void 0 && !test.ok) return this.#emit(c, info, f, test);
3390
3597
  const after = names.next({
3391
3598
  pos: {
3392
3599
  origin: base.t === "table" ? key : f.pos.origin,
3393
3600
  focus: key
3394
3601
  },
3395
- env
3396
- }, inner);
3602
+ env: withItem(env, e.as, t)
3603
+ }, inner, env);
3397
3604
  if (!after.ok) return this.#emit(c, info, f, after);
3398
3605
  env = after.value;
3399
3606
  }
@@ -3434,7 +3641,7 @@ var Compiler = class {
3434
3641
  if (until !== void 0) return this.#emit(c, info, f, this.#err("limit", `"iterate" made its ${String(limit)} steps, and its test "until" is not true`, f, path));
3435
3642
  break;
3436
3643
  }
3437
- const after = names.next(frame, c);
3644
+ const after = names.next(frame, c, env);
3438
3645
  if (!after.ok) return this.#emit(c, info, f, after);
3439
3646
  env = after.value;
3440
3647
  }
@@ -3481,7 +3688,7 @@ var Compiler = class {
3481
3688
  key: t.key,
3482
3689
  test: r
3483
3690
  });
3484
- else if (r.value === true) out.push({ key: t.key });
3691
+ else if (r.value === true) out.push(t);
3485
3692
  else if (r.value !== false) out.push({
3486
3693
  key: t.key,
3487
3694
  test: this.#err("kind-mismatch", `the test of "where" gave a ${typeof r.value}, not a boolean`, at, testPath)
@@ -3501,7 +3708,12 @@ var Compiler = class {
3501
3708
  if (!r.ok) return r;
3502
3709
  const listed = asList(r.value, this.#missing(f, path));
3503
3710
  if (listed === void 0) return this.#err("kind-mismatch", `the axis "list" needs a list, not a ${describeType(r.value)}`, f, path);
3504
- const items = listed.items.map(({ key, result }) => result.ok ? { key } : {
3711
+ let index = 0;
3712
+ const items = listed.items.map(({ key, result }) => result.ok ? {
3713
+ key,
3714
+ value: result.value,
3715
+ index: index++
3716
+ } : {
3505
3717
  key,
3506
3718
  test: result
3507
3719
  });
@@ -3512,6 +3724,7 @@ var Compiler = class {
3512
3724
  const { path } = info;
3513
3725
  const listOp = isListOp(op) ? op : void 0;
3514
3726
  const fn = this.#fns !== void 0 && Object.hasOwn(this.#fns, op) ? this.#fns[op] : void 0;
3727
+ const named = isOpName(op);
3515
3728
  return (f, c) => {
3516
3729
  const all = this.#all(args, f, c, path, "arguments");
3517
3730
  if (!all.ok) return this.#emit(c, info, f, all);
@@ -3522,8 +3735,10 @@ var Compiler = class {
3522
3735
  if (values.length > 0) for (const d of this.#domains) {
3523
3736
  if (!safeIs(d, self)) continue;
3524
3737
  accepted ??= d;
3525
- const resolved = resolveOp(d, self, op);
3526
- if (resolved !== void 0) return this.#emit(c, info, f, this.#call(resolved, op, values.slice(1), f, path));
3738
+ const spec = named && Object.hasOwn(d.ops, op) ? d.ops[op] : void 0;
3739
+ if (spec?.fn !== void 0) return this.#emit(c, info, f, this.#call(d, spec, spec.fn, self, op, values.slice(1), f, path));
3740
+ const method = spec !== void 0 || d.methods === "all" ? findMethod(self, op) : void 0;
3741
+ if (method !== void 0) return this.#emit(c, info, f, this.#call(d, spec ?? NO_SPEC, (receiver, ...given) => method.apply(receiver, [...given]), self, op, values.slice(1), f, path));
3527
3742
  }
3528
3743
  if (fn !== void 0) return this.#emit(c, info, f, this.#checkResult(this.#invoke(() => fn(...values), op, f, path), f, path, op));
3529
3744
  if (listOp !== void 0 && Array.isArray(self)) return this.#emit(c, info, f, this.#listOp(listOp, listOfArray(self, this.#missing(f, path)), values.slice(1), f, path));
@@ -3568,8 +3783,15 @@ var Compiler = class {
3568
3783
  };
3569
3784
  }
3570
3785
  }
3571
- #call(op, name, rest, f, path) {
3572
- const { domain, spec } = op;
3786
+ /** This method starts an op that resolveOp found, for example a method of the receiver. */
3787
+ #callResolved(op, self, name, rest, f, path) {
3788
+ return this.#call(op.domain, op.spec, (_self, ...args) => op.call(args), self, name, rest, f, path);
3789
+ }
3790
+ /**
3791
+ * This method starts the op `name` of the domain `domain` with the receiver `self` and the arguments `rest`. It lifts
3792
+ * the numbers, checks the arguments and checks the result.
3793
+ */
3794
+ #call(domain, spec, run, self, name, rest, f, path) {
3573
3795
  const lift = spec.liftScalar;
3574
3796
  const from = domain.fromScalar;
3575
3797
  let callArgs = rest;
@@ -3585,7 +3807,13 @@ var Compiler = class {
3585
3807
  return this.#err(k, `argument ${i + 1} of "${name}" is a ${describeType(callArgs[i])}, not a ${kind === "domain" ? domain.name : kind}`, f, path, { op: name });
3586
3808
  }
3587
3809
  }
3588
- return this.#checkResult(this.#invoke(() => op.call(callArgs), name, f, path), f, path, name);
3810
+ let value;
3811
+ try {
3812
+ value = run(self, ...callArgs);
3813
+ } catch (thrown) {
3814
+ return this.#threw(thrown, `"${name}" threw an exception`, f, path, { op: name });
3815
+ }
3816
+ return this.#checkResult(ok(value), f, path, name);
3589
3817
  }
3590
3818
  #invoke(run, op, f, path) {
3591
3819
  try {
@@ -3594,6 +3822,14 @@ var Compiler = class {
3594
3822
  return this.#threw(thrown, `"${op}" threw an exception`, f, path, { op });
3595
3823
  }
3596
3824
  }
3825
+ /**
3826
+ * This method gives the first domain that accepts a value. It starts only the tests of the domains without a primitive
3827
+ * type: a domain of the type of the value accepts it (KIND.PRIMITIVE).
3828
+ */
3829
+ #domainOf(value) {
3830
+ const candidates = this.#ofType.get(typeof value) ?? this.#open;
3831
+ for (const d of candidates) if (d.primitive !== void 0 || testIs(d, value)) return d;
3832
+ }
3597
3833
  /** This method checks the value that an op gave: no `undefined`, finite numbers, and valid domain values. */
3598
3834
  #checkResult(r, f, path, op) {
3599
3835
  if (!r.ok) return r;
@@ -3601,7 +3837,7 @@ var Compiler = class {
3601
3837
  const extra = { op };
3602
3838
  if (value === void 0 || value === null) return this.#err("undefined-result", `"${op}" gave no value`, f, path, extra);
3603
3839
  if (typeof value === "number" && !Number.isFinite(value)) return this.#err("not-finite", `"${op}" gave ${value}`, f, path, extra);
3604
- const d = this.#domains.find((dom) => safeIs(dom, value));
3840
+ const d = this.#domainOf(value);
3605
3841
  if (d?.valid !== void 0) {
3606
3842
  let valid;
3607
3843
  try {
@@ -3617,10 +3853,12 @@ var Compiler = class {
3617
3853
  const optsArg = WITH_ARGUMENT.has(op) ? rest[1] : rest[0];
3618
3854
  const strict = optsArg?.strict === true;
3619
3855
  if (op === "get") return this.#get(list, rest[0], strict, f, path);
3856
+ if (op === "group") return this.#group(list, rest[0], strict, f, path);
3620
3857
  const good = goodItems(list, strict);
3621
3858
  if (!good.ok) return good;
3622
3859
  const okItems = good.value;
3623
- const okValues = okItems.flatMap((it) => it.result.ok ? [it.result.value] : []);
3860
+ const okValues = [];
3861
+ for (const it of okItems) okValues.push(valueOf(it));
3624
3862
  const numbers = () => {
3625
3863
  const bad = okValues.find((x) => typeof x !== "number");
3626
3864
  return bad === void 0 ? ok(okValues) : this.#err("kind-mismatch", `"${op}" needs numbers, but an item is a ${describeType(bad)}`, f, path, { op });
@@ -3644,19 +3882,36 @@ var Compiler = class {
3644
3882
  case "drop": {
3645
3883
  const n = whole();
3646
3884
  if (!n.ok) return n;
3647
- return ok(vexList(op === "take" ? okItems.slice(0, n.value) : okItems.slice(n.value)));
3885
+ return ok(checkedList(op === "take" ? okItems.slice(0, n.value) : okItems.slice(n.value)));
3648
3886
  }
3649
3887
  case "append": {
3650
3888
  const more = other();
3651
- return more.ok ? ok(vexList([...okItems, ...more.value])) : more;
3889
+ return more.ok ? ok(checkedList([...okItems, ...more.value])) : more;
3652
3890
  }
3653
3891
  case "without": {
3654
3892
  const more = other();
3655
3893
  if (!more.ok) return more;
3656
3894
  const gone = new Set(more.value.map((it) => it.key));
3657
- return ok(vexList(okItems.filter((it) => !gone.has(it.key))));
3895
+ return ok(checkedList(okItems.filter((it) => !gone.has(it.key))));
3658
3896
  }
3659
3897
  case "flat": return this.#flat(okValues, strict, f, path);
3898
+ case "distinct": {
3899
+ const seen = /* @__PURE__ */ new Set();
3900
+ const out = [];
3901
+ for (let i = 0; i < okValues.length; i++) {
3902
+ const x = okValues[i];
3903
+ if (!isIndexValue(x)) return this.#err("kind-mismatch", `"distinct" needs numbers, texts or booleans, but an item is a ${describeType(x)}`, f, path, { op });
3904
+ if (Number.isNaN(x) || !seen.has(x)) out.push(okItems[i]);
3905
+ seen.add(x);
3906
+ }
3907
+ return ok(checkedList(out));
3908
+ }
3909
+ case "join": {
3910
+ const sep = rest[0];
3911
+ if (typeof sep !== "string") return this.#err("kind-mismatch", `"join" needs a text separator, not a ${describeType(sep)}`, f, path, { op });
3912
+ const bad = okValues.find((x) => typeof x !== "string");
3913
+ return bad === void 0 ? ok(okValues.join(sep)) : this.#err("kind-mismatch", `"join" needs texts, but an item is a ${describeType(bad)}`, f, path, { op });
3914
+ }
3660
3915
  case "indexOf": {
3661
3916
  const x = rest[0];
3662
3917
  if (!isIndexValue(x)) return this.#err("kind-mismatch", `"indexOf" needs a number, a text or a boolean, not a ${describeType(x)}`, f, path, { op });
@@ -3717,6 +3972,38 @@ var Compiler = class {
3717
3972
  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" });
3718
3973
  }
3719
3974
  /**
3975
+ * This method gives the groups of a list (LIST.GROUP). The item at a position has the key at the same position of
3976
+ * `keys`, so the two lists must have the same number of items. A pair with an error item or an error key is not in a
3977
+ * group (LIST.LENIENT). Each key gives one item, in the order of its first pair, and its value is a list of its items.
3978
+ */
3979
+ #group(list, keys, strict, f, path) {
3980
+ const good = goodItems(list, strict);
3981
+ if (!good.ok) return good;
3982
+ const listed = asList(keys, this.#missing(f, path));
3983
+ if (listed === void 0) return this.#err("kind-mismatch", `"group" needs a list of keys as its second argument, not a ${describeType(keys)}`, f, path, { op: "group" });
3984
+ const goodKeys = goodItems(listed, strict);
3985
+ if (!goodKeys.ok) return goodKeys;
3986
+ const { items } = list;
3987
+ const keyItems = listed.items;
3988
+ if (keyItems.length !== items.length) return this.#err("kind-mismatch", `"group" needs one key for each item, but the list has ${String(items.length)} items and ${String(keyItems.length)} keys`, f, path, { op: "group" });
3989
+ const groups = /* @__PURE__ */ new Map();
3990
+ for (let i = 0; i < items.length; i++) {
3991
+ const it = items[i];
3992
+ const k = keyItems[i].result;
3993
+ if (!it.result.ok || !k.ok) continue;
3994
+ if (typeof k.value !== "string") return this.#err("kind-mismatch", `"group" needs text keys, but a key is a ${describeType(k.value)}`, f, path, { op: "group" });
3995
+ const g = groups.get(k.value);
3996
+ if (g === void 0) groups.set(k.value, [it]);
3997
+ else g.push(it);
3998
+ }
3999
+ const out = [];
4000
+ for (const [key, g] of groups) out.push({
4001
+ key,
4002
+ result: ok(checkedList(g))
4003
+ });
4004
+ return ok(checkedList(out));
4005
+ }
4006
+ /**
3720
4007
  * This method joins the lists that are the values of the items of a list, in order (LIST.FLAT). Each list follows the
3721
4008
  * rules of LIST.BUILD. A value that is not a list gives `#VALUE!`.
3722
4009
  */
@@ -3729,7 +4016,7 @@ var Compiler = class {
3729
4016
  if (!good.ok) return good;
3730
4017
  out.push(...good.value);
3731
4018
  }
3732
- return ok(vexList(out));
4019
+ return ok(checkedList(out));
3733
4020
  }
3734
4021
  /**
3735
4022
  * This method sorts the items of a list by their sort values, from the smallest (LIST.SORT). The sort is stable. The
@@ -3752,7 +4039,7 @@ var Compiler = class {
3752
4039
  const b = keys[j];
3753
4040
  return a < b ? -1 : a > b ? 1 : 0;
3754
4041
  });
3755
- return ok(vexList(order.map((i) => items[i])));
4042
+ return ok(checkedList(order.map((i) => items[i])));
3756
4043
  }
3757
4044
  /**
3758
4045
  * This method gives the sort value of each item for the option `by` of `sortBy` (LIST.SORT.BY). The op of the name
@@ -3768,7 +4055,7 @@ var Compiler = class {
3768
4055
  if (op !== void 0) break;
3769
4056
  }
3770
4057
  if (op === void 0) return this.#err("unknown-op", `no domain gives "${by}" for a ${describeType(x)}`, f, path, { op: by });
3771
- const r = this.#call(op, by, [], f, path);
4058
+ const r = this.#callResolved(op, x, by, [], f, path);
3772
4059
  if (!r.ok) return r;
3773
4060
  out.push(r.value);
3774
4061
  }
@@ -3797,7 +4084,7 @@ var Compiler = class {
3797
4084
  const d = this.#domains.find((dom) => safeIs(dom, acc) && resolveOp(dom, acc, opName) !== void 0);
3798
4085
  const op = d === void 0 ? void 0 : resolveOp(d, acc, opName);
3799
4086
  if (op === void 0) return this.#err("unknown-op", `no domain gives "${opName}" for a ${describeType(acc)}`, f, path, { op: opName });
3800
- const r = this.#call(op, opName, [values[i]], f, path);
4087
+ const r = this.#callResolved(op, acc, opName, [values[i]], f, path);
3801
4088
  if (!r.ok) return r;
3802
4089
  acc = r.value;
3803
4090
  }
@@ -3813,19 +4100,39 @@ const WITH_ARGUMENT = /* @__PURE__ */ new Set([
3813
4100
  "append",
3814
4101
  "without",
3815
4102
  "get",
3816
- "indexOf"
4103
+ "indexOf",
4104
+ "group",
4105
+ "join"
3817
4106
  ]);
3818
4107
  /**
3819
4108
  * This function gives the items of a list that have a value (LIST.LENIENT). A list op does not skip `#DEPTH!`, so that
3820
4109
  * error comes first (EVAL.DEPTH). With `strict`, the first error item is the result.
3821
4110
  */
3822
4111
  function goodItems(list, strict) {
3823
- const depth = list.items.find((it) => !it.result.ok && isDepthError(it.result.error))?.result;
3824
- if (depth !== void 0 && !depth.ok) return fail(depth.error);
3825
- const firstError = list.items.find((it) => !it.result.ok)?.result;
3826
- if (strict && firstError !== void 0 && !firstError.ok) return fail(firstError.error);
3827
- return ok(list.items.filter((it) => it.result.ok));
4112
+ const { items } = list;
4113
+ let first;
4114
+ for (const it of items) {
4115
+ if (it.result.ok) continue;
4116
+ if (isDepthError(it.result.error)) return fail(it.result.error);
4117
+ first ??= it.result.error;
4118
+ }
4119
+ if (first === void 0) return ok(items);
4120
+ if (strict) return fail(first);
4121
+ const out = [];
4122
+ for (const it of items) if (it.result.ok) out.push(it);
4123
+ return ok(out);
3828
4124
  }
4125
+ /**
4126
+ * This function makes a list from the items of lists that passed the check of LIST.SHAPE, or from items of the same
4127
+ * shape. Thus the list skips the check of `isVexList`.
4128
+ */
4129
+ function checkedList(items) {
4130
+ const list = vexList(items);
4131
+ CHECKED.add(list);
4132
+ return list;
4133
+ }
4134
+ /** This function gives the value of an item with a value. */
4135
+ const valueOf = (it) => it.result.value;
3829
4136
  /** This function makes the index of the keys of a list. An error item is not an item of its key (LIST.LENIENT). */
3830
4137
  function keyIndexOf(list) {
3831
4138
  const values = /* @__PURE__ */ new Map();
@@ -3850,8 +4157,16 @@ const FORBIDDEN_FIELDS = /* @__PURE__ */ new Set([
3850
4157
  ]);
3851
4158
  /** This function tells if a segment of a path can name a field. A compiler uses the same rule as the interpreter. */
3852
4159
  const isFieldName = (seg) => seg.length > 0 && !FORBIDDEN_FIELDS.has(seg);
3853
- /** This function runs the `is` test of a domain. A test that throws counts as `false`. */
4160
+ /**
4161
+ * This function tells if a domain accepts a value. A domain with a primitive type accepts each value of that type and
4162
+ * no other value (KIND.PRIMITIVE), so its test `is` does not start. For another domain, a test that throws counts as
4163
+ * `false`.
4164
+ */
3854
4165
  function safeIs(d, value) {
4166
+ return d.primitive !== void 0 ? typeof value === d.primitive : testIs(d, value);
4167
+ }
4168
+ /** This function starts the `is` test of a domain. A test that throws counts as `false`. */
4169
+ function testIs(d, value) {
3855
4170
  try {
3856
4171
  return d.is(value);
3857
4172
  } catch {
@@ -3992,7 +4307,7 @@ function deps(e) {
3992
4307
  if (!rule.in.some((pattern) => pathMatches(child.slot, pattern))) continue;
3993
4308
  const source = rule.names;
3994
4309
  const at = (source.keysAt ?? source.listAt ?? []).reduce((x, k) => x[String(k)], around.doc.value);
3995
- if (!(source.keysAt !== void 0 ? Object.keys(at) : at).includes(name)) continue;
4310
+ if (!(source.keysAt !== void 0 ? Object.keys(at) : at ?? []).includes(name)) continue;
3996
4311
  found = fnVisits.get(at[name]);
3997
4312
  break search;
3998
4313
  }
@@ -4979,6 +5294,37 @@ function stepExprs(step, unique, addr) {
4979
5294
  }
4980
5295
  return out;
4981
5296
  }
5297
+ /**
5298
+ * The number of the open bodies of `each` and steps of `fold` of a list chain. The names `as` of a loop end with this
5299
+ * number, so a loop inside a body has other names than the loop around it (BUILD.LIST.ITEM).
5300
+ */
5301
+ let itemDepth = 0;
5302
+ /** This function gives the value of `build`, with the next number for the names `as` inside it. */
5303
+ function inItemLoop(build) {
5304
+ itemDepth += 1;
5305
+ try {
5306
+ return build();
5307
+ } finally {
5308
+ itemDepth -= 1;
5309
+ }
5310
+ }
5311
+ /** This function tells if the expression reads the name, in one of its parts. It uses a stack, not recursion. */
5312
+ function reads(e, name) {
5313
+ const todo = [e];
5314
+ for (let x = todo.pop(); x !== void 0; x = todo.pop()) {
5315
+ if (x.tag === "var" && x.name === name) return true;
5316
+ todo.push(...children(x));
5317
+ }
5318
+ return false;
5319
+ }
5320
+ /**
5321
+ * This function gives the names `as` of a fold whose step reads the index. The axis must be `list`. The name of the item
5322
+ * of the loop of `each` stays, so the item of the step keeps its value (BUILD.LIST.ITEM).
5323
+ */
5324
+ function foldItemNames(loop, index) {
5325
+ if (listOf(loop.axis) === void 0) throw new TypeError("the index of a fold needs the axis list: go over the items of a list with each first");
5326
+ return [loop.as?.[0] ?? `$item${itemDepth}`, index];
5327
+ }
4982
5328
  const PROXY_RESERVED = /* @__PURE__ */ new Set([
4983
5329
  "then",
4984
5330
  "catch",
@@ -5290,9 +5636,15 @@ var ListChainImpl = class ListChainImpl {
5290
5636
  expr: loop.body,
5291
5637
  addr: []
5292
5638
  });
5293
- const next = stepExprs(step(names.vars, item), names.unique, []);
5639
+ const index = loop.as?.[1] ?? `$index${itemDepth}`;
5640
+ const next = stepExprs(inItemLoop(() => step(names.vars, item, new ChainImpl({
5641
+ ...this.#s,
5642
+ expr: v(index),
5643
+ addr: []
5644
+ }))), names.unique, []);
5645
+ const as = Object.values(next).some((x) => reads(x, index)) ? foldItemNames(loop, index) : loop.as;
5294
5646
  const r = result(names.vars);
5295
- const folded = fold(loop.axis, names.first, next, toExpr(r, this.#s.addr), loop.at);
5647
+ const folded = fold(loop.axis, names.first, next, toExpr(r, this.#s.addr), loop.at, as);
5296
5648
  return chainOf({
5297
5649
  ...this.#s,
5298
5650
  expr: e.tag === "let" ? let_(e.bind, folded) : folded
@@ -5378,12 +5730,24 @@ var ListChainImpl = class ListChainImpl {
5378
5730
  flat(opts) {
5379
5731
  return this.#list("flat", [], opts);
5380
5732
  }
5733
+ distinct(opts) {
5734
+ return this.#list("distinct", [], opts);
5735
+ }
5736
+ group(keys, opts) {
5737
+ return this.#list("group", [listProgram("group", keys)], opts);
5738
+ }
5739
+ join(sep, opts) {
5740
+ return this.#op("join", [typeof sep === "string" ? lit(sep) : sep.program], opts);
5741
+ }
5381
5742
  each(body, opts) {
5382
- const start = new ChainImpl({
5743
+ const inner = {
5383
5744
  ...this.#s,
5384
- expr: lit(null),
5385
5745
  addr: [],
5386
5746
  depth: this.#s.depth + 1
5747
+ };
5748
+ const start = new ChainImpl({
5749
+ ...inner,
5750
+ expr: lit(null)
5387
5751
  });
5388
5752
  const list = {
5389
5753
  t: "list",
@@ -5398,9 +5762,18 @@ var ListChainImpl = class ListChainImpl {
5398
5762
  axis: ordered,
5399
5763
  test: opts.where(start).program
5400
5764
  };
5765
+ const names = [`$item${itemDepth}`, `$index${itemDepth}`];
5766
+ const program = inItemLoop(() => body(start, new ChainImpl({
5767
+ ...inner,
5768
+ expr: v(names[0])
5769
+ }), new ChainImpl({
5770
+ ...inner,
5771
+ expr: v(names[1])
5772
+ })).program);
5773
+ const as = reads(program, names[1]) ? names : reads(program, names[0]) ? [names[0]] : void 0;
5401
5774
  return new ListChainImpl({
5402
5775
  ...this.#s,
5403
- expr: each(axis, body(start).program)
5776
+ expr: each(axis, program, void 0, as)
5404
5777
  });
5405
5778
  }
5406
5779
  result(k) {