-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMolang.ts
491 lines (445 loc) · 12.7 KB
/
Molang.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
import { ExecutionEnvironment } from './env/env'
import { IExpression, IParserConfig } from './main'
import { NameExpression, PrefixExpression } from './parser/expressions'
import { GenericOperatorExpression } from './parser/expressions/genericOperator'
import {
plusHelper,
minusHelper,
multiplyHelper,
divideHelper,
} from './parser/parselets/binaryOperator'
import { StaticExpression } from './parser/expressions/static'
import { StringExpression } from './parser/expressions/string'
import { MolangParser } from './parser/molang'
export class Molang {
protected expressionCache: Record<string, IExpression> = {}
protected totalCacheEntries = 0
protected executionEnvironment!: ExecutionEnvironment
protected parser: MolangParser
constructor(
env: Record<string, unknown> = {},
protected config: Partial<IParserConfig> = {}
) {
if (config.useOptimizer === undefined) this.config.useOptimizer = true
if (config.useCache === undefined) this.config.useCache = true
if (config.earlyReturnsSkipParsing === undefined)
this.config.earlyReturnsSkipParsing = true
if (config.earlyReturnsSkipTokenization === undefined)
this.config.earlyReturnsSkipTokenization = true
if (config.convertUndefined === undefined)
this.config.convertUndefined = false
this.parser = new MolangParser({
...this.config,
tokenizer: undefined,
})
this.updateExecutionEnv(env, config.assumeFlatEnvironment)
}
updateConfig(newConfig: Partial<IParserConfig>) {
newConfig = Object.assign(this.config, newConfig)
if (newConfig.tokenizer) this.parser.setTokenizer(newConfig.tokenizer)
this.parser.updateConfig({ ...this.config, tokenizer: undefined })
this.executionEnvironment.updateConfig(newConfig)
}
updateExecutionEnv(env: Record<string, unknown>, isFlat = false) {
this.executionEnvironment = new ExecutionEnvironment(env, {
useRadians: this.config.useRadians,
convertUndefined: this.config.convertUndefined,
isFlat,
variableHandler: this.config.variableHandler,
})
this.parser.setExecutionEnvironment(this.executionEnvironment)
}
/**
* Clears the Molang expression cache
*/
clearCache() {
this.expressionCache = {}
this.totalCacheEntries = 0
}
/**
* Execute the given Molang string `expression`
* @param expression The Molang string to execute
*
* @returns The value the Molang expression corresponds to
*/
execute(expression: string) {
this.parser.setExecutionEnvironment(this.executionEnvironment)
const abstractSyntaxTree = this.parse(expression)
const result = abstractSyntaxTree.eval()
if (result === undefined) return 0
if (typeof result === 'boolean') return Number(result)
return result
}
/**
* Execute the given Molang string `expression`
* In case of errors, return 0
* @param expression The Molang string to execute
*
* @returns The value the Molang expression corresponds to and 0 if the statement is invalid
*/
executeAndCatch(expression: string) {
try {
return this.execute(expression)
} catch {
return 0
}
}
/**
* Parse the given Molang string `expression`
* @param expression The Molang string to parse
*
* @returns An AST that corresponds to the Molang expression
*/
parse(expression: string): IExpression {
if (this.config.useCache ?? true) {
const abstractSyntaxTree = this.expressionCache[expression]
if (abstractSyntaxTree) return abstractSyntaxTree
}
this.parser.init(expression)
let abstractSyntaxTree = this.parser.parseExpression()
if ((this.config.useOptimizer ?? true) && abstractSyntaxTree.isStatic())
abstractSyntaxTree = new StaticExpression(abstractSyntaxTree.eval())
// console.log(JSON.stringify(abstractSyntaxTree, null, ' '))
if (this.config.useCache ?? true) {
if (this.totalCacheEntries > (this.config.maxCacheSize || 256))
this.clearCache()
this.expressionCache[expression] = abstractSyntaxTree
this.totalCacheEntries++
}
return abstractSyntaxTree
}
rearrangeOptimally(ast: IExpression): IExpression {
let lastAst
do {
lastAst = ast.toString()
ast = ast.walk((expr) => {
if (expr instanceof GenericOperatorExpression) {
let leftExpr = expr.allExpressions[0]
let rightExpr = expr.allExpressions[1]
if (
leftExpr instanceof GenericOperatorExpression &&
rightExpr.isStatic()
) {
let rightSubExpr = leftExpr.allExpressions[1]
let leftSubExpr = leftExpr.allExpressions[0]
//If leftmost is nonstatic and right is, swap
if (
!leftSubExpr.isStatic() &&
!(
leftSubExpr instanceof GenericOperatorExpression
) &&
rightSubExpr.isStatic()
) {
let temp = leftSubExpr
leftSubExpr = rightSubExpr
rightSubExpr = temp
}
if (!rightSubExpr.isStatic()) {
//Both are additions
if (
expr.operator === '+' &&
leftExpr.operator === '+'
) {
const newSubExpr =
new GenericOperatorExpression(
leftSubExpr,
rightExpr,
'+',
plusHelper
)
return new GenericOperatorExpression(
newSubExpr,
rightSubExpr,
'+',
plusHelper
)
}
//Both are subtractions
if (
expr.operator === '-' &&
leftExpr.operator === '-'
) {
const newSubExpr =
new GenericOperatorExpression(
leftSubExpr,
rightExpr,
'-',
minusHelper
)
return new GenericOperatorExpression(
newSubExpr,
rightSubExpr,
'-',
minusHelper
)
}
//Both are multiplications
if (
expr.operator === '*' &&
leftExpr.operator === '*'
) {
const newSubExpr =
new GenericOperatorExpression(
leftSubExpr,
rightExpr,
'*',
multiplyHelper
)
return new GenericOperatorExpression(
newSubExpr,
rightSubExpr,
'*',
multiplyHelper
)
}
//One is a division, other is a multiplication
if (
(expr.operator === '/' &&
leftExpr.operator === '*') ||
(expr.operator === '*' &&
leftExpr.operator === '/')
) {
const newSubExpr =
new GenericOperatorExpression(
leftSubExpr,
rightExpr,
'/',
divideHelper
)
return new GenericOperatorExpression(
newSubExpr,
rightSubExpr,
'*',
multiplyHelper
)
}
//Two divisions
if (
expr.operator === '/' &&
leftExpr.operator === '/'
) {
const newSubExpr =
new GenericOperatorExpression(
leftSubExpr,
rightExpr,
'*',
multiplyHelper
)
return new GenericOperatorExpression(
rightSubExpr,
newSubExpr,
'/',
divideHelper
)
}
//First is a subtraction, other is an addition
if (
expr.operator === '-' &&
leftExpr.operator === '+'
) {
const newSubExpr =
new GenericOperatorExpression(
leftSubExpr,
rightExpr,
'-',
minusHelper
)
return new GenericOperatorExpression(
newSubExpr,
rightSubExpr,
'+',
plusHelper
)
}
//First is an addition, other is an subtraction
if (
expr.operator === '+' &&
leftExpr.operator === '-'
) {
const newSubExpr =
new GenericOperatorExpression(
leftSubExpr,
rightExpr,
'+',
plusHelper
)
return new GenericOperatorExpression(
newSubExpr,
rightSubExpr,
'-',
minusHelper
)
}
}
}
}
})
} while (ast.toString() !== lastAst)
return ast
}
resolveStatic(ast: IExpression) {
// 0. Rearrange statements so all static expressions can be resolved
ast = this.rearrangeOptimally(ast)
// 1. Resolve all static expressions
ast = ast.walk((expr) => {
if (expr instanceof StringExpression) return
if (expr.isStatic()) return new StaticExpression(expr.eval())
})
// 2. Remove unnecessary operations
ast = ast.walk((expr) => {
if (expr instanceof GenericOperatorExpression) {
switch (expr.operator) {
case '+':
case '-': {
// If one of the two operands is 0,
// we can simplify the expression to only return the other operand
const zeroEquivalentOperand = expr.allExpressions.find(
(expr) => expr.isStatic() && expr.eval() === 0
)
//We check if the first operand is the zero equivalent operand
const firstOperand =
expr.allExpressions[0] === zeroEquivalentOperand
if (zeroEquivalentOperand) {
const otherOperand = expr.allExpressions.find(
(expr) => expr !== zeroEquivalentOperand
)
//If have subtraction and the first operand is the zero equivalent operand, we need to negate the other operand
if (
expr.operator === '-' &&
firstOperand &&
otherOperand
) {
return new PrefixExpression(
'MINUS',
otherOperand
)
}
//Fallback to only returning the other operand
return otherOperand
}
break
}
case '*': {
// If one of the two operands is 0,
// we can simplify the expression to 0
const zeroEquivalentOperand = expr.allExpressions.find(
(expr) => expr.isStatic() && expr.eval() === 0
)
if (zeroEquivalentOperand) {
return new StaticExpression(0)
}
// If one of the two operands is 1,
// we can simplify the expression to only return the other operand
const oneEquivalentOperand = expr.allExpressions.find(
(expr) => expr.isStatic() && expr.eval() === 1
)
if (oneEquivalentOperand) {
const otherOperand = expr.allExpressions.find(
(expr) => expr !== oneEquivalentOperand
)
return otherOperand
}
}
case '/': {
const leftOperand = expr.allExpressions[0]
const rightOperand = expr.allExpressions[1]
// If the right operand is 1, we can simplify the expression to only return the left operand
if (
rightOperand.isStatic() &&
rightOperand.eval() === 1
) {
return leftOperand
}
// If the left operand is 0, we can simplify the expression to 0
if (
leftOperand.isStatic() &&
leftOperand.eval() === 0
) {
return new StaticExpression(0)
}
break
}
}
//Limited common subexpression elimination
switch (expr.operator) {
case '+': {
const leftOperand = expr.allExpressions[0]
const rightOperand = expr.allExpressions[1]
if (
leftOperand.toString() === rightOperand.toString()
) {
return new GenericOperatorExpression(
new StaticExpression(2),
leftOperand,
'*',
multiplyHelper
)
}
break
}
case '-': {
const leftOperand = expr.allExpressions[0]
const rightOperand = expr.allExpressions[1]
if (
leftOperand.toString() === rightOperand.toString()
) {
return new StaticExpression(0)
}
}
}
}
})
return ast
}
minimize(ast: IExpression) {
// 1. Resolve all static expressions
ast = this.resolveStatic(ast)
// 2. Rename accessors to short hand
const replaceMap = new Map([
['query.', 'q.'],
['variable.', 'v.'],
['context.', 'c.'],
['temp.', 't.'],
])
ast = ast.walk((expr) => {
if (expr instanceof NameExpression) {
const name = expr.toString()
for (const [key, replaceWith] of replaceMap) {
if (name.startsWith(key)) {
expr.setName(name.replace(key, replaceWith))
}
}
return expr
}
})
// 3. Rename variables
/**
* TODO: We need to store the variable map across multiple calls to minimize because
* the variable transform needs to be consistent across multiple molang scripts.
* Temporary variables should still be cleared after a single call to minimize though.
*/
const variableMap = new Map()
ast = ast.walk((expr) => {
if (expr instanceof NameExpression) {
const name = expr.toString()
if (!name.startsWith('v.') && !name.startsWith('t.')) return
// Don't minify vars like "v.x" or "t.x"
if (name.length === 3) return
const varPrefix = name.startsWith('v.') ? 'v.' : 't.'
if (variableMap.has(name)) {
expr.setName(variableMap.get(name))
} else {
// Get unique name
const newName = `${varPrefix}v${variableMap.size}`
variableMap.set(name, newName)
expr.setName(newName)
}
return expr
}
})
return ast
}
getParser() {
return this.parser
}
}