-
Notifications
You must be signed in to change notification settings - Fork 4
/
eval.go
1522 lines (1338 loc) · 36.8 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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package eval
import (
"fmt"
"magpie/ast"
"math"
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
var importMap map[string]*Scope = map[string]*Scope{}
func panicToError(p interface{}, node ast.Node) *Error {
errLine := node.Pos().Sline()
switch e := p.(type) {
case *Error: //Error Object defined in errors.go file
return e
case error, string, fmt.Stringer:
return newError(errLine, "%s", e)
default:
return newError(errLine, "unknown error:%s", e)
}
}
func Eval(node ast.Node, scope *Scope) (val Object) {
defer func() {
if r := recover(); r != nil {
val = panicToError(r, node)
}
}()
//fmt.Printf("node.Type=%T, node=<%s>, start=%d, end=%d\n", node, node.String(), node.Pos().Line, node.End().Line) //debugging
switch node := node.(type) {
case *ast.Program:
return evalProgram(node, scope)
case *ast.ImportStatement:
return evalImportStatement(node, scope)
case *ast.BlockStatement:
return evalBlockStatement(node, scope)
case *ast.ExpressionStatement:
return Eval(node.Expression, scope)
case *ast.NumberLiteral:
return evalNumber(node, scope)
case *ast.StringLiteral:
return evalStringLiteral(node, scope)
case *ast.FunctionLiteral:
return evalFunctionLiteral(node, scope)
case *ast.StructStatement:
return evalStructStatement(node, scope)
case *ast.SwitchExpression:
return evalSwitchExpression(node, scope)
case *ast.CallExpression:
return evalCallExpression(node, scope)
case *ast.MethodCallExpression:
return evalMethodCallExpression(node, scope)
case *ast.PrefixExpression:
right := Eval(node.Right, scope)
if isError(right) {
return right
}
return evalPrefixExpression(node, right, scope)
case *ast.InfixExpression:
left := Eval(node.Left, scope)
if isError(left) {
return left
}
right := Eval(node.Right, scope)
if isError(right) {
return right
}
return evalInfixExpression(node, left, right, scope)
case *ast.PostfixExpression:
left := Eval(node.Left, scope)
if left.Type() == ERROR_OBJ {
return left
}
return evalPostfixExpression(node, left, scope)
case *ast.BooleanLiteral:
return nativeBoolToBooleanObject(node.Value)
case *ast.NilLiteral:
return NIL
case *ast.ArrayLiteral:
members := evalExpressions(node.Members, scope)
if len(members) == 1 && isError(members[0]) {
return members[0]
}
return &Array{Members: members}
case *ast.IndexExpression:
left := Eval(node.Left, scope)
if isError(left) {
return left
}
index := Eval(node.Index, scope)
if isError(index) {
return index
}
return evalIndexExpression(node, left, index)
case *ast.HashLiteral:
return evalHashLiteral(node, scope)
case *ast.TupleLiteral:
members := evalExpressions(node.Members, scope)
if len(members) == 1 && isError(members[0]) {
return members[0]
}
return &Tuple{Members: members}
case *ast.LetStatement:
return evalLetStatement(node, scope)
case *ast.ReturnStatement:
return evalReturnStatement(node, scope)
case *ast.Identifier:
return evalIdentifier(node, scope)
case *ast.IfExpression:
return evalIfExpression(node, scope)
case *ast.AssignExpression:
return evalAssignExpression(node, scope)
case *ast.BreakExpression:
return BREAK
case *ast.ContinueExpression:
return CONTINUE
case *ast.FallthroughExpression:
return FALLTHROUGH
case *ast.CForLoop:
return evalCForLoopExpression(node, scope)
case *ast.ForEverLoop:
return evalForEverLoopExpression(node, scope)
case *ast.ForEachArrayLoop:
return evalForEachArrayExpression(node, scope)
case *ast.ForEachMapLoop:
return evalForEachMapExpression(node, scope)
case *ast.DoLoop:
return evalDoLoopExpression(node, scope)
case *ast.WhileLoop:
return evalWhileLoopExpression(node, scope)
case *ast.RegExLiteral:
return evalRegExLiteral(node, scope)
}
return nil
}
func evalProgram(program *ast.Program, scope *Scope) (results Object) {
if len(program.Imports) > 0 {
results = loadImports(program.Imports, scope)
if results.Type() == ERROR_OBJ {
return
}
}
for _, stmt := range program.Statements {
results = Eval(stmt, scope)
if returnValue, ok := results.(*ReturnValue); ok {
return returnValue.Value
}
if errObj, ok := results.(*Error); ok {
return errObj
}
}
if results == nil {
return NIL
}
return results
}
func loadImports(imports map[string]*ast.ImportStatement, scope *Scope) Object {
for _, p := range imports {
v := evalImportStatement(p, scope)
if v.Type() == ERROR_OBJ {
return newError(p.Pos().Sline(), ERR_IMPORT, p.ImportPath)
}
}
return NIL
}
func evalImportStatement(i *ast.ImportStatement, scope *Scope) Object {
if importedScope, ok := importMap[i.ImportPath]; ok {
importedScope.GetAllExported(scope)
return NIL
}
newScope := NewScope(nil, scope.Writer)
v := evalProgram(i.Program, newScope)
if v.Type() == ERROR_OBJ {
return newError(i.Pos().Sline(), ERR_IMPORT, i.ImportPath)
}
importMap[i.ImportPath] = newScope
newScope.GetAllExported(scope)
return NIL
}
func evalBlockStatement(block *ast.BlockStatement, scope *Scope) Object {
var result Object
for _, statement := range block.Statements {
result = Eval(statement, scope)
if result != nil {
rt := result.Type()
if rt == RETURN_VALUE_OBJ || rt == ERROR_OBJ {
return result
}
}
if _, ok := result.(*Break); ok {
return result
}
if _, ok := result.(*Continue); ok {
return result
}
if _, ok := result.(*Fallthrough); ok {
return result
}
}
return result
}
func evalNumber(n *ast.NumberLiteral, scope *Scope) Object {
return NewNumber(n.Value)
}
func evalStringLiteral(s *ast.StringLiteral, scope *Scope) Object {
return NewString(s.Value)
}
func evalFunctionLiteral(fl *ast.FunctionLiteral, scope *Scope) Object {
fn := &Function{Literal: fl, Scope: scope}
if fl.Name != "" {
scope.Set(fl.Name, fn)
}
return fn
}
func evalStructStatement(structStmt *ast.StructStatement, scope *Scope) Object {
scope.SetStruct(structStmt) //save to scope
return NIL
}
func evalSwitchExpression(switchExpr *ast.SwitchExpression, scope *Scope) Object {
obj := Eval(switchExpr.Expr, scope)
var defaultBlock *ast.BlockStatement
match := false
through := false
loopCases:
for _, choice := range switchExpr.Cases { //iterate through all cases
if choice.Default {
defaultBlock = choice.Block
continue
}
// only go through the evaluation of the cases when not in fallthrough mode.
if !through {
for _, expr := range choice.Exprs {
out := Eval(expr, scope)
// literal match?
if obj.Type() == out.Type() && (obj.Inspect() == out.Inspect()) {
match = true
break
}
// regexp-match?
if out.Type() == REGEX_OBJ {
matched := out.(*RegEx).RegExp.MatchString(obj.Inspect())
if matched {
match = true
break
}
}
}
}
if match || through {
through = false
result := evalBlockStatement(choice.Block, scope)
if _, ok := result.(*Fallthrough); ok {
through = true
continue loopCases
}
return NIL
}
}
// handle default
if !match && defaultBlock != nil {
return evalBlockStatement(defaultBlock, scope)
}
return NIL
}
func createStructObj(structStmt *ast.StructStatement, scope *Scope) *Struct {
structObj := &Struct{
Scope: NewScope(scope, nil),
}
Eval(structStmt.Block, structObj.Scope)
scope.Set(structStmt.Name, structObj)
return structObj
}
func evalPrefixExpression(node *ast.PrefixExpression, right Object, scope *Scope) Object {
switch node.Operator {
case "+":
return evalPlusPrefixOperatorExpression(node, right, scope)
case "-":
return evalMinusPrefixOperatorExpression(node, right, scope)
case "!":
return evalBangOperatorExpression(node, right, scope)
default:
return newError(node.Pos().Sline(), ERR_PREFIXOP, node.Operator, right.Type())
}
}
func evalPlusPrefixOperatorExpression(node *ast.PrefixExpression, right Object, scope *Scope) Object {
if right.Type() != NUMBER_OBJ {
return newError(node.Pos().Sline(), ERR_PREFIXOP, node.Operator, right.Type())
}
return right
}
func evalMinusPrefixOperatorExpression(node *ast.PrefixExpression, right Object, scope *Scope) Object {
if right.Type() != NUMBER_OBJ {
return newError(node.Pos().Sline(), ERR_PREFIXOP, node.Operator, right.Type())
}
value := right.(*Number).Value
return NewNumber(-value)
}
func evalBangOperatorExpression(node *ast.PrefixExpression, right Object, scope *Scope) Object {
return nativeBoolToBooleanObject(!IsTrue(right))
}
func evalInfixExpression(node *ast.InfixExpression, left, right Object, scope *Scope) Object {
if left.Type() == GO_OBJ {
left = goValueToObject(left.(*GoObject).obj)
}
if right.Type() == GO_OBJ {
right = goValueToObject(right.(*GoObject).obj)
}
operator := node.Operator
switch {
case operator == "=~", operator == "!~":
if right.Type() != REGEX_OBJ {
return newError(node.Pos().Sline(), ERR_NOTREGEXP, right.Type())
}
matched := right.(*RegEx).RegExp.MatchString(left.Inspect())
if matched {
if operator == "=~" {
return TRUE
}
return FALSE
} else {
if operator == "=~" {
return FALSE
}
return TRUE
}
case operator == "&&":
leftCond := objectToNativeBoolean(left)
if !leftCond {
return FALSE
}
rightCond := objectToNativeBoolean(right)
return nativeBoolToBooleanObject(leftCond && rightCond)
case operator == "||":
leftCond := objectToNativeBoolean(left)
if leftCond {
return TRUE
}
rightCond := objectToNativeBoolean(right)
return nativeBoolToBooleanObject(leftCond || rightCond)
case left.Type() == NUMBER_OBJ && right.Type() == NUMBER_OBJ:
return evalNumberInfixExpression(node, left, right, scope)
case left.Type() == STRING_OBJ && right.Type() == STRING_OBJ:
return evalStringInfixExpression(node, left, right, scope)
case operator == "==":
return nativeBoolToBooleanObject(left == right)
case operator == "!=":
return nativeBoolToBooleanObject(left != right)
default:
return newError(node.Pos().Sline(), ERR_INFIXOP, left.Type(), node.Operator, right.Type())
}
}
func evalStringInfixExpression(node *ast.InfixExpression, left, right Object, scope *Scope) Object {
leftVal := left.(*String).String
rightVal := right.(*String).String
switch node.Operator {
case "+":
return NewString(leftVal + rightVal)
case "<":
return nativeBoolToBooleanObject(leftVal < rightVal)
case "<=":
return nativeBoolToBooleanObject(leftVal <= rightVal)
case ">":
return nativeBoolToBooleanObject(leftVal > rightVal)
case ">=":
return nativeBoolToBooleanObject(leftVal >= rightVal)
case "==":
return nativeBoolToBooleanObject(leftVal == rightVal)
case "!=":
return nativeBoolToBooleanObject(leftVal != rightVal)
default:
return newError(node.Pos().Sline(), ERR_INFIXOP, left.Type(), node.Operator, right.Type())
}
}
func evalNumberInfixExpression(node *ast.InfixExpression, left, right Object, scope *Scope) Object {
leftVal := left.(*Number).Value
rightVal := right.(*Number).Value
switch node.Operator {
case "+":
return &Number{Value: leftVal + rightVal}
case "-":
return &Number{Value: leftVal - rightVal}
case "*":
return &Number{Value: leftVal * rightVal}
case "/":
if rightVal == 0 {
return newError(node.Pos().Sline(), ERR_DIVIDEBYZERO)
}
return &Number{Value: leftVal / rightVal}
case "%":
v := math.Mod(leftVal, rightVal)
return &Number{Value: v}
case "**":
return &Number{Value: math.Pow(leftVal, rightVal)}
case "<":
return nativeBoolToBooleanObject(leftVal < rightVal)
case "<=":
return nativeBoolToBooleanObject(leftVal <= rightVal)
case ">":
return nativeBoolToBooleanObject(leftVal > rightVal)
case ">=":
return nativeBoolToBooleanObject(leftVal >= rightVal)
case "==":
return nativeBoolToBooleanObject(leftVal == rightVal)
case "!=":
return nativeBoolToBooleanObject(leftVal != rightVal)
default:
return newError(node.Pos().Sline(), ERR_INFIXOP, left.Type(), node.Operator, right.Type())
}
}
func evalPostfixExpression(node *ast.PostfixExpression, left Object, scope *Scope) Object {
switch node.Operator {
case "++":
return evalIncrementPostfixExpression(node, left, scope)
case "--":
return evalDecrementPostfixExpression(node, left, scope)
default:
return newError(node.Pos().Sline(), ERR_POSTFIXOP, node.Operator, left.Type())
}
}
func evalIncrementPostfixExpression(node *ast.PostfixExpression, left Object, scope *Scope) Object {
switch left.Type() {
case NUMBER_OBJ:
leftObj := left.(*Number)
returnVal := NewNumber(leftObj.Value)
scope.Set(node.Left.String(), NewNumber(leftObj.Value+1))
return returnVal
default:
return newError(node.Pos().Sline(), ERR_POSTFIXOP, node.Operator, left.Type())
}
}
func evalDecrementPostfixExpression(node *ast.PostfixExpression, left Object, scope *Scope) Object {
switch left.Type() {
case NUMBER_OBJ:
leftObj := left.(*Number)
returnVal := NewNumber(leftObj.Value)
scope.Set(node.Left.String(), NewNumber(leftObj.Value-1))
return returnVal
default:
return newError(node.Pos().Sline(), ERR_POSTFIXOP, node.Operator, left.Type())
}
}
func evalLetStatement(l *ast.LetStatement, scope *Scope) (val Object) {
values := []Object{}
valuesLen := 0
for _, value := range l.Values {
val := Eval(value, scope)
if val.Type() == TUPLE_OBJ {
tupleObj := val.(*Tuple)
if tupleObj.IsMulti {
valuesLen += len(tupleObj.Members)
values = append(values, tupleObj.Members...)
} else {
valuesLen += 1
values = append(values, tupleObj)
}
} else {
valuesLen += 1
values = append(values, val)
}
}
for idx, item := range l.Names {
if idx >= valuesLen { //There are more Names than Values
if item.Token.Literal != "_" {
val = NIL
scope.Set(item.String(), val)
}
} else {
if item.Token.Literal == "_" { // _: placeholder
continue
}
val = values[idx]
if val.Type() != ERROR_OBJ {
scope.Set(item.String(), val)
} else {
return
}
}
}
return
}
func evalReturnStatement(r *ast.ReturnStatement, scope *Scope) Object {
if r.ReturnValue == nil { //no return value, we default return `NIL` object
return &ReturnValue{Value: NIL, Values: []Object{NIL}}
}
ret := &ReturnValue{}
for _, value := range r.ReturnValues {
ret.Values = append(ret.Values, Eval(value, scope))
}
// for old campatibility
ret.Value = ret.Values[0]
return ret
}
func evalIdentifier(node *ast.Identifier, scope *Scope) Object {
//Get from global scope first
if obj, ok := GetGlobalObj(node.Value); ok {
return obj
}
if val, ok := scope.Get(node.Value); ok {
return val
}
if builtin, ok := builtins[node.Value]; ok {
return builtin
}
return newError(node.Pos().Sline(), ERR_UNKNOWNIDENT, node.Value)
}
func evalIfExpression(ie *ast.IfExpression, scope *Scope) Object {
//eval "if/else-if" part
for _, c := range ie.Conditions {
condition := Eval(c.Cond, scope)
if condition.Type() == ERROR_OBJ {
return condition
}
if IsTrue(condition) {
return evalBlockStatement(c.Body, scope)
}
}
//eval "else" part
if ie.Alternative != nil {
return evalBlockStatement(ie.Alternative, scope)
}
return NIL
}
func evalExpressions(exps []ast.Expression, scope *Scope) []Object {
var result []Object
for _, e := range exps {
evaluated := Eval(e, scope)
if isError(evaluated) {
return []Object{evaluated}
}
result = append(result, evaluated)
}
return result
}
func evalIndexExpression(node *ast.IndexExpression, left, index Object) Object {
switch {
case left.Type() == STRING_OBJ:
return evalStringIndex(node.Pos().Sline(), left, index)
case left.Type() == ARRAY_OBJ:
return evalArrayIndexExpression(node.Pos().Sline(), left, index)
case left.Type() == HASH_OBJ:
return evalHashIndexExpression(node.Pos().Sline(), left, index)
case left.Type() == TUPLE_OBJ:
return evalTupleIndexExpression(node.Pos().Sline(), left, index)
default:
return newError(node.Pos().Sline(), ERR_NOINDEXABLE, left.Type())
}
}
func evalStringIndex(line string, left, index Object) Object {
str := left.(*String)
idx := int64(index.(*Number).Value)
max := int64(utf8.RuneCountInString(str.String)) - 1
if idx < 0 || idx > max {
return newError(line, ERR_INDEX, idx)
}
return NewString(string([]rune(str.String)[idx])) //support utf8,not very efficient
}
func evalArrayIndexExpression(line string, array, index Object) Object {
arrayObject := array.(*Array)
idx := int64(index.(*Number).Value)
max := int64(len(arrayObject.Members) - 1)
if idx < 0 || idx > max {
return newError(line, ERR_INDEX, idx)
}
return arrayObject.Members[idx]
}
//Almost same as evalArrayIndexExpression
func evalTupleIndexExpression(line string, tuple, index Object) Object {
tupleObject := tuple.(*Tuple)
idx := int64(index.(*Number).Value)
max := int64(len(tupleObject.Members) - 1)
if idx < 0 || idx > max {
return newError(line, ERR_INDEX, idx)
}
return tupleObject.Members[idx]
}
func evalHashIndexExpression(line string, hash, index Object) Object {
hashObject := hash.(*Hash)
key, ok := index.(Hashable)
if !ok {
return newError(line, ERR_KEY, index.Type())
}
pair, ok := hashObject.Pairs[key.HashKey()]
if !ok {
return NIL
}
return pair.Value
}
func evalHashLiteral(node *ast.HashLiteral, scope *Scope) Object {
pairs := make(map[HashKey]HashPair)
for keyNode, valueNode := range node.Pairs {
key := Eval(keyNode, scope)
if isError(key) {
return key
}
hashKey, ok := key.(Hashable)
if !ok {
return newError(node.Pos().Sline(), ERR_KEY, key.Type())
}
value := Eval(valueNode, scope)
if isError(value) {
return value
}
hashed := hashKey.HashKey()
pairs[hashed] = HashPair{Key: key, Value: value}
}
return &Hash{Pairs: pairs}
}
func evalMethodCallExpression(call *ast.MethodCallExpression, scope *Scope) Object {
//First check if is a stanard library object
str := call.Object.String()
if obj, ok := GetGlobalObj(str); ok {
switch o := call.Call.(type) {
case *ast.Identifier: //e.g. os.xxx
if i, ok := GetGlobalObj(str + "." + o.String()); ok {
return i
}
case *ast.CallExpression: //e.g. method call like 'fmt.Printf()'
if method, ok := call.Call.(*ast.CallExpression); ok {
args := evalExpressions(method.Arguments, scope)
if len(args) == 1 && isError(args[0]) {
return args[0]
}
if obj.Type() == HASH_OBJ { // It's a GoFuncObject
foundMethod := false
hash := obj.(*Hash)
for _, pair := range hash.Pairs {
funcName := pair.Key.(*String).String
if funcName == o.Function.String() {
foundMethod = true
goFuncObj := pair.Value.(*GoFuncObject)
return goFuncObj.CallMethod(call.Call.Pos().Sline(), scope, o.Function.String(), args...)
}
}
if !foundMethod {
return newError(call.Call.Pos().Sline(), ERR_NOMETHODEX, str, o.Function.String(), str, strings.Title(o.Function.String()))
}
} else {
return obj.CallMethod(call.Call.Pos().Sline(), scope, o.Function.String(), args...)
}
}
}
} else {
//process variable registed using 'RegisterGoVars' method
if obj, ok := GetGlobalObj(str + "." + call.Call.String()); ok {
return obj
}
}
obj := Eval(call.Object, scope)
if obj.Type() == ERROR_OBJ {
return obj
}
switch m := obj.(type) {
case *Struct:
switch o := call.Call.(type) {
case *ast.Identifier:
if i, ok := m.Scope.Get(call.Call.String()); ok {
return i
}
case *ast.CallExpression:
funcName := o.Function.String()
if !unicode.IsUpper(rune(funcName[0])) && str != "self" {
return newError(call.Call.Pos().Sline(), ERR_NAMENOTEXPORTED, call.Object.String(), funcName)
}
args := evalExpressions(o.Arguments, scope)
if len(args) == 1 && isError(args[0]) {
return args[0]
}
r := obj.CallMethod(call.Call.Pos().Sline(), scope, funcName, args...)
return r
case *ast.IndexExpression: //e.g. math.xxx[i] (assume 'math' is a struct)
//left := Eval(o.Left, m.Scope)
//index := Eval(o.Index, m.Scope)
//return evalIndexExpression(o, left, index)
return Eval(o, m.Scope)
}
default:
if method, ok := call.Call.(*ast.CallExpression); ok {
args := evalExpressions(method.Arguments, scope)
if len(args) == 1 && isError(args[0]) {
return args[0]
}
return obj.CallMethod(call.Call.Pos().Sline(), scope, method.Function.String(), args...)
}
}
return newError(call.Call.Pos().Sline(), ERR_NOMETHOD, call.String(), obj.Type())
}
func evalAssignExpression(a *ast.AssignExpression, scope *Scope) Object {
val := Eval(a.Value, scope)
if val.Type() == ERROR_OBJ {
return val
}
if strings.Contains(a.Name.String(), ".") {
switch o := a.Name.(type) {
case *ast.MethodCallExpression: //structObj.x = 10
obj := Eval(o.Object, scope)
if obj.Type() == ERROR_OBJ {
return obj
}
switch m := obj.(type) {
case *Struct:
switch c := o.Call.(type) {
case *ast.Identifier:
m.Scope.Set(c.Value, val)
return val
case *ast.IndexExpression: //structObj.xxx[idx]
var left Object
var ok bool
name := c.Left.(*ast.Identifier).Value
if left, ok = m.Scope.Get(name); !ok {
return newError(a.Pos().Sline(), ERR_UNKNOWNIDENT, name)
}
b := &ast.AssignExpression{Token: a.Token, Name: c}
switch left.Type() {
case STRING_OBJ:
return evalStrAssignExpression(b, name, left, m.Scope, val)
case ARRAY_OBJ:
return evalArrayAssignExpression(b, name, left, m.Scope, val)
case TUPLE_OBJ:
return evalTupleAssignExpression(b, name, left, m.Scope, val)
case HASH_OBJ:
return evalHashAssignExpression(b, name, left, m.Scope, val)
}
default:
//error
}
}
}
}
var name string
switch nodeType := a.Name.(type) {
//a = 10
case *ast.Identifier:
name = nodeType.Value
//arr[idx] = "xxx", here `a.Name` = arr[idx]
case *ast.IndexExpression:
switch nodeType.Left.(type) {
case *ast.Identifier:
name = nodeType.Left.(*ast.Identifier).Value //here, name = arr
}
case *ast.MethodCallExpression:
name = nodeType.Object.String()
}
if a.Token.Literal == "=" {
switch nodeType := a.Name.(type) {
case *ast.Identifier: //e.g. a = "hello"
scope.Set(nodeType.Value, val)
return val
}
}
// Check if the variable exists or not
var left Object
var ok bool
if left, ok = scope.Get(name); !ok {
return newError(a.Pos().Sline(), ERR_UNKNOWNIDENT, name)
}
switch left.Type() {
case NUMBER_OBJ:
return evalNumAssignExpression(a, name, left, scope, val)
case STRING_OBJ:
return evalStrAssignExpression(a, name, left, scope, val)
case ARRAY_OBJ:
return evalArrayAssignExpression(a, name, left, scope, val)
case TUPLE_OBJ:
return evalTupleAssignExpression(a, name, left, scope, val)
case HASH_OBJ:
return evalHashAssignExpression(a, name, left, scope, val)
}
return newError(a.Pos().Sline(), ERR_INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
// num += num
// num -= num
// etc...
func evalNumAssignExpression(a *ast.AssignExpression, name string, left Object, scope *Scope, val Object) (ret Object) {
switch a.Token.Literal {
case "+=":
case "-=":
}
return newError(a.Pos().Sline(), ERR_INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
//str[idx] = item
//str += item
func evalStrAssignExpression(a *ast.AssignExpression, name string, left Object, scope *Scope, val Object) (ret Object) {
leftVal := left.(*String).String
switch a.Token.Literal {
case "=":
switch nodeType := a.Name.(type) {
case *ast.IndexExpression: //str[idx] = xxx
index := Eval(nodeType.Index, scope)
if index == NIL {
ret = NIL
return
}
idx := int64(index.(*Number).Value)
if idx < 0 || idx >= int64(len(leftVal)) {
return newError(a.Pos().Sline(), ERR_INDEX, idx)
}
ret = NewString(leftVal[:idx] + val.Inspect() + leftVal[idx+1:])
scope.Set(name, ret)
return
}
}
return newError(a.Pos().Sline(), ERR_INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
//array[idx] = item
//array += item
func evalArrayAssignExpression(a *ast.AssignExpression, name string, left Object, scope *Scope, val Object) (ret Object) {
leftVals := left.(*Array).Members
switch a.Token.Literal {
case "=":
switch nodeType := a.Name.(type) {
case *ast.IndexExpression: //arr[idx] = xxx
index := Eval(nodeType.Index, scope)
if index == NIL {
ret = NIL
return
}
idx := int64(index.(*Number).Value)
if idx < 0 {
return newError(a.Pos().Sline(), ERR_INDEX, idx)
}
if idx < int64(len(leftVals)) { //index is in range
leftVals[idx] = val
ret = &Array{Members: leftVals}
scope.Set(name, ret)
return
} else { //index is out of range, we auto-expand the array
for i := int64(len(leftVals)); i < idx; i++ {
leftVals = append(leftVals, NIL)
}
leftVals = append(leftVals, val)
ret = &Array{Members: leftVals}
scope.Set(name, ret)
return
}
}
return newError(a.Pos().Sline(), ERR_INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
return newError(a.Pos().Sline(), ERR_INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
//tuple element can not be assigned
func evalTupleAssignExpression(a *ast.AssignExpression, name string, left Object, scope *Scope, val Object) (ret Object) {
//Tuple is an immutable sequence of values
if a.Token.Literal == "=" { //tuple[idx] = item
str := fmt.Sprintf("%s[IDX]", TUPLE_OBJ)
return newError(a.Pos().Sline(), ERR_INFIXOP, str, a.Token.Literal, val.Type())
}
return newError(a.Pos().Sline(), ERR_INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
//hash[key] = value
func evalHashAssignExpression(a *ast.AssignExpression, name string, left Object, scope *Scope, val Object) (ret Object) {
leftHash := left.(*Hash)
switch a.Token.Literal {
case "=":
switch nodeType := a.Name.(type) {
case *ast.IndexExpression: //hashObj[key] = val
key := Eval(nodeType.Index, scope)
leftHash.push(a.Pos().Sline(), key, val)
return leftHash
case *ast.Identifier: //hashObj.key = val
key := strings.Split(a.Name.String(), ".")[1]
keyObj := NewString(key)
leftHash.push(a.Pos().Sline(), keyObj, val)
return leftHash
}
return newError(a.Pos().Sline(), ERR_INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
return newError(a.Pos().Sline(), ERR_INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
//for (init; condition; updater) { block }
// returns the last expression value or NIL
func evalCForLoopExpression(fl *ast.CForLoop, scope *Scope) Object { //fl:For Loop
if fl.Init != nil {
init := Eval(fl.Init, scope)
if init.Type() == ERROR_OBJ {
return init
}