@mark1russell7/vex-compiler 0.17.1 → 0.18.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.17.1",
4
+ "version": "0.18.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",
@@ -30,6 +30,10 @@
30
30
  "types": "./build/index.d.ts",
31
31
  "default": "./build/index.js"
32
32
  },
33
+ "./module": {
34
+ "types": "./build/module-entry.d.ts",
35
+ "default": "./build/module-entry.js"
36
+ },
33
37
  "./package.json": "./package.json"
34
38
  },
35
39
  "files": [
@@ -42,22 +46,29 @@
42
46
  "access": "public"
43
47
  },
44
48
  "devDependencies": {
45
- "@mark1russell7/cue": "github:mark1russell7/cue",
46
- "@mark1russell7/vex-domains": "0.17.1",
47
- "@mark1russell7/vex-testkit": "0.17.1",
49
+ "@mark1russell7/cue": "github:mark1russell7/cue#da04dd56699a2ae806ab64da5b1d677476afe69e",
50
+ "@mark1russell7/vex-domains": "0.18.0",
51
+ "@mark1russell7/vex-testkit": "0.18.0",
48
52
  "@types/node": "^26.6.4",
49
53
  "fast-check": "^4.10.2",
50
54
  "typescript": "^7.0.2",
51
55
  "vitest": "^5.0.3"
52
56
  },
53
57
  "dependencies": {
54
- "@mark1russell7/vex": "0.17.1"
58
+ "@mark1russell7/coeval": "^0.21.0",
59
+ "@mark1russell7/vex": "0.18.0",
60
+ "acorn": "^8.19.0",
61
+ "astring": "^1.9.0"
55
62
  },
56
63
  "scripts": {
57
64
  "build": "tsdown",
58
65
  "test": "vitest run",
59
66
  "test:watch": "vitest",
60
- "bench:gate": "node bench/gate.ts",
67
+ "bench:gate": "node bench/gate-processes.ts",
68
+ "bench:places": "node bench/places.ts",
69
+ "bench:growth": "node bench/growth.ts",
70
+ "bench:growth:gates": "node bench/growth.ts gates",
71
+ "bench:gate:one": "node bench/gate.ts",
61
72
  "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
62
73
  }
63
74
  }
package/src/facts.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * whose op the interpreter takes first, and the kinds and the lifts of its parameters. The facts come from the op
4
4
  * tables, so the same options always give the same facts, and the same source.
5
5
  */
6
- import { children, isListOp, isOpName, isVexList, liftsAt, listOf, type AnyDomain, type Expr, type ExtHandler, type FreeFn, type OpSpec, type ParamKind, type PrimitiveKind, type ReturnKind } from "@mark1russell7/vex";
6
+ import { isListOp, isOpName, liftsAt, listItemKind, type AnyDomain, type ExtHandler, type FreeFn, type ListOp, type OpSpec, type ParamKind, type PrimitiveKind, type ReturnKind } from "@mark1russell7/vex";
7
7
 
8
8
  /**
9
9
  * The most bodies of functions that tier 2 puts at the calls of one program. A function that calls another function
@@ -11,28 +11,13 @@ import { children, isListOp, isOpName, isVexList, liftsAt, listOf, type AnyDomai
11
11
  */
12
12
  export const MAX_CALLS = 10_000;
13
13
 
14
- /**
15
- * The list ops that give a list, or read a position or a key of a list (LIST.SORT, LIST.TAKE, LIST.NTH, LIST.BUILD,
16
- * LIST.GET, LIST.INDEXOF, LIST.FILL, LIST.DISTINCT, LIST.GROUP, LIST.JOIN).
17
- */
18
- const ORDER_OPS: ReadonlySet<string> = new Set(["sortBy", "take", "nth", "drop", "append", "flat", "without", "get", "indexOf", "fill", "distinct", "group", "join"]);
14
+ /** The list ops that are one loop with an `each`. Each other list op takes the list as a value (COMPILE.LIST.VALUE). */
15
+ export type FusedOp = Exclude<ListOp, "sortBy" | "take" | "nth" | "setNth" | "drop" | "append" | "flat" | "without" | "get" | "indexOf" | "distinct" | "group" | "join">;
19
16
 
20
- /**
21
- * This function gives the reason that tier 2 cannot take a program with lists as values. The reason is the axis `list`,
22
- * an op on the order or the keys of a list, or a list literal. Tier 1 evaluates such a program. It uses a stack, not
23
- * recursion.
24
- */
25
- export function listReason(expr: Expr): string | undefined {
26
- const todo: Expr[] = [expr];
27
- for (let x = todo.pop(); x !== undefined; x = todo.pop()) {
28
- if ((x.tag === "each" || x.tag === "fold") && listOf(x.axis) !== undefined) return 'the program has the axis "list", and tier 2 does not have lists as values yet';
29
- // Stryker disable next-line ConditionalExpression: a node that is not an app has no field op, so the set does not have it
30
- if (x.tag === "app" && ORDER_OPS.has(x.op)) return `the program has the list op "${x.op}", and tier 2 does not have lists as values yet`;
31
- if (x.tag === "lit" && isVexList(x.value)) return "the program has a list literal, and tier 2 does not have lists as values yet";
32
- todo.push(...children(x));
33
- }
34
- return undefined;
35
- }
17
+ const FUSED_OPS: ReadonlySet<string> = new Set<FusedOp>(["count", "sum", "min", "max", "mean", "any", "all", "none", "values", "keys", "reduce", "first", "errors"]);
18
+
19
+ /** This function tells if a list op over an `each` is one loop in tier 2. The lowering gives the same answer to the memo. */
20
+ export const isFusedOp = (op: string): op is FusedOp => FUSED_OPS.has(op);
36
21
 
37
22
  /** The function of an op of a domain, or a method. */
38
23
  export type Method = (...args: unknown[]) => unknown;
@@ -52,7 +37,8 @@ export const primitiveOf = (k: Kind | ListKind | undefined): PrimitiveKind | und
52
37
  /**
53
38
  * The kind of a list: the kind of its items, which can be a list too. A column of lists of a module of a sheet has such a
54
39
  * kind (COMPILE.MODULE.SHEET.LIST). With `texts`, a key of an item can be a key of a list literal or of `fill`, not the
55
- * key of a record. A field of the schema can have such a kind too (COMPILE.MODULE.LIST.INPUT).
40
+ * key of a record. A field of the schema can have such a kind too (COMPILE.MODULE.LIST.INPUT), and a variable of the
41
+ * schema can have it (COMPILE.MODULE.LIST.VAR).
56
42
  */
57
43
  export interface ListKind {
58
44
  readonly list: Kind | ListKind;
@@ -62,11 +48,12 @@ export interface ListKind {
62
48
  /**
63
49
  * The kinds that a host declares (docs/COMPILER.md §3.2): the kind of each field of the records, and of each variable of
64
50
  * the run. A read of a declared field or variable checks the kind. When the check fails, tier 1 evaluates the program.
65
- * A field can hold a list (COMPILE.MODULE.LIST.INPUT). Tier 2 does not check the kind of such a field.
51
+ * A field and a variable can hold a list (COMPILE.MODULE.LIST.INPUT, COMPILE.MODULE.LIST.VAR). Tier 2 does not check
52
+ * the kind of such a field or variable.
66
53
  */
67
54
  export interface Schema {
68
55
  readonly fields?: Readonly<Record<string, Kind | ListKind>>;
69
- readonly vars?: Readonly<Record<string, Kind>>;
56
+ readonly vars?: Readonly<Record<string, Kind | ListKind>>;
70
57
  }
71
58
 
72
59
  /** The options of a program: the domains, the free functions and the extension handlers, and the schema of the host. */
@@ -120,11 +107,13 @@ const FREE: SiteFacts = Object.freeze({ t: "free" });
120
107
  /**
121
108
  * The op of a site whose values have known kinds (KIND.STATIC):
122
109
  * - `fn`: the function of the op of the domain `domain`. `bad` is true when an argument has a kind that the op does
123
- * not accept, so the interpreter gives an error. `returns` is the kind of the result, if the op declares it.
110
+ * not accept, so the interpreter gives an error. `returns` is the kind of the result, if the op declares it. `item`
111
+ * is the kind of the items of a result that is a list (KIND.RETURNS.LIST). `lifted` has the positions after the
112
+ * receiver of the numbers that `fromScalar` lifts, if the caller asks for them.
124
113
  * - `free`: no domain that accepts the receiver has the op, and a free function has the name.
125
114
  */
126
115
  export type StaticSite =
127
- | { readonly t: "fn"; readonly domain: number; readonly bad: boolean; readonly returns: Kind | undefined }
116
+ | { readonly t: "fn"; readonly domain: number; readonly bad: boolean; readonly returns: Kind | undefined; readonly item?: PrimitiveKind; readonly lifted?: readonly number[] }
128
117
  | { readonly t: "free" };
129
118
 
130
119
  const STATIC_FREE: StaticSite = Object.freeze({ t: "free" });
@@ -135,7 +124,7 @@ const NO_LISTS: ReadonlySet<number> = new Set();
135
124
  /** This function gives the kind of the result of an op of a domain, if the op declares it. */
136
125
  function returnsOf(domain: AnyDomain, kind: ReturnKind | undefined): Kind | undefined {
137
126
  if (kind === "domain") return kindOfDomain(domain);
138
- return kind === "any" ? undefined : kind;
127
+ return kind === "any" || listItemKind(kind) !== undefined ? undefined : (kind as Kind | undefined);
139
128
  }
140
129
 
141
130
  /**
@@ -149,13 +138,22 @@ function fits(domain: AnyDomain, param: ParamKind | undefined, arg: Kind | undef
149
138
  return arg === (param === "domain" ? kindOfDomain(domain) : param);
150
139
  }
151
140
 
141
+ /** This function tells if two domains declare different field names, so they have no common value (KIND.FIELDS). */
142
+ function disjoint(a: AnyDomain, b: AnyDomain | undefined): boolean {
143
+ const x = a.fields;
144
+ const y = b?.fields;
145
+ return x !== undefined && y !== undefined && (x.length !== y.length || x.some((name) => !y.includes(name)));
146
+ }
147
+
152
148
  /**
153
149
  * This function tells if a domain accepts a value of a kind. A domain with a primitive type accepts its type, and a
154
- * domain without one accepts the values of its kind. For another value, it gives `undefined`: its `is` can accept it.
150
+ * domain without one accepts the values of its kind. It does not accept a value of a domain with other fields. For
151
+ * another value, it gives `undefined`: its `is` can accept it.
155
152
  */
156
- function accepts(d: AnyDomain, kind: Kind): boolean | undefined {
153
+ function accepts(domains: readonly AnyDomain[], d: AnyDomain, kind: Kind): boolean | undefined {
157
154
  if (d.primitive !== undefined) return d.primitive === kind;
158
- return kind === kindOfDomain(d) ? true : undefined;
155
+ if (kind === kindOfDomain(d)) return true;
156
+ return disjoint(d, domains.find((x) => kindOfDomain(x) === kind)) ? false : undefined;
159
157
  }
160
158
 
161
159
  /** The facts of the options. */
@@ -170,9 +168,10 @@ export interface Facts {
170
168
  /**
171
169
  * This function gives the op of a site with the kinds of its values, the receiver first. When the kinds do not decide
172
170
  * the op, it gives `undefined`. Each domain before the op must declare a primitive type. Then the interpreter takes
173
- * the same op at each run. `lists` has the positions of the values that are lists, after the receiver.
171
+ * the same op at each run. `lists` has the positions of the values that are lists, after the receiver. A number that
172
+ * the op lifts gives `undefined`, unless `lift` is true: then the caller lifts the numbers at the positions `lifted`.
174
173
  */
175
- staticSite(name: string, kinds: readonly (Kind | undefined)[], lists?: ReadonlySet<number>): StaticSite | undefined;
174
+ staticSite(name: string, kinds: readonly (Kind | undefined)[], lists?: ReadonlySet<number>, lift?: boolean): StaticSite | undefined;
176
175
  /**
177
176
  * This function gives the index of the domain that checks a result of a kind. When no domain accepts such a value,
178
177
  * it gives -1. When a domain without a primitive type comes first, it gives `undefined`.
@@ -183,6 +182,10 @@ export interface Facts {
183
182
  * op for each receiver, for example `fill` (LIST.FILL).
184
183
  */
185
184
  own(name: string): boolean;
185
+ /** This function tells if a domain declares a list as the result of the op `name` (KIND.RETURNS.LIST). */
186
+ givesList(name: string): boolean;
187
+ /** This function gives the number of domains with an identity of the op `name`, as `#reduce` of the interpreter counts them (LIST.EMPTY). */
188
+ identities(name: string): number;
186
189
  }
187
190
 
188
191
  /** This function gives the facts of a set of options. */
@@ -192,12 +195,12 @@ export function factsOf(options: Options): Facts {
192
195
  const last = domains.findLastIndex((d) => d.valid !== undefined);
193
196
  return {
194
197
  checks: domains.slice(0, last + 1).map((d) => d.valid !== undefined),
195
- staticSite(name, kinds, lists = NO_LISTS) {
198
+ staticSite(name, kinds, lists = NO_LISTS, lift = false) {
196
199
  const [self, ...args] = kinds;
197
200
  // A primitive value is not a list, so a list op name is an op of a domain here, as in the interpreter.
198
201
  if (self === undefined) return undefined;
199
202
  for (const [i, d] of domains.entries()) {
200
- const takes = accepts(d, self);
203
+ const takes = accepts(domains, d, self);
201
204
  if (takes === undefined) return undefined;
202
205
  const e = takes ? entryOf(d, name) : undefined;
203
206
  // A primitive value has no methods, so only the function of a spec is an op for it. The domain of a value without
@@ -206,18 +209,20 @@ export function factsOf(options: Options): Facts {
206
209
  if (takes && d.primitive === undefined) return undefined;
207
210
  continue;
208
211
  }
209
- // A lifted number goes through fromScalar: the site keeps the dispatch of the runtime.
210
- // A list is not a number, so the interpreter does not lift it.
211
- if (d.fromScalar !== undefined && args.some((a, j) => a !== "string" && a !== "boolean" && !lists.has(j + 1) && liftsAt(e.spec.liftScalar, j))) return undefined;
212
- const ok = args.map((a, j) => fits(d, e.spec.params?.[j], a, lists.has(j + 1)));
212
+ // A lifted number goes through fromScalar: the site keeps the dispatch of the runtime, or the caller lifts it. A
213
+ // list is not a number, and neither is a value of another kind, so the interpreter does not lift them.
214
+ const lifted = d.fromScalar === undefined ? [] : args.flatMap((a, j) => ((a === undefined || a === "number") && !lists.has(j + 1) && liftsAt(e.spec.liftScalar, j) ? [j] : []));
215
+ if (lifted.some((j) => !lift || args[j] === undefined)) return undefined;
216
+ const ok = args.map((a, j) => fits(d, e.spec.params?.[j], lifted.includes(j) ? kindOfDomain(d) : a, lists.has(j + 1)));
213
217
  if (ok.includes(undefined)) return undefined;
214
- return { t: "fn", domain: i, bad: ok.includes(false), returns: returnsOf(d, e.spec.returns) };
218
+ const item = listItemKind(e.spec.returns);
219
+ return { t: "fn", domain: i, bad: ok.includes(false), returns: returnsOf(d, e.spec.returns), ...(item === undefined ? {} : { item }), ...(lifted.length === 0 ? {} : { lifted }) };
215
220
  }
216
221
  return fns !== undefined && Object.hasOwn(fns, name) ? STATIC_FREE : undefined;
217
222
  },
218
223
  checkOf(kind) {
219
224
  for (const [i, d] of domains.entries()) {
220
- const takes = accepts(d, kind);
225
+ const takes = accepts(domains, d, kind);
221
226
  if (takes === undefined) return undefined;
222
227
  if (takes) return i;
223
228
  }
@@ -226,6 +231,12 @@ export function factsOf(options: Options): Facts {
226
231
  own(name) {
227
232
  return domains.every((d) => entryOf(d, name) === undefined) && !(fns !== undefined && Object.hasOwn(fns, name));
228
233
  },
234
+ givesList(name) {
235
+ return domains.some((d) => Object.hasOwn(d.ops, name) && listItemKind((d.ops[name] as OpSpec<unknown>).returns) !== undefined);
236
+ },
237
+ identities(name) {
238
+ return domains.filter((d) => Object.hasOwn(d.ops, name) && (d.ops[name] as OpSpec<unknown>).identity !== undefined).length;
239
+ },
229
240
  site(name, arity) {
230
241
  // Without values, the interpreter takes no op of a domain. A list op can have a list as its receiver.
231
242
  if (arity === 0 || isListOp(name)) return undefined;
package/src/fn-text.ts ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The text of a function of a domain (COMPILE.MODULE.TEXT). JavaScript gives a text that depends on the loader.
3
+ * A runner can keep the spaces of the types, drop parentheses or change a quote. A module copies such a text,
4
+ * so this file parses it and prints the tree. Equal trees give equal bytes under each runner.
5
+ */
6
+ import { parseExpressionAt } from "acorn";
7
+ import { GENERATOR, generate, type Generator, type State } from "astring";
8
+
9
+ /** A node of the tree. The printer reads only these fields. */
10
+ interface TreeNode {
11
+ readonly type: string;
12
+ readonly value?: unknown;
13
+ readonly name?: string;
14
+ readonly callee?: TreeNode;
15
+ readonly arguments?: readonly TreeNode[];
16
+ }
17
+
18
+ /** The printer of one kind of node. */
19
+ type Print = (node: TreeNode, state: State) => void;
20
+
21
+ /** The printers of the kinds of nodes that the default printer does not change. */
22
+ const PRINTERS = GENERATOR as unknown as Readonly<Record<string, Print>>;
23
+
24
+ /** This function tells if a call only names a function: the runner `tsx` wraps each named function in such a call. */
25
+ function isNameCall(node: TreeNode): boolean {
26
+ const [, name] = node.arguments as readonly TreeNode[];
27
+ return node.callee?.name === "__name" && node.arguments?.length === 2 && typeof name?.value === "string";
28
+ }
29
+
30
+ /** The printers that give one form to each literal, and that remove a call that only names a function. */
31
+ const TEXT_PRINTERS: Readonly<Record<string, Print>> = {
32
+ ...PRINTERS,
33
+ Literal: (node, state) => {
34
+ if (typeof node.value === "string") state.write(JSON.stringify(node.value));
35
+ else if (typeof node.value === "number" && Number.isFinite(node.value)) state.write(String(node.value));
36
+ else (PRINTERS["Literal"] as Print)(node, state);
37
+ },
38
+ CallExpression(node, state) {
39
+ const [fn] = node.arguments as readonly TreeNode[];
40
+ if (isNameCall(node)) (TEXT_PRINTERS[(fn as TreeNode).type] as Print).call(TEXT_PRINTERS, fn as TreeNode, state);
41
+ else (PRINTERS["CallExpression"] as Print).call(TEXT_PRINTERS, node, state);
42
+ },
43
+ };
44
+
45
+ /**
46
+ * This function gives the text of a function, in one form for each runner. A text that does not parse as one expression
47
+ * stays as it is, for example a method or a native function. A module refuses such a text when it tries the copy.
48
+ */
49
+ export function functionText(f: (...a: never[]) => unknown): string {
50
+ const raw = Function.prototype.toString.call(f);
51
+ try {
52
+ const tree = parseExpressionAt(raw, 0, { ecmaVersion: "latest" });
53
+ if (tree.end !== raw.length) return raw;
54
+ return generate(tree, { generator: TEXT_PRINTERS as unknown as Generator, indent: "", lineEnd: " " });
55
+ } catch {
56
+ return raw;
57
+ }
58
+ }
package/src/index.ts CHANGED
@@ -3,6 +3,5 @@
3
3
  */
4
4
  export { generate, load, tiered, type Generated, type GenerateOptions, type Tier2, type TieredProgram, type TierStats } from "./tiers.ts";
5
5
  export type { Schema } from "./facts.ts";
6
- export { emitModule, emitSheetModule, type Emitted, type ListKind, type ModuleOptions, type SheetModuleOptions } from "./module.ts";
7
- export { FALLBACK, createRuntime, type Fallback, type Runtime, type RuntimeOptions } from "./runtime.ts";
8
- export type { LExpr, LoopProgram, LStmt, PrimOp, RuntimeFn } from "./loop.ts";
6
+ export { FALLBACK, createRuntime, type Fallback, type LazyError, type Runtime, type RuntimeOptions } from "./runtime.ts";
7
+ export type { ErrorSite, Fail, LExpr, LoopProgram, LStmt, PrimOp, RuntimeFn } from "./loop.ts";
package/src/js.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import { liftsAt, type ParamKind } from "@mark1russell7/vex";
12
12
  import { primitiveOf, type Facts, type SiteFacts, type StaticSite } from "./facts.ts";
13
- import { constant, FIXED_LOCALS, type Fail, type LExpr, type LoopProgram, type LStmt, type RuntimeFn } from "./loop.ts";
13
+ import { call, constant, FIXED_LOCALS, type Fail, type LExpr, type LoopProgram, type LStmt, type RuntimeFn } from "./loop.ts";
14
14
 
15
15
  type OpExpr = Extract<LExpr, { readonly t: "op" }>;
16
16
 
@@ -28,8 +28,13 @@ function kindCheck(kind: ParamKind | undefined, a: string, d: string): readonly
28
28
 
29
29
  const name = (n: number): string => `l${n}`;
30
30
 
31
- /** This function prints the source of a program. The body gives the function of the program. */
32
- export function printJs(p: LoopProgram, facts: Facts): string {
31
+ /**
32
+ * This function prints the source of a program. The body gives the function of the program. The source of a compile has
33
+ * no indent, so its size stays linear in the block nesting (COMPILE.SOURCE.SIZE). With `indented`, each line shows its
34
+ * block. The golden files read that form, and the two forms differ only in the spaces at the start of a line.
35
+ */
36
+ export function printJs(p: LoopProgram, facts: Facts, indented = false): string {
37
+ const deeper = (indent: string): string => (indented ? `${indent} ` : indent);
33
38
  const used = new Set<RuntimeFn>();
34
39
  const constants = new Set<number>();
35
40
  const sites = new Map<string, string>();
@@ -50,6 +55,10 @@ export function printJs(p: LoopProgram, facts: Facts): string {
50
55
  return String(x.v);
51
56
  case "fallback":
52
57
  return "F";
58
+ case "none":
59
+ return "undefined";
60
+ case "site":
61
+ return `K[${x.i}]`;
53
62
  case "array":
54
63
  return `[${x.items.map(expr).join(", ")}]`;
55
64
  case "call":
@@ -76,6 +85,8 @@ export function printJs(p: LoopProgram, facts: Facts): string {
76
85
  return `Math.${x.op}(${a}, ${b})`;
77
86
  case "isNumber":
78
87
  return `(typeof ${a} === "number")`;
88
+ case "isFinite":
89
+ return `Number.isFinite(${a})`;
79
90
  case "isBoolean":
80
91
  return `(typeof ${a} === "boolean")`;
81
92
  case "isString":
@@ -84,6 +95,8 @@ export function printJs(p: LoopProgram, facts: Facts): string {
84
95
  return `(${a} !== undefined && ${a} !== null)`;
85
96
  case "isObject":
86
97
  return `(typeof ${a} === "object" || typeof ${a} === "function")`;
98
+ case "unless":
99
+ return `(${a} ? undefined : ${b})`;
87
100
  case "get":
88
101
  return `${a}.get(${b})`;
89
102
  case "member":
@@ -96,6 +109,8 @@ export function printJs(p: LoopProgram, facts: Facts): string {
96
109
  return `${a}.keys`;
97
110
  case "idxOf":
98
111
  return `${a}.idx`;
112
+ case "valuesOf":
113
+ return `${a}.values`;
99
114
  case "memoGet":
100
115
  return `${a}.get(${b}, ${c})`;
101
116
  case "memoPut":
@@ -125,13 +140,22 @@ export function printJs(p: LoopProgram, facts: Facts): string {
125
140
  domains.add(i);
126
141
  return `d${i}`;
127
142
  };
143
+ // The record of a result that failed its checks. The result is `FALLBACK` after it.
144
+ const bad = (out: string): string => {
145
+ used.add("bad");
146
+ return `${out} = bad_(${out});`;
147
+ };
148
+ // The check `valid` of the domain at the index `i`, with the record of its failure.
149
+ const validity = (out: string, i: number): string => {
150
+ used.add("invalid");
151
+ return `try { if (!${domain(i)}.valid(${out})) ${bad(out)} } catch (e) { ${out} = invalid_(e, ${i}); }`;
152
+ };
128
153
  // The checks of the result of an op, as `#checkResult` of the interpreter. A domain without `valid` stops the search.
129
154
  const resultChecks = (out: string, checks: readonly boolean[], indent: string): void => {
130
155
  lines.push(`${indent}if (${out} !== F) {`);
131
- lines.push(`${indent} if (${out} === undefined || ${out} === null || (typeof ${out} === "number" && !Number.isFinite(${out}))) ${out} = F;`);
156
+ lines.push(`${indent} if (${out} === undefined || ${out} === null || (typeof ${out} === "number" && !Number.isFinite(${out}))) ${bad(out)}`);
132
157
  checks.forEach((valid, i) => {
133
- const d = domain(i);
134
- lines.push(valid ? `${indent} else if (${d}.is(${out})) { try { if (!${d}.valid(${out})) ${out} = F; } catch (e) { ${out} = threw_(e); } }` : `${indent} else if (${d}.is(${out})) {}`);
158
+ lines.push(valid ? `${indent} else if (${domain(i)}.is(${out})) { ${validity(out, i)} }` : `${indent} else if (${domain(i)}.is(${out})) {}`);
135
159
  });
136
160
  lines.push(`${indent}}`);
137
161
  };
@@ -141,9 +165,9 @@ export function printJs(p: LoopProgram, facts: Facts): string {
141
165
  * the op in a `try`, and checks the result. A number that the op lifts, and each failed guard, go to the dispatch.
142
166
  */
143
167
  const siteBlock = (n: number, x: OpExpr, indent: string): boolean => {
144
- const attempt = (call: string, ind: string): void => {
168
+ const attempt = (invoked: string, ind: string): void => {
145
169
  threw = true;
146
- lines.push(`${ind}try { ${name(n)} = ${call}; } catch (e) { ${name(n)} = threw_(e); }`);
170
+ lines.push(`${ind}try { ${name(n)} = ${invoked}; } catch (e) { ${name(n)} = threw_(e); }`);
147
171
  };
148
172
  const st = facts.staticSite(p.constants[x.name] as string, x.kinds);
149
173
  if (st !== undefined) {
@@ -169,7 +193,7 @@ export function printJs(p: LoopProgram, facts: Facts): string {
169
193
  /**
170
194
  * The block of a static site (KIND.STATIC). The kinds of its values decide its op, so the site uses the function of the
171
195
  * op with no guard. A result of another kind breaks the declaration of the op. Then the program stops, and tier 1
172
- * evaluates it.
196
+ * evaluates it. An argument of a kind that the op does not accept goes to the dispatch, which gives the failure.
173
197
  */
174
198
  const staticBlock = (n: number, x: OpExpr, st: StaticSite, indent: string, attempt: (call: string, ind: string) => void): void => {
175
199
  const out = name(n);
@@ -181,9 +205,8 @@ export function printJs(p: LoopProgram, facts: Facts): string {
181
205
  resultChecks(out, facts.checks, indent);
182
206
  return;
183
207
  }
184
- // An argument of a kind that the op does not accept: the interpreter gives an error.
185
208
  if (st.bad) {
186
- lines.push(`${indent}${out} = F;`);
209
+ lines.push(`${indent}${out} = ${generic(x, siteOf(x), values)};`);
187
210
  return;
188
211
  }
189
212
  const f = `f${x.name}_${st.domain}`;
@@ -197,13 +220,10 @@ export function printJs(p: LoopProgram, facts: Facts): string {
197
220
  return;
198
221
  }
199
222
  lines.push(`${indent}if (${out} !== F && typeof ${out} !== "${kind}") return F; // the kind of the result`);
200
- if (kind === "number") lines.push(`${indent}if (${out} !== F && !Number.isFinite(${out})) ${out} = F;`);
223
+ if (kind === "number") lines.push(`${indent}if (${out} !== F && !Number.isFinite(${out})) ${bad(out)}`);
201
224
  const check = facts.checkOf(kind);
202
225
  if (check === undefined) resultChecks(out, facts.checks, indent);
203
- else if (facts.checks[check] === true) {
204
- const d = domain(check);
205
- lines.push(`${indent}if (${out} !== F) { try { if (!${d}.valid(${out})) ${out} = F; } catch (e) { ${out} = threw_(e); } }`);
206
- }
226
+ else if (facts.checks[check] === true) lines.push(`${indent}if (${out} !== F) { ${validity(out, check)} }`);
207
227
  };
208
228
  const opBlock = (n: number, x: OpExpr, f: Extract<SiteFacts, { readonly t: "op" }>, indent: string, attempt: (call: string, ind: string) => void): void => {
209
229
  const site = siteOf(x);
@@ -214,38 +234,40 @@ export function printJs(p: LoopProgram, facts: Facts): string {
214
234
  const d = domain(f.domain);
215
235
  lines.push(`${indent}${label}: {`);
216
236
  let inner: string;
217
- let call: string;
237
+ let invoked: string;
218
238
  if (f.method) {
219
239
  const m = `m${label}`;
220
240
  lines.push(`${indent} if (typeof ${self} === "object" && ${self} !== null) {`, `${indent} const ${m} = ${site}.m;`);
221
241
  lines.push(`${indent} if (${m} !== undefined && ${self}[${expr(constant(x.name))}] === ${m} && ${d}.is(${self})) {`);
222
242
  inner = `${indent} `;
223
- call = `${self}[${expr(constant(x.name))}](${args.join(", ")})`;
243
+ invoked = `${self}[${expr(constant(x.name))}](${args.join(", ")})`;
224
244
  } else {
225
245
  sites.set(`${site}_f`, `${site}.fn`);
226
246
  lines.push(`${indent} if (${d}.is(${self})) {`);
227
247
  inner = `${indent} `;
228
- call = `${site}_f(${values.join(", ")})`;
248
+ invoked = `${site}_f(${values.join(", ")})`;
229
249
  }
230
250
  const lifted = args.filter((_a, i) => liftsAt(f.lift, i)).map((a) => `typeof ${a} === "number"`);
231
251
  if (lifted.length > 0) lines.push(`${inner}if (${lifted.join(" || ")}) { ${out} = ${generic(x, site, values)}; break ${label}; }`);
232
252
  const kinds = args.flatMap((a, i) => kindCheck(f.params?.[i], a, d));
233
- if (kinds.length > 0) lines.push(`${inner}if (!(${kinds.join(" && ")})) { ${out} = F; break ${label}; }`);
234
- attempt(call, inner);
253
+ if (kinds.length > 0) lines.push(`${inner}if (!(${kinds.join(" && ")})) { ${out} = ${generic(x, site, values)}; break ${label}; }`);
254
+ attempt(invoked, inner);
235
255
  resultChecks(out, facts.checks, inner);
236
256
  lines.push(`${inner}break ${label};`);
237
257
  if (f.method) lines.push(`${indent} }`);
238
258
  lines.push(`${indent} }`, `${indent} ${out} = ${generic(x, site, values)};`, `${indent}}`);
239
259
  };
240
- // The statement of a failure (docs/COMPILER.md §4.1).
241
- const action = (f: Fail): string => {
260
+ // The statement of a failure (docs/COMPILER.md §4.1). A failure that keeps its error always has one (`keeps`).
261
+ const action = (f: Fail, error: LExpr | undefined): string => {
242
262
  switch (f.t) {
243
263
  case "return":
264
+ return `return ${expr(call("raise", error as LExpr))};`;
265
+ case "stop":
244
266
  return "return F;";
245
267
  case "break":
246
- return `break L${f.label};`;
268
+ return f.keep === undefined ? `break L${f.label};` : `{ ${name(f.keep)} = ${expr(error as LExpr)}; break L${f.label}; }`;
247
269
  case "continue":
248
- return f.strict === undefined ? `continue L${f.label};` : `{ if (${expr(f.strict.cond)}) ${action(f.strict.else)} continue L${f.label}; }`;
270
+ return f.strict === undefined ? `continue L${f.label};` : `{ if (${expr(f.strict.cond)}) ${action(f.strict.else, error)} continue L${f.label}; }`;
249
271
  }
250
272
  };
251
273
  const lines: string[] = [];
@@ -260,17 +282,17 @@ export function printJs(p: LoopProgram, facts: Facts): string {
260
282
  lines.push(`${indent}${name(s.n)} = ${expr(s.value)};`);
261
283
  return;
262
284
  case "check":
263
- lines.push(`${indent}if (!(${expr(s.ok)})) ${action(s.fail)} // ${s.reason}`);
285
+ lines.push(`${indent}if (!(${expr(s.ok)})) ${action(s.fail, s.error)} // ${s.reason}`);
264
286
  return;
265
287
  case "fail":
266
- lines.push(`${indent}${action(s.fail)}`);
288
+ lines.push(`${indent}${action(s.fail, s.error)}`);
267
289
  return;
268
290
  case "if":
269
291
  lines.push(`${indent}if (${expr(s.cond)}) {`);
270
- stmts(s.yes, `${indent} `);
292
+ stmts(s.yes, deeper(indent));
271
293
  if (s.no.length > 0) {
272
294
  lines.push(`${indent}} else {`);
273
- stmts(s.no, `${indent} `);
295
+ stmts(s.no, deeper(indent));
274
296
  }
275
297
  lines.push(`${indent}}`);
276
298
  return;
@@ -279,20 +301,23 @@ export function printJs(p: LoopProgram, facts: Facts): string {
279
301
  lines.push(`${indent}${a} = ${expr(s.over)};`);
280
302
  lines.push(`${indent}L${s.label}: for (${i} = 0; ${i} < ${a}.length; ${i}++) {`);
281
303
  lines.push(`${indent} ${name(s.item)} = ${a}[${i}];`);
282
- stmts(s.body, `${indent} `);
304
+ stmts(s.body, deeper(indent));
283
305
  lines.push(`${indent}}`);
284
306
  return;
285
307
  }
286
308
  case "block":
287
309
  lines.push(`${indent}L${s.label}: {`);
288
- stmts(s.body, `${indent} `);
310
+ stmts(s.body, deeper(indent));
289
311
  lines.push(`${indent}}`);
290
312
  return;
291
313
  case "repeat":
292
314
  lines.push(`${indent}L${s.label}: for (;;) {`);
293
- stmts(s.body, `${indent} `);
315
+ stmts(s.body, deeper(indent));
294
316
  lines.push(`${indent}}`);
295
317
  return;
318
+ case "break":
319
+ lines.push(`${indent}break L${s.label};`);
320
+ return;
296
321
  case "next":
297
322
  lines.push(`${indent}continue;`);
298
323
  return;
@@ -322,5 +347,6 @@ export function printJs(p: LoopProgram, facts: Facts): string {
322
347
  ` try {`,
323
348
  ];
324
349
  const tail = [` } catch {`, ` return F;`, ` }`, `};`, ``];
325
- return [...head, ...lines, ...tail].join("\n");
350
+ const text = [...head, ...lines, ...tail];
351
+ return (indented ? text : text.map((line) => line.trimStart())).join("\n");
326
352
  }