-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.ts
246 lines (218 loc) · 6.38 KB
/
index.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
const OPERAND = 'operand'
const OPERATOR = 'operator'
const PREC: { [key: string]: number } = {
'(': -2,
')': -1,
or: 0,
and: 1,
not: 2,
}
const ASSOC: { [key: string]: string } = {
or: 'left',
and: 'left',
not: 'right',
}
const VALID_TOKEN = /^(?:@[^@]*|and|or|not|\(|\))$/;
/**
* Parses infix boolean expression (using Dijkstra's Shunting Yard algorithm)
* and builds a tree of expressions. The root node of the expression is returned.
*
* This expression can be evaluated by passing in an array of literals that resolve to true
*/
export default function parse(infix: string): Node {
const tokens = tokenize(infix)
if (tokens.length === 0) {
return new True()
}
const expressions: Node[] = []
const operators: string[] = []
let expectedTokenType = OPERAND
tokens.forEach(function (token) {
if (isUnary(token)) {
check(expectedTokenType, OPERAND)
operators.push(token)
expectedTokenType = OPERAND
} else if (isBinary(token)) {
check(expectedTokenType, OPERATOR)
while (
operators.length > 0 &&
isOp(peek(operators)) &&
((ASSOC[token] === 'left' && PREC[token] <= PREC[peek(operators)]) ||
(ASSOC[token] === 'right' && PREC[token] < PREC[peek(operators)]))
) {
pushExpr(pop(operators), expressions)
}
operators.push(token)
expectedTokenType = OPERAND
} else if ('(' === token) {
check(expectedTokenType, OPERAND)
operators.push(token)
expectedTokenType = OPERAND
} else if (')' === token) {
check(expectedTokenType, OPERATOR)
while (operators.length > 0 && peek(operators) !== '(') {
pushExpr(pop(operators), expressions)
}
if (operators.length === 0) {
throw new Error(
`Tag expression "${infix}" could not be parsed because of syntax error: Unmatched ).`
)
}
if (peek(operators) === '(') {
pop(operators)
}
expectedTokenType = OPERATOR
} else {
check(expectedTokenType, OPERAND)
pushExpr(token, expressions)
expectedTokenType = OPERATOR
}
})
while (operators.length > 0) {
if (peek(operators) === '(') {
throw new Error(
`Tag expression "${infix}" could not be parsed because of syntax error: Unmatched (.`
)
}
pushExpr(pop(operators), expressions)
}
return pop(expressions)
function check(expectedTokenType: string, tokenType: string) {
if (expectedTokenType !== tokenType) {
throw new Error(
`Tag expression "${infix}" could not be parsed because of syntax error: Expected ${expectedTokenType}.`
)
}
}
}
function tokenize(expr: string): string[] {
const tokens = []
let isEscaped = false
let token: string[] = []
for (let i = 0; i < expr.length; i++) {
const c = expr.charAt(i)
if (isEscaped) {
if (c === '(' || c === ')' || c === '\\' || /\s/.test(c)) {
token.push(c)
isEscaped = false
} else {
throw new Error(
`Tag expression "${expr}" could not be parsed because of syntax error: Illegal escape before "${c}".`
)
}
} else if (c === '\\') {
isEscaped = true
} else if (c === '(' || c === ')' || /\s/.test(c)) {
if (token.length > 0) {
isTokenValid(token.join(''),expr);
tokens.push(token.join(''))
token = []
}
if (!/\s/.test(c)) {
tokens.push(c)
}
} else {
token.push(c)
}
}
if (token.length > 0) {
isTokenValid(token.join(''),expr);
tokens.push(token.join(''))
}
return tokens
}
function isTokenValid(token: string, expr: string): void {
if (!token.match(VALID_TOKEN)) {
throw new Error(
`Tag expression "${expr}" could not be parsed because of syntax error: Please adhere to the Gherkin tag naming convention, using tags like "@tag1" and avoiding more than one "@" in the tag name.`
);
}
}
function isUnary(token: string) {
return 'not' === token
}
function isBinary(token: string) {
return 'or' === token || 'and' === token
}
function isOp(token: string) {
return ASSOC[token] !== undefined
}
function peek(stack: string[]) {
return stack[stack.length - 1]
}
function pop<T>(stack: T[]): T {
if (stack.length === 0) {
throw new Error('empty stack')
}
return stack.pop() as T
}
function pushExpr(token: string, stack: Node[]) {
if (token === 'and') {
const rightAndExpr = pop(stack)
stack.push(new And(pop(stack), rightAndExpr))
} else if (token === 'or') {
const rightOrExpr = pop(stack)
stack.push(new Or(pop(stack), rightOrExpr))
} else if (token === 'not') {
stack.push(new Not(pop(stack)))
} else {
stack.push(new Literal(token))
}
}
interface Node {
evaluate(variables: string[]): boolean
}
class Literal implements Node {
constructor(private readonly value: string) {}
public evaluate(variables: string[]) {
return variables.indexOf(this.value) !== -1
}
public toString() {
return this.value
.replace(/\\/g, '\\\\')
.replace(/\(/g, '\\(')
.replace(/\)/g, '\\)')
.replace(/\s/g, '\\ ')
}
}
class Or implements Node {
constructor(private readonly leftExpr: Node, private readonly rightExpr: Node) {}
public evaluate(variables: string[]) {
return this.leftExpr.evaluate(variables) || this.rightExpr.evaluate(variables)
}
public toString() {
return '( ' + this.leftExpr.toString() + ' or ' + this.rightExpr.toString() + ' )'
}
}
class And implements Node {
constructor(private readonly leftExpr: Node, private readonly rightExpr: Node) {}
public evaluate(variables: string[]) {
return this.leftExpr.evaluate(variables) && this.rightExpr.evaluate(variables)
}
public toString() {
return '( ' + this.leftExpr.toString() + ' and ' + this.rightExpr.toString() + ' )'
}
}
class Not implements Node {
constructor(private readonly expr: Node) {}
public evaluate(variables: string[]) {
return !this.expr.evaluate(variables)
}
public toString() {
if (this.expr instanceof And || this.expr instanceof Or) {
// -- HINT: Binary Operators already have already '( ... )'.
return 'not ' + this.expr.toString()
}
// -- OTHERWISE:
return 'not ( ' + this.expr.toString() + ' )'
}
}
class True implements Node {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public evaluate(variables: string[]) {
return true
}
public toString() {
return 'true'
}
}