-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathvisitor.go
1375 lines (1227 loc) · 40.7 KB
/
visitor.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 gscript
import (
"fmt"
"github.com/antlr/antlr4/runtime/Go/antlr"
"github.com/crossoverJie/gscript/log"
"github.com/crossoverJie/gscript/parser"
"github.com/crossoverJie/gscript/resolver"
"github.com/crossoverJie/gscript/stack"
sym "github.com/crossoverJie/gscript/symbol"
"strconv"
)
type Visitor struct {
parser.BaseGScriptVisitor
at *resolver.AnnotatedTree
stack stack.Stack
// 当 return 时,标记该 statement 所属的 block 的返回值
blockCtx2Mark map[*parser.BlockContext]interface{}
}
func NewVisitor(at *resolver.AnnotatedTree) *Visitor {
return &Visitor{at: at}
}
func ArithmeticOperators(script string) interface{} {
input := antlr.NewInputStream(script)
lexer := parser.NewGScriptLexer(input)
stream := antlr.NewCommonTokenStream(lexer, 0)
tree := parser.NewGScriptParser(stream).Prog()
visitor := Visitor{}
return visitor.Visit(tree)
}
/**
栈帧入栈
*/
func (v *Visitor) pushStack(frame *stack.Frame) {
// todo crossoverJie parentFrame 设置
if !v.stack.IsEmpty() {
// 栈顶开始查找
for i := v.stack.Size() - 1; i > 0; i-- {
f := v.stack.Get(i).(*stack.Frame)
// 函数是一等公民时,需要根据变量的作用域进行判断
funcObject, ok := frame.GetObject().(*stack.FuncObject)
// 新写入的栈帧的 parent 与当前的 parent 相同时
if f.GetScope().GetEncloseScope() == frame.GetScope().GetEncloseScope() {
frame.SetParent(f.GetParent())
break
} else if f.GetScope() == frame.GetScope().GetEncloseScope() {
// 新写入的栈帧是某个已有的栈帧的下级
frame.SetParent(f)
break
} else if ok {
referenceVariable := funcObject.GetReferenceVariable()
if referenceVariable != nil && referenceVariable.GetEncloseScope() == f.GetScope() {
frame.SetParent(f)
break
}
}
}
if frame.GetParent() == nil {
// 上一级作用域作为本级作用域的父级
frame.SetParent(v.stack.Peek().(*stack.Frame))
}
}
v.stack.Push(frame)
}
func (v *Visitor) popStack() {
v.stack.Pop()
}
// 在整个栈帧中获取左值
func (v *Visitor) getLeftValue(variable *sym.Variable) *LeftValue {
frame := v.stack.Peek().(*stack.Frame)
var object stack.Object
for frame != nil {
// 按照作用域获取变量值,内部作用域覆盖外部作用域。
if frame.GetScope().ContainsSymbol(variable) {
object = frame.GetObject()
break
}
frame = frame.GetParent()
}
// 闭包查询,闭包的变量不在父 scope 中,得一级一级的栈帧中查找。
if object == nil {
frame = v.stack.Peek().(*stack.Frame)
for frame != nil {
if frame.ContainsVariable(variable) {
object = frame.GetObject()
break
}
frame = frame.GetParent()
}
}
return NewLeftValue(variable, object)
}
func (v *Visitor) Visit(tree antlr.ParseTree) interface{} {
switch ctx := tree.(type) {
case *parser.ProgContext:
return v.VisitProg(ctx)
case *parser.BlockStmContext:
return v.VisitBlockStm(ctx)
case *parser.StmBlockLabelContext:
return v.VisitStmBlockLabel(ctx)
case *parser.BlockVarDeclarContext:
return v.VisitBlockVarDeclar(ctx)
case *parser.VariableDeclaratorsContext:
return v.VisitVariableDeclarators(ctx)
case *parser.ParseContext:
return v.VisitParse(ctx)
case *parser.StmIfElseContext:
return v.VisitStmIfElse(ctx)
case *parser.StmReturnContext:
return v.VisitStmReturn(ctx)
case *parser.StmBreakContext:
return v.VisitStmBreak(ctx)
case *parser.StmContinueContext:
return v.VisitStmContinue(ctx)
case *parser.StmExprContext:
return v.VisitStmExpr(ctx)
case *parser.StmForContext:
return v.VisitStmFor(ctx)
case *parser.StmWhileContext:
return v.VisitStmWhile(ctx)
case *parser.BlockFuncContext:
return nil
case *parser.ExprContext:
return v.VisitExpr(ctx)
case *parser.PrimaryContext:
return v.VisitPrimary(ctx)
case *parser.LiteralContext:
return v.VisitLiteral(ctx)
case *parser.BlockClassDeclarContext:
return nil
case *parser.ClassDeclarationContext:
return v.VisitClassDeclaration(ctx)
case *parser.ClassBodyContext:
return v.VisitClassBody(ctx)
default:
panic("Unknown context")
}
}
func (v *Visitor) VisitProg(ctx *parser.ProgContext) interface{} {
// 将scope写入栈帧
scope := v.at.GetNode2Scope()[ctx]
v.pushStack(stack.NewBlockScopeFrame(scope))
ret := v.VisitBlockStms(ctx.BlockStatements().(*parser.BlockStmsContext))
v.popStack()
return ret
}
func (v *Visitor) VisitBlock(ctx *parser.BlockContext) interface{} {
// 将 scope 写入栈帧
scope := v.at.GetNode2Scope()[ctx]
if scope != nil {
v.pushStack(stack.NewBlockScopeFrame(scope))
}
// 执行完一个 block 时,需要将标记的 block 置为空;不然在有循环调用时,第二次会直接返回第一次标记的数据。
if v.blockCtx2Mark != nil && len(v.blockCtx2Mark) > 0 {
v.blockCtx2Mark = nil
}
ret := v.VisitBlockStms(ctx.BlockStatements().(*parser.BlockStmsContext))
if scope != nil {
v.popStack()
}
return ret
}
func (v *Visitor) VisitBlockStms(ctx *parser.BlockStmsContext) interface{} {
var ret interface{}
for _, context := range ctx.AllBlockStatement() {
// 当下级的 statement 中有 return,该 return 以上的所有 block 都得需要返回 return。
// 如果当前 block 中存在递归调用,则不需要 return,需要继续执行。
blockContext, ok := context.GetParent().GetParent().(*parser.BlockContext)
if ok {
ret, ok := v.blockCtx2Mark[blockContext]
recursion := v.at.GetRecursion(blockContext)
if ok && !recursion {
return ret
}
}
ret = v.Visit(context)
switch ret.(type) {
case *ContinueObject:
return ret
case *BreakObject:
return ret
case *ReturnObject:
if ctx.GetParent() != nil && ctx.GetParent().GetParent() != nil {
// 获取两级父级,可以少扫描一次 Block
v.scanBlockStatementCtx(ctx.GetParent().GetParent().(antlr.ParseTree), ret)
}
return ret
}
//ret = retTemp
}
// 当 return 时, statements 下只有一个时,需要返回数据。
// 不然会返回 nil:for_test.go TestTowSum()
if len(ctx.AllBlockStatement()) == 1 && len(v.blockCtx2Mark) > 0 {
blockContext, ok := ctx.GetParent().(*parser.BlockContext)
if ok {
return v.blockCtx2Mark[blockContext]
}
}
return ret
}
// 在 return 的时候递归向上扫描所有的 Block,并打上标记,用于后面执行 return 的时候直接返回。
func (v *Visitor) scanBlockStatementCtx(tree antlr.ParseTree, value interface{}) {
context, ok := tree.(*parser.BlockContext)
if ok {
if v.blockCtx2Mark == nil {
v.blockCtx2Mark = make(map[*parser.BlockContext]interface{})
}
v.blockCtx2Mark[context] = value
}
if tree.GetParent() != nil {
v.scanBlockStatementCtx(tree.GetParent().(antlr.ParseTree), value)
}
}
func (v *Visitor) VisitBlockVarDeclar(ctx *parser.BlockVarDeclarContext) interface{} {
return v.Visit(ctx.VariableDeclarators())
}
func (v *Visitor) VisitVariableDeclarators(ctx *parser.VariableDeclaratorsContext) interface{} {
var ret interface{}
for _, context := range ctx.AllVariableDeclarator() {
ret = v.VisitVariableDeclarator(context.(*parser.VariableDeclaratorContext))
}
return ret
}
func (v *Visitor) VisitVariableDeclarator(ctx *parser.VariableDeclaratorContext) interface{} {
var ret interface{}
leftValue := v.VisitVariableDeclaratorId(ctx.VariableDeclaratorId().(*parser.VariableDeclaratorIdContext)).(*LeftValue)
if ctx.VariableInitializer() != nil {
ret = v.VisitVariableInitializer(ctx.VariableInitializer().(*parser.VariableInitializerContext))
switch ret.(type) {
case *LeftValue:
ret = ret.(*LeftValue).GetValue()
case *ArrayObject:
// 数组赋值 int b=a[0];
arrayObject := ret.(*ArrayObject)
ret = arrayObject.GetIndexValue()
}
// 数组赋值校验
//if leftValue.GetVariable().IsArray() && leftValue.GetVariable().GetType() != sym.Any {
// if ret != nil && reflect.TypeOf(ret).Kind() != reflect.Slice {
// // int[] a=10;
// log.RuntimePanic(ctx, fmt.Sprintf("cannot use %v as type %s[]", ret, leftValue.GetVariable().GetType().GetName()))
// }
//}
// todo crossoverJie 可以删掉,全部改为了编译期校验
// 为变量赋值
// int e=10 int e = foo() any 类型不需要校验
//if leftValue.GetVariable().GetType() != sym.Any {
// switch ret.(type) {
// case int:
// if leftValue.GetVariable().GetType() != sym.Int && leftValue.GetVariable().GetType() != sym.Byte {
// // string a=10; 校验这类错误
// log.RuntimePanic(ctx, fmt.Sprintf("variable %s type error", leftValue.GetVariable().GetName()))
// }
// case string:
// if leftValue.GetVariable().GetType() != sym.String {
// // int a="1"; 校验这类错误
// log.RuntimePanic(ctx, fmt.Sprintf("variable %s type error", leftValue.GetVariable().GetName()))
// }
// case float64:
// if leftValue.GetVariable().GetType() != sym.Float {
// // int a=10.1;
// log.RuntimePanic(ctx, fmt.Sprintf("variable %s type error", leftValue.GetVariable().GetName()))
//
// }
// case bool:
// if leftValue.GetVariable().GetType() != sym.Bool {
// // bool a=10.1;
// log.RuntimePanic(ctx, fmt.Sprintf("variable %s type error", leftValue.GetVariable().GetName()))
//
// }
// case byte:
// if leftValue.GetVariable().GetType() != sym.Byte {
// log.RuntimePanic(ctx, fmt.Sprintf("variable %s type error", leftValue.GetVariable().GetName()))
// }
// }
//}
leftValue.SetValue(ret)
}
return ret
}
func (v *Visitor) VisitVariableDeclaratorId(ctx *parser.VariableDeclaratorIdContext) interface{} {
symbol := v.at.GetSymbolOfNode()[ctx]
value := v.getLeftValue(symbol.(*sym.Variable))
return value
}
func (v *Visitor) VisitVariableInitializer(ctx *parser.VariableInitializerContext) interface{} {
if ctx.Expr() != nil {
return v.Visit(ctx.Expr())
}
// array init
if ctx.ArrayInitializer() != nil {
allContext := ctx.ArrayInitializer().(*parser.ArrayInitializerContext)
lenAndCap := v.VisitArrayInitializer(ctx.ArrayInitializer().(*parser.ArrayInitializerContext))
length := lenAndCap.([]int)[0]
cap := lenAndCap.([]int)[1]
//var array []interface{}
var array []interface{}
if cap > 0 {
array = make([]interface{}, length, cap)
} else {
array = make([]interface{}, length)
}
if length == 0 {
//any[] a = {1,2,3};或者是没有指定数组大小时
for _, context := range allContext.AllVariableInitializer() {
val := v.VisitVariableInitializer(context.(*parser.VariableInitializerContext))
array = append(array, val)
}
} else {
if length < len(allContext.AllVariableInitializer()) {
// int[] a =[1]{1,2,3};
log.RuntimePanic(ctx, fmt.Sprintf("array index out of bounds"))
}
// int[] a = [3]{1,2}; 这类初始化
for i, context := range allContext.AllVariableInitializer() {
val := v.VisitVariableInitializer(context.(*parser.VariableInitializerContext))
array[i] = val
}
}
return array
}
return nil
}
func (v *Visitor) VisitArrayInitializer(ctx *parser.ArrayInitializerContext) interface{} {
lenAndCap := make([]int, 2)
var (
len, cap int
)
if ctx.LBRACK() != nil && ctx.RBRACK() != nil {
length := v.Visit(ctx.Expr(0))
switch length.(type) {
case int:
//return length.(int)
len = length.(int)
case *LeftValue:
value := length.(*LeftValue).GetValue()
switch value.(type) {
case int:
//return value.(int)
len = value.(int)
default:
log.RuntimePanic(ctx, fmt.Sprintf("non-int len argument in Initialization function"))
}
default:
log.RuntimePanic(ctx, fmt.Sprintf("non-int len argument in Initialization function"))
}
if ctx.Expr(1) != nil {
capacity := v.Visit(ctx.Expr(0))
switch capacity.(type) {
case int:
//return length.(int)
cap = capacity.(int)
case *LeftValue:
value := capacity.(*LeftValue).GetValue()
switch value.(type) {
case int:
//return value.(int)
cap = value.(int)
default:
log.RuntimePanic(ctx, fmt.Sprintf("non-int cap argument in Initialization function"))
}
default:
log.RuntimePanic(ctx, fmt.Sprintf("non-int cap argument in Initialization function"))
}
}
}
lenAndCap[0] = len
lenAndCap[1] = cap
return lenAndCap
}
func (v *Visitor) VisitBlockStm(ctx *parser.BlockStmContext) interface{} {
return v.Visit(ctx.Statement())
}
func (v *Visitor) VisitStmBlockLabel(ctx *parser.StmBlockLabelContext) interface{} {
return v.VisitBlock(ctx.GetBlockLabel().(*parser.BlockContext))
}
func (v *Visitor) VisitParse(ctx *parser.ParseContext) interface{} {
for _, expr := range ctx.GetExpr_list() {
return v.Visit(expr)
}
return nil
}
func (v *Visitor) VisitExpr(ctx *parser.ExprContext) interface{} {
var ret interface{}
if ctx.Primary() != nil {
ret = v.Visit(ctx.Primary())
}
// 获取数组数据
if ctx.GetArray() != nil && ctx.GetIndex() != nil {
left := v.VisitExpr(ctx.GetArray().(*parser.ExprContext))
index := v.VisitExpr(ctx.GetIndex().(*parser.ExprContext))
switch index.(type) {
case int:
ret = NewArrayObject(left.(*LeftValue), index.(int))
case *LeftValue:
leftValue := index.(*LeftValue)
ret = NewArrayObject(left.(*LeftValue), leftValue.GetValue().(int))
}
}
// 数组切片
if ctx.IDENTIFIER() != nil && ctx.LBRACK() != nil && ctx.RBRACK() != nil {
symbol := v.at.GetSymbolOfNode()[ctx]
variable := v.getLeftValue(symbol.(*sym.Variable))
if !variable.GetVariable().IsArray() {
log.RuntimePanic(ctx, fmt.Sprintf("cannot slice %s (type %s)", variable.GetVariable().GetName(), variable.GetVariable().GetType().GetName()))
}
var (
startIndex, endIndex int
)
start := v.Visit(ctx.Expr(0))
switch start.(type) {
case int:
startIndex = start.(int)
case *LeftValue:
startLeft := start.(*LeftValue)
startIndexLeft, ok := startLeft.GetValue().(int)
if !ok {
log.RuntimePanic(ctx, fmt.Sprintf("invalid slice index %s (type %s)", startLeft.GetVariable().GetName(), startLeft.GetVariable().GetType().GetName()))
}
startIndex = startIndexLeft
}
end := v.Visit(ctx.Expr(1))
switch end.(type) {
case int:
endIndex = end.(int)
case *LeftValue:
endLeft := end.(*LeftValue)
endIndexLeft, ok := endLeft.GetValue().(int)
if !ok {
log.RuntimePanic(ctx, fmt.Sprintf("invalid slice index %s (type %s)", endLeft.GetVariable().GetName(), endLeft.GetVariable().GetType().GetName()))
}
endIndex = endIndexLeft
}
switch variable.GetValue().(type) {
case []interface{}:
list := variable.GetValue().([]interface{})
return list[startIndex:endIndex]
case []byte:
list := variable.GetValue().([]byte)
return list[startIndex:endIndex]
}
return nil
}
if ctx.GetBop() != nil && len(ctx.AllExpr()) >= 2 {
val1 := v.Visit(ctx.GetLhs())
val2 := v.Visit(ctx.GetRhs())
leftObject := val1
rightObject := val2
switch val1.(type) {
case *LeftValue:
leftObject = val1.(*LeftValue).GetValue()
case *ArrayObject:
leftObject = val1.(*ArrayObject).GetIndexValue()
}
switch val2.(type) {
case *LeftValue:
rightObject = val2.(*LeftValue).GetValue()
case *ArrayObject:
rightObject = val2.(*ArrayObject).GetIndexValue()
}
//推导出来的该节点类型
deriveType := v.at.GetTypeOfNode()[ctx]
type1 := v.at.GetTypeOfNode()[ctx.Expr(0)]
type2 := v.at.GetTypeOfNode()[ctx.Expr(1)]
if deriveType == sym.Any {
// 两个值都是any类型,需要运行时通过值判断
deriveType = sym.GetUpperTypeWithValue(ctx, leftObject, rightObject)
} else if deriveType == nil {
// 处理:int x = n[0] + n[1]; 这种情况deriveType为空,需要运行时重新推导
deriveType = sym.GetUpperTypeWithValue(ctx, leftObject, rightObject)
// 运行时计算 type
type1, type2 = sym.GetType(type1, type2, leftObject, rightObject)
}
switch ctx.GetBop().GetTokenType() {
case parser.GScriptParserMULT:
if deriveType == sym.Int {
return leftObject.(int) * rightObject.(int)
} else if deriveType == sym.Byte {
return leftObject.(byte) * rightObject.(byte)
} else if deriveType == sym.Float {
return leftObject.(float64) * rightObject.(float64)
} else if type1.IsType(type2) {
// 两个参数类型相同,执行运算符重载
return v.callOpFunction(ctx, type1, ctx.GetBop().GetTokenType(), leftObject, rightObject)
} else {
log.RuntimePanic(ctx, fmt.Sprintf("invalid operation: %v * %v", leftObject, rightObject))
}
case parser.GScriptParserDIV:
if deriveType == sym.Int {
if rightObject.(int) == 0 {
log.RuntimePanic(ctx, "integer divide by zero")
}
return leftObject.(int) / rightObject.(int)
} else if deriveType == sym.Byte {
return leftObject.(byte) / rightObject.(byte)
} else if deriveType == sym.Float {
return leftObject.(float64) / rightObject.(float64)
} else if type1.IsType(type2) {
// 两个参数类型相同,执行运算符重载
return v.callOpFunction(ctx, type1, ctx.GetBop().GetTokenType(), leftObject, rightObject)
} else {
log.RuntimePanic(ctx, fmt.Sprintf("invalid operation: %v / %v", leftObject, rightObject))
}
case parser.GScriptParserPLUS:
if deriveType == sym.String {
return fmt.Sprintf("%v", leftObject) + fmt.Sprintf("%v", rightObject)
} else if deriveType == sym.Int {
return leftObject.(int) + rightObject.(int)
} else if deriveType == sym.Byte {
return leftObject.(byte) + rightObject.(byte)
} else if deriveType == sym.Float {
return sym.Value2Float(leftObject) + sym.Value2Float(rightObject)
} else if type1.IsType(type2) {
// 两个参数类型相同,执行运算符重载
return v.callOpFunction(ctx, type1, ctx.GetBop().GetTokenType(), leftObject, rightObject)
} else {
log.RuntimePanic(ctx, fmt.Sprintf("invalid operation: %v + %v", leftObject, rightObject))
}
case parser.GScriptParserSUB:
if deriveType == sym.Int {
return leftObject.(int) - rightObject.(int)
} else if deriveType == sym.Byte {
return leftObject.(byte) - rightObject.(byte)
} else if deriveType == sym.Float {
return sym.Value2Float(leftObject) - sym.Value2Float(rightObject)
} else if type1.IsType(type2) {
// 两个参数类型相同,执行运算符重载
return v.callOpFunction(ctx, type1, ctx.GetBop().GetTokenType(), leftObject, rightObject)
} else {
log.RuntimePanic(ctx, fmt.Sprintf("invalid operation: %v - %v", leftObject, rightObject))
}
case parser.GScriptParserMOD:
return leftObject.(int) % rightObject.(int)
case parser.GScriptParserGT:
deriveType = sym.GetUpperType(ctx, type1, type2)
if deriveType == sym.String {
// 字符串比较永远都是 false
return false
} else if deriveType == sym.Int {
return leftObject.(int) > rightObject.(int)
} else if deriveType == sym.Byte {
return leftObject.(byte) > rightObject.(byte)
} else if deriveType == sym.Float {
return sym.Value2Float(leftObject) > sym.Value2Float(rightObject)
} else if type1.IsType(type2) {
// 两个参数类型相同,执行运算符重载
return v.callOpFunction(ctx, sym.Bool, ctx.GetBop().GetTokenType(), leftObject, rightObject)
} else {
log.RuntimePanic(ctx, fmt.Sprintf("invalid operation: %v > %v", leftObject, rightObject))
}
case parser.GScriptParserLT:
deriveType = sym.GetUpperType(ctx, type1, type2)
if deriveType == sym.String {
// 字符串比较永远都是 false
return false
} else if deriveType == sym.Int {
return leftObject.(int) < rightObject.(int)
} else if deriveType == sym.Byte {
return leftObject.(byte) < rightObject.(byte)
} else if deriveType == sym.Float {
return sym.Value2Float(leftObject) < sym.Value2Float(rightObject)
} else if type1.IsType(type2) {
// 两个参数类型相同,执行运算符重载
return v.callOpFunction(ctx, sym.Bool, ctx.GetBop().GetTokenType(), leftObject, rightObject)
} else {
log.RuntimePanic(ctx, fmt.Sprintf("invalid operation: %v < %v", leftObject, rightObject))
}
case parser.GScriptParserGE:
deriveType = sym.GetUpperType(ctx, type1, type2)
if deriveType == sym.String {
// 字符串比较永远都是 false
return false
} else if deriveType == sym.Int {
return leftObject.(int) >= rightObject.(int)
} else if deriveType == sym.Byte {
return leftObject.(byte) >= rightObject.(byte)
} else if deriveType == sym.Float {
return sym.Value2Float(leftObject) >= sym.Value2Float(rightObject)
} else if type1.IsType(type2) {
// 两个参数类型相同,执行运算符重载
return v.callOpFunction(ctx, sym.Bool, ctx.GetBop().GetTokenType(), leftObject, rightObject)
} else {
log.RuntimePanic(ctx, fmt.Sprintf("invalid operation: %v > %v", leftObject, rightObject))
}
case parser.GScriptParserLE:
deriveType = sym.GetUpperType(ctx, type1, type2)
if deriveType == sym.String {
// 字符串比较永远都是 false
return false
} else if deriveType == sym.Int {
return leftObject.(int) <= rightObject.(int)
} else if deriveType == sym.Byte {
return leftObject.(byte) <= rightObject.(byte)
} else if deriveType == sym.Float {
return sym.Value2Float(leftObject) <= sym.Value2Float(rightObject)
} else if type1.IsType(type2) {
// 两个参数类型相同,执行运算符重载
return v.callOpFunction(ctx, sym.Bool, ctx.GetBop().GetTokenType(), leftObject, rightObject)
} else {
log.RuntimePanic(ctx, fmt.Sprintf("invalid operation: %v > %v", leftObject, rightObject))
}
case parser.GScriptParserEQUAL:
deriveType = sym.GetUpperType(ctx, type1, type2)
if deriveType == sym.String {
return fmt.Sprintf("%v", leftObject) == fmt.Sprintf("%v", rightObject)
} else if deriveType == sym.Int {
return leftObject.(int) == rightObject.(int)
} else if deriveType == sym.Byte {
return leftObject.(byte) == rightObject.(byte)
} else if deriveType == sym.Float {
return sym.Value2Float(leftObject) == sym.Value2Float(rightObject)
} else if deriveType == sym.Nil {
if leftObject == nil && rightObject == nil {
return true
} else {
return false
}
} else if deriveType == sym.Any {
// 两个 any 值进行比较
return leftObject == rightObject
} else if type1.IsType(type2) {
// 两个参数类型相同,执行运算符重载
return v.callOpFunction(ctx, sym.Bool, ctx.GetBop().GetTokenType(), leftObject, rightObject)
} else {
return leftObject == rightObject
}
case parser.GScriptParserNOTEQUAL:
deriveType = sym.GetUpperType(ctx, type1, type2)
if deriveType == sym.String {
return fmt.Sprintf("%v", leftObject) != fmt.Sprintf("%v", rightObject)
} else if deriveType == sym.Int {
return leftObject.(int) != rightObject.(int)
} else if deriveType == sym.Byte {
return leftObject.(byte) != rightObject.(byte)
} else if deriveType == sym.Float {
return sym.Value2Float(leftObject) != sym.Value2Float(rightObject)
} else if deriveType == sym.Nil {
if leftObject != nil || rightObject != nil {
return true
} else {
return false
}
} else if deriveType == sym.Any {
// 两个 any 值进行比较
return leftObject != rightObject
} else if type1.IsType(type2) {
// 两个参数类型相同,执行运算符重载
return v.callOpFunction(ctx, sym.Bool, ctx.GetBop().GetTokenType(), leftObject, rightObject)
} else {
log.RuntimePanic(ctx, fmt.Sprintf("invalid operation: %v != %v", leftObject, rightObject))
}
case parser.GScriptParserASSIGN:
switch val1.(type) {
case *LeftValue:
l := val1.(*LeftValue)
r := val2
switch val2.(type) {
case *LeftValue:
r = val2.(*LeftValue).GetValue()
}
// e = e+10
l.SetValue(r)
return r
case *ArrayObject:
// 数组赋值 a[1]=3;
arrayObject := val1.(*ArrayObject)
switch val2.(type) {
case *LeftValue:
r := val2.(*LeftValue).GetValue()
arrayObject.SetIndexValue(r)
default:
arrayObject.SetIndexValue(val2)
}
}
}
}
if ctx.GetBop() != nil && (ctx.GetBop().GetTokenType() == parser.GScriptParserAND || ctx.GetBop().GetTokenType() == parser.GScriptParserOR) {
// &&
left := v.VisitExpr(ctx.GetLhs().(*parser.ExprContext))
right := v.VisitExpr(ctx.GetRhs().(*parser.ExprContext))
var (
leftCondition = false
rightCondition = false
)
switch left.(type) {
case bool:
leftCondition = left.(bool)
case *LeftValue:
b, ok := left.(*LeftValue).GetValue().(bool)
if ok {
leftCondition = b
}
}
switch right.(type) {
case bool:
rightCondition = right.(bool)
case *LeftValue:
b, ok := right.(*LeftValue).GetValue().(bool)
if ok {
rightCondition = b
}
}
if ctx.GetBop().GetTokenType() == parser.GScriptParserAND {
return leftCondition && rightCondition
} else if ctx.GetBop().GetTokenType() == parser.GScriptParserOR {
return leftCondition || rightCondition
} else {
return false
}
}
if ctx.GetBop() != nil && ctx.GetBop().GetTokenType() == parser.GScriptParserDOT {
l := v.VisitExpr(ctx.Expr(0).(*parser.ExprContext))
switch l.(type) {
case *LeftValue:
left := l.(*LeftValue)
switch left.GetValue().(type) {
case *stack.ClassObject:
classObject := left.GetValue().(*stack.ClassObject)
if ctx.IDENTIFIER() != nil {
_ = v.at.GetSymbolOfNode()[ctx.Expr(0)].(*sym.Variable)
// todo crossoverJie this/super 从父级查找
variable := v.at.GetSymbolOfNode()[ctx].(*sym.Variable)
// person.age; 返回的是 age 的左值
return NewLeftValue(variable, classObject)
} else if ctx.FunctionCall() != nil {
// person.getAge();
// todo crossoverJie isSuper 赋值
return v.receiveFunctionCall(ctx.FunctionCall().(*parser.FunctionCallContext), classObject, false)
}
case *LeftValue:
leftValue := left.GetValue().(*LeftValue)
if ctx.IDENTIFIER() != nil {
v1 := v.at.GetSymbolOfNode()[ctx].(*sym.Variable)
switch leftValue.GetValue().(type) {
case *stack.ClassObject:
classObject := leftValue.GetValue().(*stack.ClassObject)
return NewLeftValue(v1, classObject)
}
}
case stack.Object:
object := left.GetValue().(stack.Object)
v1 := v.at.GetSymbolOfNode()[ctx].(*sym.Variable)
value := object.GetValue(v1)
return value
}
}
}
// 后缀计算
if ctx.GetPostfix() != nil {
lhs := ctx.GetLhs()
value := v.Visit(lhs)
switch value.(type) {
case *LeftValue:
leftValue := value.(*LeftValue)
switch ctx.GetPostfix().GetTokenType() {
case parser.GScriptParserINC:
leftValue.SetValue(leftValue.GetValue().(int) + 1)
return value
case parser.GScriptParserDEC:
leftValue.SetValue(leftValue.GetValue().(int) - 1)
return value
}
case int:
switch ctx.GetPostfix().GetTokenType() {
case parser.GScriptParserINC:
value = value.(int) + 1
return value
case parser.GScriptParserDEC:
value = value.(int) - 1
return value
}
}
}
// 前缀计算
if ctx.GetPrefix() != nil {
rhs := ctx.GetRhs()
value := v.Visit(rhs)
if ctx.GetPrefix().GetTokenType() == parser.GScriptParserBANG {
switch value.(type) {
case bool:
return !value.(bool)
}
line := ctx.GetStart().GetLine()
column := ctx.GetStart().GetColumn()
panic(fmt.Sprintf("invalid ! symbol in line:%d and column:%d", line, column))
} else if ctx.GetPrefix().GetTokenType() == parser.GScriptParserSUB {
// int a = -10; int b=-10.1;
switch value.(type) {
case *LeftValue:
getValue := value.(*LeftValue).GetValue()
switch getValue.(type) {
case int:
return -getValue.(int)
case float64:
return -getValue.(float64)
}
case int:
return -value.(int)
case float64:
return -value.(float64)
}
}
}
if ctx.FunctionCall() != nil {
return v.VisitFunctionCall(ctx.FunctionCall().(*parser.FunctionCallContext))
}
return ret
}
// 执行自定义的运算符重载函数
func (v *Visitor) callOpFunction(ctx antlr.ParserRuleContext, returnType sym.Type, tokenType int, leftObject, rightObject interface{}) interface{} {
function := v.at.GetOpFunction(returnType, tokenType)
if function != nil {
funcObject := stack.NewFuncObject(function)
opParams := []interface{}{leftObject, rightObject}
return v.executeFunctionCall(funcObject, opParams)
} else {
log.RuntimePanic(ctx, fmt.Sprintf("no match to operator overloading function"))
}
return nil
}
// VisitFunctionCall 函数调用
func (v *Visitor) VisitFunctionCall(ctx *parser.FunctionCallContext) interface{} {
var ret interface{}
name := ctx.IDENTIFIER().GetText()
// internal function
function := GetInternalFunction(name)
if function != nil {
return function(v, ctx)
}
// 默认构造函数
symbol := v.at.GetSymbolOfNode()[ctx]
switch symbol.(type) {
case *sym.DefaultConstructorFunc:
class := symbol.(*sym.DefaultConstructorFunc).GetClass()
return v.initClassObject(class)
}
functionObject := v.getFunctionObject(ctx)
// 如果对象的构造函数 Person(10)
if functionObject.GetFunction().IsConstructor() {
// 获取当前函数所归属的 class
classObject := v.initClassObject(functionObject.GetFunction().GetEncloseScope().(*sym.Class))
v.receiveFunctionCall(ctx, classObject, false)
return classObject
}
// 构建函数调用的参数值
paramValues := v.buildParamValues(ctx)
// 执行函数调用
ret = v.executeFunctionCall(functionObject, paramValues)
// todo crossoverJie 支持 return
return ret
}
// 初始化 classObject 对象
func (v *Visitor) initClassObject(class *sym.Class) *stack.ClassObject {
object := stack.NewClassObject(class)
var tempStack stack.Stack
tempStack.Push(class)
v.pushStack(stack.NewClassStackFrame(object))
// todo crossoverJie 如果有父类需要一次初始化
for !tempStack.IsEmpty() {
pop := tempStack.Pop().(*sym.Class)
v.initClassObjectField(pop, object)
}
v.popStack()
return object
}
// 初始化 classObject 中的变量数据
func (v *Visitor) initClassObjectField(class *sym.Class, object *stack.ClassObject) {
for _, symbol := range class.GetSymbols() {
switch symbol.(type) {
case *sym.Variable:
// 为 class 中的变量初始化为空值
object.SetValue(symbol.(*sym.Variable), nil)
}
}
// 初始化变量,比如 class X{**int a=10**}
ctx := class.GetCtx().(*parser.ClassDeclarationContext)
v.VisitClassDeclaration(ctx)
}
// 获取函数的 object 对象,需要用来压栈
func (v *Visitor) getFunctionObject(ctx *parser.FunctionCallContext) *stack.FuncObject {
var (
funcObject *stack.FuncObject
function *sym.Func
)
symbol := v.at.GetSymbolOfNode()[ctx]
switch symbol.(type) {
case *sym.Func:
function = symbol.(*sym.Func)
case *sym.Variable:
// symbol 是函数变量类型
variable := symbol.(*sym.Variable)
value := v.getLeftValue(variable).GetValue()
functionObject, ok := value.(*stack.FuncObject)
if ok {
function = functionObject.GetFunction()
return functionObject
}
default:
name := ctx.IDENTIFIER().GetText()
log.RuntimePanic(ctx, fmt.Sprintf("unable find function %s", name))
}
funcObject = stack.NewFuncObject(function)
return funcObject
}
// 构建函数调用的参数值 myfunc(2+2+a) 2+2+a 的值
func (v *Visitor) buildParamValues(ctx *parser.FunctionCallContext) []interface{} {
ret := make([]interface{}, 0)