-
Notifications
You must be signed in to change notification settings - Fork 26
/
build.ts
434 lines (407 loc) · 13.3 KB
/
build.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import {ast} from '@masochist/codegen';
import {invariant} from '@masochist/common';
import keyToTransition from './NFA/keyToTransition';
import type {
Consequent,
Expression,
IfStatement,
Program,
Statement,
WhileStatement,
} from '@masochist/codegen';
import type {Transition} from './NFA/NFA';
import type {TransitionTable} from './NFA/TransitionTable';
export type Stats = {
[buildStat: string]: number;
};
// TODO: see if i can avoid so many ternaries
export default function build(
table: TransitionTable,
stats: Stats = {},
): Program {
invariant(table.startStates.size === 1, 'Need exactly one start state');
const START = Array.from(table.startStates)[0];
stats['startStates'] = table.startStates.size;
stats['acceptStates'] = table.acceptStates.size;
stats['totalStates'] = table.transitions.length;
stats['ignoredTokens'] = (table.labels || []).filter(
(label) => label?.has('IGNORED'),
).length;
// Should be same as 'acceptStates'.
stats['totalTokens'] = (table.labels || []).filter(
(label) => label?.size,
).length;
// Optimization stats.
stats['inlineableAcceptStates'] = 0;
stats['inlinedAcceptStates'] = 0; // Should match 'inlineableAcceptStates'.
stats['inlinedSelfTransitions'] = 0;
const whileStatement: WhileStatement = {
kind: 'WhileStatement',
condition: ast.expression('this.index <= length'),
block: [
ast.const('state', 'this.state'),
ast.statement(
'let ch = this.index < length ? input.charCodeAt(this.index) : -1',
),
],
};
// Will make one consequent for each state.
const consequents: Array<Consequent> = [];
whileStatement.block.push(
{
kind: 'IfStatement',
consequents,
alternate: [
{
kind: 'ThrowStatement',
// TODO: include state id in error
expression: ast.new('Error', ast.string('Unexpected state')),
},
],
},
ast.statement('this.index++'),
);
// Identify accept states reachable from exactly one other state, which
// themselves have no outgoing edges. These will be inlined inside the other
// state and won't exist as separate states within the machine.
const inlineableStates = new Set<number>();
const statesLeadingToAcceptStates: Array<Set<number>> = [];
table.transitions.forEach((transitionMap, i) => {
for (const targets of transitionMap.values()) {
for (const target of targets) {
if (table.acceptStates.has(target) && !table.transitions[target].size) {
if (statesLeadingToAcceptStates[target]) {
statesLeadingToAcceptStates[target].add(i);
} else {
statesLeadingToAcceptStates[target] = new Set([i]);
}
}
}
}
});
statesLeadingToAcceptStates.forEach((set, i) => {
if (set?.size === 1) {
inlineableStates.add(i);
}
});
stats['inlineableAcceptStates'] = inlineableStates.size;
// Now actually generate code for the states.
table.transitions.forEach((transitionMap, i) => {
if (inlineableStates.has(i)) {
return;
}
// 1. Group conditions by target states.
const conditions: Array<Array<NonNullable<Transition>> | undefined> = [];
for (const [key, targets] of transitionMap) {
invariant(targets.size === 1, 'Transitions must be deterministic');
const target = Array.from(targets)[0];
const transition = keyToTransition(key);
invariant(transition !== null, 'Epsilon transitions are not allowed');
conditions[target] = (conditions[target] || []).concat(transition);
}
// 2. Build state.
const consequent: Consequent = {
kind: 'Consequent',
condition: ast.equals(
ast.identifier('state'),
i === START ? ast.identifier('START') : ast.number(i),
),
block: [],
};
const isAccept = table.acceptStates.has(i)
? Array.from(table.labels?.[i] ?? [])[0]
: undefined;
const isIgnored = isAccept === 'IGNORED';
if (!conditions.length) {
// Should only get here for an ignored state.
invariant(isIgnored);
consequent.block.push(
...filterEmpty(
ast.comment('IGNORED token.'),
ast.statement('this.tokenStart = this.index'),
i === START ? ast.empty : ast.statement('this.state = START'),
ast.continue(),
),
);
} else {
// Process conditions for self-transitions first, because we want to deal
// with these in a `while` loop first, before we enter the following `if`.
const selfCondition = conditions[i];
if (selfCondition) {
stats['inlinedSelfTransitions']++;
conditions[i] = undefined;
const loop = ast.while(expressionForTransitions(selfCondition), []);
loop.block.push(
ast.statement('this.index++'),
ast.statement(
'ch = this.index < length ? input.charCodeAt(this.index) : -1',
),
);
consequent.block.push(loop);
}
const ignoreToken = isIgnored
? filterEmpty(
ast.comment('IGNORED token.'),
ast.statement('this.tokenStart = this.index'),
// TODO: deal with these self-transitions as well
i === START ? ast.empty : ast.statement('this.state = START'),
ast.continue(),
)
: undefined;
const acceptToken = isAccept
? filterEmpty(
i === START ? ast.empty : ast.statement('this.state = START'),
ast.return(
ast.call(
'this.emit',
ast.string(isAccept),
'this.index',
'input',
),
),
)
: undefined;
const remainingConditions = conditions.filter(Boolean).length;
if (remainingConditions) {
// We need to add our `if` statement.
const ifStatement: IfStatement = {
kind: 'IfStatement',
consequents: [],
};
conditions.forEach((transitions, j) => {
if (!transitions) {
// Only previously processed self-transitions can be undefined.
invariant(i === j);
return;
}
const condition = expressionForTransitions(transitions);
const block: Array<Statement> = [];
if (inlineableStates.has(j)) {
block.push(
...filterEmpty(
i === START ? ast.empty : ast.statement('this.state = START'),
ast.return(
ast.call(
'this.emit',
ast.string(Array.from(table.labels?.[j] ?? [])[0]),
'this.index + 1',
'input',
),
),
),
);
stats['inlinedAcceptStates']++;
} else {
invariant(
i !== j,
'Self-transitions should have been excised by now',
);
block.push(ast.statement(`this.state = ${j}`));
}
ifStatement.consequents.push({
kind: 'Consequent',
condition,
block,
});
});
if (ignoreToken) {
ifStatement.alternate = ignoreToken;
} else if (acceptToken) {
ifStatement.alternate = acceptToken;
} else {
ifStatement.alternate = [
// TODO: only do this if consequents don't provide complete coverage
ast.statement('this.state = REJECT'),
];
}
consequent.block.push(ifStatement);
} else {
// There was no `if` statement, only a `while` loop. Fall through to
// what would have been the `alternate`:
if (ignoreToken) {
consequent.block.push(...ignoreToken);
} else if (acceptToken) {
consequent.block.push(...acceptToken);
} else {
consequent.block.push(ast.statement('this.state = REJECT'));
}
}
}
consequents.push(consequent);
});
consequents.push({
kind: 'Consequent',
condition: ast.expression('state === REJECT'),
block: [
{
kind: 'ThrowStatement',
expression: ast.new('Error', ast.string('Failed to recognize token')),
},
],
});
const program: Program = {
kind: 'Program',
statements: [
ast.docComment(
'vim: set nomodifiable : DO NOT EDIT - edit "build.ts", run "make lexer" instead',
'',
'@generated',
),
ast.import('Token', './Token'),
ast.statement('const REJECT = -1'),
ast.statement('const START = 0'),
ast.export(
ast.class('Lexer', [
ast.propertyDeclaration('input', 'string'),
ast.propertyDeclaration('state', 'number'),
ast.propertyDeclaration('tokenStart', 'number'),
ast.propertyDeclaration('index', 'number'),
// Cosmetic only, due to: https://github.com/microsoft/TypeScript/issues/9694
ast.docComment('@param {string} input'),
ast.method(
'constructor',
['input: string'],
[
ast.statement('this.input = input'),
ast.statement('this.state = START'),
ast.statement('this.tokenStart = 0'),
ast.statement('this.index = 0'),
],
),
// Cosmetic only, due to: https://github.com/microsoft/TypeScript/issues/9694
ast.docComment(
'@param {string} name',
'@param {number} end',
'@param {string} input',
),
ast.method(
'emit',
['name: string', 'end: number', 'input: string'],
[
ast.const(
'token',
ast.new('Token', 'name', 'this.tokenStart', 'end', 'input'),
),
ast.statement('this.tokenStart = end'),
ast.statement('this.index = end'),
ast.statement('return token'),
],
),
ast.method(
'next',
[],
[
ast.const('input', 'this.input'),
ast.const('length', 'input.length'),
whileStatement,
ast.statement('return null'),
],
),
]),
),
// Cosmetic only, due to: https://github.com/microsoft/TypeScript/issues/9694
ast.docComment(
'@param {string} input',
'@returns {Generator<Token, void, unknown>}',
),
ast.default(
// Note the TS annotation in the argument here; it's one of few explicit
// annotations required to make `tsc` accept the generated lexer without
// any errors or warnings. Without this, we'd get:
//
// error TS7006: Parameter 'input' implicitly has an 'any' type.
//
ast.function(
'*lex',
['input: string'],
[
ast.const('lexer', ast.new('Lexer', 'input')),
ast.while(ast.true, [
ast.const('token', ast.call(ast.member('lexer', 'next'))),
{
kind: 'IfStatement',
consequents: [
{
kind: 'Consequent',
condition: ast.expression('token === null'),
block: [ast.return()],
},
],
alternate: [ast.yield('token')],
},
]),
],
),
),
],
};
return program;
}
function charForComparison(value: string): string {
invariant(value.length === 1);
const charCode = value.charCodeAt(0);
if (charCode <= 0xff) {
return '0x' + charCode.toString(16).padStart(2, '0');
} else {
return '0x' + charCode.toString(16).padStart(4, '0');
}
}
/**
* Returns a conditional expression for a set of transitions that have
* previously been grouped by target state. eg.
*
* ch === 0x20 || ch >= 0x30 && ch <= 0xffff
*
*/
function expressionForTransitions(
transitions: Array<NonNullable<Transition>>,
identifier: string = 'ch',
): Expression {
invariant(transitions.length);
const expressions: Array<Expression> = [];
for (const transition of transitions) {
if (transition.kind === 'Anything') {
// TODO bite the bullet and make "." equal 0x0000 to 0xffff but not:
//
// - U+000A (\n)
// - U+000D (\r)
// - U+2028 LINE SEPARATOR
// - U+2029 PARAGRAPH SEPARATOR
//
// Moot for now because I don't have it anywhere in my state machine.
expressions.push(ast.true);
} else if (transition.kind === 'Atom') {
expressions.push(
ast.expression(
`${identifier} === ${charForComparison(transition.value)}`,
),
);
} else {
expressions.push(
ast.binop(
ast.expression(
`${identifier} >= ${charForComparison(transition.from)}`,
),
'&&',
ast.expression(
`${identifier} <= ${charForComparison(transition.to)}`,
),
),
);
}
}
if (expressions.length === 1) {
return expressions[0];
} else {
return expressions.reduce((acc, expression) => {
if (acc) {
return ast.binop(acc, '||', expression);
} else {
return expression;
}
});
}
}
function filterEmpty(...statements: Array<Statement>): Array<Statement> {
return statements.filter((statement) => statement.kind !== 'EmptyStatement');
}