forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
realm.go
1532 lines (1446 loc) · 35.2 KB
/
realm.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/hex"
"encoding/json"
"fmt"
"reflect"
"strings"
)
/*
## Realms
Gno is designed with blockchain smart contract programming in
mind. A smart-contract enabled blockchain is like a
massive-multiuser-online operating-system (MMO-OS). Each user
is provided a home package, for example
"gno.land/r/username". This is not just a regular package but
a "realm package", and functions and methods declared there
have special privileges.
Every "realm package" should define at last one package-level variable:
```go
// PKGPATH: gno.land/r/alice
package alice
var root interface{}
func UpdateRoot(...) error {
root = ...
}
```
Here, the root variable can be any object, and indicates the
root node in the data realm identified by the package path
"gno.land/r/alice".
Any number of package-level values may be declared in a
realm; they are all owned by the package and get
merkle-hashed into a single root hash for the package realm.
The gas cost of transactions that modify state are paid for
by whoever submits the transaction, but the storage rent is
paid for by the realm. Anyone can pay the storage upkeep of
a realm to keep it alive.
*/
//----------------------------------------
// PkgID & Realm
type PkgID struct {
Hashlet
}
func (pid PkgID) MarshalAmino() (string, error) {
return hex.EncodeToString(pid.Hashlet[:]), nil
}
func (pid *PkgID) UnmarshalAmino(h string) error {
_, err := hex.Decode(pid.Hashlet[:], []byte(h))
return err
}
func (pid PkgID) String() string {
return fmt.Sprintf("RID%X", pid.Hashlet[:])
}
func (pid PkgID) Bytes() []byte {
return pid.Hashlet[:]
}
func PkgIDFromPkgPath(path string) PkgID {
return PkgID{HashBytes([]byte(path))}
}
func ObjectIDFromPkgPath(path string) ObjectID {
return ObjectID{
PkgID: PkgIDFromPkgPath(path),
NewTime: 1, // by realm logic.
}
}
// NOTE: A nil realm is special and has limited functionality; enough to
// support methods that don't require persistence. This is the default realm
// when a machine starts with a non-realm package.
type Realm struct {
ID PkgID
Path string
Time uint64
newCreated []Object
newEscaped []Object
newDeleted []Object
created []Object // about to become real.
updated []Object // real objects that were modified.
deleted []Object // real objects that became deleted.
escaped []Object // real objects with refcount > 1.
}
// Creates a blank new realm with counter 0.
func NewRealm(path string) *Realm {
id := PkgIDFromPkgPath(path)
return &Realm{
ID: id,
Path: path,
Time: 0,
}
}
func (rlm *Realm) String() string {
if rlm == nil {
return "Realm(nil)"
} else {
return fmt.Sprintf(
"Realm{Path:%q,Time:%d}#%X",
rlm.Path, rlm.Time, rlm.ID.Bytes())
}
}
//----------------------------------------
// ownership hooks
// po's old elem value is xo, will become co.
// po, xo, and co may each be nil.
// if rlm or po is nil, do nothing.
// xo or co is nil if the element value is undefined or has no
// associated object.
func (rlm *Realm) DidUpdate(po, xo, co Object) {
if rlm == nil {
return
}
if debug {
if co != nil && co.GetIsDeleted() {
panic("cannot attach a deleted object")
}
if po != nil && po.GetIsTransient() {
panic("should not happen")
}
if po != nil && po.GetIsDeleted() {
panic("cannot attach to a deleted object")
}
}
if po == nil || !po.GetIsReal() {
return // do nothing.
}
if po.GetObjectID().PkgID != rlm.ID {
panic("cannot modify external-realm or non-realm object")
}
// From here on, po is real (not new-real).
// Updates to .newCreated/.newEscaped /.newDeleted made here. (first gen)
// More appends happen during FinalizeRealmTransactions(). (second+ gen)
rlm.MarkDirty(po)
if co != nil {
co.IncRefCount()
if co.GetRefCount() > 1 {
if co.GetIsEscaped() {
// already escaped
} else {
rlm.MarkNewEscaped(co)
}
} else if co.GetIsReal() {
rlm.MarkDirty(co)
} else {
co.SetOwner(po)
rlm.MarkNewReal(co)
}
}
if xo != nil {
xo.DecRefCount()
if xo.GetRefCount() == 0 {
if xo.GetIsReal() {
rlm.MarkNewDeleted(xo)
}
}
}
}
//----------------------------------------
// mark*
func (rlm *Realm) MarkNewReal(oo Object) {
if debug {
if pv, ok := oo.(*PackageValue); ok {
// packages should have no owner.
if pv.GetOwner() != nil {
panic("should not happen")
}
// packages should have ref-count 1.
if pv.GetRefCount() != 1 {
panic("should not happen")
}
} else {
if oo.GetOwner() == nil {
panic("should not happen")
}
if !oo.GetOwner().GetIsReal() {
panic("should not happen")
}
}
}
if oo.GetIsNewReal() {
return // already marked.
}
oo.SetIsNewReal(true)
// append to .newCreated
if rlm.newCreated == nil {
rlm.newCreated = make([]Object, 0, 256)
}
rlm.newCreated = append(rlm.newCreated, oo)
}
func (rlm *Realm) MarkDirty(oo Object) {
if debug {
if !oo.GetIsReal() && !oo.GetIsNewReal() {
panic("should not happen")
}
}
if oo.GetIsDirty() {
return // already marked.
}
if oo.GetIsNewReal() {
return // treat as new-real.
}
oo.SetIsDirty(true, rlm.Time)
// append to .updated
if rlm.updated == nil {
rlm.updated = make([]Object, 0, 256)
}
rlm.updated = append(rlm.updated, oo)
}
func (rlm *Realm) MarkNewDeleted(oo Object) {
if debug {
if !oo.GetIsNewReal() && !oo.GetIsReal() {
panic("should not happen")
}
if oo.GetIsDeleted() {
panic("should not happen")
}
}
if oo.GetIsNewDeleted() {
return // already marked.
}
oo.SetIsNewDeleted(true)
// append to .newDeleted
if rlm.newDeleted == nil {
rlm.newDeleted = make([]Object, 0, 256)
}
rlm.newDeleted = append(rlm.newDeleted, oo)
}
func (rlm *Realm) MarkNewEscaped(oo Object) {
if debug {
if !oo.GetIsNewReal() && !oo.GetIsReal() {
panic("should not happen")
}
if oo.GetIsDeleted() {
panic("should not happen")
}
if oo.GetIsEscaped() {
panic("should not happen")
}
}
if oo.GetIsNewEscaped() {
return // already marked.
}
oo.SetIsNewEscaped(true)
// append to .newEscaped.
if rlm.newEscaped == nil {
rlm.newEscaped = make([]Object, 0, 256)
}
rlm.newEscaped = append(rlm.newEscaped, oo)
}
//----------------------------------------
// transactions
// OpReturn calls this when exiting a realm transaction.
func (rlm *Realm) FinalizeRealmTransaction(readonly bool, store Store) {
if readonly {
if true ||
len(rlm.newCreated) > 0 ||
len(rlm.newEscaped) > 0 ||
len(rlm.newDeleted) > 0 ||
len(rlm.created) > 0 ||
len(rlm.updated) > 0 ||
len(rlm.deleted) > 0 ||
len(rlm.escaped) > 0 {
panic("realm updates in readonly transaction")
}
return
}
if debug {
// * newCreated - may become created unless ancestor is deleted
// * newDeleted - may become deleted unless attached to new-real owner
// * newEscaped - may become escaped unless new-real and refcount 0 or 1.
// * updated - includes all real updated objects, and will be appended with ancestors
ensureUniq(rlm.newCreated)
ensureUniq(rlm.newEscaped)
ensureUniq(rlm.newDeleted)
ensureUniq(rlm.updated)
if false ||
rlm.created != nil ||
rlm.deleted != nil ||
rlm.escaped != nil {
panic("should not happen")
}
}
// log realm boundaries in opslog.
store.LogSwitchRealm(rlm.Path)
// increment recursively for created descendants.
// also assigns object ids for all.
rlm.processNewCreatedMarks(store)
// decrement recursively for deleted descendants.
rlm.processNewDeletedMarks(store)
// at this point, all ref-counts are final.
// demote any escaped if ref-count is 1.
rlm.processNewEscapedMarks(store)
// given created and updated objects,
// mark all owned-ancestors also as dirty.
rlm.markDirtyAncestors(store)
if debug {
ensureUniq(rlm.created, rlm.updated, rlm.deleted)
ensureUniq(rlm.escaped)
}
// save all the created and updated objects.
// hash calculation is done along the way,
// or via escaped-object persistence in
// the iavl tree.
rlm.saveUnsavedObjects(store)
// delete all deleted objects.
rlm.removeDeletedObjects(store)
// reset realm state for new transaction.
rlm.clearMarks()
}
//----------------------------------------
// processNewCreatedMarks
// Crawls marked created children and increments ref counts,
// finding more newly created objects recursively.
// All newly created objects become appended to .created,
// and get assigned ids.
func (rlm *Realm) processNewCreatedMarks(store Store) {
// Create new objects and their new descendants.
for _, oo := range rlm.newCreated {
if debug {
if oo.GetIsDirty() {
panic("should not happen")
}
}
if oo.GetRefCount() == 0 {
if debug {
if !oo.GetIsNewDeleted() {
panic("should have been marked new-deleted")
}
}
// No need to unmark, will be garbage collected.
// oo.SetIsNewReal(false)
// skip if became deleted.
continue
} else {
rlm.incRefCreatedDescendants(store, oo)
}
}
// Save new realm time.
if len(rlm.newCreated) > 0 {
store.SetPackageRealm(rlm)
}
}
// oo must be marked new-real, and ref-count already incremented.
func (rlm *Realm) incRefCreatedDescendants(store Store, oo Object) {
if debug {
if oo.GetIsDirty() {
panic("should not happen")
}
if oo.GetRefCount() <= 0 {
panic("should not happen")
}
}
// RECURSE GUARD
// if id already set, skip.
// this happens when a node marked created was already
// visited via recursion from a prior marked created.
if !oo.GetObjectID().IsZero() {
return
}
rlm.assignNewObjectID(oo)
rlm.created = append(rlm.created, oo)
// RECURSE GUARD END
// recurse for children.
more := getChildObjects2(store, oo)
for _, child := range more {
if _, ok := child.(*PackageValue); ok {
if debug {
if child.GetRefCount() < 1 {
panic("should not happen")
}
}
// extern package values are skipped.
continue
}
child.IncRefCount()
rc := child.GetRefCount()
if rc == 1 {
if child.GetIsReal() {
// a deleted real became undeleted.
child.SetOwner(oo)
rlm.MarkDirty(child)
} else {
// a (possibly pre-existing) new object
// became real (again).
// NOTE: may already be marked for first gen
// newCreated or updated.
child.SetOwner(oo)
rlm.incRefCreatedDescendants(store, child)
child.SetIsNewReal(true)
}
} else if rc > 1 {
if child.GetIsEscaped() {
// already escaped, do nothing.
} else {
// NOTE: do not unset owner here,
// may become unescaped later
// in processNewEscapedMarks().
// NOTE: may already be escaped.
rlm.MarkNewEscaped(child)
}
} else {
panic("should not happen")
}
}
}
//----------------------------------------
// processNewDeletedMarks
// Crawls marked deleted children and decrements ref counts,
// finding more newly deleted objects, recursively.
// Recursively found deleted objects are appended
// to rlm.deleted.
// Must run *after* processNewCreatedMarks().
func (rlm *Realm) processNewDeletedMarks(store Store) {
for _, oo := range rlm.newDeleted {
if debug {
if oo.GetObjectID().IsZero() {
panic("should not happen")
}
}
if oo.GetRefCount() > 0 {
oo.SetIsNewDeleted(false)
// skip if became undeleted.
continue
} else {
rlm.decRefDeletedDescendants(store, oo)
}
}
}
// Like incRefCreatedDescendants but decrements.
func (rlm *Realm) decRefDeletedDescendants(store Store, oo Object) {
if debug {
if oo.GetObjectID().IsZero() {
panic("should not happen")
}
if oo.GetRefCount() != 0 {
panic("should not happen")
}
}
// RECURSE GUARD
// if already deleted, skip.
// this happens when a node marked deleted was already
// deleted via recursion from a prior marked deleted.
if oo.GetIsDeleted() {
return
}
oo.SetIsNewDeleted(false)
oo.SetIsNewReal(false)
oo.SetIsNewEscaped(false)
oo.SetIsDeleted(true, rlm.Time)
rlm.deleted = append(rlm.deleted, oo)
// RECURSE GUARD END
// recurse for children
more := getChildObjects2(store, oo)
for _, child := range more {
child.DecRefCount()
rc := child.GetRefCount()
if rc == 0 {
rlm.decRefDeletedDescendants(store, child)
} else if rc > 0 {
// do nothing
} else {
panic("should not happen")
}
}
}
//----------------------------------------
// processNewEscapedMarks
// demotes new-real escaped objects with refcount 0 or 1. remaining
// objects get their original owners marked dirty (to be further
// marked via markDirtyAncestors).
func (rlm *Realm) processNewEscapedMarks(store Store) {
escaped := make([]Object, 0, len(rlm.newEscaped))
// These are those marked by MarkNewEscaped(),
// regardless of whether new-real or was real,
// but is always newly escaped,
// (and never can be unescaped,)
// except for new-reals that get demoted
// because ref-count isn't >= 2.
for _, eo := range rlm.newEscaped {
if debug {
if !eo.GetIsNewEscaped() {
panic("should not happen")
}
if eo.GetIsEscaped() {
panic("should not happen")
}
}
if eo.GetRefCount() <= 1 {
// demote; do not add to escaped.
eo.SetIsNewEscaped(false)
continue
} else {
// escape;
// NOTE: do not unset new-escaped,
// we do that upon actually persisting
// the hash index.
// eo.SetIsNewEscaped(false)
escaped = append(escaped, eo)
// add to escaped, and mark dirty previous owner.
po := getOwner(store, eo)
if po == nil {
// e.g. !eo.GetIsNewReal(),
// should have no parent.
continue
} else {
if po.GetRefCount() == 0 {
// is deleted, ignore.
} else if po.GetIsNewReal() {
// will be saved regardless.
} else {
// exists, mark dirty.
rlm.MarkDirty(po)
}
if eo.GetObjectID().IsZero() {
panic("should not happen")
}
// escaped has no owner.
eo.SetOwner(nil)
}
}
}
rlm.escaped = escaped // XXX is this actually used?
}
//----------------------------------------
// markDirtyAncestors
// New and modified objects' owners and their owners
// (ancestors) must be marked as dirty to update the
// hash tree.
func (rlm *Realm) markDirtyAncestors(store Store) {
markAncestorsOne := func(oo Object) {
for {
if pv, ok := oo.(*PackageValue); ok {
if debug {
if pv.GetRefCount() < 1 {
panic("expected package value to have refcount 1 or greater")
}
}
// package values have no ancestors.
break
}
rc := oo.GetRefCount()
if debug {
if rc == 0 {
panic("should not happen")
}
}
if rc > 1 {
if debug {
if !oo.GetIsEscaped() && !oo.GetIsNewEscaped() {
panic("should not happen")
}
if !oo.GetOwnerID().IsZero() {
panic("should not happen")
}
}
// object is escaped, so
// it has no parent.
break
} // else, rc == 1
po := getOwner(store, oo)
if po == nil {
break // no more owners.
} else if po.GetIsNewReal() {
// already will be marked
// via call to markAncestorsOne
// via .created.
break
} else if po.GetIsDirty() {
// already will be marked
// via call to markAncestorsOne
// via .updated.
break
} else {
rlm.MarkDirty(po)
// next case
oo = po
}
}
}
// NOTE: newly dirty-marked owners get appended
// to .updated without affecting iteration.
for _, oo := range rlm.updated {
markAncestorsOne(oo)
}
// NOTE: must happen after iterating over rlm.updated
// for the same reason.
for _, oo := range rlm.created {
markAncestorsOne(oo)
}
}
//----------------------------------------
// saveUnsavedObjects
// Saves .created and .updated objects.
func (rlm *Realm) saveUnsavedObjects(store Store) {
for _, co := range rlm.created {
// for i := len(rlm.created) - 1; i >= 0; i-- {
// co := rlm.created[i]
if !co.GetIsNewReal() {
// might have happened already as child
// of something else created.
continue
} else {
rlm.saveUnsavedObjectRecursively(store, co)
}
}
for _, uo := range rlm.updated {
// for i := len(rlm.updated) - 1; i >= 0; i-- {
// uo := rlm.updated[i]
if !uo.GetIsDirty() {
// might have happened already as child
// of something else created/dirty.
continue
} else {
rlm.saveUnsavedObjectRecursively(store, uo)
}
}
}
// store unsaved children first.
func (rlm *Realm) saveUnsavedObjectRecursively(store Store, oo Object) {
if debug {
if !oo.GetIsNewReal() && !oo.GetIsDirty() {
panic("should not happen")
}
// object id should have been assigned during processNewCreatedMarks.
if oo.GetObjectID().IsZero() {
panic("should not happen")
}
// deleted objects should not have gotten here.
if false ||
oo.GetRefCount() <= 0 ||
oo.GetIsNewDeleted() ||
oo.GetIsDeleted() {
panic("should not happen")
}
}
// first, save unsaved children.
unsaved := getUnsavedChildObjects(oo)
for _, uch := range unsaved {
if uch.GetIsEscaped() || uch.GetIsNewEscaped() {
// no need to save preemptively.
} else {
rlm.saveUnsavedObjectRecursively(store, uch)
}
}
// then, save self.
if oo.GetIsNewReal() {
// save created object.
if debug {
if oo.GetIsDirty() {
panic("should not happen")
}
}
rlm.saveObject(store, oo)
oo.SetIsNewReal(false)
} else {
// update existing object.
if debug {
if !oo.GetIsDirty() {
panic("should not happen")
}
if !oo.GetIsReal() {
panic("should not happen")
}
if oo.GetIsNewReal() {
panic("should not happen")
}
}
rlm.saveObject(store, oo)
oo.SetIsDirty(false, 0)
}
}
func (rlm *Realm) saveObject(store Store, oo Object) {
oid := oo.GetObjectID()
if oid.IsZero() {
panic("unexpected zero object id")
}
/* XXX DELETE
// ensure all types were already saved (@ preprocessor).
if debug {
types := getUnsavedTypes(oo, nil)
for _, typ := range types {
tid := typ.TypeID()
if store.GetType(tid) == nil {
panic("missing type")
}
}
}
*/
// set hash to escape index.
if oo.GetIsNewEscaped() {
oo.SetIsNewEscaped(false)
oo.SetIsEscaped(true)
// XXX anything else to do?
}
// set object to store.
// NOTE: also sets the hash to object.
store.SetObject(oo)
// set index.
if oo.GetIsEscaped() {
// XXX save oid->hash to iavl.
fmt.Println("XXX save hash to iavl")
}
}
//----------------------------------------
// removeDeletedObjects
func (rlm *Realm) removeDeletedObjects(store Store) {
for _, do := range rlm.deleted {
store.DelObject(do)
}
}
//----------------------------------------
// clearMarks
func (rlm *Realm) clearMarks() {
// sanity check
if debug {
for _, oo := range rlm.newDeleted {
if oo.GetIsNewDeleted() {
panic("should not happen")
}
}
for _, oo := range rlm.newCreated {
if oo.GetIsNewReal() {
panic("should not happen")
}
}
for _, oo := range rlm.newEscaped {
if oo.GetIsNewEscaped() {
panic("should not happen")
}
}
}
// reset
rlm.newCreated = nil
rlm.newEscaped = nil
rlm.newDeleted = nil
rlm.created = nil
rlm.updated = nil
rlm.deleted = nil
rlm.escaped = nil
}
//----------------------------------------
// getSelfOrChildObjects
// Get self (if object) or child objects.
// Value is either Object or RefValue.
// Shallow; doesn't recurse into objects.
func getSelfOrChildObjects(val Value, more []Value) []Value {
if _, ok := val.(RefValue); ok {
return append(more, val)
} else if _, ok := val.(Object); ok {
return append(more, val)
} else {
return getChildObjects(val, more)
}
}
// Gets child objects.
// Shallow; doesn't recurse into objects.
func getChildObjects(val Value, more []Value) []Value {
switch cv := val.(type) {
case nil:
return more
case StringValue:
return more
case BigintValue:
return more
case DataByteValue:
panic("should not happen")
case PointerValue:
if cv.Base != nil {
more = getSelfOrChildObjects(cv.Base, more)
} else {
more = getSelfOrChildObjects(cv.TV.V, more)
}
return more
case *ArrayValue:
for _, ctv := range cv.List {
more = getSelfOrChildObjects(ctv.V, more)
}
return more
case *SliceValue:
more = getSelfOrChildObjects(cv.Base, more)
return more
case *StructValue:
for _, ctv := range cv.Fields {
more = getSelfOrChildObjects(ctv.V, more)
}
return more
case *FuncValue:
if bv, ok := cv.Closure.(*Block); ok {
more = getSelfOrChildObjects(bv, more)
}
return more
case *BoundMethodValue:
more = getChildObjects(cv.Func, more) // *FuncValue not object
more = getSelfOrChildObjects(cv.Receiver.V, more)
return more
case *MapValue:
for cur := cv.List.Head; cur != nil; cur = cur.Next {
more = getSelfOrChildObjects(cur.Key.V, more)
more = getSelfOrChildObjects(cur.Value.V, more)
}
return more
case TypeValue:
return more
case *PackageValue:
more = getSelfOrChildObjects(cv.Block, more)
for _, fb := range cv.FBlocks {
more = getSelfOrChildObjects(fb, more)
}
return more
case *Block:
for _, ctv := range cv.Values {
more = getSelfOrChildObjects(ctv.V, more)
}
more = getSelfOrChildObjects(cv.Parent, more)
return more
case *NativeValue:
panic("native values not supported")
default:
panic(fmt.Sprintf(
"unexpected type %v",
reflect.TypeOf(val)))
}
}
// like getChildObjects() but loads RefValues into objects.
func getChildObjects2(store Store, val Value) []Object {
chos := getChildObjects(val, nil)
objs := make([]Object, 0, len(chos))
for _, child := range chos {
if ref, ok := child.(RefValue); ok {
oo := store.GetObject(ref.ObjectID)
objs = append(objs, oo)
} else if oo, ok := child.(Object); ok {
objs = append(objs, oo)
}
}
return objs
}
//----------------------------------------
// getUnsavedChildObjects
// Gets all unsaved child objects.
// Shallow; doesn't recurse into objects.
func getUnsavedChildObjects(val Value) []Object {
vals := getChildObjects(val, nil)
unsaved := make([]Object, 0, len(vals))
for _, val := range vals {
// sanity check:
if pv, ok := val.(*PackageValue); ok {
if !pv.IsRealm() && pv.GetIsDirty() {
panic("unexpected dirty non-realm package " + pv.PkgPath)
}
}
// ...
if _, ok := val.(RefValue); ok {
// is already saved.
} else if obj, ok := val.(Object); ok {
// if object...
if isUnsaved(obj) {
unsaved = append(unsaved, obj)
}
} else {
panic("should not happen")
}
}
return unsaved
}
//----------------------------------------
// copyTypeWithRefs
func copyMethods(methods []TypedValue) []TypedValue {
res := make([]TypedValue, len(methods))
for i, mtv := range methods {
// NOTE: this works because copyMethods/copyTypeWithRefs
// gets called AFTER the file block (method closure)
// gets saved (e.g. from *Machine.savePackage()).
res[i] = TypedValue{
T: copyTypeWithRefs(mtv.T),
V: copyValueWithRefs(nil, mtv.V),
}
}
return res
}
func refOrCopyType(typ Type) Type {
if dt, ok := typ.(*DeclaredType); ok {
return RefType{ID: dt.TypeID()}
} else {
return copyTypeWithRefs(typ)
}
}
func copyFieldsWithRefs(fields []FieldType) []FieldType {
fieldsCpy := make([]FieldType, len(fields))
for i, field := range fields {
fieldsCpy[i] = FieldType{
Name: field.Name,
Type: refOrCopyType(field.Type),
Embedded: field.Embedded,
Tag: field.Tag,
}
}
return fieldsCpy
}
// Copies type but with references to dependant types;
// the result is suitable for persistence bytes serialization.
func copyTypeWithRefs(typ Type) Type {
switch ct := typ.(type) {
case nil:
panic("should not happen")
case PrimitiveType:
return ct
case *PointerType:
return &PointerType{
Elt: refOrCopyType(ct.Elt),
}
case FieldType:
panic("should not happen")
case *ArrayType:
return &ArrayType{
Len: ct.Len,
Elt: refOrCopyType(ct.Elt),
Vrd: ct.Vrd,
}
case *SliceType:
return &SliceType{
Elt: refOrCopyType(ct.Elt),
Vrd: ct.Vrd,
}
case *StructType:
return &StructType{
PkgPath: ct.PkgPath,
Fields: copyFieldsWithRefs(ct.Fields),
}
case *FuncType:
return &FuncType{
Params: copyFieldsWithRefs(ct.Params),
Results: copyFieldsWithRefs(ct.Results),
}
case *MapType:
return &MapType{
Key: refOrCopyType(ct.Key),