@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/LICENSE +21 -0
- package/README.md +73 -2
- package/build/index.d.ts +297 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +3736 -0
- package/build/index.js.map +1 -0
- package/package.json +60 -3
- package/src/facts.ts +206 -0
- package/src/index.ts +8 -0
- package/src/js.ts +324 -0
- package/src/loop.ts +138 -0
- package/src/lower.ts +710 -0
- package/src/memo.ts +235 -0
- package/src/module.ts +1723 -0
- package/src/runtime.ts +332 -0
- package/src/tiers.ts +102 -0
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
|
+
"$schema": "https://json.schemastore.org/package",
|
|
2
3
|
"name": "@mark1russell7/vex-compiler",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
4
|
+
"version": "0.8.0",
|
|
5
|
+
"description": "The Vex compiler: generated JavaScript for Vex programs, at run time and at build time, with the results of the interpreter.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"vex",
|
|
8
|
+
"compiler",
|
|
9
|
+
"codegen",
|
|
10
|
+
"jit",
|
|
11
|
+
"spreadsheet",
|
|
12
|
+
"typescript"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://mark1russell7.github.io/vex/",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/mark1russell7/vex/issues"
|
|
17
|
+
},
|
|
18
|
+
"author": "Mark Russell (https://github.com/mark1russell7)",
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/mark1russell7/vex.git",
|
|
23
|
+
"directory": "packages/compiler"
|
|
24
|
+
},
|
|
25
|
+
"type": "module",
|
|
26
|
+
"main": "./build/index.js",
|
|
27
|
+
"types": "./build/index.d.ts",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./build/index.d.ts",
|
|
31
|
+
"default": "./build/index.js"
|
|
32
|
+
},
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"build",
|
|
37
|
+
"src",
|
|
38
|
+
"!src/**/*.test.ts",
|
|
39
|
+
"!src/__golden__"
|
|
40
|
+
],
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@mark1russell7/cue": "github:mark1russell7/cue",
|
|
46
|
+
"@mark1russell7/vex-domains": "0.8.0",
|
|
47
|
+
"@mark1russell7/vex-testkit": "0.8.0",
|
|
48
|
+
"@types/node": "^26.6.4",
|
|
49
|
+
"fast-check": "^4.10.2",
|
|
50
|
+
"typescript": "^7.0.2",
|
|
51
|
+
"vitest": "^5.0.3"
|
|
52
|
+
},
|
|
53
|
+
"dependencies": {
|
|
54
|
+
"@mark1russell7/vex": "0.8.0"
|
|
55
|
+
},
|
|
56
|
+
"scripts": {
|
|
57
|
+
"build": "tsdown",
|
|
58
|
+
"test": "vitest run",
|
|
59
|
+
"test:watch": "vitest",
|
|
60
|
+
"bench:gate": "node bench/gate.ts",
|
|
61
|
+
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test.json"
|
|
62
|
+
}
|
|
6
63
|
}
|
package/src/facts.ts
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The facts of the options that the printer uses (docs/COMPILER.md §13.2). For each op site, they give the domain
|
|
3
|
+
* whose op the interpreter takes first, and the kinds and the lifts of its parameters. The facts come from the op
|
|
4
|
+
* tables, so the same options always give the same facts, and the same source.
|
|
5
|
+
*/
|
|
6
|
+
import { children, isListOp, isOpName, liftsAt, listOf, type AnyDomain, type Expr, type ExtHandler, type FreeFn, type OpSpec, type ParamKind, type PrimitiveKind, type ReturnKind } from "@mark1russell7/vex";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The most bodies of functions that tier 2 puts at the calls of one program. A function that calls another function
|
|
10
|
+
* twice doubles its body, so a chain of such functions grows fast. A module prints each function once.
|
|
11
|
+
*/
|
|
12
|
+
export const MAX_CALLS = 10_000;
|
|
13
|
+
|
|
14
|
+
/** The list ops that give a list or read a position of a list (LIST.SORT, LIST.TAKE, LIST.NTH). */
|
|
15
|
+
const ORDER_OPS: ReadonlySet<string> = new Set(["sortBy", "take", "nth"]);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* This function gives the reason that tier 2 cannot take a program with lists as values. The reason is the axis `list`
|
|
19
|
+
* or an op on the order of a list. Tier 1 evaluates such a program. It uses a stack, not recursion.
|
|
20
|
+
*/
|
|
21
|
+
export function listReason(expr: Expr): string | undefined {
|
|
22
|
+
const todo: Expr[] = [expr];
|
|
23
|
+
for (let x = todo.pop(); x !== undefined; x = todo.pop()) {
|
|
24
|
+
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';
|
|
25
|
+
// Stryker disable next-line ConditionalExpression: a node that is not an app has no field op, so the set does not have it
|
|
26
|
+
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`;
|
|
27
|
+
todo.push(...children(x));
|
|
28
|
+
}
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The function of an op of a domain, or a method. */
|
|
33
|
+
export type Method = (...args: unknown[]) => unknown;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The kind of a value that the compiler knows: a primitive type, or `domain:Name`. The second kind is for a value of
|
|
37
|
+
* the domain `Name` without a primitive type (KIND.DOMAIN).
|
|
38
|
+
*/
|
|
39
|
+
export type Kind = PrimitiveKind | `domain:${string}`;
|
|
40
|
+
|
|
41
|
+
/** This function gives the kind of the values of a domain. */
|
|
42
|
+
export const kindOfDomain = (d: AnyDomain): Kind => d.primitive ?? `domain:${d.name}`;
|
|
43
|
+
|
|
44
|
+
/** This function gives a kind if it is a primitive type, else `undefined`. */
|
|
45
|
+
export const primitiveOf = (k: Kind | undefined): PrimitiveKind | undefined => (k === "number" || k === "string" || k === "boolean" ? k : undefined);
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The kinds that a host declares (docs/COMPILER.md §3.2): the kind of each field of the records, and of each variable of
|
|
49
|
+
* the run. A read of a declared field or variable checks the kind. When the check fails, tier 1 evaluates the program.
|
|
50
|
+
*/
|
|
51
|
+
export interface Schema {
|
|
52
|
+
readonly fields?: Readonly<Record<string, Kind>>;
|
|
53
|
+
readonly vars?: Readonly<Record<string, Kind>>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The options of a program: the domains, the free functions and the extension handlers, and the schema of the host. */
|
|
57
|
+
export interface Options {
|
|
58
|
+
readonly domains?: readonly AnyDomain[];
|
|
59
|
+
readonly fns?: Readonly<Record<string, FreeFn>>;
|
|
60
|
+
readonly extensions?: Readonly<Record<string, ExtHandler>>;
|
|
61
|
+
readonly schema?: Schema;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The op of one name in one domain, as `resolveOp` of the core finds it. It is the function of the spec, or else a
|
|
66
|
+
* method of the receiver.
|
|
67
|
+
*/
|
|
68
|
+
export interface Entry {
|
|
69
|
+
readonly domain: AnyDomain;
|
|
70
|
+
readonly spec: OpSpec<unknown>;
|
|
71
|
+
readonly fn: Method | undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const NO_SPEC: OpSpec<unknown> = Object.freeze({});
|
|
75
|
+
|
|
76
|
+
/** This function gives the op of a name in a domain, or `undefined` for a domain without the op. */
|
|
77
|
+
export function entryOf(domain: AnyDomain, name: string): Entry | undefined {
|
|
78
|
+
if (!isOpName(name)) return undefined;
|
|
79
|
+
const declared = Object.hasOwn(domain.ops, name) ? (domain.ops[name] as OpSpec<unknown>) : undefined;
|
|
80
|
+
if (declared === undefined) return domain.methods === "all" ? { domain, spec: NO_SPEC, fn: undefined } : undefined;
|
|
81
|
+
return { domain, spec: declared, fn: declared.fn as Method | undefined };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The facts of an op site:
|
|
86
|
+
* - `op`: the op of the domain `domain` comes first. It is a method of the receiver, or else the function of the spec.
|
|
87
|
+
* `params` are the kinds of the parameters, and `lift` lifts numbers (`liftScalar`, if the domain has `fromScalar`).
|
|
88
|
+
* - `free`: no domain has the op, and a free function has the name.
|
|
89
|
+
*
|
|
90
|
+
* Without facts, the site uses the dispatch of the runtime only.
|
|
91
|
+
*/
|
|
92
|
+
export type SiteFacts =
|
|
93
|
+
| {
|
|
94
|
+
readonly t: "op";
|
|
95
|
+
readonly domain: number;
|
|
96
|
+
readonly method: boolean;
|
|
97
|
+
readonly params: readonly ParamKind[] | undefined;
|
|
98
|
+
readonly lift: OpSpec<unknown>["liftScalar"];
|
|
99
|
+
}
|
|
100
|
+
| { readonly t: "free" };
|
|
101
|
+
|
|
102
|
+
const FREE: SiteFacts = Object.freeze({ t: "free" });
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The op of a site whose values have known kinds (KIND.STATIC):
|
|
106
|
+
* - `fn`: the function of the op of the domain `domain`. `bad` is true when an argument has a kind that the op does
|
|
107
|
+
* not accept, so the interpreter gives an error. `returns` is the kind of the result, if the op declares it.
|
|
108
|
+
* - `free`: no domain that accepts the receiver has the op, and a free function has the name.
|
|
109
|
+
*/
|
|
110
|
+
export type StaticSite =
|
|
111
|
+
| { readonly t: "fn"; readonly domain: number; readonly bad: boolean; readonly returns: Kind | undefined }
|
|
112
|
+
| { readonly t: "free" };
|
|
113
|
+
|
|
114
|
+
const STATIC_FREE: StaticSite = Object.freeze({ t: "free" });
|
|
115
|
+
|
|
116
|
+
/** This function gives the kind of the result of an op of a domain, if the op declares it. */
|
|
117
|
+
function returnsOf(domain: AnyDomain, kind: ReturnKind | undefined): Kind | undefined {
|
|
118
|
+
if (kind === "domain") return kindOfDomain(domain);
|
|
119
|
+
return kind === "any" ? undefined : kind;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** This function tells if an argument of a kind fits a parameter, or `undefined` if the kind of the argument is unknown. */
|
|
123
|
+
function fits(domain: AnyDomain, param: ParamKind | undefined, arg: Kind | undefined): boolean | undefined {
|
|
124
|
+
if (param === undefined || param === "any") return true;
|
|
125
|
+
if (arg === undefined) return undefined;
|
|
126
|
+
return arg === (param === "domain" ? kindOfDomain(domain) : param);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* This function tells if a domain accepts a value of a kind. A domain with a primitive type accepts its type, and a
|
|
131
|
+
* domain without one accepts the values of its kind. For another value, it gives `undefined`: its `is` can accept it.
|
|
132
|
+
*/
|
|
133
|
+
function accepts(d: AnyDomain, kind: Kind): boolean | undefined {
|
|
134
|
+
if (d.primitive !== undefined) return d.primitive === kind;
|
|
135
|
+
return kind === kindOfDomain(d) ? true : undefined;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** The facts of the options. */
|
|
139
|
+
export interface Facts {
|
|
140
|
+
/** This function gives the facts of the site of the op `name` with `arity` values, the receiver first, if it has facts. */
|
|
141
|
+
site(name: string, arity: number): SiteFacts | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* The checks of the result of an op, as `#checkResult` of the interpreter: for each domain, `true` if it has `valid`.
|
|
144
|
+
* The list ends at the last domain with `valid`, because the domains after it check nothing.
|
|
145
|
+
*/
|
|
146
|
+
readonly checks: readonly boolean[];
|
|
147
|
+
/**
|
|
148
|
+
* This function gives the op of a site with the kinds of its values, the receiver first. When the kinds do not decide
|
|
149
|
+
* the op, it gives `undefined`. Each domain before the op must declare a primitive type. Then the interpreter takes
|
|
150
|
+
* the same op at each run.
|
|
151
|
+
*/
|
|
152
|
+
staticSite(name: string, kinds: readonly (Kind | undefined)[]): StaticSite | undefined;
|
|
153
|
+
/**
|
|
154
|
+
* This function gives the index of the domain that checks a result of a kind. When no domain accepts such a value,
|
|
155
|
+
* it gives -1. When a domain without a primitive type comes first, it gives `undefined`.
|
|
156
|
+
*/
|
|
157
|
+
checkOf(kind: Kind): number | undefined;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** This function gives the facts of a set of options. */
|
|
161
|
+
export function factsOf(options: Options): Facts {
|
|
162
|
+
const domains = options.domains ?? [];
|
|
163
|
+
const fns = options.fns;
|
|
164
|
+
const last = domains.findLastIndex((d) => d.valid !== undefined);
|
|
165
|
+
return {
|
|
166
|
+
checks: domains.slice(0, last + 1).map((d) => d.valid !== undefined),
|
|
167
|
+
staticSite(name, kinds) {
|
|
168
|
+
const [self, ...args] = kinds;
|
|
169
|
+
// A primitive value is not a list, so a list op name is an op of a domain here, as in the interpreter.
|
|
170
|
+
if (self === undefined) return undefined;
|
|
171
|
+
for (const [i, d] of domains.entries()) {
|
|
172
|
+
const takes = accepts(d, self);
|
|
173
|
+
if (takes === undefined) return undefined;
|
|
174
|
+
const e = takes ? entryOf(d, name) : undefined;
|
|
175
|
+
// A primitive value has no methods, so only the function of a spec is an op for it. The domain of a value without
|
|
176
|
+
// a primitive type can have methods, and a later domain can accept the value too.
|
|
177
|
+
if (e?.fn === undefined) {
|
|
178
|
+
if (takes && d.primitive === undefined) return undefined;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
// A lifted number goes through fromScalar: the site keeps the dispatch of the runtime.
|
|
182
|
+
if (d.fromScalar !== undefined && args.some((a, j) => a !== "string" && a !== "boolean" && liftsAt(e.spec.liftScalar, j))) return undefined;
|
|
183
|
+
const ok = args.map((a, j) => fits(d, e.spec.params?.[j], a));
|
|
184
|
+
if (ok.includes(undefined)) return undefined;
|
|
185
|
+
return { t: "fn", domain: i, bad: ok.includes(false), returns: returnsOf(d, e.spec.returns) };
|
|
186
|
+
}
|
|
187
|
+
return fns !== undefined && Object.hasOwn(fns, name) ? STATIC_FREE : undefined;
|
|
188
|
+
},
|
|
189
|
+
checkOf(kind) {
|
|
190
|
+
for (const [i, d] of domains.entries()) {
|
|
191
|
+
const takes = accepts(d, kind);
|
|
192
|
+
if (takes === undefined) return undefined;
|
|
193
|
+
if (takes) return i;
|
|
194
|
+
}
|
|
195
|
+
return -1;
|
|
196
|
+
},
|
|
197
|
+
site(name, arity) {
|
|
198
|
+
// Without values, the interpreter takes no op of a domain. A list op can have a list as its receiver.
|
|
199
|
+
if (arity === 0 || isListOp(name)) return undefined;
|
|
200
|
+
const index = domains.findIndex((d) => entryOf(d, name) !== undefined);
|
|
201
|
+
if (index < 0) return fns !== undefined && Object.hasOwn(fns, name) ? FREE : undefined;
|
|
202
|
+
const e = entryOf(domains[index] as AnyDomain, name) as Entry;
|
|
203
|
+
return { t: "op", domain: index, method: e.fn === undefined, params: e.spec.params, lift: e.domain.fromScalar === undefined ? undefined : e.spec.liftScalar };
|
|
204
|
+
},
|
|
205
|
+
};
|
|
206
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Vex compiler (docs/COMPILER.md): generated JavaScript for Vex programs, with the results of the interpreter.
|
|
3
|
+
*/
|
|
4
|
+
export { generate, load, tiered, type Generated, type GenerateOptions, type Tier2, type TieredProgram, type TierStats } from "./tiers.ts";
|
|
5
|
+
export type { Schema } from "./facts.ts";
|
|
6
|
+
export { emitModule, type Emitted, type ModuleOptions } 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";
|
package/src/js.ts
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The back end of JavaScript source (docs/COMPILER.md §3.4). It prints a program of the loop IR as the body of a
|
|
3
|
+
* function with the parameters `K` (the constants) and `R` (the runtime).
|
|
4
|
+
*
|
|
5
|
+
* The source has no name and no literal of the program as text: it reads each one from `K`, by its index (§5). The
|
|
6
|
+
* same program and the same facts always give the same source.
|
|
7
|
+
*
|
|
8
|
+
* With the facts of the options, each op site gets its fast path in the source (§13.2). Each site then has its own
|
|
9
|
+
* inline caches in the engine, and a guard sends each other case to the dispatch of the runtime.
|
|
10
|
+
*/
|
|
11
|
+
import { liftsAt, type ParamKind } from "@mark1russell7/vex";
|
|
12
|
+
import type { Facts, SiteFacts, StaticSite } from "./facts.ts";
|
|
13
|
+
import { constant, FIXED_LOCALS, type Fail, type LExpr, type LoopProgram, type LStmt, type RuntimeFn } from "./loop.ts";
|
|
14
|
+
|
|
15
|
+
type OpExpr = Extract<LExpr, { readonly t: "op" }>;
|
|
16
|
+
|
|
17
|
+
/** This function gives the call of the dispatch of a site. With more than 3 values, the dispatch takes an array. */
|
|
18
|
+
function generic(x: OpExpr, site: string, values: readonly string[]): string {
|
|
19
|
+
return x.args.length <= 3 ? `${site}(${values.join(", ")})` : `${site}([${values.join(", ")}])`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** This function gives the check of an argument of the kind `kind`, for an op of the domain `d`. */
|
|
23
|
+
function kindCheck(kind: ParamKind | undefined, a: string, d: string): readonly string[] {
|
|
24
|
+
if (kind === "domain") return [`${d}.is(${a})`];
|
|
25
|
+
if (kind === "number" || kind === "boolean" || kind === "string") return [`typeof ${a} === "${kind}"`];
|
|
26
|
+
return [];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const name = (n: number): string => `l${n}`;
|
|
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 {
|
|
33
|
+
const used = new Set<RuntimeFn>();
|
|
34
|
+
const constants = new Set<number>();
|
|
35
|
+
const sites = new Map<string, string>();
|
|
36
|
+
const domains = new Set<number>();
|
|
37
|
+
// The functions of the ops of the static sites. They read the domains, so they come after them.
|
|
38
|
+
const fns = new Map<string, string>();
|
|
39
|
+
let threw = false;
|
|
40
|
+
let siteLabels = 0;
|
|
41
|
+
const expr = (x: LExpr): string => {
|
|
42
|
+
switch (x.t) {
|
|
43
|
+
case "const":
|
|
44
|
+
constants.add(x.i);
|
|
45
|
+
return `k${x.i}`;
|
|
46
|
+
case "local":
|
|
47
|
+
return name(x.n);
|
|
48
|
+
case "num":
|
|
49
|
+
case "bool":
|
|
50
|
+
return String(x.v);
|
|
51
|
+
case "fallback":
|
|
52
|
+
return "F";
|
|
53
|
+
case "array":
|
|
54
|
+
return `[${x.items.map(expr).join(", ")}]`;
|
|
55
|
+
case "call":
|
|
56
|
+
used.add(x.fn);
|
|
57
|
+
return `${x.fn}_(${x.args.map(expr).join(", ")})`;
|
|
58
|
+
case "op":
|
|
59
|
+
return generic(x, siteOf(x), x.args.map(expr));
|
|
60
|
+
case "memo":
|
|
61
|
+
sites.set(`mo${x.id}`, "R.memo()");
|
|
62
|
+
return `mo${x.id}`;
|
|
63
|
+
case "targets": {
|
|
64
|
+
// An axis has one function of targets for each site, with its cache.
|
|
65
|
+
const site = `a${x.axis}`;
|
|
66
|
+
sites.set(site, `R.axis(${expr(constant(x.axis))})`);
|
|
67
|
+
return `${site}(${x.args.map(expr).join(", ")})`;
|
|
68
|
+
}
|
|
69
|
+
case "prim": {
|
|
70
|
+
const [a, b, c, d, e] = x.args.map(expr);
|
|
71
|
+
switch (x.op) {
|
|
72
|
+
case "!":
|
|
73
|
+
return `(!${a})`;
|
|
74
|
+
case "min":
|
|
75
|
+
case "max":
|
|
76
|
+
return `Math.${x.op}(${a}, ${b})`;
|
|
77
|
+
case "isNumber":
|
|
78
|
+
return `(typeof ${a} === "number")`;
|
|
79
|
+
case "isBoolean":
|
|
80
|
+
return `(typeof ${a} === "boolean")`;
|
|
81
|
+
case "isString":
|
|
82
|
+
return `(typeof ${a} === "string")`;
|
|
83
|
+
case "isValue":
|
|
84
|
+
return `(${a} !== undefined && ${a} !== null)`;
|
|
85
|
+
case "isObject":
|
|
86
|
+
return `(typeof ${a} === "object" || typeof ${a} === "function")`;
|
|
87
|
+
case "get":
|
|
88
|
+
return `${a}.get(${b})`;
|
|
89
|
+
case "member":
|
|
90
|
+
return `${a}[${b}]`;
|
|
91
|
+
case "records":
|
|
92
|
+
return `${a}.records`;
|
|
93
|
+
case "recordAt":
|
|
94
|
+
return `(${a} !== undefined ? ${a}[${b}] : ${c}.get(${d}))`;
|
|
95
|
+
case "keysOf":
|
|
96
|
+
return `${a}.keys`;
|
|
97
|
+
case "idxOf":
|
|
98
|
+
return `${a}.idx`;
|
|
99
|
+
case "memoGet":
|
|
100
|
+
return `${a}.get(${b}, ${c})`;
|
|
101
|
+
case "memoPut":
|
|
102
|
+
return `${a}.put(${b}, ${c}, ${d}, ${e})`;
|
|
103
|
+
case "entryValue":
|
|
104
|
+
return `${a}.v`;
|
|
105
|
+
case "entryOk":
|
|
106
|
+
return `${a}.ok`;
|
|
107
|
+
case "+":
|
|
108
|
+
case "/":
|
|
109
|
+
case "===":
|
|
110
|
+
case "!==":
|
|
111
|
+
case "||":
|
|
112
|
+
case "&&":
|
|
113
|
+
return `(${a} ${x.op} ${b})`;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
// An op has one dispatch for each name and number of arguments, and the function gets it when it loads.
|
|
119
|
+
function siteOf(x: OpExpr): string {
|
|
120
|
+
const site = `s${x.name}_${x.args.length}`;
|
|
121
|
+
sites.set(site, `R.site(${expr(constant(x.name))}, ${x.args.length})`);
|
|
122
|
+
return site;
|
|
123
|
+
}
|
|
124
|
+
const domain = (i: number): string => {
|
|
125
|
+
domains.add(i);
|
|
126
|
+
return `d${i}`;
|
|
127
|
+
};
|
|
128
|
+
// The checks of the result of an op, as `#checkResult` of the interpreter. A domain without `valid` stops the search.
|
|
129
|
+
const resultChecks = (out: string, checks: readonly boolean[], indent: string): void => {
|
|
130
|
+
lines.push(`${indent}if (${out} !== F) {`);
|
|
131
|
+
lines.push(`${indent} if (${out} === undefined || ${out} === null || (typeof ${out} === "number" && !Number.isFinite(${out}))) ${out} = F;`);
|
|
132
|
+
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})) {}`);
|
|
135
|
+
});
|
|
136
|
+
lines.push(`${indent}}`);
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* The fast path of an op site that assigns the local `n`. A method site guards the method of the last receiver and
|
|
140
|
+
* the domain of the receiver, and a site of a function guards the domain. Then the site checks the arguments, calls
|
|
141
|
+
* the op in a `try`, and checks the result. A number that the op lifts, and each failed guard, go to the dispatch.
|
|
142
|
+
*/
|
|
143
|
+
const siteBlock = (n: number, x: OpExpr, indent: string): boolean => {
|
|
144
|
+
const attempt = (call: string, ind: string): void => {
|
|
145
|
+
threw = true;
|
|
146
|
+
lines.push(`${ind}try { ${name(n)} = ${call}; } catch (e) { ${name(n)} = threw_(e); }`);
|
|
147
|
+
};
|
|
148
|
+
const st = facts.staticSite(p.constants[x.name] as string, x.kinds);
|
|
149
|
+
if (st !== undefined) {
|
|
150
|
+
staticBlock(n, x, st, indent, attempt);
|
|
151
|
+
return true;
|
|
152
|
+
}
|
|
153
|
+
const f = facts.site(p.constants[x.name] as string, x.args.length);
|
|
154
|
+
switch (f?.t) {
|
|
155
|
+
case undefined:
|
|
156
|
+
return false;
|
|
157
|
+
case "free": {
|
|
158
|
+
const site = siteOf(x);
|
|
159
|
+
sites.set(`${site}_f`, `${site}.free`);
|
|
160
|
+
attempt(`${site}_f(${x.args.map(expr).join(", ")})`, indent);
|
|
161
|
+
resultChecks(name(n), facts.checks, indent);
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
case "op":
|
|
165
|
+
opBlock(n, x, f, indent, attempt);
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
/**
|
|
170
|
+
* 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
|
+
* 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.
|
|
173
|
+
*/
|
|
174
|
+
const staticBlock = (n: number, x: OpExpr, st: StaticSite, indent: string, attempt: (call: string, ind: string) => void): void => {
|
|
175
|
+
const out = name(n);
|
|
176
|
+
const values = x.args.map(expr);
|
|
177
|
+
if (st.t === "free") {
|
|
178
|
+
const site = siteOf(x);
|
|
179
|
+
sites.set(`${site}_f`, `${site}.free`);
|
|
180
|
+
attempt(`${site}_f(${values.join(", ")})`, indent);
|
|
181
|
+
resultChecks(out, facts.checks, indent);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
// An argument of a kind that the op does not accept: the interpreter gives an error.
|
|
185
|
+
if (st.bad) {
|
|
186
|
+
lines.push(`${indent}${out} = F;`);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const f = `f${x.name}_${st.domain}`;
|
|
190
|
+
fns.set(f, `${domain(st.domain)}.ops[${expr(constant(x.name))}].fn`);
|
|
191
|
+
attempt(`${f}(${values.join(", ")})`, indent);
|
|
192
|
+
const kind = st.returns;
|
|
193
|
+
if (kind === undefined) {
|
|
194
|
+
resultChecks(out, facts.checks, indent);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
lines.push(`${indent}if (${out} !== F && typeof ${out} !== "${kind}") return F; // the kind of the result`);
|
|
198
|
+
if (kind === "number") lines.push(`${indent}if (${out} !== F && !Number.isFinite(${out})) ${out} = F;`);
|
|
199
|
+
const check = facts.checkOf(kind);
|
|
200
|
+
if (check === undefined) resultChecks(out, facts.checks, indent);
|
|
201
|
+
else if (facts.checks[check] === true) {
|
|
202
|
+
const d = domain(check);
|
|
203
|
+
lines.push(`${indent}if (${out} !== F) { try { if (!${d}.valid(${out})) ${out} = F; } catch (e) { ${out} = threw_(e); } }`);
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
const opBlock = (n: number, x: OpExpr, f: Extract<SiteFacts, { readonly t: "op" }>, indent: string, attempt: (call: string, ind: string) => void): void => {
|
|
207
|
+
const site = siteOf(x);
|
|
208
|
+
const values = x.args.map(expr);
|
|
209
|
+
const out = name(n);
|
|
210
|
+
const label = `S${siteLabels++}`;
|
|
211
|
+
const [self, ...args] = values as [string, ...string[]];
|
|
212
|
+
const d = domain(f.domain);
|
|
213
|
+
lines.push(`${indent}${label}: {`);
|
|
214
|
+
let inner: string;
|
|
215
|
+
let call: string;
|
|
216
|
+
if (f.method) {
|
|
217
|
+
const m = `m${label}`;
|
|
218
|
+
lines.push(`${indent} if (typeof ${self} === "object" && ${self} !== null) {`, `${indent} const ${m} = ${site}.m;`);
|
|
219
|
+
lines.push(`${indent} if (${m} !== undefined && ${self}[${expr(constant(x.name))}] === ${m} && ${d}.is(${self})) {`);
|
|
220
|
+
inner = `${indent} `;
|
|
221
|
+
call = `${self}[${expr(constant(x.name))}](${args.join(", ")})`;
|
|
222
|
+
} else {
|
|
223
|
+
sites.set(`${site}_f`, `${site}.fn`);
|
|
224
|
+
lines.push(`${indent} if (${d}.is(${self})) {`);
|
|
225
|
+
inner = `${indent} `;
|
|
226
|
+
call = `${site}_f(${values.join(", ")})`;
|
|
227
|
+
}
|
|
228
|
+
const lifted = args.filter((_a, i) => liftsAt(f.lift, i)).map((a) => `typeof ${a} === "number"`);
|
|
229
|
+
if (lifted.length > 0) lines.push(`${inner}if (${lifted.join(" || ")}) { ${out} = ${generic(x, site, values)}; break ${label}; }`);
|
|
230
|
+
const kinds = args.flatMap((a, i) => kindCheck(f.params?.[i], a, d));
|
|
231
|
+
if (kinds.length > 0) lines.push(`${inner}if (!(${kinds.join(" && ")})) { ${out} = F; break ${label}; }`);
|
|
232
|
+
attempt(call, inner);
|
|
233
|
+
resultChecks(out, facts.checks, inner);
|
|
234
|
+
lines.push(`${inner}break ${label};`);
|
|
235
|
+
if (f.method) lines.push(`${indent} }`);
|
|
236
|
+
lines.push(`${indent} }`, `${indent} ${out} = ${generic(x, site, values)};`, `${indent}}`);
|
|
237
|
+
};
|
|
238
|
+
// The statement of a failure (docs/COMPILER.md §4.1).
|
|
239
|
+
const action = (f: Fail): string => {
|
|
240
|
+
switch (f.t) {
|
|
241
|
+
case "return":
|
|
242
|
+
return "return F;";
|
|
243
|
+
case "break":
|
|
244
|
+
return `break L${f.label};`;
|
|
245
|
+
case "continue":
|
|
246
|
+
return f.strict === undefined ? `continue L${f.label};` : `{ if (${expr(f.strict.cond)}) ${action(f.strict.else)} continue L${f.label}; }`;
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
const lines: string[] = [];
|
|
250
|
+
const stmts = (ss: readonly LStmt[], indent: string): void => {
|
|
251
|
+
for (const s of ss) stmt(s, indent);
|
|
252
|
+
};
|
|
253
|
+
const stmt = (s: LStmt, indent: string): void => {
|
|
254
|
+
switch (s.t) {
|
|
255
|
+
case "let":
|
|
256
|
+
case "set":
|
|
257
|
+
if (s.value.t === "op" && siteBlock(s.n, s.value, indent)) return;
|
|
258
|
+
lines.push(`${indent}${name(s.n)} = ${expr(s.value)};`);
|
|
259
|
+
return;
|
|
260
|
+
case "check":
|
|
261
|
+
lines.push(`${indent}if (!(${expr(s.ok)})) ${action(s.fail)} // ${s.reason}`);
|
|
262
|
+
return;
|
|
263
|
+
case "fail":
|
|
264
|
+
lines.push(`${indent}${action(s.fail)}`);
|
|
265
|
+
return;
|
|
266
|
+
case "if":
|
|
267
|
+
lines.push(`${indent}if (${expr(s.cond)}) {`);
|
|
268
|
+
stmts(s.yes, `${indent} `);
|
|
269
|
+
if (s.no.length > 0) {
|
|
270
|
+
lines.push(`${indent}} else {`);
|
|
271
|
+
stmts(s.no, `${indent} `);
|
|
272
|
+
}
|
|
273
|
+
lines.push(`${indent}}`);
|
|
274
|
+
return;
|
|
275
|
+
case "loop": {
|
|
276
|
+
const [a, i] = [name(s.array), name(s.index)];
|
|
277
|
+
lines.push(`${indent}${a} = ${expr(s.over)};`);
|
|
278
|
+
lines.push(`${indent}L${s.label}: for (${i} = 0; ${i} < ${a}.length; ${i}++) {`);
|
|
279
|
+
lines.push(`${indent} ${name(s.item)} = ${a}[${i}];`);
|
|
280
|
+
stmts(s.body, `${indent} `);
|
|
281
|
+
lines.push(`${indent}}`);
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
case "block":
|
|
285
|
+
lines.push(`${indent}L${s.label}: {`);
|
|
286
|
+
stmts(s.body, `${indent} `);
|
|
287
|
+
lines.push(`${indent}}`);
|
|
288
|
+
return;
|
|
289
|
+
case "repeat":
|
|
290
|
+
lines.push(`${indent}L${s.label}: for (;;) {`);
|
|
291
|
+
stmts(s.body, `${indent} `);
|
|
292
|
+
lines.push(`${indent}}`);
|
|
293
|
+
return;
|
|
294
|
+
case "next":
|
|
295
|
+
lines.push(`${indent}continue;`);
|
|
296
|
+
return;
|
|
297
|
+
case "push":
|
|
298
|
+
lines.push(`${indent}${name(s.n)}.push(${expr(s.value)});`);
|
|
299
|
+
return;
|
|
300
|
+
case "return":
|
|
301
|
+
lines.push(`${indent}return ${expr(s.value)};`);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
stmts(p.body, " ");
|
|
306
|
+
const params = Array.from({ length: FIXED_LOCALS }, (_, n) => name(n));
|
|
307
|
+
const locals = Array.from({ length: p.locals - FIXED_LOCALS }, (_, n) => name(n + FIXED_LOCALS));
|
|
308
|
+
const head = [
|
|
309
|
+
`"use strict";`,
|
|
310
|
+
`const F = R.F;`,
|
|
311
|
+
// The order is the order of the first use, so the same program gives the same source.
|
|
312
|
+
...[...used].map((fn) => `const ${fn}_ = R.${fn};`),
|
|
313
|
+
...[...constants].map((i) => `const k${i} = K[${i}];`),
|
|
314
|
+
...[...sites].map(([site, init]) => `const ${site} = ${init};`),
|
|
315
|
+
...[...domains].map((i) => `const d${i} = R.domain(${i});`),
|
|
316
|
+
...[...fns].map(([f, init]) => `const ${f} = ${init};`),
|
|
317
|
+
...(threw ? [`const threw_ = R.threw;`] : []),
|
|
318
|
+
`return function vex(${params.join(", ")}) {`,
|
|
319
|
+
...(locals.length > 0 ? [` let ${locals.join(", ")};`] : []),
|
|
320
|
+
` try {`,
|
|
321
|
+
];
|
|
322
|
+
const tail = [` } catch {`, ` return F;`, ` }`, `};`, ``];
|
|
323
|
+
return [...head, ...lines, ...tail].join("\n");
|
|
324
|
+
}
|