-
Notifications
You must be signed in to change notification settings - Fork 6
/
types.go
1721 lines (1512 loc) · 41 KB
/
types.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
/*
Copyright 2022 fy <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package dicescript
import (
"errors"
"fmt"
"math"
"reflect"
"strconv"
"strings"
"golang.org/x/exp/rand"
)
type VMValueType int
type IntType int // :IntType
const IntTypeSize = strconv.IntSize / 8 // 只能为 4 或 8(32位/64位)
const (
VMTypeInt VMValueType = 0
VMTypeFloat VMValueType = 1
VMTypeString VMValueType = 2
VMTypeNull VMValueType = 4
VMTypeComputedValue VMValueType = 5
VMTypeArray VMValueType = 6
VMTypeDict VMValueType = 7
VMTypeFunction VMValueType = 8
VMTypeNativeFunction VMValueType = 9
VMTypeNativeObject VMValueType = 10
// 内部对象
vmTypeLocal VMValueType = 20
vmTypeGlobal VMValueType = 21
)
var binOperator = []func(*VMValue, *Context, *VMValue) *VMValue{
(*VMValue).OpAdd,
(*VMValue).OpSub,
(*VMValue).OpMultiply,
(*VMValue).OpDivide,
(*VMValue).OpModulus,
(*VMValue).OpPower,
(*VMValue).OpNullCoalescing,
(*VMValue).OpCompLT,
(*VMValue).OpCompLE,
(*VMValue).OpCompEQ,
(*VMValue).OpCompNE,
(*VMValue).OpCompGE,
(*VMValue).OpCompGT,
(*VMValue).OpBitwiseAnd,
(*VMValue).OpBitwiseOr,
}
type RollConfig struct {
EnableDiceWoD bool // 启用WOD骰子语法,即XaYmZkNqM,X个数,Y加骰线,Z面数,N阈值(>=),M阈值(<=)
EnableDiceCoC bool // 启用COC骰子语法,即bX/pX奖惩骰
EnableDiceFate bool // 启用Fate骰语法,即fX
EnableDiceDoubleCross bool // 启用双十字骰语法,即XcY
DisableBitwiseOp bool // 禁用位运算,用于st,如 &a=1d4
DisableStmts bool // 禁用语句语法(如if while等),仅允许表达式
DisableNDice bool // 禁用Nd语法,即只能2d6这样写,不能写2d
// 如果返回值为true,那么跳过剩下的储存流程。如果overwrite不为nil,对v进行覆盖。
// 另注: 钩子函数中含有ctx的原因是可能在函数中进行调用,此时ctx会发生变化
HookFuncValueStore func(ctx *Context, name string, v *VMValue) (overwrite *VMValue, solved bool)
// 如果overwrite不为nil,将结束值加载并使用overwrite值。如果为nil,将以newName为key进行加载
HookFuncValueLoad func(ctx *Context, name string) (newName string, overwrite *VMValue)
// 读取后回调(返回值将覆盖之前读到的值。如果之前未读取到值curVal将为nil),用户需要在里面调用doCompute保证结果正确
HookFuncValueLoadOverwrite func(ctx *Context, name string, curVal *VMValue, doCompute func(curVal *VMValue) *VMValue, detail *BufferSpan) *VMValue
// st回调,注意val和extra都经过clone,可以放心储存
CallbackSt func(_type string, name string, val *VMValue, extra *VMValue, op string, detail string) // st回调
CustomMakeDetailFunc func(ctx *Context, details []BufferSpan, dataBuffer []byte, parsedOffset int) string // 自定义计算过程
ParseExprLimit uint64 // 解析算力限制,防止构造特殊语句进行DOS攻击,0为无限,建议值1000万
OpCountLimit IntType // 算力限制,超过这个值会报错,0为无限,建议值30000
DefaultDiceSideExpr string // 默认骰子面数
defaultDiceSideExprCacheFunc *VMValue // expr的缓存函数
PrintBytecode bool // 执行时打印字节码
IgnoreDiv0 bool // 当div0时暂不报错
DiceMinMode bool // 骰子以最小值结算,用于获取下界
DiceMaxMode bool // 以最大值结算 获取上界
}
type customDiceItem struct {
// expr string
// callback func(ctx *Context, groups []string) *VMValue
// parse func(ctx *Context, p *parser)
// 该怎样写呢?似乎将一些解析相关的struct暴露出去并不合适
// 这里我有三个选项,第一种是创建一种更简单的语法进行编译:例如
// nos 'd' expr 可以看成是一种简易正则
// 选项二:
// 将parser独立成包(关联点很少,并不困难),同时将几个expr暴露出去
// 这样用户直接与parser进行交互
// 使用难度较大,但自由度也很大
// 选项三:
// 对文档流进行简易封装,用户可以使用GetNext获取下一个字符,最后用户需要告知消耗了几个字符,然后生成了什么
// 自由度甚至更大,但需要额外封装一下 expr 等几个主要的语法节点供调用
//
// 值得额外注意的一点是,customDice实际上会参与两个阶段,即解析和执行
// 解析阶段需要确认是否匹配,同时给出抓取文本的规则,接着执行时需要使用解析过程生成的数据
// 这需要专门的数据结构来配合,回溯的问题也值得考虑
//
// 再补充一点,由于是字节码虚拟机,所以 'd' e:expr 这里对e的映射实际上没有意义,
// 并不会得到e的值因为expr语句实际上的执行结果是写入字节码
// 所以用户还需要能操作vm数据栈?还是搞点语法糖?
// 我认为可以先考虑选项三,再从其基础上制作选项一
}
type Context struct {
parser *parser
subThreadDepth int
Attrs *ValueMap
UpCtx *Context
// subThread *Context // 用于执行子句
code []ByteCode
codeIndex int
stack []VMValue
top int
NumOpCount IntType // 算力计数
// CocFlagVarPrefix string // 解析过程中出现,当VarNumber开启时有效,可以是困难极难常规大成功
Config RollConfig // 标记
Error error // 报错信息
Ret *VMValue // 返回值
RestInput string // 剩余字符串
Matched string // 匹配的字符串
DetailSpans []BufferSpan
detailCache string // 计算过程
IsComputedLoaded bool
Seed []byte // 随机种子,16个字节,即双uint64
RandSrc *rand.PCGSource // 根据种子生成的source
IsRunning bool // 是否正在运行,Run时会置为true,halt时会置为false
CustomDiceInfo []*customDiceItem
forceSolveDetail bool // 一个辅助属性,用于computed时强制获取计算过程
/** 全局变量 */
globalNames *ValueMap
// 全局scope的写入回调
GlobalValueStoreFunc func(name string, v *VMValue)
// 全局scope的读取回调
GlobalValueLoadFunc func(name string) *VMValue
// 全局scope的读取后回调(返回值将覆盖之前读到的值。如果之前未读取到值curVal将为nil)
GlobalValueLoadOverwriteFunc func(name string, curVal *VMValue) *VMValue
}
func (ctx *Context) GetDetailText() string {
if ctx.DetailSpans != nil {
if ctx.detailCache != "" {
return ctx.detailCache
}
ctx.detailCache = ctx.makeDetailStr(ctx.DetailSpans)
return ctx.detailCache
}
return ""
}
func (ctx *Context) StackTop() int {
return ctx.top
}
func (ctx *Context) Depth() int {
return ctx.subThreadDepth
}
func (ctx *Context) SetConfig(cfg *RollConfig) {
ctx.Config = *cfg
}
func (ctx *Context) Init() {
ctx.Attrs = &ValueMap{}
ctx.globalNames = &ValueMap{}
ctx.detailCache = ""
ctx.DetailSpans = nil
if ctx.Seed != nil {
s := rand.PCGSource{}
_ = s.UnmarshalBinary(ctx.Seed)
ctx.RandSrc = &s
}
}
func (ctx *Context) GetCurSeed() ([]byte, error) {
if ctx.RandSrc != nil {
return ctx.RandSrc.MarshalBinary()
}
return randSource.MarshalBinary()
}
func (ctx *Context) loadInnerVar(name string) *VMValue {
return builtinValues[name]
}
func (ctx *Context) LoadNameGlobalWithDetail(name string, isRaw bool, detail *BufferSpan) *VMValue {
var loadFunc func(name string) *VMValue
if loadFunc == nil {
loadFunc = ctx.GlobalValueLoadFunc
}
// 检测全局表
if loadFunc != nil {
val := loadFunc(name)
if val != nil {
if !isRaw && val.TypeId == VMTypeComputedValue {
val = val.ComputedExecute(ctx, detail)
if ctx.Error != nil {
return nil
}
}
return val
}
}
// else {
// ctx.Error = errors.New("未设置 GlobalValueLoadFunc,无法获取变量")
// return nil
// }
// 检测内置变量/函数检查
val := ctx.loadInnerVar(name)
if ctx.GlobalValueLoadOverwriteFunc != nil {
val = ctx.GlobalValueLoadOverwriteFunc(name, val)
}
if val == nil {
val = NewNullVal()
}
if !isRaw && val.TypeId == VMTypeComputedValue {
val = val.ComputedExecute(ctx, detail)
if ctx.Error != nil {
return nil
}
}
return val
}
func (ctx *Context) LoadNameGlobal(name string, isRaw bool) *VMValue {
return ctx.LoadNameGlobalWithDetail(name, isRaw, nil)
}
func (ctx *Context) LoadNameLocalWithDetail(name string, isRaw bool, detail *BufferSpan) *VMValue {
// if ctx.currentThis != nil {
// return ctx.currentThis.AttrGet(ctx, name)
// } else {
// if ctx.subThreadDepth >= 1 {
ret, exists := ctx.Attrs.Load(name)
if !exists {
ret = NewNullVal()
}
if !isRaw && ret.TypeId == VMTypeComputedValue {
ret = ret.ComputedExecute(ctx, detail)
if ctx.Error != nil {
return nil
}
}
return ret
// }
// }
}
func (ctx *Context) LoadNameLocal(name string, isRaw bool) *VMValue {
return ctx.LoadNameLocalWithDetail(name, isRaw, nil)
}
func (ctx *Context) LoadNameWithDetail(name string, isRaw bool, useHook bool, detail *BufferSpan) *VMValue {
if useHook && ctx.Config.HookFuncValueLoad != nil {
var overwrite *VMValue
name, overwrite = ctx.Config.HookFuncValueLoad(ctx, name)
if overwrite != nil {
// 使用弄进来的替代值进行计算
return overwrite
}
}
// 先local再global
curCtx := ctx
for {
ret := curCtx.LoadNameLocalWithDetail(name, isRaw, detail)
if curCtx.Error != nil {
ctx.Error = curCtx.Error
return nil
}
if ret.TypeId != VMTypeNull {
return ret
}
if curCtx.UpCtx == nil {
break
} else {
curCtx = curCtx.UpCtx
}
}
return ctx.LoadNameGlobalWithDetail(name, isRaw, detail)
}
func (ctx *Context) LoadName(name string, isRaw bool, useHook bool) *VMValue {
return ctx.LoadNameWithDetail(name, isRaw, useHook, nil)
}
// StoreName 储存变量
func (ctx *Context) StoreName(name string, v *VMValue, useHook bool) {
if useHook && ctx.Config.HookFuncValueStore != nil {
overwrite, solved := ctx.Config.HookFuncValueStore(ctx, name, v)
if solved {
return
}
if overwrite != nil {
v = overwrite
}
}
if _, ok := ctx.globalNames.Load(name); ok {
ctx.StoreNameGlobal(name, v)
} else {
ctx.StoreNameLocal(name, v)
}
}
func (ctx *Context) StoreNameLocal(name string, v *VMValue) {
ctx.Attrs.Store(name, v)
}
func (ctx *Context) StoreNameGlobal(name string, v *VMValue) {
storeFunc := ctx.GlobalValueStoreFunc
if storeFunc != nil {
storeFunc(name, v)
} else {
ctx.Error = errors.New("未设置 ValueStoreNameFunc,无法储存变量")
return
}
}
func (ctx *Context) RegCustomDice(s string, callback func(ctx *Context, groups []string) *VMValue) error {
// re, err := regexp.Compile(s)
// if err != nil {
// return err
// }
// ctx.CustomDiceInfo = append(ctx.CustomDiceInfo, &customDiceItem{re, callback})
return nil
}
type VMValue struct {
TypeId VMValueType `json:"t"`
Value any `json:"v"`
// ExpiredTime int64 `json:"expiredTime"`
}
type VMDictValue VMValue
type ArrayData struct {
List []*VMValue
}
type DictData struct {
Dict *ValueMap
}
type ComputedData struct {
Expr string
/* 缓存数据 */
Attrs *ValueMap
code []ByteCode
codeIndex int
}
type FunctionData struct {
Expr string
Name string
Params []string
Defaults []*VMValue
/* 缓存数据 */
Self *VMValue // 若存在self,即为bound method
code []ByteCode
codeIndex int
// ctx *Context
}
type NativeFunctionDef func(ctx *Context, this *VMValue, params []*VMValue) *VMValue
type NativeFunctionData struct {
Name string
Params []string
Defaults []*VMValue
/* 缓存数据 */
Self *VMValue // 若存在self,即为bound method
NativeFunc NativeFunctionDef
}
type NativeObjectData struct {
Name string
AttrSet func(ctx *Context, name string, v *VMValue)
AttrGet func(ctx *Context, name string) *VMValue
ItemSet func(ctx *Context, index *VMValue, v *VMValue)
ItemGet func(ctx *Context, index *VMValue) *VMValue
DirFunc func(ctx *Context) []*VMValue
ToString func(ctx *Context) string
}
func (v *VMValue) Clone() *VMValue {
// switch v.TypeId {
// case VMTypeDict, VMTypeArray:
// return v
// default:
return &VMValue{TypeId: v.TypeId, Value: v.Value}
// }
}
func (v *VMValue) AsBool() bool {
switch v.TypeId {
case VMTypeInt:
return v.Value != IntType(0)
case VMTypeFloat:
return v.Value != 0.0
case VMTypeString:
return v.Value != ""
case VMTypeNull:
return false
case VMTypeComputedValue:
vd := v.Value.(*ComputedData)
return vd.Expr != ""
case VMTypeArray:
ad := v.MustReadArray()
return len(ad.List) != 0
case VMTypeDict:
dd := v.MustReadDictData()
return dd.Dict.Length() != 0
case VMTypeFunction, VMTypeNativeFunction, VMTypeNativeObject:
return true
default:
return false
}
}
type recursionInfo struct {
exists map[interface{}]bool
}
func (v *VMValue) ToString() string {
ri := &recursionInfo{exists: map[interface{}]bool{}}
return v.toStringRaw(ri)
}
func (v *VMValue) toStringRaw(ri *recursionInfo) string {
if v == nil {
return "NIL"
}
switch v.TypeId {
case VMTypeInt:
return strconv.FormatInt(int64(v.Value.(IntType)), 10)
case VMTypeFloat:
return strconv.FormatFloat(v.Value.(float64), 'f', -1, 64)
case VMTypeString:
return v.Value.(string)
case VMTypeNull:
return "null"
case VMTypeArray:
// 避免循环重复
if _, exists := ri.exists[v.Value]; exists {
return "[...]"
}
ri.exists[v.Value] = true
s := "["
arr, _ := v.ReadArray()
for index, i := range arr.List {
x := i.toReprRaw(ri)
s += x
if index != len(arr.List)-1 {
s += ", "
}
}
s += "]"
return s
case VMTypeComputedValue:
cd, _ := v.ReadComputed()
return "&(" + cd.Expr + ")"
case VMTypeDict:
// 避免循环重复
if _, exists := ri.exists[v.Value]; exists {
return "{...}"
}
ri.exists[v.Value] = true
var items []string
dd, _ := v.ReadDictData()
dd.Dict.Range(func(key string, value *VMValue) bool {
txt := value.toReprRaw(ri)
// txt := ""
// if value.TypeId == VMTypeArray {
// txt = "[...]"
// } else if value.TypeId == VMTypeDict {
// txt = "{...}"
// } else {
// txt = value.ToRepr()
// }
items = append(items, fmt.Sprintf("'%s': %s", key, txt))
return true
})
return "{" + strings.Join(items, ", ") + "}"
case VMTypeFunction:
cd, _ := v.ReadFunctionData()
return "function " + cd.Name
case VMTypeNativeFunction:
cd, _ := v.ReadNativeFunctionData()
return "nfunction " + cd.Name
case VMTypeNativeObject:
od, _ := v.ReadNativeObjectData()
return "nobject " + od.Name
default:
return "a value"
}
}
func (v *VMValue) toReprRaw(ri *recursionInfo) string {
if v == nil {
return "NIL"
}
switch v.TypeId {
case VMTypeString:
// TODO: 检测其中是否有"
return "'" + v.toStringRaw(ri) + "'"
case VMTypeInt, VMTypeFloat, VMTypeNull, VMTypeArray, VMTypeComputedValue, VMTypeDict, VMTypeFunction, VMTypeNativeFunction, VMTypeNativeObject:
return v.toStringRaw(ri)
default:
return "<a value>"
}
}
func (v *VMValue) ToRepr() string {
ri := &recursionInfo{exists: map[any]bool{}}
return v.toReprRaw(ri)
}
func (v *VMValue) ReadInt() (IntType, bool) {
if v.TypeId == VMTypeInt {
return v.Value.(IntType), true
}
return 0, false
}
func (v *VMValue) ReadFloat() (float64, bool) {
if v.TypeId == VMTypeFloat {
return v.Value.(float64), true
}
return 0, false
}
func (v *VMValue) ReadString() (string, bool) {
if v.TypeId == VMTypeString {
return v.Value.(string), true
}
return "", false
}
func (v *VMValue) ReadArray() (*ArrayData, bool) {
if v.TypeId == VMTypeArray {
return v.Value.(*ArrayData), true
}
return nil, false
}
func (v *VMValue) ReadComputed() (*ComputedData, bool) {
if v.TypeId == VMTypeComputedValue {
return v.Value.(*ComputedData), true
}
return nil, false
}
func (v *VMValue) ReadDictData() (*DictData, bool) {
if v.TypeId == VMTypeDict {
return v.Value.(*DictData), true
}
return nil, false
}
func (v *VMValue) MustReadDictData() *DictData {
if v.TypeId == VMTypeDict {
return v.Value.(*DictData)
}
panic("错误: 不正确的类型")
}
func (v *VMValue) MustReadArray() *ArrayData {
if ad, ok := v.ReadArray(); ok {
return ad
}
panic("错误: 不正确的类型")
}
func (v *VMValue) MustReadInt() IntType {
val, ok := v.ReadInt()
if ok {
return val
}
panic("错误: 不正确的类型")
}
func (v *VMValue) MustReadFloat() float64 {
val, ok := v.ReadFloat()
if ok {
return val
}
panic("错误: 不正确的类型")
}
func (v *VMValue) ReadFunctionData() (*FunctionData, bool) {
if v.TypeId == VMTypeFunction {
return v.Value.(*FunctionData), true
}
return nil, false
}
func (v *VMValue) ReadNativeFunctionData() (*NativeFunctionData, bool) {
if v.TypeId == VMTypeNativeFunction {
return v.Value.(*NativeFunctionData), true
}
return nil, false
}
func (v *VMValue) ReadNativeObjectData() (*NativeObjectData, bool) {
if v.TypeId == VMTypeNativeObject {
return v.Value.(*NativeObjectData), true
}
return nil, false
}
func (v *VMValue) OpAdd(ctx *Context, v2 *VMValue) *VMValue {
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
val := v.Value.(IntType) + v2.Value.(IntType)
return NewIntVal(val)
case VMTypeFloat:
val := float64(v.Value.(IntType)) + v2.Value.(float64)
return NewFloatVal(val)
}
case VMTypeFloat:
switch v2.TypeId {
case VMTypeInt:
val := v.Value.(float64) + float64(v2.Value.(IntType))
return NewFloatVal(val)
case VMTypeFloat:
val := v.Value.(float64) + v2.Value.(float64)
return NewFloatVal(val)
}
case VMTypeString:
switch v2.TypeId {
case VMTypeString:
val := v.Value.(string) + v2.Value.(string)
return NewStrVal(val)
}
case VMTypeArray:
switch v2.TypeId {
case VMTypeArray:
arr, _ := v.ReadArray()
arr2, _ := v2.ReadArray()
length := len(arr.List) + len(arr2.List)
if length > 512 {
ctx.Error = errors.New("不能一次性创建过长的数组")
return nil
}
arrFinal := make([]*VMValue, len(arr.List)+len(arr2.List))
copy(arrFinal, arr.List)
for index, i := range arr2.List {
arrFinal[len(arr.List)+index] = i
}
return NewArrayVal(arrFinal...)
}
}
return nil
}
func (v *VMValue) OpSub(ctx *Context, v2 *VMValue) *VMValue {
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
val := v.Value.(IntType) - v2.Value.(IntType)
return NewIntVal(val)
case VMTypeFloat:
val := float64(v.Value.(IntType)) - v2.Value.(float64)
return NewFloatVal(val)
}
case VMTypeFloat:
switch v2.TypeId {
case VMTypeInt:
val := v.Value.(float64) - float64(v2.Value.(IntType))
return NewFloatVal(val)
case VMTypeFloat:
val := v.Value.(float64) - v2.Value.(float64)
return NewFloatVal(val)
}
}
return nil
}
func (v *VMValue) OpMultiply(ctx *Context, v2 *VMValue) *VMValue {
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
// TODO: 溢出,均未考虑溢出
val := v.Value.(IntType) * v2.Value.(IntType)
return NewIntVal(val)
case VMTypeFloat:
val := float64(v.Value.(IntType)) * v2.Value.(float64)
return NewFloatVal(val)
case VMTypeArray:
return v2.ArrayRepeatTimesEx(ctx, v)
}
case VMTypeFloat:
switch v2.TypeId {
case VMTypeInt:
val := v.Value.(float64) * float64(v2.Value.(IntType))
return NewFloatVal(val)
case VMTypeFloat:
val := v.Value.(float64) * v2.Value.(float64)
return NewFloatVal(val)
}
case VMTypeArray:
return v.ArrayRepeatTimesEx(ctx, v2)
}
return nil
}
func (v *VMValue) OpDivide(ctx *Context, v2 *VMValue) *VMValue {
setDivideZero := func() *VMValue {
if ctx.Config.IgnoreDiv0 {
return v
}
ctx.Error = errors.New("被除数为0")
return nil
}
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
if v2.Value.(IntType) == 0 {
return setDivideZero()
}
val := v.Value.(IntType) / v2.Value.(IntType)
return NewIntVal(val)
case VMTypeFloat:
if v2.Value.(float64) == 0 {
return setDivideZero()
}
val := float64(v.Value.(IntType)) / v2.Value.(float64)
return NewFloatVal(val)
}
case VMTypeFloat:
switch v2.TypeId {
case VMTypeInt:
if v2.Value.(IntType) == 0 {
return setDivideZero()
}
val := v.Value.(float64) / float64(v2.Value.(IntType))
return NewFloatVal(val)
case VMTypeFloat:
if v2.Value.(float64) == 0 {
return setDivideZero()
}
val := v.Value.(float64) / v2.Value.(float64)
return NewFloatVal(val)
}
}
return nil
}
func (v *VMValue) OpModulus(ctx *Context, v2 *VMValue) *VMValue {
setDivideZero := func() {
ctx.Error = errors.New("被除数被0")
}
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
if v2.Value.(IntType) == 0 {
setDivideZero()
return nil
}
val := v.Value.(IntType) % v2.Value.(IntType)
return NewIntVal(val)
}
}
return nil
}
func (v *VMValue) OpPower(ctx *Context, v2 *VMValue) *VMValue {
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
val := IntType(math.Pow(float64(v.Value.(IntType)), float64(v2.Value.(IntType))))
return NewIntVal(val)
case VMTypeFloat:
val := math.Pow(float64(v.Value.(IntType)), v2.Value.(float64))
return NewFloatVal(val)
}
case VMTypeFloat:
switch v2.TypeId {
case VMTypeInt:
val := math.Pow(v.Value.(float64), float64(v2.Value.(IntType)))
return NewFloatVal(val)
case VMTypeFloat:
val := math.Pow(v.Value.(float64), v2.Value.(float64))
return NewFloatVal(val)
}
}
return nil
}
func (v *VMValue) OpNullCoalescing(ctx *Context, v2 *VMValue) *VMValue {
if v.TypeId == VMTypeNull {
return v2
} else {
return v
}
}
func boolToVMValue(v bool) *VMValue {
var val IntType
if v {
val = 1
}
return NewIntVal(val)
}
func (v *VMValue) OpCompLT(ctx *Context, v2 *VMValue) *VMValue {
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
return boolToVMValue(v.Value.(IntType) < v2.Value.(IntType))
case VMTypeFloat:
return boolToVMValue(float64(v.Value.(IntType)) < v2.Value.(float64))
}
case VMTypeFloat:
switch v2.TypeId {
case VMTypeInt:
return boolToVMValue(v.Value.(float64) < float64(v2.Value.(IntType)))
case VMTypeFloat:
return boolToVMValue(v.Value.(float64) < v2.Value.(float64))
}
}
return nil
}
func (v *VMValue) OpCompLE(ctx *Context, v2 *VMValue) *VMValue {
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
return boolToVMValue(v.Value.(IntType) <= v2.Value.(IntType))
case VMTypeFloat:
return boolToVMValue(float64(v.Value.(IntType)) <= v2.Value.(float64))
}
case VMTypeFloat:
switch v2.TypeId {
case VMTypeInt:
return boolToVMValue(v.Value.(float64) <= float64(v2.Value.(IntType)))
case VMTypeFloat:
return boolToVMValue(v.Value.(float64) <= v2.Value.(float64))
}
}
return nil
}
func (v *VMValue) OpCompEQ(ctx *Context, v2 *VMValue) *VMValue {
return boolToVMValue(ValueEqual(v, v2, true))
}
func (v *VMValue) OpCompNE(ctx *Context, v2 *VMValue) *VMValue {
ret := v.OpCompEQ(ctx, v2)
return boolToVMValue(!ret.AsBool())
}
func (v *VMValue) OpCompGE(ctx *Context, v2 *VMValue) *VMValue {
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
return boolToVMValue(v.Value.(IntType) >= v2.Value.(IntType))
case VMTypeFloat:
return boolToVMValue(float64(v.Value.(IntType)) >= v2.Value.(float64))
}
case VMTypeFloat:
switch v2.TypeId {
case VMTypeInt:
return boolToVMValue(v.Value.(float64) >= float64(v2.Value.(IntType)))
case VMTypeFloat:
return boolToVMValue(v.Value.(float64) >= v2.Value.(float64))
}
}
return nil
}
func (v *VMValue) OpCompGT(ctx *Context, v2 *VMValue) *VMValue {
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
return boolToVMValue(v.Value.(IntType) > v2.Value.(IntType))
case VMTypeFloat:
return boolToVMValue(float64(v.Value.(IntType)) > v2.Value.(float64))
}
case VMTypeFloat:
switch v2.TypeId {
case VMTypeInt:
return boolToVMValue(v.Value.(float64) > float64(v2.Value.(IntType)))
case VMTypeFloat:
return boolToVMValue(v.Value.(float64) > v2.Value.(float64))
}
}
return nil
}
func (v *VMValue) OpBitwiseAnd(ctx *Context, v2 *VMValue) *VMValue {
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
return NewIntVal(v.Value.(IntType) & v2.Value.(IntType))
}
}
return nil
}
func (v *VMValue) OpBitwiseOr(ctx *Context, v2 *VMValue) *VMValue {
switch v.TypeId {
case VMTypeInt:
switch v2.TypeId {
case VMTypeInt:
return NewIntVal(v.Value.(IntType) | v2.Value.(IntType))
}
}
return nil
}
func (v *VMValue) OpPositive() *VMValue {
switch v.TypeId {
case VMTypeInt:
return NewIntVal(v.Value.(IntType))
case VMTypeFloat:
return NewFloatVal(v.Value.(float64))
}
return nil
}
func (v *VMValue) OpNegation() *VMValue {
switch v.TypeId {
case VMTypeInt:
return NewIntVal(-v.Value.(IntType))
case VMTypeFloat:
return NewFloatVal(-v.Value.(float64))
}