-
Notifications
You must be signed in to change notification settings - Fork 26
/
Parser.ts
674 lines (562 loc) · 15.1 KB
/
Parser.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
import skein from './skein';
import type {Token} from '..';
/**
* The type parameter `A` is the type of the AST nodes produced by the Grammar.
*/
export type Grammar<A> = {
[symbolName: string]: Expression | [Expression, (result: any) => A];
};
interface ExpressionOperators {
ignore: Expression;
optional: Expression;
plus: Expression;
star: Expression;
}
type Expression = TerminalSymbol | NonTerminalSymbol;
type TerminalSymbol = {
hash: string;
kind: 'TOKEN';
name: string;
predicate?: (contents: string) => boolean;
} & ExpressionOperators;
type AndExpression = {
hash: string;
kind: 'AND';
expression: Expression;
};
type ChoiceExpression = {
hash: string;
kind: 'CHOICE';
expressions: Array<Expression>;
} & ExpressionOperators;
type IgnoreExpression = {
hash: string;
kind: 'IGNORE';
expression: Expression;
};
type NotExpression = {
hash: string;
kind: 'NOT';
expression: Expression;
};
type OptionalExpression = {
hash: string;
kind: 'OPTIONAL';
expression: Expression;
};
type PlusExpression = {
hash: string;
kind: 'PLUS';
expression: Expression;
};
type SequenceExpression = {
hash: string;
kind: 'SEQUENCE';
expressions: Array<Expression>;
} & ExpressionOperators;
type StarExpression = {
hash: string;
kind: 'STAR';
expression: Expression;
};
type SymbolReference = {
hash: string;
kind: 'SYMBOL';
name: string;
};
type NonTerminalSymbol =
| AndExpression
| ChoiceExpression
| IgnoreExpression
| NotExpression
| OptionalExpression
| PlusExpression
| SequenceExpression
| StarExpression
| SymbolReference;
/**
* Packrat PEG parser.
*
* The type parameter, `A` is the type of AST nodes returned by the production
* functions in the Grammar.
*/
export default class Parser<A> {
private _errorIndex: number;
private _errorStack: Array<string>;
private _grammar: Grammar<A>;
private _isIgnored: (token: Token) => boolean;
private _iterator?: Generator<Token, Token>;
private _memo: Map<string, Map<number, [A, Token | null] | null>> | null;
private _parseStack: Array<string | null>;
constructor(grammar: Grammar<A>, isIgnored: (token: Token) => boolean) {
this._grammar = grammar;
this._isIgnored = isIgnored;
this._memo = null;
// Remember rightmost index.
this._errorIndex = 0;
this._errorStack = [];
this._parseStack = [];
if (!Object.keys(grammar).length) {
throw new Error('Grammar must have at least one rule');
}
}
parse(iterator: Generator<Token, Token>): A | null {
this._iterator = iterator;
const startToken = this.next();
if (!startToken) {
return null;
}
this._memo = new Map();
const rules = Object.keys(this._grammar);
const startRule = rules[0];
const maybe = this.evaluate(startRule, startToken);
if (maybe) {
const [result, next] = maybe;
if (next) {
// Failed to consume all input.
this._errorIndex = next.index;
this._errorStack = [];
} else {
this._memo = null;
return result;
}
}
throw new Error(
'Parse error:\n' +
'\n' +
` Expected: ${
this._errorStack[this._errorStack.length - 1] || 'end of input'
}\n` +
'\n' +
` Parsing: ${this._errorStack.join(' \u00bb ') || startRule}\n` +
'\n' +
` At: index ${this._errorIndex}\n`,
);
}
private evaluate(
start: Expression | string,
current: Token,
): [A, Token | null] | null {
const rule = typeof start === 'string' ? this._grammar[start] : start;
const index = current.index;
if (typeof start === 'string') {
this._parseStack.push(start);
} else {
this._parseStack.push(null);
}
if (!rule) {
throw new Error(
`Failed to resolve symbol reference ${JSON.stringify(rule)}`,
);
}
const [expression, production] = Array.isArray(rule)
? rule
: [rule, identity];
const key = expression.hash;
let map: Map<number, [A, Token | null] | null>;
if (this._memo!.has(key)) {
map = this._memo!.get(key)!;
} else {
map = new Map();
this._memo!.set(key, map);
}
if (map.has(index)) {
return map.get(index)!;
}
// TODO: instead of esoteric label and break statements, just repeat code
outer: {
switch (expression.kind) {
case 'AND':
// TODO
break;
case 'CHOICE':
{
let next: Token | null = current;
for (let i = 0; i < expression.expressions.length; i++) {
let result;
if (!next) {
// same edge case here, although less likely: next choice is
// optional expression (in practice, those should always
// include a non-optional part).
break;
}
const maybe = this.evaluate(expression.expressions[i], next);
if (maybe) {
[result, next] = maybe;
this._parseStack.pop();
const tuple: [A, Token | null] = [production(result), next];
map.set(index, tuple);
return tuple;
}
}
}
break;
case 'IGNORE':
{
const maybe = this.evaluate(expression.expression, current);
if (maybe) {
const [result, next] = maybe;
// Note that we don't actually ignore the result; it is up to
// the caller to do that (see the SEQUENCE case).
this._parseStack.pop();
const tuple: [A, Token | null] = [production(result), next];
map.set(index, tuple);
return tuple;
}
}
break;
case 'NOT':
// TODO
break;
case 'OPTIONAL': {
const maybe = this.evaluate(expression.expression, current);
this._parseStack.pop();
if (maybe) {
const [result, next] = maybe;
const tuple: [A, Token | null] = [production(result), next];
map.set(index, tuple);
return tuple;
} else {
const tuple: [A, Token | null] = [production(undefined), current];
map.set(index, tuple);
return tuple;
}
}
case 'PLUS':
{
const results = [];
let next: Token | null = current;
while (next) {
const maybe = this.evaluate(expression.expression, next);
let result;
if (maybe) {
[result, next] = maybe;
results.push(result);
} else {
break;
}
}
if (results.length) {
this._parseStack.pop();
const tuple: [A, Token | null] = [production(results), next];
map.set(index, tuple);
return tuple;
}
}
break;
case 'SEQUENCE': {
const results = [];
let next: Token | null = current;
for (let i = 0; i < expression.expressions.length; i++) {
if (!next) {
// edge case here: no next token, but next expression(s) is/are optional...
break;
}
const subExpression = expression.expressions[i];
const maybe = this.evaluate(subExpression, next);
let result;
if (maybe) {
[result, next] = maybe;
if (
typeof subExpression === 'string' ||
subExpression.kind !== 'IGNORE'
) {
results.push(result);
}
} else {
break outer;
}
}
this._parseStack.pop();
const tuple: [A, Token | null] = [production(results), next];
map.set(index, tuple);
return tuple;
}
case 'STAR': {
const results = [];
let next: Token | null = current;
while (next) {
const maybe = this.evaluate(expression.expression, next);
let result;
if (maybe) {
[result, next] = maybe;
results.push(result);
} else {
break;
}
}
this._parseStack.pop();
const tuple: [A, Token | null] = [
production(results.length ? results : undefined),
next,
];
map.set(index, tuple);
return tuple;
}
case 'SYMBOL':
{
const maybe = this.evaluate(expression.name, current);
if (maybe) {
const [result, next] = maybe;
// TODO: refactor to avoid this repetition
this._parseStack.pop();
const tuple: [A, Token | null] = [production(result), next];
map.set(index, tuple);
return tuple;
}
}
break;
case 'TOKEN':
if (current.name === expression.name) {
if (
expression.predicate &&
!expression.predicate(current.contents)
) {
break outer;
}
this._parseStack.pop();
const tuple: [A, Token | null] = [
production(current.contents),
this.next(),
];
map.set(index, tuple);
return tuple;
}
break;
}
}
if (index > this._errorIndex) {
this._errorIndex = index;
this._errorStack = this._parseStack.filter(isNonNull);
}
this._parseStack.pop();
map.set(index, null);
return null;
}
/**
* Returns the next lexical (non-ignored) Token after `token`, or
* `null` if there isn't one.
*/
private next(): Token | null {
while (true) {
const {done, value} = this._iterator!.next();
if (done) {
break;
} else {
if (this._isIgnored(value)) {
continue;
}
return value;
}
}
return null;
}
}
/**
* "And" predicate.
*
* Succeeds when `expression` succeeds, but does not consume any input.
*/
export function and(value: Expression | string): AndExpression {
const expression = wrap(value);
return {
hash: `and:${skein(expression.hash)}`,
expression,
kind: 'AND',
};
}
/**
* Ordered choice.
*
* Tries each expression in `expressions`, succeeding as soon as encountering a
* successful expression. After each unsuccessful match, backtracks.
*/
export function choice(
...values: Array<Expression | string>
): ChoiceExpression {
const expressions = values.map(wrap);
return withProperties({
hash: `choice:${skein(expressions.map(hash).join(':'))}`,
expressions,
kind: 'CHOICE',
});
}
/**
* Takes something that may be a symbol reference (ie. a string referencing
* another rule) and turns it into an expression.
*/
function wrap(maybeReference: string | Expression): Expression {
if (typeof maybeReference === 'string') {
return r(maybeReference);
} else {
return maybeReference;
}
}
/**
* Returns a hash for `expression`.
*
* This is a function to facilitate easy mapping over an array; eg:
*
* expressions.map(hash)
*
* as opposed to:
*
* expressions.map(expression => expression.hash)
*
*/
function hash(expression: Expression): string {
return expression.hash;
}
/**
* Identity function that returns its argument unmodified.
*/
function identity<T extends unknown>(id: T): T {
return id;
}
/**
* Succeeds when the wrapped `expression` succeeds, and marks the result to be
* consumed but not propagated.
*
* The typical use case is to recognize a syntatic construct like a list, where
* you want to recognize but discard the opening and closing brackets, but
* capture the inner contents.
*
* Note: currently only the `sequence` functionality pays attention to this
* modifier.
*/
export function ignore(value: Expression | string): IgnoreExpression {
const expression = wrap(value);
return {
hash: `ignore:${skein(expression.hash)}`,
expression,
kind: 'IGNORE',
};
}
function isNonNull<T>(value: T | null): value is T {
return value !== null;
}
/**
* "Not" predicate.
*
* Succeeds when `expression` does not succeed, but does not consume any input.
*/
export function not(value: Expression | string): NotExpression {
const expression = wrap(value);
return {
hash: `not:${skein(expression.hash)}`,
expression,
kind: 'NOT',
};
}
/**
* Optional combinator.
*
* Succeeds when 0 or 1 repetitions of `expression` succeed.
*/
export function optional(value: Expression | string): OptionalExpression {
const expression = wrap(value);
return {
hash: `optional:${skein(expression.hash)}`,
expression,
kind: 'OPTIONAL',
};
}
/**
* Kleene plus.
*
* Succeeds when 1 or more repetitions of `expression` succeed.
*/
export function plus(value: Expression | string): PlusExpression {
const expression = wrap(value);
return {
hash: `plus:${skein(expression.hash)}`,
expression,
kind: 'PLUS',
};
}
/**
* Sequence.
*
* Tries each expression in `expressions`, succeeding if all expressions are
* successful. Fails on any unsuccessful match.
*/
export function sequence(
...values: Array<Expression | string>
): SequenceExpression {
const expressions = values.map(wrap);
return withProperties({
hash: `sequence:${skein(expressions.map(hash).join(':'))}`,
expressions,
kind: 'SEQUENCE',
});
}
/**
* Kleene star.
*
* Succeeds when 0 or more repetitions of `expression` succeed.
*/
export function star(value: Expression | string): StarExpression {
const expression = wrap(value);
return {
hash: `star:${skein(expression.hash)}`,
expression,
kind: 'STAR',
};
}
/**
* Creates a symbol that references another rule.
*/
export function r(name: string): SymbolReference {
return {
hash: `r:${skein(name)}`,
kind: 'SYMBOL',
name,
};
}
/**
* Represents a terminal symbol of the type identified by `name`.
*
* The optional `predicate` function allows an arbitrary check of the token
* contents to be specified to gate success.
*
* TODO: add disclaimer here about hashes assuming predicate doesn't close over
* anything...
*/
export function t(
name: string,
predicate?: (contents: string) => boolean,
): TerminalSymbol {
return withProperties({
hash: `t:${skein(
[name, predicate?.toString() ?? ''].map(skein).join(':'),
)}`,
kind: 'TOKEN',
name,
predicate,
});
}
function withProperties<T extends unknown>(base: T): T & ExpressionOperators {
Object.defineProperties(base, {
ignore: {
get() {
return withProperties(ignore(base as Expression));
},
},
optional: {
get() {
return withProperties(optional(base as Expression));
},
},
plus: {
get() {
return withProperties(plus(base as Expression));
},
},
star: {
get() {
return withProperties(star(base as Expression));
},
},
});
return base as T & ExpressionOperators;
}