-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
vm.go
1708 lines (1430 loc) · 42.8 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
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 vm implements a simple stack-based virtual machine.
//
// We're constructed with a set of opcodes, and we process those forever,
// or until we hit a `return` statement which terminates the program.
//
// As well as a series of opcodes to execute we're also given a set
// of constants to work with. These are loaded to the stack on-demand,
// so they can be manipulated.
package vm
import (
"context"
"encoding/binary"
"fmt"
"math"
"reflect"
"strings"
"time"
"unicode/utf8"
"github.com/skx/evalfilter/v2/code"
"github.com/skx/evalfilter/v2/environment"
"github.com/skx/evalfilter/v2/object"
"github.com/skx/evalfilter/v2/stack"
)
// BytecodeVisitor is the function-signature of the callbackup function which
// can be invoked to iterate over our generated bytecode.
//
// The callback function can be used via the `WalkBytecode` method, and the
// return values should make sense: If there is an error then that is returned
// otherwise the bool-value will control whether the iteration continues,
// return true to keep walking, and false to abort the process.
type BytecodeVisitor func(offset int, instruction code.Opcode, argument interface{}) (bool, error)
// True is our global "true" object.
var True = &object.Boolean{Value: true}
// False is our global "false" object.
var False = &object.Boolean{Value: false}
// Null is our global "null" object.
var Null = &object.Null{}
// Void is our global "void" object.
var Void = &object.Void{}
// VM is the structure which holds our state.
type VM struct {
// bytecode contains the actual series of instructions we'll execute.
bytecode code.Instructions
// constants is an array holding constants which were found in
// the script-source. These constants include string-literals,
// numeric-literals, boolean values as well as variable names, the
// names of functions, and references to object/map values.
//
// constants are treated as atoms, so they are unique.
constants []object.Object
// context is passed to us from our evalfilter, and can be
// used by callers to implement timeouts.
context context.Context
// debug can be enabled to dump our execution-log as we run.
debug bool
// environment holds the environment, which will allow variables
// and functions to be get/set.
environment *environment.Environment
// fields contains the contents of all the fields in the object
// or map we're executing against. We discover these via reflection
// at run-time.
//
// Reflection is slow so the map here is used as a cache, avoiding
// the need to reparse the same object multiple times.
fields map[string]object.Object
// functions that are defined in our scripting language
functions map[string]environment.UserFunction
// stack holds a pointer to our stack-object.
//
// We're a stack-based virtual machine so this is used for
// much of our internal implementation.
stack *stack.Stack
}
// New constructs a new virtual machine.
//
// If the value `OPTIMIZE` exists inside the environment we're passed
// we'll also run a series of simple optimizer steps. These are naive,
// but do speedup carefully constructed test cases.
func New(constants []object.Object, bytecode code.Instructions, functions map[string]environment.UserFunction, env *environment.Environment) *VM {
// If we have a `DEBUG` environment then we enable debugging.
_, debug := env.Get("DEBUG")
// If we have "OPTIMIZE" set then we optimize our bytecode.
//
// We don't need to store this flag anywhere, we'll just run
// the optimizer immediately.
_, optimize := env.Get("OPTIMIZE")
// Create the machine
vm := &VM{
bytecode: bytecode,
constants: constants,
debug: debug,
environment: env,
functions: functions,
stack: stack.New(),
}
// Set a default context
ctx := context.Background()
vm.SetContext(ctx)
// Optimize the bytecode, if we should.
if optimize {
// Run the optimization, which will return the
// number of bytecode instructions "saved" or
// reduced/removed.
vm.optimizeBytecode()
//
// Now functions
//
tmp := make(map[string]environment.UserFunction)
for name, fun := range functions {
// Save the main bytecode away
safe := vm.bytecode
// Replace it with the bytecode from the function
vm.bytecode = fun.Bytecode
// Tweak it
saved := vm.optimizeBytecode()
if debug && optimize {
fmt.Printf("Bytecode optimizer saved %d bytes for function %s\n", saved, name)
}
// Save it away
fun.Bytecode = vm.bytecode
tmp[name] = fun
// And reset the saved vm-bytecode
vm.bytecode = safe
}
vm.functions = tmp
}
return vm
}
// SetContext allows a context to be used as our virtual machine is
// running. This is most used to allow our caller to setup a
// timeout/deadline which will avoid denial-of-service problems if
// user-supplied script(s) contain infinite loops.
func (vm *VM) SetContext(ctx context.Context) {
vm.context = ctx
}
// Run launches our virtual machine, interpreting the bytecode-program we were
// constructed with.
//
// We terminate when we hit a return-operation, or if we ever hit the end of
// the supplied bytecode. As programs can contain flow-control operation
// it is certainly possible they will never return.
//
// (Our compiler only implements the 'while' loop for control-flow, but it
// is possible a hand-created program could build such a things via the
// instruction-set.)
func (vm *VM) Run(obj interface{}) (object.Object, error) {
//
// Sanity-check the bytecode program is non-empty
//
if len(vm.bytecode) < 1 {
return nil, fmt.Errorf("the bytecode program is empty")
}
//
// Make an empty map to store field/map contents.
//
vm.fields = make(map[string]object.Object)
//
// When built-in functions are invoked their return value is stored
// upon the stack. Usually this is OK because the return value will
// be used for something, and thus popped-off.
//
// However it is possible that user-added functions place their
// return value upon the stack, where it is never used. This will
// cause the stack to needlessly grow, so we ensure that we
// reset it between runs here to avoid unbounded growth.
//
// (This used to be the case with the built-in functions `print`
// and `printf`. They would always store a value upon the stack
// which no user would ever test/use/care-about. This was resolved
// via the addition of the &object.Void{} type. However we
// cannot assume everybody remember to use that.)
//
vm.stack.Clear()
//
// Instruction pointer and length of bytecode.
//
ip := 0
ln := len(vm.bytecode)
//
// Loop over all the bytecode.
//
// NOTE: Our instruction-set supports control-flow, so it
// is possible this function will run forever, and never terminate.
// This is why we allow `SetContext` to setup a timeout-period.
//
for ip < ln {
//
// We've been given a context, which we'll test at every
// iteration of our main-loop.
//
// This is a little slow and inefficient, but we need
// to allow our execution to be time-limited.
//
select {
case <-vm.context.Done():
return &object.Null{},
fmt.Errorf("timeout during execution")
default:
// nop
}
//
// Get the next opcode
//
op := code.Opcode(vm.bytecode[ip])
//
// Find out how long it is.
//
opLen := code.Length(op)
//
// If the opcode is more than a single byte long
// we read the argument here.
//
opArg := 0
if opLen > 1 {
//
// Note in the future we might have to cope
// with opcodes with more than a single argument,
// and they might be different sizes.
//
opArg = int(binary.BigEndian.Uint16(vm.bytecode[ip+1 : ip+3]))
}
if vm.debug {
fmt.Printf("\n\tStack: [%s]\n",
strings.Join(vm.stack.Export(), ", "))
if opLen > 1 {
fmt.Printf("%04d\t%s\t%04d\n", ip, code.String(op), opArg)
} else {
fmt.Printf("%04d\t%s\n", ip, code.String(op))
}
}
switch op {
// NOP
case code.OpNop:
// NOP should only be seen if we're running
// an unoptimized / partially optimized program.
// Store an integer upon the stack
case code.OpPush:
vm.stack.Push(&object.Integer{Value: int64(opArg)})
// Lookup variable/field, by name
case code.OpConstant:
if opArg >= len(vm.constants) {
return nil, fmt.Errorf("access to constant which doesn't exist")
}
// move the contents of a constant onto the stack
vm.stack.Push(vm.constants[opArg])
// Lookup variable/field, by name
case code.OpLookup:
if opArg >= len(vm.constants) {
return nil, fmt.Errorf("access to constant which doesn't exist")
}
// Get the name.
name := vm.constants[opArg].Inspect()
// Lookup the value.
val := vm.lookup(obj, name)
vm.stack.Push(val)
// Setup a local variable, by name
case code.OpLocal:
name, err := vm.stack.Pop()
if err != nil {
return nil, err
}
// now set the value
vm.environment.SetLocal(name.Inspect(), Null)
// Set a variable by name
case code.OpSet:
var name object.Object
var val object.Object
var err error
name, err = vm.stack.Pop()
if err != nil {
return nil, err
}
val, err = vm.stack.Pop()
if err != nil {
return nil, err
}
vm.environment.Set(name.Inspect(), val)
// maths & comparisons
case code.OpAdd, // addition
code.OpSub, // subtraction
code.OpMul, // multiplication
code.OpDiv, // division
code.OpMod, // modulus
code.OpPower, // power
code.OpLess, // comparison: <
code.OpLessEqual, // comparison: <=
code.OpGreater, // comparison: >
code.OpGreaterEqual, // comparison: >=
code.OpEqual, // comparison: ==
code.OpNotEqual, // comparison: !=
code.OpMatches, // regexp match
code.OpNotMatches, // regexp negative match
code.OpAnd, // logical AND
code.OpOr, // logical OR
code.OpArrayIn: // array membership test
// Run the test, error gets returned, otherwise
// we're done.
err := vm.executeBinaryOperation(op)
if err != nil {
return nil, err
}
// Store an array
case code.OpArray:
// The argument contains the number of
// array elements we're going to expect
// to be present upon the stack.
// Make the array of the appropriate size
elements := make([]object.Object, opArg)
// Add on each entry.
for opArg > 0 {
var err error
elements[opArg-1], err = vm.stack.Pop()
if err != nil {
return nil, err
}
opArg--
}
// Construct the actual array and add to the stack
arr := &object.Array{Elements: elements}
vm.stack.Push(arr)
// Store a hash
case code.OpHash:
hashedPairs := make(map[object.HashKey]object.HashPair)
for i := 0; i < opArg; i += 2 {
value, err := vm.stack.Pop()
if err != nil {
return nil, err
}
key, err := vm.stack.Pop()
if err != nil {
return nil, err
}
pair := object.HashPair{Key: key, Value: value}
hashKey, ok := key.(object.Hashable)
if !ok {
return nil, fmt.Errorf("unusable as hash key: %s", key.Type())
}
hashedPairs[hashKey.HashKey()] = pair
}
hash := &object.Hash{Pairs: hashedPairs}
vm.stack.Push(hash)
// Case statement
case code.OpCase:
caseVal, err := vm.stack.Pop()
if err != nil {
return nil, err
}
val, err := vm.stack.Pop()
if err != nil {
return nil, err
}
// Is this a literal match
if val.Type() == caseVal.Type() &&
(val.Inspect() == caseVal.Inspect()) {
vm.stack.Push(True)
} else if caseVal.Type() == object.REGEXP {
// Horrid - invoke Matches() to run the test.
args := []object.Object{val, caseVal}
fn, ok := vm.environment.GetFunction("match")
if !ok {
return nil, fmt.Errorf("failed to lookup match-function")
}
out := fn.(func(args []object.Object) object.Object)
ret := out(args)
vm.stack.Push(ret)
} else {
vm.stack.Push(False)
}
// Array/String index
case code.OpIndex:
index, err := vm.stack.Pop()
if err != nil {
return nil, err
}
left, err := vm.stack.Pop()
if err != nil {
return nil, err
}
err = vm.executeIndexExpression(left, index)
if err != nil {
return nil, err
}
// !true -> false
case code.OpBang:
err := vm.executeBangOperator()
if err != nil {
return nil, err
}
// -1
case code.OpMinus:
err := vm.executeMinusOperator()
if err != nil {
return nil, err
}
// square root
case code.OpSquareRoot:
err := vm.executeSquareRoot()
if err != nil {
return nil, err
}
// Boolean literal
case code.OpTrue:
vm.stack.Push(True)
case code.OpVoid:
vm.stack.Push(Void)
// Boolean literal
case code.OpFalse:
vm.stack.Push(False)
// return from script
case code.OpReturn:
result, err := vm.stack.Pop()
return result, err
// flow-control: unconditional jump
case code.OpJump:
// NOTE: We reduce the offset, because
// at the end of our loop we increment
// it again..
ip = opArg - opLen
if opArg >= len(vm.bytecode) {
return nil, fmt.Errorf("instruction pointer is out of bounds")
}
// flow-control: jump if stack contains non-true
case code.OpJumpIfFalse:
condition, err := vm.stack.Pop()
if err != nil {
return nil, err
}
// If the condition evaluated to a non-true
// then we change the IP.
if !condition.True() {
// NOTE: We reduce the offset, because
// at the end of our loop we increment
// it again..
ip = opArg - opLen
if opArg >= len(vm.bytecode) {
return nil, fmt.Errorf("instruction pointer is out of bounds")
}
}
// function-call: This is messy.
//
// Handles builtins and user-defined functions.
case code.OpCall:
// The OpCall instruction is followed by an
// argument describing the number of args the
// function we're calling should be invoked with.
// get the name of the function from the stack.
fName, err := vm.stack.Pop()
if err != nil {
return nil, err
}
name := fName.Inspect()
//
// The argument to the call-instruction is the
// number of arguments to pass to the function
// we're to invoke.
//
// Of course these are in reverse.
//
// Create an array and pop each stack-argument
// off into the correct location.
//
fnArgs := make([]object.Object, opArg)
for opArg > 0 {
fnArgs[opArg-1], err = vm.stack.Pop()
if err != nil {
return nil, fmt.Errorf("attempting to call function %s failed - %s", name, err.Error())
}
opArg--
}
// Get the function we're to invoke.
fn, ok := vm.environment.GetFunction(name)
if ok {
// Cast the function & call it
out := fn.(func(args []object.Object) object.Object)
ret := out(fnArgs)
// store the result back on the stack - unless
// it's a weird one.
if ret.Type() != object.VOID {
vm.stack.Push(ret)
}
break
}
// Function isn't a built-in, so now we need to see
// if it is a user-defined function.
val, ok2 := vm.functions[name]
if !ok2 {
return nil, fmt.Errorf("the function %s does not exist", name)
}
// Save IP + bytecode
oldIP := ip
oldBytecode := vm.bytecode
oldStack := vm.stack
vm.stack = stack.New()
vm.environment.AddScope()
// switch so that we're interpreting the bytecode
// of the compiled function-body.
vm.bytecode = val.Bytecode
// Sanity-check we have enough arguments
if len(val.Arguments) != len(fnArgs) {
return nil, fmt.Errorf("mismatch in argument-counts for %s, expected %d but got %d", name, len(val.Arguments), len(fnArgs))
}
// Now for each arg we set the value
for i, name := range val.Arguments {
vm.environment.SetLocal(name, fnArgs[i])
}
// Run ourselves against that new bytecode.
//
// This is a bit horrid.
out, err := vm.Run(obj)
// Did we get an error? If so return it
if err != nil {
return nil, err
}
// Otherwise we're going to keep running from
// where we left off - resetting the state of
// our stack, instruction-pointer, and bytecode.
ip = oldIP
vm.bytecode = oldBytecode
vm.stack = oldStack
// Put the return-value on the stack
if out.Type() != object.VOID {
vm.stack.Push(out)
}
// Drop the scope which means function-arguments
// are dropped.
err = vm.environment.RemoveScope()
if err != nil {
return nil, err
}
// reset the state of an object which is to be iterated upon
case code.OpIterationReset:
// Create a scoped environment
vm.environment.AddScope()
// get object we're iterating over..
out, err := vm.stack.Pop()
if err != nil {
return nil, err
}
// Cast it to the interface.
helper, ok := out.(object.Iterable)
if !ok {
return nil, fmt.Errorf("%s object doesn't implement the Iterable interface", out.Type())
}
// Reset it, and place back upon the stack.
helper.Reset()
vm.stack.Push(out)
// Iterate over an object that implements the Iterable interface.
case code.OpIterationNext:
//
// There should be three values on the stack
//
// variable name
// index name
// item
//
varName, err := vm.stack.Pop()
if err != nil {
return nil, err
}
idxName, err := vm.stack.Pop()
if err != nil {
return nil, err
}
obj, err := vm.stack.Pop()
if err != nil {
return nil, err
}
// Ensure that it is an iterable thing.
helper, ok := obj.(object.Iterable)
if !ok {
return nil, fmt.Errorf("%s object doesn't implement the Iterable interface", obj.Type())
}
// Get the next value, it's index, and a
// success/fail result.
ret, idx, ok := helper.Next()
if ok {
// Set the index + name
vm.environment.SetLocal(varName.Inspect(), ret)
idxName := idxName.Inspect()
if idxName != "" {
vm.environment.SetLocal(idxName, idx)
}
// Push the iterable object back upon the
// stack for the next loop.
vm.stack.Push(obj)
// And also push `True` so our loop will
// continue.
vm.stack.Push(True)
} else {
// The iteration is over.
//
// So next time we'll fall-through to after
// the foreach-loop.
//
vm.stack.Push(False)
// Remove our scoped environment now to
// discard the name/index values that
// might have been set.
err := vm.environment.RemoveScope()
if err != nil {
return nil, err
}
}
// Create an array of numbers.
case code.OpRange:
var min object.Object
var max object.Object
var err error
max, err = vm.stack.Pop()
if err != nil {
return nil, err
}
min, err = vm.stack.Pop()
if err != nil {
return nil, err
}
if min.Type() != object.INTEGER {
return nil, fmt.Errorf("argument for the start of the range must be an integer")
}
if max.Type() != object.INTEGER {
return nil, fmt.Errorf("argument for the end of the range must be an integer")
}
// The actual min/max values we're going to range over.
minI := min.(*object.Integer).Value
maxI := max.(*object.Integer).Value
if minI > maxI {
return nil, fmt.Errorf("the start of a range must be smaller than the end")
}
// length
l := maxI - minI + 1
// holder for elements of the correct size
elements := make([]object.Object, l)
// Make the array
var i int64
i = 0
for i < l {
elements[i] = &object.Integer{Value: minI + i}
i++
}
// Now store the elements
arr := &object.Array{Elements: elements}
vm.stack.Push(arr)
// Increment the value of an object, by name, if the Increment
// interface is implemented by it.
case code.OpInc:
if opArg >= len(vm.constants) {
return nil, fmt.Errorf("access to constant which doesn't exist")
}
// Get the name of the variable whos' contents
// we should increment.
name := vm.constants[opArg].Inspect()
// Lookup the current value of that object.
val := vm.lookup(obj, name)
// Can we use our interface?
helper, ok := val.(object.Increment)
if !ok {
return nil, fmt.Errorf("%s object doesn't implement the Increment() interface", val.Type())
}
// Mutate & store
helper.Increase()
vm.environment.Set(name, val)
// OpInc follows OpLookup, so we can drop the value we were given
_, err := vm.stack.Pop()
if err != nil {
return nil, err
}
// Decrement the value of an object, by name, if the Decrement
// interface is implemented by it.
case code.OpDec:
if opArg >= len(vm.constants) {
return nil, fmt.Errorf("access to constant which doesn't exist")
}
// Get the name of the variable whos' contents
// we should decrement.
name := vm.constants[opArg].Inspect()
// Lookup the current value of that object.
val := vm.lookup(obj, name)
// Can we use our interface?
helper, ok := val.(object.Decrement)
if !ok {
return nil, fmt.Errorf("%s object doesn't implement the Decrement() interface", val.Type())
}
// Mutate & store
helper.Decrease()
vm.environment.Set(name, val)
// OpDec follows OpLookup, so we can drop the value we were given
_, err := vm.stack.Pop()
if err != nil {
return nil, err
}
// NOP
case code.OpPlaceholder:
// Unknown opcode
default:
return nil, fmt.Errorf("unhandled opcode: %v %s", op, code.String(op))
}
ip += opLen
}
//
// If we get here we've hit the end of the bytecode, and we
// didn't encounter a return-instruction.
//
// In the case where a user is running the script as a filter
// then a missing return code is probably going to be treated
// as a "false" return. But the caller can decide that.
//
return Null, nil
}
// inspectObject discovers the names/values of all structure fields, or
// map contents.
//
// This method is called the first time any reference is made to a field
// value - which means we don't eat the cost unless we need it, and we
// don't have to call reflection more than once. (Reflection is s-l-o-w.)
func (vm *VM) inspectObject(obj interface{}) {
//
// If the reference is nil we have nothing to walk.
//
if obj == nil {
return
}
//
// Get the value, be it a "thing", or a pointer to a thing.
//
val := reflect.Indirect(reflect.ValueOf(obj))
//
// Is this a map?
//
if val.Kind() == reflect.Map {
//
// Get all keys in the map.
//
for _, key := range val.MapKeys() {
// The name of the key.
name := key.Interface().(string)
// The actual thing inside it
field := val.MapIndex(key).Elem()
// Convert to an object
ret := vm.primitiveToObject(field)
// Store it in our map
vm.fields[name] = ret
}
return
}
//
// OK this is an object, so we walk over the fields within it.
//
for i := 0; i < val.NumField(); i++ {
// Get the field
field := val.Field(i)
// Get the name
typeField := val.Type().Field(i)
name := typeField.Name
// Convert the value to one of our objects
ret := vm.primitiveToObject(field)
// Store it in our map
vm.fields[name] = ret
}
}
// convert a primitive into one of our internal objects.
func (vm *VM) primitiveToObject(field reflect.Value) object.Object {
var ret object.Object
//
// Time gets special handling
//
timeKind := reflect.TypeOf(time.Time{}).Kind()
//
// Invalid value? Return null
//
if !field.IsValid() {
return &object.Null{}
}
switch field.Kind() {
case reflect.Map:
ret = vm.createHash(field)
case reflect.Slice:
ret = vm.createArrayFromSlice(field)
case reflect.Int, reflect.Int64:
ret = &object.Integer{Value: field.Int()}
case reflect.Float32, reflect.Float64:
ret = &object.Float{Value: field.Float()}
case reflect.String:
ret = &object.String{Value: field.String()}
case reflect.Bool:
ret = &object.Boolean{Value: field.Bool()}
case timeKind:
time, ok := field.Interface().(time.Time)
if ok {
ret = &object.Integer{Value: time.Unix()}
}
default:
fmt.Printf("Failed to reflect on %T\n", field.Interface())
}
return ret
}
// create one of our internal hash-objects via reflection.
//
// This may well recurse.
func (vm *VM) createHash(field reflect.Value) object.Object {
hashedPairs := make(map[object.HashKey]object.HashPair)
for _, key := range field.MapKeys() {
// Get the key value - note this supports way more
// than we allow here. (As not all of our objects
// can be used as hash-keys.)
k := vm.primitiveToObject(key)
// The actual thing inside it.
val := field.MapIndex(key).Elem()
// Get the value.
v := vm.primitiveToObject(val)
pair := object.HashPair{Key: k, Value: v}
hashedPairs[k.(object.Hashable).HashKey()] = pair
}
return &object.Hash{Pairs: hashedPairs}