-
Notifications
You must be signed in to change notification settings - Fork 1
/
condition-parser.ts
272 lines (229 loc) · 8.64 KB
/
condition-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
import { ConditionError } from '../../error/';
import { LexerToken, ParseTree } from '../';
/**
* A recursive decent parser for a SQL condition (WHERE or ON). This parser
* takes in a set of tokens, as generated by the [[ConditionLexer.parse]]
* method, and makes sure that the condition is valid. If the condition
* sentence does not match the condition grammer, an exception is raised.
* Otherwise, a [[ParseTree]] is created.
*/
export class ConditionParser {
/**
* Parse the tokens return a [[ParseTree]]. The condition must follow the
* following grammar.
*
* <pre>
* <condition> ::= "{" <comparison> | <null-comparison> | <in-comparison> | <logical-condition> "}"
* <comparison> ::= <comparison-operator> ":" "{" <column> ":" <value> "}"
* <null-comparison> ::= <null-comparison-operator> ":" "{" <column> ":" <nullable> "}"
* <in-comparison> ::= <in-comparison-operator> ":" "{" <column> ":" "[" <value> {"," <value>} "]" "}"
* <logical-condition> ::= <boolean-operator> ":" "[" <condition> {"," <condition>} "]"
* <comparison-operator> ::= "$eq" | "$neq" | "$lt" | "$lte" | "$gt" | "$gte" | "$like" | "$notlike"
* <in-comparison-operator> ::= "$in" | "$notIn"
* <null-comparison-operator> ::= "$is" | "$isnt"
* <boolean-operator> ::= "$and" | "$or"
* <nullable> ::= null | <parameter>
* <value> ::= <parameter> | <column> | <number>
* <column> ::= <string>
* <parameter> ::= :<string>
* </pre>
*
* @param tokens - An array of tokens, as created by the [[ConditionLexer]].parse
* method.
* @return - A parse tree. Each node in the tree has a token and children
* nodes.
*/
parse(tokens: LexerToken[]): ParseTree {
let tokenInd: number = 0;
let token: LexerToken = tokens[tokenInd];
let tree: ParseTree = null;
let curNode: ParseTree = null;
// Parse the program, and return the resulting parse tree.
condition();
if (token !== null)
throw new ConditionError(errorString('EOL'));
return tree;
// <condition> ::= "{" <comparison> | <null-comparison> | <in-comparison> | <logical-condition> "}"
function condition(): void {
const pairParts = ['comparison-operator', 'null-comparison-operator', 'in-comparison-operator', 'boolean-operator'];
charTerminal('{');
if (!tokenIn(pairParts))
throw new ConditionError(errorString('[' + pairParts.join(' | ') + ']'));
if (token.type === 'comparison-operator')
comparison();
else if (token.type === 'null-comparison-operator')
nullComparison();
else if (token.type === 'in-comparison-operator')
inComparison();
else
logicalCondition();
charTerminal('}');
}
// <comparison> ::= <comparison-operator> ":" "{" <column> ":" <value> "}"
function comparison(): void {
comparisonOperator();
charTerminal(':');
charTerminal('{');
column();
charTerminal(':');
value();
charTerminal('}');
}
// <in-comparison> ::= <in-comparison-operator> ":" "{" <column> ":" "[" <value> {"," <value>} "]" "}"
function inComparison(): void {
inComparisonOperator();
charTerminal(':');
charTerminal('{');
column();
charTerminal(':');
charTerminal('[');
value();
while (token.value === ',') {
charTerminal(',');
value();
}
charTerminal(']');
charTerminal('}');
}
// <null-comparison> ::= <null-comparison-operator> ":" "{" <column> ":" <nullable> "}"
function nullComparison(): void {
nullComparisonOperator();
charTerminal(':');
charTerminal('{');
column();
charTerminal(':');
nullable();
charTerminal('}');
}
// <logical-condition> ::= <boolean-operator> ":" "[" <condition> {"," <condition>} "]"
function logicalCondition(): void {
booleanOperator();
charTerminal(':');
charTerminal('[');
condition();
// <boolean-operator> is preceded by an array of <condition>. After adding each
// <condition> node make the <boolean-operator> the current node.
curNode = curNode.parent;
while (token && token.value === ',') {
charTerminal(',');
condition();
curNode = curNode.parent;
}
charTerminal(']');
}
// <comparison-operator> ::= "$eq" | "$neq" | "$lt" | "$lte" | "$gt" | "$gte"
function comparisonOperator(): void {
matchType('comparison-operator');
}
// <in-comparison-operator> ::= "$in" | "$notIn"
function inComparisonOperator(): void {
matchType('in-comparison-operator');
}
// <null-comparison-operator> ::= "$is" | "$isnt"
function nullComparisonOperator(): void {
matchType('null-comparison-operator');
}
// <boolean-operator> ::= "$and" | "$or"
function booleanOperator(): void {
matchType('boolean-operator');
}
// <nullable> ::= null | <parameter>
function nullable(): void {
const values = ['null', 'parameter'];
if (!tokenIn(values))
throw new ConditionError(errorString('[' + values.join(' | ') + ']'));
if (token.type === 'null')
nullTerminal();
else
parameter();
}
// <value> ::= <parameter> | <column> | <number>
function value(): void {
const values = ['parameter', 'column', 'number'];
if (!tokenIn(values))
throw new ConditionError(errorString('[' + values.join(' | ') + ']'));
if (token.type === 'parameter')
parameter();
else if (token.type === 'column')
column();
else
number();
}
// <parameter> ::= :<string>
function parameter(): void {
matchType('parameter');
}
// <column> ::= <string>
function column(): void {
matchType('column');
}
// Number terminal.
function number(): void {
matchType('number');
}
// Handles non-characters. Verifies that the current token's type matches
// the passed-in type. If not, an exception is raised. If so, the token is
// advanced.
function matchType(type: string): void {
if (token === null || token.type !== type)
throw new ConditionError(errorString(`<${type}>`));
addNode();
advance();
}
// Handles the basic character terminals, which aren't needed in the
// resulting sentence/tree. These are the basic terminals: "{", "}", "[",
// "]", ":", ","
function charTerminal(c: string): void {
if (token === null || c !== token.value)
throw new ConditionError(errorString(c));
advance();
}
// Checks that the current token is a null terminal.
function nullTerminal(): void {
if (token === null || token.type !== 'null')
throw new ConditionError(errorString('null'));
addNode();
advance();
}
// Move to the next token, or set token to null if the end of the sentence is
// encountered.
function advance(): void {
if (tokenInd >= tokens.length)
throw new ConditionError('Encountered the end of the sentence prematurely.');
if (++tokenInd < tokens.length)
token = tokens[tokenInd];
else
token = null;
}
// Check if the current token matches one of the types on toks.
function tokenIn(tokTypes: string[]): boolean {
return tokTypes.some(type => token.type === type);
}
// Helper to create an error string.
function errorString(expected: string): string {
const type = token ? token.type : 'EOL';
const value = token ? token.value : 'EOL';
return `At index ${tokenInd}. Expected ${expected} but found type ` +
`${type} with value ${value}.`;
}
// Helper function to add a node to the parse tree.
function addNode(): void {
const node = new ParseTree(curNode, token);
// If there is no tree, this is the root node.
if (tree === null) {
tree = curNode = node;
return;
}
// This node is a child of the current node.
curNode.children.push(node);
// If the current token is a non-terminal then make the new node the
// current node. The tree is structued with non-terminals having terminal
// children.
// __$eq__
// / \
// 'name' ':name'
if (!token.terminal)
curNode = node;
}
}
}