-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vm.go
458 lines (418 loc) · 11.7 KB
/
vm.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
package vm
import (
"context"
"errors"
"fmt"
"reflect"
"github.com/chyroc/anbko/ast"
"github.com/chyroc/anbko/env"
)
// Options provides options to run VM with
type Options struct {
Debug bool // run in Debug mode
}
type (
// Error is a VM run error.
Error struct {
Message string
Pos ast.Position
}
// runInfo provides run incoming and outgoing information
runInfoStruct struct {
// incoming
ctx context.Context
env *env.Env
options *Options
stmt ast.Stmt
expr ast.Expr
operator ast.Operator
// outgoing
rv reflect.Value
err error
}
)
var (
nilType = reflect.TypeOf(nil)
stringType = reflect.TypeOf("a")
byteType = reflect.TypeOf(byte('a'))
runeType = reflect.TypeOf('a')
interfaceType = reflect.ValueOf([]interface{}{int64(1)}).Index(0).Type()
interfaceSliceType = reflect.TypeOf([]interface{}{})
reflectValueType = reflect.TypeOf(reflect.Value{})
errorType = reflect.ValueOf([]error{nil}).Index(0).Type()
vmErrorType = reflect.TypeOf(&Error{})
contextType = reflect.TypeOf((*context.Context)(nil)).Elem()
nilValue = reflect.New(reflect.TypeOf((*interface{})(nil)).Elem()).Elem()
trueValue = reflect.ValueOf(true)
falseValue = reflect.ValueOf(false)
zeroValue = reflect.Value{}
reflectValueNilValue = reflect.ValueOf(nilValue)
reflectValueErrorNilValue = reflect.ValueOf(reflect.New(errorType).Elem())
errInvalidTypeConversion = fmt.Errorf("invalid type conversion")
// ErrBreak when there is an unexpected break statement
ErrBreak = errors.New("unexpected break statement")
// ErrContinue when there is an unexpected continue statement
ErrContinue = errors.New("unexpected continue statement")
// ErrReturn when there is an unexpected return statement
ErrReturn = errors.New("unexpected return statement")
// ErrInterrupt when execution has been interrupted
ErrInterrupt = errors.New("execution interrupted")
)
// Error returns the VM error message.
func (e *Error) Error() string {
return e.Message
}
// newError makes VM error from error
func newError(pos ast.Pos, err error) error {
if err == nil {
return nil
}
if pos == nil {
return &Error{Message: err.Error(), Pos: ast.Position{Line: 1, Column: 1}}
}
return &Error{Message: err.Error(), Pos: pos.Position()}
}
// newStringError makes VM error from string
func newStringError(pos ast.Pos, err string) error {
if err == "" {
return nil
}
if pos == nil {
return &Error{Message: err, Pos: ast.Position{Line: 1, Column: 1}}
}
return &Error{Message: err, Pos: pos.Position()}
}
// recoverFunc generic recover function
func recoverFunc(runInfo *runInfoStruct) {
recoverInterface := recover()
if recoverInterface == nil {
return
}
switch value := recoverInterface.(type) {
case *Error:
runInfo.err = value
case error:
runInfo.err = value
default:
runInfo.err = fmt.Errorf("%v", recoverInterface)
}
}
func isNil(v reflect.Value) bool {
switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
// from reflect IsNil:
// Note that IsNil is not always equivalent to a regular comparison with nil in Go.
// For example, if v was created by calling ValueOf with an uninitialized interface variable i,
// i==nil will be true but v.IsNil will panic as v will be the zero Value.
return v.IsNil()
default:
return false
}
}
func isNum(v reflect.Value) bool {
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
reflect.Float32, reflect.Float64:
return true
}
return false
}
// equal returns true when lhsV and rhsV is same value.
func equal(lhsV, rhsV reflect.Value) bool {
lhsIsNil, rhsIsNil := isNil(lhsV), isNil(rhsV)
if lhsIsNil && rhsIsNil {
return true
}
if (!lhsIsNil && rhsIsNil) || (lhsIsNil && !rhsIsNil) {
return false
}
if lhsV.Kind() == reflect.Interface || lhsV.Kind() == reflect.Ptr {
lhsV = lhsV.Elem()
}
if rhsV.Kind() == reflect.Interface || rhsV.Kind() == reflect.Ptr {
rhsV = rhsV.Elem()
}
// Compare a string and a number.
// This will attempt to convert the string to a number,
// while leaving the other side alone. Code further
// down takes care of converting ints and floats as needed.
if isNum(lhsV) && rhsV.Kind() == reflect.String {
rhsF, err := tryToFloat64(rhsV)
if err != nil {
// Couldn't convert RHS to a float, they can't be compared.
return false
}
rhsV = reflect.ValueOf(rhsF)
} else if lhsV.Kind() == reflect.String && isNum(rhsV) {
// If the LHS is a string formatted as an int, try that before trying float
lhsI, err := tryToInt64(lhsV)
if err != nil {
// if LHS is a float, e.g. "1.2", we need to set lhsV to a float64
lhsF, err := tryToFloat64(lhsV)
if err != nil {
return false
}
lhsV = reflect.ValueOf(lhsF)
} else {
lhsV = reflect.ValueOf(lhsI)
}
}
if isNum(lhsV) && isNum(rhsV) {
return fmt.Sprintf("%v", lhsV) == fmt.Sprintf("%v", rhsV)
}
// Try to compare bools to strings and numbers
if lhsV.Kind() == reflect.Bool || rhsV.Kind() == reflect.Bool {
lhsB, err := tryToBool(lhsV)
if err != nil {
return false
}
rhsB, err := tryToBool(rhsV)
if err != nil {
return false
}
return lhsB == rhsB
}
return reflect.DeepEqual(lhsV.Interface(), rhsV.Interface())
}
func getMapIndex(key reflect.Value, aMap reflect.Value) reflect.Value {
if aMap.IsNil() {
return nilValue
}
var err error
key, err = convertReflectValueToType(key, aMap.Type().Key())
if err != nil {
return nilValue
}
// From reflect MapIndex:
// It returns the zero Value if key is not found in the map or if v represents a nil map.
value := aMap.MapIndex(key)
if !value.IsValid() {
return nilValue
}
if aMap.Type().Elem() == interfaceType && !value.IsNil() {
value = reflect.ValueOf(value.Interface())
}
return value
}
// appendSlice appends rhs to lhs
// function assumes lhsV and rhsV are slice or array
func appendSlice(expr ast.Expr, lhsV reflect.Value, rhsV reflect.Value) (reflect.Value, error) {
lhsT := lhsV.Type().Elem()
rhsT := rhsV.Type().Elem()
if lhsT == rhsT {
return reflect.AppendSlice(lhsV, rhsV), nil
}
if rhsT.ConvertibleTo(lhsT) {
for i := 0; i < rhsV.Len(); i++ {
lhsV = reflect.Append(lhsV, rhsV.Index(i).Convert(lhsT))
}
return lhsV, nil
}
leftHasSubArray := lhsT.Kind() == reflect.Slice || lhsT.Kind() == reflect.Array
rightHasSubArray := rhsT.Kind() == reflect.Slice || rhsT.Kind() == reflect.Array
if leftHasSubArray != rightHasSubArray && lhsT != interfaceType && rhsT != interfaceType {
return nilValue, newStringError(expr, "invalid type conversion")
}
if !leftHasSubArray && !rightHasSubArray {
for i := 0; i < rhsV.Len(); i++ {
value := rhsV.Index(i)
if rhsT == interfaceType {
value = value.Elem()
}
if lhsT == value.Type() {
lhsV = reflect.Append(lhsV, value)
} else if value.Type().ConvertibleTo(lhsT) {
lhsV = reflect.Append(lhsV, value.Convert(lhsT))
} else {
return nilValue, newStringError(expr, "invalid type conversion")
}
}
return lhsV, nil
}
if (leftHasSubArray || lhsT == interfaceType) && (rightHasSubArray || rhsT == interfaceType) {
for i := 0; i < rhsV.Len(); i++ {
value := rhsV.Index(i)
if rhsT == interfaceType {
value = value.Elem()
if value.Kind() != reflect.Slice && value.Kind() != reflect.Array {
return nilValue, newStringError(expr, "invalid type conversion")
}
}
newSlice, err := appendSlice(expr, reflect.MakeSlice(lhsT, 0, value.Len()), value)
if err != nil {
return nilValue, err
}
lhsV = reflect.Append(lhsV, newSlice)
}
return lhsV, nil
}
return nilValue, newStringError(expr, "invalid type conversion")
}
func makeType(runInfo *runInfoStruct, typeStruct *ast.TypeStruct) reflect.Type {
switch typeStruct.Kind {
case ast.TypeDefault:
return getTypeFromEnv(runInfo, typeStruct)
case ast.TypePtr:
var t reflect.Type
if typeStruct.SubType != nil {
t = makeType(runInfo, typeStruct.SubType)
} else {
t = getTypeFromEnv(runInfo, typeStruct)
}
if runInfo.err != nil {
return nil
}
if t == nil {
return nil
}
return reflect.PtrTo(t)
case ast.TypeSlice:
var t reflect.Type
if typeStruct.SubType != nil {
t = makeType(runInfo, typeStruct.SubType)
} else {
t = getTypeFromEnv(runInfo, typeStruct)
}
if runInfo.err != nil {
return nil
}
if t == nil {
return nil
}
for i := 1; i < typeStruct.Dimensions; i++ {
t = reflect.SliceOf(t)
}
return reflect.SliceOf(t)
case ast.TypeMap:
key := makeType(runInfo, typeStruct.Key)
if runInfo.err != nil {
return nil
}
if key == nil {
return nil
}
t := makeType(runInfo, typeStruct.SubType)
if runInfo.err != nil {
return nil
}
if t == nil {
return nil
}
if !runInfo.options.Debug {
// captures panic
defer recoverFunc(runInfo)
}
t = reflect.MapOf(key, t)
return t
case ast.TypeChan:
var t reflect.Type
if typeStruct.SubType != nil {
t = makeType(runInfo, typeStruct.SubType)
} else {
t = getTypeFromEnv(runInfo, typeStruct)
}
if runInfo.err != nil {
return nil
}
if t == nil {
return nil
}
return reflect.ChanOf(reflect.BothDir, t)
case ast.TypeStructType:
var t reflect.Type
fields := make([]reflect.StructField, 0, len(typeStruct.StructNames))
for i := 0; i < len(typeStruct.StructNames); i++ {
t = makeType(runInfo, typeStruct.StructTypes[i])
if runInfo.err != nil {
return nil
}
if t == nil {
return nil
}
fields = append(fields, reflect.StructField{Name: typeStruct.StructNames[i], Type: t})
}
if !runInfo.options.Debug {
// captures panic
defer recoverFunc(runInfo)
}
t = reflect.StructOf(fields)
return t
default:
runInfo.err = fmt.Errorf("unknown kind")
return nil
}
}
func getTypeFromEnv(runInfo *runInfoStruct, typeStruct *ast.TypeStruct) reflect.Type {
var e *env.Env
e, runInfo.err = runInfo.env.GetEnvFromPath(typeStruct.Env)
if runInfo.err != nil {
return nil
}
var t reflect.Type
t, runInfo.err = e.Type(typeStruct.Name)
return t
}
func makeValue(t reflect.Type) (reflect.Value, error) {
switch t.Kind() {
case reflect.Chan:
return reflect.MakeChan(t, 0), nil
case reflect.Func:
return reflect.MakeFunc(t, nil), nil
case reflect.Map:
// note creating slice as work around to create map
// just doing MakeMap can give incorrect type for defined types
value := reflect.MakeSlice(reflect.SliceOf(t), 0, 1)
value = reflect.Append(value, reflect.MakeMap(reflect.MapOf(t.Key(), t.Elem())))
return value.Index(0), nil
case reflect.Ptr:
ptrV := reflect.New(t.Elem())
v, err := makeValue(t.Elem())
if err != nil {
return nilValue, err
}
ptrV.Elem().Set(v)
return ptrV, nil
case reflect.Slice:
return reflect.MakeSlice(t, 0, 0), nil
case reflect.Struct:
structV := reflect.New(t).Elem()
for i := 0; i < structV.NumField(); i++ {
if structV.Field(i).Kind() == reflect.Ptr {
continue
}
v, err := makeValue(structV.Field(i).Type())
if err != nil {
return nilValue, err
}
if structV.Field(i).CanSet() {
structV.Field(i).Set(v)
}
}
return structV, nil
}
return reflect.New(t).Elem(), nil
}
// precedenceOfKinds returns the greater of two kinds
// string > float > int
func precedenceOfKinds(kind1 reflect.Kind, kind2 reflect.Kind) reflect.Kind {
if kind1 == kind2 {
return kind1
}
switch kind1 {
case reflect.String:
return kind1
case reflect.Float64, reflect.Float32:
switch kind2 {
case reflect.String:
return kind2
}
return kind1
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
switch kind2 {
case reflect.String, reflect.Float64, reflect.Float32:
return kind2
}
}
return kind1
}