@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/README.md +35 -3
- package/build/facts-3ZtCfd0v.d.ts +37 -0
- package/build/facts-3ZtCfd0v.d.ts.map +1 -0
- package/build/index.d.ts +162 -99
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1036 -4233
- package/build/index.js.map +1 -1
- package/build/memo-08WGBHWI.js +577 -0
- package/build/memo-08WGBHWI.js.map +1 -0
- package/build/module-entry.d.ts +100 -0
- package/build/module-entry.d.ts.map +1 -0
- package/build/module-entry.js +6968 -0
- package/build/module-entry.js.map +1 -0
- package/package.json +17 -6
- package/src/facts.ts +52 -41
- package/src/fn-text.ts +58 -0
- package/src/index.ts +2 -3
- package/src/js.ts +59 -33
- package/src/loop.ts +98 -10
- package/src/lower.ts +487 -125
- package/src/memo.ts +215 -94
- package/src/module-entry.ts +7 -0
- package/src/module-tidy.ts +491 -0
- package/src/module.ts +2735 -317
- package/src/runtime.ts +326 -36
- package/src/scope-key.ts +283 -0
- package/src/sheet-order.ts +13 -99
- package/src/tiers.ts +27 -12
- package/src/unshared.ts +125 -0
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The last pass of the printer of a module (`COMPILER.md` §4.4, COMPILE.MODULE.SIZE). This pass reads the lines of a
|
|
3
|
+
* printed run, and it removes code that gives no value. It does not change the value of a run, an error of a run or a
|
|
4
|
+
* refusal of the printer.
|
|
5
|
+
*
|
|
6
|
+
* The printer gives one statement on each line, and each block adds two spaces. A name with digits is a fresh name of
|
|
7
|
+
* the printer. A text of a program can hold each word, so each count of a word here also counts the words in a text. A
|
|
8
|
+
* count that is too high only stops a rule. A rule that writes code reads the tokens of the code (`rewritten`), so it
|
|
9
|
+
* does not change a text.
|
|
10
|
+
*/
|
|
11
|
+
import { type Token, tokenizer, tokTypes } from "acorn";
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
/** The parts of a module for the pass. */
|
|
15
|
+
export interface TidyParts {
|
|
16
|
+
/** The helpers and the declarations at the top of the module, by name, in their order. */
|
|
17
|
+
readonly decls: ReadonlyMap<string, string>;
|
|
18
|
+
/** The statements of the run that this pass can change: the constants of the run and the body. */
|
|
19
|
+
readonly lines: readonly string[];
|
|
20
|
+
/** The other text of the module. This pass does not change it, and each name that it reads stays. */
|
|
21
|
+
readonly kept: string;
|
|
22
|
+
/** The globals that a function of an op can read at each place of the module. */
|
|
23
|
+
readonly globals: ReadonlySet<string>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The result of the pass: the declarations that stay, and the statements of the run. */
|
|
27
|
+
export interface Tidied {
|
|
28
|
+
readonly decls: ReadonlyMap<string, string>;
|
|
29
|
+
readonly lines: readonly string[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The tokens that hold a text of the code: a string, a part of a template and a regular expression. */
|
|
33
|
+
const TEXT_TOKENS: ReadonlySet<unknown> = new Set([tokTypes.string, tokTypes.template, tokTypes.regexp]);
|
|
34
|
+
|
|
35
|
+
/** A text of the code starts with one of these characters. A comment starts with the slash too. */
|
|
36
|
+
// 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 = /["'`/]/;
|
|
38
|
+
|
|
39
|
+
/** 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
|
+
function codeOf(line: string): string {
|
|
41
|
+
if (!TEXT_START.test(line)) return line;
|
|
42
|
+
let out = "";
|
|
43
|
+
let at = 0;
|
|
44
|
+
for (const token of tokenizer(line, { ecmaVersion: "latest" })) {
|
|
45
|
+
if (!TEXT_TOKENS.has(token.type)) continue;
|
|
46
|
+
out += line.slice(at, token.start) + " ".repeat(token.end - token.start);
|
|
47
|
+
at = token.end;
|
|
48
|
+
}
|
|
49
|
+
return out + line.slice(at);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* This function writes each match of `find` in the code of a line. A match in a text does not count, and each text
|
|
54
|
+
* keeps its characters. `find` must have the flag `g`. A line with no match needs no tokens.
|
|
55
|
+
*/
|
|
56
|
+
function rewritten(line: string, find: RegExp, write: (match: RegExpExecArray) => string): string {
|
|
57
|
+
if (line.search(find) < 0) return line;
|
|
58
|
+
let out = "";
|
|
59
|
+
let at = 0;
|
|
60
|
+
for (const match of codeOf(line).matchAll(find)) {
|
|
61
|
+
out += line.slice(at, match.index) + write(match);
|
|
62
|
+
at = match.index + match[0].length;
|
|
63
|
+
}
|
|
64
|
+
return out + line.slice(at);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** This function gives the names in code. A word in a comment or in a text is not a name. */
|
|
68
|
+
export function namesOfCode(code: string): ReadonlySet<string> {
|
|
69
|
+
const names = new Set<string>();
|
|
70
|
+
for (const token of tokenizer(code, { ecmaVersion: "latest", sourceType: "module" })) if (token.type === tokTypes.name) names.add((token as Token & { readonly value: string }).value);
|
|
71
|
+
return names;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The words of a text. */
|
|
75
|
+
const WORD = /[A-Za-z_$][\w$]*/g;
|
|
76
|
+
|
|
77
|
+
/** This function gives the words of a text. */
|
|
78
|
+
export const wordsOf = (text: string): readonly string[] => text.match(WORD) ?? [];
|
|
79
|
+
|
|
80
|
+
/** This function gives the count of a word in some lines. A line without the text of the word needs no walk. */
|
|
81
|
+
function countOf(lines: readonly string[], name: string): number {
|
|
82
|
+
let sum = 0;
|
|
83
|
+
for (const x of lines) {
|
|
84
|
+
// Stryker disable next-line ConditionalExpression: a line without the text has no such word, so this test only saves the walk.
|
|
85
|
+
if (x.includes(name)) sum += wordsOf(x).filter((w) => w === name).length;
|
|
86
|
+
}
|
|
87
|
+
return sum;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** This function gives the number of spaces at the start of a line. */
|
|
91
|
+
const indentOf = (line: string): number => line.length - line.trimStart().length;
|
|
92
|
+
|
|
93
|
+
/** This function gives the first line after `at` that is not in the block of the line `at`. */
|
|
94
|
+
function blockEnd(lines: readonly string[], at: number): number {
|
|
95
|
+
const indent = indentOf(lines[at] as string);
|
|
96
|
+
let end = at + 1;
|
|
97
|
+
while (end < lines.length && indentOf(lines[end] as string) >= indent) end++;
|
|
98
|
+
return end;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** This function gives the line that opens the block of the line `at`, or -1 at the top of the run. */
|
|
102
|
+
function openerOf(lines: readonly string[], at: number): number {
|
|
103
|
+
const indent = indentOf(lines[at] as string);
|
|
104
|
+
let k = at - 1;
|
|
105
|
+
while (k >= 0 && indentOf(lines[k] as string) >= indent) k--;
|
|
106
|
+
return k;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The line of a function that a block opens. */
|
|
110
|
+
const FUNCTION_HEAD = /=> \{$|\bfunction\b.*\{$/;
|
|
111
|
+
|
|
112
|
+
/** This function gives the line that opens the function of the line `at`, or -1 for the function of the run. */
|
|
113
|
+
function functionOf(lines: readonly string[], at: number): number {
|
|
114
|
+
let k = openerOf(lines, at);
|
|
115
|
+
while (k >= 0 && !FUNCTION_HEAD.test(lines[k] as string)) k = openerOf(lines, k);
|
|
116
|
+
return k;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 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\])?;$/;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* This function removes each read of a key that no code reads (COMPILE.MODULE.SIZE.KEY). The read must be the first line
|
|
124
|
+
* of the loop of its position. A read of a pair must also have a loop over the length of its array. An item of a list
|
|
125
|
+
* is a pair, so the read cannot throw.
|
|
126
|
+
*/
|
|
127
|
+
export function deadKeys(lines: readonly string[]): readonly string[] {
|
|
128
|
+
return lines.filter((line, i) => {
|
|
129
|
+
const m = KEY_READ.exec(line);
|
|
130
|
+
if (m === null) return true;
|
|
131
|
+
const [, key, array, position, pair] = m as unknown as readonly [string, string, string, string, string | undefined];
|
|
132
|
+
const head = lines[i - 1] ?? "";
|
|
133
|
+
const loop = head.trimStart().startsWith(`for (let ${position} = `) && (pair === undefined || new RegExp(`(?<![\\w$.])${array}\\.length`).test(head));
|
|
134
|
+
return !loop || countOf(lines.slice(i + 1, blockEnd(lines, i)), key) > 0;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* This function gives a line with each read of the name `from` as a read of the name `to`. A property, a key of an
|
|
140
|
+
* object and a part of a longer word are not reads. A spread reads its name.
|
|
141
|
+
*/
|
|
142
|
+
function renamed(line: string, from: string, to: string): string {
|
|
143
|
+
const read = new RegExp(`(?<![\\w$])(?<!(?<!\\.\\.)\\.)(?:(?<![{,]\\s*)${from}|${from}(?!\\s*:))(?![\\w$])`, "g");
|
|
144
|
+
return rewritten(line, read, () => to);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 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;
|
|
149
|
+
|
|
150
|
+
/** This function gives the lines that write to each name, without the line that declares the name. */
|
|
151
|
+
function writesOf(lines: readonly string[]): ReadonlyMap<string, readonly number[]> {
|
|
152
|
+
const writes = new Map<string, number[]>();
|
|
153
|
+
for (const [i, line] of lines.entries()) {
|
|
154
|
+
for (const m of line.matchAll(WRITE)) {
|
|
155
|
+
const name = (m[1] ?? m[2]) as string;
|
|
156
|
+
writes.set(name, [...(writes.get(name) ?? []), i]);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return writes;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** This function tells if a line declares a name, also as a parameter of a function. */
|
|
163
|
+
function binds(line: string, name: string): boolean {
|
|
164
|
+
// Stryker disable next-line ConditionalExpression: a line without the name has no declaration of it, so this test only saves the pattern.
|
|
165
|
+
if (!line.includes(name)) return false;
|
|
166
|
+
const word = `(?<![\\w$])${name}(?![\\w$])`;
|
|
167
|
+
return new RegExp(`\\b(?:const|let)\\s+(?:[^;=]*,\\s*|\\[[^\\]]*)?${word}|\\([^()]*${word}[^()]*\\)\\s*=>|${word}\\s*=>|\\bfunction\\b[^(]*\\([^)]*${word}`).test(line);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 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);$/;
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* This function tells if the name `name` keeps its value from the line `at` to the line `end`. A name with no write
|
|
175
|
+
* keeps its value. Else no line in that part can write to it. That part must also have no function, because a function
|
|
176
|
+
* can read the name after a later write. Each other write and the declaration must be in the function of the line
|
|
177
|
+
* `at`, because a call cannot then start them. A write in a line with a function has an unknown place.
|
|
178
|
+
*/
|
|
179
|
+
function keeps(lines: readonly string[], writes: readonly number[], name: string, at: number, end: number): boolean {
|
|
180
|
+
if (writes.length === 0) return true;
|
|
181
|
+
if (writes.some((x) => x > at && x < end) || lines.slice(at, end).some((x) => x.includes("=>") || /\bfunction\b/.test(x))) return false;
|
|
182
|
+
const home = functionOf(lines, at);
|
|
183
|
+
const declared = lines.flatMap((x, i) => (binds(x, name) ? [i] : []));
|
|
184
|
+
return declared.length > 0 && [...writes, ...declared].every((x) => !(lines[x] as string).includes("=>") && functionOf(lines, x) === home);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* This function removes each alias whose two names hold one value in the whole block of the alias. Each read of the
|
|
189
|
+
* alias reads the first name (COMPILE.MODULE.SIZE.ALIAS).
|
|
190
|
+
*/
|
|
191
|
+
export function aliases(lines: readonly string[]): readonly string[] {
|
|
192
|
+
const out = [...lines];
|
|
193
|
+
const writes = writesOf(lines);
|
|
194
|
+
const gone = new Set<number>();
|
|
195
|
+
for (let i = 0; i < out.length; i++) {
|
|
196
|
+
const m = ALIAS.exec(out[i] as string);
|
|
197
|
+
if (m === null) continue;
|
|
198
|
+
const [, alias, name] = m as unknown as readonly [string, string, string];
|
|
199
|
+
const end = blockEnd(out, i);
|
|
200
|
+
const block = out.slice(i + 1, end);
|
|
201
|
+
// Each read of the alias must be in its block, and no line of that block can give either name another meaning. The
|
|
202
|
+
// printer prints the steps of a stopped walk two times, so a nested block can declare the alias again (V-073).
|
|
203
|
+
if (countOf(out, alias) !== 1 + countOf(block, alias) || block.some((x) => binds(x, name) || binds(x, alias)) || !keeps(out, writes.get(name) ?? [], name, i, end)) continue;
|
|
204
|
+
for (let k = i + 1; k < end; k++) {
|
|
205
|
+
const x = out[k] as string;
|
|
206
|
+
// Stryker disable next-line ConditionalExpression: a line without the alias stays as it is, so this test only saves the pattern.
|
|
207
|
+
if (x.includes(alias)) out[k] = renamed(x, alias, name);
|
|
208
|
+
}
|
|
209
|
+
gone.add(i);
|
|
210
|
+
}
|
|
211
|
+
return out.filter((_, i) => !gone.has(i));
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The first line of a lazy cell of the run. */
|
|
215
|
+
const CELL = /^ {2}const (c\d+) = L\(\(\) => \{$/;
|
|
216
|
+
|
|
217
|
+
/** The first line of a lazy cell at each place. */
|
|
218
|
+
const ANY_CELL = /^\s*const \w+ = L\(\(\) => \{$/;
|
|
219
|
+
|
|
220
|
+
/** 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 \(.*\) \{)$/;
|
|
222
|
+
|
|
223
|
+
/** The statements that can run a part of their line more than once. */
|
|
224
|
+
const LOOP_LINE = /^\s*(?:for|while|do)\b|=>/;
|
|
225
|
+
|
|
226
|
+
/** This function tells if the statement at the line `at` runs at most once in a run. */
|
|
227
|
+
function runsOnce(lines: readonly string[], at: number): boolean {
|
|
228
|
+
if (LOOP_LINE.test(lines[at] as string)) return false;
|
|
229
|
+
for (let k = openerOf(lines, at); k >= 0; k = openerOf(lines, k)) {
|
|
230
|
+
const line = lines[k] as string;
|
|
231
|
+
if (ANY_CELL.test(line)) return true;
|
|
232
|
+
if (!ONCE_BLOCK.test(line)) return false;
|
|
233
|
+
}
|
|
234
|
+
return true;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* This function prints a lazy cell with one read at that read (COMPILE.MODULE.SIZE.ONCE). The cell must be one
|
|
239
|
+
* `return`, and the read must be `G(c())`. The read must run at most once, so the value evaluates at most once and at
|
|
240
|
+
* the same time. `G` stays, because the value can be the sentinel. Each catch of a module takes each exception.
|
|
241
|
+
*/
|
|
242
|
+
export function onceCells(lines: readonly string[]): readonly string[] {
|
|
243
|
+
let out = lines;
|
|
244
|
+
for (let i = 0; i + 2 < out.length; i++) {
|
|
245
|
+
const name = CELL.exec(out[i] as string)?.[1];
|
|
246
|
+
const value = /^ {4}return (.*);$/.exec(out[i + 1] as string)?.[1];
|
|
247
|
+
if (name === undefined || value === undefined || out[i + 2] !== " });" || countOf(out, name) !== 2) continue;
|
|
248
|
+
const read = new RegExp(`(?<![\\w$.])G\\(${name}\\(\\)\\)`, "g");
|
|
249
|
+
const inlined = (x: string): string => rewritten(x, read, () => `G(${value})`);
|
|
250
|
+
const site = out.findIndex((x) => inlined(x) !== x);
|
|
251
|
+
if (site < 0 || !runsOnce(out, site)) continue;
|
|
252
|
+
out = out.flatMap((x, k) => (k === site ? [inlined(x)] : k >= i && k <= i + 2 ? [] : [x]));
|
|
253
|
+
i = -1;
|
|
254
|
+
}
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** A constant of the run on one line, with its name. */
|
|
259
|
+
const CONSTANT = /^ {2}const (c\d+) = (?:T\(\(\) => .*\)|\[\]);$/;
|
|
260
|
+
|
|
261
|
+
/** The first line of a constant of the run with a `try`, with its name. */
|
|
262
|
+
const HELD = /^ {2}let (c\d+);$/;
|
|
263
|
+
|
|
264
|
+
/** 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+\) => \{$/;
|
|
266
|
+
|
|
267
|
+
/** The variable of the pack of a column at each depth, with its name. */
|
|
268
|
+
const PACK = /^ *let (PK\d+);$/;
|
|
269
|
+
|
|
270
|
+
/** This function gives the name of the declaration at the line `at` and its last line, or `undefined` for another line. */
|
|
271
|
+
function constantAt(lines: readonly string[], at: number): { readonly name: string; readonly last: number } | undefined {
|
|
272
|
+
const line = lines[at] as string;
|
|
273
|
+
const one = CONSTANT.exec(line)?.[1];
|
|
274
|
+
if (one !== undefined) return { name: one, last: at };
|
|
275
|
+
const lazy = CELL.exec(line)?.[1];
|
|
276
|
+
if (lazy !== undefined) return { name: lazy, last: lines.indexOf(" });", at) };
|
|
277
|
+
const column = COLUMN.exec(line);
|
|
278
|
+
if (column !== null) return { name: column[2] as string, last: lines.indexOf(`${column[1] as string}});`, at) };
|
|
279
|
+
const pack = PACK.exec(line)?.[1];
|
|
280
|
+
if (pack !== undefined) return { name: pack, last: at };
|
|
281
|
+
const held = HELD.exec(line)?.[1];
|
|
282
|
+
return held === undefined || lines[at + 1] !== " try {" ? undefined : { name: held, last: lines.indexOf(" }", at) };
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** This function gives the count of each word of some lines. */
|
|
286
|
+
function wordCounts(lines: readonly string[]): Map<string, number> {
|
|
287
|
+
const counts = new Map<string, number>();
|
|
288
|
+
for (const w of wordsOf(lines.join("\n"))) counts.set(w, (counts.get(w) ?? 0) + 1);
|
|
289
|
+
return counts;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* This function removes each constant of the run that no code reads (COMPILE.MODULE.SIZE.DEAD). The code of a constant
|
|
294
|
+
* has no effect, and the constant holds each failure of that code. A lazy cell with no read does not run. A print that
|
|
295
|
+
* the printer drops leaves its columns and their packs, in the run and in a function, so the pass removes these too. The
|
|
296
|
+
* parameters of a function come from the code that it keeps, so such a column can read a name with no declaration.
|
|
297
|
+
*/
|
|
298
|
+
export function deadConstants(lines: readonly string[]): readonly string[] {
|
|
299
|
+
let out = lines;
|
|
300
|
+
const counts = wordCounts(lines);
|
|
301
|
+
for (let i = 0; i < out.length; i++) {
|
|
302
|
+
const c = constantAt(out, i);
|
|
303
|
+
if (c === undefined) continue;
|
|
304
|
+
const own = wordCounts(out.slice(i, c.last + 1));
|
|
305
|
+
if (counts.get(c.name) !== own.get(c.name)) continue;
|
|
306
|
+
out = [...out.slice(0, i), ...out.slice(c.last + 1)];
|
|
307
|
+
for (const [word, count] of own) counts.set(word, (counts.get(word) as number) - count);
|
|
308
|
+
i = -1;
|
|
309
|
+
}
|
|
310
|
+
return out;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** This function gives the declarations that the text `roots` reads, also through other declarations. */
|
|
314
|
+
export function liveDecls(decls: ReadonlyMap<string, string>, roots: string): ReadonlyMap<string, string> {
|
|
315
|
+
const live = new Set<string>();
|
|
316
|
+
const stack = [...wordsOf(roots)];
|
|
317
|
+
for (let w = stack.pop(); w !== undefined; w = stack.pop()) {
|
|
318
|
+
const text = decls.get(w);
|
|
319
|
+
if (text === undefined || live.has(w)) continue;
|
|
320
|
+
live.add(w);
|
|
321
|
+
stack.push(...wordsOf(text));
|
|
322
|
+
}
|
|
323
|
+
return new Map([...decls].filter(([name]) => live.has(name)));
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** 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;
|
|
328
|
+
|
|
329
|
+
/** The tokens that change a value or start a function. */
|
|
330
|
+
const NOT_INLINE: ReadonlySet<string> = new Set(["++", "--", "=>"]);
|
|
331
|
+
|
|
332
|
+
/** The words that an inline body can read at each place of a module. */
|
|
333
|
+
const PLAIN_WORDS: ReadonlySet<string> = new Set(["true", "false", "null", "NaN", "Infinity", "typeof", "void"]);
|
|
334
|
+
|
|
335
|
+
/** The words that end no value, so a slash after them starts a regular expression. */
|
|
336
|
+
const NOT_VALUES: ReadonlySet<string> = new Set(["typeof", "void"]);
|
|
337
|
+
|
|
338
|
+
/** This function gives the tokens of a body, or `undefined` for a body with another token. */
|
|
339
|
+
function tokensOf(body: string): readonly string[] | undefined {
|
|
340
|
+
const out: string[] = [];
|
|
341
|
+
BODY_TOKEN.lastIndex = 0;
|
|
342
|
+
while (BODY_TOKEN.lastIndex < body.length) {
|
|
343
|
+
const m = BODY_TOKEN.exec(body);
|
|
344
|
+
if (m === null || NOT_INLINE.has(m[0])) return undefined;
|
|
345
|
+
out.push(m[0]);
|
|
346
|
+
}
|
|
347
|
+
return out;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** This function tells if a token ends a value, so a slash after it is a division. */
|
|
351
|
+
const endsValue = (t: string): boolean => t === ")" || t === "]" || t === "}" || (/^[\w$."']/.test(t) && t !== "..." && !NOT_VALUES.has(t));
|
|
352
|
+
|
|
353
|
+
/** This function tells if a token is a name or a word of the language. */
|
|
354
|
+
const isWord = (t: string): boolean => /^[A-Za-z_$]/.test(t);
|
|
355
|
+
|
|
356
|
+
/** This function tells if a token is a space. */
|
|
357
|
+
const isSpace = (t: string): boolean => /^\s/.test(t);
|
|
358
|
+
|
|
359
|
+
/** The part of an inline body: a text, or the index of a parameter. */
|
|
360
|
+
type BodyPart = string | number;
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* This function gives the parts of the body of an arrow function, or `undefined` for a body that a site cannot hold.
|
|
364
|
+
* The body must be an expression with no assignment and no function. Each of its words must be a parameter, a global or
|
|
365
|
+
* a key of an object. Thus a local name of the site cannot take the place of a word of the body.
|
|
366
|
+
*/
|
|
367
|
+
function bodyParts(params: readonly string[], body: string, globals: ReadonlySet<string>): readonly BodyPart[] | undefined {
|
|
368
|
+
const tokens = tokensOf(body.trim());
|
|
369
|
+
if (tokens === undefined || tokens[0] === "{") return undefined;
|
|
370
|
+
const parts: BodyPart[] = [];
|
|
371
|
+
const open: string[] = [];
|
|
372
|
+
let last = "";
|
|
373
|
+
for (const [i, t] of tokens.entries()) {
|
|
374
|
+
if (isSpace(t)) {
|
|
375
|
+
parts.push(" ");
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const next = tokens.slice(i + 1).find((x) => !isSpace(x));
|
|
379
|
+
if (t === "/" && !endsValue(last)) return undefined;
|
|
380
|
+
if (t === "(" || t === "[" || t === "{") open.push(t);
|
|
381
|
+
if (t === ")" || t === "]" || t === "}") open.pop();
|
|
382
|
+
const at = params.indexOf(t);
|
|
383
|
+
const key = open.at(-1) === "{" && (last === "{" || last === ",");
|
|
384
|
+
if (!isWord(t) || (key && next === ":")) parts.push(t);
|
|
385
|
+
else if (key && next !== "," && next !== "}") return undefined;
|
|
386
|
+
else if (at >= 0) parts.push(...(key ? [`${t}:`, at] : [at]));
|
|
387
|
+
else if (PLAIN_WORDS.has(t) || globals.has(t)) parts.push(t);
|
|
388
|
+
else return undefined;
|
|
389
|
+
last = t;
|
|
390
|
+
}
|
|
391
|
+
return parts;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** 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]*);$/;
|
|
396
|
+
|
|
397
|
+
/** The name, the parameters and the parts of an inline form. */
|
|
398
|
+
interface OpForm {
|
|
399
|
+
readonly name: string;
|
|
400
|
+
readonly params: readonly string[];
|
|
401
|
+
readonly parts: readonly BodyPart[];
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** This function gives the form of a declaration, or `undefined` for a declaration without one. */
|
|
405
|
+
function opForm(text: string, globals: ReadonlySet<string>): OpForm | undefined {
|
|
406
|
+
const m = OP_DECL.exec(text);
|
|
407
|
+
if (m === null) return undefined;
|
|
408
|
+
const params = (m[2] ?? m[3] ?? "").split(",").map((x) => x.trim()).filter((x) => x !== "");
|
|
409
|
+
const parts = bodyParts(params, m[4] as string, globals);
|
|
410
|
+
return parts === undefined || params.length === 0 ? undefined : { name: m[1] as string, params, parts };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* This function gives a text with the call of `f` as its body. It gives `undefined` when the text has no call with a
|
|
415
|
+
* name for each argument.
|
|
416
|
+
*/
|
|
417
|
+
function withSite(text: string, f: OpForm): string | undefined {
|
|
418
|
+
const site = new RegExp(`(?<![\\w$.])${f.name}\\(([A-Za-z_$][\\w$]*(?:, [A-Za-z_$][\\w$]*)*)\\)`, "g");
|
|
419
|
+
const out = rewritten(text, site, (match) => {
|
|
420
|
+
const args = (match[1] as string).split(", ");
|
|
421
|
+
return args.length === f.params.length ? `(${f.parts.map((p) => (typeof p === "number" ? (args[p] as string) : p)).join("")})` : match[0];
|
|
422
|
+
});
|
|
423
|
+
return out === text ? undefined : out;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* This function prints each function of an op with one call at that call (COMPILE.MODULE.SIZE.INLINE). Each argument
|
|
428
|
+
* must be a name, so the arguments have no order, and a second read of a parameter reads the same value.
|
|
429
|
+
*/
|
|
430
|
+
export function inlineOps(parts: TidyParts): Tidied {
|
|
431
|
+
const { kept, globals } = parts;
|
|
432
|
+
const decls = new Map(parts.decls);
|
|
433
|
+
const lines = [...parts.lines];
|
|
434
|
+
const counts = new Map<string, number>();
|
|
435
|
+
for (const w of wordsOf([kept, ...decls.values(), ...lines].join("\n"))) counts.set(w, (counts.get(w) ?? 0) + 1);
|
|
436
|
+
for (const [name, text] of parts.decls) {
|
|
437
|
+
const f = counts.get(name) === 2 ? opForm(text, globals) : undefined;
|
|
438
|
+
if (f === undefined) continue;
|
|
439
|
+
const at = lines.findIndex((x) => withSite(x, f) !== undefined);
|
|
440
|
+
if (at >= 0) {
|
|
441
|
+
lines[at] = withSite(lines[at] as string, f) as string;
|
|
442
|
+
decls.delete(name);
|
|
443
|
+
continue;
|
|
444
|
+
}
|
|
445
|
+
// A check of the result of an op calls the check of its domain.
|
|
446
|
+
const check = [...decls].find(([k, x]) => k.startsWith("k_") && withSite(x, f) !== undefined);
|
|
447
|
+
if (check !== undefined) {
|
|
448
|
+
decls.set(check[0], withSite(check[1], f) as string);
|
|
449
|
+
decls.delete(name);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return { decls, lines };
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** The helper of a catch that keeps only the error of Vex (COMPILE.MODULE.FAULT). */
|
|
456
|
+
const FAULT_KEEP = "function FK(x) { if (x !== E) throw x; }";
|
|
457
|
+
/** The helper that gives the error of Vex for each exception of a copy of a function of a domain. */
|
|
458
|
+
const FAULT_WRAP = "function FW(f) { return (...a) => { try { return f(...a); } catch { throw E; } }; }";
|
|
459
|
+
|
|
460
|
+
/** This function gives a line where each catch rethrows each value that is not the error of Vex. */
|
|
461
|
+
function narrowCatches(line: string): string {
|
|
462
|
+
return rewritten(line, /catch \{/g, () => "catch ($f) { FK($f);");
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** This function gives the declaration of a copy of a function of a domain, inside the wrapper. */
|
|
466
|
+
function wrapFaults(name: string, text: string): string {
|
|
467
|
+
return `const ${name} = FW(${text.slice(`const ${name} = `.length, -1)});`;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* This function gives the form of a module where a catch keeps only the error of Vex (COMPILE.MODULE.FAULT). The start
|
|
472
|
+
* of a fault tells the two cases. A copy of a function of a domain gives the error of Vex for each exception, as in the
|
|
473
|
+
* interpreter. Another exception comes from the printed code, and it leaves the run.
|
|
474
|
+
*/
|
|
475
|
+
export function keepFaults(parts: Tidied, copies: ReadonlySet<string>): Tidied {
|
|
476
|
+
const decls = new Map([...parts.decls].map(([name, text]) => [name, copies.has(name) ? wrapFaults(name, text) : narrowCatches(text)]));
|
|
477
|
+
decls.set("FK", FAULT_KEEP);
|
|
478
|
+
decls.set("FW", FAULT_WRAP);
|
|
479
|
+
return { decls, lines: parts.lines.map(narrowCatches) };
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* This function gives the smaller form of a module, with the same behavior (COMPILE.MODULE.SIZE). With `faults` at
|
|
484
|
+
* `throw`, each function of a domain stays a declaration, so the wrapper of `keepFaults` holds each of its exceptions.
|
|
485
|
+
*/
|
|
486
|
+
export function tidy(parts: TidyParts, faults: "value" | "throw" = "value"): Tidied {
|
|
487
|
+
const lines = deadConstants(onceCells(deadConstants(aliases(deadKeys(parts.lines)))));
|
|
488
|
+
const live = liveDecls(parts.decls, [parts.kept, ...lines].join("\n"));
|
|
489
|
+
const small = faults === "throw" ? { decls: live, lines } : inlineOps({ ...parts, decls: live, lines });
|
|
490
|
+
return { decls: liveDecls(small.decls, [parts.kept, ...small.lines].join("\n")), lines: small.lines };
|
|
491
|
+
}
|