-
Notifications
You must be signed in to change notification settings - Fork 46
/
chain.ts
732 lines (649 loc) · 20.5 KB
/
chain.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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/* eslint-disable no-use-before-define */
import { defaults, uniq, uniqBy } from 'lodash';
import { Lexer } from '../lexer';
import { IToken } from '../lexer/token';
import {
Chain,
ChainFunction,
ChainNode,
ChainNodeFactory,
CreateParserOptions,
FirstOrFunctionSet,
FunctionNode,
IElement,
IParseResult,
MatchNode,
MAX_VISITER_CALL,
Node,
ParentNode,
Parser,
parserMap,
TreeNode,
VisiterOption,
VisiterStore,
} from './define';
import { match, matchFalse, matchTrue } from './match';
import { Scanner } from './scanner';
import { compareIgnoreLowerCaseWhenString, getPathByCursorIndexFromAst, tailCallOptimize } from './utils';
const createNodeByElement = (element: IElement, parentNode: ParentNode, parentIndex: number, parser: Parser): Node => {
if (element instanceof Array) {
const treeNode = new TreeNode(parentIndex);
treeNode.parentNode = parentNode;
treeNode.childs = element.map((eachElement, childIndex) => {
return createNodeByElement(eachElement, treeNode, childIndex, parser);
});
return treeNode;
}
if (typeof element === 'string') {
const matchNode = new MatchNode(
match(element)(),
{
type: 'string',
value: element,
},
parentIndex,
);
matchNode.parentNode = parentNode;
return matchNode;
}
if (typeof element === 'boolean') {
if (element) {
const trueMatchNode = new MatchNode(
matchTrue,
{
type: 'loose',
value: true,
},
parentIndex,
);
trueMatchNode.parentNode = parentNode;
return trueMatchNode;
}
const falseMatchNode = new MatchNode(
matchFalse,
{
type: 'loose',
value: false,
},
parentIndex,
);
falseMatchNode.parentNode = parentNode;
return falseMatchNode;
}
if (typeof element === 'function') {
if (element.parserName === 'match') {
const matchNode = new MatchNode(
element(),
{
type: 'special',
value: element.displayName,
},
parentIndex,
);
matchNode.parentNode = parentNode;
return matchNode;
}
if (element.parserName === 'chainNodeFactory') {
const chainNode = element(parentNode, null, parentIndex, parser);
return chainNode;
}
const functionNode = new FunctionNode(element as ChainFunction, parentIndex, parser);
functionNode.parentNode = parentNode;
return functionNode;
}
throw Error(`unknow element in chain ${element}`);
};
export const chain: Chain = (...elements) => {
return (
solveAst = args => {
return args;
},
) => {
const chainNodeFactory: ChainNodeFactory = (parentNode, creatorFunction, parentIndex = 0, parser) => {
const chainNode = new ChainNode(parentIndex);
chainNode.parentNode = parentNode;
chainNode.creatorFunction = creatorFunction;
chainNode.solveAst = solveAst;
chainNode.childs = elements.map((element, index) => {
return createNodeByElement(element, chainNode, index, parser);
});
if (creatorFunction) {
generateFirstSet(chainNode, parser);
}
return chainNode;
};
(chainNodeFactory as any).parserName = 'chainNodeFactory';
return chainNodeFactory;
};
};
function getParser(root: ChainFunction) {
if (parserMap.has(root)) {
return parserMap.get(root);
}
const parser = new Parser();
parser.rootChainNode = root()(null, null, 0, parser);
parserMap.set(root, parser);
return parser;
}
function scannerAddCursorToken(scanner: Scanner, cursorIndex: number, options?: CreateParserOptions) {
let finalCursorIndex = cursorIndex;
if (cursorIndex === null) {
return { scanner, finalCursorIndex };
}
// Find where token cursorIndex is in.
const cursorToken = scanner.getTokenByCharacterIndex(cursorIndex);
// Generate cursor token, if cursor position is not in a token.
if (!cursorToken) {
// If cursor not on token, add a match-all token.
scanner.addToken({
type: 'cursor',
value: null,
position: [cursorIndex, cursorIndex],
});
} else if (options.cursorTokenExcludes(cursorToken)) {
// If cursor is exclude, add a token next!
scanner.addToken({
type: 'cursor',
value: null,
position: [cursorIndex + 1, cursorIndex + 1],
});
finalCursorIndex += 1;
}
return { scanner, finalCursorIndex };
}
export const createParser = <AST = {}>(root: ChainFunction, lexer: Lexer, options?: CreateParserOptions) => {
return (text: string, cursorIndex: number = null): IParseResult => {
// eslint-disable-next-line no-param-reassign
options = defaults(options || {}, new CreateParserOptions());
const startTime = new Date();
const tokens = lexer(text);
const lexerTime = new Date();
const originScanner = new Scanner(tokens);
const { scanner, finalCursorIndex } = scannerAddCursorToken(new Scanner(tokens), cursorIndex, options);
// eslint-disable-next-line no-param-reassign
cursorIndex = finalCursorIndex;
const parser = getParser(root);
const cursorPrevToken = scanner.getPrevTokenByCharacterIndex(cursorIndex).prevToken;
// If cursorPrevToken is null, the cursor prev node is root.
let cursorPrevNodes: Node[] = cursorPrevToken === null ? [parser.rootChainNode] : [];
let success = false;
let ast: AST = null;
let callVisiterCount = 0;
let callParentCount = 0;
let lastMatchUnderShortestRestToken: {
restTokenCount: number;
matchNode: MatchNode;
token: IToken;
} = null;
// Parse without cursor token
newVisit({
node: parser.rootChainNode,
scanner: originScanner,
visiterOption: {
onCallVisiter: (node, store) => {
callVisiterCount += 1;
if (callVisiterCount > MAX_VISITER_CALL) {
// eslint-disable-next-line no-param-reassign
store.stop = true;
}
},
onVisiterNextNode: (node, store) => {
callParentCount += 1;
if (callParentCount > MAX_VISITER_CALL) {
// eslint-disable-next-line no-param-reassign
store.stop = true;
}
},
onMatchNode: (matchNode, store, currentVisiterOption) => {
const matchResult = matchNode.run(store.scanner);
if (!matchResult.match) {
tryChances(matchNode, store, currentVisiterOption);
} else {
const restTokenCount = store.scanner.getRestTokenCount();
// Last match at least token remaining, is the most readable reason for error.
if (
!lastMatchUnderShortestRestToken ||
(lastMatchUnderShortestRestToken && lastMatchUnderShortestRestToken.restTokenCount > restTokenCount)
) {
lastMatchUnderShortestRestToken = {
matchNode,
token: matchResult.token,
restTokenCount,
};
}
visitNextNodeFromParent(matchNode, store, currentVisiterOption, {
token: true,
...matchResult.token,
});
}
},
onSuccess: () => {
success = true;
},
onFail: node => {
success = false;
},
},
parser,
});
// Parse with curosr token
newVisit({
node: parser.rootChainNode,
scanner,
visiterOption: {
onCallVisiter: (node, store) => {
callVisiterCount += 1;
if (callVisiterCount > MAX_VISITER_CALL) {
// eslint-disable-next-line no-param-reassign
store.stop = true;
}
},
onVisiterNextNode: (node, store) => {
callParentCount += 1;
if (callParentCount > MAX_VISITER_CALL) {
// eslint-disable-next-line no-param-reassign
store.stop = true;
}
},
onSuccess: () => {
ast = parser.rootChainNode.solveAst
? parser.rootChainNode.solveAst(parser.rootChainNode.astResults)
: parser.rootChainNode.astResults;
},
onMatchNode: (matchNode, store, currentVisiterOption) => {
const matchResult = matchNode.run(store.scanner);
if (!matchResult.match) {
tryChances(matchNode, store, currentVisiterOption);
} else {
// If cursor prev token isn't null, it may a cursor prev node.
if (cursorPrevToken !== null && matchResult.token === cursorPrevToken) {
cursorPrevNodes.push(matchNode);
}
visitNextNodeFromParent(matchNode, store, currentVisiterOption, {
token: true,
...matchResult.token,
});
}
},
},
parser,
});
cursorPrevNodes = uniq(cursorPrevNodes);
// Get next matchings
let nextMatchNodes = cursorPrevNodes.reduce(
(all, cursorPrevNode) => {
return all.concat(findNextMatchNodes(cursorPrevNode, parser));
},
[] as MatchNode[],
);
nextMatchNodes = uniqBy(nextMatchNodes, each => {
return each.matching.type + each.matching.value;
});
// If has next token, filter nextMatchNodes by cursorNextToken
const cursorNextToken = scanner.getNextTokenFromCharacterIndex(cursorIndex);
if (cursorNextToken) {
nextMatchNodes = nextMatchNodes.filter(nextMatchNode => {
return !compareIgnoreLowerCaseWhenString(nextMatchNode.matching.value, cursorNextToken.value);
});
}
// Get error message
let error: IParseResult['error'] = null;
if (!success) {
const suggestions = uniqBy(
(lastMatchUnderShortestRestToken
? findNextMatchNodes(lastMatchUnderShortestRestToken.matchNode, parser)
: findNextMatchNodes(parser.rootChainNode, parser)
).map(each => {
return each.matching;
}),
each => {
return each.type + each.value;
},
);
const errorToken =
lastMatchUnderShortestRestToken && scanner.getNextByToken(lastMatchUnderShortestRestToken.token);
if (errorToken) {
error = {
suggestions,
token: errorToken,
reason: 'wrong',
};
} else {
error = {
suggestions,
token: lastMatchUnderShortestRestToken ? lastMatchUnderShortestRestToken.token : null,
reason: 'incomplete',
};
}
}
const parserTime = new Date();
// Find cursor ast from whole ast.
const cursorKeyPath = getPathByCursorIndexFromAst(ast, cursorIndex).split('.');
return {
success,
ast,
cursorKeyPath: cursorKeyPath[0] === '' ? [] : cursorKeyPath,
nextMatchings: nextMatchNodes
.reverse()
.map(each => {
return each.matching;
})
.filter(each => {
return !!each.value;
}),
error,
debugInfo: {
tokens,
callVisiterCount,
costs: {
lexer: lexerTime.getTime() - startTime.getTime(),
parser: parserTime.getTime() - startTime.getTime(),
},
},
};
};
};
function newVisit({
node,
scanner,
visiterOption,
parser,
}: {
node: Node;
scanner: Scanner;
visiterOption: VisiterOption;
parser: Parser;
}) {
const defaultVisiterOption = new VisiterOption();
defaults(visiterOption, defaultVisiterOption);
const newStore = new VisiterStore(scanner, parser);
visit({ node, store: newStore, visiterOption, childIndex: 0 });
}
const visit = tailCallOptimize(
({
node,
store,
visiterOption,
childIndex,
}: {
node: Node;
store: VisiterStore;
visiterOption: VisiterOption;
childIndex: number;
}) => {
if (store.stop) {
fail(node, store, visiterOption);
return;
}
if (!node) {
throw Error('no node!');
}
if (visiterOption.onCallVisiter) {
visiterOption.onCallVisiter(node, store);
}
if (node instanceof ChainNode) {
if (firstSetUnMatch(node, store, visiterOption, childIndex)) {
return; // If unmatch, stop!
}
visitChildNode({ node, store, visiterOption, childIndex });
} else if (node instanceof TreeNode) {
visitChildNode({ node, store, visiterOption, childIndex });
} else if (node instanceof MatchNode) {
if (node.matching.type === 'loose') {
if (node.matching.value === true) {
visitNextNodeFromParent(node, store, visiterOption, null);
} else {
throw Error('Not support loose false!');
}
} else {
visiterOption.onMatchNode(node, store, visiterOption);
}
} else if (node instanceof FunctionNode) {
const functionName = node.chainFunction.name;
const replacedNode = node.run();
replacedNode.functionName = functionName;
// eslint-disable-next-line no-param-reassign
node.parentNode.childs[node.parentIndex] = replacedNode;
visit({ node: replacedNode, store, visiterOption, childIndex: 0 });
} else {
throw Error(`Unexpected node type: ${node}`);
}
},
);
function visitChildNode({
node,
store,
visiterOption,
childIndex,
}: {
node: ParentNode;
store: VisiterStore;
visiterOption: VisiterOption;
childIndex: number;
}) {
if (node instanceof ChainNode) {
const child = node.childs[childIndex];
if (child) {
visit({ node: child, store, visiterOption, childIndex: 0 });
} else {
visitNextNodeFromParent(
node,
store,
visiterOption,
visiterOption.generateAst ? node.solveAst(node.astResults) : null,
);
}
} else {
// This case, Node === TreeNode
const child = node.childs[childIndex];
if (childIndex + 1 < node.childs.length) {
addChances({
node,
store,
visiterOption,
tokenIndex: store.scanner.getIndex(),
childIndex: childIndex + 1,
addToNextMatchNodeFinders: true,
});
}
if (child) {
visit({ node: child, store, visiterOption, childIndex: 0 });
} else {
throw Error('tree node unexpect end');
}
}
}
const visitNextNodeFromParent = tailCallOptimize(
(node: Node, store: VisiterStore, visiterOption: VisiterOption, astValue: any) => {
if (store.stop) {
fail(node, store, visiterOption);
return;
}
if (visiterOption.onVisiterNextNode) {
visiterOption.onVisiterNextNode(node, store);
}
if (!node.parentNode) {
return noNextNode(node, store, visiterOption);
}
if (node.parentNode instanceof ChainNode) {
if (visiterOption.generateAst) {
// eslint-disable-next-line no-param-reassign
node.parentNode.astResults[node.parentIndex] = astValue;
}
// A B <- next node C
// └── node <- current node
visit({ node: node.parentNode, store, visiterOption, childIndex: node.parentIndex + 1 });
} else if (node.parentNode instanceof TreeNode) {
visitNextNodeFromParent(node.parentNode, store, visiterOption, astValue);
} else {
throw Error(`Unexpected parent node type: ${node.parentNode}`);
}
},
);
function noNextNode(node: Node, store: VisiterStore, visiterOption: VisiterOption) {
if (store.scanner.isEnd()) {
if (visiterOption.onSuccess) {
visiterOption.onSuccess();
}
} else {
tryChances(node, store, visiterOption);
}
}
function addChances({
node,
store,
visiterOption,
tokenIndex,
childIndex,
addToNextMatchNodeFinders,
}: {
node: ParentNode;
store: VisiterStore;
visiterOption: VisiterOption;
tokenIndex: number;
childIndex: number;
addToNextMatchNodeFinders: boolean;
}) {
const chance = {
node,
tokenIndex,
childIndex,
};
store.restChances.push(chance);
}
function hasParentNodeByFunctionName(node: Node, functionName: string): boolean {
if (node instanceof ChainNode && node.functionName === functionName) {
return true;
}
if (node.parentNode) {
return hasParentNodeByFunctionName(node.parentNode, functionName);
}
return false;
}
function tryChances(node: Node, store: VisiterStore, visiterOption: VisiterOption) {
if (store.restChances.length === 0) {
fail(node, store, visiterOption);
return;
}
const nextChance = store.restChances.pop();
// reset scanner index
store.scanner.setIndex(nextChance.tokenIndex);
visit({ node: nextChance.node, store, visiterOption, childIndex: nextChance.childIndex });
}
function fail(node: Node, store: VisiterStore, visiterOption: VisiterOption) {
if (visiterOption.onFail) {
visiterOption.onFail(node);
}
}
// Find all tokens that may appear next
function findNextMatchNodes(node: Node, parser: Parser): MatchNode[] {
const nextMatchNodes: MatchNode[] = [];
let passCurrentNode = false;
const visiterOption: VisiterOption = {
generateAst: false,
enableFirstSet: false,
onMatchNode: (matchNode, store, currentVisiterOption) => {
if (matchNode === node && passCurrentNode === false) {
passCurrentNode = true;
visitNextNodeFromParent(matchNode, store, currentVisiterOption, null);
} else {
nextMatchNodes.push(matchNode);
}
// Suppose the match failed, so we can find another possible match chance!
tryChances(matchNode, store, currentVisiterOption);
},
};
newVisit({ node, scanner: new Scanner([]), visiterOption, parser });
return nextMatchNodes;
}
// First Set -----------------------------------------------------------------
function firstSetUnMatch(node: ChainNode, store: VisiterStore, visiterOption: VisiterOption, childIndex: number) {
if (
visiterOption.enableFirstSet &&
node.creatorFunction &&
childIndex === 0 &&
store.parser.firstSet.has(node.creatorFunction)
) {
const firstMatchNodes = store.parser.firstSet.get(node.creatorFunction);
// If not match any first match node, try chances
if (
!firstMatchNodes.some(firstMatchNode => {
return firstMatchNode.run(store.scanner, false).match;
})
) {
tryChances(node, store, visiterOption);
return true; // Yes, unMatch.
}
return false; // No, Match.
}
}
function generateFirstSet(node: ChainNode, parser: Parser) {
if (parser.firstSet.has(node.creatorFunction)) {
return;
}
const firstMatchNodes = getFirstOrFunctionSet(node, node.creatorFunction, parser);
parser.firstOrFunctionSet.set(node.creatorFunction, firstMatchNodes);
solveFirstSet(node.creatorFunction, parser);
}
function getFirstOrFunctionSet(node: Node, creatorFunction: ChainFunction, parser: Parser): FirstOrFunctionSet[] {
if (node instanceof ChainNode) {
if (node.childs[0]) {
return getFirstOrFunctionSet(node.childs[0], creatorFunction, parser);
}
} else if (node instanceof TreeNode) {
return node.childs.reduce((all, next) => {
return all.concat(getFirstOrFunctionSet(next, creatorFunction, parser));
}, []);
} else if (node instanceof MatchNode) {
return [node];
} else if (node instanceof FunctionNode) {
if (parser.relatedSet.has(node.chainFunction)) {
parser.relatedSet.get(node.chainFunction).add(creatorFunction);
} else {
parser.relatedSet.set(node.chainFunction, new Set([creatorFunction]));
}
return [node.chainFunction];
} else {
throw Error(`Unexpected node: ${node}`);
}
}
function solveFirstSet(creatorFunction: ChainFunction, parser: Parser) {
if (parser.firstSet.has(creatorFunction)) {
return;
}
const firstMatchNodes = parser.firstOrFunctionSet.get(creatorFunction);
// Try if relate functionName has done first set.
const newFirstMatchNodes = firstMatchNodes.reduce(
(all, firstMatchNode) => {
if (typeof firstMatchNode === 'string') {
if (parser.firstSet.has(firstMatchNode)) {
// eslint-disable-next-line no-param-reassign
all = all.concat(parser.firstSet.get(firstMatchNode));
} else {
all.push(firstMatchNode);
}
} else {
all.push(firstMatchNode);
}
return all;
},
[] as FirstOrFunctionSet[],
);
parser.firstOrFunctionSet.set(creatorFunction, newFirstMatchNodes);
// If all set hasn't function node, we can solve it's relative set.
if (
newFirstMatchNodes.every(firstMatchNode => {
return firstMatchNode instanceof MatchNode;
})
) {
parser.firstSet.set(creatorFunction, newFirstMatchNodes as MatchNode[]);
// If this functionName has related functionNames, solve them
if (parser.relatedSet.has(creatorFunction)) {
const relatedFunctionNames = parser.relatedSet.get(creatorFunction);
relatedFunctionNames.forEach(relatedFunctionName => {
return solveFirstSet;
});
}
}
}
// First set /////////////////////////////////////////////////////////////////