@mark1russell7/vex-compiler 0.18.0 → 0.19.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/vex-compiler",
4
- "version": "0.18.0",
4
+ "version": "0.19.0",
5
5
  "description": "The Vex compiler: generated JavaScript for Vex programs, at run time and at build time, with the results of the interpreter.",
6
6
  "keywords": [
7
7
  "vex",
@@ -47,16 +47,16 @@
47
47
  },
48
48
  "devDependencies": {
49
49
  "@mark1russell7/cue": "github:mark1russell7/cue#da04dd56699a2ae806ab64da5b1d677476afe69e",
50
- "@mark1russell7/vex-domains": "0.18.0",
51
- "@mark1russell7/vex-testkit": "0.18.0",
50
+ "@mark1russell7/vex-domains": "0.19.0",
51
+ "@mark1russell7/vex-testkit": "0.19.0",
52
52
  "@types/node": "^26.6.4",
53
53
  "fast-check": "^4.10.2",
54
54
  "typescript": "^7.0.2",
55
55
  "vitest": "^5.0.3"
56
56
  },
57
57
  "dependencies": {
58
- "@mark1russell7/coeval": "^0.21.0",
59
- "@mark1russell7/vex": "0.18.0",
58
+ "@mark1russell7/coeval": "^0.34.0",
59
+ "@mark1russell7/vex": "0.19.0",
60
60
  "acorn": "^8.19.0",
61
61
  "astring": "^1.9.0"
62
62
  },
package/src/lower.ts CHANGED
@@ -113,6 +113,17 @@ interface Block {
113
113
 
114
114
  const block = (fail: Fail): Block => ({ stmts: [], fail });
115
115
 
116
+ /**
117
+ * A region of the chains of arguments (`#chain`). The value path of each chain of the region is in one block, `value`.
118
+ * A failure of a part ends that block, and the failure paths of the chains come after it, in `paths`. `fails` holds
119
+ * the failures of the parts. A chain whose block has one of these failures is in the region, so its depth adds nothing.
120
+ */
121
+ interface Region {
122
+ readonly value: number;
123
+ readonly fails: Set<Fail>;
124
+ readonly paths: LStmt[];
125
+ }
126
+
116
127
  /**
117
128
  * The number of nodes that the failure paths of a program can copy. Past it, a node with two or more arguments that can
118
129
  * fail keeps no error, so tier 1 gives its result. Thus the size of the code has a limit.
@@ -120,8 +131,8 @@ const block = (fail: Fail): Block => ({ stmts: [], fail });
120
131
  export const MAX_COPIED = 2000;
121
132
 
122
133
  /**
123
- * The number of arguments of a node that `#chain` takes. Each argument that can fail adds a level of blocks, and the
124
- * printer and the JavaScript parser recurse over the levels. A node with more arguments keeps no error.
134
+ * The number of arguments of a node that `#chain` takes. The test of the failure path has a term for each argument that
135
+ * can fail, and the printer recurses over these terms. A node with more arguments keeps no error.
125
136
  */
126
137
  export const MAX_CHAINED = 64;
127
138
 
@@ -180,7 +191,68 @@ export function lower(expr: Expr, facts: Facts = factsOf({}), schema: Schema = {
180
191
  l.check(b, call("has", local(SPACE), local(ORIGIN)), "the origin is a key of the space", l.site(b, top, { t: "key" }));
181
192
  const value = l.expr(plain, top, [], b);
182
193
  b.stmts.push({ t: "return", value });
183
- return { body: b.stmts, locals: l.locals, constants: l.constants };
194
+ return { body: flat(b.stmts), locals: l.locals, constants: l.constants };
195
+ }
196
+
197
+ /** This function gives the statements that a statement holds, in the order of the source. */
198
+ function bodiesOf(x: LStmt): readonly (readonly LStmt[])[] {
199
+ if (x.t === "if") return [x.yes, x.no];
200
+ return x.t === "loop" || x.t === "block" || x.t === "repeat" ? [x.body] : [];
201
+ }
202
+
203
+ /** This function gives the label that a failure ends or continues, or the labels of a strict failure. */
204
+ function failLabels(f: Fail): readonly number[] {
205
+ if (f.t === "break") return [f.label];
206
+ if (f.t === "continue") return f.strict === undefined ? [f.label] : [f.label, ...failLabels(f.strict.else)];
207
+ return [];
208
+ }
209
+
210
+ /**
211
+ * This function moves the first statements of a block out of the block, while they do not end it (V-089). Such a
212
+ * statement runs first in both places, and its jumps go to the same statements. A block with no jump to it goes away.
213
+ * Thus a node in the first part of a node adds no level of blocks.
214
+ *
215
+ * The first walk gives each statement a number in the order of the source, and the first jump to each label. The
216
+ * second walk counts in the same order. A statement holds a jump to the block only if that jump has a number in the
217
+ * range of the statement. Thus each walk reads each statement once.
218
+ */
219
+ function flat(body: readonly LStmt[]): LStmt[] {
220
+ const first = new Map<number, number>();
221
+ // The number of the last statement inside each statement, at the index of the number of the statement.
222
+ const ends: number[] = [0];
223
+ let at = 0;
224
+ const note = (xs: readonly LStmt[]): void => {
225
+ for (const x of xs) {
226
+ const self = ++at;
227
+ const labels = x.t === "break" ? [x.label] : x.t === "check" || x.t === "fail" ? failLabels(x.fail) : [];
228
+ for (const label of labels) if (!first.has(label)) first.set(label, self);
229
+ bodiesOf(x).forEach(note);
230
+ ends[self] = at;
231
+ }
232
+ };
233
+ note(body);
234
+ at = 0;
235
+ // Each statement goes into its list once: a moved statement goes straight into the list of the block around it.
236
+ const walk = (xs: readonly LStmt[], out: LStmt[] = []): LStmt[] => {
237
+ for (const x of xs) one(x, out);
238
+ return out;
239
+ };
240
+ const one = (x: LStmt, out: LStmt[]): void => {
241
+ at++;
242
+ if (x.t === "if") out.push({ ...x, yes: walk(x.yes), no: walk(x.no) });
243
+ else if (x.t === "loop" || x.t === "repeat") out.push({ ...x, body: walk(x.body) });
244
+ else if (x.t !== "block") out.push(x);
245
+ else {
246
+ const jump = first.get(x.label) ?? Number.POSITIVE_INFINITY;
247
+ let rest: LStmt[] | undefined;
248
+ for (const y of x.body) {
249
+ if (rest === undefined && jump <= (ends[at + 1] ?? 0)) rest = [];
250
+ one(y, rest ?? out);
251
+ }
252
+ if (rest !== undefined) out.push({ ...x, body: rest });
253
+ }
254
+ };
255
+ return walk(body);
184
256
  }
185
257
 
186
258
  class Lowerer {
@@ -198,6 +270,12 @@ class Lowerer {
198
270
  readonly #memo: ReadonlyMap<Expr, readonly Expr[]>;
199
271
  /** The keys of the nodes of the memo whose code the lowering makes, with their values. */
200
272
  #keys: ReadonlyMap<Expr, Bound> = new Map();
273
+ /** The region of the chain whose parts the lowering makes at this time (`#chain`). */
274
+ #region: Region | undefined = undefined;
275
+ /** The depth of the loops around the lowering. */
276
+ #loops = 0;
277
+ /** The depth of the loops at the start of the code of a node of the memo with no keys, or `undefined` outside such code. */
278
+ #once: number | undefined = undefined;
201
279
  readonly #facts: Facts;
202
280
  readonly #schema: Schema;
203
281
  /** The kind of each local whose kind the lowering knows. A local gets its kind where it gets its value. */
@@ -316,7 +394,8 @@ class Lowerer {
316
394
  if (key.ok !== undefined) this.check(b, key.ok, "a key with a value");
317
395
  return key.value;
318
396
  }
319
- const keys = this.#copying > 0 ? undefined : this.#memo.get(e);
397
+ // In the code of a node of the memo with no keys, outside a loop of that code, a node evaluates at most once for each space. Its memo thus saves nothing (V-089).
398
+ const keys = this.#copying > 0 || this.#once === this.#loops ? undefined : this.#memo.get(e);
320
399
  return keys === undefined ? this.#node(e, s, path, b) : this.#memoized(e, keys, s, path, b);
321
400
  }
322
401
 
@@ -327,6 +406,14 @@ class Lowerer {
327
406
  this.#copying--;
328
407
  }
329
408
 
409
+ /** This method lowers a loop of names. A node of the memo inside the loop keeps its memo. */
410
+ #inLoop(make: () => LExpr): LExpr {
411
+ this.#loops++;
412
+ const value = make();
413
+ this.#loops--;
414
+ return value;
415
+ }
416
+
330
417
  /** This method lowers a node itself, without the memo. */
331
418
  #node(e: Expr, s: Scope, path: readonly number[], b: Block): LExpr {
332
419
  if (this.#copying > 0) this.#copied++;
@@ -361,11 +448,11 @@ class Lowerer {
361
448
  case "app":
362
449
  return this.#app(e, s, path, b);
363
450
  case "fold":
364
- return this.#fold(e, s, path, b);
451
+ return this.#inLoop(() => this.#fold(e, s, path, b));
365
452
  case "iterate":
366
- return this.#iterate(e, s, path, b);
453
+ return this.#inLoop(() => this.#iterate(e, s, path, b));
367
454
  case "fix":
368
- return this.#fix(e, s, path, b);
455
+ return this.#inLoop(() => this.#fix(e, s, path, b));
369
456
  case "last": {
370
457
  const column = s.columns.get(e.name);
371
458
  // The lowering comes before the checks. A read outside a step fails a check, and that check gives the reason.
@@ -397,6 +484,9 @@ class Lowerer {
397
484
  * The entry has no error, because the error of a node depends on its position and on its child nodes. Where the context
398
485
  * keeps the error, a copy of the node evaluates after a read of such an entry. The copy gives the error at this position.
399
486
  * A node of the memo and its keys use no extension, so this second evaluation has no effect.
487
+ *
488
+ * The code of a node with no keys evaluates once for each space. Outside its loops, a node inside it thus evaluates
489
+ * once too, and it gets no memo of its own (`#once`). So the code of nested nodes has no nested blocks (V-089).
400
490
  */
401
491
  #memoized(e: Expr, keys: readonly Expr[], s: Scope, path: readonly number[], b: Block): LExpr {
402
492
  const memo: LExpr = { t: "memo", id: this.memos++ };
@@ -407,7 +497,10 @@ class Lowerer {
407
497
  const outer = this.#keys;
408
498
  this.#keys = new Map([...outer, ...keys.map((k, i): [Expr, Bound] => [k, values[i] as Bound])]);
409
499
  const compute = block(b.fail);
500
+ const once = this.#once;
501
+ this.#once = keys.length === 0 ? this.#loops : undefined;
410
502
  const node = this.#attempt(compute, (inner) => this.#node(e, s, path, inner), false);
503
+ this.#once = once;
411
504
  this.#keys = outer;
412
505
  compute.stmts.push({ t: "set", n: h, value: prim("memoPut", memo, s.space, tuple, node.value, flag(node)) });
413
506
  b.stmts.push({ t: "let", n: h, value: prim("memoGet", memo, s.space, tuple) }, { t: "if", cond: prim("!", prim("isValue", local(h))), yes: compute.stmts, no: [] });
@@ -449,38 +542,63 @@ class Lowerer {
449
542
 
450
543
  /**
451
544
  * This method lowers arguments on the value path, with no new check. A failure of an argument keeps its error in a
452
- * local of the argument. It then jumps to the copy of the next argument that can fail. After the last copy, the errors
453
- * give the error of the node (`args` of the runtime). The copies clear the locals, for the next turn of a loop.
545
+ * local of the argument. It then ends the value block of the region, and the failure path of the chain copies the
546
+ * later arguments that can fail. After the last copy, the errors give the error of the node (`args` of the runtime).
547
+ * The failure path clears the locals, for the next turn of a loop.
454
548
  *
455
549
  * Each argument evaluates once: the value path gives up at the failure, and the copies start after it.
550
+ *
551
+ * The value path of a chain has no block of its own (V-089). A chain in a part of another chain is in the region of
552
+ * that chain. So its parts go into the value block of the region, and its failure path goes before the failure path of
553
+ * the outer chain. The depth of the blocks thus stays the same for each level of a shape. Before, each level added
554
+ * 3 blocks around argument 0, and the time of the parse of `new Function` grew with the lines times that depth.
456
555
  */
457
556
  #chain(xs: readonly Expr[], s: Scope, path: readonly number[], first: number, what: string, b: Block): LExpr[] {
458
- const end = this.labels++;
557
+ const joined = this.#region?.fails.has(b.fail) === true ? this.#region : undefined;
558
+ const region: Region = joined ?? { value: this.labels++, fails: new Set(), paths: [] };
559
+ const outer = this.#region;
560
+ this.#region = region;
561
+ // The parts write into one list: the statements of the block of a joined chain, or the value block of the region.
562
+ // So a statement goes into a list once, and the lowering stays linear in the depth of the chains.
563
+ const sink = joined === undefined ? [] : b.stmts;
459
564
  const parts = xs.map((x, i) => {
460
- const label = this.labels++;
461
565
  const error = this.locals++;
462
- const part = block({ t: "break", label, keep: error });
566
+ const fail: Fail = { t: "break", label: region.value, keep: error };
567
+ region.fails.add(fail);
463
568
  const at = [...path, first + i];
464
- return { x, at, label, error, value: this.expr(x, s, at, part), stmts: part.stmts };
569
+ const start = sink.length;
570
+ const value = this.expr(x, s, at, { stmts: sink, fail });
571
+ return { x, at, error, value, fails: sink.length > start };
465
572
  });
573
+ this.#region = outer;
466
574
  const values = parts.map((p) => p.value);
467
- const failing = parts.filter((p) => p.stmts.length > 0);
575
+ const failing = parts.filter((p) => p.fails);
468
576
  if (failing.length === 0) return values;
469
- let body: LStmt[] = [...parts.flatMap((p) => p.stmts), { t: "break", label: end }];
577
+ // Only the failed part has an error at the start of the failure path. A part after a part with an error has a copy.
578
+ const failed = (p: (typeof failing)[number]): LExpr => prim("isValue", local(p.error));
579
+ const after = this.locals++;
580
+ const copies: LStmt[] = [];
470
581
  failing.forEach((p, i) => {
471
- body = [{ t: "block", label: p.label, body }];
472
582
  const next = failing[i + 1];
473
583
  if (next === undefined) return;
584
+ copies.push({ t: "set", n: after, value: i === 0 ? failed(p) : prim("||", local(after), failed(p)) });
474
585
  const label = this.labels++;
475
586
  const copy = block({ t: "break", label, keep: next.error });
476
587
  this.#copy(() => this.expr(next.x, s, next.at, copy));
477
- body.push({ t: "block", label, body: copy.stmts });
588
+ copies.push({ t: "if", cond: local(after), yes: [{ t: "block", label, body: copy.stmts }], no: [] });
478
589
  });
479
590
  const inner = block(b.fail);
480
591
  const error = this.value(inner, this.#argsError(s, path, what, failing.map((p) => local(p.error))));
481
592
  inner.stmts.push(...failing.map((p): LStmt => ({ t: "set", n: p.error, value: { t: "none" } })));
482
- this.fail(inner, error);
483
- b.stmts.push({ t: "block", label: end, body: [...body, ...inner.stmts] });
593
+ // In the region of an outer chain, the failure path keeps the error for the part of the outer chain. The failure path of that chain comes next.
594
+ if (joined !== undefined && b.fail.t === "break" && b.fail.keep !== undefined) inner.stmts.push({ t: "set", n: b.fail.keep, value: error });
595
+ else this.fail(inner, error);
596
+ const chainFailed = failing.slice(1).reduce((x, p) => prim("||", x, failed(p)), failed(failing[0] as (typeof failing)[number]));
597
+ region.paths.push({ t: "if", cond: chainFailed, yes: [...copies, ...inner.stmts], no: [] });
598
+ if (joined !== undefined) return values;
599
+ const end = this.labels++;
600
+ sink.push({ t: "break", label: end });
601
+ b.stmts.push({ t: "block", label: end, body: [{ t: "block", label: region.value, body: sink }, ...region.paths] });
484
602
  return values;
485
603
  }
486
604
 
@@ -861,6 +979,7 @@ class Lowerer {
861
979
  each: (body: Block, key: LExpr, at: Scope, names: ReadonlyMap<string, Bound>) => void,
862
980
  ): void {
863
981
  const { axis, at: addr, as } = e;
982
+ this.#loops++;
864
983
  const list = listOf(axis);
865
984
  const tests = firstTest + axisChildren(axis) - whereTests(axis).length;
866
985
  const from = addr === undefined || addr.length === 0 ? s.focus : this.#address(addr, s, path, firstTest + axisChildren(axis), b);
@@ -913,6 +1032,7 @@ class Lowerer {
913
1032
  if (name !== undefined && item !== undefined) names.set(name, { value: this.value(body, prim("member", item.values, local(index))) });
914
1033
  if (position !== undefined && item !== undefined) names.set(position, { value: this.#typed(this.value(body, prim("member", item.nth, local(index))), "number") });
915
1034
  each(body, key, at, names);
1035
+ this.#loops--;
916
1036
  b.stmts.push({ t: "loop", label, item: target, index, array: array_, over, body: body.stmts });
917
1037
  }
918
1038
 
@@ -32,13 +32,16 @@ export interface Tidied {
32
32
  /** The tokens that hold a text of the code: a string, a part of a template and a regular expression. */
33
33
  const TEXT_TOKENS: ReadonlySet<unknown> = new Set([tokTypes.string, tokTypes.template, tokTypes.regexp]);
34
34
 
35
+ // Each pattern of this file is a function that gives a new regular expression. Thus a mutant of a pattern starts only the
36
+ // tests that use the pattern, not each test of the mutation lane (LANE.STATIC).
37
+
35
38
  /** A text of the code starts with one of these characters. A comment starts with the slash too. */
36
39
  // Stryker disable next-line Regex: `rewritten` calls `codeOf` on a line with a match, so a form that finds other characters also finds that line.
37
- const TEXT_START = /["'`/]/;
40
+ const TEXT_START = (): RegExp => /["'`/]/;
38
41
 
39
42
  /** This function gives a line of code with spaces at the place of each text. Each other character keeps its offset. A line with no text needs no tokens. */
40
43
  function codeOf(line: string): string {
41
- if (!TEXT_START.test(line)) return line;
44
+ if (!TEXT_START().test(line)) return line;
42
45
  let out = "";
43
46
  let at = 0;
44
47
  for (const token of tokenizer(line, { ecmaVersion: "latest" })) {
@@ -72,10 +75,10 @@ export function namesOfCode(code: string): ReadonlySet<string> {
72
75
  }
73
76
 
74
77
  /** The words of a text. */
75
- const WORD = /[A-Za-z_$][\w$]*/g;
78
+ const WORD = (): RegExp => /[A-Za-z_$][\w$]*/g;
76
79
 
77
80
  /** This function gives the words of a text. */
78
- export const wordsOf = (text: string): readonly string[] => text.match(WORD) ?? [];
81
+ export const wordsOf = (text: string): readonly string[] => text.match(WORD()) ?? [];
79
82
 
80
83
  /** This function gives the count of a word in some lines. A line without the text of the word needs no walk. */
81
84
  function countOf(lines: readonly string[], name: string): number {
@@ -107,17 +110,18 @@ function openerOf(lines: readonly string[], at: number): number {
107
110
  }
108
111
 
109
112
  /** The line of a function that a block opens. */
110
- const FUNCTION_HEAD = /=> \{$|\bfunction\b.*\{$/;
113
+ const FUNCTION_HEAD = (): RegExp => /=> \{$|\bfunction\b.*\{$/;
111
114
 
112
115
  /** This function gives the line that opens the function of the line `at`, or -1 for the function of the run. */
113
116
  function functionOf(lines: readonly string[], at: number): number {
117
+ const head = FUNCTION_HEAD();
114
118
  let k = openerOf(lines, at);
115
- while (k >= 0 && !FUNCTION_HEAD.test(lines[k] as string)) k = openerOf(lines, k);
119
+ while (k >= 0 && !head.test(lines[k] as string)) k = openerOf(lines, k);
116
120
  return k;
117
121
  }
118
122
 
119
123
  /** The key of an item of a list in a loop. The head of the loop must come just before it (`deadKeys`). */
120
- const KEY_READ = /^\s*const (j\d+) = ([A-Za-z]+\d*)\[(q\d+)\](\[0\])?;$/;
124
+ const KEY_READ = (): RegExp => /^\s*const (j\d+) = ([A-Za-z]+\d*)\[(q\d+)\](\[0\])?;$/;
121
125
 
122
126
  /**
123
127
  * This function removes each read of a key that no code reads (COMPILE.MODULE.SIZE.KEY). The read must be the first line
@@ -125,8 +129,9 @@ const KEY_READ = /^\s*const (j\d+) = ([A-Za-z]+\d*)\[(q\d+)\](\[0\])?;$/;
125
129
  * is a pair, so the read cannot throw.
126
130
  */
127
131
  export function deadKeys(lines: readonly string[]): readonly string[] {
132
+ const keyRead = KEY_READ();
128
133
  return lines.filter((line, i) => {
129
- const m = KEY_READ.exec(line);
134
+ const m = keyRead.exec(line);
130
135
  if (m === null) return true;
131
136
  const [, key, array, position, pair] = m as unknown as readonly [string, string, string, string, string | undefined];
132
137
  const head = lines[i - 1] ?? "";
@@ -145,13 +150,14 @@ function renamed(line: string, from: string, to: string): string {
145
150
  }
146
151
 
147
152
  /** The writes to a name. The first group holds the name after `++` or `--`, and the second group the name before an operator. */
148
- const WRITE = /(?:\+\+|--)\s*([A-Za-z_$][\w$]*)|(?<![\w$.])(?<!\b(?:const|let) )([A-Za-z_$][\w$]*)\s*(?:\+\+|--|(?:[-+*/%&|^]|<<|>>>?|\*\*|&&|\|\||\?\?)?=(?![=>]))/g;
153
+ const WRITE = (): RegExp => /(?:\+\+|--)\s*([A-Za-z_$][\w$]*)|(?<![\w$.])(?<!\b(?:const|let) )([A-Za-z_$][\w$]*)\s*(?:\+\+|--|(?:[-+*/%&|^]|<<|>>>?|\*\*|&&|\|\||\?\?)?=(?![=>]))/g;
149
154
 
150
155
  /** This function gives the lines that write to each name, without the line that declares the name. */
151
156
  function writesOf(lines: readonly string[]): ReadonlyMap<string, readonly number[]> {
152
157
  const writes = new Map<string, number[]>();
158
+ const write = WRITE();
153
159
  for (const [i, line] of lines.entries()) {
154
- for (const m of line.matchAll(WRITE)) {
160
+ for (const m of line.matchAll(write)) {
155
161
  const name = (m[1] ?? m[2]) as string;
156
162
  writes.set(name, [...(writes.get(name) ?? []), i]);
157
163
  }
@@ -168,7 +174,7 @@ function binds(line: string, name: string): boolean {
168
174
  }
169
175
 
170
176
  /** A statement that gives a new name to a fresh name, or to `o`, the key of a run. */
171
- const ALIAS = /^\s*const ([A-Za-z]+\d+) = ([A-Za-z]+\d+|o);$/;
177
+ const ALIAS = (): RegExp => /^\s*const ([A-Za-z]+\d+) = ([A-Za-z]+\d+|o);$/;
172
178
 
173
179
  /**
174
180
  * This function tells if the name `name` keeps its value from the line `at` to the line `end`. A name with no write
@@ -192,8 +198,9 @@ export function aliases(lines: readonly string[]): readonly string[] {
192
198
  const out = [...lines];
193
199
  const writes = writesOf(lines);
194
200
  const gone = new Set<number>();
201
+ const statement = ALIAS();
195
202
  for (let i = 0; i < out.length; i++) {
196
- const m = ALIAS.exec(out[i] as string);
203
+ const m = statement.exec(out[i] as string);
197
204
  if (m === null) continue;
198
205
  const [, alias, name] = m as unknown as readonly [string, string, string];
199
206
  const end = blockEnd(out, i);
@@ -212,24 +219,26 @@ export function aliases(lines: readonly string[]): readonly string[] {
212
219
  }
213
220
 
214
221
  /** The first line of a lazy cell of the run. */
215
- const CELL = /^ {2}const (c\d+) = L\(\(\) => \{$/;
222
+ const CELL = (): RegExp => /^ {2}const (c\d+) = L\(\(\) => \{$/;
216
223
 
217
224
  /** The first line of a lazy cell at each place. */
218
- const ANY_CELL = /^\s*const \w+ = L\(\(\) => \{$/;
225
+ const ANY_CELL = (): RegExp => /^\s*const \w+ = L\(\(\) => \{$/;
219
226
 
220
227
  /** The blocks that run each statement at most once, for one run of the block around them. */
221
- const ONCE_BLOCK = /^\s*(?:try \{|\} catch \{|\} else \{|(?:\} else )?if \(.*\) \{)$/;
228
+ const ONCE_BLOCK = (): RegExp => /^\s*(?:try \{|\} catch \{|\} else \{|(?:\} else )?if \(.*\) \{)$/;
222
229
 
223
230
  /** The statements that can run a part of their line more than once. */
224
- const LOOP_LINE = /^\s*(?:for|while|do)\b|=>/;
231
+ const LOOP_LINE = (): RegExp => /^\s*(?:for|while|do)\b|=>/;
225
232
 
226
233
  /** This function tells if the statement at the line `at` runs at most once in a run. */
227
234
  function runsOnce(lines: readonly string[], at: number): boolean {
228
- if (LOOP_LINE.test(lines[at] as string)) return false;
235
+ if (LOOP_LINE().test(lines[at] as string)) return false;
236
+ const cell = ANY_CELL();
237
+ const once = ONCE_BLOCK();
229
238
  for (let k = openerOf(lines, at); k >= 0; k = openerOf(lines, k)) {
230
239
  const line = lines[k] as string;
231
- if (ANY_CELL.test(line)) return true;
232
- if (!ONCE_BLOCK.test(line)) return false;
240
+ if (cell.test(line)) return true;
241
+ if (!once.test(line)) return false;
233
242
  }
234
243
  return true;
235
244
  }
@@ -241,8 +250,9 @@ function runsOnce(lines: readonly string[], at: number): boolean {
241
250
  */
242
251
  export function onceCells(lines: readonly string[]): readonly string[] {
243
252
  let out = lines;
253
+ const cell = CELL();
244
254
  for (let i = 0; i + 2 < out.length; i++) {
245
- const name = CELL.exec(out[i] as string)?.[1];
255
+ const name = cell.exec(out[i] as string)?.[1];
246
256
  const value = /^ {4}return (.*);$/.exec(out[i + 1] as string)?.[1];
247
257
  if (name === undefined || value === undefined || out[i + 2] !== " });" || countOf(out, name) !== 2) continue;
248
258
  const read = new RegExp(`(?<![\\w$.])G\\(${name}\\(\\)\\)`, "g");
@@ -256,29 +266,29 @@ export function onceCells(lines: readonly string[]): readonly string[] {
256
266
  }
257
267
 
258
268
  /** A constant of the run on one line, with its name. */
259
- const CONSTANT = /^ {2}const (c\d+) = (?:T\(\(\) => .*\)|\[\]);$/;
269
+ const CONSTANT = (): RegExp => /^ {2}const (c\d+) = (?:T\(\(\) => .*\)|\[\]);$/;
260
270
 
261
271
  /** The first line of a constant of the run with a `try`, with its name. */
262
- const HELD = /^ {2}let (c\d+);$/;
272
+ const HELD = (): RegExp => /^ {2}let (c\d+);$/;
263
273
 
264
274
  /** The first line of a column at each depth, with its indent and its name. A column does not run until a read calls it. */
265
- const COLUMN = /^( *)const (col\d+) = Q\(\(\w+\) => \{$/;
275
+ const COLUMN = (): RegExp => /^( *)const (col\d+) = Q\(\(\w+\) => \{$/;
266
276
 
267
277
  /** The variable of the pack of a column at each depth, with its name. */
268
- const PACK = /^ *let (PK\d+);$/;
278
+ const PACK = (): RegExp => /^ *let (PK\d+);$/;
269
279
 
270
280
  /** This function gives the name of the declaration at the line `at` and its last line, or `undefined` for another line. */
271
281
  function constantAt(lines: readonly string[], at: number): { readonly name: string; readonly last: number } | undefined {
272
282
  const line = lines[at] as string;
273
- const one = CONSTANT.exec(line)?.[1];
283
+ const one = CONSTANT().exec(line)?.[1];
274
284
  if (one !== undefined) return { name: one, last: at };
275
- const lazy = CELL.exec(line)?.[1];
285
+ const lazy = CELL().exec(line)?.[1];
276
286
  if (lazy !== undefined) return { name: lazy, last: lines.indexOf(" });", at) };
277
- const column = COLUMN.exec(line);
287
+ const column = COLUMN().exec(line);
278
288
  if (column !== null) return { name: column[2] as string, last: lines.indexOf(`${column[1] as string}});`, at) };
279
- const pack = PACK.exec(line)?.[1];
289
+ const pack = PACK().exec(line)?.[1];
280
290
  if (pack !== undefined) return { name: pack, last: at };
281
- const held = HELD.exec(line)?.[1];
291
+ const held = HELD().exec(line)?.[1];
282
292
  return held === undefined || lines[at + 1] !== " try {" ? undefined : { name: held, last: lines.indexOf(" }", at) };
283
293
  }
284
294
 
@@ -324,7 +334,7 @@ export function liveDecls(decls: ReadonlyMap<string, string>, roots: string): Re
324
334
  }
325
335
 
326
336
  /** The tokens of the body of a function of an op. A body with another token has no inline form. */
327
- const BODY_TOKEN = /\s+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|\.{3}|\.\d\w*|\d[\w.]*|\.[A-Za-z_$][\w$]*|[A-Za-z_$][\w$]*|===|!==|\?\?|&&|\|\||\*\*|<<|>>>|>>|==|!=|<=|>=|\+\+|--|=>|\?\.|[-+*/%<>!?:,&|^~()[\]{}]/y;
337
+ const BODY_TOKEN = (): RegExp => /\s+|"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|\.{3}|\.\d\w*|\d[\w.]*|\.[A-Za-z_$][\w$]*|[A-Za-z_$][\w$]*|===|!==|\?\?|&&|\|\||\*\*|<<|>>>|>>|==|!=|<=|>=|\+\+|--|=>|\?\.|[-+*/%<>!?:,&|^~()[\]{}]/y;
328
338
 
329
339
  /** The tokens that change a value or start a function. */
330
340
  const NOT_INLINE: ReadonlySet<string> = new Set(["++", "--", "=>"]);
@@ -338,9 +348,9 @@ const NOT_VALUES: ReadonlySet<string> = new Set(["typeof", "void"]);
338
348
  /** This function gives the tokens of a body, or `undefined` for a body with another token. */
339
349
  function tokensOf(body: string): readonly string[] | undefined {
340
350
  const out: string[] = [];
341
- BODY_TOKEN.lastIndex = 0;
342
- while (BODY_TOKEN.lastIndex < body.length) {
343
- const m = BODY_TOKEN.exec(body);
351
+ const token = BODY_TOKEN();
352
+ while (token.lastIndex < body.length) {
353
+ const m = token.exec(body);
344
354
  if (m === null || NOT_INLINE.has(m[0])) return undefined;
345
355
  out.push(m[0]);
346
356
  }
@@ -381,7 +391,8 @@ function bodyParts(params: readonly string[], body: string, globals: ReadonlySet
381
391
  if (t === ")" || t === "]" || t === "}") open.pop();
382
392
  const at = params.indexOf(t);
383
393
  const key = open.at(-1) === "{" && (last === "{" || last === ",");
384
- if (!isWord(t) || (key && next === ":")) parts.push(t);
394
+ // A word after an optional chain is the name of a key, as the token `.x` of a plain read (V-098).
395
+ if (!isWord(t) || last === "?." || (key && next === ":")) parts.push(t);
385
396
  else if (key && next !== "," && next !== "}") return undefined;
386
397
  else if (at >= 0) parts.push(...(key ? [`${t}:`, at] : [at]));
387
398
  else if (PLAIN_WORDS.has(t) || globals.has(t)) parts.push(t);
@@ -392,7 +403,7 @@ function bodyParts(params: readonly string[], body: string, globals: ReadonlySet
392
403
  }
393
404
 
394
405
  /** The declaration of a function of an op or of a check of a domain, as an arrow function. */
395
- const OP_DECL = /^const ((?:op|v)_\w+) = (?:\(([\w$,\s]*)\)|([A-Za-z_$][\w$]*))\s*=>([\s\S]*);$/;
406
+ const OP_DECL = (): RegExp => /^const ((?:op|v)_\w+) = (?:\(([\w$,\s]*)\)|([A-Za-z_$][\w$]*))\s*=>([\s\S]*);$/;
396
407
 
397
408
  /** The name, the parameters and the parts of an inline form. */
398
409
  interface OpForm {
@@ -403,7 +414,7 @@ interface OpForm {
403
414
 
404
415
  /** This function gives the form of a declaration, or `undefined` for a declaration without one. */
405
416
  function opForm(text: string, globals: ReadonlySet<string>): OpForm | undefined {
406
- const m = OP_DECL.exec(text);
417
+ const m = OP_DECL().exec(text);
407
418
  if (m === null) return undefined;
408
419
  const params = (m[2] ?? m[3] ?? "").split(",").map((x) => x.trim()).filter((x) => x !== "");
409
420
  const parts = bodyParts(params, m[4] as string, globals);