forked from DTStack/dt-sql-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicParser.ts
More file actions
111 lines (90 loc) · 2.72 KB
/
Copy pathbasicParser.ts
File metadata and controls
111 lines (90 loc) · 2.72 KB
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
import { Token, Lexer } from 'antlr4';
import { ParseTreeWalker } from 'antlr4/tree';
import ParserErrorListener, {
ParserError,
ErrorHandler,
ParserErrorCollector,
} from './parserErrorListener';
/**
* Custom Parser class, subclass needs extends it.
*/
export default abstract class BasicParser<C = any> {
private _parser;
public parse(
input: string,
errorListener?: ErrorHandler,
) {
const parser = this.createParser(input);
this._parser = parser;
parser.removeErrorListeners();
parser.addErrorListener(new ParserErrorListener(errorListener));
const parserTree = parser.program();
return parserTree;
}
public validate(input: string): ParserError[] {
const lexerError = []; const syntaxErrors = [];
const parser = this.createParser(input);
this._parser = parser;
parser.removeErrorListeners();
parser.addErrorListener(new ParserErrorCollector(syntaxErrors));
parser.program();
return lexerError.concat(syntaxErrors);
}
/**
* Create antrl4 Lexer object
* @param input source string
*/
public abstract createLexer(input: string): Lexer;
/**
* Create Parser by lexer
* @param lexer Lexer
*/
public abstract createParserFromLexer(lexer: Lexer);
/**
* Visit parser tree
* @param parserTree
*/
// public abstract visit(visitor: any, parserTree: any);
/**
* The source string
* @param input string
*/
public getAllTokens(input: string): Token[] {
return this.createLexer(input).getAllTokens();
};
/**
* Get Parser instance by input string
* @param input
*/
public createParser(input: string) {
const lexer = this.createLexer(input);
const parser: any = this.createParserFromLexer(lexer);
parser.buildParseTrees = true;
this._parser = parser;
return parser;
}
/**
* It convert tree to string, it's convenient to use in unit test.
* @param string input
*/
public parserTreeToString(input: string): string {
const parser = this.createParser(input);
this._parser = parser;
const tree = parser.program();
return tree.toStringTree(parser.ruleNames);
}
/**
* Get List-like style tree string
* @param parserTree
*/
public toString(parserTree: any): string {
return parserTree.toStringTree(this._parser.ruleNames);
}
/**
* @param listener Listener instance extends ParserListener
* @param parserTree parser Tree
*/
public listen(listener: any, parserTree: any) {
ParseTreeWalker.DEFAULT.walk(listener, parserTree);
}
}