forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
values.go
2384 lines (2224 loc) · 54.3 KB
/
values.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 gno
import (
"encoding/binary"
"fmt"
"math/big"
"reflect"
"strconv"
"strings"
"unsafe"
"github.com/gnolang/gno/pkgs/crypto"
)
//----------------------------------------
// (runtime) Value
type Value interface {
assertValue()
String() string // for debugging
}
// Fixed size primitive types are represented in TypedValue.N
// for performance.
func (StringValue) assertValue() {}
func (BigintValue) assertValue() {}
func (DataByteValue) assertValue() {}
func (PointerValue) assertValue() {}
func (*ArrayValue) assertValue() {}
func (*SliceValue) assertValue() {}
func (*StructValue) assertValue() {}
func (*FuncValue) assertValue() {}
func (*MapValue) assertValue() {}
func (*BoundMethodValue) assertValue() {}
func (TypeValue) assertValue() {}
func (*PackageValue) assertValue() {}
func (*NativeValue) assertValue() {}
func (*Block) assertValue() {}
func (RefValue) assertValue() {}
var (
_ Value = StringValue("")
_ Value = BigintValue{}
_ Value = DataByteValue{}
_ Value = PointerValue{}
_ Value = &ArrayValue{} // TODO doesn't have to be pointer?
_ Value = &SliceValue{} // TODO doesn't have to be pointer?
_ Value = &StructValue{}
_ Value = &FuncValue{}
_ Value = &MapValue{}
_ Value = &BoundMethodValue{}
_ Value = TypeValue{}
_ Value = &PackageValue{}
_ Value = &NativeValue{}
_ Value = &Block{}
_ Value = RefValue{}
)
type StringValue string
type BigintValue struct {
V *big.Int
}
func (bv BigintValue) MarshalAmino() (string, error) {
bz, err := bv.V.MarshalText()
if err != nil {
return "", err
}
return string(bz), nil
}
func (bv *BigintValue) UnmarshalAmino(s string) error {
vv := big.NewInt(0)
err := vv.UnmarshalText([]byte(s))
if err != nil {
return err
}
bv.V = vv
return nil
}
func (bv BigintValue) Copy(alloc *Allocator) BigintValue {
return BigintValue{V: big.NewInt(0).Set(bv.V)}
}
type DataByteValue struct {
Base *ArrayValue // base array.
Index int // base.Data index.
ElemType Type // is Uint8Kind.
}
func (dbv DataByteValue) GetByte() byte {
return dbv.Base.Data[dbv.Index]
}
func (dbv DataByteValue) SetByte(b byte) {
dbv.Base.Data[dbv.Index] = b
}
// Base is set if the pointer refers to an array index or
// struct field or block var.
// A pointer constructed via a &x{} composite lit
// expression or constructed via new() or make() are
// independent objects, and have nil Base.
// A pointer to a block var may end up pointing to an escape
// value after a block var escapes "to the heap".
// *(PointerValue.TypedValue) must have already become
// initialized, namely T set if a typed-nil.
// Index is -1 for the shared "_" block var,
// and -2 for (gno and native) map items.
//
// Allocation for PointerValue is not immediate,
// as usually PointerValues are temporary for assignment
// or binary operations. When a pointer is to be
// allocated, *Allocator.AllocatePointer() is called separately,
// as in OpRef.
type PointerValue struct {
TV *TypedValue // escape val if pointer to var.
Base Value // array/struct/block.
Index int // list/fields/values index, or -1 or -2 (see below).
Key *TypedValue `json:",omitempty"` // for maps.
}
const (
PointerIndexBlockBlank = -1 // for the "_" identifier in blocks
PointerIndexMap = -2 // Base is Map, use Key.
PointerIndexNative = -3 // Base is *NativeValue.
)
/*
func (pv *PointerValue) GetBase(store Store) Object {
switch cbase := pv.Base.(type) {
case nil:
return nil
case RefValue:
base := store.GetObject(cbase.ObjectID).(Object)
pv.Base = base
return base
case Object:
return cbase
default:
panic("should not happen")
}
}
*/
// cu: convert untyped; pass false for const definitions
// TODO: document as something that enables into-native assignment.
// TODO: maybe consider this as entrypoint for DataByteValue too?
func (pv PointerValue) Assign2(alloc *Allocator, store Store, rlm *Realm, tv2 TypedValue, cu bool) {
// Special cases.
if pv.Index == PointerIndexNative {
// Special case if extended object && native.
rv := pv.Base.(*NativeValue).Value
if rv.Kind() == reflect.Map { // go native object
// assign value to map directly.
krv := gno2GoValue(pv.Key, reflect.Value{})
vrv := gno2GoValue(&tv2, reflect.Value{})
rv.SetMapIndex(krv, vrv)
} else {
// assign depending on pv.TV type.
tv := pv.TV
nv1 := tv.V.(*NativeValue)
switch v2 := tv2.V.(type) {
case PointerValue:
if tv.T.Kind() != PointerKind {
panic("should not happen")
}
if nv2, ok := v2.TV.V.(*NativeValue); ok {
nrv2 := nv2.Value
if nrv2.CanAddr() {
it := nrv2.Addr()
nv1.Value.Set(it)
} else {
panic("not yet implemented")
}
} else {
panic("not yet implemented")
}
case *NativeValue:
if tv.V == nil {
// tv.V is a native function type.
// there is no default value, so just assign
// rather than .Value.Set().
if tv.T.Kind() == FuncKind {
if debug {
if tv2.T.Kind() != FuncKind {
panic("should not happen")
}
if nv, ok := tv2.V.(*NativeValue); !ok ||
nv.Value.Kind() != reflect.Func {
panic("should not happen")
}
}
tv.V = v2
} else {
tv.V = defaultValue(alloc, tv.T)
tv.V.(*NativeValue).Value.Set(v2.Value)
}
} else {
nv1.Value.Set(v2.Value)
}
case nil:
if debug {
if tv2.T != nil && tv.T.TypeID() != tv2.T.TypeID() {
panic(fmt.Sprintf("mismatched types: cannot assign %v to %v",
tv2.String(), tv.T.String()))
}
}
*tv = tv2.Copy(alloc)
default:
panic("should not happen")
}
}
return
} else if pv.TV.T == DataByteType {
// Special case of DataByte into (base=*SliceValue).Data.
pv.TV.SetDataByte(tv2.GetUint8())
return
}
// General case
if rlm != nil && pv.Base != nil {
oo1 := pv.TV.GetFirstObject(store)
pv.TV.Assign(alloc, tv2, cu)
oo2 := pv.TV.GetFirstObject(store)
rlm.DidUpdate(pv.Base.(Object), oo1, oo2)
} else {
pv.TV.Assign(alloc, tv2, cu)
}
}
func (pv PointerValue) Deref() (tv TypedValue) {
if pv.TV.T == DataByteType {
dbv := pv.TV.V.(DataByteValue)
tv.T = dbv.ElemType
tv.SetUint8(dbv.GetByte())
return
} else if nv, ok := pv.TV.V.(*NativeValue); ok {
rv := nv.Value
// XXX memoize type.
tv.T = &NativeType{Type: rv.Type()}
tv.V = nv
return
} else {
tv = *pv.TV
return
}
}
type ArrayValue struct {
ObjectInfo
List []TypedValue
Data []byte
}
// NOTE: Result should not be written to,
// behavior is unexpected when .List bytes.
func (av *ArrayValue) GetReadonlyBytes() []byte {
if av.Data == nil {
// NOTE: we cannot convert to .Data type bytearray here
// because there might be references to .List[x].
bz := make([]byte, len(av.List))
for i, tv := range av.List {
if tv.T.Kind() != Uint8Kind {
panic(fmt.Sprintf(
"expected byte kind but got %v",
tv.T.Kind()))
}
bz[i] = tv.GetUint8()
}
return bz
} else {
return av.Data
}
}
func (av *ArrayValue) GetCapacity() int {
if av.Data == nil {
// not cap(av.List) for simplicity.
// extra capacity is ignored.
return len(av.List)
} else {
// not cap(av.Data) for simplicity.
// extra capacity is ignored.
return len(av.Data)
}
}
func (av *ArrayValue) GetLength() int {
if av.Data == nil {
return len(av.List)
} else {
return len(av.Data)
}
}
// et is only required for .List byte-arrays.
func (av *ArrayValue) GetPointerAtIndexInt2(store Store, ii int, et Type) PointerValue {
if av.Data == nil {
ev := fillValueTV(store, &av.List[ii]) // by reference
return PointerValue{
TV: ev,
Base: av,
Index: ii,
}
} else {
bv := &TypedValue{ // heap alloc
T: DataByteType,
V: DataByteValue{
Base: av,
Index: ii,
ElemType: et,
},
}
return PointerValue{
TV: bv,
Base: av,
Index: ii,
}
}
}
func (av *ArrayValue) Copy(alloc *Allocator) *ArrayValue {
/* TODO: consider second ref count field.
if av.GetRefCount() == 0 {
return av
}
*/
if av.Data == nil {
av2 := alloc.NewListArray(len(av.List))
copy(av2.List, av.List)
return av2
} else {
av2 := alloc.NewDataArray(len(av.Data))
copy(av2.Data, av.Data)
return av2
}
}
type SliceValue struct {
Base Value
Offset int
Length int
Maxcap int
}
func (sv *SliceValue) GetBase(store Store) *ArrayValue {
switch cv := sv.Base.(type) {
case nil:
return nil
case RefValue:
array := store.GetObject(cv.ObjectID).(*ArrayValue)
sv.Base = array
return array
case *ArrayValue:
return cv
default:
panic("should not happen")
}
}
func (sv *SliceValue) GetCapacity() int {
return sv.Maxcap
}
func (sv *SliceValue) GetLength() int {
return sv.Length
}
// et is only required for .List byte-slices.
func (sv *SliceValue) GetPointerAtIndexInt2(store Store, ii int, et Type) PointerValue {
// Necessary run-time slice bounds check
if ii < 0 {
panic(fmt.Sprintf(
"slice index out of bounds: %d", ii))
} else if sv.Length <= ii {
panic(fmt.Sprintf(
"slice index out of bounds: %d (len=%d)",
ii, sv.Length))
}
return sv.GetBase(store).GetPointerAtIndexInt2(store, sv.Offset+ii, et)
}
type StructValue struct {
ObjectInfo
Fields []TypedValue
}
// TODO handle unexported fields in debug, and also ensure in the preprocessor.
func (sv *StructValue) GetPointerTo(store Store, path ValuePath) PointerValue {
if debug {
if path.Depth != 0 {
panic(fmt.Sprintf(
"expected path.Depth of 0 but got %s %s",
path.Name, path))
}
}
return sv.GetPointerToInt(store, int(path.Index))
}
func (sv *StructValue) GetPointerToInt(store Store, index int) PointerValue {
fv := fillValueTV(store, &sv.Fields[index])
return PointerValue{
TV: fv,
Base: sv,
Index: int(index),
}
}
// Like GetPointerTo*, but returns (a pointer of) a reference to field.
func (sv *StructValue) GetSubrefPointerTo(store Store, st *StructType, path ValuePath) PointerValue {
if debug {
if path.Depth != 0 {
panic(fmt.Sprintf(
"expected path.Depth of 0 but got %s %s",
path.Name, path))
}
}
fv := fillValueTV(store, &sv.Fields[path.Index])
ft := st.GetStaticTypeOfAt(path)
return PointerValue{
TV: &TypedValue{ // TODO: optimize
T: &PointerType{ // TODO: optimize (cont)
Elt: ft,
},
V: PointerValue{
TV: fv,
Base: sv,
Index: int(path.Index),
},
},
Base: nil, // free floating
}
}
func (sv *StructValue) Copy(alloc *Allocator) *StructValue {
/* TODO consider second refcount field
if sv.GetRefCount() == 0 {
return sv
}
*/
fields := alloc.NewStructFields(len(sv.Fields))
copy(fields, sv.Fields)
return alloc.NewStruct(fields)
}
// FuncValue.Type stores the method signature from the
// declaration, and has exact parameter/result names declared,
// whereas the TypedValue.T that contains at .V may not. (i.e.
// TypedValue.T doesn't care about parameter/result names, but
// the *FuncValue requires this for execution.
// In leu of FuncValue.Type, we could refer to FuncValue.Source
// or create a different field with param/result names, but
// *FuncType is already a suitable structure, and re-using
// makes construction TypedValue{T:*FuncType{},V:*FuncValue{}}
// faster.
type FuncValue struct {
Type Type // includes unbound receiver(s)
IsMethod bool // is an (unbound) method
Source BlockNode // for block mem allocation
Name Name // name of function/method
Closure Value // *Block or RefValue to closure (may be nil for file blocks; lazy)
FileName Name // file name where declared
PkgPath string
body []Stmt // function body
nativeBody func(*Machine) // alternative to Body
}
func (fv *FuncValue) Copy(alloc *Allocator) *FuncValue {
alloc.AllocateFunc()
return &FuncValue{
Type: fv.Type,
IsMethod: fv.IsMethod,
Source: fv.Source,
Name: fv.Name,
Closure: fv.Closure,
FileName: fv.FileName,
PkgPath: fv.PkgPath,
body: fv.body,
nativeBody: fv.nativeBody,
}
}
func (fv *FuncValue) GetType(store Store) *FuncType {
switch ct := fv.Type.(type) {
case nil:
return nil
case RefType:
typ := store.GetType(ct.ID).(*FuncType)
fv.Type = typ
return typ
case *FuncType:
return ct
default:
panic("should not happen")
}
}
func (fv *FuncValue) GetBodyFromSource(store Store) []Stmt {
if fv.body != nil {
return fv.body
} else {
source := fv.GetSource(store)
fv.body = source.GetBody()
return fv.body
}
}
func (fv *FuncValue) GetSource(store Store) BlockNode {
if rn, ok := fv.Source.(RefNode); ok {
source := store.GetBlockNode(rn.GetLocation())
fv.Source = source
return source
} else {
return fv.Source
}
}
func (fv *FuncValue) GetPackage(store Store) *PackageValue {
pv := store.GetPackage(fv.PkgPath, false)
return pv
}
// NOTE: this function does not automatically memoize the closure for
// file-level declared methods and functions. For those, caller
// should set .Closure manually after *FuncValue.Copy().
func (fv *FuncValue) GetClosure(store Store) *Block {
switch cv := fv.Closure.(type) {
case nil:
if fv.FileName == "" {
return nil
} else {
pv := fv.GetPackage(store)
fb := pv.fBlocksMap[fv.FileName]
if fb == nil {
panic(fmt.Sprintf("file block missing for file %q", fv.FileName))
}
return fb
}
case RefValue:
block := store.GetObject(cv.ObjectID).(*Block)
fv.Closure = block
return block
case *Block:
return cv
default:
panic("should not happen")
}
}
type BoundMethodValue struct {
ObjectInfo
// Underlying unbound method function.
// The type without the receiver (since bound)
// is computed lazily if needed.
Func *FuncValue
// This becomes the first arg.
// The type is .Func.Type.Params[0].
Receiver TypedValue
}
type MapValue struct {
ObjectInfo
List *MapList
vmap map[MapKey]*MapListItem // nil if uninitialized
}
type MapKey string
type MapList struct {
Head *MapListItem
Tail *MapListItem
Size int
}
type MapListImage struct {
List []*MapListItem
}
func (ml MapList) MarshalAmino() (MapListImage, error) {
mlimg := make([]*MapListItem, 0, ml.Size)
for head := ml.Head; head != nil; head = head.Next {
mlimg = append(mlimg, head)
}
return MapListImage{List: mlimg}, nil
}
func (ml *MapList) UnmarshalAmino(mlimg MapListImage) error {
for i, item := range mlimg.List {
if i == 0 {
// init case
ml.Head = item
}
item.Prev = ml.Tail
ml.Tail.Next = item
ml.Tail = item
ml.Size++
}
return nil
}
// NOTE: Value is undefined until assigned.
func (ml *MapList) Append(alloc *Allocator, key TypedValue) *MapListItem {
alloc.AllocateMapItem()
item := &MapListItem{
Prev: ml.Tail,
Next: nil,
Key: key,
// Value: undefined,
}
if ml.Head == nil {
ml.Head = item
} else {
// nothing
}
if ml.Tail != nil {
ml.Tail.Next = item
}
ml.Tail = item
ml.Size++
return item
}
func (ml *MapList) Remove(mli *MapListItem) {
prev, next := mli.Prev, mli.Next
if prev == nil {
ml.Head = next
} else {
prev.Next = next
}
if next == nil {
ml.Tail = prev
} else {
next.Prev = prev
}
ml.Size--
}
type MapListItem struct {
Prev *MapListItem `json:"-"`
Next *MapListItem `json:"-"`
Key TypedValue
Value TypedValue
}
func (mv *MapValue) MakeMap(c int) {
mv.List = &MapList{}
mv.vmap = make(map[MapKey]*MapListItem, c)
}
func (mv *MapValue) GetLength() int {
return mv.List.Size // panics if uninitialized
}
// NOTE: Go doesn't support referencing into maps, and maybe
// Gno will, but here we just use this method signature as we
// do for structs and arrays for assigning new entries. If key
// doesn't exist, a new slot is created.
func (mv *MapValue) GetPointerForKey(alloc *Allocator, store Store, key *TypedValue) PointerValue {
kmk := key.ComputeMapKey(store, false)
if mli, ok := mv.vmap[kmk]; ok {
key2 := key.Copy(alloc)
return PointerValue{
TV: fillValueTV(store, &mli.Value),
Base: mv,
Key: &key2,
Index: PointerIndexMap,
}
} else {
mli := mv.List.Append(alloc, *key)
mv.vmap[kmk] = mli
key2 := key.Copy(alloc)
return PointerValue{
TV: fillValueTV(store, &mli.Value),
Base: mv,
Key: &key2,
Index: PointerIndexMap,
}
}
}
// Like GetPointerForKey, but does not create a slot if key
// doesn't exist.
func (mv *MapValue) GetValueForKey(store Store, key *TypedValue) (val TypedValue, ok bool) {
kmk := key.ComputeMapKey(store, false)
if mli, exists := mv.vmap[kmk]; exists {
fillValueTV(store, &mli.Value)
val, ok = mli.Value, true
return
} else {
return
}
}
func (mv *MapValue) DeleteForKey(store Store, key *TypedValue) {
kmk := key.ComputeMapKey(store, false)
if mli, ok := mv.vmap[kmk]; ok {
mv.List.Remove(mli)
delete(mv.vmap, kmk)
}
}
// The type itself as a value.
type TypeValue struct {
Type Type
}
type PackageValue struct {
ObjectInfo // is a separate object from .Block.
Block Value
PkgName Name
PkgPath string
FNames []Name
FBlocks []Value
Realm *Realm `json:"-"` // if IsRealmPath(PkgPath), otherwise nil.
// NOTE: Realm is persisted separately.
fBlocksMap map[Name]*Block
}
func (pv *PackageValue) IsRealm() bool {
return IsRealmPath(pv.PkgPath)
}
func (pv *PackageValue) getFBlocksMap() map[Name]*Block {
if pv.fBlocksMap == nil {
pv.fBlocksMap = make(map[Name]*Block, len(pv.FNames))
}
return pv.fBlocksMap
}
// to call after loading *PackageValue.
func (pv *PackageValue) deriveFBlocksMap(store Store) {
if pv.fBlocksMap != nil {
panic("should not happen")
}
pv.fBlocksMap = make(map[Name]*Block, len(pv.FNames))
for i := 0; i < len(pv.FNames); i++ {
fname := pv.FNames[i]
fblock := pv.GetFileBlock(store, fname)
pv.fBlocksMap[fname] = fblock
}
}
func (pv *PackageValue) GetBlock(store Store) *Block {
bv := pv.Block
switch bv := bv.(type) {
case RefValue:
bb := store.GetObject(bv.ObjectID).(*Block)
pv.Block = bb
return bb
case *Block:
return bv
default:
panic("should not happen")
}
}
func (pv *PackageValue) GetValueAt(store Store, path ValuePath) TypedValue {
return *(pv.
GetBlock(store).
GetPointerTo(store, path).
TV)
}
func (pv *PackageValue) AddFileBlock(fn Name, fb *Block) {
for _, fname := range pv.FNames {
if fname == fn {
panic(fmt.Sprintf(
"duplicate file block for file %s",
fn))
}
}
pv.FNames = append(pv.FNames, fn)
pv.FBlocks = append(pv.FBlocks, fb)
pv.getFBlocksMap()[fn] = fb
fb.SetOwner(pv)
}
func (pv *PackageValue) GetFileBlock(store Store, fname Name) *Block {
if fb, ex := pv.getFBlocksMap()[fname]; ex {
return fb
}
for i, fn := range pv.FNames {
if fn == fname {
fbv := pv.FBlocks[i]
switch fbv := fbv.(type) {
case RefValue:
fb := store.GetObject(fbv.ObjectID).(*Block)
pv.getFBlocksMap()[fname] = fb
return fb
case *Block:
pv.getFBlocksMap()[fname] = fbv
return fbv
default:
panic("should not happen")
}
}
}
panic(fmt.Sprintf(
"file %v not found in package %v",
fname,
pv))
}
func (pv *PackageValue) GetRealm() *Realm {
return pv.Realm
}
func (pv *PackageValue) SetRealm(rlm *Realm) {
pv.Realm = rlm
}
// Convenience.
func (pv *PackageValue) GetPackageNode(store Store) *PackageNode {
return pv.GetBlock(store).GetSource(store).(*PackageNode)
}
// Convenience
func (pv *PackageValue) GetPkgAddr() crypto.Address {
return DerivePkgAddr(pv.PkgPath)
}
type NativeValue struct {
Value reflect.Value `json:"-"`
Bytes []byte // XXX is this used?
}
func (nv *NativeValue) Copy(alloc *Allocator) *NativeValue {
nt := nv.Value.Type()
nv2 := reflect.New(nt).Elem()
nv2.Set(nv.Value)
return alloc.NewNative(nv2)
}
//----------------------------------------
// TypedValue
type TypedValue struct {
T Type `json:",omitempty"` // never nil
V Value `json:",omitempty"` // an untyped value
N [8]byte `json:",omitempty"` // numeric bytes
}
func (tv *TypedValue) IsDefined() bool {
return !tv.IsUndefined()
}
func (tv *TypedValue) IsUndefined() bool {
if debug {
if tv == nil {
panic("should not happen")
}
}
if tv.T == nil {
if debug {
if tv.V != nil || tv.N != [8]byte{} {
panic(fmt.Sprintf(
"corrupted TypeValue (nil T)"))
}
}
return true
} else {
return tv.IsNilInterface()
}
}
func (tv *TypedValue) IsNilInterface() bool {
if tv.T != nil && tv.T.Kind() == InterfaceKind {
if tv.V == nil {
return true
} else {
if debug {
if tv.N != [8]byte{} {
panic(fmt.Sprintf(
"corrupted TypeValue (nil interface)"))
}
}
return false
}
}
return false
}
func (tv *TypedValue) HasKind(k Kind) bool {
if tv.T == nil {
return false
} else {
return tv.T.Kind() == k
}
}
// for debugging, returns true if V or N is not zero. just because V and N are
// zero doesn't mean it didn't get a value set.
func (tv *TypedValue) DebugHasValue() bool {
if !debug {
panic("should not happen")
}
if tv.V != nil {
return true
}
if tv.N != [8]byte{} {
return true
}
return false
}
func (tv *TypedValue) ClearNum() {
*(*uint64)(unsafe.Pointer(&tv.N)) = uint64(0)
}
func (tv TypedValue) Copy(alloc *Allocator) (cp TypedValue) {
switch cv := tv.V.(type) {
case BigintValue:
cp.T = tv.T
cp.V = cv.Copy(alloc)
case *ArrayValue:
cp.T = tv.T
cp.V = cv.Copy(alloc)
case *StructValue:
cp.T = tv.T
cp.V = cv.Copy(alloc)
case *NativeValue:
cp.T = tv.T
cp.V = cv.Copy(alloc)
default:
cp = tv
}
return
}
// Returns encoded bytes for primitive values.
// These bytes are used for both value hashes as well
// as hash key bytes.
func (tv *TypedValue) PrimitiveBytes() (data []byte) {
switch bt := baseOf(tv.T); bt {
case BoolType:
if tv.GetBool() {
return []byte{0x01}
} else {
return []byte{0x00}
}
case StringType:
return []byte(tv.GetString())
case Int8Type:
return []byte{uint8(tv.GetInt8())}
case Int16Type:
data = make([]byte, 2)
binary.LittleEndian.PutUint16(
data, uint16(tv.GetInt16()))
return data
case Int32Type:
data = make([]byte, 4)
binary.LittleEndian.PutUint32(
data, uint32(tv.GetInt32()))
return data
case IntType, Int64Type:
data = make([]byte, 8)
binary.LittleEndian.PutUint64(
data, uint64(tv.GetInt()))
return data
case Uint8Type:
return []byte{uint8(tv.GetUint8())}
case Uint16Type:
data = make([]byte, 2)
binary.LittleEndian.PutUint16(
data, uint16(tv.GetUint16()))
return data
case Uint32Type:
data = make([]byte, 4)
binary.LittleEndian.PutUint32(
data, uint32(tv.GetUint32()))
return data
case UintType, Uint64Type:
data = make([]byte, 8)
binary.LittleEndian.PutUint64(
data, uint64(tv.GetUint()))
return data
case BigintType:
return tv.V.(BigintValue).V.Bytes()
default:
panic(fmt.Sprintf(
"unexpected primitive value type: %s",
bt.String()))
}
}
// Setting IntValue to Value is slow, and creates
// a heap allocation. So N exists as a hack to keep
// values stored without interfaces..
func (tv *TypedValue) SetBool(b bool) {
if debug {
if tv.T.Kind() != BoolKind || isNative(tv.T) {
panic(fmt.Sprintf(