@mark1russell7/vex-compiler 0.0.0-stage → 0.8.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/src/runtime.ts ADDED
@@ -0,0 +1,332 @@
1
+ /**
2
+ * The runtime of generated code. Each function follows the rule of the interpreter of the core. Where the interpreter
3
+ * gives an error value, the function gives `FALLBACK`, and tier 1 then does the evaluation again (docs/COMPILER.md §4.1).
4
+ * Thus the runtime makes no error values and no `Result` objects.
5
+ *
6
+ * Generated code uses the runtime inside a `try`, and an exception gives `FALLBACK` for the whole program. A function
7
+ * of the runtime catches an exception only where the interpreter makes a value of it. In an op, it is `#CALC!`, and in
8
+ * `safeIs`, it is `false`. A full call stack is `#DEPTH!`, which no list op and no `ifError` hides, so it goes on to
9
+ * the program.
10
+ */
11
+ import {
12
+ axisTargets,
13
+ findMethod,
14
+ isListOp,
15
+ isStackOverflow,
16
+ isVexList,
17
+ liftsAt,
18
+ matchesKind,
19
+ fixAddr,
20
+ resolveAddr,
21
+ safeIs,
22
+ vexList,
23
+ type Addr,
24
+ type AnyDomain,
25
+ type Axis,
26
+ type FixedMove,
27
+ type FreeFn,
28
+ type Space,
29
+ } from "@mark1russell7/vex";
30
+ import { entryOf, type Entry, type Method, type Options } from "./facts.ts";
31
+
32
+ /** The value of a program that stops at a failed check. */
33
+ export const FALLBACK: unique symbol = Symbol("vex.fallback");
34
+ export type Fallback = typeof FALLBACK;
35
+
36
+ /** The options that a runtime keeps: the domains, the free functions and the extension handlers. */
37
+ export type RuntimeOptions = Options;
38
+
39
+ /**
40
+ * The dispatch of one op name and one number of arguments. With up to 3 arguments, it takes the values themselves, the
41
+ * receiver first. With more, it takes an array of the values. Generated code also reads its fields: the method of the
42
+ * last receiver, the function of the op of the first domain, and the free function.
43
+ */
44
+ export interface Site {
45
+ (...values: never[]): unknown;
46
+ m: Method | undefined;
47
+ readonly fn: Method | undefined;
48
+ readonly free: FreeFn | undefined;
49
+ }
50
+
51
+ /** A base axis: an axis that is not `where`. */
52
+ export type BaseAxis = Exclude<Axis, { readonly t: "where" }>;
53
+
54
+ /** The targets of an axis at a focus: the keys, and the index of each key in `keys` of the space. */
55
+ export interface Targets {
56
+ readonly keys: readonly string[];
57
+ readonly idx: readonly (number | undefined)[];
58
+ }
59
+
60
+ /** An entry of a memo: the value of a node for one space, or no value after an error. */
61
+ export interface MemoEntry {
62
+ readonly v: unknown;
63
+ readonly ok: boolean;
64
+ }
65
+
66
+ /**
67
+ * The memo of one node: an entry for each space and each value of the keys (docs/COMPILER.md §7.2 and §7.3). An entry
68
+ * with an object or a function in its keys is not kept, because each run can make a new one.
69
+ */
70
+ export interface Memo {
71
+ get(s: Space, keys: readonly unknown[]): MemoEntry | undefined;
72
+ put(s: Space, keys: readonly unknown[], v: unknown, ok: boolean): MemoEntry;
73
+ }
74
+
75
+ /** A level of a memo: the entry of the keys so far, and the levels of the next key. */
76
+ interface MemoLevel {
77
+ entry?: MemoEntry;
78
+ next?: Map<unknown, MemoLevel>;
79
+ }
80
+
81
+ /** A map key does not tell 0 from -0, but an op can. Thus -0 has its own key. */
82
+ const NEGATIVE_ZERO = Symbol("-0");
83
+
84
+ /** This function tells if a memo keeps an entry with these keys: keys without objects and functions. */
85
+ const kept = (keys: readonly unknown[]): boolean => keys.every((k) => (typeof k !== "object" || k === null) && typeof k !== "function");
86
+
87
+ /** The functions of the runtime. The names are the names of `RuntimeFn` in the loop IR. */
88
+ export interface Runtime {
89
+ readonly F: Fallback;
90
+ has(s: Space, key: string): boolean;
91
+ /** This function gives the key of an address. `values` has the values of its computed moves (NAV.COMPUTED). */
92
+ addr(s: Space, origin: string, focus: string, at: Addr, values?: readonly unknown[]): unknown;
93
+ /**
94
+ * This function gives the function of the targets of one base axis. A space does not change, so the targets stay in
95
+ * a cache for each space and focus. Generated code gets it once, when it loads.
96
+ */
97
+ axis(axis: BaseAxis): (s: Space, origin: string, focus: string) => Targets | Fallback;
98
+ table(tables: Readonly<Record<string, Space>> | undefined, name: string): unknown;
99
+ keys(s: Space): readonly string[];
100
+ /** This function gives the dispatch of an op name with `arity` arguments. Generated code gets it once, when it loads. */
101
+ site(name: string, arity: number): Site;
102
+ /** This function gives a new memo. Generated code gets one for each node of the memo, when it loads. */
103
+ memo(): Memo;
104
+ /** This function gives the domain at an index of the options. */
105
+ domain(index: number): AnyDomain | undefined;
106
+ /** An exception of an op is the error #CALC! of that op, so this function gives `FALLBACK`. A full call stack goes on. */
107
+ threw(thrown: unknown): Fallback;
108
+ step(name: string, acc: unknown, value: unknown): unknown;
109
+ result(value: unknown): unknown;
110
+ opts(value: unknown): unknown;
111
+ rec(names: readonly string[], values: readonly unknown[]): unknown;
112
+ list(keys: readonly string[], values: readonly unknown[]): unknown;
113
+ frozen(values: readonly unknown[]): unknown;
114
+ ext(kind: string, data: unknown, s: Space, origin: string, focus: string, path: readonly number[]): unknown;
115
+ var(vars: Readonly<Record<string, unknown>> | undefined, name: string): unknown;
116
+ }
117
+
118
+ /** This function makes the runtime of one set of options. */
119
+ export function createRuntime(options: RuntimeOptions): Runtime {
120
+ const domains = options.domains ?? [];
121
+ const fns = options.fns;
122
+ const extensions = options.extensions ?? {};
123
+ const F: Fallback = FALLBACK;
124
+
125
+ const threw = (thrown: unknown): Fallback => {
126
+ if (isStackOverflow(thrown)) throw thrown;
127
+ return F;
128
+ };
129
+
130
+ // The checks of the result of an op: a value, a finite number, and a valid value of its first domain.
131
+ const checked = (value: unknown): unknown => {
132
+ if (value === undefined || value === null) return F;
133
+ if (typeof value === "number" && !Number.isFinite(value)) return F;
134
+ for (const d of domains) {
135
+ if (safeIs(d, value)) return d.valid === undefined || d.valid(value) ? value : F;
136
+ }
137
+ return value;
138
+ };
139
+
140
+ // The call of an op, as `#call` of the interpreter: the lift of numbers, the kinds of the parameters, the call, and
141
+ // the checks of the result.
142
+ const invoke = (e: Entry, call: (args: readonly unknown[]) => unknown, rest: readonly unknown[]): unknown => {
143
+ try {
144
+ const lift = e.spec.liftScalar;
145
+ const from = e.domain.fromScalar;
146
+ const args = lift && from !== undefined ? rest.map((a, i): unknown => (typeof a === "number" && liftsAt(lift, i) ? from(a) : a)) : rest;
147
+ const params = e.spec.params;
148
+ if (params !== undefined && !args.every((a, i) => matchesKind(params[i] ?? "any", a, e.domain))) return F;
149
+ return checked(call(args));
150
+ } catch (thrown) {
151
+ return threw(thrown);
152
+ }
153
+ };
154
+
155
+ // The op of a name for a receiver: the first domain that accepts the receiver and has the op. `undefined` is no op.
156
+ // `seen` receives each method that the dispatch finds.
157
+ const dispatch = (entries: readonly (Entry | undefined)[], name: string, values: readonly unknown[], seen?: (m: Method) => void): unknown => {
158
+ const [self, ...rest] = values;
159
+ for (const e of entries) {
160
+ if (e === undefined || !safeIs(e.domain, self)) continue;
161
+ const fn = e.fn;
162
+ if (fn !== undefined) return invoke(e, (args) => fn(self, ...args), rest);
163
+ const method = findMethod(self, name);
164
+ if (method === undefined) continue;
165
+ seen?.(method);
166
+ return invoke(e, (args) => method.apply(self, [...args]), rest);
167
+ }
168
+ return undefined;
169
+ };
170
+
171
+ const entriesOf = (name: string): readonly (Entry | undefined)[] => domains.map((d) => entryOf(d, name));
172
+
173
+ // The entries of the op names of reduce. A program can compute such a name, so the runtime keeps them by name.
174
+ const stepEntries = new Map<string, readonly (Entry | undefined)[]>();
175
+
176
+ // The index of each key of a space, for the targets of an axis. A miss of the cache only makes the map again.
177
+ const indexes = new WeakMap<Space, ReadonlyMap<string, number>>();
178
+ const indexOf = (s: Space): ReadonlyMap<string, number> => {
179
+ let m = indexes.get(s);
180
+ // Stryker disable next-line ConditionalExpression: see the comment above
181
+ if (m === undefined) {
182
+ m = new Map(s.keys.map((k, i) => [k, i]));
183
+ // Stryker disable next-line CallExpression: see the comment above
184
+ indexes.set(s, m);
185
+ }
186
+ return m;
187
+ };
188
+
189
+ return {
190
+ F,
191
+ has: (s, key) => s.has(key),
192
+ addr(s, origin, focus, at, values) {
193
+ const pos = { origin, focus };
194
+ // An address without computed moves has no values, and its moves are fixed.
195
+ // Stryker disable next-line ConditionalExpression: fixAddr gives the same fixed moves, so the test only saves an array
196
+ const fixed = values === undefined ? undefined : fixAddr(at, values, pos);
197
+ if (fixed?.ok === false) return F;
198
+ const r = resolveAddr(s, pos, fixed === undefined ? (at as readonly FixedMove[]) : fixed.value);
199
+ return r.ok ? r.value : F;
200
+ },
201
+ axis(axis) {
202
+ const cache = new WeakMap<Space, Map<string, Targets | Fallback>>();
203
+ return (s, origin, focus) => {
204
+ let byFocus = cache.get(s);
205
+ if (byFocus === undefined) {
206
+ byFocus = new Map();
207
+ cache.set(s, byFocus);
208
+ }
209
+ let targets = byFocus.get(focus);
210
+ if (targets === undefined) {
211
+ const r = axisTargets(s, { origin, focus }, axis);
212
+ const index = indexOf(s);
213
+ targets = r.ok ? { keys: r.value, idx: r.value.map((k) => index.get(k)) } : F;
214
+ byFocus.set(focus, targets);
215
+ }
216
+ return targets;
217
+ };
218
+ },
219
+ table(tables, name) {
220
+ const t = tables !== undefined && Object.hasOwn(tables, name) ? tables[name] : undefined;
221
+ return t ?? F;
222
+ },
223
+ keys: (s) => s.keys,
224
+ // The dispatch of `app` in the interpreter: the first domain that accepts the receiver and has the op, and else a
225
+ // free function. Generated code has the fast path of each site, and it uses this dispatch for each other case.
226
+ site(name, arity) {
227
+ const entries = entriesOf(name);
228
+ const listOp = isListOp(name);
229
+ const fn = fns !== undefined && Object.hasOwn(fns, name) ? fns[name] : undefined;
230
+ const generic = (values: readonly unknown[]): unknown => {
231
+ // A list op on a list value is not an error, but tier 2 does not have it. The exception stops the program.
232
+ // Stryker disable next-line StringLiteral: the program catches the exception, so no one reads its message
233
+ if (listOp && isVexList(values[0])) throw new Error("tier 1 gives a list op on a list value");
234
+ if (values.length > 0) {
235
+ const r = dispatch(entries, name, values, (m) => {
236
+ site.m = m;
237
+ });
238
+ if (r !== undefined) return r;
239
+ }
240
+ try {
241
+ // Stryker disable next-line ConditionalExpression: a call of undefined throws, and the catch also gives F
242
+ return fn === undefined ? F : checked(fn(...values));
243
+ } catch (thrown) {
244
+ return threw(thrown);
245
+ }
246
+ };
247
+ const call = arity <= 3 ? (...values: unknown[]): unknown => generic(values) : generic;
248
+ const site: Site = Object.assign(call, { m: undefined, fn: entries.find((e) => e !== undefined)?.fn, free: fn });
249
+ return site;
250
+ },
251
+ memo() {
252
+ const spaces = new WeakMap<Space, MemoLevel>();
253
+ // The level of a space and some keys. With `make`, the function makes each missing level. A level that a read
254
+ // makes only uses memory, so the checks of `make` have no other effect.
255
+ const level = (s: Space, keys: readonly unknown[], make: boolean): MemoLevel | undefined => {
256
+ let at: MemoLevel | undefined = spaces.get(s);
257
+ if (at === undefined) {
258
+ // A read comes before each write, so the level of the space exists for each write.
259
+ // Stryker disable next-line ConditionalExpression,BooleanLiteral: see the comments above
260
+ if (!make) return undefined;
261
+ at = {};
262
+ spaces.set(s, at);
263
+ }
264
+ for (const k of keys) {
265
+ // Stryker disable next-line UnaryOperator: with +0 as the special key, 0 and -0 still get different entries
266
+ const slot = Object.is(k, -0) ? NEGATIVE_ZERO : k;
267
+ let next: MemoLevel | undefined = at.next?.get(slot);
268
+ if (next === undefined) {
269
+ // Stryker disable next-line ConditionalExpression: see the comment above
270
+ if (!make) return undefined;
271
+ next = {};
272
+ (at.next ??= new Map()).set(slot, next);
273
+ }
274
+ at = next;
275
+ }
276
+ return at;
277
+ };
278
+ return {
279
+ // Stryker disable next-line BooleanLiteral: a read that makes the levels only uses memory
280
+ get: (s, keys) => level(s, keys, false)?.entry,
281
+ put(s, keys, v, ok) {
282
+ const e = { v, ok };
283
+ if (kept(keys)) (level(s, keys, true) as MemoLevel).entry = e;
284
+ return e;
285
+ },
286
+ };
287
+ },
288
+ domain: (index) => domains[index],
289
+ threw,
290
+ // One step of `reduce`: the first domain that accepts the accumulator and has the op. No free function.
291
+ step(name, acc, value) {
292
+ let entries = stepEntries.get(name);
293
+ // A miss of the cache only reads the op tables again.
294
+ // Stryker disable ConditionalExpression,BlockStatement,CallExpression
295
+ if (entries === undefined) {
296
+ entries = entriesOf(name);
297
+ stepEntries.set(name, entries);
298
+ }
299
+ // Stryker restore ConditionalExpression,BlockStatement,CallExpression
300
+ return dispatch(entries, name, [acc, value]) ?? F;
301
+ },
302
+ result(value) {
303
+ try {
304
+ return checked(value);
305
+ } catch (thrown) {
306
+ return threw(thrown);
307
+ }
308
+ },
309
+ // A list op reads the option `strict` of its options. The read can throw, as in the interpreter.
310
+ opts: (value) => (value as { readonly strict?: unknown } | null | undefined)?.strict,
311
+ rec(names, values) {
312
+ const out: Record<string, unknown> = {};
313
+ names.forEach((n, i) => {
314
+ out[n] = values[i];
315
+ });
316
+ return Object.freeze(out);
317
+ },
318
+ list: (keys, values) => vexList(keys.map((key, i) => ({ key, result: { ok: true, value: values[i] } }))),
319
+ frozen: (values) => Object.freeze([...values]),
320
+ ext(kind, data, s, origin, focus, path) {
321
+ const handler = Object.hasOwn(extensions, kind) ? extensions[kind] : undefined;
322
+ // Stryker disable next-line ConditionalExpression: a call of undefined throws, and the program gives F for it too
323
+ if (handler === undefined) return F;
324
+ const r = handler(data, { space: s, position: { origin, focus }, path });
325
+ return r.ok ? r.value : F;
326
+ },
327
+ // The interpreter reads the own enumerable properties of the variables, with `Object.entries`.
328
+ var(vars, name) {
329
+ return vars !== undefined && Object.prototype.propertyIsEnumerable.call(vars, name) ? vars[name] : F;
330
+ },
331
+ };
332
+ }
package/src/tiers.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The tiers (docs/COMPILER.md §2.1). Tier 2 is generated JavaScript. Tier 1 is the closure compiler of the core, and it
3
+ * gives each result that tier 2 cannot give. Thus a tiered program gives the results of the interpreter.
4
+ */
5
+ import { compile, ok, type CompileOptions, type Expr, type Program, type Space } from "@mark1russell7/vex";
6
+ import { factsOf, type Schema } from "./facts.ts";
7
+
8
+ /** The options of the compiler: the options of `compile`, and the schema of the host (docs/COMPILER.md §3.2). */
9
+ export type GenerateOptions = CompileOptions & { readonly schema?: Schema };
10
+ import { printJs } from "./js.ts";
11
+ import type { LoopProgram } from "./loop.ts";
12
+ import { lower, Unsupported } from "./lower.ts";
13
+ import { createRuntime, FALLBACK } from "./runtime.ts";
14
+
15
+ /**
16
+ * The output of `generate`: the loop IR and the source of a program, and the options that the source is for. Or else
17
+ * the reason that the compiler cannot lower the program.
18
+ */
19
+ export type Generated =
20
+ | { readonly ok: true; readonly program: LoopProgram; readonly source: string; readonly options: GenerateOptions }
21
+ | { readonly ok: false; readonly reason: string };
22
+
23
+ /** A function of tier 2. It gives the value of the program, or `FALLBACK`. */
24
+ export type Tier2 = (space: Space, origin: string, vars: Readonly<Record<string, unknown>> | undefined, tables: Readonly<Record<string, Space>> | undefined) => unknown;
25
+
26
+ /**
27
+ * This function lowers an expression and prints its source for the options. The op tables of the domains give the
28
+ * fast path of each op site. It is pure, so a build can use it.
29
+ */
30
+ export function generate(expr: Expr, options: GenerateOptions = {}): Generated {
31
+ try {
32
+ const facts = factsOf(options);
33
+ const program = lower(expr, facts, options.schema);
34
+ return { ok: true, program, source: printJs(program, facts), options };
35
+ } catch (thrown) {
36
+ // A stack overflow in the lowering of a deep expression also goes to tier 1.
37
+ return { ok: false, reason: thrown instanceof Unsupported ? thrown.message : "the lowering threw an exception" };
38
+ }
39
+ }
40
+
41
+ /**
42
+ * This function makes the function of tier 2 with `new Function`, with the options of the source. It throws on a page
43
+ * that does not permit `new Function`.
44
+ */
45
+ export function load(generated: Extract<Generated, { readonly ok: true }>): Tier2 {
46
+ // oxlint-disable-next-line typescript/no-implied-eval -- the source comes from printJs, and it reads each name and literal from K (§5).
47
+ const make = new Function("K", "R", generated.source) as (k: readonly unknown[], r: ReturnType<typeof createRuntime>) => Tier2;
48
+ return make(generated.program.constants, createRuntime(generated.options));
49
+ }
50
+
51
+ /** The counts of the runs of a tiered program. */
52
+ export interface TierStats {
53
+ /** The number of runs. */
54
+ readonly runs: number;
55
+ /** The number of runs where tier 2 gave `FALLBACK`, so tier 1 gave the result. */
56
+ readonly fallbacks: number;
57
+ }
58
+
59
+ /** A program with tiers. It has the interface `Program` of the core, so it can replace a compiled program. */
60
+ export interface TieredProgram extends Program {
61
+ /** The tier of the program: 2 when it has generated code, and else 1. */
62
+ readonly tier: 1 | 2;
63
+ /** The reason that the program has no generated code. */
64
+ readonly reason?: string;
65
+ readonly stats: TierStats;
66
+ }
67
+
68
+ /**
69
+ * This function compiles an expression into tier 2 if it can, and else into tier 1. After a failed check of tier 2,
70
+ * tier 1 does that evaluation again. A run with a trace and `explain` always use tier 1, because tier 2 makes no trace.
71
+ */
72
+ export function tiered(expr: Expr, options: GenerateOptions = {}): TieredProgram {
73
+ const slow = compile(expr, options);
74
+ const generated = generate(expr, options);
75
+ let fast: Tier2 | undefined;
76
+ let reason: string | undefined;
77
+ if (generated.ok) {
78
+ try {
79
+ fast = load(generated);
80
+ } catch {
81
+ reason = "the page does not permit new Function";
82
+ }
83
+ } else {
84
+ reason = generated.reason;
85
+ }
86
+ const stats = { runs: 0, fallbacks: 0 };
87
+ return {
88
+ expr,
89
+ tier: fast === undefined ? 1 : 2,
90
+ ...(reason === undefined ? {} : { reason }),
91
+ stats,
92
+ run(r) {
93
+ stats.runs++;
94
+ if (fast === undefined || r.trace !== undefined) return slow.run(r);
95
+ const value = fast(r.space, r.origin, r.vars, r.tables);
96
+ if (value !== FALLBACK) return ok(value);
97
+ stats.fallbacks++;
98
+ return slow.run(r);
99
+ },
100
+ explain: (r) => slow.explain(r),
101
+ };
102
+ }