forked from haifenghuang/magpie
/
eval.go
5977 lines (5291 loc) · 154 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 (
"bytes"
"fmt"
"magpie/ast"
_ "magpie/lexer"
"magpie/message"
"magpie/token"
"math"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
)
var (
TRUE = &Boolean{Bool: true, Valid: true}
FALSE = &Boolean{Bool: false, Valid: true}
BREAK = &Break{}
CONTINUE = &Continue{}
NIL = &Nil{}
EMPTY = &Optional{Value: NIL}
// Built-in types which you can extend.
builtinTypes = []string{
"integer", // signed integer
"uinteger", // unsigned integer
"float",
"boolean",
"string",
"array",
"tuple",
"hash"}
)
var importScope *Scope
var importedCache map[string]Object
var mux sync.Mutex
//REPL with color support
var REPLColor bool
const ServiceHint = "* Running on %s (Press CTRL+C to quit)\n"
var Dbg *Debugger
var MsgHandler *message.MessageHandler
type Context struct {
N []ast.Node //N: node
S *Scope //S: Scope
}
func PanicToError(p interface{}, node ast.Node) error {
switch e := p.(type) {
case *Error: //Error Object defined in errors.go file
return fmt.Errorf("%s - Line:%s", e.Inspect(), node.Pos().Sline())
case error:
return fmt.Errorf("%s - Line:%s", e, node.Pos().Sline())
case string:
return fmt.Errorf("%s - Line:%s", e, node.Pos().Sline())
case fmt.Stringer:
return fmt.Errorf("%s - Line:%s", e.String(), node.Pos().Sline())
default:
return fmt.Errorf("unknown error type (%T) - Line:%s", e, node.Pos().Sline())
}
}
func Eval(node ast.Node, scope *Scope) (val Object) {
defer func() {
if r := recover(); r != nil {
err := PanicToError(r, node)
fmt.Fprintf(os.Stderr, "%s\n", err.Error())
//WHY return NIL? if we do not return 'NIL', we may get something like below:
// PANIC=runtime error: invalid memory address or nil pointer
val = NIL
}
}()
if Dbg != nil {
Dbg.SetNodeAndScope(node, scope)
if Dbg.CanStop() {
MsgHandler.SendMessage(message.Message{Type: message.EVAL_LINE, Body: Context{N: []ast.Node{node}, S: scope}})
}
}
//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.ExpressionStatement:
return Eval(node.Expression, scope)
case *ast.ImportStatement:
return evalImportStatement(node, scope)
case *ast.LetStatement:
return evalLetStatement(node, scope)
case *ast.ConstStatement:
return evalConstStatement(node, scope)
case *ast.ReturnStatement:
if Dbg != nil {
MsgHandler.SendMessage(message.Message{Type: message.RETURN, Body: Context{N: []ast.Node{node}, S: scope}})
}
return evalReturnStatement(node, scope)
case *ast.DeferStmt:
return evalDeferStatement(node, scope)
case *ast.FunctionStatement:
return evalFunctionStatement(node, scope)
case *ast.Boolean:
return nativeBoolToBooleanObject(node.Value)
case *ast.IntegerLiteral:
return evalIntegerLiteral(node)
case *ast.UIntegerLiteral:
return evalUIntegerLiteral(node)
case *ast.FloatLiteral:
return evalFloatLiteral(node)
case *ast.StringLiteral:
return evalStringLiteral(node)
case *ast.InterpolatedString:
return evalInterpolatedString(node, scope)
case *ast.Identifier:
return evalIdentifier(node, scope)
case *ast.ArrayLiteral:
return evalArrayLiteral(node, scope)
case *ast.TupleLiteral:
return evalTupleLiteral(node, scope)
case *ast.HashLiteral:
return evalHashLiteral(node, scope)
case *ast.StructLiteral:
return evalStructLiteral(node, scope)
case *ast.EnumLiteral:
return evalEnumLiteral(node, scope)
case *ast.RangeLiteral:
return evalRangeLiteral(node, scope)
case *ast.EnumStatement:
return evalEnumStatement(node, scope)
case *ast.FunctionLiteral:
return evalFunctionLiteral(node, scope)
case *ast.PrefixExpression:
return evalPrefixExpression(node, scope)
case *ast.InfixExpression:
left := Eval(node.Left, scope)
if left.Type() == ERROR_OBJ {
return left
}
right := Eval(node.Right, scope)
if right.Type() == ERROR_OBJ {
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(left, node, scope)
case *ast.IfExpression:
return evalIfExpression(node, scope)
case *ast.IfMacroStatement:
return evalIfMacroStatement(node, scope)
case *ast.UnlessExpression:
return evalUnlessExpression(node, scope)
case *ast.BlockStatement:
return evalBlockStatements(node.Statements, scope)
case *ast.CallExpression:
// if Dbg != nil {
// MsgHandler.SendMessage(message.Message{Type: message.CALL, Body: Context{N: []ast.Node{node}, S: scope}})
// }
return evalFunctionCall(node, scope)
case *ast.MethodCallExpression:
if Dbg != nil {
MsgHandler.SendMessage(message.Message{Type: message.METHOD_CALL, Body: Context{N: []ast.Node{node}, S: scope}})
}
return evalMethodCallExpression(node, scope)
case *ast.IndexExpression:
return evalIndexExpression(node, scope)
case *ast.GrepExpr:
return evalGrepExpression(node, scope)
case *ast.MapExpr:
return evalMapExpression(node, scope)
case *ast.CaseExpr:
return evalCaseExpression(node, scope)
case *ast.DoLoop:
return evalDoLoopExpression(node, scope)
case *ast.WhileLoop:
return evalWhileLoopExpression(node, scope)
case *ast.ForLoop:
return evalForLoopExpression(node, scope)
case *ast.ForEverLoop:
return evalForEverLoopExpression(node, scope)
case *ast.ForEachArrayLoop:
return evalForEachArrayExpression(node, scope)
case *ast.ForEachDotRange:
return evalForEachDotRangeExpression(node, scope)
case *ast.ForEachMapLoop:
return evalForEachMapExpression(node, scope)
case *ast.ListComprehension:
return evalListComprehension(node, scope)
case *ast.ListRangeComprehension:
return evalListRangeComprehension(node, scope)
case *ast.ListMapComprehension:
return evalListMapComprehension(node, scope)
case *ast.HashComprehension:
return evalHashComprehension(node, scope)
case *ast.HashRangeComprehension:
return evalHashRangeComprehension(node, scope)
case *ast.HashMapComprehension:
return evalHashMapComprehension(node, scope)
case *ast.BreakExpression:
return BREAK
case *ast.ContinueExpression:
return CONTINUE
case *ast.ThrowStmt:
return evalThrowStatement(node, scope)
case *ast.AssignExpression:
return evalAssignExpression(node, scope)
case *ast.RegExLiteral:
return evalRegExLiteral(node)
case *ast.TryStmt:
return evalTryStatement(node, scope)
case *ast.TernaryExpression:
return evalTernaryExpression(node, scope)
case *ast.SpawnStmt:
return evalSpawnStatement(node, scope)
case *ast.NilLiteral:
return NIL
case *ast.Pipe:
return evalPipeExpression(node, scope)
//Class related
case *ast.ClassStatement:
return evalClassStatement(node, scope)
case *ast.ClassLiteral:
return evalClassLiteral(node, scope)
case *ast.NewExpression:
return evalNewExpression(node, scope)
//using
case *ast.UsingStmt:
return evalUsingStatement(node, scope)
//command expression
case *ast.CmdExpression:
return evalCmdExpression(node, scope)
//linq query expression
case *ast.QueryExpr:
return evalLinqQueryExpression(node, scope)
//await expression
case *ast.AwaitExpr:
return evalAwaitExpression(node, scope)
//service statement
case *ast.ServiceStatement:
return evalServiceStatement(node, scope)
//date time object
case *ast.DateTimeExpr:
if node.Pattern == nil {
return &TimeObj{Tm: time.Now(), Valid: true}
}
is := evalInterpolatedString(node.Pattern, scope).(*InterpolatedString)
var err error
dt := &TimeObj{Valid: true}
dt.Tm, err = time.Parse(builtinDate_Normal, is.String.String)
if err != nil {
dt.Valid = false
}
return dt
//diamond: <$fobj>
case *ast.DiamondExpr:
return evalDiamondExpr(node, scope)
}
return nil
}
// Program Evaluation Entry Point Functions, and Helpers:
func evalProgram(program *ast.Program, scope *Scope) (results Object) {
if importedCache == nil {
importedCache = make(map[string]Object)
}
results = loadImports(program.Imports, scope)
if results.Type() == ERROR_OBJ {
return
}
for _, statement := range program.Statements {
results = Eval(statement, scope)
switch s := results.(type) {
case *ReturnValue:
return s.Value
case *Error:
return s
case *Throw:
//convert ThrowValue to Errors
return NewError(s.stmt.Pos().Sline(), THROWNOTHANDLED, s.value.Inspect())
}
}
if results == nil {
return NIL
}
return results
}
func loadImports(imports map[string]*ast.ImportStatement, scope *Scope) Object {
if importScope == nil {
importScope = NewScope(nil, scope.Writer)
}
for _, p := range imports {
v := Eval(p, scope)
if v.Type() == ERROR_OBJ {
return NewError(p.Pos().Sline(), IMPORTERROR, p.ImportPath)
}
}
return NIL
}
// Statements...
func evalImportStatement(i *ast.ImportStatement, scope *Scope) Object {
mux.Lock()
defer mux.Unlock()
// Check the cache
if cache, ok := importedCache[i.ImportPath]; ok {
return cache
}
imported := &ImportedObject{Name: i.ImportPath, Scope: NewScope(nil, scope.Writer)}
if _, ok := importScope.Get(i.ImportPath); !ok {
evalProgram(i.Program, imported.Scope)
importScope.Set(i.ImportPath, imported)
}
//store the evaluated result to cache
importedCache[i.ImportPath] = imported
return imported
}
func evalLetStatement(l *ast.LetStatement, scope *Scope) (val Object) {
if l.DestructingFlag {
v := Eval(l.Values[0], scope)
valType := v.Type()
switch valType {
case HASH_OBJ:
h := v.(*Hash)
for _, item := range l.Names {
if item.Token.Type == token.UNDERSCORE {
continue
}
found := false
for _, pair := range h.Pairs {
if item.String() == pair.Key.Inspect() {
val = pair.Value
scope.Set(item.String(), pair.Value)
found = true
}
}
if !found {
val = NIL
scope.Set(item.String(), val)
}
}
case ARRAY_OBJ:
arr := v.(*Array)
valuesLen := len(arr.Members)
for idx, item := range l.Names {
if idx >= valuesLen { //There are more Names than Values
if item.Token.Type != token.UNDERSCORE {
val = NIL
scope.Set(item.String(), val)
}
} else {
if item.Token.Type == token.UNDERSCORE {
continue
}
val = arr.Members[idx]
if val.Type() != ERROR_OBJ {
scope.Set(item.String(), val)
} else {
return
}
}
}
case TUPLE_OBJ:
tup := v.(*Tuple)
valuesLen := len(tup.Members)
for idx, item := range l.Names {
if idx >= valuesLen { //There are more Names than Values
if item.Token.Type != token.UNDERSCORE {
val = NIL
scope.Set(item.String(), val)
}
val = NIL
scope.Set(item.String(), val)
} else {
if item.Token.Type == token.UNDERSCORE {
continue
}
val = tup.Members[idx]
if val.Type() != ERROR_OBJ {
scope.Set(item.String(), val)
} else {
return
}
}
}
default:
return NewError(l.Pos().Sline(), GENERICERROR, "Only Array|Tuple|Hash is allowed!")
}
return
}
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)
for _, tupleItem := range tupleObj.Members {
values = append(values, tupleItem)
}
} 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.Type != token.UNDERSCORE {
val = NIL
scope.Set(item.String(), val)
}
} else {
if item.Token.Type == token.UNDERSCORE {
continue
}
val = values[idx]
if val.Type() != ERROR_OBJ {
scope.Set(item.String(), val)
} else {
return
}
}
}
return
}
func evalConstStatement(c *ast.ConstStatement, scope *Scope) Object {
for idx, name := range c.Name {
val := Eval(c.Value[idx], scope)
if val.Type() == ERROR_OBJ {
return val
}
scope.SetConst(name.Value, val)
}
return NIL
}
func evalNumAssignExpression(a *ast.AssignExpression, name string, left Object, scope *Scope, val Object) (ret Object) {
var leftVal float64
var rightVal float64
isInt := left.Type() == INTEGER_OBJ && val.Type() == INTEGER_OBJ
isUInt := left.Type() == UINTEGER_OBJ && val.Type() == UINTEGER_OBJ
if left.Type() == INTEGER_OBJ {
leftVal = float64(left.(*Integer).Int64)
} else if left.Type() == UINTEGER_OBJ {
leftVal = float64(left.(*UInteger).UInt64)
} else {
leftVal = left.(*Float).Float64
}
//Check `right`'s type
if val.Type() == INTEGER_OBJ {
rightVal = float64(val.(*Integer).Int64)
} else if val.Type() == UINTEGER_OBJ {
rightVal = float64(val.(*UInteger).UInt64)
} else {
rightVal = val.(*Float).Float64
}
var ok bool
switch a.Token.Literal {
case "+=":
result := leftVal + rightVal
if isInt { //only 'INTEGER + INTEGER'
ret, ok = scope.Reset(name, NewInteger(int64(result)))
if ok {
return
}
} else if isUInt { //only 'UINTEGER + UINTEGER'
ret, ok = scope.Reset(name, NewUInteger(uint64(result)))
if ok {
return
}
} else {
ret, ok = checkNumAssign(scope, name, left, val, result)
if ok {
return
}
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
case "-=":
result := leftVal - rightVal
if isInt {
ret, ok = scope.Reset(name, NewInteger(int64(result)))
if ok {
return
}
} else if isUInt {
ret, ok = scope.Reset(name, NewUInteger(uint64(result)))
if ok {
return
}
} else {
ret, ok = checkNumAssign(scope, name, left, val, result)
if ok {
return
}
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
case "*=":
result := leftVal * rightVal
if isInt {
ret, ok = scope.Reset(name, NewInteger(int64(result)))
if ok {
return
}
} else if isUInt {
ret, ok = scope.Reset(name, NewUInteger(uint64(result)))
if ok {
return
}
} else {
ret, ok = checkNumAssign(scope, name, left, val, result)
if ok {
return
}
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
case "/=":
if rightVal == 0 {
return NewError(a.Pos().Sline(), DIVIDEBYZERO)
}
result := leftVal / rightVal
//Always return Float
ret, ok = scope.Reset(name, NewFloat(result))
if ok {
return
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
case "%=":
if isInt {
ret, ok = scope.Reset(name, NewInteger(int64(leftVal)%int64(rightVal)))
if ok {
return
}
} else if isUInt {
ret, ok = scope.Reset(name, NewUInteger(uint64(leftVal)%uint64(rightVal)))
if ok {
return
}
} else {
result := math.Mod(leftVal, rightVal)
ret, ok = checkNumAssign(scope, name, left, val, result)
if ok {
return
}
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
case "^=":
if isInt {
ret, ok = scope.Reset(name, NewInteger(int64(leftVal)^int64(rightVal)))
if ok {
return
}
} else if isUInt {
ret, ok = scope.Reset(name, NewUInteger(uint64(leftVal)^uint64(rightVal)))
if ok {
return
}
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
case "|=":
if isInt {
ret, ok = scope.Reset(name, NewInteger(int64(leftVal)|int64(rightVal)))
if ok {
return
}
} else if isUInt {
ret, ok = scope.Reset(name, NewUInteger(uint64(leftVal)|uint64(rightVal)))
if ok {
return
}
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
case "&=":
if isInt {
ret, ok = scope.Reset(name, NewInteger(int64(leftVal)&int64(rightVal)))
if ok {
return
}
} else if isUInt {
ret, ok = scope.Reset(name, NewUInteger(uint64(leftVal)&uint64(rightVal)))
if ok {
return
}
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
func checkNumAssign(scope *Scope, name string, left Object, right Object, result float64) (ret Object, ok bool) {
if left.Type() == FLOAT_OBJ || right.Type() == FLOAT_OBJ {
ret, ok = scope.Reset(name, NewFloat(result))
return
}
if (left.Type() == INTEGER_OBJ && right.Type() == UINTEGER_OBJ) ||
(left.Type() == UINTEGER_OBJ && right.Type() == INTEGER_OBJ) {
if result > math.MaxInt64 {
ret, ok = scope.Reset(name, NewUInteger(uint64(result)))
} else {
ret, ok = scope.Reset(name, NewInteger(int64(result)))
}
}
return
}
//str[idx] = item
//str += item
func evalStrAssignExpression(a *ast.AssignExpression, name string, left Object, scope *Scope, val Object) (ret Object) {
leftVal := left.(*String).String
var ok bool
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
}
var idx int64
switch o := index.(type) {
case *Integer:
idx = o.Int64
case *UInteger:
idx = int64(o.UInt64)
}
if idx < 0 || idx >= int64(len(leftVal)) {
return NewError(a.Pos().Sline(), INDEXERROR, idx)
}
str := NewString(leftVal[:idx] + val.Inspect() + leftVal[idx+1:])
ret, ok = scope.Reset(name, str)
if ok {
return
}
}
}
ret, ok = scope.Reset(name, NewString(leftVal+val.Inspect()))
if ok {
return
}
return NewError(a.Pos().Sline(), 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
var ok bool
switch a.Token.Literal {
case "+=":
switch nodeType := a.Name.(type) {
case *ast.Identifier:
name = nodeType.Value
leftVals = append(leftVals, val)
ret, ok = scope.Reset(name, &Array{Members: leftVals})
if ok {
return
}
}
case "=":
switch nodeType := a.Name.(type) {
case *ast.IndexExpression: //arr[idx] = xxx
index := Eval(nodeType.Index, scope)
if index == NIL {
ret = NIL
return
}
var idx int64
switch o := index.(type) {
case *Integer:
idx = o.Int64
case *UInteger:
idx = int64(o.UInt64)
}
if idx < 0 {
return NewError(a.Pos().Sline(), INDEXERROR, idx)
}
if idx < int64(len(leftVals)) { //index is in range
leftVals[idx] = val
ret, ok = scope.Reset(name, &Array{Members: leftVals})
if ok {
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, ok = scope.Reset(name, &Array{Members: leftVals})
if ok {
return
}
}
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
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(), INFIXOP, str, a.Token.Literal, val.Type())
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
func evalHashAssignExpression(a *ast.AssignExpression, name string, left Object, scope *Scope, val Object) (ret Object) {
leftHash := left.(*Hash)
var ok bool
switch a.Token.Literal {
case "+=":
if _, ok := val.(*Hash); !ok { //must be hash type
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
rightHash := val.(*Hash)
for _, hk := range rightHash.Order { //hk:hash key
pair, _ := rightHash.Pairs[hk]
leftHash.Push(a.Pos().Sline(), pair.Key, pair.Value)
}
ret, ok = scope.Reset(name, leftHash)
if ok {
return
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
case "-=":
_, ok := val.(Hashable)
if !ok {
return NewError(a.Pos().Sline(), KEYERROR, val.Type())
}
leftHash.Pop(a.Pos().Sline(), val)
ret, ok = scope.Reset(name, leftHash)
if ok {
return
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
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(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
return NewError(a.Pos().Sline(), INFIXOP, left.Type(), a.Token.Literal, val.Type())
}
func evalStructAssignExpression(a *ast.AssignExpression, scope *Scope, val Object) (retVal Object) {
strArr := strings.Split(a.Name.String(), ".")
var aObj Object
var aVal Object
var ok bool
if aObj, ok = scope.Get(strArr[0]); !ok {
return NewError(a.Pos().Sline(), UNKNOWNIDENT, strArr[0])
}
st, ok := aObj.(*Struct)
if !ok {
return NewError(a.Pos().Sline(), UNKNOWNIDENT, strArr[0])
}
if aVal, ok = st.Scope.Get(strArr[1]); !ok {
return NewError(a.Pos().Sline(), UNKNOWNIDENT, strArr[1])
}
structScope := st.Scope
if a.Token.Literal == "=" {
v, ok := structScope.Reset(strArr[1], retVal)
if ok {
return v
}
return NewError(a.Pos().Sline(), UNKNOWNIDENT, a.Name.String())
}
switch aVal.Type() {
case INTEGER_OBJ, UINTEGER_OBJ, FLOAT_OBJ:
retVal = evalNumAssignExpression(a, strArr[1], aVal, structScope, val)
st.Scope = structScope
return
case STRING_OBJ:
retVal = evalStrAssignExpression(a, strArr[1], aVal, structScope, val)
st.Scope = structScope
return
case ARRAY_OBJ:
retVal = evalArrayAssignExpression(a, strArr[1], aVal, structScope, val)
st.Scope = structScope
return
case HASH_OBJ:
retVal = evalHashAssignExpression(a, strArr[1], aVal, structScope, val)
st.Scope = structScope
return
}
return NewError(a.Pos().Sline(), INFIXOP, aVal.Type(), a.Token.Literal, val.Type())
}
//instanceObj[x] = xxx
//instanceObj[x,y] = xxx
func evalClassIndexerAssignExpression(a *ast.AssignExpression, obj Object, indexExpr *ast.IndexExpression, val Object, scope *Scope) Object {
instanceObj := obj.(*ObjectInstance)
var num int
switch o := indexExpr.Index.(type) {
case *ast.ClassIndexerExpression:
num = len(o.Parameters)
default:
num = 1
}
propName := "this" + fmt.Sprintf("%d", num)
//check if the Indexer is static
if instanceObj.IsStatic(propName, ClassPropertyKind) {
return NewError(a.Pos().Sline(), INDEXERSTATICERROR, instanceObj.Class.Name)
}
p := instanceObj.GetProperty(propName)
if p != nil {
//no setter or setter block is empty, e.g. 'property xxx { set; }'
if p.Setter == nil || len(p.Setter.Body.Statements) == 0 {
return NewError(a.Pos().Sline(), INDEXERUSEERROR, instanceObj.Class.Name)
} else {
newScope := NewScope(instanceObj.Scope, nil)
newScope.Set("value", val)
switch o := indexExpr.Index.(type) {
case *ast.ClassIndexerExpression:
for i, v := range o.Parameters {
index := Eval(v, scope)
newScope.Set(p.Indexes[i].Value, index)
}
default:
index := Eval(indexExpr.Index, scope)
newScope.Set(p.Indexes[0].Value, index)
}
results := Eval(p.Setter.Body, newScope)
if results.Type() == RETURN_VALUE_OBJ {
return results.(*ReturnValue).Value
}
return results
}
} else {
return NewError(a.Pos().Sline(), INDEXNOTFOUNDERROR, instanceObj.Class.Name)
}
}
func evalAssignExpression(a *ast.AssignExpression, scope *Scope) (val 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:
obj := Eval(o.Object, scope)
if obj.Type() == ERROR_OBJ {
return obj
}
switch m := obj.(type) {
case *Hash:
switch c := o.Call.(type) {
case *ast.Identifier:
//e.g.
//doc = {"one": {"two": { "three": [1, 2, 3,] }}}
//doc.one.two.three = 44
m.Push(a.Pos().Sline(), NewString(c.Value), val)
return
case *ast.IndexExpression:
//e.g.
//doc = {"one": {"two": { "three": [1, 2, 3,] }}}
//doc.one.two.three[2] = 44
leftVal := m.Get(a.Pos().Sline(), NewString(c.Left.String()))
indexVal := Eval(c.Index, scope)
switch v := leftVal.(type) {
case *Hash:
v.Push(a.Pos().Sline(), indexVal, val)
case *Array:
v.Set(a.Pos().Sline(), indexVal, val)
case *Tuple:
str := fmt.Sprintf("%s[IDX]", TUPLE_OBJ)
return NewError(a.Pos().Sline(), INFIXOP, str, "=", val.Type())
}
return NIL
}
}
}
var aObj Object
var ok bool
strArr := strings.Split(a.Name.String(), ".")
if aObj, ok = scope.Get(strArr[0]); !ok {
return reportTypoSuggestions(a.Pos().Sline(), scope, strArr[0])
//return NewError(a.Pos().Sline(), UNKNOWNIDENT, strArr[0])3
}
if aObj.Type() == ENUM_OBJ { //it's enum type
return NewError(a.Pos().Sline(), GENERICERROR, "Enum value cannot be reassigned!")
} else if aObj.Type() == HASH_OBJ { //e.g. hash.key = value
return evalHashAssignExpression(a, strArr[0], aObj, scope, val)
} else if aObj.Type() == INSTANCE_OBJ { //e.g. this.var = xxxx
instanceObj := aObj.(*ObjectInstance)
// //get variable's modifier level
// ml := instanceObj.GetModifierLevel(strArr[1], ClassMemberKind) //ml:modifier level
// if ml == ast.ModifierPrivate {
// return NewError(a.Pos().Sline(), CLSMEMBERPRIVATE, strArr[1], instanceObj.Class.Name)
// }
//check if it's a property
p := instanceObj.GetProperty(strArr[1])
if p == nil { //not property, return value from scope
// check if it's a static variable