This repository has been archived by the owner on Jun 4, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
syntaxer.ts
76 lines (58 loc) · 1.87 KB
/
syntaxer.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
import Logger from 'core/Logger';
import { ILexemeResult, ILexerResult } from 'core/syntax-tree/lexer';
import { ILexeme } from 'core/syntax-tree/lexicon';
export interface ISyntaxerResult {
tree?: ISyntaxTree;
valid: boolean;
error?: string;
}
export interface ISyntaxTree {
lexeme: ILexeme;
block?: ISyntaxTree;
left?: ISyntaxTree;
right: ISyntaxTree;
value: string;
}
const parser = (lexs: ILexemeResult[]): ISyntaxTree => {
let nesting = 0;
const nestedLexs = lexs.map(lex => {
const res = Object.assign({}, lex, { nesting: nesting });
nesting += (lex.lexeme.nesting || 0);
return res;
});
// find lowest priority 0-nesting lex
const pivot = nestedLexs
.filter(lex => lex.nesting === 0 && typeof lex.lexeme.priority === 'number')
.sort((a, b) => (b.lexeme.priority || -1) - (a.lexeme.priority || -1))[0];
Logger.trace('parser -> pivot', pivot, lexs);
const pivotIndex = nestedLexs.indexOf(pivot);
if (pivot.lexeme.syntaxer) {
let tree = pivot.lexeme.syntaxer(lexs, pivot, pivotIndex);
if (Array.isArray(tree.left)) {
tree.left = parser(tree.left);
}
if (Array.isArray(tree.right)) {
tree.right = parser(tree.right);
}
if (Array.isArray(tree.block)) {
tree.block = parser(tree.block);
}
return tree;
} else {
throw new Error(pivot.lexeme.type);
}
};
export default (lexerResult: ILexerResult): ISyntaxerResult => {
const { lexemes } = lexerResult;
if (!lexerResult.valid) {
return { valid: false, error: `lexer -- ${lexerResult.error}` };
}
if (lexerResult.lexemes.length === 0) {
return { valid: true };
}
try {
return { tree: parser(lexemes), valid: true };
} catch (error) {
return { valid: false, error };
}
};