-
Notifications
You must be signed in to change notification settings - Fork 2
/
eval.go
536 lines (436 loc) · 11.7 KB
/
eval.go
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
package spiker
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
// Evaluator run the expression and evaluate the value
func Evaluator(nodeList []AstNode) (res interface{}, err error) {
globalScope := NewScopeTable("GLOBAL", 1, nil)
return EvaluateWithScope(nodeList, globalScope)
}
// EvaluateWithScope same as Evaluator, evaluate with scope
func EvaluateWithScope(nodeList []AstNode, scope *VariableScope) (res interface{}, err error) {
defer func() {
if e := recover(); e != nil {
if e, ok := e.(directiveExport); ok {
res = e.val
return
}
err = fmt.Errorf("%v", e)
}
}()
for _, node := range nodeList {
// store the last expression value
v := EvalExpr(node, scope)
if v != nil {
res = v
}
}
// return the last statement value
return
}
// EvalExpr returns the value of the expression
func EvalExpr(node AstNode, scope *VariableScope) interface{} {
switch node := node.(type) {
case *NodeAssignOp:
return evalAssign(node, scope)
case *NodeUnaryOp:
return evalUnary(node, scope)
case *NodeBinaryOp:
return evalBinary(node, scope)
case *NodeVariable:
return evalVariable(node, scope)
case *NodeNumber:
return node.Value
case *NodeString:
return node.Value
case *NodeBool:
return node.Value
case *NodeList:
return evalList(node, scope)
case *NodeMap:
return evalMap(node, scope)
case *NodeVarIndex:
return evalVarIndex(node, scope)
case *NodeIf:
return evalIfStmt(node, scope)
case *NodeFuncCallOp:
return evalFuncCall(node, scope)
case *NodeWhile:
return evalWhileStmt(node, scope)
case *NodeFuncDef:
evalFuncDef(node, scope)
}
return nil
}
// return the variable value from scope
func evalVariable(expr *NodeVariable, scope *VariableScope) interface{} {
if val, ok := scope.Get(expr.Value); ok {
return val
}
return nil
}
// init the map value
func evalMap(expr *NodeMap, scope *VariableScope) interface{} {
dict := make(ValueMap)
for idx, val := range expr.Map {
dict[Interface2String(EvalExpr(idx, scope))] = EvalExpr(val, scope)
}
return dict
}
// init the list value
func evalList(expr *NodeList, scope *VariableScope) interface{} {
list := make(ValueList, 0)
for _, sub := range expr.List {
list = append(list, EvalExpr(sub, scope))
}
return list
}
// assign and return a value
func evalAssign(expr *NodeAssignOp, scope *VariableScope) interface{} {
name := expr.Var.Value
exprVal := EvalExpr(expr.Expr, scope)
initVal, ok := scope.Get(name) // original value
// initial value
if !ok {
initVal = 0
// string concat
if expr.Op == SymbolAssignAdd && !IsNumber(Interface2String(exprVal)) {
initVal = ""
}
}
switch expr.Op {
case SymbolAssign:
scope.Set(name, exprVal)
case SymbolAssignAdd:
scope.Set(name, calcMath(SymbolAdd, initVal, exprVal))
case SymbolAssignSub:
scope.Set(name, calcMath(SymbolSub, initVal, exprVal))
case SymbolAssignMul:
scope.Set(name, calcMath(SymbolMul, initVal, exprVal))
case SymbolAssignDiv:
scope.Set(name, calcMath(SymbolDiv, initVal, exprVal))
case SymbolAssignMod:
scope.Set(name, calcMath(SymbolMod, initVal, exprVal))
}
if val, ok := scope.Get(name); ok {
return val
}
return nil
}
// evalUnary unary operation
func evalUnary(expr *NodeUnaryOp, scope *VariableScope) interface{} {
right := EvalExpr(expr.Right, scope)
switch expr.Op {
case SymbolLogicNot:
return !IsTrue(right)
case SymbolNot:
rightNumber, _ := ParseNumber(Interface2String(right))
return ^int(rightNumber)
case SymbolSub:
return -Interface2Float64(right)
}
return nil
}
// evalBinary binary operator
func evalBinary(expr *NodeBinaryOp, scope *VariableScope) interface{} {
left := EvalExpr(expr.Left, scope)
right := EvalExpr(expr.Right, scope)
switch expr.Op {
case SymbolAdd, SymbolSub, SymbolMul, SymbolDiv, SymbolMod, SymbolPow,
SymbolAnd, SymbolOr, SymbolXor, SymbolSHR, SymbolSHL:
return calcMath(expr.Op, left, right)
case SymbolLogicAnd:
return IsTrue(left) && IsTrue(right)
case SymbolLogicOr:
return IsTrue(left) || IsTrue(right)
case SymbolEQL, SymbolNEQ, SymbolGTR, SymbolGTE, SymbolLSS, SymbolLTE:
return calcComparison(expr.Op, left, right)
case SymbolIn:
return calcIn(left, right)
}
return nil
}
// report whether element is within a value
func calcIn(elem interface{}, set interface{}) bool {
leftString := Interface2String(elem)
switch set := set.(type) {
case ValueList:
for _, v := range set {
if leftString == Interface2String(v) {
return true
}
}
case ValueMap:
for _, v := range set {
if leftString == Interface2String(v) {
return true
}
}
case string:
return strings.Contains(set, leftString)
case int, float64:
return strings.Contains(Interface2String(set), leftString)
}
return false
}
// mathematical calculation
func calcMath(symbol Symbol, left interface{}, right interface{}) interface{} {
bigLeft := new(big.Float).SetFloat64(Interface2Float64(left))
bigRight := new(big.Float).SetFloat64(Interface2Float64(right))
leftString := Interface2String(left)
rightString := Interface2String(right)
leftNumber, leftErr := ParseNumber(leftString)
rightNumber, rightErr := ParseNumber(rightString)
isNumberExpr := leftErr == nil && rightErr == nil && IsNumber(leftString) && IsNumber(rightString)
var bigNumber *big.Float
switch symbol {
case SymbolAdd:
if !isNumberExpr {
// concat string
return Interface2String(left) + Interface2String(right)
}
// number addition
bigNumber = new(big.Float).Add(bigLeft, bigRight)
case SymbolSub:
bigNumber = new(big.Float).Sub(bigLeft, bigRight)
case SymbolMul:
bigNumber = new(big.Float).Mul(bigLeft, bigRight)
case SymbolDiv:
if bigRight == new(big.Float).SetFloat64(0) {
panic("RUNTIME ERROR: division by zero")
}
bigNumber = new(big.Float).Quo(bigLeft, bigRight)
case SymbolMod:
return int(leftNumber) % int(rightNumber)
case SymbolPow:
return math.Pow(leftNumber, rightNumber)
case SymbolAnd:
return int(leftNumber) & int(rightNumber)
case SymbolOr:
return int(leftNumber) | int(rightNumber)
case SymbolXor:
return int(leftNumber) ^ int(rightNumber)
case SymbolSHR:
return int(leftNumber) >> int(rightNumber)
case SymbolSHL:
return int(leftNumber) << int(rightNumber)
}
if bigNumber != nil {
res, _ := strconv.ParseFloat(bigNumber.String(), 64)
return res
} else if isNumberExpr {
return 0
}
return ""
}
// compare two value
func calcComparison(symbol Symbol, left interface{}, right interface{}) bool {
leftString := Interface2String(left)
rightString := Interface2String(right)
leftNumber, leftErr := ParseNumber(leftString)
rightNumber, rightErr := ParseNumber(rightString)
isNumberExpr := leftErr == nil && rightErr == nil && IsNumber(leftString) && IsNumber(rightString)
switch symbol {
case SymbolEQL:
if isNumberExpr {
return leftNumber == rightNumber
}
return leftString == rightString
case SymbolNEQ:
if isNumberExpr {
return leftNumber != rightNumber
}
return leftString != rightString
case SymbolGTR:
if isNumberExpr {
return leftNumber > rightNumber
}
return leftString > rightString
case SymbolGTE:
if isNumberExpr {
return leftNumber >= rightNumber
}
return leftString >= rightString
case SymbolLSS:
if isNumberExpr {
return leftNumber < rightNumber
}
return leftString < rightString
case SymbolLTE:
if isNumberExpr {
return leftNumber <= rightNumber
}
return leftString <= rightString
}
return false
}
// function call
func evalFuncCall(fnc *NodeFuncCallOp, scope *VariableScope) interface{} {
// custom function
if fnd, ok := scope.Get("_custom_func_" + fnc.Name.Value); ok {
if fn, ok := fnd.(*NodeFuncDef); ok {
return execCustomFunc(fnc, fn, scope)
}
}
// builtin function
localScope := NewScopeTable("builtin_func_"+fnc.Name.Value, scope.scopeLevel+1, scope)
if bfn, ok := builtinMap[fnc.Name.Value]; ok {
return bfn(fnc, localScope)
}
panic(fmt.Sprintf("call to undefined function %s()", fnc.Name.Value))
}
// register function declare
func evalFuncDef(fnd *NodeFuncDef, scope *VariableScope) {
scope.Set("_custom_func_"+fnd.Name.Value, fnd)
}
// exec custom function
func execCustomFunc(fnc *NodeFuncCallOp, fnd *NodeFuncDef, scope *VariableScope) (val interface{}) {
if len(fnc.Params) != len(fnd.Params) {
panic(fmt.Sprintf(
"%s() expects at least %d parameters, %d given",
fnc.Name.Value, len(fnd.Params), len(fnc.Params)),
)
}
localScope := NewScopeTable("custom_func_"+fnc.Name.Value, scope.scopeLevel+1, nil)
for i, p := range fnc.Params {
localScope.Set(fnd.Params[i].Name.Value, EvalExpr(p, scope))
}
// before return, recover `return` statement
defer func() {
if e := recover(); e != nil {
if e, ok := e.(directiveReturn); ok {
val = e.val
return
}
panic(e)
}
}()
// eval body statements
val = evalStmts(fnd.Body, localScope, true)
return
}
// return the index value
func evalVarIndex(vi *NodeVarIndex, scope *VariableScope) interface{} {
varVal := EvalExpr(vi.Var, scope)
switch varVal := varVal.(type) {
case string:
idx := int(EvalExpr(vi.Index, scope).(float64))
r := []rune(varVal)
if len(r) > idx {
return string(r[idx])
}
panic(fmt.Sprintf("RUNTIME ERROR: undefined offset %d", idx))
case float64:
idx := int(EvalExpr(vi.Index, scope).(float64))
r := strconv.FormatFloat(varVal, 'f', -1, 64)
if len(r) > idx {
return r[idx]
}
panic(fmt.Sprintf("RUNTIME ERROR: undefined offset %d", idx))
case int:
idx := int(EvalExpr(vi.Index, scope).(float64))
r := strconv.Itoa(varVal)
if len(r) > idx {
return r[idx]
}
panic(fmt.Sprintf("RUNTIME ERROR: undefined offset %d", idx))
case ValueList:
idx := int(EvalExpr(vi.Index, scope).(float64))
r := varVal
if len(r) > idx {
return r[idx]
}
panic(fmt.Sprintf("RUNTIME ERROR: undefined offset %d", idx))
case ValueMap:
idx := Interface2String(EvalExpr(vi.Index, scope))
r := varVal
if val, ok := r[idx]; ok {
return val
}
panic(fmt.Sprintf("RUNTIME ERROR: undefined offset %s", idx))
}
return nil
}
// if-else statement
func evalIfStmt(expr *NodeIf, scope *VariableScope) (val interface{}) {
if expr.Expr == nil {
return
}
if IsTrue(EvalExpr(expr.Expr, scope)) {
val = evalStmts(expr.Body, scope, false)
} else if expr.ElseIf != nil {
return evalIfStmt(expr.ElseIf, scope)
} else {
val = evalStmts(expr.Else, scope, false)
}
return
}
// while statement
func evalWhileStmt(expr *NodeWhile, scope *VariableScope) (val interface{}) {
if expr.Expr == nil {
return
}
for IsTrue(EvalExpr(expr.Expr, scope)) {
var brk Symbol
brk, val = func() (brk Symbol, val interface{}) {
defer func() {
if e := recover(); e != nil {
switch e.(type) {
case directiveContinue:
brk = SymbolContinue
case directiveBreak:
brk = SymbolBreak
default:
panic(e)
}
}
}()
val = evalStmts(expr.Body, scope, false)
return
}()
if brk == SymbolContinue {
continue
} else if brk == SymbolBreak {
break
}
}
return
}
// eval statements, with return/break/continue
// `isf` means function not support break/continue
func evalStmts(nodes []AstNode, scope *VariableScope, isf bool) (val interface{}) {
for _, node := range nodes {
val = EvalExpr(node, scope)
switch node := node.(type) {
case *NodeReturn: // return
var ret = directiveReturn{
hasVal: true,
}
var tuples []interface{}
for _, a := range node.Tuples {
tuples = append(tuples, EvalExpr(a, scope))
}
if len(tuples) == 0 {
ret.hasVal = false
} else if len(tuples) == 1 {
ret.val = tuples[0]
} else {
ret.val = tuples
}
panic(ret)
case *NodeBreak: // break
if !isf {
panic(directiveBreak{})
}
case *NodeContinue: // continue
if !isf {
panic(directiveContinue{})
}
}
}
return
}